subagent-prompt-assembly.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. import { describe, expect, it, vi } from "vitest";
  2. import { createTestModelSelection } from "./test-model-selection.js";
  3. import {
  4. createModelId,
  5. createModelProviderId,
  6. createSessionId,
  7. modelMessageContentToText,
  8. } from "@zcode/contracts";
  9. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  10. import { buildPersistentAgentMemoryPrompt } from "../src/subagent/persistent-memory-prompt.js";
  11. import { resolvePersistentAgentMemoryRoot } from "../src/subagent/persistent-memory.js";
  12. import { createSubagentContextBuilder } from "../src/subagent/context-builder.js";
  13. import { MemoryFileSystem } from "./memory-test-utils.js";
  14. import { createTestSessionEventStore } from "./test-event-store.js";
  15. import { createTestModelFactory } from "./test-runtime-model.js";
  16. function createMainModelSelection() {
  17. return {
  18. providerId: createModelProviderId("anthropic"),
  19. modelId: createModelId("claude-haiku-4-5-20251001-cc"),
  20. };
  21. }
  22. const USER_AGENTS_INSTRUCTION = "User AGENTS instruction sentinel.";
  23. const WORKSPACE_AGENTS_INSTRUCTION = "Workspace AGENTS instruction sentinel.";
  24. const PROJECT_CONTEXT_SENTINEL = "subagent-project-context-leak-sentinel";
  25. function createParentContextSourcePort() {
  26. const hostEnvInfo = (cwd: string) => ({
  27. cwd,
  28. platform: "darwin",
  29. shell: "zsh",
  30. osVersion: "Darwin 24.3.0",
  31. nodeVersion: "24.14.0",
  32. });
  33. return {
  34. async resolveEnvironment(request: { workingDirectory: string }) {
  35. return hostEnvInfo(request.workingDirectory);
  36. },
  37. async resolveGitContext() {
  38. return { isGitRepository: false };
  39. },
  40. async resolveContextSources(request: {
  41. currentDate?: string;
  42. envInfo?: {
  43. cwd: string;
  44. platform: string;
  45. shell: string;
  46. osVersion: string;
  47. nodeVersion: string;
  48. isGitRepository?: boolean;
  49. };
  50. workingDirectory: string;
  51. }) {
  52. return {
  53. workingDirectory: request.workingDirectory,
  54. currentDate: request.currentDate,
  55. diagnostics: [],
  56. envInfo: request.envInfo ?? hostEnvInfo(request.workingDirectory),
  57. userInstructions: {
  58. filePath: "/repo/AGENTS.md",
  59. fileName: "AGENTS.md",
  60. content: WORKSPACE_AGENTS_INSTRUCTION,
  61. bytesRead: WORKSPACE_AGENTS_INSTRUCTION.length,
  62. sizeBytes: WORKSPACE_AGENTS_INSTRUCTION.length,
  63. truncated: false,
  64. sources: [
  65. {
  66. scope: "user" as const,
  67. filePath: "/Users/test/.zcode/AGENTS.md",
  68. fileName: "AGENTS.md",
  69. content: USER_AGENTS_INSTRUCTION,
  70. bytesRead: USER_AGENTS_INSTRUCTION.length,
  71. sizeBytes: USER_AGENTS_INSTRUCTION.length,
  72. truncated: false,
  73. },
  74. {
  75. scope: "workspace" as const,
  76. filePath: "/repo/AGENTS.md",
  77. fileName: "AGENTS.md",
  78. content: WORKSPACE_AGENTS_INSTRUCTION,
  79. bytesRead: WORKSPACE_AGENTS_INSTRUCTION.length,
  80. sizeBytes: WORKSPACE_AGENTS_INSTRUCTION.length,
  81. truncated: false,
  82. },
  83. ],
  84. },
  85. projectContext: {
  86. type: "node" as const,
  87. scripts: { [PROJECT_CONTEXT_SENTINEL]: "must-not-appear" },
  88. },
  89. };
  90. },
  91. };
  92. }
  93. function systemContents(request: any): string[] {
  94. return systemMessages(request).map((message: any) => message.content);
  95. }
  96. function systemMessages(request: any): any[] {
  97. return request.messages.filter((message: any) => message.role === "system");
  98. }
  99. function expectSystemMessagesCached(request: any): void {
  100. for (const message of systemMessages(request)) {
  101. expect(message.cacheControl).toEqual({ type: "ephemeral" });
  102. }
  103. }
  104. function allMessageText(request: any): string {
  105. return request.messages
  106. .map((message: any) => modelMessageContentToText(message.content))
  107. .join("\n");
  108. }
  109. function countOccurrences(text: string, value: string): number {
  110. return text.split(value).length - 1;
  111. }
  112. function expectInjectedAgentsMd(request: any, childTask: string): void {
  113. const messages = request.messages as any[];
  114. const contextIndex = messages.findIndex(
  115. (message) =>
  116. message.role === "user" &&
  117. modelMessageContentToText(message.content).includes(USER_AGENTS_INSTRUCTION),
  118. );
  119. const taskIndex = messages.findIndex(
  120. (message) =>
  121. message.role === "user" && modelMessageContentToText(message.content) === childTask,
  122. );
  123. expect(contextIndex).toBeGreaterThanOrEqual(0);
  124. expect(taskIndex).toBeGreaterThan(contextIndex);
  125. const contextText = modelMessageContentToText(messages[contextIndex]?.content);
  126. expect(contextText).toContain("<system-reminder>");
  127. expect(contextText).toContain("Codebase and user instructions are shown below.");
  128. expect(contextText).toContain(USER_AGENTS_INSTRUCTION);
  129. expect(contextText).toContain(WORKSPACE_AGENTS_INSTRUCTION);
  130. expect(contextText.indexOf(USER_AGENTS_INSTRUCTION)).toBeLessThan(
  131. contextText.indexOf(WORKSPACE_AGENTS_INSTRUCTION),
  132. );
  133. expect(contextText.indexOf("Codebase and user instructions")).toBeLessThan(
  134. contextText.indexOf(USER_AGENTS_INSTRUCTION),
  135. );
  136. expect(contextText).not.toContain("Today's date");
  137. const text = allMessageText(request);
  138. expect(countOccurrences(text, "Codebase and user instructions are shown below")).toBe(1);
  139. expect(text).not.toContain("# claudeMd");
  140. expect(countOccurrences(text, USER_AGENTS_INSTRUCTION)).toBe(1);
  141. expect(countOccurrences(text, WORKSPACE_AGENTS_INSTRUCTION)).toBe(1);
  142. expect(text).not.toContain(PROJECT_CONTEXT_SENTINEL);
  143. expect(text).not.toContain("# Memory");
  144. expect(systemContents(request).join("\n")).not.toContain(USER_AGENTS_INSTRUCTION);
  145. expect(systemContents(request).join("\n")).not.toContain(WORKSPACE_AGENTS_INSTRUCTION);
  146. expect(systemContents(request).join("\n")).not.toContain("# agentsMd");
  147. }
  148. function expectNoInjectedAgentsMd(request: any): void {
  149. const text = allMessageText(request);
  150. expect(text).not.toContain("# agentsMd");
  151. expect(text).not.toContain("# claudeMd");
  152. expect(text).not.toContain(USER_AGENTS_INSTRUCTION);
  153. expect(text).not.toContain(WORKSPACE_AGENTS_INSTRUCTION);
  154. expect(text).not.toContain(PROJECT_CONTEXT_SENTINEL);
  155. }
  156. describe("subagent provider-visible prompt assembly", () => {
  157. it("assembles Explore child system messages with ZCode prefix, agent prompt, notes, and environment context", async () => {
  158. const sessionId = createSessionId("subagent-prompt-explore");
  159. const contextSourcePort = createParentContextSourcePort();
  160. const resolveContext = vi.spyOn(contextSourcePort, "resolveContextSources");
  161. const eventStore = createTestSessionEventStore();
  162. const childRequests: any[] = [];
  163. let parentCallCount = 0;
  164. const runtime = createTestAgentRuntime(
  165. sessionId,
  166. {
  167. mode: "build",
  168. modelSelection: createTestModelSelection(createMainModelSelection()),
  169. bashShellSelection: {
  170. dialect: "git-bash",
  171. display: { name: "Git Bash" },
  172. path: "C:\\Program Files\\Git\\bin\\bash.exe",
  173. source: "user-config",
  174. },
  175. workingDirectory: "/Users/dev/Desktop/Z/z-code/apps/zcode-cli",
  176. currentDate: "2026-06-04",
  177. envInfo: {
  178. cwd: "/Users/dev/Desktop/Z/z-code/apps/zcode-cli",
  179. platform: "darwin",
  180. shell: "zsh",
  181. osVersion: "Darwin 24.3.0",
  182. nodeVersion: "24.14.0",
  183. isGitRepository: true,
  184. },
  185. },
  186. {
  187. contextSourcePort,
  188. eventStore,
  189. modelFactory: createTestModelFactory({
  190. properties: { supportsNativeWebSearch: true },
  191. async generateText(request: any) {
  192. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  193. if (toolNames.includes("Agent")) {
  194. parentCallCount++;
  195. if (parentCallCount === 1) {
  196. return {
  197. finishReason: "tool-calls",
  198. text: "",
  199. toolCalls: [
  200. {
  201. id: "call_explore",
  202. name: "Agent",
  203. input: {
  204. description: "Find runtime loop",
  205. prompt: "Find where the runtime injects tool results.",
  206. subagent_type: "Explore",
  207. },
  208. },
  209. ],
  210. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  211. };
  212. }
  213. return {
  214. finishReason: "stop",
  215. text: "parent used explore result",
  216. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  217. };
  218. }
  219. childRequests.push(request);
  220. return {
  221. finishReason: "stop",
  222. text: "Explore found the runtime path.",
  223. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  224. };
  225. },
  226. } as never),
  227. },
  228. );
  229. await runtime.executeTurn("Use an explore agent for this question");
  230. expect(childRequests).toHaveLength(1);
  231. expectSystemMessagesCached(childRequests[0]);
  232. const systems = systemContents(childRequests[0]);
  233. expect(systems.map((content) => content.endsWith("\n"))).toEqual([false, false]);
  234. expect(systems[0]).toBe("You are ZCode, an interactive agent");
  235. expect(systems[1]).toMatch(/^\nYou are ZCode Explore/u);
  236. expect(systems[1]).toContain("READ-ONLY MODE");
  237. expect(systems[1]).toContain("\n\nNotes:");
  238. expect(systems[1]).toContain("Agent threads always have their cwd reset between bash calls");
  239. expect(systems[1]).toContain("the parent agent reads your text output");
  240. expect(systems[1]).not.toContain("<env>");
  241. expect(systems[1]).not.toContain("You are powered by");
  242. const childMessages = childRequests[0].messages;
  243. const environmentMessage = childMessages.find((message: any) =>
  244. modelMessageContentToText(message.content).includes("# Environment\n"),
  245. );
  246. const taskIndex = childMessages.findIndex(
  247. (message: any) =>
  248. modelMessageContentToText(message.content) ===
  249. "Find where the runtime injects tool results.",
  250. );
  251. // 不支持 MCS 时,环境是任务前的 user reminder。
  252. expect(environmentMessage.role).toBe("user");
  253. expect(childMessages.indexOf(environmentMessage)).toBeLessThan(taskIndex);
  254. // 只有父级解析一次 context;child 初始化不再调用。
  255. expect(resolveContext).toHaveBeenCalledTimes(1);
  256. const childText = allMessageText(childRequests[0]);
  257. expect(childText).toContain(
  258. " - Primary working directory: /Users/dev/Desktop/Z/z-code/apps/zcode-cli",
  259. );
  260. expect(childText).toContain(" - Is a git repository: true");
  261. expect(childText).toContain(" - Shell: Git Bash");
  262. expect(
  263. countOccurrences(
  264. childText,
  265. "You are powered by the model named anthropic/claude-haiku-4-5-20251001-cc.",
  266. ),
  267. ).toBe(1);
  268. const text = allMessageText(childRequests[0]);
  269. expect(text).not.toContain(
  270. "You help the user with software engineering work in the current workspace.",
  271. );
  272. expect(text).not.toContain("# user_instructions");
  273. expect(text).not.toContain("Project context:");
  274. expectNoInjectedAgentsMd(childRequests[0]);
  275. });
  276. it("adds common notes and environment context to general-purpose child prompts", async () => {
  277. const sessionId = createSessionId("subagent-prompt-general-purpose");
  278. const eventStore = createTestSessionEventStore();
  279. const childRequests: any[] = [];
  280. let parentCallCount = 0;
  281. const runtime = createTestAgentRuntime(
  282. sessionId,
  283. {
  284. mode: "build",
  285. modelSelection: createTestModelSelection(createMainModelSelection()),
  286. presentationSurface: "zcode_desktop",
  287. workingDirectory: "/repo/current",
  288. currentDate: "2026-06-04",
  289. envInfo: {
  290. cwd: "/repo/initial",
  291. platform: "darwin",
  292. shell: "zsh",
  293. osVersion: "Darwin 24.3.0",
  294. nodeVersion: "24.14.0",
  295. isGitRepository: true,
  296. },
  297. },
  298. {
  299. contextSourcePort: createParentContextSourcePort(),
  300. eventStore,
  301. modelFactory: createTestModelFactory({
  302. properties: { supportsNativeWebSearch: true },
  303. async generateText(request: any) {
  304. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  305. if (toolNames.includes("Agent")) {
  306. parentCallCount++;
  307. if (parentCallCount === 1) {
  308. return {
  309. finishReason: "tool-calls",
  310. text: "",
  311. toolCalls: [
  312. {
  313. id: "call_general",
  314. name: "Agent",
  315. input: {
  316. description: "Research runtime",
  317. prompt: "Research how child runtimes are created.",
  318. },
  319. },
  320. ],
  321. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  322. };
  323. }
  324. return {
  325. finishReason: "stop",
  326. text: "parent used general result",
  327. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  328. };
  329. }
  330. childRequests.push(request);
  331. return {
  332. finishReason: "stop",
  333. text: "General-purpose agent found the runtime path.",
  334. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  335. };
  336. },
  337. } as never),
  338. },
  339. );
  340. await runtime.executeTurn("Use a general-purpose agent for this question");
  341. expect(childRequests).toHaveLength(1);
  342. expectSystemMessagesCached(childRequests[0]);
  343. const systems = systemContents(childRequests[0]);
  344. expect(systems).toHaveLength(2);
  345. expect(systems[0]).toBe("You are ZCode, an interactive agent");
  346. expect(systems[1]).toContain("You are an agent for ZCode CLI");
  347. expect(systems[1]).toContain("Complete the task fully—don't gold-plate");
  348. expect(systems[1]).toContain("the caller will relay this to the user");
  349. expect(systems[1]).not.toContain("fully--don't gold-plate");
  350. expect(systems[1]).not.toContain("key findings; the caller");
  351. expect(systems[1]).toContain("Agent threads always have their cwd reset between bash calls");
  352. expect(systems[1]).not.toContain("<env>");
  353. expect(allMessageText(childRequests[0])).toContain(
  354. " - Primary working directory: /repo/current",
  355. );
  356. expect(allMessageText(childRequests[0])).not.toContain(
  357. " - Primary working directory: /repo/initial",
  358. );
  359. // 父会话已离开起始目录,child 必须沿用当前环境事实,不能带回起始快照里的 true。
  360. expect(allMessageText(childRequests[0])).toContain(" - Is a git repository: false");
  361. expectInjectedAgentsMd(childRequests[0], "Research how child runtimes are created.");
  362. });
  363. it.each([
  364. { expectedToInject: true, injectAgentsMd: undefined, label: "missing default" },
  365. { expectedToInject: false, injectAgentsMd: false, label: "explicit false" },
  366. ])(
  367. "assembles custom child prompts with $label AGENTS.md injection",
  368. async ({ expectedToInject, injectAgentsMd, label }) => {
  369. const sessionId = createSessionId(`subagent-prompt-custom-${label.replace(/\s+/gu, "-")}`);
  370. const eventStore = createTestSessionEventStore();
  371. const childRequests: any[] = [];
  372. let parentCallCount = 0;
  373. const runtime = createTestAgentRuntime(
  374. sessionId,
  375. {
  376. mode: "build",
  377. modelSelection: createTestModelSelection(createMainModelSelection()),
  378. workingDirectory: "/repo",
  379. currentDate: "2026-06-04",
  380. envInfo: {
  381. cwd: "/repo",
  382. platform: "darwin",
  383. shell: "zsh",
  384. osVersion: "Darwin 24.3.0",
  385. nodeVersion: "24.14.0",
  386. isGitRepository: false,
  387. },
  388. subagents: {
  389. profiles: [
  390. {
  391. name: "code-researcher",
  392. description: "Research code paths.",
  393. color: "blue",
  394. source: "user",
  395. systemPrompt: "You are a focused code researcher. Return concise findings.",
  396. tools: ["Read", "Grep", "Glob"],
  397. ...(injectAgentsMd === undefined ? {} : { injectAgentsMd }),
  398. },
  399. ],
  400. },
  401. },
  402. {
  403. contextSourcePort: createParentContextSourcePort(),
  404. eventStore,
  405. modelFactory: createTestModelFactory({
  406. properties: { supportsNativeWebSearch: true },
  407. async generateText(request: any) {
  408. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  409. if (toolNames.includes("Agent")) {
  410. parentCallCount++;
  411. if (parentCallCount === 1) {
  412. return {
  413. finishReason: "tool-calls",
  414. text: "",
  415. toolCalls: [
  416. {
  417. id: "call_custom",
  418. name: "Agent",
  419. input: {
  420. description: "Research custom",
  421. prompt: "Research the custom profile path.",
  422. subagent_type: "code-researcher",
  423. },
  424. },
  425. ],
  426. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  427. };
  428. }
  429. return {
  430. finishReason: "stop",
  431. text: "parent used custom result",
  432. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  433. };
  434. }
  435. childRequests.push(request);
  436. return {
  437. finishReason: "stop",
  438. text: "Custom agent found the runtime path.",
  439. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  440. };
  441. },
  442. } as never),
  443. },
  444. );
  445. await runtime.executeTurn("Use the custom researcher agent for this question");
  446. expect(childRequests).toHaveLength(1);
  447. expectSystemMessagesCached(childRequests[0]);
  448. const systems = systemContents(childRequests[0]);
  449. expect(systems).toHaveLength(2);
  450. expect(systems[0]).toBe("You are ZCode, an interactive agent");
  451. expect(systems[1]).toMatch(
  452. /^\nYou are a focused code researcher\. Return concise findings\.\n\nMessages from the agent that launched you — .+\n\nNotes:/u,
  453. );
  454. expect(allMessageText(childRequests[0])).toContain(" - Is a git repository: false");
  455. if (expectedToInject) {
  456. expectInjectedAgentsMd(childRequests[0], "Research the custom profile path.");
  457. } else {
  458. expectNoInjectedAgentsMd(childRequests[0]);
  459. }
  460. },
  461. );
  462. it("puts the launcher-messages paragraph between the trimmed agent prompt and Notes", () => {
  463. const result = createSubagentContextBuilder({
  464. agentPrompt: "\n You are a reviewer.\n",
  465. envInfo: {
  466. cwd: "/repo",
  467. platform: "darwin",
  468. shell: "zsh",
  469. osVersion: "Darwin 24.3.0",
  470. nodeVersion: "24.14.0",
  471. isGitRepository: false,
  472. },
  473. }).build();
  474. const systems = systemContents({ messages: result.systemMessages });
  475. // agent 正文两端 trim 后接启动方消息段,再接 Notes;逐字文本由 subagent-explore 锁定。
  476. expect(systems[1]).toMatch(
  477. /^\nYou are a reviewer\.\n\nMessages from the agent that launched you — .+\n\nNotes:\n/u,
  478. );
  479. });
  480. it("keeps Notes in the body and environment separate when a custom child prompt is empty", () => {
  481. const result = createSubagentContextBuilder({
  482. agentPrompt: "",
  483. envInfo: {
  484. cwd: "/repo",
  485. platform: "darwin",
  486. shell: "zsh",
  487. osVersion: "Darwin 24.3.0",
  488. nodeVersion: "24.14.0",
  489. isGitRepository: false,
  490. },
  491. }).build();
  492. expectSystemMessagesCached({ messages: result.systemMessages });
  493. const systems = systemContents({ messages: result.systemMessages });
  494. expect(systems).toHaveLength(2);
  495. expect(systems[0]).toBe("You are ZCode, an interactive agent");
  496. expect(systems[1]).toMatch(/^\n\nMessages from the agent that launched you — .+\n\nNotes:/u);
  497. expect(systems[1]).not.toContain("<env>");
  498. expect(result.metaUserAttachments).toEqual([]);
  499. expect(result.sections.find((section) => section.source === "env_info")?.content).toContain(
  500. "# Environment\n",
  501. );
  502. expect(systems.join("")).toBe(
  503. result.sections
  504. .filter((section) => section.injectionTarget === "system")
  505. .map((section) => section.content)
  506. .join(""),
  507. );
  508. });
  509. it.each(["user", "project", "local"] as const)(
  510. "projects exact %s persistent memory context and supported write tools to a custom child",
  511. async (scope) => {
  512. const sessionId = createSessionId(`subagent-prompt-persistent-memory-${scope}`);
  513. const eventStore = createTestSessionEventStore();
  514. const memoryRoot = resolvePersistentAgentMemoryRoot({
  515. agentName: "persistent-reviewer",
  516. scope,
  517. storageRoot: "/storage",
  518. workspaceRoot: "/repo",
  519. });
  520. const fileSystemPort = new MemoryFileSystem({
  521. [`${memoryRoot}/MEMORY.md`]: "- [Review style](review-style.md) — keep reviews concise",
  522. });
  523. const parentRequests: any[] = [];
  524. const childRequests: any[] = [];
  525. let parentCallCount = 0;
  526. const runtime = createTestAgentRuntime(
  527. sessionId,
  528. {
  529. memory: { enabled: true, storageRoot: "/storage", use: true },
  530. mode: "build",
  531. modelSelection: createTestModelSelection(createMainModelSelection()),
  532. workingDirectory: "/repo",
  533. currentDate: "2026-06-04",
  534. envInfo: {
  535. cwd: "/repo",
  536. platform: "darwin",
  537. shell: "zsh",
  538. osVersion: "Darwin 24.3.0",
  539. nodeVersion: "24.14.0",
  540. isGitRepository: false,
  541. },
  542. subagents: {
  543. profiles: [
  544. {
  545. name: "persistent-reviewer",
  546. description: "Review with durable context.",
  547. disallowedTools: ["Edit"],
  548. memory: scope,
  549. source: "user",
  550. systemPrompt: "",
  551. tools: ["Grep"],
  552. },
  553. ],
  554. },
  555. },
  556. {
  557. eventStore,
  558. fileSystemPort,
  559. modelFactory: createTestModelFactory({
  560. properties: { supportsNativeWebSearch: true },
  561. async generateText(request: any) {
  562. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  563. if (toolNames.includes("Agent")) {
  564. parentRequests.push(request);
  565. parentCallCount += 1;
  566. if (parentCallCount === 1) {
  567. return {
  568. finishReason: "tool-calls",
  569. text: "",
  570. toolCalls: [
  571. {
  572. id: "call_persistent",
  573. name: "Agent",
  574. input: {
  575. description: "Review persistent",
  576. prompt: "Review using the persistent context.",
  577. subagent_type: "persistent-reviewer",
  578. },
  579. },
  580. ],
  581. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  582. };
  583. }
  584. return {
  585. finishReason: "stop",
  586. text: "parent used persistent review",
  587. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  588. };
  589. }
  590. childRequests.push(request);
  591. if (childRequests.length === 1) {
  592. return {
  593. finishReason: "tool-calls",
  594. text: "",
  595. toolCalls: [
  596. {
  597. id: "write_persistent_memory",
  598. name: "Write",
  599. input: {
  600. content: "Keep reviews concise.",
  601. file_path: `${memoryRoot}/review-style.md`,
  602. },
  603. },
  604. ],
  605. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  606. };
  607. }
  608. return {
  609. finishReason: "stop",
  610. text: "Persistent reviewer completed.",
  611. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  612. };
  613. },
  614. } as never),
  615. },
  616. );
  617. await runtime.executeTurn("review");
  618. expect(childRequests).toHaveLength(2);
  619. const expectedMemoryPrompt = buildPersistentAgentMemoryPrompt({
  620. indexContent: "- [Review style](review-style.md) — keep reviews concise",
  621. rootDir: memoryRoot,
  622. scope,
  623. });
  624. // 记忆段之后先接启动方消息段,再接 Notes。
  625. expect(
  626. systemContents(childRequests[0])[1]?.split(
  627. "\n\nMessages from the agent that launched you",
  628. )[0],
  629. ).toBe(`\n${expectedMemoryPrompt}`);
  630. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  631. expect(childToolNames).toContain("Grep");
  632. expect(childToolNames).toContain("Write");
  633. expect(childToolNames).not.toContain("Edit");
  634. expect(childToolNames).not.toContain("Read");
  635. expect(fileSystemPort.createdDirectories).toContain(memoryRoot);
  636. expect(fileSystemPort.files[`${memoryRoot}/review-style.md`]).toBe("Keep reviews concise.");
  637. expect(
  638. parentRequests[0].messages
  639. .map((message: any) => modelMessageContentToText(message.content))
  640. .join("\n"),
  641. ).toContain("Tools: Grep, Write");
  642. },
  643. );
  644. it("keeps subagent context builder output after runtime context refresh", async () => {
  645. const sessionId = createSessionId("subagent-prompt-refresh");
  646. const eventStore = createTestSessionEventStore();
  647. const requests: any[] = [];
  648. const runtime = createTestAgentRuntime(
  649. sessionId,
  650. {
  651. mode: "build",
  652. modelSelection: createTestModelSelection(createMainModelSelection()),
  653. workingDirectory: "/repo/current",
  654. currentDate: "2026-06-04",
  655. envInfo: {
  656. cwd: "/repo/current",
  657. platform: "darwin",
  658. shell: "zsh",
  659. osVersion: "Darwin 24.3.0",
  660. nodeVersion: "24.14.0",
  661. isGitRepository: true,
  662. },
  663. subagentContext: {
  664. agentPrompt: "You are a focused child agent. Keep the result concise.",
  665. },
  666. taskType: "subagent_child",
  667. },
  668. {
  669. eventStore,
  670. modelFactory: createTestModelFactory({
  671. properties: { supportsNativeWebSearch: true },
  672. async generateText(request: any) {
  673. requests.push(request);
  674. return {
  675. finishReason: "stop",
  676. text: `child response ${requests.length}`,
  677. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  678. };
  679. },
  680. } as never),
  681. },
  682. );
  683. await runtime.executeTurn("first child request");
  684. runtime.updateConfig({ language: "zh-CN" });
  685. await runtime.executeTurn("second child request after refresh");
  686. expect(requests).toHaveLength(2);
  687. for (const request of requests) {
  688. expectSystemMessagesCached(request);
  689. const systems = systemContents(request);
  690. expect(systems).toHaveLength(2);
  691. expect(systems[0]).toBe("You are ZCode, an interactive agent");
  692. expect(systems[1]).toMatch(
  693. /^\nYou are a focused child agent\. Keep the result concise\.\n\nMessages from the agent that launched you — .+\n\nNotes:/u,
  694. );
  695. expect(systems[1]).toContain("Agent threads always have their cwd reset between bash calls");
  696. expect(allMessageText(request)).toContain(" - Primary working directory: /repo/current");
  697. expect(allMessageText(request)).toContain(
  698. "You are powered by the model named anthropic/claude-haiku-4-5-20251001-cc.",
  699. );
  700. expect(allMessageText(request)).not.toContain(
  701. "You help the user with software engineering work in the current workspace.",
  702. );
  703. expect(allMessageText(request)).not.toContain("# ZCode Desktop Context");
  704. }
  705. });
  706. });