memory-e2e-runtime.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { dirname, join, resolve } from "node:path";
  3. import { fileURLToPath, pathToFileURL } from "node:url";
  4. import {
  5. existingMemoryFile,
  6. initialProjectMemoryIndex,
  7. memoryE2EText,
  8. } from "./memory-e2e-provider.mjs";
  9. const scriptDir = dirname(fileURLToPath(import.meta.url));
  10. const repoRoot = resolve(scriptDir, "../../../..");
  11. const modelId = "memory-e2e-model";
  12. const providerId = "memory-e2e-provider";
  13. export async function createScenarioPaths(runRoot, modules) {
  14. const project = scenarioRoot(runRoot, "project");
  15. const custom = scenarioRoot(runRoot, "custom");
  16. const disabled = scenarioRoot(runRoot, "disabled");
  17. const headless = scenarioRoot(runRoot, "headless");
  18. const shutdown = scenarioRoot(runRoot, "shutdown");
  19. for (const scenario of [project, custom, disabled, headless, shutdown]) {
  20. await mkdir(scenario.workspace, { recursive: true });
  21. await mkdir(scenario.storageRoot, { recursive: true });
  22. }
  23. project.memoryRoot = modules.core.resolveProjectMemoryRoot({
  24. cliStorageRoot: join(project.storageRoot, "cli"),
  25. workspacePath: project.workspace,
  26. });
  27. project.indexFile = join(project.memoryRoot, "MEMORY.md");
  28. project.existingFile = join(project.memoryRoot, "database-test-policy.md");
  29. project.extractedFile = join(project.memoryRoot, "deployment-approval-policy.md");
  30. await mkdir(project.memoryRoot, { recursive: true });
  31. await writeFile(project.indexFile, initialProjectMemoryIndex(), "utf8");
  32. await writeFile(project.existingFile, existingMemoryFile(), "utf8");
  33. custom.memoryRoot = join(custom.workspace, ".zcode", "agent-memory", "memory-curator");
  34. custom.memoryFile = join(custom.memoryRoot, "review-convention.md");
  35. await mkdir(custom.memoryRoot, { recursive: true });
  36. await writeFile(
  37. join(custom.memoryRoot, "MEMORY.md"),
  38. "- [Review convention](review-convention.md): Keep review findings evidence-first.\n",
  39. "utf8",
  40. );
  41. disabled.memoryRoot = modules.core.resolveProjectMemoryRoot({
  42. cliStorageRoot: join(disabled.storageRoot, "cli"),
  43. workspacePath: disabled.workspace,
  44. });
  45. headless.memoryRoot = modules.core.resolveProjectMemoryRoot({
  46. cliStorageRoot: join(headless.storageRoot, "cli"),
  47. workspacePath: headless.workspace,
  48. });
  49. headless.indexFile = join(headless.memoryRoot, "MEMORY.md");
  50. headless.existingFile = join(headless.memoryRoot, "database-test-policy.md");
  51. await mkdir(headless.memoryRoot, { recursive: true });
  52. await writeFile(headless.indexFile, initialProjectMemoryIndex(), "utf8");
  53. await writeFile(headless.existingFile, existingMemoryFile(), "utf8");
  54. shutdown.memoryRoot = modules.core.resolveProjectMemoryRoot({
  55. cliStorageRoot: join(shutdown.storageRoot, "cli"),
  56. workspacePath: shutdown.workspace,
  57. });
  58. shutdown.cancelledFile = join(shutdown.memoryRoot, "must-not-be-written.md");
  59. return { custom, disabled, headless, project, shutdown };
  60. }
  61. export async function runMemoryScenarios(input) {
  62. await runProjectMemoryScenario(input);
  63. await runCustomAgentScenario(input);
  64. await runDisabledScenario(input);
  65. await runHeadlessExtractionDisabledScenario(input);
  66. return {
  67. closeCancellation: await runCloseCancellationScenario(input),
  68. };
  69. }
  70. export async function loadZCodeModules() {
  71. const paths = {
  72. bootstrap: join(repoRoot, "apps/zcode-cli/packages/bootstrap/dist/index.js"),
  73. bootstrapModelConfig: join(repoRoot, "apps/zcode-cli/packages/bootstrap/dist/model-config.js"),
  74. core: join(repoRoot, "apps/zcode-cli/packages/core/dist/index.js"),
  75. projectMemoryRetrievalBranch: join(
  76. repoRoot,
  77. "apps/zcode-cli/packages/core/dist/memory/project-memory-retrieval-branch.js",
  78. ),
  79. providerConfig: join(repoRoot, "packages/provider/dist/config/index.js"),
  80. providerRegistry: join(repoRoot, "packages/provider/dist/registry.js"),
  81. };
  82. try {
  83. const [
  84. bootstrap,
  85. bootstrapModelConfig,
  86. core,
  87. projectMemoryRetrievalBranch,
  88. providerConfig,
  89. providerRegistry,
  90. ] = await Promise.all(Object.values(paths).map((path) => import(pathToFileURL(path).href)));
  91. return {
  92. bootstrap: { ...bootstrap, ...bootstrapModelConfig },
  93. core,
  94. projectMemoryRetrievalBranch,
  95. provider: { ...providerConfig, ...providerRegistry },
  96. };
  97. } catch (error) {
  98. throw new Error(
  99. "Unable to load built ZCode packages. Run the Memory E2E e2e:build script first.",
  100. { cause: error },
  101. );
  102. }
  103. }
  104. function scenarioRoot(runRoot, name) {
  105. const root = join(runRoot, name);
  106. return {
  107. root,
  108. storageRoot: join(root, "storage"),
  109. workspace: join(root, "workspace"),
  110. };
  111. }
  112. async function runProjectMemoryScenario({ modules, paths, provider }) {
  113. const app = await createApp({
  114. modules,
  115. provider,
  116. sessionId: "memory-e2e-project-session",
  117. storageRoot: paths.project.storageRoot,
  118. workspace: paths.project.workspace,
  119. });
  120. try {
  121. await withTimeout(
  122. app.submitPrompt(memoryE2EText.defaultBranchPrompt),
  123. 15_000,
  124. "project default Memory turn",
  125. );
  126. await withTimeout(
  127. app.submitPrompt(memoryE2EText.extractionPrompt),
  128. 15_000,
  129. "project Extraction turn",
  130. );
  131. await withTimeout(
  132. app.runtime.drainMemoryExtractions(),
  133. 15_000,
  134. "project Memory Extraction completion",
  135. );
  136. } finally {
  137. await withTimeout(app.close?.(), 15_000, "project Memory close");
  138. }
  139. const nextSession = await createApp({
  140. modules,
  141. provider,
  142. sessionId: "memory-e2e-project-next-session",
  143. storageRoot: paths.project.storageRoot,
  144. workspace: paths.project.workspace,
  145. });
  146. try {
  147. await withTimeout(
  148. nextSession.submitPrompt(memoryE2EText.extractedDefaultPrompt),
  149. 15_000,
  150. "project Memory next-session index turn",
  151. );
  152. await withTimeout(
  153. nextSession.runtime.drainMemoryExtractions(),
  154. 15_000,
  155. "project Memory next-session Extraction completion",
  156. );
  157. } finally {
  158. await withTimeout(nextSession.close?.(), 15_000, "project Memory next-session close");
  159. }
  160. }
  161. async function runCustomAgentScenario({ modules, paths, provider }) {
  162. const profile = {
  163. description: "Maintain durable review conventions.",
  164. memory: "project",
  165. name: "memory-curator",
  166. source: "project",
  167. systemPrompt: "Review and preserve durable collaboration guidance.",
  168. tools: ["Grep"],
  169. };
  170. const app = await createApp({
  171. modules,
  172. profiles: [profile],
  173. provider,
  174. sessionId: "memory-e2e-custom-parent-session",
  175. storageRoot: paths.custom.storageRoot,
  176. subagentsEnabled: true,
  177. workspace: paths.custom.workspace,
  178. });
  179. try {
  180. await withTimeout(
  181. app.submitPrompt(memoryE2EText.customParentPrompt),
  182. 15_000,
  183. "custom agent Memory turn",
  184. );
  185. await withTimeout(
  186. app.runtime.drainMemoryExtractions(),
  187. 15_000,
  188. "custom agent parent Extraction completion",
  189. );
  190. } finally {
  191. await withTimeout(app.close?.(), 15_000, "custom agent close");
  192. }
  193. }
  194. async function runDisabledScenario({ modules, paths, provider }) {
  195. const app = await createApp({
  196. memoryEnabled: false,
  197. modules,
  198. provider,
  199. sessionId: "memory-e2e-disabled-session",
  200. storageRoot: paths.disabled.storageRoot,
  201. workspace: paths.disabled.workspace,
  202. });
  203. try {
  204. await withTimeout(
  205. app.submitPrompt(memoryE2EText.disabledPrompt),
  206. 15_000,
  207. "disabled Memory turn",
  208. );
  209. } finally {
  210. await withTimeout(app.close?.(), 15_000, "disabled Memory close");
  211. }
  212. }
  213. async function runHeadlessExtractionDisabledScenario({ modules, paths, provider }) {
  214. const app = await createApp({
  215. extractionEnabled: false,
  216. modules,
  217. provider,
  218. sessionId: "memory-e2e-headless-session",
  219. storageRoot: paths.headless.storageRoot,
  220. workspace: paths.headless.workspace,
  221. });
  222. try {
  223. await withTimeout(
  224. app.submitPrompt(memoryE2EText.headlessPrompt),
  225. 15_000,
  226. "headless Memory turn",
  227. );
  228. await withTimeout(
  229. app.runtime.drainMemoryExtractions(),
  230. 15_000,
  231. "headless Memory Extraction drain",
  232. );
  233. } finally {
  234. await withTimeout(app.close?.(), 15_000, "headless Memory close");
  235. }
  236. }
  237. async function runCloseCancellationScenario({ closeBarrier, modules, paths, provider }) {
  238. const app = await createApp({
  239. modules,
  240. provider,
  241. sessionId: "memory-e2e-close-cancellation-session",
  242. storageRoot: paths.shutdown.storageRoot,
  243. workspace: paths.shutdown.workspace,
  244. });
  245. let closePromise;
  246. let closeStartedAtMs = 0;
  247. let closeDurationMs = 0;
  248. try {
  249. await withTimeout(
  250. app.submitPrompt(memoryE2EText.closeCancellationPrompt),
  251. 15_000,
  252. "Memory close-cancellation Main turn",
  253. );
  254. await withTimeout(
  255. closeBarrier.waitUntilStarted(),
  256. 15_000,
  257. "Memory close-cancellation Extraction start",
  258. );
  259. closeStartedAtMs = Date.now();
  260. closePromise = app.close?.();
  261. await withTimeout(closePromise, 2_000, "Memory close-cancellation session close");
  262. closeDurationMs = Date.now() - closeStartedAtMs;
  263. } finally {
  264. closeBarrier.releaseResponse();
  265. await withTimeout(closePromise ?? app.close?.(), 15_000, "Memory close-cancellation cleanup");
  266. }
  267. await waitForProviderRecord(
  268. provider,
  269. (record) =>
  270. record.requestBody.includes(memoryE2EText.closeCancellationPrompt) &&
  271. record.requestBody.includes(memoryE2EText.extractionMarker),
  272. "Memory close-cancellation provider capture",
  273. );
  274. await nextTask();
  275. return { closeDurationMs };
  276. }
  277. function createApp(input) {
  278. const env = {
  279. ...process.env,
  280. ZCODE_ENV: "test",
  281. ZCODE_STORAGE_DIR: input.storageRoot,
  282. };
  283. const target = {
  284. apiKey: "memory-e2e-key",
  285. apiKeyRequired: false,
  286. baseURL: input.provider.baseURL,
  287. kind: "anthropic",
  288. model: modelId,
  289. provider: providerId,
  290. };
  291. const modelAdapter = input.modules.bootstrap.createModelAdapter({
  292. env,
  293. executionConfig: input.modules.bootstrap.createRuntimeAiSdkModelExecutionConfig(env),
  294. });
  295. const providerRegistry = createProviderRegistry(input.modules.provider, target);
  296. return input.modules.bootstrap.createZCodeApp({
  297. env,
  298. modelAdapter,
  299. providerRegistry,
  300. runtimeConfig: {
  301. memory: {
  302. enabled: input.memoryEnabled ?? true,
  303. ...(input.extractionEnabled === undefined
  304. ? {}
  305. : { extractionEnabled: input.extractionEnabled }),
  306. use: true,
  307. },
  308. mcp: { enabled: false },
  309. mode: "yolo",
  310. modelSelection: { providerId, modelId, options: { reasoningLevel: "disabled" } },
  311. modelStreaming: "off",
  312. subagents: {
  313. enabled: input.subagentsEnabled ?? false,
  314. maxTurns: 4,
  315. profiles: input.profiles ?? [],
  316. },
  317. titleGeneration: { enabled: false },
  318. workingDirectory: input.workspace,
  319. },
  320. sessionId: input.sessionId,
  321. skipUserConfig: true,
  322. });
  323. }
  324. function createProviderRegistry(providerModule, target) {
  325. const providerConfig = new providerModule.ProviderConfig({
  326. access: new providerModule.ApiKeyAccessConfig({ apiKey: target.apiKey }),
  327. api: new providerModule.ProviderApiConfig({
  328. type: "anthropic-messages",
  329. baseUrl: target.baseURL,
  330. }),
  331. models: [modelId],
  332. enabled: true,
  333. });
  334. const modelConfig = new providerModule.ModelConfig({
  335. properties: new providerModule.ModelPropertiesConfig({
  336. contextWindow: 1_000_000,
  337. inputFormat: {
  338. supportsText: true,
  339. supportsImage: true,
  340. supportsVideo: true,
  341. supportsAudio: false,
  342. supportsPdf: true,
  343. },
  344. outputFormat: { supportsText: true },
  345. supportsToolCall: true,
  346. supportsJsonSchemaOutput: true,
  347. supportsNativeWebSearch: false,
  348. supportsMidConversationSystem: true,
  349. }),
  350. optionSpecs: new providerModule.ModelOptionSpecsConfig({
  351. // fixture 必须遵守当前 Option Map 合同,避免在 Memory 请求之前就创建模型失败。
  352. reasoningLevel: { values: ["disabled"], map: "{}" },
  353. maxOutputTokens: { max: 1_000_000, map: '{"max_tokens": maxOutputTokens}' },
  354. }),
  355. });
  356. return new providerModule.ProviderRegistry([
  357. {
  358. providerId,
  359. config: providerConfig,
  360. models: [{ modelId, config: modelConfig }],
  361. },
  362. ]);
  363. }
  364. async function withTimeout(promise, timeoutMs, label) {
  365. if (!promise) return;
  366. let timer;
  367. try {
  368. await Promise.race([
  369. promise,
  370. new Promise((_, reject) => {
  371. timer = setTimeout(
  372. () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),
  373. timeoutMs,
  374. );
  375. timer.unref?.();
  376. }),
  377. ]);
  378. } finally {
  379. if (timer) clearTimeout(timer);
  380. }
  381. }
  382. async function waitForProviderRecord(provider, predicate, label) {
  383. const deadline = Date.now() + 5_000;
  384. while (!provider.records.some(predicate)) {
  385. if (Date.now() >= deadline) {
  386. throw new Error(`${label} timed out`);
  387. }
  388. await nextTask();
  389. }
  390. }
  391. async function nextTask() {
  392. await new Promise((resolve) => setImmediate(resolve));
  393. }