subagent-prompt-assembly.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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.map((content) => content.endsWith("\n"))).toEqual([false, false]);
  228. expect(systems[0]).toBe("You are ZCode, an interactive coding agent");
  229. expect(systems[1]).toMatch(/^\nYou are ZCode Explore/u);
  230. expect(systems[1]).toContain("READ-ONLY MODE");
  231. expect(systems[1]).toContain("\n\nNotes:");
  232. expect(systems[1]).toContain("Agent threads always have their cwd reset between bash calls");
  233. expect(systems[1]).toContain("the parent agent reads your text output");
  234. expect(systems[1]).toContain(
  235. "\n\nHere is useful information about the environment you are running in:",
  236. );
  237. expect(systems[1]).toContain("Working directory: /Users/dev/Desktop/Z/z-code/apps/zcode-cli");
  238. expect(systems[1]).toContain("Is directory a git repo: Yes");
  239. expect(systems[1]).toContain("Platform: darwin");
  240. expect(systems[1]).toContain("Shell: Git Bash");
  241. expect(systems[1]).toContain("OS Version: Darwin 24.3.0");
  242. expect(systems[1]).toContain(
  243. "You are powered by the model named anthropic/claude-haiku-4-5-20251001-cc.",
  244. );
  245. const text = allMessageText(childRequests[0]);
  246. expect(text).not.toContain(
  247. "You help the user with software engineering work in the current workspace.",
  248. );
  249. expect(text).not.toContain("# user_instructions");
  250. expect(text).not.toContain("Project context:");
  251. expectNoInjectedAgentsMd(childRequests[0]);
  252. });
  253. it("adds common notes and environment context to general-purpose child prompts", async () => {
  254. const sessionId = createSessionId("subagent-prompt-general-purpose");
  255. const eventStore = createTestSessionEventStore();
  256. const childRequests: any[] = [];
  257. let parentCallCount = 0;
  258. const runtime = createTestAgentRuntime(
  259. sessionId,
  260. {
  261. mode: "build",
  262. modelSelection: createTestModelSelection(createMainModelSelection()),
  263. presentationSurface: "zcode_desktop",
  264. workingDirectory: "/repo/current",
  265. currentDate: "2026-06-04",
  266. envInfo: {
  267. cwd: "/repo/initial",
  268. platform: "darwin",
  269. shell: "zsh",
  270. osVersion: "Darwin 24.3.0",
  271. nodeVersion: "24.14.0",
  272. isGitRepository: true,
  273. },
  274. },
  275. {
  276. contextSourcePort: createParentContextSourcePort(),
  277. eventStore,
  278. modelFactory: createTestModelFactory({
  279. properties: { supportsNativeWebSearch: true },
  280. async generateText(request: any) {
  281. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  282. if (toolNames.includes("Agent")) {
  283. parentCallCount++;
  284. if (parentCallCount === 1) {
  285. return {
  286. finishReason: "tool-calls",
  287. text: "",
  288. toolCalls: [
  289. {
  290. id: "call_general",
  291. name: "Agent",
  292. input: {
  293. description: "Research runtime",
  294. prompt: "Research how child runtimes are created.",
  295. },
  296. },
  297. ],
  298. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  299. };
  300. }
  301. return {
  302. finishReason: "stop",
  303. text: "parent used general result",
  304. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  305. };
  306. }
  307. childRequests.push(request);
  308. return {
  309. finishReason: "stop",
  310. text: "General-purpose agent found the runtime path.",
  311. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  312. };
  313. },
  314. } as never),
  315. },
  316. );
  317. await runtime.executeTurn("Use a general-purpose agent for this question");
  318. expect(childRequests).toHaveLength(1);
  319. expectSystemMessagesCached(childRequests[0]);
  320. const systems = systemContents(childRequests[0]);
  321. expect(systems).toHaveLength(2);
  322. expect(systems[0]).toBe("You are ZCode, an interactive coding agent");
  323. expect(systems[1]).toContain("You are an agent for ZCode CLI");
  324. expect(systems[1]).toContain("Complete the task fully—don't gold-plate");
  325. expect(systems[1]).toContain("the caller will relay this to the user");
  326. expect(systems[1]).not.toContain("fully--don't gold-plate");
  327. expect(systems[1]).not.toContain("key findings; the caller");
  328. expect(systems[1]).toContain("Agent threads always have their cwd reset between bash calls");
  329. expect(systems[1]).toContain("Working directory: /repo/current");
  330. expect(systems[1]).not.toContain("Working directory: /repo/initial");
  331. expectInjectedAgentsMd(childRequests[0], "Research how child runtimes are created.");
  332. });
  333. it.each([
  334. { expectedToInject: true, injectAgentsMd: undefined, label: "missing default" },
  335. { expectedToInject: false, injectAgentsMd: false, label: "explicit false" },
  336. ])(
  337. "assembles custom child prompts with $label AGENTS.md injection",
  338. async ({ expectedToInject, injectAgentsMd, label }) => {
  339. const sessionId = createSessionId(`subagent-prompt-custom-${label.replace(/\s+/gu, "-")}`);
  340. const eventStore = createTestSessionEventStore();
  341. const childRequests: any[] = [];
  342. let parentCallCount = 0;
  343. const runtime = createTestAgentRuntime(
  344. sessionId,
  345. {
  346. mode: "build",
  347. modelSelection: createTestModelSelection(createMainModelSelection()),
  348. workingDirectory: "/repo",
  349. currentDate: "2026-06-04",
  350. envInfo: {
  351. cwd: "/repo",
  352. platform: "darwin",
  353. shell: "zsh",
  354. osVersion: "Darwin 24.3.0",
  355. nodeVersion: "24.14.0",
  356. isGitRepository: false,
  357. },
  358. subagents: {
  359. profiles: [
  360. {
  361. name: "code-researcher",
  362. description: "Research code paths.",
  363. color: "blue",
  364. source: "user",
  365. systemPrompt: "You are a focused code researcher. Return concise findings.",
  366. tools: ["Read", "Grep", "Glob"],
  367. ...(injectAgentsMd === undefined ? {} : { injectAgentsMd }),
  368. },
  369. ],
  370. },
  371. },
  372. {
  373. contextSourcePort: createParentContextSourcePort(),
  374. eventStore,
  375. modelFactory: createTestModelFactory({
  376. properties: { supportsNativeWebSearch: true },
  377. async generateText(request: any) {
  378. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  379. if (toolNames.includes("Agent")) {
  380. parentCallCount++;
  381. if (parentCallCount === 1) {
  382. return {
  383. finishReason: "tool-calls",
  384. text: "",
  385. toolCalls: [
  386. {
  387. id: "call_custom",
  388. name: "Agent",
  389. input: {
  390. description: "Research custom",
  391. prompt: "Research the custom profile path.",
  392. subagent_type: "code-researcher",
  393. },
  394. },
  395. ],
  396. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  397. };
  398. }
  399. return {
  400. finishReason: "stop",
  401. text: "parent used custom result",
  402. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  403. };
  404. }
  405. childRequests.push(request);
  406. return {
  407. finishReason: "stop",
  408. text: "Custom agent found the runtime path.",
  409. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  410. };
  411. },
  412. } as never),
  413. },
  414. );
  415. await runtime.executeTurn("Use the custom researcher agent for this question");
  416. expect(childRequests).toHaveLength(1);
  417. expectSystemMessagesCached(childRequests[0]);
  418. const systems = systemContents(childRequests[0]);
  419. expect(systems).toHaveLength(2);
  420. expect(systems[0]).toBe("You are ZCode, an interactive coding agent");
  421. expect(systems[1]).toMatch(
  422. /^\nYou are a focused code researcher\. Return concise findings\.\n\nNotes:/u,
  423. );
  424. expect(systems[1]).toContain("Is directory a git repo: No");
  425. if (expectedToInject) {
  426. expectInjectedAgentsMd(childRequests[0], "Research the custom profile path.");
  427. } else {
  428. expectNoInjectedAgentsMd(childRequests[0]);
  429. }
  430. },
  431. );
  432. it("keeps Notes and environment in one body when a custom child prompt is empty", () => {
  433. const result = createSubagentContextBuilder({
  434. agentPrompt: "",
  435. envInfo: {
  436. cwd: "/repo",
  437. platform: "darwin",
  438. shell: "zsh",
  439. osVersion: "Darwin 24.3.0",
  440. nodeVersion: "24.14.0",
  441. isGitRepository: false,
  442. },
  443. }).build();
  444. expectSystemMessagesCached({ messages: result.systemMessages });
  445. const systems = systemContents({ messages: result.systemMessages });
  446. expect(systems).toHaveLength(2);
  447. expect(systems[0]).toBe("You are ZCode, an interactive coding agent");
  448. expect(systems[1]).toMatch(/^\n\nNotes:/u);
  449. expect(systems[1]).toContain(
  450. "\n\nHere is useful information about the environment you are running in:",
  451. );
  452. expect(systems.join("")).toBe(
  453. result.sections
  454. .filter((section) => section.injectionTarget === "system")
  455. .map((section) => section.content)
  456. .join(""),
  457. );
  458. });
  459. it.each(["user", "project", "local"] as const)(
  460. "projects exact %s persistent memory context and supported write tools to a custom child",
  461. async (scope) => {
  462. const sessionId = createSessionId(`subagent-prompt-persistent-memory-${scope}`);
  463. const eventStore = createTestSessionEventStore();
  464. const memoryRoot = resolvePersistentAgentMemoryRoot({
  465. agentName: "persistent-reviewer",
  466. scope,
  467. storageRoot: "/storage",
  468. workspaceRoot: "/repo",
  469. });
  470. const fileSystemPort = new MemoryFileSystem({
  471. [`${memoryRoot}/MEMORY.md`]: "- [Review style](review-style.md) — keep reviews concise",
  472. });
  473. const parentRequests: any[] = [];
  474. const childRequests: any[] = [];
  475. let parentCallCount = 0;
  476. const runtime = createTestAgentRuntime(
  477. sessionId,
  478. {
  479. memory: { enabled: true, storageRoot: "/storage", use: true },
  480. mode: "build",
  481. modelSelection: createTestModelSelection(createMainModelSelection()),
  482. workingDirectory: "/repo",
  483. currentDate: "2026-06-04",
  484. envInfo: {
  485. cwd: "/repo",
  486. platform: "darwin",
  487. shell: "zsh",
  488. osVersion: "Darwin 24.3.0",
  489. nodeVersion: "24.14.0",
  490. isGitRepository: false,
  491. },
  492. subagents: {
  493. profiles: [
  494. {
  495. name: "persistent-reviewer",
  496. description: "Review with durable context.",
  497. disallowedTools: ["Edit"],
  498. memory: scope,
  499. source: "user",
  500. systemPrompt: "",
  501. tools: ["Grep"],
  502. },
  503. ],
  504. },
  505. },
  506. {
  507. eventStore,
  508. fileSystemPort,
  509. modelFactory: createTestModelFactory({
  510. properties: { supportsNativeWebSearch: true },
  511. async generateText(request: any) {
  512. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  513. if (toolNames.includes("Agent")) {
  514. parentRequests.push(request);
  515. parentCallCount += 1;
  516. if (parentCallCount === 1) {
  517. return {
  518. finishReason: "tool-calls",
  519. text: "",
  520. toolCalls: [
  521. {
  522. id: "call_persistent",
  523. name: "Agent",
  524. input: {
  525. description: "Review persistent",
  526. prompt: "Review using the persistent context.",
  527. subagent_type: "persistent-reviewer",
  528. },
  529. },
  530. ],
  531. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  532. };
  533. }
  534. return {
  535. finishReason: "stop",
  536. text: "parent used persistent review",
  537. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  538. };
  539. }
  540. childRequests.push(request);
  541. if (childRequests.length === 1) {
  542. return {
  543. finishReason: "tool-calls",
  544. text: "",
  545. toolCalls: [
  546. {
  547. id: "write_persistent_memory",
  548. name: "Write",
  549. input: {
  550. content: "Keep reviews concise.",
  551. file_path: `${memoryRoot}/review-style.md`,
  552. },
  553. },
  554. ],
  555. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  556. };
  557. }
  558. return {
  559. finishReason: "stop",
  560. text: "Persistent reviewer completed.",
  561. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  562. };
  563. },
  564. } as never),
  565. },
  566. );
  567. await runtime.executeTurn("review");
  568. expect(childRequests).toHaveLength(2);
  569. const expectedMemoryPrompt = buildPersistentAgentMemoryPrompt({
  570. indexContent: "- [Review style](review-style.md) — keep reviews concise",
  571. rootDir: memoryRoot,
  572. scope,
  573. });
  574. expect(systemContents(childRequests[0])[1]?.split("\n\nNotes:")[0]).toBe(
  575. `\n${expectedMemoryPrompt}`,
  576. );
  577. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  578. expect(childToolNames).toContain("Grep");
  579. expect(childToolNames).toContain("Write");
  580. expect(childToolNames).not.toContain("Edit");
  581. expect(childToolNames).not.toContain("Read");
  582. expect(fileSystemPort.createdDirectories).toContain(memoryRoot);
  583. expect(fileSystemPort.files[`${memoryRoot}/review-style.md`]).toBe("Keep reviews concise.");
  584. expect(
  585. parentRequests[0].messages
  586. .map((message: any) => modelMessageContentToText(message.content))
  587. .join("\n"),
  588. ).toContain("Tools: Grep, Write");
  589. },
  590. );
  591. it("keeps subagent context builder output after runtime context refresh", async () => {
  592. const sessionId = createSessionId("subagent-prompt-refresh");
  593. const eventStore = createTestSessionEventStore();
  594. const requests: any[] = [];
  595. const runtime = createTestAgentRuntime(
  596. sessionId,
  597. {
  598. mode: "build",
  599. modelSelection: createTestModelSelection(createMainModelSelection()),
  600. workingDirectory: "/repo/current",
  601. currentDate: "2026-06-04",
  602. envInfo: {
  603. cwd: "/repo/current",
  604. platform: "darwin",
  605. shell: "zsh",
  606. osVersion: "Darwin 24.3.0",
  607. nodeVersion: "24.14.0",
  608. isGitRepository: true,
  609. },
  610. subagentContext: {
  611. agentPrompt: "You are a focused child agent. Keep the result concise.",
  612. },
  613. taskType: "subagent_child",
  614. },
  615. {
  616. eventStore,
  617. modelFactory: createTestModelFactory({
  618. properties: { supportsNativeWebSearch: true },
  619. async generateText(request: any) {
  620. requests.push(request);
  621. return {
  622. finishReason: "stop",
  623. text: `child response ${requests.length}`,
  624. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  625. };
  626. },
  627. } as never),
  628. },
  629. );
  630. await runtime.executeTurn("first child request");
  631. runtime.updateConfig({ language: "zh-CN" });
  632. await runtime.executeTurn("second child request after refresh");
  633. expect(requests).toHaveLength(2);
  634. for (const request of requests) {
  635. expectSystemMessagesCached(request);
  636. const systems = systemContents(request);
  637. expect(systems).toHaveLength(2);
  638. expect(systems[0]).toBe("You are ZCode, an interactive coding agent");
  639. expect(systems[1]).toMatch(
  640. /^\nYou are a focused child agent\. Keep the result concise\.\n\nNotes:/u,
  641. );
  642. expect(systems[1]).toContain("Agent threads always have their cwd reset between bash calls");
  643. expect(systems[1]).toContain("Working directory: /repo/current");
  644. expect(systems[1]).toContain(
  645. "You are powered by the model named anthropic/claude-haiku-4-5-20251001-cc.",
  646. );
  647. expect(allMessageText(request)).not.toContain(
  648. "You help the user with software engineering work in the current workspace.",
  649. );
  650. expect(allMessageText(request)).not.toContain("# ZCode Desktop Context");
  651. }
  652. });
  653. });