@aaac/runtime 0.1.52 → 0.1.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/adapters/adk-sdk.d.ts +1 -1
  2. package/dist/adapters/adk-sdk.js +1 -1
  3. package/dist/adapters/claude-agent-sdk.d.ts +1 -1
  4. package/dist/adapters/mock.d.ts +1 -1
  5. package/dist/adapters/openai-agents-sdk.d.ts +1 -1
  6. package/dist/{chunk-YZQRSVDZ.js → chunk-3H3PVPPF.js} +198 -4
  7. package/dist/chunk-3H3PVPPF.js.map +1 -0
  8. package/dist/chunk-LDCQZPDG.js +11 -0
  9. package/dist/chunk-LDCQZPDG.js.map +1 -0
  10. package/dist/{chunk-C6XCN33A.js → chunk-N4KNGDYY.js} +344 -28
  11. package/dist/chunk-N4KNGDYY.js.map +1 -0
  12. package/dist/{chunk-EH5VFZYJ.js → chunk-NMX4C6LC.js} +6 -2
  13. package/dist/chunk-NMX4C6LC.js.map +1 -0
  14. package/dist/{chunk-4OMCAGNY.js → chunk-QVH5KKBR.js} +57 -2
  15. package/dist/{chunk-4OMCAGNY.js.map → chunk-QVH5KKBR.js.map} +1 -1
  16. package/dist/claude-bundles/full.js +223 -217
  17. package/dist/claude-bundles/lean.js +6 -6
  18. package/dist/generator/index.d.ts +2 -286
  19. package/dist/generator/index.js +1 -1
  20. package/dist/index-LqEvaRk-.d.ts +299 -0
  21. package/dist/index.d.ts +29 -17
  22. package/dist/index.js +75 -412
  23. package/dist/index.js.map +1 -1
  24. package/dist/lib/claude-native/hooks-lite.d.ts +18 -306
  25. package/dist/lib/claude-native/hooks-lite.js +8 -2
  26. package/dist/lib/claude-native/index.d.ts +153 -20
  27. package/dist/lib/claude-native/index.js +170 -36
  28. package/dist/lib/claude-native/index.js.map +1 -1
  29. package/dist/navigation-context-D_E1NIUf.d.ts +41 -0
  30. package/dist/{task-runner-Sez_CXcD.d.ts → task-runner-CLc8iTzy.d.ts} +5 -8
  31. package/dist/workspace-pre-tool-use-C6nidc0q.d.ts +333 -0
  32. package/package.json +2 -1
  33. package/dist/chunk-C6XCN33A.js.map +0 -1
  34. package/dist/chunk-EH5VFZYJ.js.map +0 -1
  35. package/dist/chunk-YZQRSVDZ.js.map +0 -1
  36. package/dist/navigation-context-BE1KHJ_8.d.ts +0 -22
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/candidate-agents.ts","../src/lib/analyzer-bridge.ts","../src/lib/process-axis-bridge.ts","../src/lib/task-runner.ts","../src/lib/model-pricing.ts","../src/lib/artifact-resolver.ts","../src/lib/dsl-context.ts","../src/lib/bound-resolver.ts","../src/lib/navigation-context.ts"],"sourcesContent":["/**\n * Candidate Agents — backend-neutral bridge for LLM-internal routing (model B)\n *\n * The runtime registers a set of *candidate sub-agents* with the SDK so the\n * entry/main agent's LLM can delegate to them internally via the SDK's native\n * subagent mechanism:\n *\n * - Claude `Options.agents: Record<string, AgentDefinition>`\n * - OpenAI `Agent.handoffs: Agent[]`\n * - ADK `LlmAgent.subAgents: BaseAgent[]`\n *\n * `CandidateAgent` is the common, SDK-independent contract. Each adapter maps it\n * onto its provider's native shape. The selection rule (which agents become\n * candidates) lives here so all adapters stay backend-agnostic.\n */\n\nimport type { ResolvedToolchain } from \"./bound-resolver.js\";\nimport type { AgentContractLike } from \"./task-runner.js\";\n\n/**\n * SDK-independent description of a sub-agent the entry agent's LLM may delegate\n * to. Adapters translate this into their provider's native subagent shape.\n */\nexport interface CandidateAgent {\n /** Agent id (used as the SDK subagent key / name). */\n name: string;\n /** When to use this agent — the routing hint shown to the delegating LLM. */\n description: string;\n /** The agent's system prompt (role / purpose / responsibilities / constraints / rules). */\n prompt: string;\n /** Optional allowed tool names (omit to inherit from the parent agent). */\n tools?: string[];\n /** Optional model id (omit to inherit from the parent agent). */\n model?: string;\n}\n\n/**\n * Render an agent contract into its system-prompt string: the static\n * Role / Responsibilities / Constraints / Rules sections.\n *\n * Shared by `buildSplitTaskPrompt` (entry agent system prompt) and\n * `buildCandidateAgents` (each candidate's `prompt`) so both stay in sync.\n */\nexport function renderAgentSystemPrompt(agent: AgentContractLike): string {\n const sections: string[] = [];\n\n sections.push(`# Role: ${agent.role_name}\\n\\n${agent.purpose}`);\n\n if (agent.responsibilities.length > 0) {\n sections.push(\n `## Responsibilities\\n\\n${agent.responsibilities.map((r) => `- ${r}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.constraints.length > 0) {\n sections.push(\n `## Constraints\\n\\n${agent.constraints.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.rules && agent.rules.length > 0) {\n const ruleLines = agent.rules.map(\n (r) => `- **${r.id}** [${r.severity}]: ${r.description}`,\n );\n sections.push(`## Rules\\n\\n${ruleLines.join(\"\\n\")}`);\n }\n\n return sections.join(\"\\n\\n\");\n}\n\n/** Derive a concise routing description (first sentence/line) from a purpose. */\nfunction deriveDescription(purpose: string): string {\n const firstLine = purpose.split(\"\\n\").map((l) => l.trim()).find((l) => l.length > 0) ?? \"\";\n // Prefer the first sentence when the line packs several together.\n const sentenceEnd = firstLine.search(/[.!?](\\s|$)/);\n if (sentenceEnd !== -1) {\n return firstLine.slice(0, sentenceEnd + 1).trim();\n }\n return firstLine;\n}\n\nexport interface BuildCandidateAgentsOptions {\n /** The entry/main agent id. Excluded from the candidate set. */\n entryAgentId?: string;\n /**\n * When provided (typically the entry agent's `can_invoke_agents`), restrict\n * candidates to these agent ids. Omit to allow every non-entry agent.\n */\n allowedAgentIds?: readonly string[];\n toolchainsByAgent?: Map<string, ResolvedToolchain[]>;\n}\n\n/**\n * Build the candidate sub-agent set from an agent registry.\n *\n * Selection rule: every agent EXCEPT the entry agent; if `allowedAgentIds` is\n * given, further restrict to that allow-list.\n */\nexport function buildCandidateAgents(\n agentRegistry: Record<string, AgentContractLike>,\n opts?: BuildCandidateAgentsOptions,\n): CandidateAgent[] {\n const entryId = opts?.entryAgentId;\n const allowed = opts?.allowedAgentIds;\n const allowSet = allowed ? new Set(allowed) : undefined;\n\n const candidates: CandidateAgent[] = [];\n for (const [id, agent] of Object.entries(agentRegistry)) {\n if (id === entryId) continue;\n if (allowSet && !allowSet.has(id)) continue;\n\n const agentTools = agent.can_execute_tools ? [...agent.can_execute_tools] : [];\n const derivedToolchains = opts?.toolchainsByAgent?.get(id);\n if (derivedToolchains) {\n for (const tc of derivedToolchains) {\n if (!agentTools.includes(tc.id)) {\n agentTools.push(tc.id);\n }\n }\n }\n\n candidates.push({\n name: id,\n description: deriveDescription(agent.purpose),\n prompt: renderAgentSystemPrompt(agent),\n ...(agentTools.length > 0 ? { tools: agentTools } : {}),\n });\n }\n return candidates;\n}\n","/**\n * Analyzer Bridge — integrates artifact-contracts-analyzer as a standard\n * runtime tool provider.\n *\n * Wraps analyzeImpact, generateContextPack, and buildCallGraph behind a\n * lazily-initialised DependencyGraph, and exposes them as SdkFunctionTool[]\n * for adapter consumption.\n *\n * `artifact-contracts-analyzer` is a peerDependency (optional) loaded via\n * dynamic import; when absent, every method returns a descriptive error\n * rather than crashing.\n */\n\nimport type { SdkFunctionTool } from \"./library-tool-sdk.js\";\n\n// ---------------------------------------------------------------------------\n// Re-exported duck types — the bridge never statically imports the analyzer\n// package, so we define the minimal shapes callers need.\n// ---------------------------------------------------------------------------\n\n/** Subset of DependencyGraph that the bridge caches and exposes. */\nexport type DependencyGraph = Record<string, unknown>;\n\n/** Subset of ImpactReport returned by analyzeImpact. */\nexport type ImpactReport = Record<string, unknown>;\n\n/** Subset of ContextPack returned by generateContextPack. */\nexport type ContextPack = {\n entries: Array<{\n path: string;\n artifactId?: string;\n relevanceScore: number;\n contentMode: string;\n content: string;\n reason: string;\n }>;\n metadata: {\n totalTokens: number;\n budgetTokens: number;\n filesIncluded: number;\n filesExcluded: number;\n filesReferenced: number;\n artifactsCovered: string[];\n generatedAt: string;\n };\n taskId?: string;\n};\n\n/** Subset of CallGraph returned by buildCallGraph. */\nexport type CallGraph = Record<string, unknown>;\n\n/** Subset of ContextMap returned by getContextMap. */\nexport type ContextMap = Record<string, unknown>;\n\nexport interface GetContextMapInput {\n instruction: string;\n candidates: Array<{\n path?: string;\n symbolId?: string;\n artifactId?: string;\n }>;\n depth?: number;\n direction?: \"downstream\" | \"upstream\" | \"both\";\n budgetTokens?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Bridge options and interface\n// ---------------------------------------------------------------------------\n\nexport interface AnalyzerBridgeOptions {\n projectRoot: string;\n navigationIndex?: Record<string, unknown>;\n artifactPatterns?: Map<string, string[]>;\n manifests?: string[];\n}\n\nexport interface AnalyzeImpactInput {\n direction: \"downstream\" | \"upstream\";\n maxDepth: number;\n limit: number;\n}\n\nexport interface GenerateContextPackInput {\n budgetTokens: number;\n granularity: \"file\" | \"symbol\";\n}\n\nexport interface BuildCallGraphInput {\n maxDepth: number;\n direction: \"forward\" | \"reverse\";\n}\n\nexport interface AnalyzerBridge {\n buildGraph(): Promise<void>;\n getGraph(): Promise<DependencyGraph>;\n analyzeImpact(\n changed: string[],\n options?: Partial<AnalyzeImpactInput>,\n ): Promise<ImpactReport>;\n generateContextPack(\n changed: string[],\n options?: Partial<GenerateContextPackInput>,\n ): Promise<ContextPack>;\n buildCallGraph(\n entry: string,\n options?: Partial<BuildCallGraphInput>,\n ): Promise<CallGraph>;\n getContextMap(\n input: GetContextMapInput,\n ): Promise<ContextMap>;\n invalidateCache(): void;\n buildAnalyzerTools(): SdkFunctionTool[];\n}\n\n// ---------------------------------------------------------------------------\n// Dynamic import helper\n// ---------------------------------------------------------------------------\n\ninterface AnalyzerModule {\n buildAstGraph: (options: Record<string, unknown>) => Promise<{ graph: Record<string, unknown>; fileContents: Map<string, string> }>;\n buildDependencyGraph: (options: Record<string, unknown>) => Promise<DependencyGraph>;\n analyzeImpact: (options: Record<string, unknown>) => Promise<ImpactReport>;\n generateContextPack: (options: Record<string, unknown>) => Promise<ContextPack>;\n getContextMap: (options: Record<string, unknown>) => Promise<ContextMap>;\n buildCallGraph: (options: Record<string, unknown>) => CallGraph;\n createDefaultRegistry: () => Record<string, unknown>;\n loadExternalProviders?: (projectRoot: string, configPath?: string) => Promise<unknown[]>;\n integrateExternalInsights?: (\n graph: DependencyGraph,\n providers: unknown[],\n query: Record<string, unknown>,\n ) => Promise<{ graph: DependencyGraph }>;\n}\n\nconst ANALYZER_PKG = \"artifact-contracts-analyzer\";\n\nasync function loadAnalyzerModule(): Promise<AnalyzerModule> {\n const mod = (await import(\n /* webpackIgnore: true */ ANALYZER_PKG\n )) as Record<string, unknown>;\n return mod as unknown as AnalyzerModule;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nexport function createAnalyzerBridge(\n options: AnalyzerBridgeOptions,\n): AnalyzerBridge {\n const { projectRoot, navigationIndex, artifactPatterns, manifests } = options;\n\n let cachedGraph: DependencyGraph | null = null;\n let cachedFileContents: Map<string, string> | null = null;\n let graphBuildPromise: Promise<void> | null = null;\n\n async function ensureGraph(): Promise<DependencyGraph> {\n if (cachedGraph) return cachedGraph;\n if (graphBuildPromise) {\n await graphBuildPromise;\n return cachedGraph!;\n }\n graphBuildPromise = doBuildGraph();\n await graphBuildPromise;\n return cachedGraph!;\n }\n\n async function doBuildGraph(): Promise<void> {\n let mod: AnalyzerModule;\n try {\n mod = await loadAnalyzerModule();\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n throw new Error(\n `artifact-contracts-analyzer is not available. ` +\n `Install it to use analyzer features: ${msg}`,\n );\n }\n\n const patterns = artifactPatterns ?? new Map<string, string[]>();\n const registry = mod.createDefaultRegistry();\n\n const astResult = await mod.buildAstGraph({\n projectRoot,\n artifactPatterns: patterns,\n registry,\n });\n\n cachedFileContents = astResult.fileContents;\n\n cachedGraph = await mod.buildDependencyGraph({\n ast: astResult.graph,\n projectRoot,\n artifactPatterns: patterns,\n manifests: manifests ?? [],\n });\n\n if (\n typeof (mod as { loadExternalProviders?: unknown }).loadExternalProviders ===\n \"function\" &&\n typeof (mod as { integrateExternalInsights?: unknown })\n .integrateExternalInsights === \"function\"\n ) {\n try {\n const loadProviders = (\n mod as {\n loadExternalProviders: (\n projectRoot: string,\n ) => Promise<unknown[]>;\n }\n ).loadExternalProviders;\n const integrate = (\n mod as {\n integrateExternalInsights: (\n graph: DependencyGraph,\n providers: unknown[],\n query: Record<string, unknown>,\n ) => Promise<{ graph: DependencyGraph }>;\n }\n ).integrateExternalInsights;\n const providers = await loadProviders(projectRoot);\n if (providers.length > 0) {\n const integration = await integrate(\n cachedGraph,\n providers,\n { projectRoot },\n );\n cachedGraph = integration.graph;\n }\n } catch {\n // External providers are optional — fail open.\n }\n }\n }\n\n const bridge: AnalyzerBridge = {\n async buildGraph(): Promise<void> {\n await ensureGraph();\n },\n\n async getGraph(): Promise<DependencyGraph> {\n return ensureGraph();\n },\n\n async analyzeImpact(\n changed: string[],\n opts?: Partial<AnalyzeImpactInput>,\n ): Promise<ImpactReport> {\n let mod: AnalyzerModule;\n try {\n mod = await loadAnalyzerModule();\n } catch {\n return {\n error:\n \"artifact-contracts-analyzer is not installed. Install it as a peer dependency to use impact analysis.\",\n changed,\n };\n }\n\n const graph = await ensureGraph();\n return mod.analyzeImpact({\n graph,\n changed,\n direction: opts?.direction ?? \"downstream\",\n ...(opts?.maxDepth !== undefined ? { maxDepth: opts.maxDepth } : {}),\n ...(opts?.limit !== undefined ? { limit: opts.limit } : {}),\n ...(navigationIndex ? { navigationIndex } : {}),\n });\n },\n\n async generateContextPack(\n changed: string[],\n opts?: Partial<GenerateContextPackInput>,\n ): Promise<ContextPack> {\n let mod: AnalyzerModule;\n try {\n mod = await loadAnalyzerModule();\n } catch {\n return {\n entries: [],\n metadata: {\n totalTokens: 0,\n budgetTokens: opts?.budgetTokens ?? 50_000,\n filesIncluded: 0,\n filesExcluded: 0,\n filesReferenced: 0,\n artifactsCovered: [],\n generatedAt: new Date().toISOString(),\n },\n } as ContextPack;\n }\n\n const graph = await ensureGraph();\n return mod.generateContextPack({\n graph,\n changed,\n projectRoot,\n ...(opts?.budgetTokens !== undefined\n ? { budgetTokens: opts.budgetTokens }\n : {}),\n ...(opts?.granularity ? { granularity: opts.granularity } : {}),\n ...(navigationIndex ? { navigationIndex } : {}),\n ...(cachedFileContents ? { fileContents: cachedFileContents } : {}),\n });\n },\n\n async buildCallGraph(\n entry: string,\n opts?: Partial<BuildCallGraphInput>,\n ): Promise<CallGraph> {\n let mod: AnalyzerModule;\n try {\n mod = await loadAnalyzerModule();\n } catch {\n return {\n error:\n \"artifact-contracts-analyzer is not installed. Install it as a peer dependency to use call graph analysis.\",\n entry,\n };\n }\n\n const graph = await ensureGraph();\n return mod.buildCallGraph({\n graph,\n entry,\n ...(opts?.maxDepth !== undefined ? { maxDepth: opts.maxDepth } : {}),\n ...(opts?.direction ? { direction: opts.direction } : {}),\n }) as CallGraph;\n },\n\n async getContextMap(input: GetContextMapInput): Promise<ContextMap> {\n let mod: AnalyzerModule;\n try {\n mod = await loadAnalyzerModule();\n } catch {\n return {\n error:\n \"artifact-contracts-analyzer is not installed. Install it as a peer dependency to use context map analysis.\",\n instruction: input.instruction,\n };\n }\n\n const graph = await ensureGraph();\n return mod.getContextMap({\n graph,\n projectRoot,\n instruction: input.instruction,\n candidates: input.candidates,\n ...(input.depth !== undefined ? { depth: input.depth } : {}),\n ...(input.direction ? { direction: input.direction } : {}),\n ...(input.budgetTokens !== undefined\n ? { budgetTokens: input.budgetTokens }\n : {}),\n ...(navigationIndex ? { navigationIndex } : {}),\n ...(cachedFileContents ? { fileContents: cachedFileContents } : {}),\n });\n },\n\n invalidateCache(): void {\n cachedGraph = null;\n cachedFileContents = null;\n graphBuildPromise = null;\n },\n\n buildAnalyzerTools(): SdkFunctionTool[] {\n return [\n {\n name: \"analyzer.analyzeImpact\",\n description:\n \"Analyze the impact of changed files across the dependency graph\",\n inputSchema: {\n type: \"object\",\n properties: {\n changed: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"File paths that changed\",\n },\n direction: {\n type: \"string\",\n enum: [\"downstream\", \"upstream\"],\n description:\n \"Traversal direction. downstream = what breaks if this changes\",\n },\n maxDepth: {\n type: \"number\",\n description: \"Maximum BFS depth to explore\",\n },\n limit: {\n type: \"number\",\n description:\n \"Cap the number of affected entries returned\",\n },\n },\n required: [\"changed\"],\n },\n handler: async (\n args: Record<string, unknown>,\n ): Promise<string> => {\n const changed = args.changed as string[];\n const result = await bridge.analyzeImpact(changed, {\n direction: args.direction as\n | \"downstream\"\n | \"upstream\"\n | undefined,\n maxDepth: args.maxDepth as number | undefined,\n limit: args.limit as number | undefined,\n });\n return JSON.stringify(result);\n },\n },\n {\n name: \"analyzer.generateContextPack\",\n description:\n \"Generate a token-budget-constrained context pack for changed files\",\n inputSchema: {\n type: \"object\",\n properties: {\n changed: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"File paths that changed\",\n },\n budgetTokens: {\n type: \"number\",\n description: \"Token budget for the context pack\",\n },\n granularity: {\n type: \"string\",\n enum: [\"file\", \"symbol\"],\n description: \"Context granularity level\",\n },\n },\n required: [\"changed\"],\n },\n handler: async (\n args: Record<string, unknown>,\n ): Promise<string> => {\n const changed = args.changed as string[];\n const result = await bridge.generateContextPack(changed, {\n budgetTokens: args.budgetTokens as number | undefined,\n granularity: args.granularity as\n | \"file\"\n | \"symbol\"\n | undefined,\n });\n return JSON.stringify(result);\n },\n },\n {\n name: \"analyzer.getContextMap\",\n description:\n \"Build a structured context map from instruction and candidate paths/artifacts/symbols\",\n inputSchema: {\n type: \"object\",\n properties: {\n instruction: {\n type: \"string\",\n description: \"Natural-language task instruction\",\n },\n candidates: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n symbolId: { type: \"string\" },\n artifactId: { type: \"string\" },\n },\n },\n description:\n \"Candidate seeds from navigation-index (paths, symbols, artifacts)\",\n },\n depth: {\n type: \"number\",\n description: \"Traversal depth (default 2)\",\n },\n direction: {\n type: \"string\",\n enum: [\"downstream\", \"upstream\", \"both\"],\n description: \"Impact traversal direction\",\n },\n budgetTokens: {\n type: \"number\",\n description: \"Token budget for suggested read targets\",\n },\n },\n required: [\"instruction\", \"candidates\"],\n },\n handler: async (\n args: Record<string, unknown>,\n ): Promise<string> => {\n const result = await bridge.getContextMap({\n instruction: args.instruction as string,\n candidates: args.candidates as GetContextMapInput[\"candidates\"],\n depth: args.depth as number | undefined,\n direction: args.direction as GetContextMapInput[\"direction\"],\n budgetTokens: args.budgetTokens as number | undefined,\n });\n return JSON.stringify(result);\n },\n },\n {\n name: \"analyzer.buildCallGraph\",\n description: \"Build a call graph rooted at a symbol\",\n inputSchema: {\n type: \"object\",\n properties: {\n entry: {\n type: \"string\",\n description:\n \"Entry symbolId (filePath#name) to root the call graph at\",\n },\n maxDepth: {\n type: \"number\",\n description: \"Maximum traversal depth\",\n },\n direction: {\n type: \"string\",\n enum: [\"forward\", \"reverse\"],\n description:\n \"Traversal direction: forward (callees) or reverse (callers)\",\n },\n },\n required: [\"entry\"],\n },\n handler: async (\n args: Record<string, unknown>,\n ): Promise<string> => {\n const entry = args.entry as string;\n const result = await bridge.buildCallGraph(entry, {\n maxDepth: args.maxDepth as number | undefined,\n direction: args.direction as\n | \"forward\"\n | \"reverse\"\n | undefined,\n });\n return JSON.stringify(result);\n },\n },\n ];\n },\n };\n\n return bridge;\n}\n\n// ---------------------------------------------------------------------------\n// ContextPack prompt rendering utilities\n// ---------------------------------------------------------------------------\n\n/**\n * Duck-type check: does `value` look like a ContextPack?\n * Checks for the `entries` array and `metadata` object with expected fields.\n */\nexport function isContextPack(value: unknown): value is ContextPack {\n if (typeof value !== \"object\" || value === null) return false;\n const obj = value as Record<string, unknown>;\n if (!Array.isArray(obj.entries)) return false;\n if (typeof obj.metadata !== \"object\" || obj.metadata === null) return false;\n const meta = obj.metadata as Record<string, unknown>;\n return (\n typeof meta.totalTokens === \"number\" &&\n typeof meta.budgetTokens === \"number\"\n );\n}\n\n/**\n * Render a ContextPack as a structured prompt section.\n * Used by task-runner when `variables.analyzerContextPack` is present.\n */\nexport function renderContextPackPrompt(pack: ContextPack): string {\n const m = pack.metadata;\n const sections: string[] = [];\n\n sections.push(\"## Source Code Context\");\n\n sections.push(\n `### Budget\\n- Tokens used: ${m.totalTokens} / ${m.budgetTokens}\\n` +\n `- Files included: ${m.filesIncluded}, excluded: ${m.filesExcluded}, referenced: ${m.filesReferenced}`,\n );\n\n if (m.artifactsCovered.length > 0) {\n sections.push(\n `### Affected Artifacts\\n${m.artifactsCovered.map((a) => `- ${a}`).join(\"\\n\")}`,\n );\n }\n\n if (pack.entries.length > 0) {\n const fileBlocks: string[] = [];\n for (const entry of pack.entries) {\n const ext = entry.path.split(\".\").pop() ?? \"\";\n const header = `#### ${entry.path} (relevance: ${entry.relevanceScore}, mode: ${entry.contentMode})`;\n const reason = `> ${entry.reason}`;\n if (entry.content) {\n fileBlocks.push(\n `${header}\\n${reason}\\n\\n\\`\\`\\`${ext}\\n${entry.content}\\n\\`\\`\\``,\n );\n } else {\n fileBlocks.push(`${header}\\n${reason}`);\n }\n }\n sections.push(`### Files\\n${fileBlocks.join(\"\\n\\n\")}`);\n }\n\n return sections.join(\"\\n\\n\");\n}\n","/**\n * Process axis emit helpers for runtime integration.\n * These wrap @aaac/observability's EventCollector for structured process axis events.\n */\n\nimport { generateId } from \"@aaac/observability\";\nimport type { AttrValue } from \"@aaac/observability\";\nimport type { ObserverEmitFn } from \"./observability-bridge.js\";\n\nexport interface ProcessWorkflowOptions {\n workflowId: string;\n sessionId: string;\n parentSpanId?: string;\n /** Optional observer — no-op when undefined. */\n observer?: ObserverEmitFn;\n}\n\nexport interface ProcessTaskOptions {\n taskId: string;\n targetAgent: string;\n sessionId: string;\n parentSpanId?: string;\n /** Optional observer — no-op when undefined. */\n observer?: ObserverEmitFn;\n}\n\nexport interface ProcessEditOptions {\n filePath: string;\n artifactId?: string;\n sessionId: string;\n parentSpanId?: string;\n /** Optional observer — no-op when undefined. */\n observer?: ObserverEmitFn;\n}\n\n/** Build attribute record; omits keys with undefined/empty-string values. */\nfunction attrs(base: Record<string, AttrValue | undefined>): Record<string, AttrValue> {\n const out: Record<string, AttrValue> = {};\n for (const [k, v] of Object.entries(base)) {\n if (v !== undefined && v !== \"\") out[k] = v;\n }\n return out;\n}\n\n/**\n * Tool names that mutate files on disk and therefore should produce a\n * process.edit event for cross-axis correlation (enrich R3/R5).\n *\n * Read/search/shell tools are intentionally excluded — only file writes count\n * as edits. Matched case-insensitively so adapter-specific casing variants\n * (Write/write, MultiEdit/multi_edit) are all recognised.\n */\nconst FILE_EDIT_TOOL_NAMES = new Set([\n \"write\",\n \"edit\",\n \"multiedit\",\n \"multi_edit\",\n \"notebookedit\",\n \"notebook_edit\",\n]);\n\n/**\n * True when a tool name denotes a file-mutating edit, so a process.edit event\n * should be emitted for it. Used by the task runner to instrument the Process\n * axis from live tool-use progress events (#167).\n */\nexport function isFileEditTool(toolName: string | undefined): boolean {\n if (!toolName) return false;\n return FILE_EDIT_TOOL_NAMES.has(toolName.toLowerCase());\n}\n\n/**\n * Emit process.workflow open span.\n */\nexport function emitProcessWorkflowOpen(options: ProcessWorkflowOptions): string | undefined {\n if (!options.observer) return undefined;\n\n const spanId = generateId();\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.workflow\",\n lifecycle: \"open\",\n spanId,\n parentSpanId: options.parentSpanId,\n attributes: attrs({\n axis: \"process\",\n \"agent.session_id\": options.sessionId,\n \"workflow.id\": options.workflowId,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit process.workflow close span.\n */\nexport function emitProcessWorkflowClose(\n spanId: string,\n options: { status: string; durationMs?: number; observer?: ObserverEmitFn },\n): void {\n if (!options.observer) return;\n\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.workflow\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"process\",\n \"workflow.status\": options.status,\n ...(options.durationMs !== undefined\n ? { \"workflow.duration_ms\": options.durationMs }\n : {}),\n }),\n });\n}\n\n/**\n * Emit process.task open span.\n */\nexport function emitProcessTaskOpen(options: ProcessTaskOptions): string | undefined {\n if (!options.observer) return undefined;\n\n const spanId = generateId();\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.task\",\n lifecycle: \"open\",\n spanId,\n parentSpanId: options.parentSpanId,\n attributes: attrs({\n axis: \"process\",\n \"agent.session_id\": options.sessionId,\n \"task.id\": options.taskId,\n \"task.type\": \"implement\",\n \"task.target_agent\": options.targetAgent,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit process.task close span.\n */\nexport function emitProcessTaskClose(\n spanId: string,\n options: { status: string; durationMs?: number; observer?: ObserverEmitFn },\n): void {\n if (!options.observer) return;\n\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.task\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"process\",\n \"task.status\": options.status,\n ...(options.durationMs !== undefined\n ? { \"task.duration_ms\": options.durationMs }\n : {}),\n }),\n });\n}\n\n/**\n * Emit process.edit instant span.\n */\nexport function emitProcessEdit(options: ProcessEditOptions): string | undefined {\n if (!options.observer) return undefined;\n\n const spanId = generateId();\n options.observer({\n source: \"aaac-runtime\",\n eventType: \"process.edit\",\n lifecycle: \"instant\",\n spanId,\n parentSpanId: options.parentSpanId,\n attributes: attrs({\n axis: \"process\",\n \"agent.session_id\": options.sessionId,\n \"edit.path\": options.filePath,\n \"edit.artifact_id\": options.artifactId,\n }),\n });\n return spanId;\n}\n","/**\n * Task Runner — runs a single DSL task via an SDK agent\n *\n * Responsibilities:\n * 1. Resolve task contract → target agent contract\n * 2. Build the agent prompt from contract + context\n * 3. Apply plugin prompt enhancers and beforeTask hooks\n * 4. Send to SDK agent (via abstract SdkAdapter) and stream result\n * 5. Parse + validate result against handoff schema\n * 6. Apply plugin afterTask hooks\n * 7. Return typed result or escalation signal\n *\n * Two recovery strategies:\n * - followUp: lightweight, same session — fix output format only\n * - retry: heavyweight, new session — re-execute entire task\n */\n\nimport { z } from \"zod\";\nimport * as yaml from \"yaml\";\n\nimport type { MemoryRef } from \"./memory-store.js\";\nimport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\nimport { pluginRegistry } from \"./plugin.js\";\nimport { buildCandidateAgents, renderAgentSystemPrompt, type CandidateAgent } from \"./candidate-agents.js\";\nimport { isContextPack, renderContextPackPrompt } from \"./analyzer-bridge.js\";\nimport {\n createExecutionEnvelope,\n emitSubagentOpen,\n emitSubagentClose,\n type ObserverEmitFn,\n type ExecutionEnvelope,\n type InnerSpanOptions,\n type TokenUsage,\n} from \"./observability-bridge.js\";\nimport { computeCostUsd } from \"./model-pricing.js\";\nimport {\n emitProcessTaskOpen,\n emitProcessTaskClose,\n emitProcessEdit,\n isFileEditTool,\n} from \"./process-axis-bridge.js\";\n\nexport type { MemoryRef } from \"./memory-store.js\";\nexport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\nexport type { CandidateAgent } from \"./candidate-agents.js\";\nexport { buildCandidateAgents, renderAgentSystemPrompt } from \"./candidate-agents.js\";\nexport type { ObserverEmitFn, ExecutionEnvelope, InnerSpanOptions, TokenUsage } from \"./observability-bridge.js\";\n\n// Duck-typed contracts so the runtime doesn't depend on generated shapes.\n\nexport interface AgentContractLike {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n readonly rules?: readonly { readonly id: string; readonly description: string; readonly severity: string }[];\n /**\n * Agent ids this agent is allowed to delegate to. When present, it restricts\n * the candidate sub-agent set registered with the SDK for LLM-internal routing.\n */\n readonly can_invoke_agents?: readonly string[];\n /**\n * Tool names this agent may execute. When present, sub-agents receive an\n * isolated tool set instead of inheriting the parent agent's tools.\n */\n readonly can_execute_tools?: readonly string[];\n}\n\nexport interface TaskContractLike {\n readonly id: string;\n readonly description: string;\n readonly target_agent: string;\n readonly result_handoff: string;\n readonly completion_criteria: readonly string[];\n readonly model_class?: \"fast\" | \"standard\" | \"thinking\";\n /**\n * When true, the adapter may enable Dynamic Workflow tools (e.g. Claude's\n * Workflow tool) so the agent can internally parallelise sub-tasks.\n * Handoff validation at the task boundary is still enforced.\n */\n readonly allow_dynamic_workflow?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Progress events\n// ---------------------------------------------------------------------------\n\n/**\n * Progress event emitted by adapters during agent execution.\n * Enables real-time visibility into what the agent is doing\n * (tool calls, text output, status changes).\n */\nexport interface AgentProgressEvent {\n type: \"tool_use\" | \"tool_result\" | \"text\" | \"status\" | \"cache_metrics\";\n tool_name?: string;\n /** Tool invocation arguments (e.g. file path, command). */\n input?: Record<string, unknown>;\n message?: string;\n /** SDK session ID for correlating events within a single adapter call. */\n session_id?: string;\n /** Cache utilization metrics from the SDK response. */\n cacheMetrics?: {\n cachedInputTokens?: number;\n totalInputTokens?: number;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Prompt caching\n// ---------------------------------------------------------------------------\n\n/**\n * A prompt split into static (cacheable) and dynamic (per-invocation) sections.\n * Adapters that support prompt caching can use the `system` sections as\n * provider-specific system prompts, reducing token costs on repeated calls.\n */\nexport interface SplitPrompt {\n /** Static sections: role, responsibilities, constraints, rules, task, schema, recovery. */\n system: string[];\n /** Dynamic sections: user request, handoff input, prior context, files, acceptance criteria. */\n user: string;\n}\n\n/**\n * Optional cache configuration for adapters that support prompt caching.\n * Provider-specific defaults apply when individual fields are omitted.\n */\nexport interface CacheConfig {\n /** Enable prompt caching. Defaults to true when the adapter supports it. */\n enabled?: boolean;\n /** Provider-specific TTL (e.g. \"5m\", \"1h\", \"24h\"). */\n ttl?: string;\n /** Stable key for cross-session cache reuse (provider-specific). */\n cacheKey?: string;\n}\n\n// ---------------------------------------------------------------------------\n// SDK adapter interface\n// ---------------------------------------------------------------------------\n\n/**\n * Base options for SdkAdapter.send(). SDK-specific options (model, cwd,\n * sessionMode, etc.) belong on the adapter constructor / factory — not here.\n */\nexport interface AdapterSendOptions {\n readonly: boolean;\n /**\n * Optional callback invoked with intermediate progress events during execution.\n * Adapters that consume an internal event stream (e.g. Claude SDK's AsyncGenerator)\n * call this for each non-result message, enabling callers to display live progress.\n */\n onProgress?: (event: AgentProgressEvent) => void;\n /**\n * Split prompt for prompt caching support. When provided, adapters that support\n * caching can separate static (cacheable) instructions from dynamic content.\n * Adapters without caching support can ignore this and use the prompt argument.\n */\n splitPrompt?: SplitPrompt;\n /**\n * Candidate sub-agents the entry agent's LLM may delegate to (model B,\n * LLM-internal routing). Adapters register these via their native subagent\n * mechanism (Claude `agents`, OpenAI `handoffs`, ADK `subAgents`). When\n * omitted or empty, adapters behave exactly as before (single agent).\n */\n agents?: CandidateAgent[];\n /**\n * When true, adapters that support dynamic workflow tools (e.g. Claude's\n * Workflow tool for agent()/pipeline()/parallel()) should enable them.\n * The task's final output is still validated against the handoff schema.\n */\n allowDynamicWorkflow?: boolean;\n /**\n * In-process library tools to register with the SDK as function tools.\n * Adapters convert these to their native tool format (Claude MCP, OpenAI\n * function tools, ADK tools). I/O is validated against the tool's schemas.\n */\n libraryTools?: LibraryToolRegistry;\n /**\n * Optional observer emit function for inner turn-level spans\n * (agent.llm_turn, agent.tool_exec). When undefined, adapters skip\n * instrumentation entirely (no-op).\n */\n observer?: ObserverEmitFn;\n /**\n * Parent span ID for inner turn-level spans. Typically the subagent span ID\n * so that LLM turn and tool execution spans are correlated as children.\n */\n parentSpanId?: string;\n /**\n * Agent-axis session id (= the enclosing agent.session run_id). Threaded so\n * inner agent.llm_turn / agent.tool_exec spans carry a non-NULL session_id and\n * join the cross-axis correlation rules (#143 / #140).\n */\n sessionId?: string;\n}\n\n/**\n * Rich execution request for adapters that need more than a prompt string.\n * Adapters can implement sendExecution() to receive full contract context.\n */\nexport interface AgentExecutionRequest {\n agentId: string;\n taskId: string;\n prompt: string;\n\n handoff?: {\n type: string;\n payload: unknown;\n };\n\n schema?: {\n handoffType: string;\n zodSchema: unknown;\n promptDescription: string;\n };\n\n context: TaskContext;\n\n /** Resumable memory reference from a previous run. */\n memoryRef?: MemoryRef;\n\n /**\n * Split prompt for prompt caching support. When provided, adapters can\n * separate static instructions (system) from dynamic content (user).\n */\n splitPrompt?: SplitPrompt;\n\n /**\n * Candidate sub-agents for LLM-internal routing (model B). Mirrors\n * `AdapterSendOptions.agents`; also forwarded via `options.agents`.\n */\n agents?: CandidateAgent[];\n\n options: AdapterSendOptions & {\n maxFollowUps: number;\n attempt: number;\n };\n}\n\nexport interface SdkAdapter {\n /** Start a new task session and return the full text response. */\n send(prompt: string, options: AdapterSendOptions): Promise<string>;\n\n /**\n * Send a follow-up message within the same agent session.\n * Used for output-format corrections without re-executing the task.\n * Falls back to send() if not implemented (stateless adapters like mock).\n */\n followUp?(message: string): Promise<string>;\n\n /**\n * Rich execution path. When implemented, the runtime prefers this over\n * send() and passes the full contract context. Adapters that only need\n * a prompt string can ignore this — the runtime falls back to send().\n */\n sendExecution?(request: AgentExecutionRequest): Promise<string>;\n\n /** Return the memory_ref produced by the last send/sendExecution call. */\n getLastMemoryRef?(): MemoryRef | null;\n\n /** Return the token usage from the last send/sendExecution call. */\n getLastTokenUsage?(): TokenUsage | null;\n\n /** Check if this adapter is compatible with the given compat tag. */\n isCompatible?(compat: string): boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface TaskContext {\n user_request: string;\n prior_context?: string;\n relevant_paths?: string[];\n acceptance_criteria?: string[];\n\n /**\n * Structured handoff input (primary data). When present, prompt builders\n * should derive the prompt from this rather than user_request alone.\n */\n handoff_input?: {\n type: string;\n version?: number;\n payload: unknown;\n };\n\n /** Arbitrary structured variables plugins or workflow context may inject. */\n variables?: Record<string, unknown>;\n\n /** Resumable memory reference from a previous run. */\n memoryRef?: MemoryRef;\n}\n\nexport type TaskOutcome =\n | { status: \"success\"; data: unknown; raw: string; memoryRef?: MemoryRef }\n | { status: \"validation_error\"; errors: z.ZodError; raw: string }\n | { status: \"escalation\"; reason: string; raw: string }\n | { status: \"error\"; message: string };\n\n/**\n * Retry strategy decision.\n *\n * - \"follow_up\": lightweight — same session, fix output format only\n * - \"retry\": heavyweight — new send(), re-execute the entire task\n * - \"abort\": stop retrying, return the current outcome\n */\nexport type RetryDecision = \"follow_up\" | \"retry\" | \"abort\";\n\nexport interface TaskRunOptions {\n /** Max follow-up attempts (output format correction, same session). Default: 2 */\n maxFollowUps?: number;\n /** Max full retry attempts (re-execute entire task via send). Default: 0 */\n maxRetries?: number;\n /**\n * Called on each failure to decide which recovery strategy to use.\n * Default: validation_error → follow_up, empty output → retry, else abort.\n */\n decideRetryStrategy?: (\n outcome: TaskOutcome,\n counts: { followUps: number; retries: number },\n ) => Promise<RetryDecision> | RetryDecision;\n /**\n * Writable stream for real-time progress output during agent execution.\n * When provided, intermediate adapter events (tool use, status, etc.)\n * are formatted and written here. Typical value: process.stderr.\n */\n progressOutput?: { write(chunk: string): unknown };\n /**\n * Optional observer emit function for agent-axis spans (agent.subagent open/close).\n * When undefined, no spans are emitted (observer is optional — no-op).\n * Pass EventCollector.emit.bind(collector) to wire the full observability pipeline.\n */\n observer?: ObserverEmitFn;\n /**\n * Parent span ID (typically the enclosing agent.session span's run_id).\n * Used to correlate agent.subagent spans with their parent session.\n */\n parentSpanId?: string;\n /**\n * Agent-axis session id (= the enclosing agent.session run_id). Threaded from\n * the workflow runner so the subagent span and all inner spans share one\n * non-NULL session_id, even when parentSpanId is an evaluate iteration span\n * rather than the session span (#143 / #140).\n */\n sessionId?: string;\n /** LLM adapter identifier for the execution envelope (gen_ai.system). */\n envelopeAdapter?: string;\n /** LLM model identifier for the execution envelope (gen_ai.request.model). */\n envelopeModel?: string;\n}\n\nexport interface TaskRunResult {\n outcome: TaskOutcome;\n follow_ups_used: number;\n retries_used: number;\n tokenUsage?: TokenUsage;\n}\n\n// ---------------------------------------------------------------------------\n// Schema-to-prompt description utility\n// ---------------------------------------------------------------------------\n\ninterface FieldDescriptor {\n name: string;\n type: string;\n required: boolean;\n description?: string;\n constraints?: string;\n}\n\ntype ZodCheckEntry = {\n kind?: string;\n value?: number;\n regex?: RegExp;\n isInt?: boolean;\n _zod?: { def?: Record<string, unknown> };\n};\n\nfunction getZodChecks(schema: z.ZodType): ZodCheckEntry[] {\n const def = (schema as z.ZodType & { _def?: { checks?: ZodCheckEntry[] } })._def;\n return def?.checks ?? [];\n}\n\n/** Extract validation constraints from Zod's internal checks for prompt display. */\nfunction extractZodConstraints(schema: z.ZodType): string | undefined {\n const inner = unwrapOptional(schema);\n const parts: string[] = [];\n\n if (inner instanceof z.ZodString) {\n const str = inner as z.ZodString & {\n minLength?: number | null;\n maxLength?: number | null;\n };\n if (str.minLength != null) parts.push(`min: ${str.minLength}`);\n if (str.maxLength != null) parts.push(`max: ${str.maxLength}`);\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n if (check.kind === \"regex\" && check.regex) parts.push(`regex: ${check.regex}`);\n const def = check._zod?.def;\n if (def?.format === \"regex\" && def.pattern instanceof RegExp) {\n parts.push(`regex: ${def.pattern}`);\n }\n }\n } else if (inner instanceof z.ZodNumber) {\n let hasInt = false;\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"int\") hasInt = true;\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n if (check.isInt) hasInt = true;\n const def = check._zod?.def;\n if (def?.check === \"number_format\" && def.format === \"safeint\") hasInt = true;\n if (def?.check === \"greater_than\") parts.push(`min: ${def.value}`);\n if (def?.check === \"less_than\") parts.push(`max: ${def.value}`);\n }\n if (hasInt) parts.unshift(\"int\");\n } else if (inner instanceof z.ZodArray) {\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n const def = check._zod?.def;\n if (def?.check === \"min_length\") parts.push(`min: ${def.minimum}`);\n if (def?.check === \"max_length\") parts.push(`max: ${def.maximum}`);\n }\n }\n\n return parts.length > 0 ? parts.join(\", \") : undefined;\n}\n\nfunction zodTypeToString(schema: z.ZodType): string {\n if (schema instanceof z.ZodString) return \"string\";\n if (schema instanceof z.ZodNumber) return \"number\";\n if (schema instanceof z.ZodBoolean) return \"boolean\";\n if (schema instanceof z.ZodEnum) return `enum(${(schema.options as string[]).join(\", \")})`;\n if (schema instanceof z.ZodLiteral) return `\"${String((schema._def as { values: unknown[] }).values[0])}\"`;\n\n if (schema instanceof z.ZodArray) {\n const element = (schema as z.ZodArray<z.ZodType>)._def.element;\n const inner = zodTypeToString(element);\n return `${inner}[]`;\n }\n if (schema instanceof z.ZodObject) return \"object\";\n if (schema instanceof z.ZodOptional) {\n return zodTypeToString((schema as z.ZodOptional<z.ZodType>)._def.innerType);\n }\n if (schema instanceof z.ZodRecord) return \"Record<string, unknown>\";\n return \"unknown\";\n}\n\n/** Unwrap ZodOptional to get the inner type. */\nfunction unwrapOptional(schema: z.ZodType): z.ZodType {\n if (schema instanceof z.ZodOptional) {\n return (schema as z.ZodOptional<z.ZodType>)._def.innerType;\n }\n return schema;\n}\n\n/** Get the element schema from an array type. */\nfunction getArrayElement(schema: z.ZodType): z.ZodType | null {\n const inner = unwrapOptional(schema);\n if (inner instanceof z.ZodArray) {\n return (inner as z.ZodArray<z.ZodType>)._def.element;\n }\n return null;\n}\n\nfunction extractFieldDescriptors(schema: z.ZodType): FieldDescriptor[] | null {\n let shape: Record<string, z.ZodType> | null = null;\n\n if (schema instanceof z.ZodObject) {\n shape = (schema as z.ZodObject<Record<string, z.ZodType>>).shape;\n }\n\n if (!shape) return null;\n\n return Object.entries(shape).map(([name, field]) => {\n const isOptional = field instanceof z.ZodOptional;\n const innerField = isOptional ? (field as z.ZodOptional<z.ZodType>)._def.innerType : field;\n const description = (innerField as z.ZodType & { description?: string }).description\n ?? (field as z.ZodType & { description?: string }).description;\n return {\n name,\n type: zodTypeToString(field as z.ZodType),\n required: !isOptional,\n description,\n constraints: extractZodConstraints(innerField as z.ZodType),\n };\n });\n}\n\n/**\n * Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.\n * Recursively generates sub-tables for nested objects and array elements.\n */\nexport function zodSchemaToPromptDescription(schema: z.ZodType): string {\n const tables: string[] = [];\n collectFieldTables(schema, \"\", tables);\n return tables.join(\"\\n\\n\");\n}\n\nfunction collectFieldTables(\n schema: z.ZodType,\n pathPrefix: string,\n tables: string[],\n): void {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return;\n\n const title = pathPrefix ? `**${pathPrefix}**\\n\\n` : \"\";\n const header = \"| Field | Type | Required | Constraints | Description |\";\n const sep = \"|-------|------|----------|-------------|-------------|\";\n const rows = fields.map((f) =>\n `| ${f.name} | ${f.type} | ${f.required ? \"Yes\" : \"No\"} | ${f.constraints ?? \"\"} | ${f.description ?? \"\"} |`,\n );\n tables.push(`${title}${[header, sep, ...rows].join(\"\\n\")}`);\n\n const shape = (schema instanceof z.ZodObject)\n ? (schema as z.ZodObject<Record<string, z.ZodType>>).shape\n : null;\n if (!shape) return;\n\n for (const f of fields) {\n const rawField = shape[f.name];\n const inner = unwrapOptional(rawField);\n\n if (inner instanceof z.ZodObject) {\n collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);\n } else if (inner instanceof z.ZodArray) {\n const element = (inner as z.ZodArray<z.ZodType>)._def.element;\n if (element instanceof z.ZodObject) {\n collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);\n }\n }\n }\n}\n\n/**\n * Generate a YAML example from a Zod schema shape, recursively expanding\n * nested objects and arrays up to a configurable depth.\n */\nexport function zodSchemaToYamlExample(schema: z.ZodType, maxDepth = 3): string {\n return renderYamlObject(schema, 0, maxDepth);\n}\n\nfunction renderYamlObject(schema: z.ZodType, indent: number, maxDepth: number): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const prefix = \" \".repeat(indent);\n const lines: string[] = [];\n\n for (const f of fields) {\n const shape = (schema instanceof z.ZodObject)\n ? (schema as z.ZodObject<Record<string, z.ZodType>>).shape\n : null;\n const rawField = shape?.[f.name];\n\n if (f.type.endsWith(\"[]\")) {\n lines.push(`${prefix}${f.name}:`);\n const element = rawField ? getArrayElement(rawField) : null;\n if (element && element instanceof z.ZodObject && indent < maxDepth) {\n const nested = renderYamlObject(element, indent + 2, maxDepth);\n if (nested) {\n const basePrefix = \" \".repeat(indent + 2);\n const nestedLines = nested.split(\"\\n\");\n lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);\n for (let i = 1; i < nestedLines.length; i++) {\n lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);\n }\n } else {\n lines.push(`${prefix} - key: \"value\"`);\n }\n } else if (f.type === \"string[]\") {\n lines.push(`${prefix} - \"example\"`);\n } else {\n lines.push(`${prefix} - key: \"value\"`);\n }\n } else if (f.type === \"object\" && indent < maxDepth) {\n const inner = rawField ? unwrapOptional(rawField) : null;\n if (inner && inner instanceof z.ZodObject) {\n lines.push(`${prefix}${f.name}:`);\n const nested = renderYamlObject(inner, indent + 1, maxDepth);\n if (nested) {\n lines.push(nested);\n } else {\n lines.push(`${prefix} key: \"value\"`);\n }\n } else {\n lines.push(`${prefix}${f.name}:`);\n lines.push(`${prefix} key: \"value\"`);\n }\n } else if (f.type === \"string\") {\n lines.push(`${prefix}${f.name}: \"...\"`);\n } else if (f.type === \"number\") {\n lines.push(`${prefix}${f.name}: 0`);\n } else if (f.type === \"boolean\") {\n lines.push(`${prefix}${f.name}: false`);\n } else if (f.type.startsWith(\"enum(\")) {\n const enumVals = f.type.slice(5, -1).split(\", \");\n lines.push(`${prefix}${f.name}: \"${enumVals[0]}\"`);\n } else {\n lines.push(`${prefix}${f.name}: \"...\"`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Navigation index (Level 1) prompt rendering\n// ---------------------------------------------------------------------------\n\n/** Minimal duck-typed shape of an artifact node in the navigation index. */\ninterface NavigationArtifactNode {\n files?: { path_patterns?: string[] };\n properties?: { type?: string; authority?: string; manual_edit?: string };\n relations?: { source_artifacts?: string[]; derived_artifacts?: string[] };\n agents?: { owners?: string[]; editors?: string[]; readers?: string[] };\n}\n\n/**\n * Duck-type check: does `value` look like a ProjectNavigationIndex?\n * Requires a `system` object and an `artifacts` record.\n */\nexport function isNavigationIndex(\n value: unknown,\n): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const obj = value as Record<string, unknown>;\n return (\n typeof obj.system === \"object\" &&\n obj.system !== null &&\n typeof obj.artifacts === \"object\" &&\n obj.artifacts !== null\n );\n}\n\n/**\n * Render the Level 1 navigation index as a compact prompt section — a\n * human-readable SUMMARY of artifacts (type, authority, edit policy, key\n * relations and owning agents), NOT a raw JSON dump. Gives the agent a map of\n * the project's artifacts so it can navigate before acting.\n */\nexport function renderNavigationIndexPrompt(\n navigationIndex: Record<string, unknown>,\n): string {\n const system = navigationIndex.system as\n | { id?: string; name?: string }\n | undefined;\n const artifacts =\n (navigationIndex.artifacts as Record<string, NavigationArtifactNode>) ?? {};\n const ids = Object.keys(artifacts);\n\n const sections: string[] = [\"## Project Navigation Index\"];\n\n const systemLabel = system?.name\n ? `${system.name}${system.id ? ` (${system.id})` : \"\"}`\n : (system?.id ?? \"unknown\");\n sections.push(\n `System: ${systemLabel}\\nArtifacts: ${ids.length}`,\n );\n\n if (ids.length > 0) {\n const lines: string[] = [];\n for (const id of ids) {\n const node = artifacts[id] ?? {};\n const props = node.properties ?? {};\n const tags = [props.type, props.authority]\n .filter((v): v is string => typeof v === \"string\" && v.length > 0)\n .join(\", \");\n const editPolicy =\n typeof props.manual_edit === \"string\" ? `, edit:${props.manual_edit}` : \"\";\n lines.push(`- ${id}${tags || editPolicy ? ` [${tags}${editPolicy}]` : \"\"}`);\n\n const patterns = node.files?.path_patterns;\n if (Array.isArray(patterns) && patterns.length > 0) {\n lines.push(` files: ${patterns.join(\", \")}`);\n }\n\n const derived = node.relations?.derived_artifacts;\n if (Array.isArray(derived) && derived.length > 0) {\n lines.push(` derived → ${derived.join(\", \")}`);\n }\n\n const owners = node.agents?.owners;\n if (Array.isArray(owners) && owners.length > 0) {\n lines.push(` owners: ${owners.join(\", \")}`);\n }\n }\n sections.push(lines.join(\"\\n\"));\n }\n\n return sections.join(\"\\n\\n\");\n}\n\n/** Collect analyzer.* tool ids from a wired library tool registry. */\nexport function collectAnalyzerToolIds(\n registry?: LibraryToolRegistry,\n): string[] {\n if (!registry) return [];\n return registry\n .getAll()\n .map((def) => def.toolId)\n .filter((id) => id.startsWith(\"analyzer.\"));\n}\n\n/**\n * Level 1 exploration mandate applies when the runtime injected a navigation\n * index (codebase map) — the signal that artifact-scoped investigation is active.\n */\nexport function shouldInjectAnalyzerExplorationMandate(\n context: TaskContext,\n): boolean {\n return isNavigationIndex(context.variables?.navigationIndex);\n}\n\n/**\n * System-prompt section mandating analyzer MCP tools before ad-hoc file reads.\n * Injected automatically by runTask when Level 1 context is present.\n */\nexport function renderAnalyzerExplorationMandatePrompt(\n toolIds: readonly string[],\n): string {\n const tools = toolIds.length > 0\n ? toolIds.map((id) => `- \\`${id}\\``).join(\"\\n\")\n : \"- `analyzer.getContextMap`\\n- `analyzer.analyzeImpact`\\n- `analyzer.generateContextPack`\\n- `analyzer.buildCallGraph`\";\n\n return [\n \"## Codebase Exploration Protocol (Level 2)\",\n \"\",\n \"A Project Navigation Index is provided in the user prompt. When you need to\",\n \"investigate the codebase (locate affected files, trace dependencies, or scope\",\n \"changes), you MUST use the analyzer MCP tools **before** ad-hoc Read/Grep/Glob:\",\n \"\",\n \"1. Use the navigation index to pick candidate artifacts and path patterns.\",\n \"2. Call `analyzer.getContextMap` with your `instruction` and `candidates[]`.\",\n \"3. Review suggestedReadTargets / suggestedEditTargets / suggestedValidationTargets.\",\n \"4. Call `analyzer.analyzeImpact` when you need a flat impact report.\",\n \"5. Use Read/Grep/Glob only for gaps the analyzer output did not cover.\",\n \"\",\n \"Available analyzer tools:\",\n tools,\n ].join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Prompt builder\n// ---------------------------------------------------------------------------\n\nexport interface PromptBuilderOptions {\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: {\n condition: string;\n fix_task: string;\n revalidate_task?: string;\n };\n /** When set, injects Level 1 analyzer exploration mandate into the system prompt. */\n analyzerExploration?: {\n toolIds: readonly string[];\n };\n}\n\n/**\n * Build a prompt split into static (cacheable) and dynamic (per-invocation) parts.\n *\n * Static (system): Role, Responsibilities, Constraints, Rules, Task description,\n * Completion Criteria, Output Format / Schema, Recovery Instructions.\n *\n * Dynamic (user): User Request, Handoff Input, Prior Context,\n * Relevant Files, Acceptance Criteria.\n */\nexport function buildSplitTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): SplitPrompt {\n const system: string[] = [];\n\n // Role / Responsibilities / Constraints / Rules — shared with candidate\n // sub-agent prompts via renderAgentSystemPrompt so both stay in sync.\n system.push(renderAgentSystemPrompt(agent));\n\n if (\n options?.analyzerExploration?.toolIds.length &&\n shouldInjectAnalyzerExplorationMandate(context)\n ) {\n system.push(\n renderAnalyzerExplorationMandatePrompt(options.analyzerExploration.toolIds),\n );\n }\n\n system.push(`## Task: ${task.id}\\n\\n${task.description}`);\n\n if (task.completion_criteria.length > 0) {\n system.push(\n `## Completion Criteria\\n\\n${task.completion_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let outputSection = `## Required Output Format\\n\\nReturn your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n outputSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n outputSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n outputSection += ` Include all required fields.`;\n }\n\n system.push(outputSection);\n\n if (options?.retry) {\n const r = options.retry;\n let recoverySection = `## Recovery Instructions\\n\\nIf the task fails due to: \"${r.condition}\"\\n→ Apply the recovery approach from task \"${r.fix_task}\"`;\n if (r.revalidate_task) {\n recoverySection += `\\n→ Then revalidate using task \"${r.revalidate_task}\"`;\n }\n system.push(recoverySection);\n }\n\n // Dynamic sections (per-invocation)\n const userSections: string[] = [];\n\n if (context.handoff_input) {\n const hi = context.handoff_input;\n const payloadStr = typeof hi.payload === \"string\"\n ? hi.payload\n : yaml.stringify(hi.payload);\n userSections.push(`## User Request\\n\\n${context.user_request}`);\n userSections.push(`## Handoff Input (${hi.type})\\n\\n\\`\\`\\`yaml\\n${payloadStr}\\`\\`\\``);\n } else {\n userSections.push(`## User Request\\n\\n${context.user_request}`);\n }\n\n if (context.prior_context) {\n userSections.push(`## Prior Context\\n\\n${context.prior_context}`);\n }\n\n if (context.relevant_paths && context.relevant_paths.length > 0) {\n userSections.push(\n `## Relevant Files\\n\\n${context.relevant_paths.map((p) => `- ${p}`).join(\"\\n\")}`,\n );\n }\n\n if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {\n userSections.push(\n `## Acceptance Criteria\\n\\n${context.acceptance_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (context.variables && Object.keys(context.variables).length > 0) {\n const contextPack = context.variables.analyzerContextPack;\n if (isContextPack(contextPack)) {\n userSections.push(renderContextPackPrompt(contextPack));\n }\n\n const navigationIndex = context.variables.navigationIndex;\n if (isNavigationIndex(navigationIndex)) {\n userSections.push(renderNavigationIndexPrompt(navigationIndex));\n }\n\n const otherVars = Object.entries(context.variables).filter(\n ([k]) => k !== \"analyzerContextPack\" && k !== \"navigationIndex\",\n );\n if (otherVars.length > 0) {\n const varLines = otherVars\n .map(([k, v]) => `- ${k}: ${typeof v === \"string\" ? v : JSON.stringify(v)}`)\n .join(\"\\n\");\n userSections.push(`## Context Variables\\n\\n${varLines}`);\n }\n }\n\n return {\n system,\n user: userSections.join(\"\\n\\n---\\n\\n\"),\n };\n}\n\n/** Join a SplitPrompt back into a single monolithic prompt string. */\nfunction joinSplitPrompt(split: SplitPrompt): string {\n return [...split.system, split.user].join(\"\\n\\n---\\n\\n\");\n}\n\nexport function buildTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): string {\n return joinSplitPrompt(buildSplitTaskPrompt(agent, task, context, options));\n}\n\n// ---------------------------------------------------------------------------\n// Result parser\n// ---------------------------------------------------------------------------\n\nexport function extractStructuredResult(raw: string): unknown | null {\n const yamlMatch = raw.match(/```ya?ml\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n try { return yaml.parse(yamlMatch[1]); } catch { /* fall through */ }\n }\n\n const jsonMatch = raw.match(/```json\\n([\\s\\S]*?)```/);\n if (jsonMatch) {\n try { return JSON.parse(jsonMatch[1]); } catch { /* fall through */ }\n }\n\n try { return JSON.parse(raw); } catch { /* not JSON */ }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Internal: validate LLM output against handoff schema\n// ---------------------------------------------------------------------------\n\nfunction validateOutput(\n fullOutput: string,\n task: TaskContractLike,\n schemas: Record<string, z.ZodType>,\n): TaskOutcome {\n if (!fullOutput.trim()) {\n return { status: \"error\", message: \"Agent returned empty output\" };\n }\n\n const parsed = extractStructuredResult(fullOutput);\n if (!parsed) {\n return {\n status: \"validation_error\",\n errors: new z.ZodError([{ code: \"custom\", message: \"Could not extract structured result from agent output\", path: [] }]),\n raw: fullOutput,\n };\n }\n\n const schema = schemas[task.result_handoff];\n if (!schema) {\n return { status: \"success\", data: parsed, raw: fullOutput };\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n return { status: \"validation_error\", errors: validation.error, raw: fullOutput };\n }\n\n const data = validation.data as Record<string, unknown>;\n if (data.escalation_needed === true) {\n return {\n status: \"escalation\",\n reason: (data.escalation_reasons as string) ?? \"Agent requested escalation\",\n raw: fullOutput,\n };\n }\n\n return { status: \"success\", data: validation.data, raw: fullOutput };\n}\n\nfunction attachMemoryRef(outcome: TaskOutcome, adapter: SdkAdapter): TaskOutcome {\n if (outcome.status !== \"success\") return outcome;\n const ref = adapter.getLastMemoryRef?.();\n if (!ref) return outcome;\n return { ...outcome, memoryRef: ref };\n}\n\n// ---------------------------------------------------------------------------\n// Follow-up prompt builder (lightweight, output-format correction only)\n// ---------------------------------------------------------------------------\n\nexport function buildRetryFollowUp(\n task: TaskContractLike,\n lastOutcome: TaskOutcome,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n sections.push(\n \"Your previous response could not be validated. \" +\n \"The task work itself is fine — please re-output only the structured result block in the correct format.\",\n );\n\n if (lastOutcome.status === \"validation_error\") {\n sections.push(`Validation errors:\\n${lastOutcome.errors.message}`);\n } else if (lastOutcome.status === \"error\") {\n sections.push(`Error: ${lastOutcome.message}`);\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let formatSection = `Required format: Return your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n formatSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n formatSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n formatSection += ` Include all required fields.`;\n }\n\n sections.push(formatSection);\n\n return sections.join(\"\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Default retry strategy\n// ---------------------------------------------------------------------------\n\nfunction defaultDecideRetryStrategy(\n outcome: TaskOutcome,\n _counts: { followUps: number; retries: number },\n): RetryDecision {\n if (outcome.status === \"validation_error\") {\n return \"follow_up\";\n }\n if (outcome.status === \"error\") {\n if (outcome.message === \"Agent returned empty output\") return \"retry\";\n return \"abort\";\n }\n return \"abort\";\n}\n\n// ---------------------------------------------------------------------------\n// Progress formatting\n// ---------------------------------------------------------------------------\n\nfunction summarizeToolInput(input?: Record<string, unknown>): string {\n if (!input) return \"\";\n const path = input.file_path ?? input.path ?? input.filename ?? input.file;\n if (typeof path === \"string\") return ` — ${path}`;\n const cmd = input.command ?? input.cmd;\n if (typeof cmd === \"string\") return ` — ${cmd.length > 80 ? cmd.slice(0, 77) + \"...\" : cmd}`;\n const query = input.query ?? input.search ?? input.pattern;\n if (typeof query === \"string\") return ` — \"${query}\"`;\n return \"\";\n}\n\nfunction timestamp(): string {\n return new Date().toISOString();\n}\n\nfunction formatProgressPrefix(\n event: AgentProgressEvent,\n taskId: string,\n agentId?: string,\n): string {\n const ts = timestamp();\n const sid = event.session_id ? event.session_id.slice(0, 8) : \"-\";\n const agent = agentId ?? \"-\";\n return `[${ts},${sid},${agent},${taskId}]`;\n}\n\nfunction formatProgressEvent(\n event: AgentProgressEvent,\n taskId: string,\n agentId?: string,\n): string {\n const prefix = formatProgressPrefix(event, taskId, agentId);\n switch (event.type) {\n case \"tool_use\":\n return `${prefix} ⚙ ${event.tool_name ?? \"tool\"}${summarizeToolInput(event.input)}\\n`;\n case \"tool_result\":\n return \"\";\n case \"text\": {\n if (!event.message) return \"\";\n const trimmed = event.message.trim();\n if (!trimmed) return \"\";\n const firstLine = trimmed.split(\"\\n\")[0];\n const preview = firstLine.length > 120 ? firstLine.slice(0, 117) + \"...\" : firstLine;\n return `${prefix} 💭 ${preview}\\n`;\n }\n case \"status\":\n return event.message ? `${prefix} ● ${event.message}\\n` : \"\";\n default:\n return \"\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Execute\n// ---------------------------------------------------------------------------\n\nexport async function runTask(\n adapter: SdkAdapter,\n taskId: string,\n context: TaskContext,\n options?: TaskRunOptions & {\n agentRegistry?: Record<string, AgentContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n libraryTools?: LibraryToolRegistry;\n },\n): Promise<TaskRunResult> {\n const taskReg = options?.taskRegistry ?? {};\n const agentReg = options?.agentRegistry ?? {};\n const schemas = options?.handoffSchemas ?? {};\n\n const task = taskReg[taskId];\n if (!task) return { outcome: { status: \"error\", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };\n\n const agentContract = agentReg[task.target_agent];\n if (!agentContract) return { outcome: { status: \"error\", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };\n\n // ── ExecutionEnvelope (Phase 1-1) ──────────────────────────────────────────\n // Create a standard envelope for this task execution. run_id is a UUIDv7.\n // parent_run_id is set to the enclosing session's spanId (from workflow-runner).\n const taskEnvelope: ExecutionEnvelope = createExecutionEnvelope({\n taskInstanceId: taskId,\n componentId: agentContract.id,\n fromAgent: agentContract.id,\n parentRunId: options?.parentSpanId, // correlates to agent.session run_id\n adapter: options?.envelopeAdapter,\n model: options?.envelopeModel,\n });\n\n const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);\n if (modifiedContext === null) {\n return { outcome: { status: \"error\", message: `Task \"${taskId}\" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);\n\n const analyzerToolIds = collectAnalyzerToolIds(options?.libraryTools);\n const promptOpts: PromptBuilderOptions = {\n handoffSchemas: schemas,\n retry: options?.retry,\n ...(analyzerToolIds.length > 0 &&\n shouldInjectAnalyzerExplorationMandate(enrichedContext)\n ? { analyzerExploration: { toolIds: analyzerToolIds } }\n : {}),\n };\n const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };\n\n let prompt: string;\n let splitPrompt: SplitPrompt | undefined;\n\n const pluginPrompt = pluginRegistry.applyPromptBuilder(builderArgs);\n if (pluginPrompt) {\n prompt = pluginPrompt;\n } else {\n const split = buildSplitTaskPrompt(agentContract, task, enrichedContext, promptOpts);\n splitPrompt = split;\n prompt = joinSplitPrompt(split);\n }\n\n const enhancedPrompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);\n if (enhancedPrompt !== prompt) {\n splitPrompt = undefined;\n prompt = enhancedPrompt;\n }\n\n const isReadonly = agentContract.mode === \"read-only\";\n const allowDynamicWorkflow = task.allow_dynamic_workflow ?? false;\n\n // Build candidate sub-agents for LLM-internal routing (model B). The entry\n // agent (this task's target_agent) gets every other registry agent as a\n // candidate, restricted to its can_invoke_agents allow-list when present.\n // Empty registry → undefined (adapters then behave exactly as before).\n const candidateAgents = Object.keys(agentReg).length > 0\n ? buildCandidateAgents(agentReg, {\n entryAgentId: agentContract.id,\n allowedAgentIds: agentContract.can_invoke_agents,\n })\n : [];\n const agents = candidateAgents.length > 0 ? candidateAgents : undefined;\n\n const maxFollowUps = options?.maxFollowUps ?? 2;\n const maxRetries = options?.maxRetries ?? 0;\n const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;\n\n // ── Process axis instrumentation (R3/R5 cross-axis correlation, #167) ───────\n // The Process axis must be instrumented in the LIVE runtime so the enrich\n // rules R3/R4 accumulate this task's modified files and R5 can link the commit\n // that materializes them. `effectiveSessionId` (below) is the SAME id\n // propagated to the git post-commit hook via AAAC_SESSION_ID, so the runtime\n // accumulation and the hook's promotion.commit correlate across processes.\n // All emit* helpers no-op when options.observer is undefined.\n const taskExecStart = Date.now();\n // The agent session id correlates every span emitted for this task (the\n // subagent span and all inner llm_turn/tool_exec spans) and joins the agent\n // axis to the cursor/git axes (#143 / #140). Prefer the explicit session id\n // threaded by the workflow runner; fall back to the parent session span, then\n // to this task's own run_id so the session_id is NEVER NULL — even when\n // runTask is invoked standalone (no workflow, no parent span).\n const effectiveSessionId =\n options?.sessionId ?? options?.parentSpanId ?? taskEnvelope.run_id;\n // process.task open is emitted just after the agent.subagent open below, so\n // the agent span stays the first span for this task. The id is captured here\n // (let) so the finally can close it. Dedupe repeated edits to the same path to\n // limit write volume on the shared SqliteSink (R3 also dedupes, but this\n // avoids needless emit() round-trips).\n let processTaskSpanId: string | undefined;\n const emittedEditPaths = new Set<string>();\n\n const onProgress =\n options?.progressOutput || options?.observer\n ? (event: AgentProgressEvent) => {\n if (options?.progressOutput) {\n const line = formatProgressEvent(event, taskId, agentContract.id);\n if (line) options.progressOutput.write(line);\n }\n // Emit a process.edit for each file-mutating tool call so R3 can\n // accumulate this task's modified files for cross-axis linking (#167).\n if (\n options?.observer &&\n event.type === \"tool_use\" &&\n isFileEditTool(event.tool_name)\n ) {\n const input = event.input ?? {};\n const p =\n input.file_path ?? input.path ?? input.filename ?? input.file;\n if (typeof p === \"string\" && p.length > 0 && !emittedEditPaths.has(p)) {\n emittedEditPaths.add(p);\n // IMPORTANT: do NOT set parentSpanId here. The enrich rule R3\n // resolves the parent task AND accumulates this file into the\n // per-task modified-files set (which R5 intersects with the\n // commit) ONLY when process.edit arrives WITHOUT a parentSpanId\n // (process.ts returns early otherwise). Leaving it unresolved is\n // what makes the cross-axis link materialize (#167).\n emitProcessEdit({\n filePath: p,\n sessionId: effectiveSessionId,\n observer: options.observer,\n });\n }\n }\n }\n : undefined;\n\n let followUpsUsed = 0;\n let retriesUsed = 0;\n\n let memoryRef = enrichedContext.memoryRef;\n if (memoryRef && adapter.isCompatible && !adapter.isCompatible(memoryRef.compat)) {\n console.warn(\n `Memory ref compat mismatch: ${memoryRef.compat} is not compatible with this adapter`,\n );\n memoryRef = undefined;\n }\n\n // ── agent.subagent open (Phase 1-3) ────────────────────────────────────────\n // Emit agent.subagent open span. subagentSpanId = taskEnvelope.run_id.\n // parentSpanId = options.parentSpanId (agent.session span from runWorkflow).\n // No-op when options.observer is undefined. taskExecStart / effectiveSessionId\n // are computed above with the Process axis instrumentation so both axes share\n // one session id and a single start clock.\n const subagentSpanId = emitSubagentOpen(\n options?.observer,\n taskEnvelope,\n options?.parentSpanId,\n taskId,\n agentContract.role_name,\n effectiveSessionId,\n );\n\n // ── process.task open (#167) ───────────────────────────────────────────────\n // Emitted after agent.subagent open so the agent span remains first, but\n // before any tool runs so R3/R4 see this task on the active-task stack when\n // process.edit events arrive. No-op when options.observer is undefined.\n processTaskSpanId = emitProcessTaskOpen({\n taskId,\n targetAgent: task.target_agent,\n sessionId: effectiveSessionId,\n parentSpanId: subagentSpanId ?? options?.parentSpanId,\n observer: options?.observer,\n });\n\n // ── Exception-safe subagent lifecycle ──────────────────────────────────────\n // Everything between the agent.subagent open span and its close span (initial\n // send, validation/afterTask hooks and the recovery loop) can throw or return\n // early. Wrap that region in try/finally so the close span is emitted EXACTLY\n // ONCE on EVERY exit path — success, a returned failure AND a thrown exception\n // — leaving no span stuck 'open'. This mirrors runWorkflow's session lifecycle.\n // A `closed` guard prevents double emission; closeStatus/closeCause carry the\n // outcome into the finally. The original exception is always re-thrown\n // unchanged (the finally never swallows it) to preserve propagation semantics.\n let closeStatus = \"error\";\n let closeCause: string | undefined;\n let spanClosed = false;\n const closeSubagentSpan = (): void => {\n if (spanClosed) return;\n spanClosed = true;\n const durationMs = Date.now() - taskExecStart;\n const lastTokenUsage = adapter.getLastTokenUsage?.();\n taskEnvelope.execution_metadata = {\n ...(taskEnvelope.execution_metadata ?? {}),\n duration_ms: durationMs,\n ...(lastTokenUsage ? {\n token_usage: {\n input_tokens: lastTokenUsage.inputTokens,\n output_tokens: lastTokenUsage.outputTokens,\n ...(lastTokenUsage.totalTokens !== undefined ? { total_tokens: lastTokenUsage.totalTokens } : {}),\n ...(lastTokenUsage.cacheReadTokens !== undefined ? { cache_read_input_tokens: lastTokenUsage.cacheReadTokens } : {}),\n ...(lastTokenUsage.cacheCreationTokens !== undefined ? { cache_creation_input_tokens: lastTokenUsage.cacheCreationTokens } : {}),\n },\n } : {}),\n };\n if (lastTokenUsage) {\n const costUsd = computeCostUsd(\n taskEnvelope.model,\n lastTokenUsage.inputTokens,\n lastTokenUsage.outputTokens,\n );\n if (costUsd !== undefined) {\n taskEnvelope.execution_metadata = {\n ...taskEnvelope.execution_metadata,\n cost_usd: costUsd,\n };\n }\n }\n emitSubagentClose(\n options?.observer,\n subagentSpanId ?? taskEnvelope.run_id,\n taskEnvelope,\n durationMs,\n closeStatus,\n agentContract.role_name,\n closeCause,\n effectiveSessionId,\n );\n // ── process.task close (#167) ─────────────────────────────────────────────\n // Pop this task off the enrich active-task stack (R3/R4). Guarded by the\n // same `spanClosed` flag so it is emitted EXACTLY ONCE on every exit path.\n if (processTaskSpanId) {\n emitProcessTaskClose(processTaskSpanId, {\n status: closeStatus,\n durationMs,\n observer: options?.observer,\n });\n }\n };\n\n try {\n // --- Initial send (prefer sendExecution if available) ---\n let fullOutput: string;\n try {\n if (adapter.sendExecution) {\n fullOutput = await adapter.sendExecution({\n agentId: agentContract.id,\n taskId,\n prompt,\n handoff: schemas[task.result_handoff]\n ? { type: task.result_handoff, payload: undefined }\n : undefined,\n schema: schemas[task.result_handoff]\n ? {\n handoffType: task.result_handoff,\n zodSchema: schemas[task.result_handoff],\n promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff]),\n }\n : undefined,\n context: enrichedContext,\n memoryRef,\n splitPrompt,\n agents,\n options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId, maxFollowUps, attempt: 0 },\n });\n } else {\n fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId });\n }\n } catch (err) {\n // SDK errors on the initial send are returned as an error outcome (NOT\n // re-thrown) — preserve that semantics. The finally emits the close span.\n closeStatus = \"error\";\n closeCause = `SDK error: ${(err as Error).message}`;\n return { outcome: { status: \"error\", message: closeCause }, follow_ups_used: 0, retries_used: 0 };\n }\n\n let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n\n // --- Recovery loop ---\n while (outcome.status === \"validation_error\" || outcome.status === \"error\") {\n const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });\n\n if (decision === \"abort\") break;\n\n // If requested strategy is exhausted, escalate to the other\n let effectiveDecision = decision;\n if (effectiveDecision === \"follow_up\" && followUpsUsed >= maxFollowUps) {\n effectiveDecision = \"retry\";\n }\n if (effectiveDecision === \"retry\" && retriesUsed >= maxRetries) {\n break;\n }\n\n if (effectiveDecision === \"follow_up\") {\n followUpsUsed++;\n\n const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);\n try {\n if (adapter.followUp) {\n fullOutput = await adapter.followUp(followUpPrompt);\n } else {\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- FollowUp ${followUpsUsed} ---\\n${followUpPrompt}`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });\n }\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on followUp ${followUpsUsed}: ${(err as Error).message}` };\n continue;\n }\n } else {\n // effectiveDecision === \"retry\" — full re-execution\n retriesUsed++;\n\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- Full Retry ${retriesUsed} ---\\nPrevious attempt failed: ` +\n (outcome.status === \"validation_error\"\n ? `Validation errors: ${outcome.errors.message}`\n : outcome.status === \"error\" ? outcome.message : \"unknown\") +\n `\\nPlease re-execute the entire task.`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n\n try {\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on retry ${retriesUsed}: ${(err as Error).message}` };\n continue;\n }\n }\n\n outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n // Normal exit: record the final outcome status for the close span.\n closeStatus = outcome.status;\n const finalTokenUsage = adapter.getLastTokenUsage?.() ?? undefined;\n return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed, tokenUsage: finalTokenUsage };\n } catch (err) {\n // Post-send / recovery threw (e.g. validation, afterTask hook or decide()).\n // Record the cause and re-throw unchanged — the finally still emits close.\n closeStatus = \"error\";\n closeCause = (err as Error).message;\n throw err;\n } finally {\n // ── agent.subagent close (Phase 1-3) ─────────────────────────────────────\n closeSubagentSpan();\n }\n}\n","/**\n * Model pricing table for cost_usd computation (#210).\n *\n * Prices are USD per 1M tokens. Unknown models fail open (return undefined).\n */\n\nexport interface ModelPricing {\n inputPerMillion: number;\n outputPerMillion: number;\n}\n\n/** Normalise model id for lookup (strip provider prefixes / version suffixes). */\nexport function normalizeModelId(model: string): string {\n return model.trim().toLowerCase();\n}\n\nconst PRICING_TABLE: Record<string, ModelPricing> = {\n // Anthropic Claude\n \"claude-opus-4-6\": { inputPerMillion: 15, outputPerMillion: 75 },\n \"claude-opus-4\": { inputPerMillion: 15, outputPerMillion: 75 },\n \"claude-sonnet-4\": { inputPerMillion: 3, outputPerMillion: 15 },\n \"claude-sonnet-4-6\": { inputPerMillion: 3, outputPerMillion: 15 },\n \"claude-haiku-4\": { inputPerMillion: 0.8, outputPerMillion: 4 },\n // OpenAI GPT\n \"gpt-5.5\": { inputPerMillion: 2.5, outputPerMillion: 10 },\n \"gpt-5.3-codex\": { inputPerMillion: 2.5, outputPerMillion: 10 },\n \"gpt-4.1\": { inputPerMillion: 2, outputPerMillion: 8 },\n \"gpt-4o\": { inputPerMillion: 2.5, outputPerMillion: 10 },\n \"gpt-4o-mini\": { inputPerMillion: 0.15, outputPerMillion: 0.6 },\n // Google Gemini\n \"gemini-2.5-pro\": { inputPerMillion: 1.25, outputPerMillion: 10 },\n \"gemini-2.5-flash\": { inputPerMillion: 0.15, outputPerMillion: 0.6 },\n \"gemini-2.0-flash\": { inputPerMillion: 0.1, outputPerMillion: 0.4 },\n};\n\nexport function resolveModelPricing(model: string | undefined): ModelPricing | undefined {\n if (!model) return undefined;\n const key = normalizeModelId(model);\n if (PRICING_TABLE[key]) return PRICING_TABLE[key];\n // Prefix match for versioned ids (e.g. claude-sonnet-4-20250514)\n for (const [known, pricing] of Object.entries(PRICING_TABLE)) {\n if (key.startsWith(known)) return pricing;\n }\n return undefined;\n}\n\nexport function computeCostUsd(\n model: string | undefined,\n inputTokens: number,\n outputTokens: number,\n): number | undefined {\n const pricing = resolveModelPricing(model);\n if (!pricing) return undefined;\n if (inputTokens <= 0 && outputTokens <= 0) return undefined;\n const cost =\n (inputTokens * pricing.inputPerMillion + outputTokens * pricing.outputPerMillion) /\n 1_000_000;\n return Math.round(cost * 1_000_000) / 1_000_000;\n}\n","/**\n * Project artifact composition — the ONE place where the project manifest's\n * `artifacts:` contract (an artifact-contracts registry) is composed onto a\n * resolved agents DSL. Both the execution path (BoundResolver) and the\n * navigation-index path consume this; neither resolves the registry itself.\n *\n * Composition, not intersection (`docs/governance-layer-spec.md` §2.2: the\n * runtime joins every declared contract into one static DSL, and the\n * navigation-index is built from that join):\n *\n * - DSL artifact whose id the registry declares → the registry's concrete\n * data is merged over the component's default (upstream binding semantics).\n * - DSL artifact the registry does not declare → keeps its component default;\n * upstream reports `unbound-artifact`.\n * - Registry artifact no DSL artifact maps to → STILL a project artifact. It is\n * declared here so the binder merges and path-substitutes it exactly like the\n * mapped ones. Dropping it (the previous behaviour) meant an artifact the\n * project governs — including `authority: generated` ones — was invisible to\n * `@` completion and unprotected by the PreToolUse edit guard. This mirrors\n * `toolchains:`, whose registry entries are all composed in (bound-resolver).\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport YAML from \"yaml\";\n\nexport interface ArtifactResolveOptions {\n dsl: Record<string, unknown>;\n artifactBinding?: {\n source: string;\n mappings?: Record<string, string>;\n };\n paths?: Record<string, string>;\n}\n\nexport interface ArtifactResolveResult {\n dsl: Record<string, unknown>;\n diagnostics: Array<{ path: string; message: string; severity: string }>;\n}\n\n/**\n * Read the `artifacts:` map from an artifact-contracts registry. Read/parse\n * failures are loud: the manifest named this file, so silently continuing would\n * present a component-default index as if it were the project's.\n */\nasync function loadArtifactRegistry(\n source: string,\n): Promise<Record<string, unknown>> {\n let content: string;\n try {\n content = await readFile(source, \"utf8\");\n } catch {\n throw new Error(\n `Failed to read artifact registry: ${source} ` +\n \"(declared by the project manifest's `artifacts:`).\",\n );\n }\n\n let parsed: unknown;\n try {\n parsed = YAML.parse(content);\n } catch (err) {\n throw new Error(\n `Invalid YAML in artifact registry ${source}: ${(err as Error).message}`,\n );\n }\n\n const artifacts = (parsed as { artifacts?: unknown } | null | undefined)?.artifacts;\n if (artifacts && typeof artifacts === \"object\" && !Array.isArray(artifacts)) {\n return artifacts as Record<string, unknown>;\n }\n return {};\n}\n\nexport async function resolveArtifacts(\n options: ArtifactResolveOptions,\n): Promise<ArtifactResolveResult> {\n if (!options.artifactBinding) {\n return { dsl: options.dsl, diagnostics: [] };\n }\n\n const { resolveArtifactBinding } = await import(\"agent-contracts\");\n const registry = await loadArtifactRegistry(options.artifactBinding.source);\n const dslArtifacts = (options.dsl.artifacts ?? {}) as Record<string, unknown>;\n const mappings = options.artifactBinding.mappings;\n\n // Registry ids that no DSL artifact resolves to (directly or via `mappings`)\n // are declared as empty artifacts so the binder produces them from the\n // registry — one code path for every artifact, mapped or composed. Ids that ARE\n // claimed by a DSL artifact are left alone, so a mapping collision still\n // surfaces upstream's `orphan-binding` instead of vanishing.\n const claimed = new Set(\n Object.keys(dslArtifacts).map((id) => mappings?.[id] ?? id),\n );\n const composed = Object.keys(registry).filter(\n (id) => !claimed.has(id) && !(id in dslArtifacts),\n );\n\n const bound = resolveArtifactBinding(\n {\n ...Object.fromEntries(composed.map((id) => [id, {}])),\n ...dslArtifacts,\n },\n { artifacts: registry },\n mappings,\n options.paths,\n );\n\n return {\n dsl: { ...options.dsl, artifacts: bound.artifacts },\n diagnostics: bound.diagnostics.map((d) => ({\n path: d.rule,\n message: d.message,\n severity: d.severity,\n })),\n };\n}\n","/**\n * Runtime DSL Context — builds WorkflowRegistries from embedded DSL data,\n * optionally merging with project-level DSL extensions.\n *\n * Default flow:\n * CLI binary embeds resolved DSL data (from code generation) →\n * loadDslContext() builds registries from it.\n *\n * Extended flow:\n * Project provides a DSL that extends/overrides the embedded base →\n * loadDslContext() merges via agent-contracts' mergeDsl() →\n * builds registries from the merged result.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport type { z } from \"zod\";\nimport YAML from \"yaml\";\nimport type { WorkflowRegistries, WorkflowContractLike, WorkflowStep, DelegateStep } from \"./workflow-runner.js\";\nimport type { AgentContractLike, TaskContractLike } from \"./task-runner.js\";\nimport { jsonSchemaToZod } from \"./schema-converter.js\";\nimport type { GuardrailRule, GuardrailRuleData } from \"./guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface LoadDslOptions {\n /**\n * Pre-resolved DSL data embedded in the CLI binary.\n * Produced by the code generator alongside TypeScript contracts.\n * This is the default DSL — used as-is when no project extension exists.\n */\n embeddedDsl: Record<string, unknown>;\n\n /**\n * Path to a project-level DSL file that extends/overrides the embedded DSL.\n * When provided, the project DSL is resolved (including its own extends chain)\n * and merged with embeddedDsl via mergeDsl().\n */\n projectDslPath?: string;\n\n /** Entities the CLI depends on — validated after merge. */\n requiredEntities?: RequiredEntities;\n}\n\nexport interface RequiredEntities {\n workflows?: string[];\n tasks?: string[];\n}\n\nexport interface DslContext {\n readonly registries: WorkflowRegistries;\n readonly dsl: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nexport class DslValidationError extends Error {\n readonly missing: string[];\n constructor(missing: string[]) {\n super(\n \"Required entities missing after DSL merge:\\n\" +\n missing.map((m) => ` - ${m}`).join(\"\\n\"),\n );\n this.name = \"DslValidationError\";\n this.missing = missing;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internal: build registries from resolved DSL\n// ---------------------------------------------------------------------------\n\nfunction buildAgentRegistry(\n agents: Record<string, Record<string, unknown>>,\n): Record<string, AgentContractLike> {\n const registry: Record<string, AgentContractLike> = {};\n for (const [id, agent] of Object.entries(agents)) {\n const rawMode = (agent.mode as string) ?? \"read-only\";\n const mode: \"read-write\" | \"read-only\" = rawMode === \"read-write\" ? \"read-write\" : \"read-only\";\n registry[id] = {\n id,\n role_name: (agent.role_name as string) ?? id,\n purpose: (agent.purpose as string) ?? \"\",\n mode,\n responsibilities: (agent.responsibilities as string[]) ?? [],\n constraints: (agent.constraints as string[]) ?? [],\n rules: (agent.rules as Array<{ id: string; description: string; severity: string }>) ?? [],\n can_invoke_agents: (agent.can_invoke_agents as string[]) ?? undefined,\n can_execute_tools: (agent.can_execute_tools as string[]) ?? undefined,\n };\n }\n return registry;\n}\n\nfunction buildTaskRegistry(\n tasks: Record<string, Record<string, unknown>>,\n): Record<string, TaskContractLike> {\n const registry: Record<string, TaskContractLike> = {};\n for (const [id, task] of Object.entries(tasks)) {\n registry[id] = {\n id,\n description: (task.description as string) ?? \"\",\n target_agent: (task.target_agent as string) ?? \"\",\n result_handoff: (task.result_handoff as string) ?? \"\",\n completion_criteria: (task.completion_criteria as string[]) ?? [],\n model_class: task.model_class as \"fast\" | \"standard\" | \"thinking\" | undefined,\n };\n }\n return registry;\n}\n\nfunction buildWorkflowStep(step: Record<string, unknown>): WorkflowStep {\n if (step.type === \"gate\") {\n return {\n type: \"gate\" as const,\n gate_kind: (step.gate_kind as string) ?? \"\",\n description: (step.description as string) ?? \"\",\n depends_on: step.depends_on as readonly string[] | undefined,\n };\n }\n if (step.type === \"evaluate\") {\n return {\n type: \"evaluate\" as const,\n task: (step.task as string) ?? \"\",\n from_agent: (step.from_agent as string) ?? \"\",\n evaluator_agent: step.evaluator_agent as string | undefined,\n description: step.description as string | undefined,\n loop_to: (step.loop_to as string) ?? \"\",\n max_iterations: (step.max_iterations as number) ?? 1,\n inject_as: step.inject_as as string | undefined,\n on_exhausted: step.on_exhausted as \"abort\" | \"fail_partial\" | \"escalate\" | undefined,\n depends_on: step.depends_on as readonly string[] | undefined,\n };\n }\n return {\n type: \"delegate\" as const,\n task: (step.task as string) ?? \"\",\n from_agent: (step.from_agent as string) ?? \"\",\n description: (step.description as string) ?? \"\",\n optional: (step.optional as boolean) ?? false,\n max_retries: (step.max_retries as number) ?? 0,\n max_follow_ups: step.max_follow_ups as number | undefined,\n depends_on: step.depends_on as readonly string[] | undefined,\n instruction: step.instruction as string | undefined,\n receives: step.receives as DelegateStep[\"receives\"],\n retry: step.retry as { condition: string; fix_task: string; revalidate_task?: string } | undefined,\n };\n}\n\nfunction buildWorkflowRegistry(\n workflows: Record<string, Record<string, unknown>>,\n): Record<string, WorkflowContractLike> {\n const registry: Record<string, WorkflowContractLike> = {};\n for (const [id, wf] of Object.entries(workflows)) {\n const steps = ((wf.steps as Record<string, unknown>[]) ?? []).map(buildWorkflowStep);\n registry[id] = { id, description: (wf.description as string) ?? \"\", steps };\n }\n return registry;\n}\n\nfunction buildHandoffSchemas(\n handoffTypes: Record<string, Record<string, unknown>>,\n): Record<string, z.ZodType> {\n const schemas: Record<string, z.ZodType> = {};\n for (const [id, ht] of Object.entries(handoffTypes)) {\n const schema = ht.schema as Record<string, unknown> | undefined;\n if (schema) {\n schemas[id] = jsonSchemaToZod(schema);\n }\n }\n return schemas;\n}\n\n// ---------------------------------------------------------------------------\n// Build registries from a resolved DSL object\n// ---------------------------------------------------------------------------\n\nexport function buildRegistriesFromDsl(\n dsl: Record<string, unknown>,\n): WorkflowRegistries {\n const agents = (dsl.agents as Record<string, Record<string, unknown>>) ?? {};\n const tasks = (dsl.tasks as Record<string, Record<string, unknown>>) ?? {};\n const workflows = (dsl.workflow as Record<string, Record<string, unknown>>) ?? {};\n const handoffTypes = (dsl.handoff_types as Record<string, Record<string, unknown>>) ?? {};\n\n return {\n agentRegistry: buildAgentRegistry(agents),\n taskRegistry: buildTaskRegistry(tasks),\n workflowRegistry: buildWorkflowRegistry(workflows),\n handoffSchemas: buildHandoffSchemas(handoffTypes),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nfunction validateRequiredEntities(\n dsl: Record<string, unknown>,\n required: RequiredEntities,\n): void {\n const missing: string[] = [];\n\n const workflows = (dsl.workflow as Record<string, unknown>) ?? {};\n const tasks = (dsl.tasks as Record<string, unknown>) ?? {};\n const handoffTypes = (dsl.handoff_types as Record<string, unknown>) ?? {};\n\n if (required.workflows) {\n for (const wfId of required.workflows) {\n if (!(wfId in workflows)) {\n missing.push(`workflow \"${wfId}\" is required by the CLI but not found in the resolved DSL`);\n }\n }\n }\n\n if (required.tasks) {\n for (const taskId of required.tasks) {\n if (!(taskId in tasks)) {\n missing.push(`task \"${taskId}\" is required by the CLI but not found in the resolved DSL`);\n continue;\n }\n const task = tasks[taskId] as Record<string, unknown>;\n const invHandoff = task.invocation_handoff as string | undefined;\n const resHandoff = task.result_handoff as string | undefined;\n if (invHandoff && !(invHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${invHandoff}\" (invocation_handoff of task \"${taskId}\") not found`);\n }\n if (resHandoff && !(resHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${resHandoff}\" (result_handoff of task \"${taskId}\") not found`);\n }\n }\n }\n\n if (required.workflows) {\n for (const wfId of required.workflows) {\n if (!(wfId in workflows)) continue;\n const wf = workflows[wfId] as Record<string, unknown>;\n const steps = (wf.steps as Array<Record<string, unknown>>) ?? [];\n for (const step of steps) {\n if (step.type !== \"delegate\") continue;\n const taskId = step.task as string;\n if (taskId && taskId in tasks) {\n const task = tasks[taskId] as Record<string, unknown>;\n const resHandoff = task.result_handoff as string | undefined;\n if (resHandoff && !(resHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${resHandoff}\" (result of task \"${taskId}\" in workflow \"${wfId}\") not found`);\n }\n }\n }\n }\n }\n\n if (missing.length > 0) {\n throw new DslValidationError(missing);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main API\n// ---------------------------------------------------------------------------\n\n/**\n * Build a DslContext from embedded DSL data, optionally merging with\n * a project-level DSL extension.\n *\n * Default (no projectDslPath):\n * Builds registries directly from embeddedDsl — no filesystem access.\n *\n * Extended (with projectDslPath):\n * Resolves the project DSL from filesystem, merges it over embeddedDsl\n * via agent-contracts' mergeDsl(), then builds registries from the result.\n */\nexport async function loadDslContext(\n options: LoadDslOptions,\n): Promise<DslContext> {\n let dsl: Record<string, unknown>;\n\n if (options.projectDslPath) {\n const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import(\"agent-contracts\");\n const raw = await readFile(options.projectDslPath, \"utf8\");\n const projectData = YAML.parse(raw) as Record<string, unknown>;\n\n if (projectData.extends === \"/$embedded/\") {\n const { extends: _extends, ...projectOverrides } = projectData;\n const merged = mergeDsl(options.embeddedDsl, projectOverrides);\n dsl = expandDefaults(merged);\n } else {\n const projectResult = await resolveDsl(options.projectDslPath);\n const merged = mergeDsl(options.embeddedDsl, projectResult.data);\n dsl = expandDefaults(merged);\n }\n } else {\n dsl = options.embeddedDsl;\n }\n\n if (options.requiredEntities) {\n validateRequiredEntities(dsl, options.requiredEntities);\n }\n\n const registries = buildRegistriesFromDsl(dsl);\n\n return { registries, dsl };\n}\n","/**\n * BoundResolver — runtime binding + policy resolution with per-agent isolation.\n *\n * Resolves artifact composition and guardrail/policy in one pass at runtime,\n * producing a per-agent scoped ResolvedComponent. Reuses existing\n * resolveArtifacts(), buildGuardrailContext(), and agent scope resolution.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport YAML from \"yaml\";\nimport { buildGuardrailContext, type GuardrailCheckEntry, type GuardrailContext } from \"../generator/context.js\";\nimport { resolveArtifacts } from \"./artifact-resolver.js\";\nimport { buildRegistriesFromDsl } from \"./dsl-context.js\";\nimport type { GuardrailRuleData } from \"./guardrail-hooks.js\";\nimport type { WorkflowRegistries } from \"./workflow-runner.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface ArtifactBindingConfig {\n source: string;\n mappings?: Record<string, string>;\n}\n\nexport interface BoundResolveOptions {\n /** Component identifier — used for cache keying. */\n id: string;\n /** Pre-resolved DSL (e.g. embedded from codegen). */\n embeddedDsl?: Record<string, unknown>;\n /** Path to DSL file — resolved via agent-contracts when no embeddedDsl. */\n dslPath?: string;\n /** Paths to software binding YAML files (guardrail_impl, etc.). */\n bindingPaths?: string[];\n /** Active guardrail policy name from DSL guardrail_policies. */\n activeGuardrailPolicy?: string;\n /** Artifact binding config — composed via resolveArtifacts() (lib/artifact-resolver). */\n artifactBinding?: ArtifactBindingConfig;\n /** Path substitutions for artifact binding. */\n paths?: Record<string, string>;\n /** Path to toolchain-contracts.yaml. */\n toolchainContractsPath?: string;\n}\n\nexport interface ResolvedToolchain {\n id: string;\n kind: \"library\" | \"cli\" | \"component\";\n description?: string;\n module?: string;\n command?: string;\n cli_contract?: string;\n component_contract?: string;\n artifacts: { consumes: string[]; produces: string[] };\n operations?: string[];\n source: \"toolchain-contracts\" | \"agent-contracts\" | \"merged\";\n}\n\nexport interface ResolvedComponent {\n id: string;\n dsl: Record<string, unknown>;\n registries: WorkflowRegistries;\n guardrails: {\n perAgent: Map<string, GuardrailRuleData>;\n };\n diagnostics: Array<{ path?: string; message: string; severity?: string }>;\n toolchains?: Record<string, ResolvedToolchain>;\n toolchainsByAgent?: Map<string, ResolvedToolchain[]>;\n}\n\n// ---------------------------------------------------------------------------\n// Guardrail scope helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Effective guardrail IDs for an agent: entity-side bindings ∪ scope-side bindings.\n */\nexport function getEffectiveGuardrailIds(\n dsl: Record<string, unknown>,\n agentId: string,\n): Set<string> {\n const ids = new Set<string>();\n\n const agents = (dsl.agents ?? {}) as Record<string, Record<string, unknown>>;\n const agent = agents[agentId];\n if (agent) {\n for (const ref of (agent.guardrails as string[]) ?? []) {\n ids.add(ref);\n }\n }\n\n const guardrails = (dsl.guardrails ?? {}) as Record<\n string,\n { scope?: { agents?: string[] } }\n >;\n for (const [guardrailId, guardrail] of Object.entries(guardrails)) {\n if (guardrail.scope?.agents?.includes(agentId)) {\n ids.add(guardrailId);\n }\n }\n\n return ids;\n}\n\nfunction guardrailCheckToCommandRule(c: GuardrailCheckEntry) {\n return {\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action as GuardrailRuleData[\"commandRules\"][number][\"action\"],\n message: c.message,\n };\n}\n\nfunction guardrailCheckToFileRule(c: GuardrailCheckEntry) {\n return {\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action as GuardrailRuleData[\"fileRules\"][number][\"action\"],\n message: c.message,\n ...(c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}),\n };\n}\n\nfunction guardrailCheckToContentRule(c: GuardrailCheckEntry) {\n return {\n guardrail_id: c.guardrail_id,\n pattern: c.pattern,\n action: c.action as GuardrailRuleData[\"contentRules\"][number][\"action\"],\n message: c.message,\n ...(c.file_glob ? { file_glob: c.file_glob } : {}),\n ...(c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}),\n };\n}\n\nexport function guardrailContextToRuleData(\n ctx: GuardrailContext,\n effectiveIds?: Set<string>,\n): GuardrailRuleData {\n const filter = (checks: GuardrailCheckEntry[]) =>\n effectiveIds ? checks.filter((c) => effectiveIds.has(c.guardrail_id)) : checks;\n\n return {\n commandRules: filter(ctx.commandChecks).map(guardrailCheckToCommandRule),\n fileRules: filter(ctx.fileChecks).map(guardrailCheckToFileRule),\n contentRules: filter(ctx.contentChecks).map(guardrailCheckToContentRule),\n };\n}\n\nexport function buildPerAgentGuardrails(\n dsl: Record<string, unknown>,\n guardrailCtx: GuardrailContext,\n): Map<string, GuardrailRuleData> {\n const perAgent = new Map<string, GuardrailRuleData>();\n const agents = (dsl.agents ?? {}) as Record<string, unknown>;\n\n for (const agentId of Object.keys(agents)) {\n const effectiveIds = getEffectiveGuardrailIds(dsl, agentId);\n const rules = guardrailContextToRuleData(guardrailCtx, effectiveIds);\n if (\n rules.commandRules.length > 0 ||\n rules.fileRules.length > 0 ||\n rules.contentRules.length > 0\n ) {\n perAgent.set(agentId, rules);\n }\n }\n\n return perAgent;\n}\n\nconst EMPTY_GUARDRAIL_CONTEXT: GuardrailContext = {\n commandChecks: [],\n fileChecks: [],\n contentChecks: [],\n allChecks: [],\n hasGuardrails: false,\n};\n\n/**\n * Resolve the guardrail context from a DSL + its software bindings — the ONE\n * place `guardrail_impl` matchers become checks. The CLI execution path and the\n * navigation-index/hook path both call this, so the hooks enforce exactly what\n * `dev-team guard list` reports (#267).\n *\n * Checks from EVERY binding file are merged: `bindings.guardrail` is a list, and\n * overwriting per file silently dropped all but the last one (#268).\n */\nexport async function resolveGuardrailContext(\n dsl: Record<string, unknown>,\n bindingPaths?: string[],\n activeGuardrailPolicy?: string,\n options?: {\n /**\n * Ignore binding paths that do not exist. The `guard` CLI commands report on\n * whatever is present (a not-yet-created binding is not a failure); the\n * execution path wants the missing file to surface.\n */\n skipMissing?: boolean;\n },\n): Promise<GuardrailContext> {\n if (!bindingPaths || bindingPaths.length === 0) {\n return EMPTY_GUARDRAIL_CONTEXT;\n }\n\n const merged: GuardrailContext = {\n commandChecks: [],\n fileChecks: [],\n contentChecks: [],\n allChecks: [],\n hasGuardrails: false,\n };\n\n for (const bindingPath of bindingPaths) {\n let raw: string;\n try {\n raw = await readFile(bindingPath, \"utf8\");\n } catch (err) {\n if (options?.skipMissing && (err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n const binding = YAML.parse(raw) as Record<string, unknown>;\n const ctx = buildGuardrailContext(dsl, binding, activeGuardrailPolicy);\n merged.commandChecks.push(...ctx.commandChecks);\n merged.fileChecks.push(...ctx.fileChecks);\n merged.contentChecks.push(...ctx.contentChecks);\n merged.allChecks.push(...ctx.allChecks);\n merged.hasGuardrails = merged.hasGuardrails || ctx.hasGuardrails;\n }\n\n return merged;\n}\n\nfunction hasGuardrailRules(rules: GuardrailRuleData): boolean {\n return (\n rules.commandRules.length > 0 ||\n rules.fileRules.length > 0 ||\n rules.contentRules.length > 0\n );\n}\n\n// ---------------------------------------------------------------------------\n// Toolchain derivation — types for dynamic import from @aaac/toolchain\n// ---------------------------------------------------------------------------\n\ninterface ToolchainDSLEntry {\n kind: \"library\" | \"cli\" | \"component\";\n description?: string;\n module?: string;\n command?: string;\n cli_contract?: string;\n component_contract?: string;\n artifacts: { consumes: string[]; produces: string[] };\n operations?: string[];\n}\n\ninterface ToolchainContractsDSLShape {\n toolchains: Record<string, ToolchainDSLEntry>;\n}\n\ninterface ToolchainModule {\n loadToolchainContracts(filePath: string): Promise<ToolchainContractsDSLShape>;\n}\n\nfunction mergeDerivedWithAgentTools(\n derivedTools: ResolvedToolchain[],\n agentToolIds: string[],\n allToolchains: Record<string, ResolvedToolchain>,\n): ResolvedToolchain[] {\n const merged = new Map<string, ResolvedToolchain>();\n\n for (const tc of derivedTools) {\n merged.set(tc.id, tc);\n }\n\n for (const toolId of agentToolIds) {\n if (!merged.has(toolId)) {\n if (allToolchains[toolId]) {\n merged.set(toolId, { ...allToolchains[toolId], source: \"merged\" });\n }\n } else {\n const existing = merged.get(toolId)!;\n merged.set(toolId, { ...existing, source: \"merged\" });\n }\n }\n\n return Array.from(merged.values());\n}\n\nexport function deriveToolchainsForAgents(\n dsl: Record<string, unknown>,\n toolchains: Record<string, ResolvedToolchain>,\n): Map<string, ResolvedToolchain[]> {\n const result = new Map<string, ResolvedToolchain[]>();\n const agents = (dsl.agents ?? {}) as Record<string, Record<string, unknown>>;\n\n for (const [agentId, agent] of Object.entries(agents)) {\n const derivedTools: ResolvedToolchain[] = [];\n\n const canReadArtifacts = (agent.can_read_artifacts ?? []) as string[];\n const canWriteArtifacts = (agent.can_write_artifacts ?? []) as string[];\n const agentArtifacts = agent.artifacts as\n | { produces?: string[]; consumes?: string[] }\n | undefined;\n const readArtifacts = new Set([\n ...canReadArtifacts,\n ...(agentArtifacts?.consumes ?? []),\n ]);\n const writeArtifacts = new Set([\n ...canWriteArtifacts,\n ...(agentArtifacts?.produces ?? []),\n ]);\n\n for (const tc of Object.values(toolchains)) {\n let matched = false;\n\n for (const artifactId of tc.artifacts.consumes) {\n if (readArtifacts.has(artifactId) || writeArtifacts.has(artifactId)) {\n matched = true;\n break;\n }\n }\n\n if (!matched) {\n for (const artifactId of tc.artifacts.produces) {\n if (writeArtifacts.has(artifactId)) {\n matched = true;\n break;\n }\n }\n }\n\n if (matched) {\n derivedTools.push(tc);\n }\n }\n\n if (derivedTools.length > 0) {\n const agentTools = (agent.can_execute_tools ?? []) as string[];\n const mergedTools = mergeDerivedWithAgentTools(\n derivedTools,\n agentTools,\n toolchains,\n );\n result.set(agentId, mergedTools);\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// BoundResolver\n// ---------------------------------------------------------------------------\n\nexport class BoundResolver {\n private readonly cache = new Map<string, ResolvedComponent>();\n\n /**\n * Resolve binding + policy in one pass. Results are cached by component id.\n */\n async resolve(opts: BoundResolveOptions): Promise<ResolvedComponent> {\n const cached = this.cache.get(opts.id);\n if (cached) return cached;\n\n const diagnostics: ResolvedComponent[\"diagnostics\"] = [];\n let dsl: Record<string, unknown>;\n\n if (opts.embeddedDsl) {\n dsl = opts.embeddedDsl;\n } else if (opts.dslPath) {\n const { resolve: resolveDsl } = await import(\"agent-contracts\");\n const result = await resolveDsl(opts.dslPath);\n dsl = result.data;\n } else {\n throw new Error(\"BoundResolver.resolve requires embeddedDsl or dslPath\");\n }\n\n // Artifact composition (the shared seam — see lib/artifact-resolver.ts)\n if (opts.artifactBinding) {\n const bound = await resolveArtifacts({\n dsl,\n artifactBinding: opts.artifactBinding,\n paths: opts.paths,\n });\n dsl = bound.dsl;\n diagnostics.push(...bound.diagnostics);\n }\n\n // Guardrail + policy from bindings\n let guardrailCtx: GuardrailContext;\n\n guardrailCtx = await resolveGuardrailContext(\n dsl,\n opts.bindingPaths,\n opts.activeGuardrailPolicy,\n );\n\n const perAgent = guardrailCtx.hasGuardrails\n ? buildPerAgentGuardrails(dsl, guardrailCtx)\n : new Map<string, GuardrailRuleData>();\n\n let toolchains: Record<string, ResolvedToolchain> | undefined;\n let toolchainsByAgent: Map<string, ResolvedToolchain[]> | undefined;\n\n if (opts.toolchainContractsPath) {\n const toolchainPkg = \"@aaac/toolchain\";\n const mod = (await import(/* webpackIgnore: true */ toolchainPkg)) as ToolchainModule;\n const tcDoc = await mod.loadToolchainContracts(opts.toolchainContractsPath);\n\n toolchains = {};\n for (const [id, tc] of Object.entries(tcDoc.toolchains) as Array<[string, ToolchainDSLEntry]>) {\n toolchains[id] = {\n id,\n kind: tc.kind,\n description: tc.description,\n module: tc.module,\n command: tc.command,\n cli_contract: tc.cli_contract,\n component_contract: tc.component_contract,\n artifacts: {\n consumes: [...tc.artifacts.consumes],\n produces: [...tc.artifacts.produces],\n },\n operations: tc.operations ? [...tc.operations] : undefined,\n source: \"toolchain-contracts\",\n };\n }\n\n toolchainsByAgent = deriveToolchainsForAgents(dsl, toolchains);\n }\n\n const component: ResolvedComponent = {\n id: opts.id,\n dsl,\n registries: buildRegistriesFromDsl(dsl),\n guardrails: { perAgent },\n diagnostics,\n ...(toolchains ? { toolchains } : {}),\n ...(toolchainsByAgent ? { toolchainsByAgent } : {}),\n };\n\n this.cache.set(opts.id, component);\n return component;\n }\n\n /** Clear cached components (e.g. for testing). */\n clearCache(): void {\n this.cache.clear();\n }\n}\n\n/** Get guardrail rules for a specific agent from a ResolvedComponent. */\nexport function getGuardrailRulesForAgent(\n component: ResolvedComponent,\n agentId: string,\n): GuardrailRuleData | undefined {\n const perAgent = component.guardrails.perAgent.get(agentId);\n return perAgent && hasGuardrailRules(perAgent) ? perAgent : undefined;\n}\n","import type { Dsl } from \"agent-contracts\";\nimport { resolveArtifacts } from \"./artifact-resolver.js\";\nimport {\n guardrailContextToRuleData,\n resolveGuardrailContext,\n} from \"./bound-resolver.js\";\nimport { loadDslContext } from \"./dsl-context.js\";\nimport type { GuardrailRuleData } from \"./guardrail-hooks.js\";\n\nexport interface NavigationContextOptions {\n configPath?: string;\n embeddedDsl?: Record<string, unknown>;\n projectDslPath?: string;\n artifactBinding?: {\n source: string;\n mappings?: Record<string, string>;\n };\n paths?: Record<string, string>;\n /**\n * Software binding files (`guardrail_impl`) from the project manifest's\n * `bindings.guardrail`. Without them the hooks enforce NO Bash guardrails\n * while the CLI enforces the project's — the asymmetry behind #267.\n */\n bindingPaths?: string[];\n /** Active guardrail policy name from the manifest. */\n activeGuardrailPolicy?: string;\n}\n\nexport interface NavigationContext {\n dsl: Record<string, unknown>;\n navigationIndex: Record<string, unknown>;\n /**\n * Guardrail rules resolved from the DSL + the project's software bindings.\n *\n * The navigation-index does not carry guardrail rules (it is an\n * artifact/tool graph), so they are surfaced separately here for the\n * PreToolUse Bash guardrail path (#238 / C5). `undefined` when the project\n * declares no guardrail binding.\n */\n guardrailRules?: GuardrailRuleData;\n diagnostics: Array<{ path: string; message: string; severity: string }>;\n}\n\nexport async function buildNavigationContext(\n options: NavigationContextOptions,\n): Promise<NavigationContext> {\n const diagnostics: NavigationContext[\"diagnostics\"] = [];\n let dsl: Record<string, unknown>;\n\n if (options.embeddedDsl != null) {\n if (options.projectDslPath) {\n const ctx = await loadDslContext({\n embeddedDsl: options.embeddedDsl,\n projectDslPath: options.projectDslPath,\n });\n dsl = ctx.dsl;\n } else {\n dsl = options.embeddedDsl;\n }\n } else if (options.projectDslPath) {\n // No embedded DSL: resolve the project DSL file directly\n const { resolve } = await import(\"agent-contracts\");\n const result = await resolve(options.projectDslPath);\n dsl = result.data;\n } else {\n throw new Error(\"buildNavigationContext requires embeddedDsl or projectDslPath\");\n }\n\n if (options.artifactBinding) {\n const bound = await resolveArtifacts({\n dsl,\n artifactBinding: options.artifactBinding,\n paths: options.paths,\n });\n dsl = bound.dsl;\n diagnostics.push(...bound.diagnostics);\n }\n\n const { validateSchema, buildNavigationIndex } = await import(\"agent-contracts\");\n const validation = validateSchema(dsl);\n for (const d of validation.diagnostics) {\n diagnostics.push({\n path: d.path,\n message: d.message,\n severity: d.severity ?? \"error\",\n });\n }\n\n // Use validated Dsl when available; fall back to raw dsl on validation failure\n const navigationIndex = buildNavigationIndex(\n (validation.data ?? dsl) as unknown as Dsl,\n ) as Record<string, unknown>;\n\n // Same resolver the CLI execution path uses, so `dev-team guard list` and the\n // PreToolUse Bash guard agree (#267).\n const guardrailCtx = await resolveGuardrailContext(\n dsl,\n options.bindingPaths,\n options.activeGuardrailPolicy,\n );\n const guardrailRules = guardrailCtx.hasGuardrails\n ? guardrailContextToRuleData(guardrailCtx)\n : undefined;\n\n return { dsl, navigationIndex, guardrailRules, diagnostics };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2CO,SAAS,wBAAwB,OAAkC;AACxE,QAAM,WAAqB,CAAC;AAE5B,WAAS,KAAK,WAAW,MAAM,SAAS;AAAA;AAAA,EAAO,MAAM,OAAO,EAAE;AAE9D,MAAI,MAAM,iBAAiB,SAAS,GAAG;AACrC,aAAS;AAAA,MACP;AAAA;AAAA,EAA0B,MAAM,iBAAiB,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA,IAClF;AAAA,EACF;AAEA,MAAI,MAAM,YAAY,SAAS,GAAG;AAChC,aAAS;AAAA,MACP;AAAA;AAAA,EAAqB,MAAM,YAAY,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA,IACxE;AAAA,EACF;AAEA,MAAI,MAAM,SAAS,MAAM,MAAM,SAAS,GAAG;AACzC,UAAM,YAAY,MAAM,MAAM;AAAA,MAC5B,CAAC,MAAM,OAAO,EAAE,EAAE,OAAO,EAAE,QAAQ,MAAM,EAAE,WAAW;AAAA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aAAa;AACtC,gBAAY,KAAK;AAAA,MACf,MAAM,EAAE;AAAA,MACR,SAAS,EAAE;AAAA,MACX,UAAU,EAAE,YAAY;AAAA,IAC1B,CAAC;AAAA,EACH;AAGA,QAAM,kBAAkB;AAAA,IACrB,WAAW,QAAQ;AAAA,EACtB;AAIA,QAAM,eAAe,MAAM;AAAA,IACzB;AAAA,IACA,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AACA,QAAM,iBAAiB,aAAa,gBAChC,2BAA2B,YAAY,IACvC;AAEJ,SAAO,EAAE,KAAK,iBAAiB,gBAAgB,YAAY;AAC7D;","names":["readFile","YAML","readFile","YAML","readFile","YAML","readFile","YAML"]}
@@ -104,7 +104,11 @@ function globFragmentToRegex(fragment) {
104
104
  }
