subagent-prompt-assembly.test.ts 26 KB

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