incoming-message-evidence.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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) => (block?.type === "text" ? String(block.text ?? "") : ""))
  20. .join("\n");
  21. }
  22. /** 验证实际网络载荷;黄金样本独立于生产 formatter。 */
  23. export async function assertIncomingMessage(
  24. request: unknown,
  25. input: {
  26. presentation: Presentation;
  27. marker: string;
  28. role: "user" | "system";
  29. body?: string;
  30. evidenceLabel?: string;
  31. },
  32. ) {
  33. const fixture = JSON.parse(
  34. await readFile(
  35. new URL(
  36. "../../../../../apps/zcode-cli/packages/core/tests/fixtures/runtime-input-presentation.json",
  37. import.meta.url,
  38. ),
  39. "utf8",
  40. ),
  41. ) as { expected: Record<Presentation, string> };
  42. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  43. if (artifactDir) {
  44. const directory = join(artifactDir, "incoming-message-wire");
  45. await mkdir(directory, { recursive: true });
  46. const name = `${input.evidenceLabel ?? "default"}-${input.presentation}-${input.marker.replace(/[^a-zA-Z0-9_-]/gu, "_").slice(0, 96)}.json`;
  47. // 只保存实际 provider JSON body;不持久化网络凭据或 headers。
  48. await writeFile(join(directory, name), `${JSON.stringify(request, null, 2)}\n`, "utf8");
  49. }
  50. const messages = (request as { messages: WireMessage[] }).messages;
  51. assertWireIntegrity(request);
  52. const template = fixture.expected[input.presentation];
  53. const prefix = template.split("{body}")[0]!;
  54. const index = messages.findIndex(
  55. (message) =>
  56. wireText(message.content).includes(prefix) &&
  57. wireText(message.content).includes(input.marker),
  58. );
  59. expect(index).toBeGreaterThanOrEqual(0);
  60. const message = messages[index]!;
  61. const text = wireText(message.content);
  62. const body =
  63. input.body ??
  64. (input.presentation.startsWith("subagent")
  65. ? text.match(/<subagent-message>[\s\S]*?<\/subagent-message>/u)?.[0]
  66. : text.match(/<task-notification>[\s\S]*?<\/task-notification>/gu)?.join("\n\n"));
  67. expect(body).toBeDefined();
  68. const wrapped =
  69. input.role === "user" &&
  70. (input.presentation.endsWith("_steer") || input.presentation === "task_notification");
  71. // 独立校验 provider 表达;提取自 wire 的正文可能已转义,不能再次编码实体。
  72. const wireBody = wrapped ? body!.replace(/<(\/?system-reminder\b)/gi, "&lt;$1") : body!;
  73. const expected = template.replace("{body}", wireBody);
  74. expect(
  75. messages.reduce((count, item) => count + wireText(item.content).split(expected).length - 1, 0),
  76. ).toBe(1);
  77. expect(message.role).toBe(input.role);
  78. expect(text).toContain(expected);
  79. if (input.presentation !== "coordinator_input") {
  80. const expectedBlock = wrapped ? `<system-reminder>\n${expected}\n</system-reminder>` : expected;
  81. const blocks =
  82. typeof message.content === "string"
  83. ? [message.content]
  84. : Array.isArray(message.content)
  85. ? message.content.filter((block) => block.type === "text").map((block) => block.text)
  86. : [];
  87. // 精确比较完整 block,防止正确模板前后夹入额外控制文案。
  88. expect(blocks).toContain(expectedBlock);
  89. if (wrapped) {
  90. const actualBlock = blocks.find(
  91. (block) => block.includes(prefix) && block.includes(input.marker),
  92. );
  93. expect(actualBlock?.match(/<\/?system-reminder\b/gi)).toHaveLength(2);
  94. }
  95. }
  96. // 只统计 text block,工具入参中的同名载荷不算第二份输入。
  97. expect(
  98. messages.reduce((count, item) => count + wireText(item.content).split(wireBody).length - 1, 0),
  99. ).toBe(1);
  100. if (input.role === "system") expect(text).not.toContain(`<system-reminder>\n${prefix}`);
  101. else if (wrapped) expect(text).toContain(`<system-reminder>\n${expected}\n</system-reminder>`);
  102. else expect(text).not.toContain(`<system-reminder>\n${expected}`);
  103. return { index, messages };
  104. }
  105. /** 系统中途消息不能拆开并行工具的结果批次,也不能泄漏内部来源字段。 */
  106. export function assertWireIntegrity(request: unknown): void {
  107. const messages = (request as { messages: WireMessage[] }).messages;
  108. expect(JSON.stringify(request)).not.toMatch(
  109. /"(?:inputPresentation|steerContext|sourceEntries)"\s*:/u,
  110. );
  111. const pending = new Set<string>();
  112. for (const message of messages) {
  113. const blocks = Array.isArray(message.content) ? message.content : [];
  114. const results = blocks.filter((block) => block.type === "tool_result");
  115. if (pending.size > 0) {
  116. expect(message.role).toBe("user");
  117. expect(results.map((block) => block.tool_use_id).sort()).toEqual([...pending].sort());
  118. pending.clear();
  119. } else {
  120. expect(results).toHaveLength(0);
  121. }
  122. for (const block of blocks) {
  123. if (block.type === "tool_use") pending.add(block.id);
  124. }
  125. expect(wireText(message.content).length > 0 || blocks.length > 0).toBe(true);
  126. }
  127. expect([...pending]).toHaveLength(0);
  128. }
  129. /** 既有后台生命周期用例共用全文断言;角色分支另由双能力时序矩阵固定验证。 */
  130. export async function assertTaskNotificationContents(
  131. request: unknown,
  132. evidenceLabel: string,
  133. ): Promise<void> {
  134. const messages = (request as { messages: WireMessage[] }).messages;
  135. for (const [index, message] of messages.entries()) {
  136. const text = wireText(message.content);
  137. const bodies = text.match(/<task-notification>[\s\S]*?<\/task-notification>/gu);
  138. if (!bodies?.length) continue;
  139. expect(["user", "system"]).toContain(message.role);
  140. const body = bodies.join("\n\n");
  141. const marker = bodies[0]!.match(/<task-id>([^<]+)<\/task-id>/u)?.[1];
  142. expect(marker).toBeTruthy();
  143. // user 的中途降级与新轮通知现在使用相同包装,不能再根据标签推断消费时机。
  144. // 此处只验证全文;实际时序及角色仍由 BG25/BG36 双能力用例单独固定。
  145. const mid = message.role === "system";
  146. await assertIncomingMessage(request, {
  147. presentation: mid ? "task_notification_steer" : "task_notification",
  148. marker: marker!,
  149. body,
  150. role: message.role as "system" | "user",
  151. evidenceLabel: `${evidenceLabel}-${index}`,
  152. });
  153. }
  154. }