memory-agent-loop.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createModelId,
  4. createModelProviderId,
  5. type Model,
  6. type ModelInputMessage,
  7. type ModelRequest,
  8. type ModelResult,
  9. type ModelToolContract,
  10. } from "@zcode/contracts";
  11. import {
  12. evaluateMemoryAgentToolPolicy,
  13. runMemoryAgentLoop,
  14. type MemoryAgentModelRequest,
  15. } from "../src/memory/memory-agent-loop.js";
  16. import { DEFAULT_MODEL_REQUEST_MEDIA_BUDGET_BYTES } from "../src/runtime/helpers/media-budget.js";
  17. import type { ToolExecutionResult } from "../src/tool/types.js";
  18. import { createTestInputFormat } from "./test-runtime-model.js";
  19. const modelSelection = {
  20. providerId: createModelProviderId("test"),
  21. modelId: createModelId("memory-agent"),
  22. };
  23. const memoryRoot = "/workspace/.memory";
  24. describe("runMemoryAgentLoop", () => {
  25. it("preserves the frozen provider context and real tool catalog on every model turn", async () => {
  26. const initialMessages = Object.freeze([
  27. Object.freeze({ role: "system", content: "full system" }),
  28. Object.freeze({ role: "user", content: "full conversation" }),
  29. Object.freeze({ role: "user", content: "extract now" }),
  30. ]) satisfies readonly ModelInputMessage[];
  31. const tools = Object.freeze([
  32. tool("Read", true, "none"),
  33. tool("Write", false, "workspace"),
  34. tool("Agent", false, "session"),
  35. ]) satisfies readonly ModelToolContract[];
  36. const requests: MemoryAgentModelRequest[] = [];
  37. const executeTool = vi.fn(async (call) => executionResult(call.id, call.name, "written"));
  38. const model = generateOnlyModel(async (request) => {
  39. requests.push(request as MemoryAgentModelRequest);
  40. if (requests.length < 5) {
  41. return modelResult({
  42. text: `turn ${requests.length}`,
  43. toolCalls: [{ id: `read-${requests.length}`, name: "Read", input: {} }],
  44. });
  45. }
  46. return modelResult({
  47. text: "last turn",
  48. toolCalls: [
  49. {
  50. id: "write-last",
  51. name: "Write",
  52. input: { file_path: `${memoryRoot}/fact.md`, content: "fact" },
  53. },
  54. ],
  55. });
  56. });
  57. const result = await runMemoryAgentLoop({
  58. abortSignal: new AbortController().signal,
  59. executeTool,
  60. maxTurns: 5,
  61. messages: initialMessages,
  62. model,
  63. rootDir: memoryRoot,
  64. tools,
  65. workingDirectory: "/workspace",
  66. workspaceRoot: "/workspace",
  67. });
  68. expect(requests).toHaveLength(5);
  69. expect(executeTool).toHaveBeenCalledTimes(5);
  70. expect(executeTool).toHaveBeenLastCalledWith(
  71. expect.objectContaining({ id: "write-last", name: "Write" }),
  72. expect.objectContaining({ abortSignal: expect.any(AbortSignal) }),
  73. );
  74. expect(requests[0]?.messages).toEqual(initialMessages);
  75. expect(requests.every((request) => request.tools === tools)).toBe(true);
  76. expect(requests.every((request) => request.options?.reasoningLevel === "low")).toBe(true);
  77. expect(requests.every((request) => request.options?.maxOutputTokens === 5_000)).toBe(true);
  78. expect(requests[1]?.messages.slice(-2)).toEqual([
  79. expect.objectContaining({
  80. role: "assistant",
  81. content: "turn 1",
  82. toolCalls: [{ id: "read-1", name: "Read", input: {} }],
  83. }),
  84. expect.objectContaining({
  85. role: "tool",
  86. content: "written",
  87. toolCallId: "read-1",
  88. toolName: "Read",
  89. isError: false,
  90. }),
  91. ]);
  92. expect(result.turns).toBe(5);
  93. expect(result.messages.slice(-2)).toEqual([
  94. expect.objectContaining({ role: "assistant", content: "last turn" }),
  95. expect.objectContaining({ role: "tool", toolCallId: "write-last", isError: false }),
  96. ]);
  97. expect(initialMessages).toHaveLength(3);
  98. });
  99. it("applies media capability and budget projection on every model turn", async () => {
  100. const unsupportedVideo = {
  101. type: "video" as const,
  102. mediaType: "video/mp4",
  103. dataUrl: "data:video/mp4;base64,dmlkZW8=",
  104. };
  105. const sharedImageDataUrl = `data:image/png;base64,${"A".repeat(5 * 1024 * 1024)}`;
  106. const retainedImageCount = Math.floor(
  107. DEFAULT_MODEL_REQUEST_MEDIA_BUDGET_BYTES / Buffer.byteLength(sharedImageDataUrl, "utf8"),
  108. );
  109. const historicalImage = {
  110. type: "image" as const,
  111. mediaType: "image/png",
  112. dataUrl: sharedImageDataUrl,
  113. };
  114. const requests: ModelRequest[] = [];
  115. const executeTool = vi.fn(async (call) => ({
  116. ...executionResult(call.id, call.name, "read media"),
  117. modelContent: [unsupportedVideo, historicalImage],
  118. }));
  119. const model = generateOnlyModel(
  120. async (request) => {
  121. requests.push(request);
  122. return requests.length === 1
  123. ? modelResult({
  124. toolCalls: [
  125. { id: "read-media-1", name: "Read", input: {} },
  126. { id: "read-media-2", name: "Read", input: {} },
  127. ],
  128. })
  129. : modelResult({ text: "done" });
  130. },
  131. { inputFormat: createTestInputFormat({ supportsVideo: false }) },
  132. );
  133. await runMemoryAgentLoop({
  134. executeTool,
  135. maxTurns: 2,
  136. messages: [
  137. {
  138. role: "user",
  139. content: [
  140. { type: "text", text: "historical media" },
  141. unsupportedVideo,
  142. ...Array.from({ length: retainedImageCount + 2 }, () => historicalImage),
  143. ],
  144. },
  145. { role: "user", content: "extract memory" },
  146. ],
  147. model,
  148. rootDir: memoryRoot,
  149. tools: [tool("Read", true, "none")],
  150. workingDirectory: "/workspace",
  151. workspaceRoot: "/workspace",
  152. });
  153. expect(requests).toHaveLength(2);
  154. for (const request of requests) {
  155. const blocks = request.messages.flatMap((message) =>
  156. Array.isArray(message.content) ? message.content : [],
  157. );
  158. const text = blocks
  159. .filter((block) => block.type === "text")
  160. .map((block) => block.text)
  161. .join("\n");
  162. expect(blocks.filter((block) => block.type === "video")).toHaveLength(0);
  163. expect(blocks.filter((block) => block.type === "image")).toHaveLength(retainedImageCount);
  164. expect(text).toContain("does not support video input");
  165. expect(text).toContain("Media omitted from provider request");
  166. }
  167. });
  168. it("returns the exact provider-visible denial text without invoking the executor", async () => {
  169. const executeTool = vi.fn();
  170. const requests: ModelRequest[] = [];
  171. const model = generateOnlyModel(async (request) => {
  172. requests.push(request);
  173. if (requests.length === 1) {
  174. return modelResult({
  175. toolCalls: [
  176. { id: "network", name: "WebFetch", input: { url: "https://example.com" } },
  177. { id: "bash-write", name: "Bash", input: { command: "touch /workspace/file" } },
  178. ],
  179. });
  180. }
  181. return modelResult({ text: "done" });
  182. });
  183. const result = await runMemoryAgentLoop({
  184. executeTool,
  185. maxTurns: 2,
  186. messages: [{ role: "user", content: "extract" }],
  187. model,
  188. rootDir: memoryRoot,
  189. tools: [tool("WebFetch", true, "network"), tool("Bash", false, "workspace")],
  190. workingDirectory: "/workspace",
  191. workspaceRoot: "/workspace",
  192. });
  193. expect(executeTool).not.toHaveBeenCalled();
  194. const deniedToolMessages = [
  195. {
  196. content:
  197. "only Read, Grep, Glob, read-only Bash, and Edit/Write within /workspace/.memory are allowed",
  198. role: "tool",
  199. toolCallId: "network",
  200. toolName: "WebFetch",
  201. isError: true,
  202. },
  203. {
  204. content:
  205. "Only read-only shell commands and rm with all paths inside /workspace/.memory are permitted in this context (ls, find, grep, cat, stat, wc, head, tail, and similar)",
  206. role: "tool",
  207. toolCallId: "bash-write",
  208. toolName: "Bash",
  209. isError: true,
  210. },
  211. ];
  212. expect(requests).toHaveLength(2);
  213. expect(requests[1]?.messages.slice(-2)).toEqual(deniedToolMessages);
  214. expect(result.messages.slice(-3, -1)).toEqual(deniedToolMessages);
  215. });
  216. it("returns the catalog-miss result before applying the Memory tool policy", async () => {
  217. const executeTool = vi.fn();
  218. const requests: ModelRequest[] = [];
  219. const model = generateOnlyModel(async (request) => {
  220. requests.push(request);
  221. if (requests.length === 1) {
  222. return modelResult({
  223. toolCalls: [
  224. { id: "empty-name", name: "", input: {} },
  225. { id: "unknown-name", name: "Unknown", input: {} },
  226. ],
  227. });
  228. }
  229. return modelResult({ text: "done" });
  230. });
  231. await runMemoryAgentLoop({
  232. executeTool,
  233. maxTurns: 2,
  234. messages: [{ role: "user", content: "extract" }],
  235. model,
  236. rootDir: memoryRoot,
  237. tools: [tool("Read", true, "none")],
  238. workingDirectory: "/workspace",
  239. workspaceRoot: "/workspace",
  240. });
  241. expect(executeTool).not.toHaveBeenCalled();
  242. expect(requests).toHaveLength(2);
  243. expect(requests[1]?.messages.slice(-2)).toEqual([
  244. {
  245. content: "<tool_use_error>Error: No such tool available: </tool_use_error>",
  246. role: "tool",
  247. toolCallId: "empty-name",
  248. toolName: "",
  249. isError: true,
  250. },
  251. {
  252. content: "<tool_use_error>Error: No such tool available: Unknown</tool_use_error>",
  253. role: "tool",
  254. toolCallId: "unknown-name",
  255. toolName: "Unknown",
  256. isError: true,
  257. },
  258. ]);
  259. });
  260. it("executes tool calls returned by the fiftieth Dream turn", async () => {
  261. let requestCount = 0;
  262. const executeTool = vi.fn(async (call) => executionResult(call.id, call.name, "done"));
  263. const model = generateOnlyModel(async () => {
  264. requestCount += 1;
  265. return modelResult({
  266. toolCalls: [
  267. requestCount === 50
  268. ? {
  269. id: "write-fiftieth",
  270. name: "Write",
  271. input: { file_path: `${memoryRoot}/fact.md`, content: "fact" },
  272. }
  273. : { id: `read-${requestCount}`, name: "Read", input: {} },
  274. ],
  275. });
  276. });
  277. const result = await runMemoryAgentLoop({
  278. executeTool,
  279. maxTurns: 50,
  280. messages: [{ role: "user", content: "dream" }],
  281. model,
  282. rootDir: memoryRoot,
  283. tools: [tool("Read", true, "none"), tool("Write", false, "workspace")],
  284. workingDirectory: "/workspace",
  285. workspaceRoot: "/workspace",
  286. });
  287. expect(result.turns).toBe(50);
  288. expect(executeTool).toHaveBeenCalledTimes(50);
  289. expect(executeTool).toHaveBeenLastCalledWith(
  290. expect.objectContaining({ id: "write-fiftieth", name: "Write" }),
  291. expect.any(Object),
  292. );
  293. });
  294. });
  295. describe("evaluateMemoryAgentToolPolicy", () => {
  296. const registeredTools = [
  297. tool("Read", true, "none"),
  298. tool("Grep", true, "none"),
  299. tool("Bash", false, "workspace"),
  300. tool("Write", false, "workspace"),
  301. tool("Edit", false, "workspace"),
  302. tool("Agent", false, "session"),
  303. tool("WebFetch", true, "network"),
  304. tool("mcp__server__lookup", true, "network"),
  305. tool("OtherReadOnly", true, "none"),
  306. ] as const;
  307. it.each([
  308. ["registered read-only", "Read", {}],
  309. ["read-only Bash", "Bash", { command: "head -n 5 /workspace/notes.txt" }],
  310. ["read-only Bash with safe environment", "Bash", { command: "LANG=C head /workspace/file" }],
  311. ["read-only Bash with input redirect", "Bash", { command: "head < /workspace/file" }],
  312. [
  313. "read-only Bash redirected to /dev/null",
  314. "Bash",
  315. {
  316. command: "head /workspace/file > /dev/null",
  317. },
  318. ],
  319. [
  320. "read-only background Bash",
  321. "Bash",
  322. {
  323. command: "head /workspace/file",
  324. run_in_background: true,
  325. },
  326. ],
  327. ["Memory Write", "Write", { file_path: `${memoryRoot}/fact.md`, content: "fact" }],
  328. [
  329. "Memory Edit",
  330. "Edit",
  331. { file_path: `${memoryRoot}/nested/fact.md`, old_string: "a", new_string: "b" },
  332. ],
  333. ["narrow Bash removal", "Bash", { command: `rm -f ${memoryRoot}/old.md` }],
  334. ])("allows %s", (_label, name, input) => {
  335. expect(decide(name, input, registeredTools)).toMatchObject({ allowed: true });
  336. });
  337. it("does not let static metadata bypass the explicit shell, Agent, or MCP boundaries", () => {
  338. expect(
  339. decide("Bash", { command: "touch /workspace/file" }, [tool("Bash", true, "none")]),
  340. ).toMatchObject({ allowed: false });
  341. expect(decide("Agent", {}, [tool("Agent", true, "none")])).toMatchObject({ allowed: false });
  342. expect(
  343. decide("mcp__server__lookup", {}, [tool("mcp__server__lookup", true, "none")]),
  344. ).toMatchObject({ allowed: false });
  345. });
  346. it.each([
  347. ".git",
  348. "hooks",
  349. ".husky",
  350. ".githooks",
  351. "node_modules",
  352. ".vscode",
  353. ".idea",
  354. "head",
  355. "config",
  356. "objects",
  357. "refs",
  358. ".claude",
  359. "skills",
  360. "commands",
  361. "agents",
  362. ".cargo",
  363. ".devcontainer",
  364. ".yarn",
  365. ".mvn",
  366. ])("denies Memory Write/Edit in the sensitive %s path segment", (segment) => {
  367. const filePath = `${memoryRoot}/${segment}/fact.md`;
  368. expect(decide("Write", { file_path: filePath }, registeredTools)).toMatchObject({
  369. allowed: false,
  370. });
  371. expect(decide("Edit", { file_path: filePath }, registeredTools)).toMatchObject({
  372. allowed: false,
  373. });
  374. });
  375. it("uses the foreground sensitive-segment normalization without broadening it", () => {
  376. for (const segment of [".GIT", ".git.", ".git ", ".g\u200cit", ".git:stream"]) {
  377. expect(
  378. decide("Write", { file_path: `${memoryRoot}/${segment}/fact.md` }, registeredTools),
  379. ).toMatchObject({ allowed: false });
  380. }
  381. expect(
  382. decide("Write", { file_path: `${memoryRoot}/.git-notes/fact.md` }, registeredTools),
  383. ).toMatchObject({ allowed: true });
  384. });
  385. it("keeps the narrow Markdown rm policy unchanged for sensitive path segments", () => {
  386. expect(
  387. decide("Bash", { command: `rm -f ${memoryRoot}/.git/fact.md` }, registeredTools),
  388. ).toMatchObject({ allowed: true });
  389. });
  390. it.each([
  391. ["unregistered", "Unknown", {}],
  392. ["Agent", "Agent", {}],
  393. ["network tool", "WebFetch", { url: "https://example.com" }],
  394. ["MCP tool", "mcp__server__lookup", {}],
  395. ["unlisted read-only tool", "OtherReadOnly", {}],
  396. ["outside Write", "Write", { file_path: "/workspace/outside.md", content: "x" }],
  397. ["uppercase extension", "Write", { file_path: `${memoryRoot}/fact.MD`, content: "x" }],
  398. ["write-capable Bash", "Bash", { command: "touch /workspace/file" }],
  399. ["recursive removal", "Bash", { command: `rm -rf ${memoryRoot}/old.md` }],
  400. ["glob removal", "Bash", { command: `rm ${memoryRoot}/*.md` }],
  401. ["write redirect", "Bash", { command: "head /workspace/file > /workspace/copy" }],
  402. ["unsafe environment prefix", "Bash", { command: "PATH=/tmp head /workspace/file" }],
  403. ])("denies %s", (_label, name, input) => {
  404. expect(decide(name, input, registeredTools)).toMatchObject({ allowed: false });
  405. });
  406. });
  407. function decide(name: string, input: unknown, tools: readonly ModelToolContract[]) {
  408. return evaluateMemoryAgentToolPolicy({
  409. rootDir: memoryRoot,
  410. toolCall: { id: "call", name, input },
  411. tools,
  412. workingDirectory: "/workspace",
  413. workspaceRoot: "/workspace",
  414. });
  415. }
  416. function tool(
  417. name: string,
  418. readOnly: boolean,
  419. sideEffectScope: ModelToolContract["sideEffectScope"],
  420. ): ModelToolContract {
  421. return {
  422. name,
  423. inputSchema: { type: "object" },
  424. readOnly,
  425. sideEffectScope,
  426. };
  427. }
  428. function generateOnlyModel(
  429. generateText: (request: ModelRequest) => Promise<ModelResult>,
  430. properties: Partial<Model["properties"]> = {},
  431. ): Model {
  432. return {
  433. ...modelSelection,
  434. properties: {
  435. requiresMfjsToolSchema: false,
  436. contextWindow: 200_000,
  437. inputFormat: createTestInputFormat(),
  438. outputFormat: { supportsText: true },
  439. supportsToolCall: true,
  440. supportsJsonSchemaOutput: true,
  441. supportsNativeWebSearch: false,
  442. supportsMidConversationSystem: true,
  443. ...properties,
  444. },
  445. optionSpecs: {
  446. reasoningLevel: { values: ["low", "high"] },
  447. maxOutputTokens: { max: 32_000 },
  448. },
  449. options: { maxOutputTokens: 32_000, reasoningLevel: "high" },
  450. bind() {
  451. return this;
  452. },
  453. generateText,
  454. streamText() {
  455. throw new Error("memory agent loop must not stream");
  456. },
  457. };
  458. }
  459. function modelResult(
  460. input: Pick<Partial<ModelResult>, "reasoning" | "text" | "toolCalls">,
  461. ): ModelResult {
  462. return {
  463. finishReason: input.toolCalls?.length ? "tool_calls" : "stop",
  464. model: modelSelection,
  465. text: input.text ?? "",
  466. toolCalls: input.toolCalls,
  467. reasoning: input.reasoning,
  468. usage: {},
  469. };
  470. }
  471. function executionResult(
  472. toolCallId: string,
  473. toolName: string,
  474. output: unknown,
  475. ): ToolExecutionResult {
  476. const now = new Date();
  477. return {
  478. completedAt: now,
  479. durationMs: 0,
  480. output,
  481. startedAt: now,
  482. success: true,
  483. toolCallId,
  484. toolName,
  485. };
  486. }