persistent-agent-memory.test.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 config = projectPersistentAgentMemoryTools({
  73. memory: { enabled: true, storageRoot: "/storage", use: true },
  74. subagents: { profiles: [profile] },
  75. });
  76. const projected = config.subagents?.profiles?.[0];
  77. expect(projected?.tools).toEqual(["Grep", "Write", "Edit"]);
  78. expect(projected?.tools).not.toContain("Read");
  79. expect(formatAgentProfilesForPrompt([projected!])).toContain(
  80. "- reviewer/a b: Review changes. (Tools: Grep, Write)",
  81. );
  82. expect(
  83. projectPersistentAgentMemoryTools({
  84. memory: { enabled: false, storageRoot: "/storage", use: true },
  85. subagents: { profiles: [profile] },
  86. }).subagents?.profiles?.[0]?.tools,
  87. ).toEqual(["Grep"]);
  88. expect(
  89. projectPersistentAgentMemoryTools({
  90. memory: { enabled: true, storageRoot: "/storage", use: true },
  91. subagents: { profiles: [customProfile({ memory: "project" })] },
  92. }).subagents?.profiles?.[0]?.tools,
  93. ).toBeUndefined();
  94. expect(
  95. projectPersistentAgentMemoryTools({
  96. memory: { enabled: true, storageRoot: "/storage", use: true },
  97. subagents: { profiles: [customProfile({ memory: "project", tools: [] })] },
  98. }).subagents?.profiles?.[0]?.tools,
  99. ).toEqual(["Write", "Edit"]);
  100. });
  101. it("reads MEMORY.md for every child launch and creates nothing when globally disabled", async () => {
  102. const memoryRoot = root("project");
  103. const indexPath = join(memoryRoot, "MEMORY.md");
  104. const fileSystem = new MemoryFileSystem({ [indexPath]: "first index" });
  105. const profile = customProfile({ memory: "project", tools: ["Write"] });
  106. const memory = { enabled: true, storageRoot: "/storage", use: true };
  107. const first = await loadPersistentAgentMemory({
  108. fileSystemPort: fileSystem,
  109. memory,
  110. profile,
  111. workspaceRoot: "/workspace/app",
  112. });
  113. fileSystem.files[indexPath] = "second index";
  114. const second = await loadPersistentAgentMemory({
  115. fileSystemPort: fileSystem,
  116. memory,
  117. profile,
  118. workspaceRoot: "/workspace/app",
  119. });
  120. expect(first?.prompt).toContain("## MEMORY.md\n\nfirst index");
  121. expect(second?.prompt).toContain("## MEMORY.md\n\nsecond index");
  122. expect(first?.rootDir).toBe(memoryRoot);
  123. expect(fileSystem.createdDirectories).toContain(memoryRoot);
  124. const disabledFileSystem = new MemoryFileSystem({});
  125. expect(
  126. await loadPersistentAgentMemory({
  127. fileSystemPort: disabledFileSystem,
  128. memory: { enabled: false, storageRoot: "/storage", use: true },
  129. profile,
  130. workspaceRoot: "/workspace/app",
  131. }),
  132. ).toBeUndefined();
  133. expect(disabledFileSystem.createdDirectories.size).toBe(0);
  134. });
  135. it("still returns the custom Memory prompt when directory creation fails", async () => {
  136. const fileSystem = new MemoryFileSystem({});
  137. fileSystem.createDirectory = async () => {
  138. throw new Error("mkdir failed");
  139. };
  140. const loaded = await loadPersistentAgentMemory({
  141. fileSystemPort: fileSystem,
  142. memory: { enabled: true, storageRoot: "/storage", use: true },
  143. profile: customProfile({ memory: "user", tools: ["Write"] }),
  144. workspaceRoot: "/workspace/app",
  145. });
  146. expect(loaded?.rootDir).toBe("/storage/agent-memory/reviewer-a-b");
  147. expect(loaded?.prompt).toContain("# Persistent Agent Memory");
  148. });
  149. });
  150. function root(scope: "user" | "project" | "local"): string {
  151. return resolvePersistentAgentMemoryRoot({
  152. agentName: "reviewer/a b",
  153. scope,
  154. storageRoot: "/storage",
  155. workspaceRoot: "/workspace/app",
  156. });
  157. }
  158. function customProfile(overrides: Partial<AgentProfile>): AgentProfile {
  159. return {
  160. description: "Review changes.",
  161. name: "reviewer/a b",
  162. source: "project",
  163. systemPrompt: "Review carefully.",
  164. ...overrides,
  165. };
  166. }