import { describe, expect, it } from "vitest"; import { createTestModelSelection } from "./test-model-selection.js"; import { createModelId, createModelProviderId, createSessionId, modelMessageContentToText, } from "@zcode/contracts"; import { createTestAgentRuntime } from "./test-agent-runtime.js"; import { buildPersistentAgentMemoryPrompt } from "../src/subagent/persistent-memory-prompt.js"; import { resolvePersistentAgentMemoryRoot } from "../src/subagent/persistent-memory.js"; import { createSubagentContextBuilder } from "../src/subagent/context-builder.js"; import { MemoryFileSystem } from "./memory-test-utils.js"; import { createTestSessionEventStore } from "./test-event-store.js"; import { createTestModelFactory } from "./test-runtime-model.js"; function createMainModelSelection() { return { providerId: createModelProviderId("anthropic"), modelId: createModelId("claude-haiku-4-5-20251001-cc"), }; } const USER_AGENTS_INSTRUCTION = "User AGENTS instruction sentinel."; const WORKSPACE_AGENTS_INSTRUCTION = "Workspace AGENTS instruction sentinel."; const PROJECT_CONTEXT_SENTINEL = "subagent-project-context-leak-sentinel"; function createParentContextSourcePort() { return { async resolveContextSources(request: { currentDate?: string; envInfo?: { cwd: string; platform: string; shell: string; osVersion: string; nodeVersion: string; isGitRepository?: boolean; }; workingDirectory: string; }) { return { workingDirectory: request.workingDirectory, currentDate: request.currentDate, diagnostics: [], envInfo: request.envInfo ?? { cwd: request.workingDirectory, platform: "darwin", shell: "zsh", osVersion: "Darwin 24.3.0", nodeVersion: "24.14.0", }, userInstructions: { filePath: "/repo/AGENTS.md", fileName: "AGENTS.md", content: WORKSPACE_AGENTS_INSTRUCTION, bytesRead: WORKSPACE_AGENTS_INSTRUCTION.length, sizeBytes: WORKSPACE_AGENTS_INSTRUCTION.length, truncated: false, sources: [ { scope: "user" as const, filePath: "/Users/test/.zcode/AGENTS.md", fileName: "AGENTS.md", content: USER_AGENTS_INSTRUCTION, bytesRead: USER_AGENTS_INSTRUCTION.length, sizeBytes: USER_AGENTS_INSTRUCTION.length, truncated: false, }, { scope: "workspace" as const, filePath: "/repo/AGENTS.md", fileName: "AGENTS.md", content: WORKSPACE_AGENTS_INSTRUCTION, bytesRead: WORKSPACE_AGENTS_INSTRUCTION.length, sizeBytes: WORKSPACE_AGENTS_INSTRUCTION.length, truncated: false, }, ], }, projectContext: { type: "node" as const, scripts: { [PROJECT_CONTEXT_SENTINEL]: "must-not-appear" }, }, }; }, }; } function systemContents(request: any): string[] { return systemMessages(request).map((message: any) => message.content); } function systemMessages(request: any): any[] { return request.messages.filter((message: any) => message.role === "system"); } function expectSystemMessagesCached(request: any): void { for (const message of systemMessages(request)) { expect(message.cacheControl).toEqual({ type: "ephemeral" }); } } function allMessageText(request: any): string { return request.messages .map((message: any) => modelMessageContentToText(message.content)) .join("\n"); } function countOccurrences(text: string, value: string): number { return text.split(value).length - 1; } function expectInjectedAgentsMd(request: any, childTask: string): void { const messages = request.messages as any[]; const contextIndex = messages.findIndex( (message) => message.role === "user" && modelMessageContentToText(message.content).includes(USER_AGENTS_INSTRUCTION), ); const taskIndex = messages.findIndex( (message) => message.role === "user" && modelMessageContentToText(message.content) === childTask, ); expect(contextIndex).toBeGreaterThanOrEqual(0); expect(taskIndex).toBeGreaterThan(contextIndex); const contextText = modelMessageContentToText(messages[contextIndex]?.content); expect(contextText).toContain(""); expect(contextText).toContain("# agentsMd"); expect(contextText).toContain("Codebase and user instructions are shown below."); expect(contextText).toContain(USER_AGENTS_INSTRUCTION); expect(contextText).toContain(WORKSPACE_AGENTS_INSTRUCTION); expect(contextText.indexOf(USER_AGENTS_INSTRUCTION)).toBeLessThan( contextText.indexOf(WORKSPACE_AGENTS_INSTRUCTION), ); expect(contextText.indexOf("# agentsMd")).toBeLessThan( contextText.indexOf(USER_AGENTS_INSTRUCTION), ); expect(contextText.indexOf(WORKSPACE_AGENTS_INSTRUCTION)).toBeLessThan( contextText.indexOf("# currentDate"), ); const text = allMessageText(request); expect(countOccurrences(text, "# agentsMd")).toBe(1); expect(text).not.toContain("# claudeMd"); expect(countOccurrences(text, USER_AGENTS_INSTRUCTION)).toBe(1); expect(countOccurrences(text, WORKSPACE_AGENTS_INSTRUCTION)).toBe(1); expect(text).not.toContain(PROJECT_CONTEXT_SENTINEL); expect(text).not.toContain("# Memory"); expect(systemContents(request).join("\n")).not.toContain(USER_AGENTS_INSTRUCTION); expect(systemContents(request).join("\n")).not.toContain(WORKSPACE_AGENTS_INSTRUCTION); expect(systemContents(request).join("\n")).not.toContain("# agentsMd"); } function expectNoInjectedAgentsMd(request: any): void { const text = allMessageText(request); expect(text).not.toContain("# agentsMd"); expect(text).not.toContain("# claudeMd"); expect(text).not.toContain(USER_AGENTS_INSTRUCTION); expect(text).not.toContain(WORKSPACE_AGENTS_INSTRUCTION); expect(text).not.toContain(PROJECT_CONTEXT_SENTINEL); } describe("subagent provider-visible prompt assembly", () => { it("assembles Explore child system messages with ZCode prefix, agent prompt, notes, and environment context", async () => { const sessionId = createSessionId("subagent-prompt-explore"); const eventStore = createTestSessionEventStore(); const childRequests: any[] = []; let parentCallCount = 0; const runtime = createTestAgentRuntime( sessionId, { mode: "build", modelSelection: createTestModelSelection(createMainModelSelection()), bashShellSelection: { dialect: "git-bash", display: { name: "Git Bash" }, path: "C:\\Program Files\\Git\\bin\\bash.exe", source: "user-config", }, workingDirectory: "/Users/dev/Desktop/Z/z-code/apps/zcode-cli", currentDate: "2026-06-04", envInfo: { cwd: "/Users/dev/Desktop/Z/z-code/apps/zcode-cli", platform: "darwin", shell: "zsh", osVersion: "Darwin 24.3.0", nodeVersion: "24.14.0", isGitRepository: true, }, }, { contextSourcePort: createParentContextSourcePort(), eventStore, modelFactory: createTestModelFactory({ properties: { supportsNativeWebSearch: true }, async generateText(request: any) { const toolNames = (request.tools ?? []).map((tool: any) => tool.name); if (toolNames.includes("Agent")) { parentCallCount++; if (parentCallCount === 1) { return { finishReason: "tool-calls", text: "", toolCalls: [ { id: "call_explore", name: "Agent", input: { description: "Find runtime loop", prompt: "Find where the runtime injects tool results.", subagent_type: "Explore", }, }, ], usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 }, }; } return { finishReason: "stop", text: "parent used explore result", usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 }, }; } childRequests.push(request); return { finishReason: "stop", text: "Explore found the runtime path.", usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 }, }; }, } as never), }, ); await runtime.executeTurn("Use an explore agent for this question"); expect(childRequests).toHaveLength(1); expectSystemMessagesCached(childRequests[0]); const systems = systemContents(childRequests[0]); expect(systems).toHaveLength(2); expect(systems.map((content) => content.endsWith("\n"))).toEqual([false, false]); expect(systems[0]).toBe("You are ZCode, an interactive coding agent"); expect(systems[1]).toMatch(/^\nYou are ZCode Explore/u); expect(systems[1]).toContain("READ-ONLY MODE"); expect(systems[1]).toContain("\n\nNotes:"); expect(systems[1]).toContain("Agent threads always have their cwd reset between bash calls"); expect(systems[1]).toContain("the parent agent reads your text output"); expect(systems[1]).toContain( "\n\nHere is useful information about the environment you are running in:", ); expect(systems[1]).toContain( "Working directory: /Users/dev/Desktop/Z/z-code/apps/zcode-cli", ); expect(systems[1]).toContain("Is directory a git repo: Yes"); expect(systems[1]).toContain("Platform: darwin"); expect(systems[1]).toContain("Shell: Git Bash"); expect(systems[1]).toContain("OS Version: Darwin 24.3.0"); expect(systems[1]).toContain( "You are powered by the model named anthropic/claude-haiku-4-5-20251001-cc.", ); const text = allMessageText(childRequests[0]); expect(text).not.toContain( "You help the user with software engineering work in the current workspace.", ); expect(text).not.toContain("# user_instructions"); expect(text).not.toContain("Project context:"); expectNoInjectedAgentsMd(childRequests[0]); }); it("adds common notes and environment context to general-purpose child prompts", async () => { const sessionId = createSessionId("subagent-prompt-general-purpose"); const eventStore = createTestSessionEventStore(); const childRequests: any[] = []; let parentCallCount = 0; const runtime = createTestAgentRuntime( sessionId, { mode: "build", modelSelection: createTestModelSelection(createMainModelSelection()), presentationSurface: "zcode_desktop", workingDirectory: "/repo/current", currentDate: "2026-06-04", envInfo: { cwd: "/repo/initial", platform: "darwin", shell: "zsh", osVersion: "Darwin 24.3.0", nodeVersion: "24.14.0", isGitRepository: true, }, }, { contextSourcePort: createParentContextSourcePort(), eventStore, modelFactory: createTestModelFactory({ properties: { supportsNativeWebSearch: true }, async generateText(request: any) { const toolNames = (request.tools ?? []).map((tool: any) => tool.name); if (toolNames.includes("Agent")) { parentCallCount++; if (parentCallCount === 1) { return { finishReason: "tool-calls", text: "", toolCalls: [ { id: "call_general", name: "Agent", input: { description: "Research runtime", prompt: "Research how child runtimes are created.", }, }, ], usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 }, }; } return { finishReason: "stop", text: "parent used general result", usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 }, }; } childRequests.push(request); return { finishReason: "stop", text: "General-purpose agent found the runtime path.", usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 }, }; }, } as never), }, ); await runtime.executeTurn("Use a general-purpose agent for this question"); expect(childRequests).toHaveLength(1); expectSystemMessagesCached(childRequests[0]); const systems = systemContents(childRequests[0]); expect(systems).toHaveLength(2); expect(systems[0]).toBe("You are ZCode, an interactive coding agent"); expect(systems[1]).toContain("You are an agent for ZCode CLI"); expect(systems[1]).toContain("Complete the task fully—don't gold-plate"); expect(systems[1]).toContain("the caller will relay this to the user"); expect(systems[1]).not.toContain("fully--don't gold-plate"); expect(systems[1]).not.toContain("key findings; the caller"); expect(systems[1]).toContain("Agent threads always have their cwd reset between bash calls"); expect(systems[1]).toContain("Working directory: /repo/current"); expect(systems[1]).not.toContain("Working directory: /repo/initial"); expectInjectedAgentsMd(childRequests[0], "Research how child runtimes are created."); }); it.each([ { expectedToInject: true, injectAgentsMd: undefined, label: "missing default" }, { expectedToInject: false, injectAgentsMd: false, label: "explicit false" }, ])( "assembles custom child prompts with $label AGENTS.md injection", async ({ expectedToInject, injectAgentsMd, label }) => { const sessionId = createSessionId(`subagent-prompt-custom-${label.replace(/\s+/gu, "-")}`); const eventStore = createTestSessionEventStore(); const childRequests: any[] = []; let parentCallCount = 0; const runtime = createTestAgentRuntime( sessionId, { mode: "build", modelSelection: createTestModelSelection(createMainModelSelection()), workingDirectory: "/repo", currentDate: "2026-06-04", envInfo: { cwd: "/repo", platform: "darwin", shell: "zsh", osVersion: "Darwin 24.3.0", nodeVersion: "24.14.0", isGitRepository: false, }, subagents: { profiles: [ { name: "code-researcher", description: "Research code paths.", color: "blue", source: "user", systemPrompt: "You are a focused code researcher. Return concise findings.", tools: ["Read", "Grep", "Glob"], ...(injectAgentsMd === undefined ? {} : { injectAgentsMd }), }, ], }, }, { contextSourcePort: createParentContextSourcePort(), eventStore, modelFactory: createTestModelFactory({ properties: { supportsNativeWebSearch: true }, async generateText(request: any) { const toolNames = (request.tools ?? []).map((tool: any) => tool.name); if (toolNames.includes("Agent")) { parentCallCount++; if (parentCallCount === 1) { return { finishReason: "tool-calls", text: "", toolCalls: [ { id: "call_custom", name: "Agent", input: { description: "Research custom", prompt: "Research the custom profile path.", subagent_type: "code-researcher", }, }, ], usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 }, }; } return { finishReason: "stop", text: "parent used custom result", usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 }, }; } childRequests.push(request); return { finishReason: "stop", text: "Custom agent found the runtime path.", usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 }, }; }, } as never), }, ); await runtime.executeTurn("Use the custom researcher agent for this question"); expect(childRequests).toHaveLength(1); expectSystemMessagesCached(childRequests[0]); const systems = systemContents(childRequests[0]); expect(systems).toHaveLength(2); expect(systems[0]).toBe("You are ZCode, an interactive coding agent"); expect(systems[1]).toMatch( /^\nYou are a focused code researcher\. Return concise findings\.\n\nNotes:/u, ); expect(systems[1]).toContain("Is directory a git repo: No"); if (expectedToInject) { expectInjectedAgentsMd(childRequests[0], "Research the custom profile path."); } else { expectNoInjectedAgentsMd(childRequests[0]); } }, ); it("keeps Notes and environment in one body when a custom child prompt is empty", () => { const result = createSubagentContextBuilder({ agentPrompt: "", envInfo: { cwd: "/repo", platform: "darwin", shell: "zsh", osVersion: "Darwin 24.3.0", nodeVersion: "24.14.0", isGitRepository: false, }, }).build(); expectSystemMessagesCached({ messages: result.systemMessages }); const systems = systemContents({ messages: result.systemMessages }); expect(systems).toHaveLength(2); expect(systems[0]).toBe("You are ZCode, an interactive coding agent"); expect(systems[1]).toMatch(/^\n\nNotes:/u); expect(systems[1]).toContain( "\n\nHere is useful information about the environment you are running in:", ); expect(systems).not.toContain("\n"); expect(systems.join("")).toBe( result.sections .filter((section) => section.injectionTarget === "system") .map((section) => section.content) .join(""), ); }); it.each(["user", "project", "local"] as const)( "projects exact %s persistent memory context and supported write tools to a custom child", async (scope) => { const sessionId = createSessionId(`subagent-prompt-persistent-memory-${scope}`); const eventStore = createTestSessionEventStore(); const memoryRoot = resolvePersistentAgentMemoryRoot({ agentName: "persistent-reviewer", scope, storageRoot: "/storage", workspaceRoot: "/repo", }); const fileSystemPort = new MemoryFileSystem({ [`${memoryRoot}/MEMORY.md`]: "- [Review style](review-style.md) — keep reviews concise", }); const parentRequests: any[] = []; const childRequests: any[] = []; let parentCallCount = 0; const runtime = createTestAgentRuntime( sessionId, { memory: { enabled: true, storageRoot: "/storage", use: true }, mode: "build", modelSelection: createTestModelSelection(createMainModelSelection()), workingDirectory: "/repo", currentDate: "2026-06-04", envInfo: { cwd: "/repo", platform: "darwin", shell: "zsh", osVersion: "Darwin 24.3.0", nodeVersion: "24.14.0", isGitRepository: false, }, subagents: { profiles: [ { name: "persistent-reviewer", description: "Review with durable context.", disallowedTools: ["Edit"], memory: scope, source: "user", systemPrompt: "", tools: ["Grep"], }, ], }, }, { eventStore, fileSystemPort, modelFactory: createTestModelFactory({ properties: { supportsNativeWebSearch: true }, async generateText(request: any) { const toolNames = (request.tools ?? []).map((tool: any) => tool.name); if (toolNames.includes("Agent")) { parentRequests.push(request); parentCallCount += 1; if (parentCallCount === 1) { return { finishReason: "tool-calls", text: "", toolCalls: [ { id: "call_persistent", name: "Agent", input: { description: "Review persistent", prompt: "Review using the persistent context.", subagent_type: "persistent-reviewer", }, }, ], usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 }, }; } return { finishReason: "stop", text: "parent used persistent review", usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 }, }; } childRequests.push(request); if (childRequests.length === 1) { return { finishReason: "tool-calls", text: "", toolCalls: [ { id: "write_persistent_memory", name: "Write", input: { content: "Keep reviews concise.", file_path: `${memoryRoot}/review-style.md`, }, }, ], usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 }, }; } return { finishReason: "stop", text: "Persistent reviewer completed.", usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 }, }; }, } as never), }, ); await runtime.executeTurn("review"); expect(childRequests).toHaveLength(2); const expectedMemoryPrompt = buildPersistentAgentMemoryPrompt({ indexContent: "- [Review style](review-style.md) — keep reviews concise", rootDir: memoryRoot, scope, }); expect(systemContents(childRequests[0])[1]?.split("\n\nNotes:")[0]).toBe( `\n${expectedMemoryPrompt}`, ); const childToolNames = childRequests[0].tools.map((tool: any) => tool.name); expect(childToolNames).toContain("Grep"); expect(childToolNames).toContain("Write"); expect(childToolNames).not.toContain("Edit"); expect(childToolNames).not.toContain("Read"); expect(fileSystemPort.createdDirectories).toContain(memoryRoot); expect(fileSystemPort.files[`${memoryRoot}/review-style.md`]).toBe("Keep reviews concise."); expect( parentRequests[0].messages .map((message: any) => modelMessageContentToText(message.content)) .join("\n"), ).toContain("Tools: Grep, Write"); }, ); it("keeps subagent context builder output after runtime context refresh", async () => { const sessionId = createSessionId("subagent-prompt-refresh"); const eventStore = createTestSessionEventStore(); const requests: any[] = []; const runtime = createTestAgentRuntime( sessionId, { mode: "build", modelSelection: createTestModelSelection(createMainModelSelection()), workingDirectory: "/repo/current", currentDate: "2026-06-04", envInfo: { cwd: "/repo/current", platform: "darwin", shell: "zsh", osVersion: "Darwin 24.3.0", nodeVersion: "24.14.0", isGitRepository: true, }, subagentContext: { agentPrompt: "You are a focused child agent. Keep the result concise.", }, taskType: "subagent_child", }, { eventStore, modelFactory: createTestModelFactory({ properties: { supportsNativeWebSearch: true }, async generateText(request: any) { requests.push(request); return { finishReason: "stop", text: `child response ${requests.length}`, usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 }, }; }, } as never), }, ); await runtime.executeTurn("first child request"); runtime.updateConfig({ language: "zh-CN" }); await runtime.executeTurn("second child request after refresh"); expect(requests).toHaveLength(2); for (const request of requests) { expectSystemMessagesCached(request); const systems = systemContents(request); expect(systems).toHaveLength(2); expect(systems[0]).toBe("You are ZCode, an interactive coding agent"); expect(systems[1]).toMatch( /^\nYou are a focused child agent\. Keep the result concise\.\n\nNotes:/u, ); expect(systems[1]).toContain("Agent threads always have their cwd reset between bash calls"); expect(systems[1]).toContain("Working directory: /repo/current"); expect(systems[1]).toContain( "You are powered by the model named anthropic/claude-haiku-4-5-20251001-cc.", ); expect(allMessageText(request)).not.toContain( "You help the user with software engineering work in the current workspace.", ); expect(allMessageText(request)).not.toContain("# ZCode Desktop Context"); } }); });