memory-extraction.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import { join } from "node:path";
  2. import { readFileSync } from "node:fs";
  3. import { describe, expect, it } from "vitest";
  4. import {
  5. createMessageId,
  6. createModelId,
  7. createModelProviderId,
  8. createPartId,
  9. createSessionId,
  10. type MessageId,
  11. type MessagePart,
  12. type MessageWithParts,
  13. type ToolState,
  14. } from "@zcode/contracts";
  15. import {
  16. buildMemoryExtractionPrompt,
  17. createMemoryExtractionScheduler,
  18. evaluateMemoryExtraction,
  19. type MemoryExtractionExecutionStatus,
  20. type MemoryExtractionSnapshot,
  21. } from "../src/memory/extraction.js";
  22. const SESSION_ID = createSessionId("memory-extraction");
  23. const PROVIDER_ID = createModelProviderId("test-provider");
  24. const MODEL_ID = createModelId("test-model");
  25. const WORKSPACE_ROOT = "/workspace";
  26. const MEMORY_ROOT = "/storage/memories/project/memory";
  27. describe("memory extraction prompt", () => {
  28. it("matches the frozen provider-visible fixture", () => {
  29. const timestamp = "2026-07-16T01:02:03.000Z";
  30. const fixture = readFileSync(
  31. new URL("./fixtures/memory/extraction-prompt.md", import.meta.url),
  32. "utf8",
  33. )
  34. .trimEnd()
  35. .replace("<TIMESTAMP>", timestamp);
  36. expect(
  37. buildMemoryExtractionPrompt({
  38. manifest: [
  39. {
  40. description: "Database tests must use the real database rather than mocks.",
  41. filePath: `${MEMORY_ROOT}/database-test-policy.md`,
  42. filename: "database-test-policy.md",
  43. mtimeMs: Date.parse(timestamp),
  44. type: "feedback",
  45. },
  46. ],
  47. messageCount: 2,
  48. }),
  49. ).toBe(fixture);
  50. });
  51. it("omits the existing-memory section when the manifest is empty", () => {
  52. const prompt = buildMemoryExtractionPrompt({ manifest: [], messageCount: 4 });
  53. expect(prompt).toContain("most recent ~4 messages");
  54. expect(prompt).not.toContain("## Existing memory files");
  55. });
  56. });
  57. describe("memory extraction gate", () => {
  58. it("requires one independent non-meta user text block with at least three words", () => {
  59. const cursor = userMessage("cursor", ["previous durable request"]);
  60. const shortBlocks = userMessage("short-blocks", ["one two", "three four"]);
  61. const meta = userMessage("meta", ["meta text has words"], { synthetic: true });
  62. const modelOnly = userMessage("model-only", ["hidden text has words"], {
  63. visibility: "model-only",
  64. });
  65. expect(
  66. evaluateMemoryExtraction(snapshot([cursor, shortBlocks, meta, modelOnly]), cursor.info.id),
  67. ).toEqual({ decision: "skip", messageCount: 3, reason: "no-user-prose" });
  68. const eligible = userMessage("eligible", ["one two", "one two three"]);
  69. expect(evaluateMemoryExtraction(snapshot([cursor, eligible]), cursor.info.id)).toEqual({
  70. decision: "run",
  71. messageCount: 1,
  72. });
  73. });
  74. it("skips after a contained Write or Edit regardless of tool status and filename extension", () => {
  75. const cursor = userMessage("cursor", ["previous durable request"]);
  76. const prose = userMessage("prose", ["save this durable preference"]);
  77. const statuses: ToolState[] = [
  78. { status: "pending", input: { file_path: join(MEMORY_ROOT, "pending.txt") }, raw: "" },
  79. {
  80. status: "error",
  81. input: { file_path: join(MEMORY_ROOT, "failed-without-extension") },
  82. error: "write failed",
  83. time: { start: 1, end: 2 },
  84. },
  85. ];
  86. for (const [index, state] of statuses.entries()) {
  87. const write = assistantToolMessage(`write-${index}`, index === 0 ? "Write" : "Edit", state);
  88. expect(evaluateMemoryExtraction(snapshot([cursor, prose, write]), cursor.info.id)).toEqual({
  89. decision: "skip",
  90. messageCount: 2,
  91. reason: "direct-memory-write",
  92. });
  93. }
  94. const outsideWrite = assistantToolMessage("outside", "Write", {
  95. status: "completed",
  96. input: { file_path: "/workspace/not-memory.md" },
  97. output: "ok",
  98. title: "write",
  99. metadata: {},
  100. time: { start: 1, end: 2 },
  101. });
  102. expect(
  103. evaluateMemoryExtraction(snapshot([cursor, prose, outsideWrite]), cursor.info.id),
  104. ).toEqual({ decision: "run", messageCount: 2 });
  105. });
  106. it("does not backscan direct writes when a non-empty cursor is missing", () => {
  107. const oldWrite = assistantToolMessage("old-write", "Write", {
  108. status: "completed",
  109. input: { file_path: join(MEMORY_ROOT, "old.md") },
  110. output: "ok",
  111. title: "write",
  112. metadata: {},
  113. time: { start: 1, end: 2 },
  114. });
  115. const prose = userMessage("new-prose", ["new durable preference here"]);
  116. expect(
  117. evaluateMemoryExtraction(snapshot([oldWrite, prose]), createMessageId("missing-cursor")),
  118. ).toEqual({ decision: "run", messageCount: 2 });
  119. });
  120. it("counts only conversation messages, not hidden announcement records", () => {
  121. const cursor = userMessage("cursor-hidden", ["already extracted"]);
  122. const announcement = hiddenReminder("env-announcement", "environment");
  123. const prose = userMessage("prose-hidden", ["remember the durable preference"]);
  124. const marker = hiddenReminder("interrupt", "interrupt_marker");
  125. // 隐藏公告不是对话消息,不计入 "~N messages";中断标记是普通 user 文本,计入。
  126. expect(
  127. evaluateMemoryExtraction(snapshot([cursor, announcement, prose, marker]), cursor.info.id),
  128. ).toEqual({ decision: "run", messageCount: 2 });
  129. });
  130. });
  131. describe("memory extraction scheduler", () => {
  132. it("reports pending work from schedule until the running extraction settles", async () => {
  133. const run = deferred<MemoryExtractionExecutionStatus>();
  134. const scheduler = createMemoryExtractionScheduler(async () => run.promise);
  135. expect(scheduler.hasPendingWork()).toBe(false);
  136. scheduler.schedule(snapshot([userMessage("pending", ["durable preference remains useful"])]));
  137. expect(scheduler.hasPendingWork()).toBe(true);
  138. run.resolve("success");
  139. await scheduler.drain();
  140. expect(scheduler.hasPendingWork()).toBe(false);
  141. });
  142. it("keeps one running extraction and replaces pending work with only the latest snapshot", async () => {
  143. const firstRun = deferred<MemoryExtractionExecutionStatus>();
  144. const executed: string[] = [];
  145. const scheduler = createMemoryExtractionScheduler(async ({ snapshot: input }) => {
  146. const id = input.durableMessages.at(-1)?.info.id;
  147. if (id) executed.push(id);
  148. if (id === createMessageId("a")) return firstRun.promise;
  149. return "success";
  150. });
  151. scheduler.schedule(snapshot([userMessage("a", ["alpha durable preference"])]));
  152. scheduler.schedule(snapshot([userMessage("b", ["beta durable preference"])]));
  153. scheduler.schedule(snapshot([userMessage("c", ["gamma durable preference"])]));
  154. await nextTask();
  155. expect(executed).toEqual([createMessageId("a")]);
  156. firstRun.resolve("success");
  157. await scheduler.drain();
  158. expect(executed).toEqual([createMessageId("a"), createMessageId("c")]);
  159. expect(scheduler.getCursor()).toBe(createMessageId("c"));
  160. });
  161. it.each(["success", "no-op"] as const)("advances the cursor after %s", async (status) => {
  162. const scheduler = createMemoryExtractionScheduler(async () => status);
  163. scheduler.schedule(snapshot([userMessage(status, ["durable preference to save"])]));
  164. await scheduler.drain();
  165. expect(scheduler.getCursor()).toBe(createMessageId(status));
  166. });
  167. it.each(["error", "aborted"] as const)("does not advance the cursor after %s", async (status) => {
  168. const scheduler = createMemoryExtractionScheduler(async () => status);
  169. scheduler.schedule(snapshot([userMessage(status, ["durable preference to save"])]));
  170. await scheduler.drain();
  171. expect(scheduler.getCursor()).toBeUndefined();
  172. });
  173. it("advances the cursor on direct-write and no-prose skips without executing the model callback", async () => {
  174. const executed: string[] = [];
  175. const scheduler = createMemoryExtractionScheduler(async ({ snapshot: input }) => {
  176. executed.push(input.durableMessages.at(-1)!.info.id);
  177. return "success";
  178. });
  179. const directWrite = assistantToolMessage("direct-write", "Write", {
  180. status: "error",
  181. input: { file_path: join(MEMORY_ROOT, "direct") },
  182. error: "failed",
  183. time: { start: 1, end: 2 },
  184. });
  185. scheduler.schedule(snapshot([directWrite]));
  186. await scheduler.drain();
  187. expect(scheduler.getCursor()).toBe(createMessageId("direct-write"));
  188. scheduler.schedule(
  189. snapshot([
  190. directWrite,
  191. userMessage("no-prose", ["one two", "three four"], { synthetic: false }),
  192. ]),
  193. );
  194. await scheduler.drain();
  195. expect(executed).toEqual([]);
  196. expect(scheduler.getCursor()).toBe(createMessageId("no-prose"));
  197. });
  198. it("does not advance on a thrown execution error and still runs the latest pending snapshot", async () => {
  199. const firstRun = deferred<void>();
  200. const executed: string[] = [];
  201. const scheduler = createMemoryExtractionScheduler(async ({ snapshot: input }) => {
  202. const id = input.durableMessages.at(-1)!.info.id;
  203. executed.push(id);
  204. if (id === createMessageId("throws")) {
  205. await firstRun.promise;
  206. throw new Error("model failed");
  207. }
  208. return "success";
  209. });
  210. scheduler.schedule(snapshot([userMessage("throws", ["first durable preference"])]));
  211. scheduler.schedule(snapshot([userMessage("latest", ["latest durable preference"])]));
  212. firstRun.resolve();
  213. await scheduler.drain();
  214. expect(executed).toEqual([createMessageId("throws"), createMessageId("latest")]);
  215. expect(scheduler.getCursor()).toBe(createMessageId("latest"));
  216. });
  217. it("does not strand a snapshot scheduled while the running extraction completes", async () => {
  218. const firstRun = deferred<MemoryExtractionExecutionStatus>();
  219. const executed: string[] = [];
  220. const scheduler = createMemoryExtractionScheduler(async ({ snapshot: input }) => {
  221. const id = input.durableMessages.at(-1)!.info.id;
  222. executed.push(id);
  223. if (id === createMessageId("first")) return firstRun.promise;
  224. return "success";
  225. });
  226. scheduler.schedule(snapshot([userMessage("first", ["first durable preference"])]));
  227. await nextTask();
  228. const scheduleDuringCleanup = new Promise<void>((resolve) => {
  229. void firstRun.promise.then(() => {
  230. queueMicrotask(() => {
  231. queueMicrotask(() => {
  232. scheduler.schedule(
  233. snapshot([userMessage("during-cleanup", ["latest durable preference"])]),
  234. );
  235. resolve();
  236. });
  237. });
  238. });
  239. });
  240. firstRun.resolve("success");
  241. await scheduleDuringCleanup;
  242. await scheduler.drain();
  243. expect(executed).toEqual([createMessageId("first"), createMessageId("during-cleanup")]);
  244. expect(scheduler.getCursor()).toBe(createMessageId("during-cleanup"));
  245. });
  246. it("does not advance the cursor for a snapshot acquisition error and still runs latest pending", async () => {
  247. const executed: string[] = [];
  248. const scheduler = createMemoryExtractionScheduler(async ({ snapshot: input }) => {
  249. executed.push(input.boundaryMessageId);
  250. return "success";
  251. });
  252. scheduler.schedule(Promise.reject(new Error("boundary missing")));
  253. scheduler.schedule(snapshot([userMessage("latest", ["latest durable preference"])]));
  254. await scheduler.drain();
  255. expect(executed).toEqual([createMessageId("latest")]);
  256. expect(scheduler.getCursor()).toBe(createMessageId("latest"));
  257. });
  258. it("aborts the running extraction, drops pending work, and rejects later schedules on shutdown", async () => {
  259. const runningSignal = deferred<AbortSignal>();
  260. const executed: MessageId[] = [];
  261. const scheduler = createMemoryExtractionScheduler(async ({ abortSignal, snapshot: input }) => {
  262. executed.push(input.boundaryMessageId);
  263. runningSignal.resolve(abortSignal);
  264. await waitForAbort(abortSignal);
  265. return "aborted";
  266. });
  267. scheduler.schedule(snapshot([userMessage("running", ["running durable preference"])]));
  268. const signal = await runningSignal.promise;
  269. scheduler.schedule(snapshot([userMessage("pending", ["pending durable preference"])]));
  270. scheduler.shutdown();
  271. await scheduler.drain();
  272. scheduler.schedule(snapshot([userMessage("after-close", ["later durable preference"])]));
  273. await nextTask();
  274. expect(signal.aborted).toBe(true);
  275. expect(executed).toEqual([createMessageId("running")]);
  276. expect(scheduler.getCursor()).toBeUndefined();
  277. });
  278. it("stops waiting for snapshot acquisition when shutdown starts", async () => {
  279. const snapshotGate = deferred<MemoryExtractionSnapshot>();
  280. let executeCount = 0;
  281. const scheduler = createMemoryExtractionScheduler(async () => {
  282. executeCount += 1;
  283. return "success";
  284. });
  285. scheduler.schedule(snapshotGate.promise);
  286. scheduler.shutdown();
  287. await scheduler.drain();
  288. expect(executeCount).toBe(0);
  289. expect(scheduler.getCursor()).toBeUndefined();
  290. });
  291. });
  292. function snapshot(messages: MessageWithParts[]): MemoryExtractionSnapshot {
  293. return {
  294. boundaryMessageId: messages.at(-1)!.info.id,
  295. durableMessages: messages,
  296. memoryRoot: MEMORY_ROOT,
  297. workingDirectory: WORKSPACE_ROOT,
  298. workspaceRoot: WORKSPACE_ROOT,
  299. };
  300. }
  301. function userMessage(
  302. id: string,
  303. textBlocks: string[],
  304. options: { synthetic?: boolean; visibility?: "model-only" | "user-visible" } = {},
  305. ): MessageWithParts {
  306. const messageId = createMessageId(id);
  307. return {
  308. info: {
  309. id: messageId,
  310. sessionID: SESSION_ID,
  311. role: "user",
  312. time: { created: 1 },
  313. agent: "zcode-agent",
  314. model: { providerID: PROVIDER_ID, modelID: MODEL_ID },
  315. synthetic: options.synthetic,
  316. visibility: options.visibility,
  317. },
  318. parts: textBlocks.map((text, index) => ({
  319. id: createPartId(`${id}-${index}`),
  320. sessionID: SESSION_ID,
  321. messageID: messageId,
  322. type: "text",
  323. text,
  324. })),
  325. };
  326. }
  327. function hiddenReminder(id: string, source: string): MessageWithParts {
  328. const message = userMessage(id, [`<system-reminder>${source}</system-reminder>`], {
  329. synthetic: true,
  330. visibility: "model-only",
  331. });
  332. message.info.semantics = {
  333. origin: "agent_runtime",
  334. kind: "system_reminder",
  335. source,
  336. uiVisibility: "hidden",
  337. providerVisibility: "visible",
  338. transcriptVisibility: "hidden",
  339. };
  340. // 与 buildRuntimeReminderMessage 写入的形状一致:类型记在 metadata.runtimeMessage,没有顶层 source。
  341. message.info.metadata = { runtimeMessage: { source }, source, visibility: "model-only" };
  342. return message;
  343. }
  344. function assistantToolMessage(
  345. id: string,
  346. tool: "Edit" | "Write",
  347. state: ToolState,
  348. ): MessageWithParts {
  349. const messageId = createMessageId(id);
  350. const parentId = createMessageId(`${id}-parent`);
  351. const part: MessagePart = {
  352. id: createPartId(`${id}-tool`),
  353. sessionID: SESSION_ID,
  354. messageID: messageId,
  355. type: "tool",
  356. callID: `${id}-call`,
  357. tool,
  358. state,
  359. };
  360. return {
  361. info: {
  362. id: messageId,
  363. sessionID: SESSION_ID,
  364. role: "assistant",
  365. time: { created: 1, completed: 2 },
  366. parentID: parentId,
  367. agent: "zcode-agent",
  368. cost: 0,
  369. mode: "build",
  370. modelID: MODEL_ID,
  371. path: { cwd: WORKSPACE_ROOT, root: WORKSPACE_ROOT },
  372. providerID: PROVIDER_ID,
  373. tokens: {
  374. cache: { read: 0, write: 0 },
  375. input: 0,
  376. output: 0,
  377. reasoning: 0,
  378. },
  379. },
  380. parts: [part],
  381. };
  382. }
  383. function deferred<T>() {
  384. let resolve!: (value: T | PromiseLike<T>) => void;
  385. const promise = new Promise<T>((settle) => {
  386. resolve = settle;
  387. });
  388. return { promise, resolve };
  389. }
  390. async function nextTask(): Promise<void> {
  391. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  392. }
  393. async function waitForAbort(signal: AbortSignal): Promise<void> {
  394. if (signal.aborted) return;
  395. await new Promise<void>((resolve) => {
  396. signal.addEventListener("abort", () => resolve(), { once: true });
  397. });
  398. }