memory-e2e-evidence.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. assertCondition(
  229. !disabledRequest.text.includes("# Memory"),
  230. "disabled Memory request must not contain the Memory section",
  231. );
  232. const disabledScenarioRequests = records.filter((record) => record.scenario === "disabled");
  233. assertCondition(
  234. disabledScenarioRequests.length === 1 && disabledScenarioRequests[0]?.category === "main",
  235. "disabled Memory must not issue selector or Extraction requests",
  236. disabledScenarioRequests.map(({ category }) => category),
  237. );
  238. assertCondition(
  239. !(await fileExists(paths.disabled.memoryRoot)),
  240. "disabled Memory must not create the project root",
  241. );
  242. assertions.push("memory-disabled-gate");
  243. const headlessBoundary = verifyHeadlessRequestBoundary(records);
  244. const headlessRequest = headlessBoundary.mainRequest;
  245. const expectedHeadlessMemory = mainMemoryFixture.replaceAll(
  246. "<MEMORY_ROOT>",
  247. paths.headless.memoryRoot,
  248. );
  249. assertContains(
  250. headlessRequest.text,
  251. expectedHeadlessMemory,
  252. "headless Main request must retain the active Memory system section",
  253. );
  254. if (retrievalBranch === "default-index") {
  255. const expectedHeadlessMemoryIndex = mainMemoryIndexFixture.replaceAll(
  256. "<MEMORY_INDEX_PATH>",
  257. paths.headless.indexFile,
  258. );
  259. assertContains(
  260. headlessRequest.text,
  261. expectedHeadlessMemoryIndex,
  262. "headless Main request must retain the default MEMORY.md source",
  263. );
  264. }
  265. const headlessExistingFile = await readFile(paths.headless.existingFile, "utf8");
  266. const headlessIndex = await readFile(paths.headless.indexFile, "utf8");
  267. const headlessMemoryFiles = (await readdir(paths.headless.memoryRoot)).sort();
  268. assertCondition(
  269. headlessExistingFile === existingMemoryFile(),
  270. "headless runtime must not mutate an existing Memory fact",
  271. headlessExistingFile,
  272. );
  273. assertCondition(
  274. headlessIndex === initialProjectMemoryIndex(),
  275. "headless runtime must not mutate MEMORY.md",
  276. headlessIndex,
  277. );
  278. assertCondition(
  279. headlessMemoryFiles.join("\n") === ["MEMORY.md", "database-test-policy.md"].sort().join("\n"),
  280. "headless runtime must not create an extracted Memory file",
  281. headlessMemoryFiles,
  282. );
  283. assertions.push("headless-main-memory-without-extraction");
  284. const shutdownRequests = records.filter((record) => record.scenario === "shutdown");
  285. assertCondition(
  286. shutdownRequests.length === 2 &&
  287. shutdownRequests[0]?.category === "main" &&
  288. shutdownRequests[1]?.category === "extraction",
  289. "session close must stop after the in-flight Extraction request without a tool continuation",
  290. shutdownRequests.map(({ category, index }) => ({ category, index })),
  291. );
  292. assertCondition(
  293. scenarioResults.closeCancellation.closeDurationMs < 2_000,
  294. "session close must not wait for the blocked Extraction provider response",
  295. scenarioResults.closeCancellation,
  296. );
  297. assertCondition(
  298. !(await fileExists(paths.shutdown.cancelledFile)),
  299. "late Extraction tool-use must not write after session close",
  300. paths.shutdown.cancelledFile,
  301. );
  302. assertions.push("session-close-cancels-in-flight-extraction");
  303. // 固定完整 trajectory,避免额外的 Main retry 或重放被 requireRecord 忽略。
  304. assertCondition(
  305. categoryCounts.main === (retrievalBranch === "semantic-recall" ? 10 : 9),
  306. `expected the exact ${retrievalBranch} Main request count`,
  307. categoryCounts,
  308. );
  309. // Bug 根因:headless 只关闭 Extraction;semantic Recall prefetch 与 Main 并发,direct-answer
  310. // 结束时 Selector 可能已经到达 provider,也可能在到达前被取消,不能计入固定 trajectory。
  311. const stableSelectorRequestCount = countStableSelectorRequests(records);
  312. assertCondition(
  313. stableSelectorRequestCount === (retrievalBranch === "semantic-recall" ? 2 : 0),
  314. `expected the exact ${retrievalBranch} Selector request count`,
  315. { categoryCounts, headlessSelectorRequestCount: headlessBoundary.selectorRequestCount },
  316. );
  317. verifyStableExtractionRequestCount(categoryCounts.extraction);
  318. assertCondition(
  319. categoryCounts.custom_agent === 2,
  320. "expected one custom-agent tool turn and one completion turn",
  321. categoryCounts,
  322. );
  323. return {
  324. assertions,
  325. categoryCounts,
  326. files: {
  327. customFile,
  328. existingFile,
  329. extractedFile,
  330. headlessExistingFile,
  331. headlessIndex,
  332. updatedIndex,
  333. },
  334. records,
  335. };
  336. }
  337. export async function writeMemoryE2EArtifacts({
  338. artifactsRoot,
  339. evidence,
  340. paths,
  341. provider,
  342. result,
  343. }) {
  344. await writeScriptedCaptureFile(provider, join(artifactsRoot, "provider-capture.json"));
  345. await writeFile(
  346. join(artifactsRoot, "trajectory.jsonl"),
  347. evidence.records
  348. .map((record) =>
  349. JSON.stringify({
  350. category: record.category,
  351. index: record.index,
  352. requestBody: record.body,
  353. scenario: record.scenario,
  354. startedAt: record.startedAt,
  355. }),
  356. )
  357. .join("\n") + "\n",
  358. );
  359. await writeFile(
  360. join(artifactsRoot, "trajectory-summary.json"),
  361. `${JSON.stringify(
  362. {
  363. assertions: evidence.assertions,
  364. categoryCounts: evidence.categoryCounts,
  365. retrievalBranch: result.retrievalBranch,
  366. requests: evidence.records.map(({ category, index, scenario, startedAt }) => ({
  367. category,
  368. index,
  369. scenario,
  370. startedAt,
  371. })),
  372. },
  373. null,
  374. 2,
  375. )}\n`,
  376. );
  377. await writeFile(
  378. join(artifactsRoot, "memory-files.json"),
  379. `${JSON.stringify(
  380. {
  381. custom: { content: evidence.files.customFile, path: paths.custom.memoryFile },
  382. extraction: { content: evidence.files.extractedFile, path: paths.project.extractedFile },
  383. headlessExistingFact: {
  384. content: evidence.files.headlessExistingFile,
  385. path: paths.headless.existingFile,
  386. },
  387. headlessIndex: {
  388. content: evidence.files.headlessIndex,
  389. path: paths.headless.indexFile,
  390. },
  391. projectIndex: { content: evidence.files.updatedIndex, path: paths.project.indexFile },
  392. existingFact: { content: evidence.files.existingFile, path: paths.project.existingFile },
  393. },
  394. null,
  395. 2,
  396. )}\n`,
  397. );
  398. await writeFile(join(artifactsRoot, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
  399. }
  400. function normalizeRecord(record, index) {
  401. const body = JSON.parse(record.requestBody);
  402. const text = requestText(body);
  403. return {
  404. body,
  405. category: classifyRequest(body),
  406. index,
  407. scenario: classifyScenario(text),
  408. startedAt: record.startedAt,
  409. text,
  410. };
  411. }
  412. function classifyScenario(text) {
  413. if (text.includes(memoryE2EText.closeCancellationPrompt)) return "shutdown";
  414. if (text.includes(memoryE2EText.disabledPrompt)) return "disabled";
  415. if (text.includes(memoryE2EText.headlessPrompt)) return "headless";
  416. if (
  417. text.includes(memoryE2EText.customParentPrompt) ||
  418. text.includes(memoryE2EText.customTaskPrompt) ||
  419. text.includes(memoryE2EText.customMemoryMarker)
  420. ) {
  421. return "custom";
  422. }
  423. return "project";
  424. }
  425. function toolNames(body) {
  426. return Array.isArray(body.tools)
  427. ? body.tools
  428. .map((tool) => tool?.function?.name ?? tool?.name)
  429. .filter((name) => typeof name === "string")
  430. : [];
  431. }
  432. async function fixture(name) {
  433. return (
  434. await readFile(
  435. join(repoRoot, "apps/zcode-cli/packages/core/tests/fixtures/memory", name),
  436. "utf8",
  437. )
  438. ).trimEnd();
  439. }
  440. function requireRecord(records, predicate, label) {
  441. const record = records.find(predicate);
  442. assertCondition(
  443. record,
  444. `Missing ${label}`,
  445. records.map(({ category, scenario }) => ({ category, scenario })),
  446. );
  447. return record;
  448. }
  449. export function verifyHeadlessRequestBoundary(records) {
  450. const headlessRequests = records.filter((record) => record.scenario === "headless");
  451. const mainRequests = headlessRequests.filter((record) => record.category === "main");
  452. const selectorRequests = headlessRequests.filter((record) => record.category === "selector");
  453. const extractionRequests = headlessRequests.filter((record) => record.category === "extraction");
  454. const details = headlessRequests.map(({ category, index }) => ({ category, index }));
  455. assertCondition(
  456. mainRequests.length === 1,
  457. "headless Memory must issue exactly one Main request",
  458. details,
  459. );
  460. assertCondition(
  461. extractionRequests.length === 0,
  462. "headless Memory must not issue Extraction requests",
  463. details,
  464. );
  465. assertCondition(
  466. selectorRequests.length <= 1,
  467. "headless Memory must not issue duplicate Selector requests",
  468. details,
  469. );
  470. return {
  471. mainRequest: mainRequests[0],
  472. selectorRequestCount: selectorRequests.length,
  473. };
  474. }
  475. export function countStableSelectorRequests(records) {
  476. return records.filter(
  477. (record) => record.category === "selector" && record.scenario !== "headless",
  478. ).length;
  479. }
  480. export function verifyStableExtractionRequestCount(count) {
  481. // Bug 根因:首个 no-op Extraction 与紧随其后的用户提交并发;scheduler 明确只保留
  482. // latest pending snapshot,因此它若尚未开始会被下一份快照合并,完整轨迹会少一次 no-op。
  483. assertCondition(
  484. count === 5 || count === 6,
  485. "expected five or six Extraction requests after optional initial no-op coalescing",
  486. { count },
  487. );
  488. }
  489. function assertContains(actual, expected, message) {
  490. assertCondition(actual.includes(expected), message, {
  491. expected,
  492. tail: actual.slice(-2_000),
  493. });
  494. }
  495. function assertCondition(condition, message, details) {
  496. if (condition) return;
  497. const suffix = details === undefined ? "" : `\n${JSON.stringify(details, null, 2)}`;
  498. throw new Error(`${message}${suffix}`);
  499. }
  500. function countBy(items, keyOf) {
  501. const counts = {};
  502. for (const item of items) {
  503. const key = keyOf(item);
  504. counts[key] = (counts[key] ?? 0) + 1;
  505. }
  506. return counts;
  507. }
  508. async function fileExists(path) {
  509. try {
  510. await stat(path);
  511. return true;
  512. } catch {
  513. return false;
  514. }
  515. }