memory-extraction.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. });
  121. describe("memory extraction scheduler", () => {
  122. it("reports pending work from schedule until the running extraction settles", async () => {
  123. const run = deferred<MemoryExtractionExecutionStatus>();
  124. const scheduler = createMemoryExtractionScheduler(async () => run.promise);
  125. expect(scheduler.hasPendingWork()).toBe(false);
  126. scheduler.schedule(snapshot([userMessage("pending", ["durable preference remains useful"])]));
  127. expect(scheduler.hasPendingWork()).toBe(true);
  128. run.resolve("success");
  129. await scheduler.drain();
  130. expect(scheduler.hasPendingWork()).toBe(false);
  131. });
  132. it("keeps one running extraction and replaces pending work with only the latest snapshot", async () => {
  133. const firstRun = deferred<MemoryExtractionExecutionStatus>();
  134. const executed: string[] = [];
  135. const scheduler = createMemoryExtractionScheduler(async ({ snapshot: input }) => {
  136. const id = input.durableMessages.at(-1)?.info.id;
  137. if (id) executed.push(id);
  138. if (id === createMessageId("a")) return firstRun.promise;
  139. return "success";
  140. });
  141. scheduler.schedule(snapshot([userMessage("a", ["alpha durable preference"])]));
  142. scheduler.schedule(snapshot([userMessage("b", ["beta durable preference"])]));
  143. scheduler.schedule(snapshot([userMessage("c", ["gamma durable preference"])]));
  144. await nextTask();
  145. expect(executed).toEqual([createMessageId("a")]);
  146. firstRun.resolve("success");
  147. await scheduler.drain();
  148. expect(executed).toEqual([createMessageId("a"), createMessageId("c")]);
  149. expect(scheduler.getCursor()).toBe(createMessageId("c"));
  150. });
  151. it.each(["success", "no-op"] as const)("advances the cursor after %s", async (status) => {
  152. const scheduler = createMemoryExtractionScheduler(async () => status);
  153. scheduler.schedule(snapshot([userMessage(status, ["durable preference to save"])]));
  154. await scheduler.drain();
  155. expect(scheduler.getCursor()).toBe(createMessageId(status));
  156. });
  157. it.each(["error", "aborted"] as const)("does not advance the cursor after %s", async (status) => {
  158. const scheduler = createMemoryExtractionScheduler(async () => status);
  159. scheduler.schedule(snapshot([userMessage(status, ["durable preference to save"])]));
  160. await scheduler.drain();
  161. expect(scheduler.getCursor()).toBeUndefined();
  162. });
  163. it("advances the cursor on direct-write and no-prose skips without executing the model callback", async () => {
  164. const executed: string[] = [];
  165. const scheduler = createMemoryExtractionScheduler(async ({ snapshot: input }) => {
  166. executed.push(input.durableMessages.at(-1)!.info.id);
  167. return "success";
  168. });
  169. const directWrite = assistantToolMessage("direct-write", "Write", {
  170. status: "error",
  171. input: { file_path: join(MEMORY_ROOT, "direct") },
  172. error: "failed",
  173. time: { start: 1, end: 2 },
  174. });
  175. scheduler.schedule(snapshot([directWrite]));
  176. await scheduler.drain();
  177. expect(scheduler.getCursor()).toBe(createMessageId("direct-write"));
  178. scheduler.schedule(
  179. snapshot([
  180. directWrite,
  181. userMessage("no-prose", ["one two", "three four"], { synthetic: false }),
  182. ]),
  183. );
  184. await scheduler.drain();
  185. expect(executed).toEqual([]);
  186. expect(scheduler.getCursor()).toBe(createMessageId("no-prose"));
  187. });
  188. it("does not advance on a thrown execution error and still runs the latest pending snapshot", async () => {
  189. const firstRun = deferred<void>();
  190. const executed: string[] = [];
  191. const scheduler = createMemoryExtractionScheduler(async ({ snapshot: input }) => {
  192. const id = input.durableMessages.at(-1)!.info.id;
  193. executed.push(id);
  194. if (id === createMessageId("throws")) {
  195. await firstRun.promise;
  196. throw new Error("model failed");
  197. }
  198. return "success";
  199. });
  200. scheduler.schedule(snapshot([userMessage("throws", ["first durable preference"])]));
  201. scheduler.schedule(snapshot([userMessage("latest", ["latest durable preference"])]));
  202. firstRun.resolve();
  203. await scheduler.drain();
  204. expect(executed).toEqual([createMessageId("throws"), createMessageId("latest")]);
  205. expect(scheduler.getCursor()).toBe(createMessageId("latest"));
  206. });
  207. it("does not strand a snapshot scheduled while the running extraction completes", async () => {
  208. const firstRun = deferred<MemoryExtractionExecutionStatus>();
  209. const executed: string[] = [];
  210. const scheduler = createMemoryExtractionScheduler(async ({ snapshot: input }) => {
  211. const id = input.durableMessages.at(-1)!.info.id;
  212. executed.push(id);
  213. if (id === createMessageId("first")) return firstRun.promise;
  214. return "success";
  215. });
  216. scheduler.schedule(snapshot([userMessage("first", ["first durable preference"])]));
  217. await nextTask();
  218. const scheduleDuringCleanup = new Promise<void>((resolve) => {
  219. void firstRun.promise.then(() => {
  220. queueMicrotask(() => {
  221. queueMicrotask(() => {
  222. scheduler.schedule(
  223. snapshot([userMessage("during-cleanup", ["latest durable preference"])]),
  224. );
  225. resolve();
  226. });
  227. });
  228. });
  229. });
  230. firstRun.resolve("success");
  231. await scheduleDuringCleanup;
  232. await scheduler.drain();
  233. expect(executed).toEqual([createMessageId("first"), createMessageId("during-cleanup")]);
  234. expect(scheduler.getCursor()).toBe(createMessageId("during-cleanup"));
  235. });
  236. it("does not advance the cursor for a snapshot acquisition error and still runs latest pending", async () => {
  237. const executed: string[] = [];
  238. const scheduler = createMemoryExtractionScheduler(async ({ snapshot: input }) => {
  239. executed.push(input.boundaryMessageId);
  240. return "success";
  241. });
  242. scheduler.schedule(Promise.reject(new Error("boundary missing")));
  243. scheduler.schedule(snapshot([userMessage("latest", ["latest durable preference"])]));
  244. await scheduler.drain();
  245. expect(executed).toEqual([createMessageId("latest")]);
  246. expect(scheduler.getCursor()).toBe(createMessageId("latest"));
  247. });
  248. it("aborts the running extraction, drops pending work, and rejects later schedules on shutdown", async () => {
  249. const runningSignal = deferred<AbortSignal>();
  250. const executed: MessageId[] = [];
  251. const scheduler = createMemoryExtractionScheduler(async ({ abortSignal, snapshot: input }) => {
  252. executed.push(input.boundaryMessageId);
  253. runningSignal.resolve(abortSignal);
  254. await waitForAbort(abortSignal);
  255. return "aborted";
  256. });
  257. scheduler.schedule(snapshot([userMessage("running", ["running durable preference"])]));
  258. const signal = await runningSignal.promise;
  259. scheduler.schedule(snapshot([userMessage("pending", ["pending durable preference"])]));
  260. scheduler.shutdown();
  261. await scheduler.drain();
  262. scheduler.schedule(snapshot([userMessage("after-close", ["later durable preference"])]));
  263. await nextTask();
  264. expect(signal.aborted).toBe(true);
  265. expect(executed).toEqual([createMessageId("running")]);
  266. expect(scheduler.getCursor()).toBeUndefined();
  267. });
  268. it("stops waiting for snapshot acquisition when shutdown starts", async () => {
  269. const snapshotGate = deferred<MemoryExtractionSnapshot>();
  270. let executeCount = 0;
  271. const scheduler = createMemoryExtractionScheduler(async () => {
  272. executeCount += 1;
  273. return "success";
  274. });
  275. scheduler.schedule(snapshotGate.promise);
  276. scheduler.shutdown();
  277. await scheduler.drain();
  278. expect(executeCount).toBe(0);
  279. expect(scheduler.getCursor()).toBeUndefined();
  280. });
  281. });
  282. function snapshot(messages: MessageWithParts[]): MemoryExtractionSnapshot {
  283. return {
  284. boundaryMessageId: messages.at(-1)!.info.id,
  285. durableMessages: messages,
  286. memoryRoot: MEMORY_ROOT,
  287. workingDirectory: WORKSPACE_ROOT,
  288. workspaceRoot: WORKSPACE_ROOT,
  289. };
  290. }
  291. function userMessage(
  292. id: string,
  293. textBlocks: string[],
  294. options: { synthetic?: boolean; visibility?: "model-only" | "user-visible" } = {},
  295. ): MessageWithParts {
  296. const messageId = createMessageId(id);
  297. return {
  298. info: {
  299. id: messageId,
  300. sessionID: SESSION_ID,
  301. role: "user",
  302. time: { created: 1 },
  303. agent: "zcode-agent",
  304. model: { providerID: PROVIDER_ID, modelID: MODEL_ID },
  305. synthetic: options.synthetic,
  306. visibility: options.visibility,
  307. },
  308. parts: textBlocks.map((text, index) => ({
  309. id: createPartId(`${id}-${index}`),
  310. sessionID: SESSION_ID,
  311. messageID: messageId,
  312. type: "text",
  313. text,
  314. })),
  315. };
  316. }
  317. function assistantToolMessage(
  318. id: string,
  319. tool: "Edit" | "Write",
  320. state: ToolState,
  321. ): MessageWithParts {
  322. const messageId = createMessageId(id);
  323. const parentId = createMessageId(`${id}-parent`);
  324. const part: MessagePart = {
  325. id: createPartId(`${id}-tool`),
  326. sessionID: SESSION_ID,
  327. messageID: messageId,
  328. type: "tool",
  329. callID: `${id}-call`,
  330. tool,
  331. state,
  332. };
  333. return {
  334. info: {
  335. id: messageId,
  336. sessionID: SESSION_ID,
  337. role: "assistant",
  338. time: { created: 1, completed: 2 },
  339. parentID: parentId,
  340. agent: "zcode-agent",
  341. cost: 0,
  342. mode: "build",
  343. modelID: MODEL_ID,
  344. path: { cwd: WORKSPACE_ROOT, root: WORKSPACE_ROOT },
  345. providerID: PROVIDER_ID,
  346. tokens: {
  347. cache: { read: 0, write: 0 },
  348. input: 0,
  349. output: 0,
  350. reasoning: 0,
  351. },
  352. },
  353. parts: [part],
  354. };
  355. }
  356. function deferred<T>() {
  357. let resolve!: (value: T | PromiseLike<T>) => void;
  358. const promise = new Promise<T>((settle) => {
  359. resolve = settle;
  360. });
  361. return { promise, resolve };
  362. }
  363. async function nextTask(): Promise<void> {
  364. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  365. }
  366. async function waitForAbort(signal: AbortSignal): Promise<void> {
  367. if (signal.aborted) return;
  368. await new Promise<void>((resolve) => {
  369. signal.addEventListener("abort", () => resolve(), { once: true });
  370. });
  371. }