memory-extraction.test.ts 15 KB

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