105
105
  return out;
106
106
  }
107
- function matchGlob(pattern, path) {
107
+ function expandDirectoryPattern(pattern) {
108
+ return pattern.endsWith("/") ? `${pattern}**` : pattern;
109
+ }
110
+ function matchGlob(rawPattern, path) {
111
+ const pattern = expandDirectoryPattern(rawPattern);
108
112
  let regex = "";
109
113
  let i = 0;
110
114
  while (i < pattern.length) {
@@ -325,4 +329,4 @@ export {
325
329
  createGuardrailHooksForAgent,
326
330
  createGuardrailHooksFromRules
327
331
  };
328
- //# sourceMappingURL=chunk-EH5VFZYJ.js.map
332
+ //# sourceMappingURL=chunk-NMX4C6LC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/plugin.ts","../src/lib/guardrail-hooks.ts"],"sourcesContent":["/**\n * Plugin Interface — extension points for user code injection\n */\n\nimport type { TaskContext, TaskOutcome, AgentContractLike, TaskContractLike, PromptBuilderOptions } from \"./task-runner.js\";\nimport type { WorkflowResult } from \"./workflow-runner.js\";\n\nexport interface GuardrailResult {\n matched: boolean;\n guardrail_id: string;\n severity: \"critical\" | \"mandatory\" | \"warning\" | \"info\";\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface PromptBuilderArgs {\n agent: AgentContractLike;\n task: TaskContractLike;\n context: TaskContext;\n options?: PromptBuilderOptions;\n}\n\nexport interface AgentPlugin {\n readonly id: string;\n beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;\n afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;\n /**\n * Enrich the structured TaskContext before prompt generation.\n * Unlike beforeTask (which can skip a task by returning null),\n * this hook is purely for context augmentation.\n */\n contextEnhancer?(taskId: string, context: TaskContext): TaskContext;\n /**\n * Lightweight prompt post-processor. Applied after the prompt is built.\n * Use for appending instructions or modifying sections.\n */\n promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;\n /**\n * Full prompt builder override. If provided and returns a non-null string,\n * replaces the default buildTaskPrompt output entirely.\n * Receives the agent/task contracts and context so the plugin can build\n * a completely custom prompt.\n */\n promptBuilder?(args: PromptBuilderArgs): string | null;\n customGuardrails?: {\n evaluateCommand?(command: string): GuardrailResult[];\n evaluateFilePath?(filePath: string): GuardrailResult[];\n evaluateFileContent?(filePath: string, content: string): GuardrailResult[];\n };\n beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;\n afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;\n}\n\nexport class PluginRegistry {\n private plugins: AgentPlugin[] = [];\n\n register(plugin: AgentPlugin): void {\n if (this.plugins.some((p) => p.id === plugin.id)) {\n throw new Error(`Plugin \"${plugin.id}\" is already registered`);\n }\n this.plugins.push(plugin);\n }\n\n getAll(): readonly AgentPlugin[] {\n return this.plugins;\n }\n\n async runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null> {\n let ctx: TaskContext | null = context;\n for (const plugin of this.plugins) {\n if (!plugin.beforeTask || ctx === null) continue;\n ctx = await plugin.beforeTask(taskId, ctx);\n }\n return ctx;\n }\n\n async runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome> {\n let result = outcome;\n for (const plugin of this.plugins) {\n if (!plugin.afterTask) continue;\n result = await plugin.afterTask(taskId, result);\n }\n return result;\n }\n\n applyContextEnhancers(taskId: string, context: TaskContext): TaskContext {\n let ctx = context;\n for (const plugin of this.plugins) {\n if (!plugin.contextEnhancer) continue;\n ctx = plugin.contextEnhancer(taskId, ctx);\n }\n return ctx;\n }\n\n /**\n * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,\n * or null to use the default buildTaskPrompt.\n */\n applyPromptBuilder(args: PromptBuilderArgs): string | null {\n for (const plugin of this.plugins) {\n if (!plugin.promptBuilder) continue;\n const result = plugin.promptBuilder(args);\n if (result !== null) return result;\n }\n return null;\n }\n\n applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string {\n let enhanced = prompt;\n for (const plugin of this.plugins) {\n if (!plugin.promptEnhancer) continue;\n enhanced = plugin.promptEnhancer(taskId, enhanced, context);\n }\n return enhanced;\n }\n\n evaluateCommandGuardrails(command: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateCommand) continue;\n results.push(...plugin.customGuardrails.evaluateCommand(command));\n }\n return results;\n }\n\n evaluateFilePathGuardrails(filePath: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFilePath) continue;\n results.push(...plugin.customGuardrails.evaluateFilePath(filePath));\n }\n return results;\n }\n\n evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFileContent) continue;\n results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));\n }\n return results;\n }\n\n async runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.beforeWorkflow) continue;\n await plugin.beforeWorkflow(workflowId, userRequest);\n }\n }\n\n async runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.afterWorkflow) continue;\n await plugin.afterWorkflow(workflowId, result);\n }\n }\n}\n\nexport const pluginRegistry = new PluginRegistry();\n","/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions\n * + plugin guardrails to SDK-compatible hook responses.\n *\n * Embedded guardrail rules are converted via createGuardrailHooksFromRules(),\n * which delegates to createGuardrailHooks(). All hook logic lives here.\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface HookResponse {\n permission?: \"deny\";\n user_message?: string;\n agent_message?: string;\n additionalContext?: string;\n}\n\nexport interface GuardrailRule {\n guardrail_id: string;\n pattern: string;\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailRuleData {\n commandRules: GuardrailRule[];\n fileRules: GuardrailRule[];\n contentRules: GuardrailRule[];\n}\n\nexport interface GuardrailCheckFunctions {\n checkCommand: (command: string) => GuardrailCheckResult[];\n checkFilePath: (filePath: string) => GuardrailCheckResult[];\n checkContent: (filePath: string, content: string) => GuardrailCheckResult[];\n}\n\nfunction globFragmentToRegex(fragment: string): string {\n let out = \"\";\n for (const ch of fragment) {\n if (ch === \"*\") out += \"[^/]*\";\n else if (ch === \"?\") out += \"[^/]\";\n else if (\".+^$|()[]\\\\\".includes(ch)) out += \"\\\\\" + ch;\n else out += ch;\n }\n return out;\n}\n\n/**\n * A pattern ending in `/` denotes a DIRECTORY and matches everything under it\n * (#262). This is the dominant style in artifact `path_patterns` — the embedded\n * dev-team DSL (`src/`, `lib/`, `tests/`, `.cursor/rules/`) and every\n * artifact-contracts registry rely on it. Without this, such a pattern compiles\n * to `^src/$`, which no file path can ever equal, so path → artifact reverse\n * lookup silently matched nothing and the artifact edit guard never fired.\n *\n * The rewrite is monotonic: file paths never end in `/`, so a pattern that\n * matched something before still matches exactly the same paths.\n */\nfunction expandDirectoryPattern(pattern: string): string {\n return pattern.endsWith(\"/\") ? `${pattern}**` : pattern;\n}\n\nexport function matchGlob(rawPattern: string, path: string): boolean {\n const pattern = expandDirectoryPattern(rawPattern);\n let regex = \"\";\n let i = 0;\n while (i < pattern.length) {\n if (pattern[i] === \"*\" && pattern[i + 1] === \"*\" && pattern[i + 2] === \"/\") {\n regex += \"(?:.+/)?\";\n i += 3;\n } else if (pattern[i] === \"*\" && pattern[i + 1] === \"*\") {\n regex += \".*\";\n i += 2;\n } else if (pattern[i] === \"*\") {\n regex += \"[^/]*\";\n i += 1;\n } else if (pattern[i] === \"?\") {\n regex += \"[^/]\";\n i += 1;\n } else if (pattern[i] === \"{\") {\n const end = pattern.indexOf(\"}\", i);\n if (end !== -1) {\n const alts = pattern.slice(i + 1, end).split(\",\").map(globFragmentToRegex);\n regex += \"(?:\" + alts.join(\"|\") + \")\";\n i = end + 1;\n } else {\n regex += \"\\\\{\";\n i += 1;\n }\n } else if (\".+^$|()[]\\\\\".includes(pattern[i])) {\n regex += \"\\\\\" + pattern[i];\n i += 1;\n } else {\n regex += pattern[i];\n i += 1;\n }\n }\n return new RegExp(\"^\" + regex + \"$\").test(path);\n}\n\nexport interface HookContext {\n /** Agent id for per-agent guardrail filtering. */\n agentId?: string;\n command?: string;\n filePath?: string;\n content?: string;\n}\n\nexport interface GuardrailHooks {\n beforeShellExecution: (input: { command?: string }) => HookResponse;\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }) => HookResponse;\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"block\");\n}\n\nexport function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"warn\");\n}\n\nexport function hasBlockingViolation(results: GuardrailCheckResult[]): boolean {\n return results.some((r) => !r.passed && r.action === \"block\");\n}\n\nfunction pluginResultToCheckResult(r: {\n matched: boolean;\n guardrail_id: string;\n action: string;\n message: string;\n}): GuardrailCheckResult {\n return {\n guardrail_id: r.guardrail_id,\n passed: !r.matched,\n action: r.action as GuardrailCheckResult[\"action\"],\n message: r.matched ? r.message : \"\",\n };\n}\n\n/**\n * Create SDK hook functions from generated guardrail check functions.\n *\n * Merges DSL-generated checks with plugin-registered guardrails and\n * returns hook functions in the format expected by the Claude SDK,\n * plus a generic runChecks() for programmatic use.\n */\nexport function createGuardrailHooks(checks: GuardrailCheckFunctions): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n results.push(...checks.checkCommand(ctx.command));\n results.push(\n ...pluginRegistry.evaluateCommandGuardrails(ctx.command).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath) {\n results.push(...checks.checkFilePath(ctx.filePath));\n results.push(\n ...pluginRegistry.evaluateFilePathGuardrails(ctx.filePath).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath && ctx.content) {\n results.push(...checks.checkContent(ctx.filePath, ctx.content));\n results.push(\n ...pluginRegistry\n .evaluateFileContentGuardrails(ctx.filePath, ctx.content)\n .map(pluginResultToCheckResult),\n );\n }\n\n return results;\n }\n\n function beforeShellExecution(input: { command?: string }): HookResponse {\n const command = input.command ?? \"\";\n if (!command) return {};\n\n const results = runChecks({ command });\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n if (warns.length > 0) {\n return {\n additionalContext: warns.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\"),\n };\n }\n\n return {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }): HookResponse {\n const filePath = input.tool_input?.file_path ?? input.tool_input?.path ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n const filePath = input.file_path ?? \"\";\n const content = input.content ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath, content });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };\n}\n\n/**\n * Create SDK hook functions from embedded guardrail rule data.\n */\n/**\n * Create SDK hooks scoped to a single agent from a per-agent guardrail map.\n * Returns empty-passing hooks when the agent has no rules in the map.\n */\nexport function createGuardrailHooksForAgent(\n agentId: string,\n perAgent: Map<string, GuardrailRuleData>,\n): GuardrailHooks {\n const rules = perAgent.get(agentId);\n if (!rules) {\n return createGuardrailHooks({\n checkCommand: () => [],\n checkFilePath: () => [],\n checkContent: () => [],\n });\n }\n const hooks = createGuardrailHooksFromRules(rules);\n const baseRunChecks = hooks.runChecks;\n return {\n ...hooks,\n runChecks(ctx: HookContext) {\n return baseRunChecks({ ...ctx, agentId });\n },\n };\n}\n\n/** Compile a guardrail regex pattern, supporting inline `(?i)` case-insensitivity prefix. */\nexport function compileGuardrailPattern(pattern: string): RegExp {\n if (pattern.startsWith(\"(?i)\")) {\n return new RegExp(pattern.slice(4), \"i\");\n }\n return new RegExp(pattern);\n}\n\nexport function createGuardrailHooksFromRules(rules: GuardrailRuleData): GuardrailHooks {\n const commandChecks = rules.commandRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(rule.pattern),\n action: rule.action,\n message: rule.message,\n }));\n\n const fileChecks = rules.fileRules;\n\n const contentChecks = rules.contentRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(rule.pattern),\n action: rule.action,\n message: rule.message,\n file_glob: rule.file_glob,\n exclude_glob: rule.exclude_glob,\n }));\n\n return createGuardrailHooks({\n checkCommand(command: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of commandChecks) {\n const passed = !check.pattern.test(command);\n results.push({\n guardrail_id: check.guardrail_id,\n passed,\n action: check.action,\n message: passed ? \"\" : check.message,\n });\n }\n return results;\n },\n\n checkFilePath(filePath: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of fileChecks) {\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = matchGlob(check.pattern, filePath);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n\n checkContent(filePath: string, content: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of contentChecks) {\n if (check.file_glob && !matchGlob(check.file_glob, filePath)) {\n continue;\n }\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = check.pattern.test(content);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n });\n}\n"],"mappings":";AAqDO,IAAM,iBAAN,MAAqB;AAAA,EAClB,UAAyB,CAAC;AAAA,EAElC,SAAS,QAA2B;AAClC,QAAI,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO,EAAE,GAAG;AAChD,YAAM,IAAI,MAAM,WAAW,OAAO,EAAE,yBAAyB;AAAA,IAC/D;AACA,SAAK,QAAQ,KAAK,MAAM;AAAA,EAC1B;AAAA,EAEA,SAAiC;AAC/B,WAA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AA,UACd,SAAS,SAAS,KAAK,MAAM;AAAA,QAC/B,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,IAEA,cAAc,UAA0C;AACtD,YAAM,UAAkC,CAAC;AACzC,iBAAW,SAAS,YAAY;AAC9B,YAAI,MAAM,gBAAgB,UAAU,MAAM,cAAc,QAAQ,GAAG;AACjE;AAAA,QACF;AACA,cAAM,UAAU,UAAU,MAAM,SAAS,QAAQ;AACjD,gBAAQ,KAAK;AAAA,UACX,cAAc,MAAM;AAAA,UACpB,QAAQ,CAAC;AAAA,UACT,QAAQ,MAAM;AAAA,UACd,SAAS,UAAU,MAAM,UAAU;AAAA,QACrC,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,IAEA,aAAa,UAAkB,SAAyC;AACtE,YAAM,UAAkC,CAAC;AACzC,iBAAW,SAAS,eAAe;AACjC,YAAI,MAAM,aAAa,CAAC,UAAU,MAAM,WAAW,QAAQ,GAAG;AAC5D;AAAA,QACF;AACA,YAAI,MAAM,gBAAgB,UAAU,MAAM,cAAc,QAAQ,GAAG;AACjE;AAAA,QACF;AACA,cAAM,UAAU,MAAM,QAAQ,KAAK,OAAO;AAC1C,gBAAQ,KAAK;AAAA,UACX,cAAc,MAAM;AAAA,UACpB,QAAQ,CAAC;AAAA,UACT,QAAQ,MAAM;AAAA,UACd,SAAS,UAAU,MAAM,UAAU;AAAA,QACrC,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -1,7 +1,10 @@
1
+ import {
2
+ guardrailCacheKey
3
+ } from "./chunk-LDCQZPDG.js";
1
4
  import {
2
5
  createGuardrailHooksFromRules,
3
6
  matchGlob
4
- } from "./chunk-EH5VFZYJ.js";
7
+ } from "./chunk-NMX4C6LC.js";
5
8
 
6
9
  // src/lib/claude-native/hook-protocol.ts
7
10
  function parseHookInput(raw) {
@@ -255,11 +258,63 @@ function stripMemberPrefix(filePath, memberRoot, workspaceRoot) {
255
258
 
256
259
  // src/lib/claude-native/workspace-pre-tool-use.ts
257
260
  var EDIT_TOOLS2 = /* @__PURE__ */ new Set(["Edit", "Write", "MultiEdit", "edit", "write"]);
261
+ var BASH_TOOLS2 = /* @__PURE__ */ new Set(["Bash", "bash", "Terminal", "terminal"]);
262
+ function extractCommandPathTokens(command) {
263
+ const tokens = [];
264
+ for (const raw of command.split(/\s+/)) {
265
+ const t = raw.replace(/^['"]+|['"]+$/g, "");
266
+ if (t && (t.includes("/") || t.includes("\\"))) {
267
+ tokens.push(t);
268
+ }
269
+ }
270
+ return tokens;
271
+ }
258
272
  function createWorkspacePreToolUseHandler(config) {
259
273
  const store = createCacheStore({ cacheDir: config.cacheDir });
274
+ const guardrailHooksByMember = /* @__PURE__ */ new Map();
275
+ async function loadGuardrailHooks(member) {
276
+ const key = member.name;
277
+ if (guardrailHooksByMember.has(key)) {
278
+ return guardrailHooksByMember.get(key) ?? null;
279
+ }
280
+ const cacheKey = member.guardrailCacheKey ?? guardrailCacheKey(member.cacheKey);
281
+ const entry = await store.read(cacheKey);
282
+ const rules = entry?.data;
283
+ const hooks = rules && (rules.commandRules.length > 0 || rules.fileRules.length > 0 || rules.contentRules.length > 0) ? createGuardrailHooksFromRules(rules) : null;
284
+ guardrailHooksByMember.set(key, hooks);
285
+ return hooks;
286
+ }
287
+ function membersForCommand(command) {
288
+ for (const token of extractCommandPathTokens(command)) {
289
+ const owner = routePathToMember(
290
+ token,
291
+ config.members,
292
+ config.workspaceRoot
293
+ );
294
+ if (owner) return [owner];
295
+ }
296
+ return config.members;
297
+ }
260
298
  return async function handleWorkspacePreToolUse(input) {
261
299
  const toolName = input.tool_name ?? "";
262
300
  const toolInput = input.tool_input ?? {};
301
+ if (BASH_TOOLS2.has(toolName)) {
302
+ const command = toolInput.command ?? "";
303
+ if (!command) {
304
+ return buildAllowResponse();
305
+ }
306
+ for (const member2 of membersForCommand(command)) {
307
+ const hooks = await loadGuardrailHooks(member2);
308
+ if (!hooks) continue;
309
+ const result = hooks.beforeShellExecution({ command });
310
+ if (result.permission === "deny") {
311
+ return buildDenyResponse(
312
+ result.user_message ?? "Command blocked by guardrail"
313
+ );
314
+ }
315
+ }
316
+ return buildAllowResponse();
317
+ }
263
318
  if (!EDIT_TOOLS2.has(toolName)) {
264
319
  return buildAllowResponse();
265
320
  }
@@ -316,4 +371,4 @@ export {
316
371
  stripMemberPrefix,
317
372
  createWorkspacePreToolUseHandler
318
373
  };
319
- //# sourceMappingURL=chunk-4OMCAGNY.js.map
374
+ //# sourceMappingURL=chunk-QVH5KKBR.js.map