memory-agent-loop.test.ts 17 KB

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