memory-e2e-evidence.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. import { readFile, readdir, stat, writeFile } from "node:fs/promises";
  2. import { dirname, join, resolve } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. import { writeScriptedCaptureFile } from "../compact-microcompact/scripted-provider.mjs";
  5. import {
  6. classifyRequest,
  7. existingMemoryFile,
  8. initialProjectMemoryIndex,
  9. memoryE2EText,
  10. requestText,
  11. updatedProjectMemoryIndex,
  12. } from "./memory-e2e-provider.mjs";
  13. const scriptDir = dirname(fileURLToPath(import.meta.url));
  14. const repoRoot = resolve(scriptDir, "../../../..");
  15. export async function verifyMemoryE2EEvidence({
  16. paths,
  17. provider,
  18. retrievalBranch,
  19. scenarioResults,
  20. }) {
  21. const records = provider.records
  22. .map((record, index) => normalizeRecord(record, index + 1))
  23. .sort(
  24. (left, right) => left.startedAt.localeCompare(right.startedAt) || left.index - right.index,
  25. );
  26. const categoryCounts = countBy(records, (record) => record.category);
  27. const assertions = [];
  28. const retrievalBranchRequests = records.filter(
  29. (record) =>
  30. record.category === "main" &&
  31. record.text.includes(memoryE2EText.defaultBranchPrompt) &&
  32. !record.text.includes(memoryE2EText.extractionPrompt),
  33. );
  34. assertCondition(
  35. retrievalBranchRequests.length === 2,
  36. "Memory retrieval turn must contain one initial request and one tool continuation",
  37. retrievalBranchRequests.map(({ index }) => index),
  38. );
  39. const mainMemoryFixture = await fixture(
  40. retrievalBranch === "semantic-recall"
  41. ? "main-memory-semantic-recall.md"
  42. : "main-memory-default-index.md",
  43. );
  44. const expectedMainMemory = mainMemoryFixture.replaceAll(
  45. "<MEMORY_ROOT>",
  46. paths.project.memoryRoot,
  47. );
  48. const mainMemoryIndexFixture = await fixture("main-memory-index.md");
  49. const expectedMainMemoryIndex = mainMemoryIndexFixture.replaceAll(
  50. "<MEMORY_INDEX_PATH>",
  51. paths.project.indexFile,
  52. );
  53. for (const request of retrievalBranchRequests) {
  54. assertContains(
  55. request.text,
  56. expectedMainMemory,
  57. "every Main request must contain the exact active-branch Memory section",
  58. );
  59. }
  60. if (retrievalBranch === "default-index") {
  61. for (const request of retrievalBranchRequests) {
  62. assertContains(
  63. request.text,
  64. expectedMainMemoryIndex,
  65. "every default-branch Main request must contain the exact MEMORY.md user-context source",
  66. );
  67. }
  68. assertCondition(
  69. records.every((record) => record.category !== "selector"),
  70. "default Memory branch must not issue Selector requests",
  71. categoryCounts,
  72. );
  73. assertCondition(
  74. records.every((record) => !record.text.includes(memoryE2EText.recalledPrefix)),
  75. "default Memory branch must not inject relevant_memory",
  76. );
  77. assertions.push("default-main-memory-index-without-selector-recall");
  78. } else {
  79. assertCondition(
  80. retrievalBranchRequests.every((request) => !request.text.includes(expectedMainMemoryIndex)),
  81. "semantic Memory branch must not load MEMORY.md",
  82. );
  83. const recalledRequest = requireRecord(
  84. retrievalBranchRequests,
  85. (record) => record.text.includes(memoryE2EText.recalledPrefix),
  86. "semantic Memory continuation with relevant_memory",
  87. );
  88. assertContains(
  89. recalledRequest.text,
  90. existingMemoryFile().trimEnd(),
  91. "semantic Memory continuation must contain the selected fact",
  92. );
  93. assertions.push("semantic-main-recall-without-pointer-index");
  94. }
  95. const existingFile = await readFile(paths.project.existingFile, "utf8");
  96. assertCondition(
  97. existingFile === existingMemoryFile(),
  98. "Memory retrieval must not mutate an existing fact",
  99. existingFile,
  100. );
  101. const extraction = requireRecord(
  102. records,
  103. (record) =>
  104. record.category === "extraction" && record.text.includes(memoryE2EText.extractionPrompt),
  105. "background Extraction request",
  106. );
  107. assertContains(
  108. extraction.text,
  109. memoryE2EText.extractionPrompt,
  110. "Extraction must use the successful Main turn snapshot",
  111. );
  112. assertContains(
  113. extraction.text,
  114. memoryE2EText.extractionMarker,
  115. "Extraction request must contain the Memory extraction prompt",
  116. );
  117. const extractedFile = await readFile(paths.project.extractedFile, "utf8");
  118. assertContains(
  119. extractedFile,
  120. memoryE2EText.extractionWriteMarker,
  121. "Extraction must write the scripted fact",
  122. );
  123. assertContains(
  124. extractedFile,
  125. "node_type: memory",
  126. "Extraction Write must add the fixed Memory node type",
  127. );
  128. assertContains(
  129. extractedFile,
  130. "originSessionId: memory-e2e-project-session",
  131. "Extraction Write must add the creating session",
  132. );
  133. assertions.push("background-extraction-trajectory-and-file");
  134. const updatedIndex = await readFile(paths.project.indexFile, "utf8");
  135. assertCondition(
  136. updatedIndex === updatedProjectMemoryIndex(),
  137. "Extraction must append the new fact pointer to MEMORY.md",
  138. updatedIndex,
  139. );
  140. if (retrievalBranch === "default-index") {
  141. const nextSessionRequest = requireRecord(
  142. records,
  143. (record) =>
  144. record.category === "main" && record.text.includes(memoryE2EText.extractedDefaultPrompt),
  145. "next-session default Memory request",
  146. );
  147. const expectedUpdatedMainMemoryIndex = expectedMainMemoryIndex.replace(
  148. initialProjectMemoryIndex().trimEnd(),
  149. updatedProjectMemoryIndex().trimEnd(),
  150. );
  151. assertContains(
  152. nextSessionRequest.text,
  153. expectedUpdatedMainMemoryIndex,
  154. "next session must consume the Extraction pointer through the default MEMORY.md source",
  155. );
  156. assertions.push("extraction-to-next-session-default-index-consumption");
  157. } else {
  158. const nextSessionRequest = requireRecord(
  159. records,
  160. (record) =>
  161. record.category === "main" &&
  162. record.text.includes(memoryE2EText.extractedDefaultPrompt) &&
  163. record.text.includes(memoryE2EText.recalledPrefix),
  164. "next-session semantic Memory continuation",
  165. );
  166. assertContains(
  167. nextSessionRequest.text,
  168. memoryE2EText.extractionWriteMarker,
  169. "next session must consume the fact produced by Extraction",
  170. );
  171. assertContains(
  172. nextSessionRequest.text,
  173. "originSessionId: memory-e2e-project-session",
  174. "semantic Recall must preserve the extracted fact metadata",
  175. );
  176. assertCondition(
  177. !nextSessionRequest.text.includes(expectedMainMemoryIndex),
  178. "semantic next session must not also load MEMORY.md",
  179. );
  180. assertions.push("extraction-to-next-session-semantic-recall-consumption");
  181. }
  182. const customRequest = requireRecord(
  183. records,
  184. (record) => record.category === "custom_agent",
  185. "custom agent Memory request",
  186. );
  187. assertContains(
  188. customRequest.text,
  189. memoryE2EText.customMemoryMarker,
  190. "custom child must contain the persistent Memory prompt",
  191. );
  192. assertContains(
  193. customRequest.text,
  194. "Keep review findings evidence-first",
  195. "custom child must read its existing MEMORY.md",
  196. );
  197. const customTools = toolNames(customRequest.body);
  198. for (const tool of ["Grep", "Write", "Edit"]) {
  199. assertCondition(customTools.includes(tool), `custom child must expose ${tool}`, customTools);
  200. }
  201. assertCondition(!customTools.includes("Read"), "custom Memory must not add Read", customTools);
  202. const customFile = await readFile(paths.custom.memoryFile, "utf8");
  203. assertContains(
  204. customFile,
  205. memoryE2EText.customWriteMarker,
  206. "custom agent must write its scoped fact",
  207. );
  208. assertCondition(
  209. /node_type:\s*memory/u.test(customFile),
  210. "custom agent Write must add the fixed Memory node type",
  211. customFile,
  212. );
  213. assertCondition(
  214. /originSessionId:\s*[^\s]+/u.test(customFile),
  215. "custom agent Write must add its child session id",
  216. customFile,
  217. );
  218. assertCondition(
  219. !(await fileExists(join(paths.project.memoryRoot, "review-convention.md"))),
  220. "custom agent fact must not leak into the Main project Memory root",
  221. );
  222. assertions.push("custom-agent-memory-prompt-tools-file");
  223. const disabledRequest = requireRecord(
  224. records,
  225. (record) => record.category === "main" && record.text.includes(memoryE2EText.disabledPrompt),
  226. "disabled Memory Main request",
  227. );
  228. // 只看 Memory 段标题;默认 prompt 总带 `# Memory, notes and feedback`,那一段不算 Memory 注入。
  229. assertCondition(
  230. !disabledRequest.text.includes("# Memory\n"),
  231. "disabled Memory request must not contain the Memory section",
  232. );
  233. const disabledScenarioRequests = records.filter((record) => record.scenario === "disabled");
  234. assertCondition(
  235. disabledScenarioRequests.length === 1 && disabledScenarioRequests[0]?.category === "main",
  236. "disabled Memory must not issue selector or Extraction requests",
  237. disabledScenarioRequests.map(({ category }) => category),
  238. );
  239. assertCondition(
  240. !(await fileExists(paths.disabled.memoryRoot)),
  241. "disabled Memory must not create the project root",
  242. );
  243. assertions.push("memory-disabled-gate");
  244. const headlessBoundary = verifyHeadlessRequestBoundary(records);
  245. const headlessRequest = headlessBoundary.mainRequest;
  246. const expectedHeadlessMemory = mainMemoryFixture.replaceAll(
  247. "<MEMORY_ROOT>",
  248. paths.headless.memoryRoot,
  249. );
  250. assertContains(
  251. headlessRequest.text,
  252. expectedHeadlessMemory,
  253. "headless Main request must retain the active Memory system section",
  254. );
  255. if (retrievalBranch === "default-index") {
  256. const expectedHeadlessMemoryIndex = mainMemoryIndexFixture.replaceAll(
  257. "<MEMORY_INDEX_PATH>",
  258. paths.headless.indexFile,
  259. );
  260. assertContains(
  261. headlessRequest.text,
  262. expectedHeadlessMemoryIndex,
  263. "headless Main request must retain the default MEMORY.md source",
  264. );
  265. }
  266. const headlessExistingFile = await readFile(paths.headless.existingFile, "utf8");
  267. const headlessIndex = await readFile(paths.headless.indexFile, "utf8");
  268. const headlessMemoryFiles = (await readdir(paths.headless.memoryRoot)).sort();
  269. assertCondition(
  270. headlessExistingFile === existingMemoryFile(),
  271. "headless runtime must not mutate an existing Memory fact",
  272. headlessExistingFile,
  273. );
  274. assertCondition(
  275. headlessIndex === initialProjectMemoryIndex(),
  276. "headless runtime must not mutate MEMORY.md",
  277. headlessIndex,
  278. );
  279. assertCondition(
  280. headlessMemoryFiles.join("\n") === ["MEMORY.md", "database-test-policy.md"].sort().join("\n"),
  281. "headless runtime must not create an extracted Memory file",
  282. headlessMemoryFiles,
  283. );
  284. assertions.push("headless-main-memory-without-extraction");
  285. const shutdownRequests = records.filter((record) => record.scenario === "shutdown");
  286. assertCondition(
  287. shutdownRequests.length === 2 &&
  288. shutdownRequests[0]?.category === "main" &&
  289. shutdownRequests[1]?.category === "extraction",
  290. "session close must stop after the in-flight Extraction request without a tool continuation",
  291. shutdownRequests.map(({ category, index }) => ({ category, index })),
  292. );
  293. assertCondition(
  294. scenarioResults.closeCancellation.closeDurationMs < 2_000,
  295. "session close must not wait for the blocked Extraction provider response",
  296. scenarioResults.closeCancellation,
  297. );
  298. assertCondition(
  299. !(await fileExists(paths.shutdown.cancelledFile)),
  300. "late Extraction tool-use must not write after session close",
  301. paths.shutdown.cancelledFile,
  302. );
  303. assertions.push("session-close-cancels-in-flight-extraction");
  304. // 固定完整 trajectory,避免额外的 Main retry 或重放被 requireRecord 忽略。
  305. assertCondition(
  306. categoryCounts.main === (retrievalBranch === "semantic-recall" ? 10 : 9),
  307. `expected the exact ${retrievalBranch} Main request count`,
  308. categoryCounts,
  309. );
  310. // Bug 根因:headless 只关闭 Extraction;semantic Recall prefetch 与 Main 并发,direct-answer
  311. // 结束时 Selector 可能已经到达 provider,也可能在到达前被取消,不能计入固定 trajectory。
  312. const stableSelectorRequestCount = countStableSelectorRequests(records);
  313. assertCondition(
  314. stableSelectorRequestCount === (retrievalBranch === "semantic-recall" ? 2 : 0),
  315. `expected the exact ${retrievalBranch} Selector request count`,
  316. { categoryCounts, headlessSelectorRequestCount: headlessBoundary.selectorRequestCount },
  317. );
  318. verifyStableExtractionRequestCount(categoryCounts.extraction);
  319. assertCondition(
  320. categoryCounts.custom_agent === 2,
  321. "expected one custom-agent tool turn and one completion turn",
  322. categoryCounts,
  323. );
  324. return {
  325. assertions,
  326. categoryCounts,
  327. files: {
  328. customFile,
  329. existingFile,
  330. extractedFile,
  331. headlessExistingFile,
  332. headlessIndex,
  333. updatedIndex,
  334. },
  335. records,
  336. };
  337. }
  338. export async function writeMemoryE2EArtifacts({
  339. artifactsRoot,
  340. evidence,
  341. paths,
  342. provider,
  343. result,
  344. }) {
  345. await writeScriptedCaptureFile(provider, join(artifactsRoot, "provider-capture.json"));
  346. await writeFile(
  347. join(artifactsRoot, "trajectory.jsonl"),
  348. evidence.records
  349. .map((record) =>
  350. JSON.stringify({
  351. category: record.category,
  352. index: record.index,
  353. requestBody: record.body,
  354. scenario: record.scenario,
  355. startedAt: record.startedAt,
  356. }),
  357. )
  358. .join("\n") + "\n",
  359. );
  360. await writeFile(
  361. join(artifactsRoot, "trajectory-summary.json"),
  362. `${JSON.stringify(
  363. {
  364. assertions: evidence.assertions,
  365. categoryCounts: evidence.categoryCounts,
  366. retrievalBranch: result.retrievalBranch,
  367. requests: evidence.records.map(({ category, index, scenario, startedAt }) => ({
  368. category,
  369. index,
  370. scenario,
  371. startedAt,
  372. })),
  373. },
  374. null,
  375. 2,
  376. )}\n`,
  377. );
  378. await writeFile(
  379. join(artifactsRoot, "memory-files.json"),
  380. `${JSON.stringify(
  381. {
  382. custom: { content: evidence.files.customFile, path: paths.custom.memoryFile },
  383. extraction: { content: evidence.files.extractedFile, path: paths.project.extractedFile },
  384. headlessExistingFact: {
  385. content: evidence.files.headlessExistingFile,
  386. path: paths.headless.existingFile,
  387. },
  388. headlessIndex: {
  389. content: evidence.files.headlessIndex,
  390. path: paths.headless.indexFile,
  391. },
  392. projectIndex: { content: evidence.files.updatedIndex, path: paths.project.indexFile },
  393. existingFact: { content: evidence.files.existingFile, path: paths.project.existingFile },
  394. },
  395. null,
  396. 2,
  397. )}\n`,
  398. );
  399. await writeFile(join(artifactsRoot, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
  400. }
  401. function normalizeRecord(record, index) {
  402. const body = JSON.parse(record.requestBody);
  403. const text = requestText(body);
  404. return {
  405. body,
  406. category: classifyRequest(body),
  407. index,
  408. scenario: classifyScenario(text),
  409. startedAt: record.startedAt,
  410. text,
  411. };
  412. }
  413. function classifyScenario(text) {
  414. if (text.includes(memoryE2EText.closeCancellationPrompt)) return "shutdown";
  415. if (text.includes(memoryE2EText.disabledPrompt)) return "disabled";
  416. if (text.includes(memoryE2EText.headlessPrompt)) return "headless";
  417. if (
  418. text.includes(memoryE2EText.customParentPrompt) ||
  419. text.includes(memoryE2EText.customTaskPrompt) ||
  420. text.includes(memoryE2EText.customMemoryMarker)
  421. ) {
  422. return "custom";
  423. }
  424. return "project";
  425. }
  426. function toolNames(body) {
  427. return Array.isArray(body.tools)
  428. ? body.tools
  429. .map((tool) => tool?.function?.name ?? tool?.name)
  430. .filter((name) => typeof name === "string")
  431. : [];
  432. }
  433. async function fixture(name) {
  434. return (
  435. await readFile(
  436. join(repoRoot, "apps/zcode-cli/packages/core/tests/fixtures/memory", name),
  437. "utf8",
  438. )
  439. ).trimEnd();
  440. }
  441. function requireRecord(records, predicate, label) {
  442. const record = records.find(predicate);
  443. assertCondition(
  444. record,
  445. `Missing ${label}`,
  446. records.map(({ category, scenario }) => ({ category, scenario })),
  447. );
  448. return record;
  449. }
  450. export function verifyHeadlessRequestBoundary(records) {
  451. const headlessRequests = records.filter((record) => record.scenario === "headless");
  452. const mainRequests = headlessRequests.filter((record) => record.category === "main");
  453. const selectorRequests = headlessRequests.filter((record) => record.category === "selector");
  454. const extractionRequests = headlessRequests.filter((record) => record.category === "extraction");
  455. const details = headlessRequests.map(({ category, index }) => ({ category, index }));
  456. assertCondition(
  457. mainRequests.length === 1,
  458. "headless Memory must issue exactly one Main request",
  459. details,
  460. );
  461. assertCondition(
  462. extractionRequests.length === 0,
  463. "headless Memory must not issue Extraction requests",
  464. details,
  465. );
  466. assertCondition(
  467. selectorRequests.length <= 1,
  468. "headless Memory must not issue duplicate Selector requests",
  469. details,
  470. );
  471. return {
  472. mainRequest: mainRequests[0],
  473. selectorRequestCount: selectorRequests.length,
  474. };
  475. }
  476. export function countStableSelectorRequests(records) {
  477. return records.filter(
  478. (record) => record.category === "selector" && record.scenario !== "headless",
  479. ).length;
  480. }
  481. export function verifyStableExtractionRequestCount(count) {
  482. // Bug 根因:首个 no-op Extraction 与紧随其后的用户提交并发;scheduler 明确只保留
  483. // latest pending snapshot,因此它若尚未开始会被下一份快照合并,完整轨迹会少一次 no-op。
  484. assertCondition(
  485. count === 5 || count === 6,
  486. "expected five or six Extraction requests after optional initial no-op coalescing",
  487. { count },
  488. );
  489. }
  490. function assertContains(actual, expected, message) {
  491. assertCondition(actual.includes(expected), message, {
  492. expected,
  493. tail: actual.slice(-2_000),
  494. });
  495. }
  496. function assertCondition(condition, message, details) {
  497. if (condition) return;
  498. const suffix = details === undefined ? "" : `\n${JSON.stringify(details, null, 2)}`;
  499. throw new Error(`${message}${suffix}`);
  500. }
  501. function countBy(items, keyOf) {
  502. const counts = {};
  503. for (const item of items) {
  504. const key = keyOf(item);
  505. counts[key] = (counts[key] ?? 0) + 1;
  506. }
  507. return counts;
  508. }
  509. async function fileExists(path) {
  510. try {
  511. await stat(path);
  512. return true;
  513. } catch {
  514. return false;
  515. }
  516. }