runtime-memory-recall.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import {
  2. createSessionId,
  3. getCurrentModelInvocationContext,
  4. type ModelInvocationContext,
  5. type SessionTaskType,
  6. } from "@zcode/contracts";
  7. import { describe, expect, it, vi } from "vitest";
  8. import { resolveProjectMemoryRoot } from "../src/memory/project-root.js";
  9. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  10. import { createToolRegistry } from "../src/tool/registry.js";
  11. import {
  12. consumeSettledProjectMemoryRecall,
  13. invalidateProjectMemoryRecallPaths,
  14. resetProjectMemoryRecall,
  15. startProjectMemoryRecallPrefetch,
  16. } from "../src/runtime/helpers/project-memory-recall.js";
  17. import { MemoryFileSystem } from "./memory-test-utils.js";
  18. import { createTestSessionEventStore } from "./test-event-store.js";
  19. import { createTestModelFactory, createTestRuntimeModel } from "./test-runtime-model.js";
  20. import { createRuntimeModel } from "../src/runtime/methods/runtime-model.js";
  21. const CLI_STORAGE_ROOT = "/storage/cli";
  22. const WORKSPACE_PATH = "/workspace/project";
  23. const RELEVANT_MEMORY_SOURCE = "relevant_memory";
  24. describe("AgentRuntime default project Memory branch", () => {
  25. it("does not start Selector or inject relevant_memory across a Main tool continuation", async () => {
  26. let mainRequestCount = 0;
  27. let selectorRequestCount = 0;
  28. const registry = recallBoundaryRegistry();
  29. const runtime = createRecallRuntime({
  30. registry,
  31. sessionName: "runtime-memory-default-branch",
  32. async generateText(request: any) {
  33. if (request.responseJsonSchema) {
  34. selectorRequestCount += 1;
  35. return textResult(request, '{"selected_memories":["database-policy.md"]}');
  36. }
  37. mainRequestCount += 1;
  38. if (mainRequestCount === 1) return toolCallResult("default-memory-boundary", request);
  39. return textResult(request, "done");
  40. },
  41. });
  42. await runtime.executeTurn("database policy");
  43. expect(mainRequestCount).toBe(2);
  44. expect(selectorRequestCount).toBe(0);
  45. expect((runtime as any).memoryRecallPrefetch).toBeUndefined();
  46. const recallAttachments = (runtime as any).messageHistory
  47. .toRuntimeEntries()
  48. .filter((entry: any) => entry.metadata?.source === RELEVANT_MEMORY_SOURCE);
  49. expect(recallAttachments).toHaveLength(0);
  50. });
  51. it("runs and consumes Semantic Recall only when the semantic-recall branch is selected", async () => {
  52. let selectorRequestCount = 0;
  53. let selectorContext: ModelInvocationContext | undefined;
  54. const generateText = async (request: any) => {
  55. if (request.responseJsonSchema) {
  56. selectorRequestCount += 1;
  57. selectorContext = getCurrentModelInvocationContext();
  58. return textResult(request, '{"selected_memories":["database-policy.md"]}');
  59. }
  60. return textResult(request, "done");
  61. };
  62. const runtime = createRecallRuntime({
  63. sessionName: "runtime-memory-semantic-branch",
  64. workspaceIdentity: "ssh://host/workspace",
  65. generateText,
  66. });
  67. await runtime.executeTurn("please apply the database policy");
  68. startProjectMemoryRecallPrefetch(
  69. runtime as any,
  70. {
  71. model: createRuntimeModel(runtime as never, {
  72. selection: runtime.getSessionModelSelection(),
  73. }),
  74. traceContext: { traceId: "trace-semantic-memory-recall" } as never,
  75. turnAbortSignal: new AbortController().signal,
  76. },
  77. "semantic-recall",
  78. );
  79. await vi.waitFor(() => {
  80. expect((runtime as any).memoryRecallPrefetch?.settled).toBe(true);
  81. });
  82. consumeSettledProjectMemoryRecall(runtime as any, "semantic-recall");
  83. consumeSettledProjectMemoryRecall(runtime as any, "semantic-recall");
  84. expect(selectorRequestCount).toBe(1);
  85. expect(selectorContext).toMatchObject({
  86. modelRequestSessionType: "main",
  87. metadata: { querySource: "project_memory_recall" },
  88. });
  89. const recallAttachments = (runtime as any).messageHistory
  90. .toRuntimeEntries()
  91. .filter((entry: any) => entry.metadata?.source === RELEVANT_MEMORY_SOURCE);
  92. expect(recallAttachments).toHaveLength(1);
  93. expect(String(recallAttachments[0]?.content)).toContain(
  94. "Database tests use the real database.",
  95. );
  96. });
  97. it("does not start Semantic Recall when the Turn Model lacks strict schema output", async () => {
  98. let selectorRequestCount = 0;
  99. const generateText = async (request: any) => {
  100. if (request.responseJsonSchema) selectorRequestCount += 1;
  101. return textResult(request, request.responseJsonSchema ? '{"selected_memories":[]}' : "done");
  102. };
  103. const runtime = createRecallRuntime({
  104. generateText,
  105. sessionName: "runtime-memory-semantic-unsupported-schema",
  106. });
  107. await runtime.executeTurn("please apply the database policy");
  108. startProjectMemoryRecallPrefetch(
  109. runtime as any,
  110. {
  111. model: createTestRuntimeModel({
  112. generateText,
  113. propertyOverrides: { supportsJsonSchemaOutput: false },
  114. }),
  115. traceContext: { traceId: "trace-semantic-unsupported-schema" } as never,
  116. turnAbortSignal: new AbortController().signal,
  117. },
  118. "semantic-recall",
  119. );
  120. expect(selectorRequestCount).toBe(0);
  121. expect((runtime as any).memoryRecallPrefetch).toBeUndefined();
  122. });
  123. it.each<{
  124. memory?: { enabled?: boolean; use?: boolean };
  125. name: string;
  126. taskType?: SessionTaskType;
  127. }>([
  128. { memory: { enabled: false }, name: "disabled feature" },
  129. { memory: { use: false }, name: "disabled use" },
  130. { name: "child task", taskType: "subagent_child" },
  131. ])("does not start Recall for $name", async ({ memory, name, taskType }) => {
  132. let selectorRequestCount = 0;
  133. const runtime = createRecallRuntime({
  134. memory,
  135. sessionName: `runtime-memory-recall-${name.replaceAll(" ", "-")}`,
  136. taskType,
  137. async generateText(request: any) {
  138. if (request.responseJsonSchema) selectorRequestCount += 1;
  139. return textResult(
  140. request,
  141. request.responseJsonSchema ? '{"selected_memories":[]}' : "done",
  142. );
  143. },
  144. });
  145. await runtime.executeTurn("please apply the database policy");
  146. expect(selectorRequestCount).toBe(0);
  147. });
  148. it("resets all session-local Recall state and aborts an unfinished prefetch", () => {
  149. const runtime = createRecallRuntime({
  150. sessionName: "runtime-memory-recall-reset",
  151. async generateText(request: any) {
  152. return textResult(request, "done");
  153. },
  154. });
  155. const previousState = (runtime as any).memoryRecallState;
  156. previousState.manifest = [
  157. {
  158. filePath: "/memory/fact.md",
  159. filename: "fact.md",
  160. mtimeMs: 1,
  161. },
  162. ];
  163. previousState.selectorMessages = [{ role: "user", content: "manifest" }];
  164. previousState.recalledPaths.add("/memory/fact.md");
  165. previousState.recalledContentCharacters = 42;
  166. const abortController = new AbortController();
  167. let detached = false;
  168. (runtime as any).memoryRecallPrefetch = {
  169. abortController,
  170. consumed: false,
  171. detachTurnAbort: () => {
  172. detached = true;
  173. },
  174. memories: [],
  175. settled: false,
  176. };
  177. resetProjectMemoryRecall(runtime as any);
  178. expect((runtime as any).memoryRecallState).not.toBe(previousState);
  179. expect((runtime as any).memoryRecallState).toMatchObject({
  180. recalledContentCharacters: 0,
  181. recalledPaths: new Set(),
  182. });
  183. expect((runtime as any).memoryRecallState.manifest).toBeUndefined();
  184. expect((runtime as any).memoryRecallState.selectorMessages).toBeUndefined();
  185. expect((runtime as any).memoryRecallPrefetch).toBeUndefined();
  186. expect(abortController.signal.aborted).toBe(true);
  187. expect(detached).toBe(true);
  188. });
  189. it("disposes prefetched content when Dream invalidates a touched path", () => {
  190. const runtime = createRecallRuntime({
  191. sessionName: "runtime-memory-recall-dream-invalidation",
  192. async generateText(request: any) {
  193. return textResult(request, "done");
  194. },
  195. });
  196. const memoryPath = `${resolveProjectMemoryRoot({
  197. cliStorageRoot: CLI_STORAGE_ROOT,
  198. workspacePath: WORKSPACE_PATH,
  199. })}/database-policy.md`;
  200. const abortController = new AbortController();
  201. let detached = false;
  202. (runtime as any).memoryRecallPrefetch = {
  203. abortController,
  204. consumed: false,
  205. detachTurnAbort: () => {
  206. detached = true;
  207. },
  208. memories: [
  209. {
  210. content: "stale prefetched content",
  211. entry: { filePath: memoryPath, filename: "database-policy.md", mtimeMs: 1 },
  212. },
  213. ],
  214. settled: true,
  215. };
  216. invalidateProjectMemoryRecallPaths(runtime as any, [memoryPath]);
  217. expect((runtime as any).memoryRecallPrefetch).toBeUndefined();
  218. expect(abortController.signal.aborted).toBe(true);
  219. expect(detached).toBe(true);
  220. });
  221. });
  222. function createRecallRuntime(input: {
  223. generateText: (request: any) => Promise<Record<string, unknown>>;
  224. memory?: { enabled?: boolean; use?: boolean };
  225. registry?: ReturnType<typeof createToolRegistry>;
  226. sessionName: string;
  227. taskType?: SessionTaskType;
  228. workspaceIdentity?: string;
  229. }): AgentRuntime {
  230. const rootDir = resolveProjectMemoryRoot({
  231. cliStorageRoot: CLI_STORAGE_ROOT,
  232. workspaceIdentity: input.workspaceIdentity,
  233. workspacePath: WORKSPACE_PATH,
  234. });
  235. const fileSystemPort = new RecallMemoryFileSystem({
  236. [`${rootDir}/database-policy.md`]: [
  237. "---",
  238. "name: database-policy",
  239. "description: Database tests use the real database.",
  240. "metadata:",
  241. " type: project",
  242. "---",
  243. "",
  244. "Database tests use the real database.",
  245. ].join("\n"),
  246. });
  247. return createTestAgentRuntime(
  248. createSessionId(input.sessionName),
  249. {
  250. memory: {
  251. cliStorageRoot: CLI_STORAGE_ROOT,
  252. enabled: true,
  253. use: true,
  254. workspaceIdentity: input.workspaceIdentity,
  255. ...input.memory,
  256. },
  257. mode: "yolo",
  258. taskType: input.taskType,
  259. workingDirectory: WORKSPACE_PATH,
  260. },
  261. {
  262. eventStore: createTestSessionEventStore(),
  263. fileSystemPort,
  264. modelFactory: createTestModelFactory({
  265. generateText: input.generateText,
  266. properties: { supportsMidConversationSystem: true },
  267. } as never),
  268. toolRegistry: input.registry,
  269. },
  270. );
  271. }
  272. function recallBoundaryRegistry() {
  273. const registry = createToolRegistry();
  274. registry.register({
  275. inputSchema: {},
  276. metadata: {
  277. concurrentSafe: true,
  278. destructive: false,
  279. name: "CompleteRecallBoundary",
  280. needsApproval: false,
  281. readOnly: true,
  282. riskLevel: "low",
  283. sideEffectScope: "none",
  284. },
  285. handler: async () => "tool complete",
  286. });
  287. return registry;
  288. }
  289. function toolCallResult(id: string, request?: any): Record<string, unknown> {
  290. return {
  291. finishReason: "tool-calls",
  292. model: request?.model,
  293. providerMetadata: undefined,
  294. text: "",
  295. toolCalls: [{ id, input: {}, name: "CompleteRecallBoundary" }],
  296. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  297. };
  298. }
  299. function textResult(request: any, text: string): Record<string, unknown> {
  300. return {
  301. finishReason: "stop",
  302. model: request?.model,
  303. text,
  304. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  305. };
  306. }
  307. class RecallMemoryFileSystem extends MemoryFileSystem {
  308. override async stat(request: { path: string }) {
  309. return {
  310. ...(await super.stat(request)),
  311. mtimeMs: 1,
  312. };
  313. }
  314. }