persistent-agent-memory.test.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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).not.toContain("- memory 201");
  55. });
  56. it("limits a single long MEMORY.md value and formats integer KB like the baseline", () => {
  57. const prompt = buildPersistentAgentMemoryPrompt({
  58. indexContent: "x".repeat(25_600),
  59. rootDir: root("local"),
  60. scope: "local",
  61. });
  62. expect(prompt).toContain(
  63. `${"x".repeat(25_000)}\n\n> WARNING: MEMORY.md is 25KB (limit: 24.4KB) — index entries are too long.`,
  64. );
  65. });
  66. it("adds only Write/Edit for explicit tools, then keeps existing filtering", () => {
  67. const profile = customProfile({
  68. disallowedTools: ["Edit"],
  69. memory: "project",
  70. tools: ["Grep"],
  71. });
  72. const definitions = { activeAgents: [profile] };
  73. const memory = { enabled: true, storageRoot: "/storage", use: true };
  74. const projected = projectPersistentAgentMemoryTools(definitions, memory).activeAgents[0];
  75. expect(projected?.tools).toEqual(["Grep", "Write", "Edit"]);
  76. expect(formatAgentProfilesForPrompt([projected!])).toContain(
  77. "- reviewer/a b: Review changes. (Tools: Grep, Write)",
  78. );
  79. expect(projectPersistentAgentMemoryTools(definitions, { ...memory, enabled: false })).toBe(
  80. definitions,
  81. );
  82. expect(projectPersistentAgentMemoryTools(definitions, undefined)).toBe(definitions);
  83. expect(projectPersistentAgentMemoryTools(definitions, { ...memory, storageRoot: "" })).toBe(
  84. definitions,
  85. );
  86. expect(
  87. projectPersistentAgentMemoryTools(
  88. { activeAgents: [customProfile({ memory: "project" })] },
  89. memory,
  90. ).activeAgents[0]?.tools,
  91. ).toBeUndefined();
  92. expect(
  93. projectPersistentAgentMemoryTools(
  94. { activeAgents: [customProfile({ memory: "project", tools: [] })] },
  95. memory,
  96. ).activeAgents[0]?.tools,
  97. ).toEqual(["Write", "Edit"]);
  98. expect(
  99. projectPersistentAgentMemoryTools({ activeAgents: [projected!] }, memory).activeAgents[0],
  100. ).toBe(projected);
  101. expect(profile.tools).toEqual(["Grep"]);
  102. });
  103. it("reads MEMORY.md for every child launch and creates nothing when globally disabled", async () => {
  104. const memoryRoot = root("project");
  105. const indexPath = join(memoryRoot, "MEMORY.md");
  106. const fileSystem = new MemoryFileSystem({ [indexPath]: "first index" });
  107. const profile = customProfile({ memory: "project", tools: ["Write"] });
  108. const memory = { enabled: true, storageRoot: "/storage", use: true };
  109. const first = await loadPersistentAgentMemory({
  110. fileSystemPort: fileSystem,
  111. memory,
  112. profile,
  113. workspaceRoot: "/workspace/app",
  114. });
  115. fileSystem.files[indexPath] = "second index";
  116. const second = await loadPersistentAgentMemory({
  117. fileSystemPort: fileSystem,
  118. memory,
  119. profile,
  120. workspaceRoot: "/workspace/app",
  121. });
  122. expect(first?.prompt).toContain("## MEMORY.md\n\nfirst index");
  123. expect(second?.prompt).toContain("## MEMORY.md\n\nsecond index");
  124. expect(first?.rootDir).toBe(memoryRoot);
  125. expect(fileSystem.createdDirectories).toContain(memoryRoot);
  126. const disabledFileSystem = new MemoryFileSystem({});
  127. expect(
  128. await loadPersistentAgentMemory({
  129. fileSystemPort: disabledFileSystem,
  130. memory: { enabled: false, storageRoot: "/storage", use: true },
  131. profile,
  132. workspaceRoot: "/workspace/app",
  133. }),
  134. ).toBeUndefined();
  135. expect(disabledFileSystem.createdDirectories.size).toBe(0);
  136. });
  137. it("still returns the custom Memory prompt when directory creation fails", async () => {
  138. const fileSystem = new MemoryFileSystem({});
  139. fileSystem.createDirectory = async () => {
  140. throw new Error("mkdir failed");
  141. };
  142. const loaded = await loadPersistentAgentMemory({
  143. fileSystemPort: fileSystem,
  144. memory: { enabled: true, storageRoot: "/storage", use: true },
  145. profile: customProfile({ memory: "user", tools: ["Write"] }),
  146. workspaceRoot: "/workspace/app",
  147. });
  148. expect(loaded?.rootDir).toBe("/storage/agent-memory/reviewer-a-b");
  149. expect(loaded?.prompt).toContain("# Persistent Agent Memory");
  150. });
  151. });
  152. function root(scope: "user" | "project" | "local"): string {
  153. return resolvePersistentAgentMemoryRoot({
  154. agentName: "reviewer/a b",
  155. scope,
  156. storageRoot: "/storage",
  157. workspaceRoot: "/workspace/app",
  158. });
  159. }
  160. function customProfile(overrides: Partial<AgentProfile>): AgentProfile {
  161. return {
  162. description: "Review changes.",
  163. name: "reviewer/a b",
  164. source: "project",
  165. systemPrompt: "Review carefully.",
  166. ...overrides,
  167. };
  168. }