persistent-agent-memory.test.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import { readFileSync } from "node:fs";
  2. import { join } from "node:path";
  3. import { describe, expect, it } from "vitest";
  4. import { buildPersistentAgentMemoryPrompt } from "../src/subagent/persistent-memory-prompt.js";
  5. import {
  6. loadPersistentAgentMemory,
  7. projectPersistentAgentMemoryTools,
  8. resolvePersistentAgentMemoryRoot,
  9. sanitizePersistentAgentMemoryKey,
  10. } from "../src/subagent/persistent-memory.js";
  11. import { formatAgentProfilesForPrompt, type AgentProfile } from "../src/subagent/profile.js";
  12. import { MemoryFileSystem } from "./memory-test-utils.js";
  13. const fixture = readFileSync(
  14. new URL("./fixtures/memory/custom-agent-memory.md", import.meta.url),
  15. "utf8",
  16. ).replace(/\n$/u, "");
  17. const scopeGuidance = JSON.parse(
  18. readFileSync(
  19. new URL("./fixtures/memory/custom-agent-scope-guidance.json", import.meta.url),
  20. "utf8",
  21. ),
  22. ) as Record<"user" | "project" | "local", string>;
  23. describe("persistent custom-agent memory", () => {
  24. it("uses the exact agent key replacement and three ZCode scope roots", () => {
  25. expect(sanitizePersistentAgentMemoryKey("reviewer/a b")).toBe("reviewer-a-b");
  26. expect(sanitizePersistentAgentMemoryKey("review😀agent")).toBe("review--agent");
  27. expect(sanitizePersistentAgentMemoryKey("!!!")).toBe("---");
  28. expect(sanitizePersistentAgentMemoryKey("")).toBe("unknown");
  29. expect(root("user")).toBe("/storage/agent-memory/reviewer-a-b");
  30. expect(root("project")).toBe("/workspace/app/.zcode/agent-memory/reviewer-a-b");
  31. expect(root("local")).toBe("/workspace/app/.zcode/agent-memory-local/reviewer-a-b");
  32. });
  33. it.each(["user", "project", "local"] as const)(
  34. "renders the exact empty %s-scope provider prompt",
  35. (scope) => {
  36. const memoryRoot = root(scope);
  37. const expected = fixture
  38. .replace("<MEMORY_ROOT>", memoryRoot)
  39. .replace("<SCOPE_GUIDANCE>", scopeGuidance[scope]);
  40. expect(
  41. buildPersistentAgentMemoryPrompt({ indexContent: "", rootDir: memoryRoot, scope }),
  42. ).toBe(expected);
  43. },
  44. );
  45. it("loads non-empty MEMORY.md and applies the exact 200-line truncation warning", () => {
  46. const index = Array.from({ length: 201 }, (_, index) => `- memory ${index + 1}`).join("\n");
  47. const prompt = buildPersistentAgentMemoryPrompt({
  48. indexContent: index,
  49. rootDir: root("project"),
  50. scope: "project",
  51. });
  52. expect(prompt).toContain("## MEMORY.md\n\n- memory 1");
  53. expect(prompt).toContain("- memory 200\n\n> WARNING: MEMORY.md is 201 lines (limit: 200).");
  54. expect(prompt.split("\n\n> WARNING:")[0]).not.toContain("- memory 201");
  55. expect(prompt).toContain(
  56. 'Only part of it was loaded: 1 of 201 lines were cut off, starting at line 201 ("- memory 201").',
  57. );
  58. });
  59. it("limits a single long MEMORY.md value and formats integer KB like the baseline", () => {
  60. const prompt = buildPersistentAgentMemoryPrompt({
  61. indexContent: "x".repeat(25_600),
  62. rootDir: root("local"),
  63. scope: "local",
  64. });
  65. expect(prompt).toContain(
  66. `${"x".repeat(25_000)}\n\n> WARNING: MEMORY.md is 25KB (limit: 24.4KB) — index entries are too long.`,
  67. );
  68. });
  69. it("adds only Write/Edit for explicit tools, then keeps existing filtering", () => {
  70. const profile = customProfile({
  71. disallowedTools: ["Edit"],
  72. memory: "project",
  73. tools: ["Grep"],
  74. });
  75. const definitions = { activeAgents: [profile] };
  76. const memory = { enabled: true, storageRoot: "/storage", use: true };
  77. const projected = projectPersistentAgentMemoryTools(definitions, memory).activeAgents[0];
  78. expect(projected?.tools).toEqual(["Grep", "Write", "Edit"]);
  79. expect(formatAgentProfilesForPrompt([projected!])).toContain(
  80. "- reviewer/a b: Review changes. (Tools: Grep, Write)",
  81. );
  82. expect(projectPersistentAgentMemoryTools(definitions, { ...memory, enabled: false })).toBe(
  83. definitions,
  84. );
  85. expect(projectPersistentAgentMemoryTools(definitions, undefined)).toBe(definitions);
  86. expect(projectPersistentAgentMemoryTools(definitions, { ...memory, storageRoot: "" })).toBe(
  87. definitions,
  88. );
  89. expect(
  90. projectPersistentAgentMemoryTools(
  91. { activeAgents: [customProfile({ memory: "project" })] },
  92. memory,
  93. ).activeAgents[0]?.tools,
  94. ).toBeUndefined();
  95. expect(
  96. projectPersistentAgentMemoryTools(
  97. { activeAgents: [customProfile({ memory: "project", tools: [] })] },
  98. memory,
  99. ).activeAgents[0]?.tools,
  100. ).toEqual(["Write", "Edit"]);
  101. expect(
  102. projectPersistentAgentMemoryTools({ activeAgents: [projected!] }, memory).activeAgents[0],
  103. ).toBe(projected);
  104. expect(profile.tools).toEqual(["Grep"]);
  105. });
  106. it("reads MEMORY.md for every child launch and creates nothing when globally disabled", async () => {
  107. const memoryRoot = root("project");
  108. const indexPath = join(memoryRoot, "MEMORY.md");
  109. const fileSystem = new MemoryFileSystem({ [indexPath]: "first index" });
  110. const profile = customProfile({ memory: "project", tools: ["Write"] });
  111. const memory = { enabled: true, storageRoot: "/storage", use: true };
  112. const first = await loadPersistentAgentMemory({
  113. fileSystemPort: fileSystem,
  114. memory,
  115. profile,
  116. workspaceRoot: "/workspace/app",
  117. });
  118. fileSystem.files[indexPath] = "second index";
  119. const second = await loadPersistentAgentMemory({
  120. fileSystemPort: fileSystem,
  121. memory,
  122. profile,
  123. workspaceRoot: "/workspace/app",
  124. });
  125. expect(first?.prompt).toContain("## MEMORY.md\n\nfirst index");
  126. expect(second?.prompt).toContain("## MEMORY.md\n\nsecond index");
  127. expect(first?.rootDir).toBe(memoryRoot);
  128. expect(fileSystem.createdDirectories).toContain(memoryRoot);
  129. const disabledFileSystem = new MemoryFileSystem({});
  130. expect(
  131. await loadPersistentAgentMemory({
  132. fileSystemPort: disabledFileSystem,
  133. memory: { enabled: false, storageRoot: "/storage", use: true },
  134. profile,
  135. workspaceRoot: "/workspace/app",
  136. }),
  137. ).toBeUndefined();
  138. expect(disabledFileSystem.createdDirectories.size).toBe(0);
  139. });
  140. it("still returns the custom Memory prompt when directory creation fails", async () => {
  141. const fileSystem = new MemoryFileSystem({});
  142. fileSystem.createDirectory = async () => {
  143. throw new Error("mkdir failed");
  144. };
  145. const loaded = await loadPersistentAgentMemory({
  146. fileSystemPort: fileSystem,
  147. memory: { enabled: true, storageRoot: "/storage", use: true },
  148. profile: customProfile({ memory: "user", tools: ["Write"] }),
  149. workspaceRoot: "/workspace/app",
  150. });
  151. expect(loaded?.rootDir).toBe("/storage/agent-memory/reviewer-a-b");
  152. expect(loaded?.prompt).toContain("# Persistent Agent Memory");
  153. });
  154. });
  155. function root(scope: "user" | "project" | "local"): string {
  156. return resolvePersistentAgentMemoryRoot({
  157. agentName: "reviewer/a b",
  158. scope,
  159. storageRoot: "/storage",
  160. workspaceRoot: "/workspace/app",
  161. });
  162. }
  163. function customProfile(overrides: Partial<AgentProfile>): AgentProfile {
  164. return {
  165. description: "Review changes.",
  166. name: "reviewer/a b",
  167. source: "project",
  168. systemPrompt: "Review carefully.",
  169. ...overrides,
  170. };
  171. }