memory-recall.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. import { readFileSync } from "node:fs";
  2. import { dirname, join } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. import {
  5. createFileSystemError,
  6. createModelId,
  7. createModelProviderId,
  8. type FileSystemListDirectoryEntry,
  9. type FileSystemPort,
  10. type Model,
  11. } from "@zcode/contracts";
  12. import { describe, expect, it } from "vitest";
  13. import {
  14. MEMORY_RECALL_SESSION_CHARACTER_LIMIT,
  15. buildMemorySelectorRequest,
  16. canStartMemoryRecall,
  17. createMemoryRecallState,
  18. filterMemorySelections,
  19. findLatestMemoryRecallQuery,
  20. formatMemoryManifest,
  21. formatRelevantMemoryAttachment,
  22. getMemoryRecallManifest,
  23. isMemoryRecallQueryEligible,
  24. readRecalledMemories,
  25. recordRecalledMemories,
  26. runMemorySelector,
  27. scanMemoryManifest,
  28. type MemoryManifestEntry,
  29. } from "../src/memory/recall/index.js";
  30. import { createReadFileStateKey } from "../src/tool/read-file-state.js";
  31. import type { ReadFileStateMap } from "../src/tool/types.js";
  32. import { createTestModelFormatProperties } from "./test-runtime-model.js";
  33. const TEST_DIR = dirname(fileURLToPath(import.meta.url));
  34. const MEMORY_ROOT = "/storage/memory";
  35. const DAY_MS = 86_400_000;
  36. describe("Semantic Memory manifest", () => {
  37. it("recursively scans lowercase Markdown, keeps malformed frontmatter metadata-less, and does not follow directory symlinks", async () => {
  38. const fileSystem = new RecallFileSystem({
  39. [`${MEMORY_ROOT}/MEMORY.md`]: file("index", 90),
  40. [`${MEMORY_ROOT}/UPPER.MD`]: file("uppercase", 80),
  41. [`${MEMORY_ROOT}/broken.md`]: file("---\ndescription: [\n---\nbody", 70),
  42. [`${MEMORY_ROOT}/incomplete.md`]: file("---\ndescription: unfinished\nbody", 65),
  43. [`${MEMORY_ROOT}/linked.md`]: file("linked body", 60, "symlink"),
  44. [`${MEMORY_ROOT}/nested/project-policy.md`]: file(
  45. [
  46. "---",
  47. "name: project-policy",
  48. "description: Keep the provider request stable.",
  49. "metadata:",
  50. " type: project",
  51. "---",
  52. "",
  53. "project body",
  54. ].join("\n"),
  55. 50,
  56. ),
  57. [`${MEMORY_ROOT}/plain.md`]: file("plain body", 40),
  58. [`${MEMORY_ROOT}/linked-dir`]: directory(30, "symlink"),
  59. });
  60. const manifest = await scanMemoryManifest({
  61. fileSystem,
  62. rootDir: MEMORY_ROOT,
  63. });
  64. expect(manifest.map((entry) => entry.filename)).toEqual([
  65. "broken.md",
  66. "incomplete.md",
  67. "linked.md",
  68. "nested/project-policy.md",
  69. "plain.md",
  70. ]);
  71. expect(manifest[0]).toEqual({
  72. filePath: `${MEMORY_ROOT}/broken.md`,
  73. filename: "broken.md",
  74. mtimeMs: 70,
  75. });
  76. expect(manifest[1]).toEqual({
  77. filePath: `${MEMORY_ROOT}/incomplete.md`,
  78. filename: "incomplete.md",
  79. mtimeMs: 65,
  80. });
  81. expect(manifest[3]).toMatchObject({
  82. description: "Keep the provider request stable.",
  83. type: "project",
  84. });
  85. expect(fileSystem.listRequests).not.toContain(`${MEMORY_ROOT}/linked-dir`);
  86. expect(fileSystem.rangeRequests).toEqual(
  87. expect.arrayContaining([
  88. { limitLines: 30, path: `${MEMORY_ROOT}/linked.md` },
  89. { limitLines: 30, path: `${MEMORY_ROOT}/nested/project-policy.md` },
  90. { limitLines: 30, path: `${MEMORY_ROOT}/plain.md` },
  91. ]),
  92. );
  93. });
  94. it("sorts by descending mtime and caps the manifest at 200 files", async () => {
  95. const files = Object.fromEntries(
  96. Array.from({ length: 205 }, (_, index) => [
  97. `${MEMORY_ROOT}/memory-${String(index).padStart(3, "0")}.md`,
  98. file(`memory ${index}`, index),
  99. ]),
  100. );
  101. const manifest = await scanMemoryManifest({
  102. fileSystem: new RecallFileSystem(files),
  103. rootDir: MEMORY_ROOT,
  104. });
  105. expect(manifest).toHaveLength(200);
  106. expect(manifest[0]?.mtimeMs).toBe(204);
  107. expect(manifest.at(-1)?.mtimeMs).toBe(5);
  108. });
  109. it("keeps a non-empty manifest sticky but rescans an empty manifest", async () => {
  110. const state = createMemoryRecallState();
  111. const fileSystem = new RecallFileSystem({
  112. [`${MEMORY_ROOT}/first.md`]: file("first", 1),
  113. });
  114. const first = await getMemoryRecallManifest({ fileSystem, rootDir: MEMORY_ROOT, state });
  115. fileSystem.files[`${MEMORY_ROOT}/second.md`] = file("second", 2);
  116. const sticky = await getMemoryRecallManifest({ fileSystem, rootDir: MEMORY_ROOT, state });
  117. expect(sticky).toBe(first);
  118. expect(sticky.map((entry) => entry.filename)).toEqual(["first.md"]);
  119. const emptyState = createMemoryRecallState();
  120. const initiallyEmpty = new RecallFileSystem({});
  121. expect(
  122. await getMemoryRecallManifest({
  123. fileSystem: initiallyEmpty,
  124. rootDir: MEMORY_ROOT,
  125. state: emptyState,
  126. }),
  127. ).toEqual([]);
  128. initiallyEmpty.files[`${MEMORY_ROOT}/later.md`] = file("later", 3);
  129. expect(
  130. await getMemoryRecallManifest({
  131. fileSystem: initiallyEmpty,
  132. rootDir: MEMORY_ROOT,
  133. state: emptyState,
  134. }),
  135. ).toHaveLength(1);
  136. expect(initiallyEmpty.listRequests.filter((path) => path === MEMORY_ROOT)).toHaveLength(2);
  137. });
  138. it("does not cache a partial manifest when the scan is aborted", async () => {
  139. const abortController = new AbortController();
  140. const state = createMemoryRecallState();
  141. const fileSystem = new AbortDuringManifestFileSystem(
  142. {
  143. [`${MEMORY_ROOT}/first.md`]: file("first", 2),
  144. [`${MEMORY_ROOT}/second.md`]: file("second", 1),
  145. },
  146. abortController,
  147. );
  148. await expect(
  149. getMemoryRecallManifest({
  150. fileSystem,
  151. rootDir: MEMORY_ROOT,
  152. signal: abortController.signal,
  153. state,
  154. }),
  155. ).resolves.toEqual([]);
  156. expect(state.manifest).toBeUndefined();
  157. expect(state.selectorMessages).toBeUndefined();
  158. });
  159. });
  160. describe("Semantic Memory selector", () => {
  161. it("builds the frozen Lite selector request with sticky conversation and structured output", () => {
  162. const fixture = JSON.parse(
  163. readFileSync(join(TEST_DIR, "fixtures/memory/selector-request.json"), "utf8"),
  164. ) as SelectorFixture;
  165. const timestamp = "2026-07-16T00:00:00.000Z";
  166. const manifest = [
  167. manifestEntry("database-test-policy.md", {
  168. description: "Database tests must use the real database rather than mocks.",
  169. mtimeMs: Date.parse(timestamp),
  170. type: "feedback",
  171. }),
  172. ];
  173. const state = createMemoryRecallState();
  174. state.manifest = manifest;
  175. state.selectorMessages = [
  176. {
  177. role: "user",
  178. content: `Available memories:\n${formatMemoryManifest(manifest)}`,
  179. cacheControl: { type: "ephemeral" },
  180. },
  181. ];
  182. const request = buildMemorySelectorRequest({
  183. query: "What database testing approach should I use for this repository?",
  184. state,
  185. });
  186. expect(request.options).toBeUndefined();
  187. expect(request.responseJsonSchema).toEqual(fixture.output_config.format.schema);
  188. expect(request.messages[0]).toEqual({
  189. role: "system",
  190. content: fixture.system[0]?.text,
  191. cacheControl: { type: "ephemeral" },
  192. });
  193. expect(request.messages.slice(1)).toEqual(
  194. fixture.messages.map((message) => ({
  195. role: message.role,
  196. content: message.content[0]?.text.replace("<TIMESTAMP>", timestamp),
  197. cacheControl: { type: "ephemeral" },
  198. })),
  199. );
  200. });
  201. it("returns an empty selection for errors or invalid JSON and only extends conversation after a valid response", async () => {
  202. const state = selectorState([manifestEntry("known.md")]);
  203. const model = textModel('{"selected_memories":["known.md","known.md"]}');
  204. const valid = await runMemorySelector({
  205. model,
  206. query: "show known memory",
  207. state,
  208. });
  209. expect(valid).toEqual({ selectedKnowledgeIds: [], selectedMemories: ["known.md", "known.md"] });
  210. expect(state.selectorMessages).toHaveLength(3);
  211. const invalidState = selectorState([manifestEntry("known.md")]);
  212. expect(
  213. await runMemorySelector({
  214. model: textModel("not json"),
  215. query: "show known memory",
  216. state: invalidState,
  217. }),
  218. ).toEqual({ selectedKnowledgeIds: [], selectedMemories: [] });
  219. expect(invalidState.selectorMessages).toHaveLength(1);
  220. expect(
  221. await runMemorySelector({
  222. model: throwingModel(),
  223. query: "show known memory",
  224. state: selectorState([manifestEntry("known.md")]),
  225. }),
  226. ).toEqual({ selectedKnowledgeIds: [], selectedMemories: [] });
  227. });
  228. it("requests the lowest reasoning level only for the selector without changing Model options", async () => {
  229. let capturedOptions: Model["options"] | undefined;
  230. const baseModel = testModel({
  231. async generateText(request) {
  232. capturedOptions = request.options;
  233. return {
  234. finishReason: "stop",
  235. model: testModelSelection(),
  236. text: '{"selected_memories":[]}',
  237. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  238. };
  239. },
  240. async *streamText() {},
  241. });
  242. const model: Model = {
  243. ...baseModel,
  244. optionSpecs: {
  245. ...baseModel.optionSpecs,
  246. reasoningLevel: {
  247. values: ["low", "high"],
  248. },
  249. },
  250. options: { ...baseModel.options, reasoningLevel: "high" },
  251. };
  252. await runMemorySelector({
  253. model,
  254. query: "show known memory",
  255. state: selectorState([manifestEntry("known.md")]),
  256. });
  257. expect(model.options).toEqual({ maxOutputTokens: 32_000, reasoningLevel: "high" });
  258. expect(capturedOptions).toEqual({
  259. maxOutputTokens: 5_000,
  260. reasoningLevel: "low",
  261. });
  262. });
  263. it("uses the disabled baseline for a selector Model without reasoning", async () => {
  264. let capturedOptions: Model["options"] | undefined;
  265. const model = testModel({
  266. async generateText(request) {
  267. capturedOptions = request.options;
  268. return {
  269. finishReason: "stop",
  270. model: testModelSelection(),
  271. text: '{"selected_memories":[]}',
  272. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  273. };
  274. },
  275. async *streamText() {},
  276. });
  277. await runMemorySelector({
  278. model,
  279. query: "show known memory",
  280. state: selectorState([manifestEntry("known.md")]),
  281. });
  282. expect(model.options).toEqual({ maxOutputTokens: 32_000, reasoningLevel: "disabled" });
  283. expect(capturedOptions).toEqual({
  284. maxOutputTokens: 5_000,
  285. reasoningLevel: "disabled",
  286. });
  287. });
  288. it("discards a valid selector response that arrives after abort", async () => {
  289. const abortController = new AbortController();
  290. const state = selectorState([manifestEntry("known.md")]);
  291. const result = await runMemorySelector({
  292. abortSignal: abortController.signal,
  293. model: testModel({
  294. async generateText(_request) {
  295. abortController.abort();
  296. return {
  297. finishReason: "stop",
  298. model: testModelSelection(),
  299. text: '{"selected_memories":["known.md"]}',
  300. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  301. };
  302. },
  303. async *streamText() {},
  304. }),
  305. query: "show known memory",
  306. state,
  307. });
  308. expect(result).toEqual({ selectedKnowledgeIds: [], selectedMemories: [] });
  309. expect(state.selectorMessages).toHaveLength(1);
  310. });
  311. it("does not call the selector when every sticky manifest path was already recalled", async () => {
  312. const state = selectorState([manifestEntry("known.md")]);
  313. state.recalledPaths.add(`${MEMORY_ROOT}/known.md`);
  314. let callCount = 0;
  315. const model = textModel('{"selected_memories":[]}', () => callCount++);
  316. expect(
  317. await runMemorySelector({
  318. model,
  319. query: "show known memory",
  320. state,
  321. }),
  322. ).toEqual({ selectedKnowledgeIds: [], selectedMemories: [] });
  323. expect(callCount).toBe(0);
  324. expect(state.selectorMessages).toHaveLength(1);
  325. const emptyState = createMemoryRecallState();
  326. await runMemorySelector({
  327. model,
  328. query: "show known memory",
  329. state: emptyState,
  330. });
  331. expect(callCount).toBe(0);
  332. });
  333. it("uses the latest non-meta user text and requires whitespace after trimming", () => {
  334. const query = findLatestMemoryRecallQuery([
  335. { message: { role: "user", content: "older query" }, metadata: { source: "real_user" } },
  336. { kind: "attachment", content: "internal", metadata: { source: "relevant_memory" } },
  337. {
  338. message: {
  339. role: "user",
  340. content: [{ type: "text", text: "latest query with spaces" }],
  341. },
  342. metadata: { source: "real_user" },
  343. },
  344. ]);
  345. expect(query).toBe("latest query with spaces");
  346. expect(isMemoryRecallQueryEligible(query)).toBe(true);
  347. expect(isMemoryRecallQueryEligible("singleword")).toBe(false);
  348. expect(isMemoryRecallQueryEligible("\t singleword \n")).toBe(false);
  349. expect(isMemoryRecallQueryEligible("中文问题")).toBe(false);
  350. });
  351. it("treats explicit real_user metadata as authoritative over literal reminder text", () => {
  352. expect(
  353. findLatestMemoryRecallQuery([
  354. {
  355. message: { role: "user", content: "older real query" },
  356. metadata: { source: "real_user" },
  357. },
  358. {
  359. message: {
  360. role: "user",
  361. content: "<system-reminder>\nliteral user text\n</system-reminder>",
  362. },
  363. metadata: { source: "real_user" },
  364. },
  365. ]),
  366. ).toBe("<system-reminder>\nliteral user text\n</system-reminder>");
  367. });
  368. it("uses the reminder-text heuristic only for metadata-less legacy messages", () => {
  369. expect(
  370. findLatestMemoryRecallQuery([
  371. {
  372. message: { role: "user", content: "older real query" },
  373. metadata: { source: "real_user" },
  374. },
  375. { message: { role: "user", content: "<system-reminder>legacy meta</system-reminder>" } },
  376. ]),
  377. ).toBe("older real query");
  378. });
  379. });
  380. describe("Semantic Memory selection and content", () => {
  381. it("preserves order and duplicates while filtering unknown, previously read, and recalled paths before the five-item cap", () => {
  382. const manifest = Array.from({ length: 8 }, (_, index) => manifestEntry(`memory-${index}.md`));
  383. const readFileState: ReadFileStateMap = new Map();
  384. const readEntry = manifest[1]!;
  385. readFileState.set(createReadFileStateKey(readEntry.filePath, 1, undefined), {
  386. content: "read",
  387. isPartialView: false,
  388. path: readEntry.filePath,
  389. readAt: new Date(),
  390. });
  391. const selected = filterMemorySelections({
  392. manifest,
  393. readFileState,
  394. recalledPaths: new Set([manifest[2]!.filePath]),
  395. selectedFilenames: [
  396. "unknown.md",
  397. "memory-1.md",
  398. "memory-2.md",
  399. "memory-0.md",
  400. "memory-0.md",
  401. "memory-3.md",
  402. "memory-4.md",
  403. "memory-5.md",
  404. "memory-6.md",
  405. ],
  406. });
  407. expect(selected.map((entry) => entry.filename)).toEqual([
  408. "memory-0.md",
  409. "memory-0.md",
  410. "memory-3.md",
  411. "memory-4.md",
  412. "memory-5.md",
  413. ]);
  414. });
  415. it("normalizes BOM and CRLF while preserving the memory frontmatter and body", async () => {
  416. const path = `${MEMORY_ROOT}/normalized.md`;
  417. const content = "\uFEFF---\r\nname: normalized\r\n---\r\n\r\nbody\r\n";
  418. const recalled = await readRecalledMemories({
  419. entries: [manifestEntry("normalized.md")],
  420. fileSystem: new RecallFileSystem({ [path]: file(content, 1) }),
  421. nowMs: 1,
  422. });
  423. expect(recalled[0]?.content).toBe("---\nname: normalized\n---\n\nbody\n");
  424. expect(recalled[0]).toMatchObject({
  425. limit: undefined,
  426. revisionId: "revision:/storage/memory/normalized.md:1",
  427. sizeBytes: Buffer.byteLength(content, "utf8"),
  428. });
  429. });
  430. it("keeps only complete lines and uses the byte truncation reason when both limits apply", async () => {
  431. const path = `${MEMORY_ROOT}/large.md`;
  432. const lines = Array.from(
  433. { length: 220 },
  434. (_, index) => `${String(index).padStart(3, "0")}:${"x".repeat(24)}`,
  435. );
  436. const recalled = await readRecalledMemories({
  437. entries: [manifestEntry("large.md")],
  438. fileSystem: new RecallFileSystem({ [path]: file(`${lines.join("\n")}\n`, 1) }),
  439. nowMs: 1,
  440. });
  441. expect(recalled[0]?.content).toContain(
  442. `> This memory file was truncated (4096 byte limit). Use the Read tool to view the complete file at: ${path}`,
  443. );
  444. expect(recalled[0]?.content).not.toContain("first 200 lines");
  445. const retained = recalled[0]!.content.split("\n\n> This memory file was truncated")[0]!;
  446. expect(Buffer.byteLength(retained, "utf8")).toBeLessThanOrEqual(4096);
  447. expect(lines).toContain(retained.split("\n").at(-1));
  448. expect(recalled[0]?.limit).toBe(retained.split("\n").length);
  449. });
  450. it("uses the exact line truncation suffix when only the 200-line limit applies", async () => {
  451. const path = `${MEMORY_ROOT}/many-lines.md`;
  452. const lines = Array.from({ length: 201 }, (_, index) => String(index));
  453. const recalled = await readRecalledMemories({
  454. entries: [manifestEntry("many-lines.md")],
  455. fileSystem: new RecallFileSystem({ [path]: file(lines.join("\n"), 1) }),
  456. nowMs: 1,
  457. });
  458. expect(
  459. recalled[0]?.content.endsWith(
  460. `> This memory file was truncated (first 200 lines). Use the Read tool to view the complete file at: ${path}`,
  461. ),
  462. ).toBe(true);
  463. expect(recalled[0]?.limit).toBe(200);
  464. });
  465. it("renders the frozen relevant-memory MCS body and stale warning", async () => {
  466. const fixture = readFileSync(join(TEST_DIR, "fixtures/memory/recalled-memory.md"), "utf8");
  467. const path = `${MEMORY_ROOT}/database-test-policy.md`;
  468. const content = `${[
  469. "---",
  470. "name: database-test-policy",
  471. "description: Database tests must use the real database rather than mocks.",
  472. "metadata:",
  473. " type: feedback",
  474. "---",
  475. "",
  476. "Use the real database for database tests; mocked database tests are not trusted.",
  477. "",
  478. "**Why:** A prior mocked test passed while production migration behavior failed.",
  479. "",
  480. "**How to apply:** Use the real database for database integration tests.",
  481. ].join("\n")}\n`;
  482. const recalled = await readRecalledMemories({
  483. entries: [manifestEntry("database-test-policy.md", { mtimeMs: 100 })],
  484. fileSystem: new RecallFileSystem({ [path]: file(content, 100) }),
  485. nowMs: 100,
  486. });
  487. expect(formatRelevantMemoryAttachment(recalled)).toBe(
  488. fixture.replaceAll("<MEMORY_ROOT>", MEMORY_ROOT),
  489. );
  490. const stale = await readRecalledMemories({
  491. entries: [manifestEntry("database-test-policy.md", { mtimeMs: 100 })],
  492. fileSystem: new RecallFileSystem({ [path]: file(content, 100) }),
  493. nowMs: 100 + 3 * DAY_MS,
  494. });
  495. expect(stale[0]?.header).toBe(
  496. `This memory is 3 days old. Memories are point-in-time observations, not live state — claims about code behavior or file:line citations may be outdated. Verify against current code before asserting as fact.\n\nMemory: ${path}:`,
  497. );
  498. const notYetStale = await readRecalledMemories({
  499. entries: [manifestEntry("database-test-policy.md", { mtimeMs: 100 })],
  500. fileSystem: new RecallFileSystem({ [path]: file(content, 100) }),
  501. nowMs: 100 + 2 * DAY_MS - 1,
  502. });
  503. expect(notYetStale[0]?.header).toBe(`Memory: ${path}:`);
  504. const oneDayOld = await readRecalledMemories({
  505. entries: [manifestEntry("database-test-policy.md", { mtimeMs: 100 })],
  506. fileSystem: new RecallFileSystem({ [path]: file(content, 100) }),
  507. nowMs: 100 + DAY_MS + 1,
  508. });
  509. expect(oneDayOld[0]?.header).toBe(`Memory: ${path}:`);
  510. const staleAtTwoDays = await readRecalledMemories({
  511. entries: [manifestEntry("database-test-policy.md", { mtimeMs: 100 })],
  512. fileSystem: new RecallFileSystem({ [path]: file(content, 100) }),
  513. nowMs: 100 + 2 * DAY_MS,
  514. });
  515. expect(staleAtTwoDays[0]?.header).toContain("This memory is 2 days old.");
  516. });
  517. it("tracks recalled paths and JavaScript character count at the 61,440 limit", () => {
  518. const state = createMemoryRecallState();
  519. expect(canStartMemoryRecall(state)).toBe(true);
  520. recordRecalledMemories(state, [
  521. {
  522. content: "🙂".repeat(MEMORY_RECALL_SESSION_CHARACTER_LIMIT / 2),
  523. filePath: `${MEMORY_ROOT}/limit.md`,
  524. header: "Memory",
  525. limit: undefined,
  526. mtimeMs: 1,
  527. sizeBytes: MEMORY_RECALL_SESSION_CHARACTER_LIMIT * 2,
  528. },
  529. ]);
  530. expect(state.recalledContentCharacters).toBe(MEMORY_RECALL_SESSION_CHARACTER_LIMIT);
  531. expect(canStartMemoryRecall(state)).toBe(false);
  532. expect(state.recalledPaths).toEqual(new Set([`${MEMORY_ROOT}/limit.md`]));
  533. });
  534. });
  535. interface TestNode {
  536. content?: string;
  537. kind: "file" | "directory";
  538. listedKind?: "file" | "directory" | "symlink";
  539. mtimeMs: number;
  540. }
  541. function file(
  542. content: string,
  543. mtimeMs: number,
  544. listedKind: TestNode["listedKind"] = "file",
  545. ): TestNode {
  546. return { content, kind: "file", listedKind, mtimeMs };
  547. }
  548. function directory(mtimeMs: number, listedKind: TestNode["listedKind"] = "directory"): TestNode {
  549. return { kind: "directory", listedKind, mtimeMs };
  550. }
  551. class RecallFileSystem implements FileSystemPort {
  552. readonly listRequests: string[] = [];
  553. readonly rangeRequests: Array<{ limitLines?: number; path: string }> = [];
  554. constructor(readonly files: Record<string, TestNode>) {}
  555. async createDirectory(request: { path: string }) {
  556. return { path: request.path };
  557. }
  558. async stat(request: { path: string }) {
  559. const node = this.node(request.path);
  560. return {
  561. kind: node.kind,
  562. mtimeMs: node.mtimeMs,
  563. path: request.path,
  564. sizeBytes: Buffer.byteLength(node.content ?? "", "utf8"),
  565. };
  566. }
  567. async readTextFile(request: { path: string; encoding?: BufferEncoding; maxBytes?: number }) {
  568. const node = this.node(request.path);
  569. if (node.kind !== "file") throw notFile(request.path);
  570. const source = Buffer.from(node.content ?? "", "utf8");
  571. const returned =
  572. request.maxBytes !== undefined && source.byteLength > request.maxBytes
  573. ? source.subarray(0, request.maxBytes)
  574. : source;
  575. const raw = returned.toString("utf8");
  576. return {
  577. bytesRead: returned.byteLength,
  578. content: raw.replace(/\r\n/gu, "\n"),
  579. encoding: request.encoding ?? "utf8",
  580. path: request.path,
  581. sizeBytes: source.byteLength,
  582. truncated: returned.byteLength < source.byteLength,
  583. };
  584. }
  585. async readBinaryFile(request: { path: string; maxBytes?: number }) {
  586. const node = this.node(request.path);
  587. const content = Buffer.from(node.content ?? "", "utf8");
  588. if (request.maxBytes !== undefined && content.byteLength > request.maxBytes) {
  589. throw createFileSystemError({
  590. code: "too_large",
  591. message: "too large",
  592. path: request.path,
  593. });
  594. }
  595. return {
  596. bytesRead: content.byteLength,
  597. content,
  598. path: request.path,
  599. sizeBytes: content.byteLength,
  600. };
  601. }
  602. async readTextFileRange(request: {
  603. path: string;
  604. encoding?: BufferEncoding;
  605. offsetLine?: number;
  606. limitLines?: number;
  607. }) {
  608. this.rangeRequests.push({ limitLines: request.limitLines, path: request.path });
  609. const node = this.node(request.path);
  610. if (node.kind !== "file") throw notFile(request.path);
  611. const source = node.content ?? "";
  612. const normalized = source.replace(/\r\n/gu, "\n");
  613. const lines = normalized.split("\n");
  614. const offset = request.offsetLine ?? 0;
  615. const selected = lines.slice(
  616. offset,
  617. request.limitLines === undefined ? undefined : offset + request.limitLines,
  618. );
  619. return {
  620. bytesRead: Buffer.byteLength(selected.join("\n"), "utf8"),
  621. content: selected.join("\n"),
  622. encoding: request.encoding ?? "utf8",
  623. lineCount: selected.length,
  624. path: request.path,
  625. sizeBytes: Buffer.byteLength(source, "utf8"),
  626. startLine: offset + 1,
  627. totalLines: lines.length,
  628. truncated: selected.length < lines.length - offset,
  629. revision: { id: `revision:${request.path}:${node.mtimeMs}` },
  630. };
  631. }
  632. async writeTextFile(request: { content: string; path: string }) {
  633. this.files[request.path] = file(request.content, Date.now());
  634. return { bytesWritten: Buffer.byteLength(request.content), path: request.path };
  635. }
  636. async removeFile(request: { missingOk?: boolean; path: string }) {
  637. const removed = delete this.files[request.path];
  638. if (!removed && !request.missingOk) throw missing(request.path);
  639. return { path: request.path, removed };
  640. }
  641. async listDirectory(request: { path: string }) {
  642. this.listRequests.push(request.path);
  643. if (request.path !== MEMORY_ROOT && this.files[request.path]?.kind !== "directory") {
  644. const hasChildren = Object.keys(this.files).some((path) =>
  645. path.startsWith(`${request.path}/`),
  646. );
  647. if (!hasChildren) throw missing(request.path);
  648. }
  649. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  650. const entries = new Map<string, FileSystemListDirectoryEntry>();
  651. for (const [path, node] of Object.entries(this.files)) {
  652. if (!path.startsWith(prefix)) continue;
  653. const relative = path.slice(prefix.length);
  654. const name = relative.split("/")[0];
  655. if (!name || entries.has(name)) continue;
  656. const direct = !relative.includes("/");
  657. const directNode = direct ? node : this.files[`${prefix}${name}`];
  658. entries.set(name, {
  659. kind: directNode?.listedKind ?? (direct ? node.kind : "directory"),
  660. name,
  661. path: `${prefix}${name}`,
  662. });
  663. }
  664. const values = [...entries.values()].sort((left, right) => left.name.localeCompare(right.name));
  665. return { durationMs: 0, entries: values, numEntries: values.length, path: request.path };
  666. }
  667. async searchFiles(request: { path: string; pattern: string }) {
  668. return {
  669. durationMs: 0,
  670. files: [],
  671. numFiles: 0,
  672. path: request.path,
  673. pattern: request.pattern,
  674. truncated: false,
  675. };
  676. }
  677. async searchText(request: {
  678. outputMode?: "content" | "files_with_matches" | "count";
  679. path: string;
  680. pattern: string;
  681. }) {
  682. return {
  683. durationMs: 0,
  684. entries: [],
  685. files: [],
  686. mode: request.outputMode ?? "files_with_matches",
  687. numMatches: 0,
  688. path: request.path,
  689. pattern: request.pattern,
  690. truncated: false,
  691. };
  692. }
  693. private node(path: string): TestNode {
  694. const direct = this.files[path];
  695. if (direct) return direct;
  696. if (Object.keys(this.files).some((candidate) => candidate.startsWith(`${path}/`))) {
  697. return directory(0);
  698. }
  699. throw missing(path);
  700. }
  701. }
  702. class AbortDuringManifestFileSystem extends RecallFileSystem {
  703. constructor(
  704. files: Record<string, TestNode>,
  705. private readonly abortController: AbortController,
  706. ) {
  707. super(files);
  708. }
  709. override async readTextFileRange(request: {
  710. path: string;
  711. encoding?: BufferEncoding;
  712. offsetLine?: number;
  713. limitLines?: number;
  714. }) {
  715. if (request.path.endsWith("/second.md")) {
  716. await Promise.resolve();
  717. if (this.abortController.signal.aborted) throw this.abortController.signal.reason;
  718. }
  719. const result = await super.readTextFileRange(request);
  720. if (request.path.endsWith("/first.md")) this.abortController.abort();
  721. return result;
  722. }
  723. }
  724. function missing(path: string): Error {
  725. return createFileSystemError({ code: "not_found", message: `missing: ${path}`, path });
  726. }
  727. function notFile(path: string): Error {
  728. return createFileSystemError({ code: "not_file", message: `not file: ${path}`, path });
  729. }
  730. function manifestEntry(
  731. filename: string,
  732. overrides: Partial<MemoryManifestEntry> = {},
  733. ): MemoryManifestEntry {
  734. return {
  735. filePath: `${MEMORY_ROOT}/${filename}`,
  736. filename,
  737. mtimeMs: 1,
  738. ...overrides,
  739. };
  740. }
  741. function selectorState(manifest: MemoryManifestEntry[]) {
  742. const state = createMemoryRecallState();
  743. state.manifest = manifest;
  744. state.selectorMessages = [
  745. {
  746. role: "user",
  747. content: `Available memories:\n${formatMemoryManifest(manifest)}`,
  748. cacheControl: { type: "ephemeral" },
  749. },
  750. ];
  751. return state;
  752. }
  753. function testModelSelection() {
  754. return {
  755. providerId: createModelProviderId("test"),
  756. modelId: createModelId("lite"),
  757. };
  758. }
  759. function textModel(text: string, onCall?: () => void): Model {
  760. return testModel({
  761. async generateText() {
  762. onCall?.();
  763. return {
  764. finishReason: "stop",
  765. model: testModelSelection(),
  766. text,
  767. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  768. };
  769. },
  770. async *streamText() {},
  771. });
  772. }
  773. function throwingModel(): Model {
  774. return testModel({
  775. async generateText() {
  776. throw new Error("selector failed");
  777. },
  778. async *streamText() {},
  779. });
  780. }
  781. function testModel(executor: Pick<Model, "generateText" | "streamText">): Model {
  782. return {
  783. ...testModelSelection(),
  784. properties: {
  785. contextWindow: 200_000,
  786. ...createTestModelFormatProperties(),
  787. supportsToolCall: true,
  788. supportsJsonSchemaOutput: true,
  789. supportsNativeWebSearch: false,
  790. supportsMidConversationSystem: true,
  791. },
  792. optionSpecs: {
  793. reasoningLevel: { values: ["disabled"] },
  794. maxOutputTokens: { max: 32_000 },
  795. },
  796. options: { maxOutputTokens: 32_000, reasoningLevel: "disabled" },
  797. bind() {
  798. return this;
  799. },
  800. ...executor,
  801. };
  802. }
  803. interface SelectorFixture {
  804. model: string;
  805. system: Array<{ text: string }>;
  806. messages: Array<{ role: "user"; content: Array<{ text: string }> }>;
  807. output_config: { format: { schema: Record<string, unknown> } };
  808. }