incoming-message-evidence.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import { mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. interface WireMessage {
  4. role: string;
  5. content: unknown;
  6. }
  7. export type Presentation =
  8. | "user_steer"
  9. | "coordinator_input"
  10. | "coordinator_steer"
  11. | "subagent_reply_steer"
  12. | "subagent_reply"
  13. | "task_notification"
  14. | "task_notification_steer";
  15. export function wireText(content: unknown): string {
  16. if (typeof content === "string") return content;
  17. if (!Array.isArray(content)) return "";
  18. return content
  19. .map((block) => {
  20. if (block?.type === "text") return String(block.text ?? "");
  21. // Anthropic 协议下紧随 tool result 的提醒并入 tool_result.content。
  22. if (block?.type === "tool_result") return wireText(block.content);
  23. return "";
  24. })
  25. .join("\n");
  26. }
  27. /** 验证实际网络载荷;黄金样本独立于生产 formatter。 */
  28. export async function assertIncomingMessage(
  29. request: unknown,
  30. input: {
  31. presentation: Presentation;
  32. marker: string;
  33. role: "user" | "system";
  34. body?: string;
  35. evidenceLabel?: string;
  36. /**
  37. * MCS 下没有 user/tool 锚点(例如 text-only 回复之后)时,同一段 run 的 MCS 文本整组降级为
  38. * 一条 user reminder,只包一次;期望文本是其中完整的一段。
  39. */
  40. mcsFallback?: boolean;
  41. },
  42. ) {
  43. const fixture = await readPresentationFixture();
  44. await saveWireEvidence(
  45. request,
  46. `${input.evidenceLabel ?? "default"}-${input.presentation}-${input.marker}`,
  47. );
  48. const messages = (request as { messages: WireMessage[] }).messages;
  49. assertWireIntegrity(request);
  50. // 模板固定取标准样本,不从 wire 反推:反推时 CLI 选错模板也能通过。
  51. // 同轮标题(fixture.inHumanTurn)只用于紧跟真实用户消息、中间没有 assistant/tool result 的中途通知,
  52. // 由 CLI 单测覆盖;现有 E2E 的中途通知都在 assistant 或 tool result 之后送达。
  53. const template = fixture.expected[input.presentation];
  54. const prefix = template.split("{body}")[0]!;
  55. const index = messages.findIndex(
  56. (message) =>
  57. wireText(message.content).includes(prefix) &&
  58. wireText(message.content).includes(input.marker),
  59. );
  60. expect(index).toBeGreaterThanOrEqual(0);
  61. const message = messages[index]!;
  62. const text = wireText(message.content);
  63. const body =
  64. input.body ??
  65. (input.presentation.startsWith("subagent")
  66. ? text.match(/<subagent-message>[\s\S]*?<\/subagent-message>/u)?.[0]
  67. : text.match(/<task-notification>[\s\S]*?<\/task-notification>/gu)?.join("\n\n"));
  68. expect(body).toBeDefined();
  69. const midTurn = input.presentation.endsWith("_steer");
  70. const wrapped =
  71. input.role === "user" &&
  72. (input.presentation.endsWith("_steer") || input.presentation === "task_notification");
  73. // 独立校验 provider 表达;提取自 wire 的正文可能已转义,不能再次编码实体。
  74. // 新轮整批通知每条一个 text block,各自带标题和一对标签;单条时只有一段。
  75. const wireBodies = (
  76. input.presentation === "task_notification" && input.body === undefined
  77. ? text.match(/<task-notification>[\s\S]*?<\/task-notification>/gu)!
  78. : [body!]
  79. ).map((part) => (wrapped ? part.replace(/<(\/?system-reminder\b)/gi, "&lt;$1") : part));
  80. const expectedParts = wireBodies.map((part) => template.replace("{body}", part));
  81. for (const expected of expectedParts) {
  82. expect(
  83. messages.reduce(
  84. (count, item) => count + wireText(item.content).split(expected).length - 1,
  85. 0,
  86. ),
  87. ).toBe(1);
  88. expect(text).toContain(expected);
  89. }
  90. expect(message.role).toBe(input.role);
  91. // 整批时除最后一块外,每块末尾一个 "\n"。
  92. const expectedBlocks = wrapped
  93. ? expectedParts.map(
  94. (part, index) =>
  95. `<system-reminder>\n${part}\n</system-reminder>${index < expectedParts.length - 1 ? "\n" : ""}`,
  96. )
  97. : [expectedParts.join("\n")];
  98. const expectedBlock = expectedBlocks.join("");
  99. if (input.presentation !== "coordinator_input") {
  100. const blocks =
  101. typeof message.content === "string"
  102. ? [message.content]
  103. : Array.isArray(message.content)
  104. ? message.content.filter((block) => block.type === "text").map((block) => block.text)
  105. : [];
  106. const toolResults = Array.isArray(message.content)
  107. ? message.content.filter((block) => block.type === "tool_result")
  108. : [];
  109. if (input.role === "system") {
  110. // MCS 下同一段 user run 的 system 文本合并为一条、以空行分隔(后续公告可能并入);
  111. // 期望文本必须是其中完整的一段,前后不能夹入其他文案。
  112. const merged = blocks.find((block) => block.includes(expectedBlock));
  113. expect(merged).toBeDefined();
  114. expect(`\n\n${merged}\n\n`).toContain(`\n\n${expectedBlock}\n\n`);
  115. } else if (input.mcsFallback) {
  116. // 降级块只有一对外层标签,期望文本是标签内以空行分隔的完整一段。
  117. const inner = expectedParts.join("\n\n");
  118. const fallback = blocks.find((block) => block.includes(inner));
  119. expect(fallback?.startsWith("<system-reminder>\n")).toBe(true);
  120. expect(fallback?.endsWith("\n</system-reminder>")).toBe(true);
  121. const body = fallback!.slice("<system-reminder>\n".length, -"\n</system-reminder>".length);
  122. expect(`\n\n${body}\n\n`).toContain(`\n\n${inner}\n\n`);
  123. expect(fallback!.match(/<\/?system-reminder\b/gi)).toHaveLength(2);
  124. } else if (wrapped && midTurn && toolResults.length > 0) {
  125. // 中途消息紧随 tool result 时并入最后一个 tool_result.content,以空行与其他段分隔。
  126. expect(blocks).not.toContain(expectedBlock);
  127. const folded = wireText(toolResults.at(-1)!.content);
  128. expect(`\n\n${folded}\n\n`).toContain(`\n\n${expectedBlock}\n\n`);
  129. } else {
  130. // 精确比较完整 block 序列,防止正确模板前后夹入额外控制文案。
  131. const start = blocks.indexOf(expectedBlocks[0]!);
  132. expect(start).toBeGreaterThanOrEqual(0);
  133. expect(blocks.slice(start, start + expectedBlocks.length)).toEqual(expectedBlocks);
  134. }
  135. // 并入 tool result 的 block 已在上面逐字比较,这里只检查独立的 text block:每块只有一对标签。
  136. if (wrapped && !(midTurn && toolResults.length > 0) && !input.mcsFallback) {
  137. const actualBlock = blocks.find(
  138. (block) => block.includes(prefix) && block.includes(input.marker),
  139. );
  140. expect(actualBlock?.match(/<\/?system-reminder\b/gi)).toHaveLength(2);
  141. }
  142. }
  143. // 只统计 text block,工具入参中的同名载荷不算第二份输入。
  144. for (const wireBody of wireBodies) {
  145. expect(
  146. messages.reduce(
  147. (count, item) => count + wireText(item.content).split(wireBody).length - 1,
  148. 0,
  149. ),
  150. ).toBe(1);
  151. }
  152. if (input.role === "system") expect(text).not.toContain(`<system-reminder>\n${prefix}`);
  153. // wireText 以 "\n" 连接各 text block;降级块已在上面逐段校验。
  154. else if (wrapped && !input.mcsFallback) expect(text).toContain(expectedBlocks.join("\n"));
  155. else if (!wrapped) expect(text).not.toContain(`<system-reminder>\n${expectedParts[0]}`);
  156. return { index, messages };
  157. }
  158. async function readPresentationFixture() {
  159. return JSON.parse(
  160. await readFile(
  161. new URL(
  162. "../../../../../apps/zcode-cli/packages/core/tests/fixtures/runtime-input-presentation.json",
  163. import.meta.url,
  164. ),
  165. "utf8",
  166. ),
  167. ) as { expected: Record<Presentation, string> };
  168. }
  169. async function saveWireEvidence(request: unknown, label: string): Promise<void> {
  170. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  171. if (!artifactDir) return;
  172. const directory = join(artifactDir, "incoming-message-wire");
  173. await mkdir(directory, { recursive: true });
  174. const name = `${label.replace(/[^a-zA-Z0-9_-]/gu, "_").slice(0, 160)}.json`;
  175. // 只保存实际 provider JSON body;不持久化网络凭据或 headers。
  176. await writeFile(join(directory, name), `${JSON.stringify(request, null, 2)}\n`, "utf8");
  177. }
  178. /**
  179. * 运行中立即发送抢占后是普通用户输入:独立 text block、整个请求里只出现一次,
  180. * 没有人类中途提示,也不并入 tool_result。
  181. */
  182. export async function assertPlainUserInput(
  183. request: unknown,
  184. input: { body: string; evidenceLabel: string },
  185. ) {
  186. await saveWireEvidence(request, `${input.evidenceLabel}-plain-user`);
  187. const messages = (request as { messages: WireMessage[] }).messages;
  188. assertWireIntegrity(request);
  189. const index = messages.findIndex((message) => textBlocksOf(message.content).includes(input.body));
  190. expect(index).toBeGreaterThanOrEqual(0);
  191. expect(messages[index]!.role).toBe("user");
  192. expect(
  193. messages.reduce(
  194. (count, item) => count + wireText(item.content).split(input.body).length - 1,
  195. 0,
  196. ),
  197. ).toBe(1);
  198. const steerPrefix = (await readPresentationFixture()).expected.user_steer.split("{body}")[0]!;
  199. expect(JSON.stringify(request)).not.toContain(JSON.stringify(steerPrefix).slice(1, -1));
  200. return { index, messages };
  201. }
  202. /**
  203. * 后一次请求只在前一次请求末尾追加:前面的消息逐条相同,前一次最后一条消息的 block
  204. * 是后一次同位置消息的前缀。缓存断点(cache_control)随请求移动,不参与比较。
  205. */
  206. export function assertAppendOnly(previousRequest: unknown, nextRequest: unknown): void {
  207. const strip = (value: unknown) =>
  208. JSON.parse(JSON.stringify(value, (key, item) => (key === "cache_control" ? undefined : item)));
  209. const previous = strip(
  210. (previousRequest as { messages: WireMessage[] }).messages,
  211. ) as WireMessage[];
  212. const next = strip((nextRequest as { messages: WireMessage[] }).messages) as WireMessage[];
  213. expect(next.length).toBeGreaterThanOrEqual(previous.length);
  214. expect(next.slice(0, previous.length - 1)).toEqual(previous.slice(0, -1));
  215. const last = previous.at(-1)!;
  216. const blocksOf = (content: unknown) =>
  217. typeof content === "string" ? [{ type: "text", text: content }] : (content as unknown[]);
  218. const lastBlocks = blocksOf(last.content);
  219. expect(next[previous.length - 1]!.role).toBe(last.role);
  220. expect(blocksOf(next[previous.length - 1]!.content).slice(0, lastBlocks.length)).toEqual(
  221. lastBlocks,
  222. );
  223. }
  224. function textBlocksOf(content: unknown): string[] {
  225. if (typeof content === "string") return [content];
  226. if (!Array.isArray(content)) return [];
  227. return content.filter((block) => block?.type === "text").map((block) => String(block.text));
  228. }
  229. /** 系统中途消息不能拆开并行工具的结果批次,也不能泄漏内部来源字段。 */
  230. export function assertWireIntegrity(request: unknown): void {
  231. const messages = (request as { messages: WireMessage[] }).messages;
  232. expect(JSON.stringify(request)).not.toMatch(
  233. /"(?:inputPresentation|steerContext|sourceEntries)"\s*:/u,
  234. );
  235. const pending = new Set<string>();
  236. for (const message of messages) {
  237. const blocks = Array.isArray(message.content) ? message.content : [];
  238. const results = blocks.filter((block) => block.type === "tool_result");
  239. if (pending.size > 0) {
  240. expect(message.role).toBe("user");
  241. expect(results.map((block) => block.tool_use_id).sort()).toEqual([...pending].sort());
  242. pending.clear();
  243. } else {
  244. expect(results).toHaveLength(0);
  245. }
  246. for (const block of blocks) {
  247. if (block.type === "tool_use") pending.add(block.id);
  248. }
  249. expect(wireText(message.content).length > 0 || blocks.length > 0).toBe(true);
  250. }
  251. expect([...pending]).toHaveLength(0);
  252. }
  253. /** 既有后台生命周期用例共用全文断言;角色分支另由双能力时序矩阵固定验证。 */
  254. export async function assertTaskNotificationContents(
  255. request: unknown,
  256. evidenceLabel: string,
  257. ): Promise<void> {
  258. const messages = (request as { messages: WireMessage[] }).messages;
  259. for (const [index, message] of messages.entries()) {
  260. const text = wireText(message.content);
  261. const bodies = text.match(/<task-notification>[\s\S]*?<\/task-notification>/gu);
  262. if (!bodies?.length) continue;
  263. expect(["user", "system"]).toContain(message.role);
  264. const body = bodies.join("\n\n");
  265. const marker = bodies[0]!.match(/<task-id>([^<]+)<\/task-id>/u)?.[1];
  266. expect(marker).toBeTruthy();
  267. // user 的中途降级与新轮通知现在使用相同包装,不能再根据标签推断消费时机。
  268. // 此处只验证全文;实际时序及角色仍由 BG25/BG36 双能力用例单独固定。
  269. // 并入 tool_result.content 的只能是中途通知(新轮通知是输入,不折叠)。
  270. const blocks = Array.isArray(message.content) ? message.content : [];
  271. const folded = blocks.some(
  272. (block) => block?.type === "tool_result" && wireText(block.content).includes(bodies[0]!),
  273. );
  274. const mid = message.role === "system" || folded;
  275. await assertIncomingMessage(request, {
  276. presentation: mid ? "task_notification_steer" : "task_notification",
  277. marker: marker!,
  278. // 修复原因:新轮通知每条各带标题和一对标签,传入拼接后的 body 会被当成一段校验,
  279. // 一条消息里有 2 条以上通知时误报失败。新轮不传 body,交给按条拆分的分支。
  280. body: mid ? body : undefined,
  281. role: message.role as "system" | "user",
  282. evidenceLabel: `${evidenceLabel}-${index}`,
  283. });
  284. }
  285. }