agent-contracts-runtime 0.36.6 → 0.36.8
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.
- package/cli-contract.yaml +76 -0
- package/dist/adapters/adk-sdk.d.ts +2 -2
- package/dist/adapters/adk-sdk.js +1 -1
- package/dist/adapters/claude-agent-sdk.d.ts +2 -2
- package/dist/adapters/mock.d.ts +1 -1
- package/dist/adapters/openai-agents-sdk.d.ts +2 -2
- package/dist/agent-runtime.bundle.mjs +584 -403
- package/dist/agent-runtime.bundle.mjs.map +4 -4
- package/dist/bound-resolver-K4UHLXN6.js +17 -0
- package/dist/bound-resolver-K4UHLXN6.js.map +1 -0
- package/dist/{chunk-FFCXUPYA.js → chunk-5UGCLWDM.js} +68 -281
- package/dist/chunk-5UGCLWDM.js.map +1 -0
- package/dist/chunk-D2QTXQB2.js +266 -0
- package/dist/chunk-D2QTXQB2.js.map +1 -0
- package/dist/chunk-LTZA6QWC.js +296 -0
- package/dist/chunk-LTZA6QWC.js.map +1 -0
- package/dist/{chunk-JDXRLHY3.js → chunk-MGRZBGQL.js} +20 -1
- package/dist/chunk-MGRZBGQL.js.map +1 -0
- package/dist/chunk-MWZXU25C.js +171 -0
- package/dist/chunk-MWZXU25C.js.map +1 -0
- package/dist/chunk-VOBS62OH.js +323 -0
- package/dist/chunk-VOBS62OH.js.map +1 -0
- package/dist/cli/index.js +95 -16
- package/dist/cli/index.js.map +1 -1
- package/dist/context-B_bekYiE.d.ts +106 -0
- package/dist/dsl-context-LACANPO4.js +13 -0
- package/dist/dsl-context-LACANPO4.js.map +1 -0
- package/dist/generator/index.d.ts +17 -106
- package/dist/generator/index.js +5 -3
- package/dist/{guardrail-hooks-B1_vgkE5.d.ts → guardrail-hooks-C8G5NGsj.d.ts} +8 -1
- package/dist/index.d.ts +80 -5
- package/dist/index.js +26 -9
- package/dist/{task-runner-C1bAy5k9.d.ts → task-runner-Bo37lS9q.d.ts} +5 -0
- package/docs/cli-reference.md +160 -0
- package/package.json +7 -2
- package/dist/chunk-FFCXUPYA.js.map +0 -1
- package/dist/chunk-JDXRLHY3.js.map +0 -1
- package/dist/chunk-KQOZCJK6.js +0 -593
- package/dist/chunk-KQOZCJK6.js.map +0 -1
package/dist/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/index.ts","../../src/generated/cli/program.ts","../../src/generated/cli/contract.ts","../../src/lib/doctor.ts","../../src/lib/init.ts","../../src/lib/implement.ts","../../src/builtin-agents/generated/agents.ts","../../src/builtin-agents/generated/tasks.ts","../../src/builtin-agents/generated/handoffs.ts","../../src/builtin-agents/generated/workflows.ts","../../src/builtin-agents/generated/dsl-data.ts","../../src/lib/audit-implementation.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * agent-runtime CLI entry point\n *\n * Uses auto-generated program from cli-contract.yaml.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { register } from \"tsx/esm/api\";\nimport { createProgram, type CommandHandlers } from \"../generated/cli/program.js\";\nimport { generate, loadConfig, checkFreshness } from \"../generator/index.js\";\nimport {\n buildTaskPrompt,\n pluginRegistry,\n runWorkflow,\n createGuardrailHooksFromRules,\n type AgentContractLike,\n type TaskContractLike,\n type SdkAdapter,\n type TaskContext,\n type WorkflowContractLike,\n type WorkflowInvocation,\n type GuardrailHooks,\n type GuardrailRuleData,\n} from \"../index.js\";\nimport { loadPlugins } from \"../lib/plugin-loader.js\";\nimport { runDoctor } from \"../lib/doctor.js\";\nimport { runInit } from \"../lib/init.js\";\nimport { runImplement, formatImplementResult } from \"../lib/implement.js\";\nimport { runAuditImplementation, formatAuditResult } from \"../lib/audit-implementation.js\";\nimport { resolvedDsl } from \"../builtin-agents/generated/index.js\";\nimport { createProgressSink, type ProgressSink } from \"../lib/progress-sink.js\";\nimport type { ResolvedProgressLog } from \"../generator/config.js\";\nimport type { z } from \"zod\";\nimport YAML from \"yaml\";\n\nregister();\n\nconst VERSION = \"0.36.5\";\n\n/**\n * Dynamically import the generated contracts from the configured generated_dir.\n * Handles both .ts (via tsx/ts-node) and .js (compiled) files,\n * and both flat exports and namespace exports.\n */\nasync function loadGeneratedContracts(configPath: string): Promise<{\n agentRegistry: Record<string, AgentContractLike>;\n taskRegistry: Record<string, TaskContractLike>;\n handoffSchemas: Record<string, z.ZodType>;\n workflowRegistry: Record<string, WorkflowContractLike>;\n guardrailHooks?: GuardrailHooks;\n}> {\n const config = await loadConfig(configPath);\n const basePath = `${config.generatedDir}/index`;\n\n let indexPath: string;\n if (existsSync(`${basePath}.js`)) {\n indexPath = `${basePath}.js`;\n } else if (existsSync(`${basePath}.ts`)) {\n indexPath = `${basePath}.ts`;\n } else {\n throw new Error(\n `Generated index file not found at ${basePath}.{js,ts}. Run \\`agent-runtime generate\\` first.`,\n );\n }\n\n const mod = await import(new URL(`file://${indexPath}`).href);\n\n let guardrailHooks: GuardrailHooks | undefined;\n const resolvedDsl = mod.resolvedDsl as Record<string, unknown> | undefined;\n if (resolvedDsl) {\n const rawRules = resolvedDsl._guardrailRules as GuardrailRuleData | undefined;\n if (\n rawRules &&\n (rawRules.commandRules?.length ||\n rawRules.fileRules?.length ||\n rawRules.contentRules?.length)\n ) {\n guardrailHooks = createGuardrailHooksFromRules(rawRules);\n }\n }\n\n return {\n agentRegistry: mod.agentRegistry ?? mod.agents?.agentRegistry ?? {},\n taskRegistry: mod.taskRegistry ?? mod.tasks?.taskRegistry ?? {},\n handoffSchemas: mod.handoffSchemas ?? mod.handoffs?.handoffSchemas ?? {},\n workflowRegistry: mod.workflowRegistry ?? mod.workflows?.workflowRegistry ?? {},\n guardrailHooks,\n };\n}\n\nasync function createAdapter(\n adapterName: string,\n guardrailHooks?: GuardrailHooks,\n cwd?: string,\n model?: string,\n): Promise<SdkAdapter> {\n switch (adapterName) {\n case \"mock\": {\n const { MockAdapter } = await import(\"../adapters/mock.js\");\n return new MockAdapter();\n }\n case \"claude\": {\n const { ClaudeAgentSdkAdapter } = await import(\"../adapters/claude-agent-sdk.js\");\n return new ClaudeAgentSdkAdapter({ cwd, guardrailHooks, ...(model ? { model } : {}) });\n }\n case \"gemini\": {\n // The \"gemini\" selector now targets Gemini models via Google ADK, which\n // provides the native subagent mechanism required for LLM-internal routing.\n const { AdkSdkAdapter } = await import(\"../adapters/adk-sdk.js\");\n return new AdkSdkAdapter({ guardrailHooks, ...(model ? { model } : {}) });\n }\n case \"openai\": {\n const { OpenAIAgentsSdkAdapter } = await import(\"../adapters/openai-agents-sdk.js\");\n return new OpenAIAgentsSdkAdapter({ guardrailHooks, ...(model ? { model } : {}) });\n }\n default:\n throw new Error(`Unknown adapter: ${adapterName}. Available: mock, claude, gemini, openai`);\n }\n}\n\nfunction formatTable(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n const sep = widths.map((w) => \"-\".repeat(w)).join(\" \");\n const pad = (s: string, w: number) => s.padEnd(w);\n const headerLine = headers.map((h, i) => pad(h, widths[i])).join(\" \");\n const dataLines = rows.map((r) =>\n r.map((c, i) => pad(c ?? \"\", widths[i])).join(\" \"),\n );\n return [headerLine, sep, ...dataLines].join(\"\\n\");\n}\n\nfunction resolveProgressSink(\n cliLogFile: string | undefined,\n configLog: ResolvedProgressLog | undefined,\n quiet: boolean,\n label: string,\n): ProgressSink | undefined {\n if (cliLogFile) {\n return createProgressSink({\n stderr: !quiet,\n file: resolve(cliLogFile),\n naming: \"single\",\n label,\n });\n }\n\n if (configLog && configLog.destination !== \"none\") {\n const dest = configLog.destination;\n return createProgressSink({\n stderr: !quiet && (dest === \"stderr\" || dest === \"both\"),\n file: (dest === \"file\" || dest === \"both\") ? configLog.file : undefined,\n naming: configLog.naming,\n label,\n });\n }\n\n if (quiet) return undefined;\n return createProgressSink({ stderr: true });\n}\n\nconst handlers: CommandHandlers = {\n async init(options, _globalOpts) {\n try {\n const outputDir = resolve(options.output ?? \".\");\n const result = await runInit({\n adapter: options.adapter ?? \"mock\",\n outputDir,\n force: options.force ?? false,\n });\n console.log(JSON.stringify(result, null, 2));\n } catch (err) {\n console.error((err as Error).message);\n process.exit(1);\n }\n },\n\n async generate(options, globalOpts) {\n try {\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n const result = await generate({\n clean: options.clean,\n check: options.check,\n templates: options.templates,\n configPath,\n });\n\n if (result.check_mode) {\n if (result.has_differences) {\n console.error(\"Generated files are out of date. Run `agent-runtime generate` to update.\");\n process.exit(1);\n }\n console.log(JSON.stringify({ ...result, status: \"up-to-date\" }, null, 2));\n } else {\n console.log(JSON.stringify(result, null, 2));\n }\n } catch (err) {\n console.error(\"Generate failed:\", (err as Error).message);\n process.exit(1);\n }\n },\n\n async run(workflowId, userRequest, options, globalOpts) {\n // --- Resolve input: --file takes precedence over positional args ---\n let resolvedWorkflowId = workflowId;\n let resolvedUserRequest = userRequest;\n let fileInvocation: WorkflowInvocation | undefined;\n\n if (options.file) {\n try {\n const raw = readFileSync(options.file, \"utf8\");\n const parsed = YAML.parse(raw) as Record<string, unknown>;\n resolvedWorkflowId = parsed.workflow as string;\n if (!resolvedWorkflowId) {\n console.error(`Error: invocation file \"${options.file}\" must contain a \"workflow\" field.`);\n process.exit(3);\n }\n fileInvocation = {\n workflow: resolvedWorkflowId,\n user_request: parsed.user_request as string | undefined,\n handoff: parsed.handoff as WorkflowInvocation[\"handoff\"],\n runtime: parsed.runtime as WorkflowInvocation[\"runtime\"],\n context: parsed.context as WorkflowInvocation[\"context\"],\n };\n resolvedUserRequest = fileInvocation.user_request ?? \"\";\n } catch (err) {\n console.error(`Failed to read invocation file: ${(err as Error).message}`);\n process.exit(3);\n }\n }\n\n if (!resolvedWorkflowId) {\n console.error(\"Error: workflow-id is required (provide as argument or via --file)\");\n process.exit(3);\n }\n if (!fileInvocation && !resolvedUserRequest) {\n console.error(\"Error: user-request is required (provide as argument or via --file)\");\n process.exit(3);\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n\n const fresh = await checkFreshness(configPath);\n if (!fresh) {\n console.error(\"Generated files are stale or missing. Run `agent-runtime generate` first.\");\n process.exit(3);\n }\n\n const config = await loadConfig(configPath);\n\n const pluginResult = await loadPlugins({\n pluginPaths: config.pluginPaths.length > 0 ? config.pluginPaths : undefined,\n projectDir: config.configDir,\n });\n if (pluginResult.loaded > 0 && !(globalOpts.quiet as boolean)) {\n console.error(`Loaded ${pluginResult.loaded} plugin(s) from ${pluginResult.files.length} file(s)`);\n }\n for (const err of pluginResult.errors) {\n console.error(`Plugin load error (${err.file}): ${err.error}`);\n }\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n process.exit(1);\n return;\n }\n\n if (!contracts.workflowRegistry[resolvedWorkflowId]) {\n console.error(`Unknown workflow: ${resolvedWorkflowId}`);\n console.error(`Available workflows: ${Object.keys(contracts.workflowRegistry).join(\", \")}`);\n process.exit(3);\n return;\n }\n\n const adapterName = (options.adapter as string) ?? \"mock\";\n const adapterCwd = fileInvocation?.context?.cwd ?? process.cwd();\n\n const { createModelResolver } = await import(\"../lib/model-resolver.js\");\n type ModelClassType = import(\"../lib/model-resolver.js\").ModelClass;\n const modelResolver = createModelResolver({\n modelMapping: config.model_mapping,\n fallbackAdapter: adapterName,\n });\n\n const adapterCache = new Map<string, SdkAdapter>();\n const modelAwareFactory = async (modelClass?: ModelClassType): Promise<SdkAdapter> => {\n const resolved = modelResolver.resolve(modelClass);\n const cacheKey = `${resolved.adapter}:${resolved.model ?? \"\"}`;\n const cached = adapterCache.get(cacheKey);\n if (cached) return cached;\n const adapter = await createAdapter(resolved.adapter, contracts.guardrailHooks, adapterCwd, resolved.model);\n adapterCache.set(cacheKey, adapter);\n return adapter;\n };\n\n let defaultAdapter: SdkAdapter;\n try {\n defaultAdapter = await modelAwareFactory();\n } catch (err) {\n console.error((err as Error).message);\n process.exit(12);\n return;\n }\n\n const hasModelMapping = Object.values(config.model_mapping).some(Boolean)\n || process.env.AGENT_RUNTIME_MODEL\n || process.env.AGENT_RUNTIME_MODEL_FAST\n || process.env.AGENT_RUNTIME_MODEL_STANDARD\n || process.env.AGENT_RUNTIME_MODEL_THINKING;\n\n const adapterOrFactory = hasModelMapping ? modelAwareFactory : defaultAdapter;\n\n const recovery = config.recovery;\n const maxRetries = options.maxRetries\n ? parseInt(options.maxRetries, 10)\n : undefined;\n const maxFollowUps = options.maxFollowUps\n ? parseInt(options.maxFollowUps, 10)\n : undefined;\n\n const registries = {\n workflowRegistry: contracts.workflowRegistry,\n taskRegistry: contracts.taskRegistry,\n agentRegistry: contracts.agentRegistry,\n handoffSchemas: contracts.handoffSchemas,\n };\n\n const onGate = options.autoApproveGates\n ? async () => true\n : async (gateKind: string, description: string) => {\n console.error(`Gate \"${gateKind}\": ${description}`);\n console.error(\"Use --auto-approve-gates to auto-approve. Rejecting by default.\");\n return false;\n };\n\n const progressSink = resolveProgressSink(\n options.logFile as string | undefined,\n config.resolvedLogging.progressLog,\n globalOpts.quiet as boolean,\n resolvedWorkflowId,\n );\n\n let result;\n try {\n if (fileInvocation) {\n const invocation: WorkflowInvocation = {\n ...fileInvocation,\n runtime: {\n ...fileInvocation.runtime,\n maxFollowUps: maxFollowUps ?? fileInvocation.runtime?.maxFollowUps ?? recovery.max_follow_ups,\n maxRetries: maxRetries ?? fileInvocation.runtime?.maxRetries ?? recovery.max_retries,\n },\n hooks: { onGate },\n progressOutput: progressSink,\n };\n result = await runWorkflow(adapterOrFactory, invocation, registries);\n } else {\n result = await runWorkflow(adapterOrFactory, resolvedWorkflowId, {\n user_request: resolvedUserRequest!,\n maxRetries: maxRetries ?? recovery.max_retries,\n maxFollowUps: maxFollowUps ?? recovery.max_follow_ups,\n onGate,\n progressOutput: progressSink,\n }, registries);\n }\n } finally {\n progressSink?.close();\n }\n\n console.log(JSON.stringify(result, null, 2));\n\n if (result.status !== \"completed\") {\n process.exit(1);\n }\n },\n\n async list(resource, options, globalOpts) {\n if (!resource) {\n console.error(\"Error: resource is required (workflows, tasks, agents)\");\n process.exit(1);\n }\n\n const validResources = [\"workflows\", \"tasks\", \"agents\"];\n if (!validResources.includes(resource)) {\n console.error(`Unknown resource: ${resource}`);\n console.error(`Available resources: ${validResources.join(\", \")}`);\n process.exit(1);\n return;\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n console.error(\"Run `agent-runtime generate` first.\");\n process.exit(1);\n return;\n }\n\n const format = options.format ?? \"table\";\n\n if (resource === \"agents\") {\n const agents = Object.values(contracts.agentRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(agents, null, 2));\n } else {\n if (agents.length === 0) {\n console.log(\"No agents defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Role\", \"Mode\", \"Purpose\"],\n agents.map((a) => [a.id, a.role_name, a.mode, a.purpose]),\n ));\n }\n } else if (resource === \"tasks\") {\n const tasks = Object.values(contracts.taskRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(tasks, null, 2));\n } else {\n if (tasks.length === 0) {\n console.log(\"No tasks defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Agent\", \"Description\"],\n tasks.map((t) => [t.id, t.target_agent, t.description]),\n ));\n }\n } else {\n const workflows = Object.values(contracts.workflowRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(workflows, null, 2));\n } else {\n if (workflows.length === 0) {\n console.log(\"No workflows defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Steps\", \"Description\"],\n workflows.map((w) => [w.id, String(w.steps.length), w.description]),\n ));\n }\n }\n },\n\n async showPrompt(taskId, options, globalOpts) {\n if (!taskId) {\n console.error(\"Error: task-id is required\");\n process.exit(1);\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n console.error(\"Run `agent-runtime generate` first.\");\n process.exit(1);\n return;\n }\n\n const task = contracts.taskRegistry[taskId];\n if (!task) {\n console.error(`Unknown task: ${taskId}`);\n console.error(`Available tasks: ${Object.keys(contracts.taskRegistry).join(\", \")}`);\n process.exit(1);\n return;\n }\n\n const agent = contracts.agentRegistry[task.target_agent];\n if (!agent) {\n console.error(`Unknown agent: ${task.target_agent} (referenced by task ${taskId})`);\n process.exit(1);\n return;\n }\n\n const showPromptConfig = await loadConfig(configPath);\n const pluginsApplied = options.withPlugins ?? false;\n if (pluginsApplied) {\n await loadPlugins({\n pluginPaths: showPromptConfig.pluginPaths.length > 0 ? showPromptConfig.pluginPaths : undefined,\n projectDir: showPromptConfig.configDir,\n });\n }\n\n const userRequest = options.userRequest ?? \"(preview)\";\n let context: TaskContext = { user_request: userRequest };\n\n if (pluginsApplied) {\n const modified = await pluginRegistry.runBeforeTask(taskId, context);\n if (modified === null) {\n console.error(`Task \"${taskId}\" skipped by plugin`);\n process.exit(1);\n return;\n }\n context = pluginRegistry.applyContextEnhancers(taskId, modified);\n }\n\n let prompt = buildTaskPrompt(agent, task, context, {\n handoffSchemas: contracts.handoffSchemas,\n });\n\n if (pluginsApplied) {\n prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, context);\n }\n\n const format = options.format ?? \"markdown\";\n if (format === \"json\") {\n console.log(JSON.stringify({\n task_id: taskId,\n agent_id: task.target_agent,\n prompt,\n handoff_schema: task.result_handoff,\n plugins_applied: pluginsApplied,\n }, null, 2));\n } else {\n console.log(prompt);\n }\n },\n\n async implement(description, options, globalOpts) {\n if (!description) {\n console.error(\"Error: description is required\");\n process.exit(3);\n }\n\n const quiet = globalOpts.quiet as boolean;\n const progressSink = options.logFile\n ? createProgressSink({ stderr: !quiet, file: resolve(options.logFile), naming: \"single\" })\n : quiet ? undefined : createProgressSink({ stderr: true });\n\n let result;\n try {\n result = await runImplement(description, {\n adapter: options.adapter ?? \"claude\",\n projectDir: options.projectDir ?? \".\",\n dryRun: options.dryRun ?? false,\n model: options.model as string | undefined,\n reportFormat: (options.reportFormat as \"json\" | \"text\" | \"yaml\") ?? \"text\",\n progressOutput: progressSink,\n });\n } finally {\n progressSink?.close();\n }\n\n if (result.status === \"failed\") {\n if (options.reportFormat === \"json\") {\n console.log(JSON.stringify({ error: result.error, status: \"failed\" }, null, 2));\n } else if (options.reportFormat === \"yaml\") {\n console.log(YAML.stringify({ error: result.error, status: \"failed\" }));\n } else {\n console.error(formatImplementResult(result));\n }\n process.exit(result.exitCode ?? 1);\n }\n\n const outputData = result.data ?? { status: result.status };\n let output: string;\n if (options.reportFormat === \"json\") {\n output = JSON.stringify(outputData, null, 2);\n } else if (options.reportFormat === \"yaml\") {\n output = YAML.stringify(outputData);\n } else {\n output = formatImplementResult(result);\n }\n\n const outputPath = options.output as string | undefined;\n if (outputPath) {\n writeFileSync(outputPath, output + \"\\n\");\n } else {\n console.log(output);\n }\n },\n\n async auditImplementation(projectDir, options, globalOpts) {\n const quiet = globalOpts.quiet as boolean;\n const progressSink = options.logFile\n ? createProgressSink({ stderr: !quiet, file: resolve(options.logFile), naming: \"single\" })\n : quiet ? undefined : createProgressSink({ stderr: true });\n\n let result;\n try {\n result = await runAuditImplementation({\n adapter: options.adapter ?? \"claude\",\n projectDir: projectDir ?? \".\",\n focus: (options.focus as \"all\" | \"dsl\" | \"runtime\" | \"cli-contract\" | \"architecture\") ?? \"all\",\n dryRun: options.dryRun ?? false,\n failOn: (options.failOn as \"warning\" | \"error\" | \"critical\") ?? \"error\",\n model: options.model as string | undefined,\n reportFormat: (options.reportFormat as \"json\" | \"text\" | \"yaml\") ?? \"text\",\n progressOutput: progressSink,\n });\n } finally {\n progressSink?.close();\n }\n\n if (result.status === \"failed\") {\n if (options.reportFormat === \"json\") {\n console.log(JSON.stringify({ error: result.error, status: \"failed\" }, null, 2));\n } else if (options.reportFormat === \"yaml\") {\n console.log(YAML.stringify({ error: result.error, status: \"failed\" }));\n } else {\n console.error(formatAuditResult(result));\n }\n process.exit(result.exitCode);\n }\n\n const outputData = result.data ?? { status: result.status };\n let output: string;\n if (options.reportFormat === \"json\") {\n output = JSON.stringify(outputData, null, 2);\n } else if (options.reportFormat === \"yaml\") {\n output = YAML.stringify(outputData);\n } else {\n output = formatAuditResult(result);\n }\n\n const outputPath = options.output as string | undefined;\n if (outputPath) {\n writeFileSync(outputPath, output + \"\\n\");\n } else {\n console.log(output);\n }\n\n if (result.exitCode !== 0) {\n process.exit(result.exitCode);\n }\n },\n\n async agents(options, _globalOpts) {\n const format = options.format ?? \"yaml\";\n try {\n if (format === \"json\") {\n console.log(JSON.stringify(resolvedDsl, null, 2));\n } else {\n console.log(YAML.stringify(resolvedDsl, { lineWidth: 120 }));\n }\n } catch (err) {\n console.error(`Failed to output DSL: ${(err as Error).message}`);\n process.exit(1);\n }\n },\n\n async doctor(globalOpts) {\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n const result = await runDoctor(configPath);\n\n const statusIcon = (s: string) =>\n s === \"pass\" ? \"✓\" : s === \"warn\" ? \"!\" : \"✗\";\n\n for (const check of result.checks) {\n const icon = statusIcon(check.status);\n const msg = check.message ? ` ${check.message}` : \"\";\n console.log(` ${icon} ${check.name.padEnd(20)} ${check.status.toUpperCase()}${msg}`);\n }\n\n console.log(\"\");\n if (result.all_passed) {\n console.log(\"All checks passed.\");\n } else {\n console.log(\"Some checks failed.\");\n }\n\n console.log(JSON.stringify(result));\n\n if (!result.all_passed) {\n process.exitCode = 1;\n }\n },\n\n};\n\nconst program = createProgram(handlers, VERSION);\nawait program.parseAsync();\n","// Auto-generated by cli-contracts. Do not edit.\nimport { Command } from \"commander\";\nimport { CONTRACT_YAML, CONTRACT_JSON_STR } from \"./contract.js\";\n\nexport interface CommandHandlers {\n init: (options: { adapter?: string; output?: string; force?: boolean; showPrompt?: boolean }, parentOpts: Record<string, unknown>) => Promise<void | string>;\n generate: (options: { clean?: boolean; check?: boolean; templates?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n run: (workflowId: string | undefined, userRequest: string | undefined, options: { adapter?: string; maxRetries?: string; maxFollowUps?: string; dryRun?: boolean; autoApproveGates?: boolean; file?: string; logFile?: string; showPrompt?: boolean }, parentOpts: Record<string, unknown>) => Promise<void | string>;\n list: (resource: string | undefined, options: { format?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n showPrompt: (taskId: string | undefined, options: { userRequest?: string; format?: string; withPlugins?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n implement: (description: string | undefined, options: { adapter?: string; projectDir?: string; dryRun?: boolean; model?: string; output?: string; reportFormat?: string; logFile?: string; showPrompt?: boolean }, parentOpts: Record<string, unknown>) => Promise<void | string>;\n auditImplementation: (projectDir: string | undefined, options: { adapter?: string; focus?: string; dryRun?: boolean; failOn?: string; model?: string; output?: string; reportFormat?: string; logFile?: string; showPrompt?: boolean }, parentOpts: Record<string, unknown>) => Promise<void | string>;\n agents: (options: { format?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n doctor: (options: Record<string, never>, parentOpts: Record<string, unknown>) => Promise<void>;\n}\n\nexport function createProgram(\n handlers: CommandHandlers,\n version: string,\n): Command {\n const program = new Command();\n program\n .name(\"agent-runtime\")\n .version(version, \"-V, --version\")\n .description(\"CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\");\n\n program.option(\"-c, --config <value>\", \"Path to agents.conf.yaml (project runtime config).\", \"./agents.conf.yaml\");\n program.option(\"-v, --verbose\", \"Enable verbose output.\", false);\n program.option(\"-q, --quiet\", \"Suppress non-error output.\", false);\n\n program\n .command(\"init\")\n .description(\"Initialize runtime scaffolding for a project.\")\n .option(\"-a, --adapter <value>\", \"Default SDK adapter to configure.\", \"mock\")\n .option(\"-o, --output <value>\", \"Output directory for generated scaffolding.\", \".\")\n .option(\"-f, --force\", \"Overwrite existing files without prompting.\", false)\n .option(\"--show-prompt\", \"Output the constructed prompt without calling the LLM API.\", false)\n .action(async (opts, cmd) => {\n if (opts.showPrompt) {\n const prompt = await handlers.init(opts, cmd.optsWithGlobals());\n if (typeof prompt === \"string\") process.stdout.write(prompt + \"\\n\");\n return;\n }\n await handlers.init(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"generate\")\n .description(\"Generate runtime contracts and hooks from DSL.\")\n .option(\"--clean\", \"Delete generated_dir before regenerating.\\nRemoves stale files that may remain from previous generations.\\n\", false)\n .option(\"--check\", \"Dry-run mode for CI. Does not write files.\\nCompares current generated output with what would be regenerated.\\nExits with code 1 if any differences are found.\\n\", false)\n .option(\"-t, --templates <value>\", \"Custom templates directory. Overrides built-in templates.\")\n .action(async (opts, cmd) => {\n await handlers.generate(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"run\")\n .description(\"Execute a workflow.\")\n .argument(\"[workflow-id]\", \"ID of the workflow to execute. Required unless --file is used.\")\n .argument(\"[user-request]\", \"Natural language description of what to do. Required unless --file is used.\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use. Overrides config.\")\n .option(\"-r, --max-retries <value>\", \"Override default max retries per step.\")\n .option(\"-f, --max-follow-ups <value>\", \"Override default max follow-ups per step.\")\n .option(\"-n, --dry-run\", \"Simulate execution without calling the SDK adapter.\", false)\n .option(\"--auto-approve-gates\", \"Automatically approve all gate steps.\", false)\n .option(\"--file <value>\", \"Path to a YAML invocation file. When provided, workflow-id and\\nuser-request arguments are read from the file instead of CLI args.\\n\")\n .option(\"-l, --log-file <value>\", \"Write agent progress log to this file. Overrides config logging.progress_log.\")\n .option(\"--show-prompt\", \"Output the constructed prompt without calling the LLM API.\", false)\n .action(async (workflowId, userRequest, opts, cmd) => {\n if (opts.showPrompt) {\n const prompt = await handlers.run(workflowId, userRequest, opts, cmd.optsWithGlobals());\n if (typeof prompt === \"string\") process.stdout.write(prompt + \"\\n\");\n return;\n }\n await handlers.run(workflowId, userRequest, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"list\")\n .description(\"List available workflows, tasks, or agents.\")\n .argument(\"<resource>\", \"Type of resource to list.\")\n .option(\"--format <value>\", \"Output format.\", \"table\")\n .action(async (resource, opts, cmd) => {\n await handlers.list(resource, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"show-prompt\")\n .description(\"Display the generated prompt for a task.\")\n .argument(\"<task-id>\", \"ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).\")\n .option(\"-u, --user-request <value>\", \"User request text to include in the prompt preview.\", \"(preview)\")\n .option(\"--format <value>\", \"Output format.\", \"markdown\")\n .option(\"--with-plugins\", \"Apply registered plugin prompt enhancers to the output.\", false)\n .action(async (taskId, opts, cmd) => {\n await handlers.showPrompt(taskId, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"implement\")\n .description(\"Implement LLM-powered commands in a CLI tool.\")\n .argument(\"<description>\", \"Natural language description of the LLM feature(s) to implement. Examples: \\\"Add an audit command for migration safety\\\", \\\"Add propose and explain commands for SQL optimization\\\".\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use. Must be an agentic adapter (claude).\", \"claude\")\n .option(\"-p, --project-dir <value>\", \"Path to the target project directory.\", \".\")\n .option(\"-n, --dry-run\", \"Output the prompt context without calling the LLM.\", false)\n .option(\"--model <value>\", \"Model name override for the selected adapter.\")\n .option(\"-o, --output <value>\", \"Write the result to a file instead of stdout.\")\n .option(\"--report-format <value>\", \"Output format for the result.\", \"text\")\n .option(\"-l, --log-file <value>\", \"Write agent progress log to this file.\")\n .option(\"--show-prompt\", \"Output the constructed prompt without calling the LLM API.\", false)\n .action(async (description, opts, cmd) => {\n if (opts.showPrompt) {\n const prompt = await handlers.implement(description, opts, cmd.optsWithGlobals());\n if (typeof prompt === \"string\") process.stdout.write(prompt + \"\\n\");\n return;\n }\n await handlers.implement(description, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"audit-implementation\")\n .description(\"Audit an LLM command integration for pattern conformance.\")\n .argument(\"[project-dir]\", \"Path to the project directory to audit. Defaults to current directory.\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use for the audit agent.\", \"claude\")\n .option(\"--focus <value>\", \"Limit audit to a specific layer. Defaults to all layers.\", \"all\")\n .option(\"-n, --dry-run\", \"Output the prompt context without calling the LLM.\", false)\n .option(\"--fail-on <value>\", \"Minimum finding severity that causes a non-zero exit.\", \"error\")\n .option(\"--model <value>\", \"Model name override for the selected adapter.\")\n .option(\"-o, --output <value>\", \"Write the result to a file instead of stdout.\")\n .option(\"--report-format <value>\", \"Output format for the audit report.\", \"text\")\n .option(\"-l, --log-file <value>\", \"Write agent progress log to this file.\")\n .option(\"--show-prompt\", \"Output the constructed prompt without calling the LLM API.\", false)\n .action(async (projectDir, opts, cmd) => {\n if (opts.showPrompt) {\n const prompt = await handlers.auditImplementation(projectDir, opts, cmd.optsWithGlobals());\n if (typeof prompt === \"string\") process.stdout.write(prompt + \"\\n\");\n return;\n }\n await handlers.auditImplementation(projectDir, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"agents\")\n .description(\"Output the full resolved DSL as structured data.\")\n .option(\"-F, --format <value>\", \"Output format.\", \"yaml\")\n .action(async (opts, cmd) => {\n await handlers.agents(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"doctor\")\n .description(\"Verify configuration, generated files, and SDK connectivity.\")\n .action(async (opts, cmd) => {\n await handlers.doctor({}, cmd.optsWithGlobals());\n });\n\n\n // Built-in extract command (auto-injected by cli-contracts)\n program\n .command(\"extract\")\n .description(\"Extract contract specification for this CLI tool.\")\n .argument(\"[commands...]\", \"Command IDs to extract. Use dot notation.\")\n .option(\"-a, --all\", \"Extract all commands.\", false)\n .option(\"--include-meta\", \"Include extraction metadata.\", true)\n .option(\"-F, --format <format>\", \"Output format (yaml or json).\", \"yaml\")\n .action(async (commands: string[], opts: { all?: boolean; includeMeta?: boolean; format?: string }, cmd: Command) => {\n if (commands.length === 0 && !opts.all) {\n process.stderr.write(JSON.stringify({ code: \"INVALID_ARGS\", message: \"Specify command IDs or use --all\" }) + \"\\n\");\n process.exit(2);\n }\n\n const format = opts.format || \"yaml\";\n const doc = JSON.parse(CONTRACT_JSON_STR);\n const cmdIds = opts.all ? [] : commands;\n\n if (cmdIds.length === 0) {\n // --all: output full contract\n if (format === \"json\") {\n const out: Record<string, unknown> = {};\n if (opts.includeMeta) {\n out._meta = {\n source: \"embedded\",\n type: \"cli-contracts/extract\",\n extractedAt: new Date().toISOString(),\n specVersion: doc.cli_contracts ?? \"0.1.0\",\n commands: [\"agent-runtime.init\",\"agent-runtime.generate\",\"agent-runtime.run\",\"agent-runtime.list\",\"agent-runtime.show-prompt\",\"agent-runtime.implement\",\"agent-runtime.audit-implementation\",\"agent-runtime.agents\",\"agent-runtime.doctor\"],\n };\n }\n Object.assign(out, doc);\n process.stdout.write(JSON.stringify(out, null, 2) + \"\\n\");\n } else {\n // YAML output\n const yamlLines: string[] = [];\n yamlLines.push(\"# agent-runtime extract\");\n yamlLines.push(\"# source: embedded\");\n yamlLines.push(\"# type: cli-contracts/command-extract\");\n if (opts.includeMeta) {\n yamlLines.push(\"---\");\n yamlLines.push(\"source: embedded\");\n yamlLines.push(\"type: cli-contracts/command-extract\");\n yamlLines.push(\"extractedAt: \" + new Date().toISOString());\n yamlLines.push(\"spec_version: \" + (doc.cli_contracts ?? \"0.1.0\"));\n yamlLines.push(\"commands:\");\n for (const id of [\"agent-runtime.init\",\"agent-runtime.generate\",\"agent-runtime.run\",\"agent-runtime.list\",\"agent-runtime.show-prompt\",\"agent-runtime.implement\",\"agent-runtime.audit-implementation\",\"agent-runtime.agents\",\"agent-runtime.doctor\"]) {\n yamlLines.push(\" - \" + id);\n }\n }\n yamlLines.push(\"---\");\n yamlLines.push(CONTRACT_YAML);\n process.stdout.write(yamlLines.join(\"\\n\") + \"\\n\");\n }\n } else {\n // Filter specific commands\n const filtered: Record<string, unknown> = {\n cli_contracts: doc.cli_contracts,\n info: doc.info,\n command_sets: {},\n };\n const fcs = filtered.command_sets as Record<string, Record<string, unknown>>;\n for (const [setId, cs] of Object.entries(doc.command_sets ?? {})) {\n const cmds = (cs as Record<string, unknown>).commands as Record<string, unknown> | undefined;\n if (!cmds) continue;\n const matched: Record<string, unknown> = {};\n for (const [cmdId, cmdDef] of Object.entries(cmds)) {\n const fullId = setId + \".\" + cmdId;\n if (cmdIds.some((id) => id === cmdId || id === fullId || cmdId.startsWith(id + \".\"))) {\n matched[cmdId] = cmdDef;\n }\n }\n if (Object.keys(matched).length > 0) {\n const setCopy = { ...(cs as Record<string, unknown>) };\n setCopy.commands = matched;\n fcs[setId] = setCopy;\n }\n }\n if (doc.components) filtered.components = doc.components;\n process.stdout.write(JSON.stringify(filtered, null, 2) + \"\\n\");\n }\n process.exit(0);\n });\n return program;\n}\n","// Auto-generated by cli-contracts. Do not edit.\n// Embedded contract for the extract subcommand.\n\nexport const CONTRACT_YAML: string = \"cli_contracts: 0.1.0\\n\\ninfo:\\n title: agent-runtime CLI\\n version: 0.36.0\\n description: |\\n Runtime bridge for executing agent-contracts workflows on Agent SDKs.\\n Generates typed contracts, handoff validators, and guardrail hooks from DSL,\\n then runs workflows through pluggable SDK adapters.\\n license:\\n name: MIT\\n\\ncommand_sets:\\n agent-runtime:\\n summary: CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\\n global_options:\\n - name: config\\n aliases: [c]\\n description: Path to agents.conf.yaml (project runtime config).\\n schema:\\n type: string\\n default: ./agents.conf.yaml\\n file:\\n mode: read\\n exists: true\\n media_type: application/yaml\\n\\n - name: verbose\\n aliases: [v]\\n description: Enable verbose output.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: quiet\\n aliases: [q]\\n description: Suppress non-error output.\\n schema:\\n type: boolean\\n default: false\\n\\n commands:\\n # -----------------------------------------------------------------------\\n # init\\n # -----------------------------------------------------------------------\\n init:\\n summary: Initialize runtime scaffolding for a project.\\n description: |\\n Generates the initial directory structure and configuration files\\n for using agent-contracts-runtime in a project.\\n Creates agents.conf.yaml and agent/src/ user code templates.\\n options:\\n - name: adapter\\n aliases: [a]\\n description: Default SDK adapter to configure.\\n schema:\\n type: string\\n enum: [claude, gemini, openai, mock]\\n default: mock\\n\\n - name: output\\n aliases: [o]\\n description: Output directory for generated scaffolding.\\n schema:\\n type: string\\n default: \\\".\\\"\\n\\n - name: force\\n aliases: [f]\\n description: Overwrite existing files without prompting.\\n schema:\\n type: boolean\\n default: false\\n\\n exits:\\n \\\"0\\\":\\n description: Scaffolding generated successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/InitResult\\\"\\n\\n \\\"1\\\":\\n description: Initialization failed (existing files, permission error, etc.).\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: false\\n sideEffects:\\n - filesystem_write\\n safeDryRunOption: \\\"\\\"\\n\\n # -----------------------------------------------------------------------\\n # generate\\n # -----------------------------------------------------------------------\\n generate:\\n summary: Generate runtime contracts and hooks from DSL.\\n description: |\\n Reads agent-contracts.yaml, resolves the DSL, validates it,\\n and generates typed contracts, handoff schemas, guardrail hooks,\\n and a runtime manifest into the configured generated_dir.\\n\\n Each generated file includes a DO NOT EDIT header.\\n options:\\n - name: clean\\n description: |\\n Delete generated_dir before regenerating.\\n Removes stale files that may remain from previous generations.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: check\\n description: |\\n Dry-run mode for CI. Does not write files.\\n Compares current generated output with what would be regenerated.\\n Exits with code 1 if any differences are found.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: templates\\n aliases: [t]\\n description: Custom templates directory. Overrides built-in templates.\\n schema:\\n type: string\\n\\n exits:\\n \\\"0\\\":\\n description: Generation completed successfully (or --check found no differences).\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/GenerateResult\\\"\\n\\n \\\"1\\\":\\n description: |\\n Generation failed, or --check detected differences between\\n current generated files and expected output.\\n stderr:\\n format: text\\n\\n \\\"2\\\":\\n description: DSL validation error. The input DSL has structural or semantic issues.\\n stderr:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/ValidationError\\\"\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects:\\n - filesystem_write\\n safeDryRunOption: check\\n\\n # -----------------------------------------------------------------------\\n # run\\n # -----------------------------------------------------------------------\\n run:\\n summary: Execute a workflow.\\n description: |\\n Loads generated contracts, creates an SDK adapter, registers user plugins,\\n and executes the specified workflow with the given user request.\\n\\n The workflow runner orchestrates task delegation, retry, gate handling,\\n and handoff validation mechanically.\\n arguments:\\n - name: workflow-id\\n required: false\\n description: ID of the workflow to execute. Required unless --file is used.\\n schema:\\n type: string\\n\\n - name: user-request\\n required: false\\n description: Natural language description of what to do. Required unless --file is used.\\n schema:\\n type: string\\n\\n options:\\n - name: adapter\\n aliases: [a]\\n description: SDK adapter to use. Overrides config.\\n schema:\\n type: string\\n enum: [claude, gemini, openai, mock]\\n\\n - name: max-retries\\n aliases: [r]\\n description: Override default max retries per step.\\n schema:\\n type: integer\\n minimum: 0\\n maximum: 10\\n\\n - name: max-follow-ups\\n aliases: [f]\\n description: Override default max follow-ups per step.\\n schema:\\n type: integer\\n minimum: 0\\n maximum: 10\\n\\n - name: dry-run\\n aliases: [n]\\n description: Simulate execution without calling the SDK adapter.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: auto-approve-gates\\n description: Automatically approve all gate steps.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: file\\n description: |\\n Path to a YAML invocation file. When provided, workflow-id and\\n user-request arguments are read from the file instead of CLI args.\\n schema:\\n type: string\\n file:\\n mode: read\\n exists: true\\n media_type: application/yaml\\n\\n - name: log-file\\n aliases: [l]\\n description: Write agent progress log to this file. Overrides config logging.progress_log.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n exits:\\n \\\"0\\\":\\n description: Workflow completed successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/WorkflowResult\\\"\\n\\n \\\"1\\\":\\n description: Workflow failed (escalation, error, or gate rejection).\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/WorkflowResult\\\"\\n stderr:\\n format: text\\n\\n \\\"3\\\":\\n description: >-\\n Input validation failed (invalid arguments, unknown workflow/adapter,\\n or generated files outdated).\\n stderr:\\n format: text\\n\\n \\\"12\\\":\\n description: Adapter initialization error (missing API key, etc.).\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: high\\n requiresConfirmation: true\\n idempotent: false\\n sideEffects:\\n - sdk_call\\n - filesystem_write\\n safeDryRunOption: dry-run\\n expectedDurationMs: 300000\\n recommendedBeforeUse:\\n - Run `agent-runtime generate --check` to ensure contracts are up to date.\\n - Run `agent-runtime doctor` to verify SDK configuration.\\n\\n # -----------------------------------------------------------------------\\n # list\\n # -----------------------------------------------------------------------\\n list:\\n summary: List available workflows, tasks, or agents.\\n description: |\\n Reads generated contracts and displays available resources.\\n Useful for discovering what workflows, tasks, and agents\\n are defined in the current project.\\n arguments:\\n - name: resource\\n required: true\\n description: Type of resource to list.\\n schema:\\n type: string\\n enum: [workflows, tasks, agents]\\n\\n options:\\n - name: format\\n description: Output format.\\n schema:\\n type: string\\n enum: [table, json]\\n default: table\\n\\n exits:\\n \\\"0\\\":\\n description: Resources listed successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/ListResult\\\"\\n\\n \\\"1\\\":\\n description: Failed to load contracts.\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: []\\n\\n # -----------------------------------------------------------------------\\n # show-prompt\\n # -----------------------------------------------------------------------\\n show-prompt:\\n summary: Display the generated prompt for a task.\\n description: |\\n Builds and displays the full prompt that would be sent to an SDK agent\\n for a given task. Useful for inspecting, debugging, and validating\\n prompt content before execution.\\n\\n Shows the agent role, responsibilities, constraints, task details,\\n completion criteria, handoff schema fields, and output format example.\\n arguments:\\n - name: task-id\\n required: true\\n description: ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).\\n schema:\\n type: string\\n\\n options:\\n - name: user-request\\n aliases: [u]\\n description: User request text to include in the prompt preview.\\n schema:\\n type: string\\n default: \\\"(preview)\\\"\\n\\n - name: format\\n description: Output format.\\n schema:\\n type: string\\n enum: [markdown, raw, json]\\n default: markdown\\n\\n - name: with-plugins\\n description: Apply registered plugin prompt enhancers to the output.\\n schema:\\n type: boolean\\n default: false\\n\\n exits:\\n \\\"0\\\":\\n description: Prompt displayed successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/ShowPromptResult\\\"\\n\\n \\\"1\\\":\\n description: Failed to build prompt (unknown task, missing contracts, etc.).\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: []\\n\\n # -----------------------------------------------------------------------\\n # implement\\n # -----------------------------------------------------------------------\\n implement:\\n summary: Implement LLM-powered commands in a CLI tool.\\n description: |\\n Uses an agentic LLM adapter (Claude, etc.) to analyze the\\n target project and implement LLM-powered commands following the\\n agent-contracts + agent-contracts-runtime + cli-contracts stack.\\n\\n The agent reads the project structure, cli-contract.yaml, and existing\\n code, then generates DSL definitions, TypeScript modules (orchestrator,\\n context-builder, formatter), CLI command handlers, and updates the\\n CLI contract with x-agent metadata.\\n\\n Requires an agentic adapter that supports tool use (file read/write).\\n arguments:\\n - name: description\\n required: true\\n description: >-\\n Natural language description of the LLM feature(s) to implement.\\n Examples: \\\"Add an audit command for migration safety\\\",\\n \\\"Add propose and explain commands for SQL optimization\\\".\\n schema:\\n type: string\\n\\n options:\\n - name: adapter\\n aliases: [a]\\n description: SDK adapter to use. Must be an agentic adapter (claude).\\n schema:\\n type: string\\n enum: [claude, mock]\\n default: claude\\n\\n - name: project-dir\\n aliases: [p]\\n description: Path to the target project directory.\\n schema:\\n type: string\\n default: \\\".\\\"\\n\\n - name: dry-run\\n aliases: [n]\\n description: Output the prompt context without calling the LLM.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: model\\n description: Model name override for the selected adapter.\\n schema:\\n type: string\\n\\n - name: output\\n aliases: [o]\\n description: Write the result to a file instead of stdout.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n - name: report-format\\n description: Output format for the result.\\n schema:\\n type: string\\n enum: [json, text, yaml]\\n default: text\\n\\n - name: log-file\\n aliases: [l]\\n description: Write agent progress log to this file.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n exits:\\n \\\"0\\\":\\n description: Implementation completed successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/ImplementResult\\\"\\n\\n \\\"1\\\":\\n description: Implementation failed.\\n stderr:\\n format: text\\n\\n \\\"3\\\":\\n description: Input validation failed (e.g. project directory not found).\\n stderr:\\n format: text\\n\\n \\\"12\\\":\\n description: Adapter initialization error.\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: high\\n requiresConfirmation: true\\n idempotent: false\\n sideEffects:\\n - sdk_call\\n - filesystem_write\\n safeDryRunOption: dry-run\\n expectedDurationMs: 300000\\n retryableExitCodes: [1, 12]\\n recommendedBeforeUse:\\n - Ensure the target project has a cli-contract.yaml or plan to create one.\\n - Run in a clean git working tree so changes can be reviewed.\\n\\n # -----------------------------------------------------------------------\\n # audit-implementation\\n # -----------------------------------------------------------------------\\n audit-implementation:\\n summary: Audit an LLM command integration for pattern conformance.\\n description: |\\n Analyzes a target project's LLM command integration to verify it\\n correctly follows the agent-contracts + agent-contracts-runtime +\\n cli-contracts stack conventions.\\n\\n Checks all three layers:\\n 1. DSL definitions (agents, tasks, workflows, handoff schemas)\\n 2. Runtime integration (adapter usage, runTask/runWorkflow, registries)\\n 3. CLI contract (standard options, x-agent metadata, exit codes)\\n\\n Produces structured findings with severity, category, and\\n concrete remediation steps. Read-only — does not modify files.\\n arguments:\\n - name: project-dir\\n required: false\\n description: >-\\n Path to the project directory to audit. Defaults to current directory.\\n schema:\\n type: string\\n\\n options:\\n - name: adapter\\n aliases: [a]\\n description: SDK adapter to use for the audit agent.\\n schema:\\n type: string\\n enum: [claude, mock]\\n default: claude\\n\\n - name: focus\\n description: >-\\n Limit audit to a specific layer. Defaults to all layers.\\n schema:\\n type: string\\n enum: [all, dsl, runtime, cli-contract, architecture]\\n default: all\\n\\n - name: dry-run\\n aliases: [n]\\n description: Output the prompt context without calling the LLM.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: fail-on\\n description: Minimum finding severity that causes a non-zero exit.\\n schema:\\n type: string\\n enum: [warning, error, critical]\\n default: error\\n\\n - name: model\\n description: Model name override for the selected adapter.\\n schema:\\n type: string\\n\\n - name: output\\n aliases: [o]\\n description: Write the result to a file instead of stdout.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n - name: report-format\\n description: Output format for the audit report.\\n schema:\\n type: string\\n enum: [json, text, yaml]\\n default: text\\n\\n - name: log-file\\n aliases: [l]\\n description: Write agent progress log to this file.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n exits:\\n \\\"0\\\":\\n description: Audit completed with no findings above threshold.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/AuditImplementationResult\\\"\\n\\n \\\"1\\\":\\n description: Audit failed (agent error, unexpected failure).\\n stderr:\\n format: text\\n\\n \\\"3\\\":\\n description: Input validation failed (e.g. project directory not found).\\n stderr:\\n format: text\\n\\n \\\"10\\\":\\n description: Audit completed with findings above --fail-on threshold.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/AuditImplementationResult\\\"\\n\\n \\\"12\\\":\\n description: Adapter initialization error.\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects:\\n - network\\n sideEffectNote: >-\\n Network calls to LLM provider when adapter is not mock.\\n Filesystem write only when --output is specified.\\n safeDryRunOption: dry-run\\n expectedDurationMs: 180000\\n retryableExitCodes: [1, 12]\\n\\n # -----------------------------------------------------------------------\\n # agents\\n # -----------------------------------------------------------------------\\n agents:\\n summary: Output the full resolved DSL as structured data.\\n description: |\\n Outputs the complete resolved DSL (agents, tasks, workflows,\\n handoff_types, etc.) embedded in this CLI binary.\\n\\n Useful for debugging, external tooling integration, and DSL\\n inspection. Unlike `list`, which shows tabular summaries,\\n this command outputs the full DSL structure.\\n options:\\n - name: format\\n aliases: [F]\\n description: Output format.\\n schema:\\n type: string\\n enum: [yaml, json]\\n default: yaml\\n\\n exits:\\n \\\"0\\\":\\n description: DSL output successfully.\\n stdout:\\n format: text\\n\\n \\\"1\\\":\\n description: Failed to load embedded DSL.\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: []\\n\\n # -----------------------------------------------------------------------\\n # doctor\\n # -----------------------------------------------------------------------\\n doctor:\\n summary: Verify configuration, generated files, and SDK connectivity.\\n description: |\\n Runs a series of diagnostic checks to verify that the project\\n is correctly configured for agent-runtime execution.\\n\\n Checks: config existence, DSL existence, generated manifest freshness,\\n adapter configuration, API key environment variables, plugin entrypoint.\\n exits:\\n \\\"0\\\":\\n description: All checks passed.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/DoctorResult\\\"\\n\\n \\\"1\\\":\\n description: One or more checks failed.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/DoctorResult\\\"\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: []\\n\\n\\n# =============================================================================\\n# Components\\n# =============================================================================\\n\\ncomponents:\\n schemas:\\n # -------------------------------------------------------------------------\\n # init\\n # -------------------------------------------------------------------------\\n InitResult:\\n type: object\\n required: [files_created]\\n properties:\\n files_created:\\n type: array\\n items:\\n type: string\\n description: List of files created by init.\\n\\n # -------------------------------------------------------------------------\\n # generate\\n # -------------------------------------------------------------------------\\n GenerateResult:\\n type: object\\n required: [files_generated, dsl_hash, generation_input_hash]\\n properties:\\n files_generated:\\n type: array\\n items:\\n type: string\\n description: List of generated file paths.\\n dsl_hash:\\n type: string\\n description: SHA-256 hash of the resolved DSL (canonical stringify).\\n generation_input_hash:\\n type: string\\n description: SHA-256 hash of all generation inputs.\\n cleaned:\\n type: boolean\\n description: Whether --clean was used.\\n check_mode:\\n type: boolean\\n description: Whether --check was used.\\n has_differences:\\n type: boolean\\n description: In --check mode, whether differences were found.\\n\\n ValidationError:\\n type: object\\n required: [errors]\\n properties:\\n errors:\\n type: array\\n items:\\n type: object\\n required: [code, message]\\n properties:\\n code:\\n type: string\\n message:\\n type: string\\n path:\\n type: string\\n description: JSON path to the invalid element.\\n\\n # -------------------------------------------------------------------------\\n # run\\n # -------------------------------------------------------------------------\\n WorkflowResult:\\n type: object\\n required: [workflow_id, status, steps, total_elapsed_ms]\\n properties:\\n workflow_id:\\n type: string\\n status:\\n type: string\\n enum: [completed, escalated, gate_rejected, error]\\n steps:\\n type: array\\n items:\\n $ref: \\\"#/components/schemas/StepResult\\\"\\n total_elapsed_ms:\\n type: integer\\n minimum: 0\\n escalation_reason:\\n type: string\\n error_message:\\n type: string\\n\\n StepResult:\\n type: object\\n required: [step_index, retries_used, elapsed_ms, outcome]\\n properties:\\n step_index:\\n type: integer\\n minimum: 0\\n task_id:\\n type: string\\n gate_kind:\\n type: string\\n outcome:\\n type: object\\n required: [status]\\n properties:\\n status:\\n type: string\\n enum: [success, validation_error, escalation, error, gate_approved, gate_rejected, skipped]\\n retries_used:\\n type: integer\\n minimum: 0\\n elapsed_ms:\\n type: integer\\n minimum: 0\\n\\n # -------------------------------------------------------------------------\\n # list\\n # -------------------------------------------------------------------------\\n ListResult:\\n type: object\\n required: [resource, items]\\n properties:\\n resource:\\n type: string\\n enum: [workflows, tasks, agents]\\n items:\\n type: array\\n items:\\n type: object\\n required: [id, description]\\n properties:\\n id:\\n type: string\\n description:\\n type: string\\n\\n # -------------------------------------------------------------------------\\n # show-prompt\\n # -------------------------------------------------------------------------\\n ShowPromptResult:\\n type: object\\n required: [task_id, agent_id, prompt]\\n properties:\\n task_id:\\n type: string\\n description: The task ID used to build the prompt.\\n agent_id:\\n type: string\\n description: The target agent ID for this task.\\n prompt:\\n type: string\\n description: The full generated prompt text.\\n handoff_schema:\\n type: string\\n description: The handoff schema ID for the task result.\\n plugins_applied:\\n type: boolean\\n description: Whether plugin prompt enhancers were applied.\\n\\n # -------------------------------------------------------------------------\\n # doctor\\n # -------------------------------------------------------------------------\\n DoctorResult:\\n type: object\\n required: [checks, all_passed]\\n properties:\\n checks:\\n type: array\\n items:\\n $ref: \\\"#/components/schemas/DoctorCheck\\\"\\n all_passed:\\n type: boolean\\n\\n # -------------------------------------------------------------------------\\n # implement\\n # -------------------------------------------------------------------------\\n ImplementResult:\\n type: object\\n required: [files_created, files_modified, summary]\\n properties:\\n files_created:\\n type: array\\n items:\\n type: string\\n description: List of new files created.\\n files_modified:\\n type: array\\n items:\\n type: string\\n description: List of existing files modified.\\n summary:\\n type: string\\n description: Human-readable summary of what was implemented.\\n commands_added:\\n type: array\\n items:\\n type: object\\n required: [name, type]\\n properties:\\n name:\\n type: string\\n type:\\n type: string\\n enum: [audit, propose, explain]\\n description:\\n type: string\\n next_steps:\\n type: array\\n items:\\n type: string\\n description: Recommended next steps for the developer.\\n\\n # -------------------------------------------------------------------------\\n # audit-implementation\\n # -------------------------------------------------------------------------\\n AuditImplementationResult:\\n type: object\\n required: [summary, riskLevel, findings]\\n properties:\\n summary:\\n type: string\\n description: One-paragraph overall assessment.\\n riskLevel:\\n type: string\\n enum: [low, medium, high, critical]\\n description: Derived from worst finding severity.\\n findings:\\n type: array\\n items:\\n $ref: \\\"#/components/schemas/AgentFinding\\\"\\n recommendedActions:\\n type: array\\n items:\\n $ref: \\\"#/components/schemas/AgentRecommendedAction\\\"\\n metadata:\\n type: object\\n properties:\\n tool:\\n type: string\\n command:\\n type: string\\n version:\\n type: string\\n generatedAt:\\n type: string\\n adapter:\\n type: string\\n model:\\n type: string\\n\\n DoctorCheck:\\n type: object\\n required: [name, status]\\n properties:\\n name:\\n type: string\\n description: Check name (e.g. config_exists, dsl_exists, manifest_fresh).\\n status:\\n type: string\\n enum: [pass, fail, warn]\\n message:\\n type: string\\n description: Human-readable detail.\\n\\n # -------------------------------------------------------------------------\\n # Canonical agent result schemas (AgentAuditResult sub-types)\\n # -------------------------------------------------------------------------\\n AgentFinding:\\n type: object\\n required: [severity, category, message]\\n properties:\\n id:\\n type: string\\n description: Unique finding identifier (e.g. F-001).\\n severity:\\n type: string\\n enum: [info, warning, error, critical]\\n category:\\n type: string\\n description: Domain vocabulary category (e.g. cli-contract-options, runtime-adapter).\\n target:\\n type: string\\n description: File path or resource the finding applies to.\\n location:\\n type: string\\n description: Line range or specific location within the target.\\n message:\\n type: string\\n description: Human-readable description of the finding.\\n recommendation:\\n type: string\\n description: Concrete remediation step.\\n confidence:\\n type: number\\n minimum: 0\\n maximum: 1\\n description: Confidence score (0–1) for the finding.\\n evidence:\\n type: array\\n items:\\n $ref: \\\"#/components/schemas/AgentEvidence\\\"\\n details:\\n type: object\\n description: Additional structured details specific to the finding category.\\n\\n AgentRecommendedAction:\\n type: object\\n required: [kind, title]\\n properties:\\n kind:\\n type: string\\n enum: [run_command, edit_file, review, confirm, block, ignore]\\n title:\\n type: string\\n description: Short human-readable title for the action.\\n command:\\n type: string\\n description: Shell command to run (when kind is run_command).\\n target:\\n type: string\\n description: File path to edit (when kind is edit_file).\\n rationale:\\n type: string\\n description: Explanation of why this action is recommended.\\n\\n AgentEvidence:\\n type: object\\n required: [type, content]\\n properties:\\n type:\\n type: string\\n description: Evidence type (e.g. code_snippet, file_excerpt, lint_output).\\n content:\\n type: string\\n description: The evidence content.\\n source:\\n type: string\\n description: Source file path or URL for the evidence.\\n\";\n\nexport const CONTRACT_JSON_STR: string = \"{\\n \\\"cli_contracts\\\": \\\"0.1.0\\\",\\n \\\"info\\\": {\\n \\\"title\\\": \\\"agent-runtime CLI\\\",\\n \\\"version\\\": \\\"0.36.0\\\",\\n \\\"description\\\": \\\"Runtime bridge for executing agent-contracts workflows on Agent SDKs.\\\\nGenerates typed contracts, handoff validators, and guardrail hooks from DSL,\\\\nthen runs workflows through pluggable SDK adapters.\\\\n\\\",\\n \\\"license\\\": {\\n \\\"name\\\": \\\"MIT\\\"\\n }\\n },\\n \\\"command_sets\\\": {\\n \\\"agent-runtime\\\": {\\n \\\"summary\\\": \\\"CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\\\",\\n \\\"global_options\\\": [\\n {\\n \\\"name\\\": \\\"config\\\",\\n \\\"aliases\\\": [\\n \\\"c\\\"\\n ],\\n \\\"description\\\": \\\"Path to agents.conf.yaml (project runtime config).\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"default\\\": \\\"./agents.conf.yaml\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"read\\\",\\n \\\"exists\\\": true,\\n \\\"media_type\\\": \\\"application/yaml\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"verbose\\\",\\n \\\"aliases\\\": [\\n \\\"v\\\"\\n ],\\n \\\"description\\\": \\\"Enable verbose output.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"quiet\\\",\\n \\\"aliases\\\": [\\n \\\"q\\\"\\n ],\\n \\\"description\\\": \\\"Suppress non-error output.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n }\\n ],\\n \\\"commands\\\": {\\n \\\"init\\\": {\\n \\\"summary\\\": \\\"Initialize runtime scaffolding for a project.\\\",\\n \\\"description\\\": \\\"Generates the initial directory structure and configuration files\\\\nfor using agent-contracts-runtime in a project.\\\\nCreates agents.conf.yaml and agent/src/ user code templates.\\\\n\\\",\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"adapter\\\",\\n \\\"aliases\\\": [\\n \\\"a\\\"\\n ],\\n \\\"description\\\": \\\"Default SDK adapter to configure.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"claude\\\",\\n \\\"gemini\\\",\\n \\\"openai\\\",\\n \\\"mock\\\"\\n ],\\n \\\"default\\\": \\\"mock\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"output\\\",\\n \\\"aliases\\\": [\\n \\\"o\\\"\\n ],\\n \\\"description\\\": \\\"Output directory for generated scaffolding.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"default\\\": \\\".\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"force\\\",\\n \\\"aliases\\\": [\\n \\\"f\\\"\\n ],\\n \\\"description\\\": \\\"Overwrite existing files without prompting.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Scaffolding generated successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/InitResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Initialization failed (existing files, permission error, etc.).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": false,\\n \\\"sideEffects\\\": [\\n \\\"filesystem_write\\\"\\n ],\\n \\\"safeDryRunOption\\\": \\\"\\\"\\n }\\n },\\n \\\"generate\\\": {\\n \\\"summary\\\": \\\"Generate runtime contracts and hooks from DSL.\\\",\\n \\\"description\\\": \\\"Reads agent-contracts.yaml, resolves the DSL, validates it,\\\\nand generates typed contracts, handoff schemas, guardrail hooks,\\\\nand a runtime manifest into the configured generated_dir.\\\\n\\\\nEach generated file includes a DO NOT EDIT header.\\\\n\\\",\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"clean\\\",\\n \\\"description\\\": \\\"Delete generated_dir before regenerating.\\\\nRemoves stale files that may remain from previous generations.\\\\n\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"check\\\",\\n \\\"description\\\": \\\"Dry-run mode for CI. Does not write files.\\\\nCompares current generated output with what would be regenerated.\\\\nExits with code 1 if any differences are found.\\\\n\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"templates\\\",\\n \\\"aliases\\\": [\\n \\\"t\\\"\\n ],\\n \\\"description\\\": \\\"Custom templates directory. Overrides built-in templates.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Generation completed successfully (or --check found no differences).\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/GenerateResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Generation failed, or --check detected differences between\\\\ncurrent generated files and expected output.\\\\n\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"2\\\": {\\n \\\"description\\\": \\\"DSL validation error. The input DSL has structural or semantic issues.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/ValidationError\\\"\\n }\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": [\\n \\\"filesystem_write\\\"\\n ],\\n \\\"safeDryRunOption\\\": \\\"check\\\"\\n }\\n },\\n \\\"run\\\": {\\n \\\"summary\\\": \\\"Execute a workflow.\\\",\\n \\\"description\\\": \\\"Loads generated contracts, creates an SDK adapter, registers user plugins,\\\\nand executes the specified workflow with the given user request.\\\\n\\\\nThe workflow runner orchestrates task delegation, retry, gate handling,\\\\nand handoff validation mechanically.\\\\n\\\",\\n \\\"arguments\\\": [\\n {\\n \\\"name\\\": \\\"workflow-id\\\",\\n \\\"required\\\": false,\\n \\\"description\\\": \\\"ID of the workflow to execute. Required unless --file is used.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"user-request\\\",\\n \\\"required\\\": false,\\n \\\"description\\\": \\\"Natural language description of what to do. Required unless --file is used.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n ],\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"adapter\\\",\\n \\\"aliases\\\": [\\n \\\"a\\\"\\n ],\\n \\\"description\\\": \\\"SDK adapter to use. Overrides config.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"claude\\\",\\n \\\"gemini\\\",\\n \\\"openai\\\",\\n \\\"mock\\\"\\n ]\\n }\\n },\\n {\\n \\\"name\\\": \\\"max-retries\\\",\\n \\\"aliases\\\": [\\n \\\"r\\\"\\n ],\\n \\\"description\\\": \\\"Override default max retries per step.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0,\\n \\\"maximum\\\": 10\\n }\\n },\\n {\\n \\\"name\\\": \\\"max-follow-ups\\\",\\n \\\"aliases\\\": [\\n \\\"f\\\"\\n ],\\n \\\"description\\\": \\\"Override default max follow-ups per step.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0,\\n \\\"maximum\\\": 10\\n }\\n },\\n {\\n \\\"name\\\": \\\"dry-run\\\",\\n \\\"aliases\\\": [\\n \\\"n\\\"\\n ],\\n \\\"description\\\": \\\"Simulate execution without calling the SDK adapter.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"auto-approve-gates\\\",\\n \\\"description\\\": \\\"Automatically approve all gate steps.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"file\\\",\\n \\\"description\\\": \\\"Path to a YAML invocation file. When provided, workflow-id and\\\\nuser-request arguments are read from the file instead of CLI args.\\\\n\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"read\\\",\\n \\\"exists\\\": true,\\n \\\"media_type\\\": \\\"application/yaml\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"log-file\\\",\\n \\\"aliases\\\": [\\n \\\"l\\\"\\n ],\\n \\\"description\\\": \\\"Write agent progress log to this file. Overrides config logging.progress_log.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Workflow completed successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/WorkflowResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Workflow failed (escalation, error, or gate rejection).\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/WorkflowResult\\\"\\n }\\n },\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"3\\\": {\\n \\\"description\\\": \\\"Input validation failed (invalid arguments, unknown workflow/adapter, or generated files outdated).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"12\\\": {\\n \\\"description\\\": \\\"Adapter initialization error (missing API key, etc.).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"high\\\",\\n \\\"requiresConfirmation\\\": true,\\n \\\"idempotent\\\": false,\\n \\\"sideEffects\\\": [\\n \\\"sdk_call\\\",\\n \\\"filesystem_write\\\"\\n ],\\n \\\"safeDryRunOption\\\": \\\"dry-run\\\",\\n \\\"expectedDurationMs\\\": 300000,\\n \\\"recommendedBeforeUse\\\": [\\n \\\"Run `agent-runtime generate --check` to ensure contracts are up to date.\\\",\\n \\\"Run `agent-runtime doctor` to verify SDK configuration.\\\"\\n ]\\n }\\n },\\n \\\"list\\\": {\\n \\\"summary\\\": \\\"List available workflows, tasks, or agents.\\\",\\n \\\"description\\\": \\\"Reads generated contracts and displays available resources.\\\\nUseful for discovering what workflows, tasks, and agents\\\\nare defined in the current project.\\\\n\\\",\\n \\\"arguments\\\": [\\n {\\n \\\"name\\\": \\\"resource\\\",\\n \\\"required\\\": true,\\n \\\"description\\\": \\\"Type of resource to list.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"workflows\\\",\\n \\\"tasks\\\",\\n \\\"agents\\\"\\n ]\\n }\\n }\\n ],\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"format\\\",\\n \\\"description\\\": \\\"Output format.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"table\\\",\\n \\\"json\\\"\\n ],\\n \\\"default\\\": \\\"table\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Resources listed successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/ListResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Failed to load contracts.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": []\\n }\\n },\\n \\\"show-prompt\\\": {\\n \\\"summary\\\": \\\"Display the generated prompt for a task.\\\",\\n \\\"description\\\": \\\"Builds and displays the full prompt that would be sent to an SDK agent\\\\nfor a given task. Useful for inspecting, debugging, and validating\\\\nprompt content before execution.\\\\n\\\\nShows the agent role, responsibilities, constraints, task details,\\\\ncompletion criteria, handoff schema fields, and output format example.\\\\n\\\",\\n \\\"arguments\\\": [\\n {\\n \\\"name\\\": \\\"task-id\\\",\\n \\\"required\\\": true,\\n \\\"description\\\": \\\"ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n ],\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"user-request\\\",\\n \\\"aliases\\\": [\\n \\\"u\\\"\\n ],\\n \\\"description\\\": \\\"User request text to include in the prompt preview.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"default\\\": \\\"(preview)\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"format\\\",\\n \\\"description\\\": \\\"Output format.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"markdown\\\",\\n \\\"raw\\\",\\n \\\"json\\\"\\n ],\\n \\\"default\\\": \\\"markdown\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"with-plugins\\\",\\n \\\"description\\\": \\\"Apply registered plugin prompt enhancers to the output.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Prompt displayed successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/ShowPromptResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Failed to build prompt (unknown task, missing contracts, etc.).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": []\\n }\\n },\\n \\\"implement\\\": {\\n \\\"summary\\\": \\\"Implement LLM-powered commands in a CLI tool.\\\",\\n \\\"description\\\": \\\"Uses an agentic LLM adapter (Claude, etc.) to analyze the\\\\ntarget project and implement LLM-powered commands following the\\\\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\\\\n\\\\nThe agent reads the project structure, cli-contract.yaml, and existing\\\\ncode, then generates DSL definitions, TypeScript modules (orchestrator,\\\\ncontext-builder, formatter), CLI command handlers, and updates the\\\\nCLI contract with x-agent metadata.\\\\n\\\\nRequires an agentic adapter that supports tool use (file read/write).\\\\n\\\",\\n \\\"arguments\\\": [\\n {\\n \\\"name\\\": \\\"description\\\",\\n \\\"required\\\": true,\\n \\\"description\\\": \\\"Natural language description of the LLM feature(s) to implement. Examples: \\\\\\\"Add an audit command for migration safety\\\\\\\", \\\\\\\"Add propose and explain commands for SQL optimization\\\\\\\".\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n ],\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"adapter\\\",\\n \\\"aliases\\\": [\\n \\\"a\\\"\\n ],\\n \\\"description\\\": \\\"SDK adapter to use. Must be an agentic adapter (claude).\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"claude\\\",\\n \\\"mock\\\"\\n ],\\n \\\"default\\\": \\\"claude\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"project-dir\\\",\\n \\\"aliases\\\": [\\n \\\"p\\\"\\n ],\\n \\\"description\\\": \\\"Path to the target project directory.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"default\\\": \\\".\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"dry-run\\\",\\n \\\"aliases\\\": [\\n \\\"n\\\"\\n ],\\n \\\"description\\\": \\\"Output the prompt context without calling the LLM.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"model\\\",\\n \\\"description\\\": \\\"Model name override for the selected adapter.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"output\\\",\\n \\\"aliases\\\": [\\n \\\"o\\\"\\n ],\\n \\\"description\\\": \\\"Write the result to a file instead of stdout.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"report-format\\\",\\n \\\"description\\\": \\\"Output format for the result.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"json\\\",\\n \\\"text\\\",\\n \\\"yaml\\\"\\n ],\\n \\\"default\\\": \\\"text\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"log-file\\\",\\n \\\"aliases\\\": [\\n \\\"l\\\"\\n ],\\n \\\"description\\\": \\\"Write agent progress log to this file.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Implementation completed successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/ImplementResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Implementation failed.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"3\\\": {\\n \\\"description\\\": \\\"Input validation failed (e.g. project directory not found).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"12\\\": {\\n \\\"description\\\": \\\"Adapter initialization error.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"high\\\",\\n \\\"requiresConfirmation\\\": true,\\n \\\"idempotent\\\": false,\\n \\\"sideEffects\\\": [\\n \\\"sdk_call\\\",\\n \\\"filesystem_write\\\"\\n ],\\n \\\"safeDryRunOption\\\": \\\"dry-run\\\",\\n \\\"expectedDurationMs\\\": 300000,\\n \\\"retryableExitCodes\\\": [\\n 1,\\n 12\\n ],\\n \\\"recommendedBeforeUse\\\": [\\n \\\"Ensure the target project has a cli-contract.yaml or plan to create one.\\\",\\n \\\"Run in a clean git working tree so changes can be reviewed.\\\"\\n ]\\n }\\n },\\n \\\"audit-implementation\\\": {\\n \\\"summary\\\": \\\"Audit an LLM command integration for pattern conformance.\\\",\\n \\\"description\\\": \\\"Analyzes a target project's LLM command integration to verify it\\\\ncorrectly follows the agent-contracts + agent-contracts-runtime +\\\\ncli-contracts stack conventions.\\\\n\\\\nChecks all three layers:\\\\n1. DSL definitions (agents, tasks, workflows, handoff schemas)\\\\n2. Runtime integration (adapter usage, runTask/runWorkflow, registries)\\\\n3. CLI contract (standard options, x-agent metadata, exit codes)\\\\n\\\\nProduces structured findings with severity, category, and\\\\nconcrete remediation steps. Read-only — does not modify files.\\\\n\\\",\\n \\\"arguments\\\": [\\n {\\n \\\"name\\\": \\\"project-dir\\\",\\n \\\"required\\\": false,\\n \\\"description\\\": \\\"Path to the project directory to audit. Defaults to current directory.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n ],\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"adapter\\\",\\n \\\"aliases\\\": [\\n \\\"a\\\"\\n ],\\n \\\"description\\\": \\\"SDK adapter to use for the audit agent.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"claude\\\",\\n \\\"mock\\\"\\n ],\\n \\\"default\\\": \\\"claude\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"focus\\\",\\n \\\"description\\\": \\\"Limit audit to a specific layer. Defaults to all layers.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"all\\\",\\n \\\"dsl\\\",\\n \\\"runtime\\\",\\n \\\"cli-contract\\\",\\n \\\"architecture\\\"\\n ],\\n \\\"default\\\": \\\"all\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"dry-run\\\",\\n \\\"aliases\\\": [\\n \\\"n\\\"\\n ],\\n \\\"description\\\": \\\"Output the prompt context without calling the LLM.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"fail-on\\\",\\n \\\"description\\\": \\\"Minimum finding severity that causes a non-zero exit.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"warning\\\",\\n \\\"error\\\",\\n \\\"critical\\\"\\n ],\\n \\\"default\\\": \\\"error\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"model\\\",\\n \\\"description\\\": \\\"Model name override for the selected adapter.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"output\\\",\\n \\\"aliases\\\": [\\n \\\"o\\\"\\n ],\\n \\\"description\\\": \\\"Write the result to a file instead of stdout.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"report-format\\\",\\n \\\"description\\\": \\\"Output format for the audit report.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"json\\\",\\n \\\"text\\\",\\n \\\"yaml\\\"\\n ],\\n \\\"default\\\": \\\"text\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"log-file\\\",\\n \\\"aliases\\\": [\\n \\\"l\\\"\\n ],\\n \\\"description\\\": \\\"Write agent progress log to this file.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Audit completed with no findings above threshold.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/AuditImplementationResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Audit failed (agent error, unexpected failure).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"3\\\": {\\n \\\"description\\\": \\\"Input validation failed (e.g. project directory not found).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"10\\\": {\\n \\\"description\\\": \\\"Audit completed with findings above --fail-on threshold.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/AuditImplementationResult\\\"\\n }\\n }\\n },\\n \\\"12\\\": {\\n \\\"description\\\": \\\"Adapter initialization error.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": [\\n \\\"network\\\"\\n ],\\n \\\"sideEffectNote\\\": \\\"Network calls to LLM provider when adapter is not mock. Filesystem write only when --output is specified.\\\",\\n \\\"safeDryRunOption\\\": \\\"dry-run\\\",\\n \\\"expectedDurationMs\\\": 180000,\\n \\\"retryableExitCodes\\\": [\\n 1,\\n 12\\n ]\\n }\\n },\\n \\\"agents\\\": {\\n \\\"summary\\\": \\\"Output the full resolved DSL as structured data.\\\",\\n \\\"description\\\": \\\"Outputs the complete resolved DSL (agents, tasks, workflows,\\\\nhandoff_types, etc.) embedded in this CLI binary.\\\\n\\\\nUseful for debugging, external tooling integration, and DSL\\\\ninspection. Unlike `list`, which shows tabular summaries,\\\\nthis command outputs the full DSL structure.\\\\n\\\",\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"format\\\",\\n \\\"aliases\\\": [\\n \\\"F\\\"\\n ],\\n \\\"description\\\": \\\"Output format.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"yaml\\\",\\n \\\"json\\\"\\n ],\\n \\\"default\\\": \\\"yaml\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"DSL output successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Failed to load embedded DSL.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": []\\n }\\n },\\n \\\"doctor\\\": {\\n \\\"summary\\\": \\\"Verify configuration, generated files, and SDK connectivity.\\\",\\n \\\"description\\\": \\\"Runs a series of diagnostic checks to verify that the project\\\\nis correctly configured for agent-runtime execution.\\\\n\\\\nChecks: config existence, DSL existence, generated manifest freshness,\\\\nadapter configuration, API key environment variables, plugin entrypoint.\\\\n\\\",\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"All checks passed.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/DoctorResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"One or more checks failed.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/DoctorResult\\\"\\n }\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": []\\n }\\n }\\n }\\n }\\n },\\n \\\"components\\\": {\\n \\\"schemas\\\": {\\n \\\"InitResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"files_created\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"files_created\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": \\\"List of files created by init.\\\"\\n }\\n }\\n },\\n \\\"GenerateResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"files_generated\\\",\\n \\\"dsl_hash\\\",\\n \\\"generation_input_hash\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"files_generated\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": \\\"List of generated file paths.\\\"\\n },\\n \\\"dsl_hash\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"SHA-256 hash of the resolved DSL (canonical stringify).\\\"\\n },\\n \\\"generation_input_hash\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"SHA-256 hash of all generation inputs.\\\"\\n },\\n \\\"cleaned\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"description\\\": \\\"Whether --clean was used.\\\"\\n },\\n \\\"check_mode\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"description\\\": \\\"Whether --check was used.\\\"\\n },\\n \\\"has_differences\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"description\\\": \\\"In --check mode, whether differences were found.\\\"\\n }\\n }\\n },\\n \\\"ValidationError\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"errors\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"errors\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"code\\\",\\n \\\"message\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"code\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"message\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"path\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"JSON path to the invalid element.\\\"\\n }\\n }\\n }\\n }\\n }\\n },\\n \\\"WorkflowResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"workflow_id\\\",\\n \\\"status\\\",\\n \\\"steps\\\",\\n \\\"total_elapsed_ms\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"workflow_id\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"status\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"completed\\\",\\n \\\"escalated\\\",\\n \\\"gate_rejected\\\",\\n \\\"error\\\"\\n ]\\n },\\n \\\"steps\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/StepResult\\\"\\n }\\n },\\n \\\"total_elapsed_ms\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0\\n },\\n \\\"escalation_reason\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"error_message\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n },\\n \\\"StepResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"step_index\\\",\\n \\\"retries_used\\\",\\n \\\"elapsed_ms\\\",\\n \\\"outcome\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"step_index\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0\\n },\\n \\\"task_id\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"gate_kind\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"outcome\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"status\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"status\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"success\\\",\\n \\\"validation_error\\\",\\n \\\"escalation\\\",\\n \\\"error\\\",\\n \\\"gate_approved\\\",\\n \\\"gate_rejected\\\",\\n \\\"skipped\\\"\\n ]\\n }\\n }\\n },\\n \\\"retries_used\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0\\n },\\n \\\"elapsed_ms\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0\\n }\\n }\\n },\\n \\\"ListResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"resource\\\",\\n \\\"items\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"resource\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"workflows\\\",\\n \\\"tasks\\\",\\n \\\"agents\\\"\\n ]\\n },\\n \\\"items\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"id\\\",\\n \\\"description\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"id\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n }\\n }\\n }\\n },\\n \\\"ShowPromptResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"task_id\\\",\\n \\\"agent_id\\\",\\n \\\"prompt\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"task_id\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The task ID used to build the prompt.\\\"\\n },\\n \\\"agent_id\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The target agent ID for this task.\\\"\\n },\\n \\\"prompt\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The full generated prompt text.\\\"\\n },\\n \\\"handoff_schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The handoff schema ID for the task result.\\\"\\n },\\n \\\"plugins_applied\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"description\\\": \\\"Whether plugin prompt enhancers were applied.\\\"\\n }\\n }\\n },\\n \\\"DoctorResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"checks\\\",\\n \\\"all_passed\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"checks\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/DoctorCheck\\\"\\n }\\n },\\n \\\"all_passed\\\": {\\n \\\"type\\\": \\\"boolean\\\"\\n }\\n }\\n },\\n \\\"ImplementResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"files_created\\\",\\n \\\"files_modified\\\",\\n \\\"summary\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"files_created\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": \\\"List of new files created.\\\"\\n },\\n \\\"files_modified\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": \\\"List of existing files modified.\\\"\\n },\\n \\\"summary\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Human-readable summary of what was implemented.\\\"\\n },\\n \\\"commands_added\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"name\\\",\\n \\\"type\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"name\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"type\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"audit\\\",\\n \\\"propose\\\",\\n \\\"explain\\\"\\n ]\\n },\\n \\\"description\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n }\\n },\\n \\\"next_steps\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": \\\"Recommended next steps for the developer.\\\"\\n }\\n }\\n },\\n \\\"AuditImplementationResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"summary\\\",\\n \\\"riskLevel\\\",\\n \\\"findings\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"summary\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"One-paragraph overall assessment.\\\"\\n },\\n \\\"riskLevel\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"low\\\",\\n \\\"medium\\\",\\n \\\"high\\\",\\n \\\"critical\\\"\\n ],\\n \\\"description\\\": \\\"Derived from worst finding severity.\\\"\\n },\\n \\\"findings\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/AgentFinding\\\"\\n }\\n },\\n \\\"recommendedActions\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/AgentRecommendedAction\\\"\\n }\\n },\\n \\\"metadata\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"tool\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"command\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"version\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"generatedAt\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"adapter\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"model\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n }\\n }\\n },\\n \\\"DoctorCheck\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"name\\\",\\n \\\"status\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"name\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Check name (e.g. config_exists, dsl_exists, manifest_fresh).\\\"\\n },\\n \\\"status\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"pass\\\",\\n \\\"fail\\\",\\n \\\"warn\\\"\\n ]\\n },\\n \\\"message\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Human-readable detail.\\\"\\n }\\n }\\n },\\n \\\"AgentFinding\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"severity\\\",\\n \\\"category\\\",\\n \\\"message\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"id\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Unique finding identifier (e.g. F-001).\\\"\\n },\\n \\\"severity\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"info\\\",\\n \\\"warning\\\",\\n \\\"error\\\",\\n \\\"critical\\\"\\n ]\\n },\\n \\\"category\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Domain vocabulary category (e.g. cli-contract-options, runtime-adapter).\\\"\\n },\\n \\\"target\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"File path or resource the finding applies to.\\\"\\n },\\n \\\"location\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Line range or specific location within the target.\\\"\\n },\\n \\\"message\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Human-readable description of the finding.\\\"\\n },\\n \\\"recommendation\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Concrete remediation step.\\\"\\n },\\n \\\"confidence\\\": {\\n \\\"type\\\": \\\"number\\\",\\n \\\"minimum\\\": 0,\\n \\\"maximum\\\": 1,\\n \\\"description\\\": \\\"Confidence score (0–1) for the finding.\\\"\\n },\\n \\\"evidence\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/AgentEvidence\\\"\\n }\\n },\\n \\\"details\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"description\\\": \\\"Additional structured details specific to the finding category.\\\"\\n }\\n }\\n },\\n \\\"AgentRecommendedAction\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"kind\\\",\\n \\\"title\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"kind\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"run_command\\\",\\n \\\"edit_file\\\",\\n \\\"review\\\",\\n \\\"confirm\\\",\\n \\\"block\\\",\\n \\\"ignore\\\"\\n ]\\n },\\n \\\"title\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Short human-readable title for the action.\\\"\\n },\\n \\\"command\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Shell command to run (when kind is run_command).\\\"\\n },\\n \\\"target\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"File path to edit (when kind is edit_file).\\\"\\n },\\n \\\"rationale\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Explanation of why this action is recommended.\\\"\\n }\\n }\\n },\\n \\\"AgentEvidence\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"type\\\",\\n \\\"content\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"type\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Evidence type (e.g. code_snippet, file_excerpt, lint_output).\\\"\\n },\\n \\\"content\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The evidence content.\\\"\\n },\\n \\\"source\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Source file path or URL for the evidence.\\\"\\n }\\n }\\n }\\n }\\n }\\n}\";\n","/**\n * Doctor — diagnostic checks for agent-contracts-runtime configuration health\n *\n * Each check returns a DoctorCheck with pass/fail/warn status.\n * The runner collects all checks and determines overall health.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport YAML from \"yaml\";\nimport { loadConfig, RuntimeConfigSchema, type ResolvedConfig } from \"../generator/config.js\";\nimport { checkFreshness } from \"../generator/index.js\";\n\nexport interface DoctorCheck {\n name: string;\n status: \"pass\" | \"fail\" | \"warn\";\n message?: string;\n}\n\nexport interface DoctorResult {\n checks: DoctorCheck[];\n all_passed: boolean;\n}\n\nconst ADAPTER_ENV_VARS: Record<string, string> = {\n claude: \"ANTHROPIC_API_KEY\",\n openai: \"OPENAI_API_KEY\",\n};\n\nasync function checkConfigExists(configPath: string): Promise<{ check: DoctorCheck; config?: ResolvedConfig }> {\n try {\n const config = await loadConfig(configPath);\n return {\n check: { name: \"config_exists\", status: \"pass\", message: `Loaded ${configPath}` },\n config,\n };\n } catch (err) {\n const absPath = resolve(configPath);\n if (!existsSync(absPath)) {\n return {\n check: { name: \"config_exists\", status: \"fail\", message: `Config file not found: ${absPath}` },\n };\n }\n return {\n check: { name: \"config_exists\", status: \"fail\", message: `Config parse error: ${(err as Error).message}` },\n };\n }\n}\n\nasync function checkDslExists(config: ResolvedConfig): Promise<DoctorCheck> {\n if (!existsSync(config.dslPath)) {\n return { name: \"dsl_exists\", status: \"fail\", message: `DSL file not found: ${config.dslPath}` };\n }\n\n try {\n const raw = await readFile(config.dslPath, \"utf8\");\n const parsed = YAML.parse(raw);\n if (!parsed || typeof parsed !== \"object\") {\n return { name: \"dsl_exists\", status: \"fail\", message: \"DSL file is empty or not a valid YAML object\" };\n }\n const agentCount = Object.keys(parsed.agents ?? {}).length;\n const taskCount = Object.keys(parsed.tasks ?? {}).length;\n const workflowCount = Object.keys(parsed.workflow ?? {}).length;\n return {\n name: \"dsl_exists\",\n status: \"pass\",\n message: `Parsed OK — ${agentCount} agent(s), ${taskCount} task(s), ${workflowCount} workflow(s)`,\n };\n } catch (err) {\n return { name: \"dsl_exists\", status: \"fail\", message: `DSL parse error: ${(err as Error).message}` };\n }\n}\n\nasync function checkManifestFresh(configPath: string, config: ResolvedConfig): Promise<DoctorCheck> {\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n\n if (!existsSync(manifestPath)) {\n return {\n name: \"manifest_fresh\",\n status: \"fail\",\n message: \"Generated manifest not found. Run `agent-runtime generate` first.\",\n };\n }\n\n try {\n const fresh = await checkFreshness(configPath);\n if (fresh) {\n return { name: \"manifest_fresh\", status: \"pass\", message: \"Generated files are up to date\" };\n }\n return {\n name: \"manifest_fresh\",\n status: \"fail\",\n message: \"Generated files are stale. Run `agent-runtime generate` to update.\",\n };\n } catch (err) {\n return { name: \"manifest_fresh\", status: \"fail\", message: `Freshness check error: ${(err as Error).message}` };\n }\n}\n\nfunction checkAdapterConfigured(): DoctorCheck {\n const configured: string[] = [];\n const missing: string[] = [];\n\n for (const [adapter, envVar] of Object.entries(ADAPTER_ENV_VARS)) {\n if (process.env[envVar]) {\n configured.push(adapter);\n } else {\n missing.push(`${adapter} (${envVar})`);\n }\n }\n\n if (configured.length > 0) {\n return {\n name: \"adapter_configured\",\n status: \"pass\",\n message: `Configured: ${configured.join(\", \")}${missing.length > 0 ? ` | Not set: ${missing.join(\", \")}` : \"\"}`,\n };\n }\n\n return {\n name: \"adapter_configured\",\n status: \"warn\",\n message: `No SDK adapter API keys found. Set one of: ${Object.entries(ADAPTER_ENV_VARS).map(([a, e]) => `${e} (${a})`).join(\", \")}`,\n };\n}\n\nasync function checkTsxAvailable(): Promise<DoctorCheck> {\n try {\n await import(\"tsx/esm\");\n return { name: \"tsx_available\", status: \"pass\", message: \"tsx is installed\" };\n } catch {\n return {\n name: \"tsx_available\",\n status: \"fail\",\n message: \"tsx is not installed. Required for loading generated .ts files. Run: npm install tsx\",\n };\n }\n}\n\nfunction checkPluginEntrypoints(config: ResolvedConfig): DoctorCheck {\n if (config.pluginPaths.length === 0) {\n return { name: \"plugin_entrypoint\", status: \"pass\", message: \"No plugins configured\" };\n }\n\n const missing: string[] = [];\n for (const p of config.pluginPaths) {\n const absPath = resolve(config.configDir, p);\n if (!existsSync(absPath)) {\n missing.push(p);\n }\n }\n\n if (missing.length === 0) {\n return {\n name: \"plugin_entrypoint\",\n status: \"pass\",\n message: `All ${config.pluginPaths.length} plugin file(s) found`,\n };\n }\n\n return {\n name: \"plugin_entrypoint\",\n status: \"fail\",\n message: `Missing plugin file(s): ${missing.join(\", \")}`,\n };\n}\n\nasync function checkBindingsValid(config: ResolvedConfig): Promise<DoctorCheck> {\n if (config.bindingPaths.length === 0) {\n return { name: \"bindings_valid\", status: \"pass\", message: \"No bindings configured\" };\n }\n\n const errors: string[] = [];\n for (const bp of config.bindingPaths) {\n if (!existsSync(bp)) {\n errors.push(`Not found: ${bp}`);\n continue;\n }\n try {\n const raw = await readFile(bp, \"utf8\");\n const parsed = YAML.parse(raw);\n if (!parsed || typeof parsed !== \"object\") {\n errors.push(`Invalid YAML object: ${bp}`);\n }\n } catch (err) {\n errors.push(`Parse error in ${bp}: ${(err as Error).message}`);\n }\n }\n\n if (errors.length === 0) {\n return {\n name: \"bindings_valid\",\n status: \"pass\",\n message: `All ${config.bindingPaths.length} binding file(s) valid`,\n };\n }\n\n return {\n name: \"bindings_valid\",\n status: \"fail\",\n message: errors.join(\"; \"),\n };\n}\n\nfunction checkLogDirectory(config: ResolvedConfig): DoctorCheck {\n const pl = config.resolvedLogging.progressLog;\n\n if (pl.destination === \"none\" || pl.destination === \"stderr\") {\n return { name: \"log_directory\", status: \"pass\", message: `Progress log destination: ${pl.destination}` };\n }\n\n if (!pl.file) {\n return {\n name: \"log_directory\",\n status: \"fail\",\n message: \"logging.progress_log.file is required when destination is 'file' or 'both'\",\n };\n }\n\n const dir = join(pl.file, \"..\");\n if (!existsSync(dir)) {\n return {\n name: \"log_directory\",\n status: \"warn\",\n message: `Log directory does not exist: ${dir} (will be created on first run)`,\n };\n }\n\n return { name: \"log_directory\", status: \"pass\", message: `Log file: ${pl.file} (naming: ${pl.naming})` };\n}\n\nexport async function runDoctor(configPath: string): Promise<DoctorResult> {\n const checks: DoctorCheck[] = [];\n\n // 1. Config exists and parses\n const configResult = await checkConfigExists(configPath);\n checks.push(configResult.check);\n\n if (!configResult.config) {\n return { checks, all_passed: false };\n }\n\n const config = configResult.config;\n\n // 2–7 can run concurrently since they only read state\n const [dslCheck, manifestCheck, pluginCheck, bindingsCheck, tsxCheck] = await Promise.all([\n checkDslExists(config),\n checkManifestFresh(configPath, config),\n Promise.resolve(checkPluginEntrypoints(config)),\n checkBindingsValid(config),\n checkTsxAvailable(),\n ]);\n\n checks.push(dslCheck);\n checks.push(manifestCheck);\n checks.push(checkAdapterConfigured());\n checks.push(pluginCheck);\n checks.push(bindingsCheck);\n checks.push(tsxCheck);\n checks.push(checkLogDirectory(config));\n\n const all_passed = checks.every((c) => c.status !== \"fail\");\n\n return { checks, all_passed };\n}\n","/**\n * init — scaffold a new agent-contracts-runtime project\n */\n\nimport { existsSync } from \"node:fs\";\nimport { mkdir, writeFile, readFile, appendFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nexport interface InitOptions {\n adapter: string;\n outputDir: string;\n force: boolean;\n}\n\nexport interface InitResult {\n files_created: string[];\n}\n\ninterface FileEntry {\n relativePath: string;\n content: string;\n}\n\nfunction buildConfigYaml(_adapter: string): string {\n return `plugins:\n - ./agent/src/plugins/example-plugin.ts\nrecovery:\n max_follow_ups: 2\n max_retries: 0\n# model_mapping:\n# standard:\n# adapter: claude\n# model: claude-opus-4-6\nmodel_mapping: {}\n`;\n}\n\nconst EXAMPLE_PLUGIN_TS = `\\\nimport type { AgentPlugin } from \"agent-contracts-runtime\";\n\n/**\n * Example plugin — extend agent-contracts-runtime with custom hooks.\n *\n * Register lifecycle hooks for tasks and workflows:\n * beforeTask / afterTask — pre/post-process task execution\n * contextEnhancer — augment task context before prompt generation\n * promptEnhancer — post-process generated prompts\n * customGuardrails — add project-specific guardrail checks\n * beforeWorkflow / afterWorkflow — workflow lifecycle hooks\n *\n * See https://github.com/foo-log-inc/agent-contracts-runtime#plugins\n */\nexport const examplePlugin: AgentPlugin = {\n id: \"example-plugin\",\n\n // Uncomment hooks as needed:\n\n // async beforeTask(taskId, context) {\n // console.log(\\`[example-plugin] beforeTask: \\${taskId}\\`);\n // return context;\n // },\n\n // async afterTask(taskId, outcome) {\n // console.log(\\`[example-plugin] afterTask: \\${taskId} — \\${outcome.status}\\`);\n // return outcome;\n // },\n\n // promptEnhancer(taskId, prompt, _context) {\n // return prompt + \"\\\\n\\\\n<!-- enhanced by example-plugin -->\";\n // },\n};\n\nexport default examplePlugin;\n`;\n\nconst CUSTOM_GUARDRAILS_TS = `\\\nimport type { AgentPlugin, GuardrailResult } from \"agent-contracts-runtime\";\n\n/**\n * Custom guardrails — project-specific safety checks.\n *\n * Implement evaluateCommand, evaluateFilePath, or evaluateFileContent\n * to enforce project rules beyond the built-in guardrails.\n *\n * See https://github.com/foo-log-inc/agent-contracts-runtime#guardrails\n */\nexport const customGuardrailsPlugin: AgentPlugin = {\n id: \"custom-guardrails\",\n\n customGuardrails: {\n // evaluateCommand(command: string): GuardrailResult[] {\n // const results: GuardrailResult[] = [];\n // // Example: block dangerous patterns\n // if (command.includes(\"DROP TABLE\")) {\n // results.push({\n // matched: true,\n // guardrail_id: \"no-drop-table\",\n // severity: \"critical\",\n // action: \"block\",\n // message: \"DROP TABLE is forbidden\",\n // });\n // }\n // return results;\n // },\n },\n};\n\nexport default customGuardrailsPlugin;\n`;\n\nconst GITIGNORE_ENTRIES = [\n \"\",\n \"# agent-contracts-runtime generated files\",\n \"agent/generated/\",\n];\n\nfunction buildScaffoldFiles(adapter: string): FileEntry[] {\n return [\n {\n relativePath: \"agents.conf.yaml\",\n content: buildConfigYaml(adapter),\n },\n {\n relativePath: \"agent/src/plugins/example-plugin.ts\",\n content: EXAMPLE_PLUGIN_TS,\n },\n {\n relativePath: \"agent/src/guardrails/custom-guardrails.ts\",\n content: CUSTOM_GUARDRAILS_TS,\n },\n ];\n}\n\nexport async function runInit(options: InitOptions): Promise<InitResult> {\n const { adapter, outputDir, force } = options;\n const files_created: string[] = [];\n\n const entries = buildScaffoldFiles(adapter);\n\n for (const entry of entries) {\n const absPath = join(outputDir, entry.relativePath);\n if (!force && existsSync(absPath)) {\n throw new Error(\n `File already exists: ${entry.relativePath}. Use --force to overwrite.`,\n );\n }\n }\n\n for (const entry of entries) {\n const absPath = join(outputDir, entry.relativePath);\n const dir = join(absPath, \"..\");\n await mkdir(dir, { recursive: true });\n await writeFile(absPath, entry.content, \"utf8\");\n files_created.push(entry.relativePath);\n }\n\n const gitignorePath = join(outputDir, \".gitignore\");\n if (existsSync(gitignorePath)) {\n const existing = await readFile(gitignorePath, \"utf8\");\n if (!existing.includes(\"agent/generated/\")) {\n await appendFile(gitignorePath, GITIGNORE_ENTRIES.join(\"\\n\") + \"\\n\", \"utf8\");\n files_created.push(\".gitignore\");\n }\n } else {\n await writeFile(gitignorePath, GITIGNORE_ENTRIES.join(\"\\n\").trimStart() + \"\\n\", \"utf8\");\n files_created.push(\".gitignore\");\n }\n\n return { files_created };\n}\n","/**\n * implement command — uses the built-in LLM Feature Implementer agent\n * to add LLM-powered commands to a CLI tool project.\n *\n * The agent is defined in DSL (dsl/implement-dsl.yaml) and its contracts\n * are pre-generated into src/builtin-agents/generated/.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { runWorkflow } from \"./workflow-runner.js\";\nimport { buildTaskPrompt } from \"./task-runner.js\";\nimport type { SdkAdapter, TaskContext } from \"./task-runner.js\";\nimport type { WorkflowInvocation } from \"./workflow-runner.js\";\nimport {\n agentRegistry,\n taskRegistry,\n handoffSchemas,\n workflowRegistry,\n resolvedDsl,\n} from \"../builtin-agents/generated/index.js\";\nimport {\n createGuardrailHooksFromRules,\n type GuardrailHooks,\n type GuardrailRuleData,\n} from \"./guardrail-hooks.js\";\nimport type { ImplementationResult } from \"../builtin-agents/generated/handoffs.js\";\n\n// ---------------------------------------------------------------------------\n// Locale detection\n// ---------------------------------------------------------------------------\n\nfunction getLocale(): string {\n return (\n process.env.LANG?.split(\".\")[0] ??\n process.env.LC_ALL?.split(\".\")[0] ??\n process.env.LANGUAGE?.split(\":\")[0] ??\n \"en_US\"\n );\n}\n\nfunction isJapanese(): boolean {\n return getLocale().startsWith(\"ja\");\n}\n\n// ---------------------------------------------------------------------------\n// Messages — locale-aware\n// ---------------------------------------------------------------------------\n\ninterface Messages {\n noProjectDir: (dir: string) => string;\n adapterError: (msg: string) => string;\n dryRunHeader: string;\n dryRunProjectDir: (dir: string) => string;\n dryRunDescription: (desc: string) => string;\n dryRunRefIncluded: string;\n dryRunRefNotFound: string;\n implementStarting: (adapter: string) => string;\n implementSuccess: string;\n implementFailed: (reason: string) => string;\n filesCreated: string;\n filesModified: string;\n commandsAdded: string;\n nextSteps: string;\n}\n\nconst en: Messages = {\n noProjectDir: (dir) => `Project directory not found: ${dir}`,\n adapterError: (msg) => `Adapter initialization failed: ${msg}`,\n dryRunHeader: \"=== Dry Run ===\",\n dryRunProjectDir: (dir) => `Project: ${dir}`,\n dryRunDescription: (desc) => `Description: ${desc}`,\n dryRunRefIncluded: \"Reference: integrate-llm-commands (included)\",\n dryRunRefNotFound: \"Reference: integrate-llm-commands (not found, will proceed without)\",\n implementStarting: (adapter) => `Starting implementation with ${adapter} adapter...`,\n implementSuccess: \"Implementation completed successfully.\",\n implementFailed: (reason) => `Implementation failed: ${reason}`,\n filesCreated: \"Files created:\",\n filesModified: \"Files modified:\",\n commandsAdded: \"Commands added:\",\n nextSteps: \"Next steps:\",\n};\n\nconst ja: Messages = {\n noProjectDir: (dir) => `プロジェクトディレクトリが見つかりません: ${dir}`,\n adapterError: (msg) => `アダプター初期化に失敗しました: ${msg}`,\n dryRunHeader: \"=== ドライラン ===\",\n dryRunProjectDir: (dir) => `プロジェクト: ${dir}`,\n dryRunDescription: (desc) => `説明: ${desc}`,\n dryRunRefIncluded: \"リファレンス: integrate-llm-commands(含まれています)\",\n dryRunRefNotFound: \"リファレンス: integrate-llm-commands(未検出、リファレンスなしで続行)\",\n implementStarting: (adapter) => `${adapter} アダプターで実装を開始します...`,\n implementSuccess: \"実装が正常に完了しました。\",\n implementFailed: (reason) => `実装に失敗しました: ${reason}`,\n filesCreated: \"作成されたファイル:\",\n filesModified: \"変更されたファイル:\",\n commandsAdded: \"追加されたコマンド:\",\n nextSteps: \"次のステップ:\",\n};\n\nfunction msg(): Messages {\n return isJapanese() ? ja : en;\n}\n\n// ---------------------------------------------------------------------------\n// Reference document loader\n// ---------------------------------------------------------------------------\n\nfunction loadReferenceDoc(): string | undefined {\n const candidates = [\n // Shipped with the package (templates/ sibling of dist/)\n join(fileURLToPath(import.meta.url), \"..\", \"..\", \"..\", \"templates\", \"implement-reference.md\"),\n // Dev-time: from the skill directory\n join(process.env.HOME ?? \"\", \".cursor\", \"skills\", \"integrate-llm-commands\", \"SKILL.md\"),\n ];\n\n for (const candidate of candidates) {\n try {\n if (existsSync(candidate)) {\n return readFileSync(candidate, \"utf8\");\n }\n } catch {\n // continue\n }\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\nasync function createImplementAdapter(\n adapterName: string,\n projectDir: string,\n model?: string,\n guardrailHooks?: GuardrailHooks,\n): Promise<SdkAdapter> {\n switch (adapterName) {\n case \"claude\": {\n const { ClaudeAgentSdkAdapter } = await import(\"../adapters/claude-agent-sdk.js\");\n return new ClaudeAgentSdkAdapter({\n cwd: projectDir,\n permissionMode: \"bypassPermissions\",\n model,\n guardrailHooks,\n });\n }\n case \"mock\": {\n const { MockAdapter } = await import(\"../adapters/mock.js\");\n return new MockAdapter();\n }\n default:\n throw new Error(\n `Unsupported adapter for implement: \"${adapterName}\". ` +\n `Available: claude, mock`,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface ImplementOptions {\n adapter: string;\n projectDir: string;\n dryRun: boolean;\n reportFormat: \"json\" | \"text\" | \"yaml\";\n model?: string;\n verbose?: boolean;\n progressOutput?: { write(chunk: string): unknown };\n}\n\nexport interface ImplementRunResult {\n status: \"success\" | \"failed\" | \"dry_run\";\n exitCode: number;\n data?: ImplementationResult;\n error?: string;\n}\n\nexport async function runImplement(\n description: string,\n options: ImplementOptions,\n): Promise<ImplementRunResult> {\n const m = msg();\n const projectDir = resolve(options.projectDir);\n\n if (!existsSync(projectDir)) {\n return { status: \"failed\", exitCode: 3, error: m.noProjectDir(projectDir) };\n }\n\n const referenceDoc = loadReferenceDoc();\n\n // --- Build invocation context (shared between dry-run and live run) ---\n const userRequest = [\n description,\n \"\",\n `Project directory: ${projectDir}`,\n ].join(\"\\n\");\n\n const context: TaskContext = {\n user_request: userRequest,\n relevant_paths: [projectDir],\n };\n\n if (referenceDoc) {\n context.prior_context =\n \"# Reference: integrate-llm-commands pattern\\n\\n\" +\n \"Follow this reference exactly when implementing LLM commands.\\n\\n\" +\n referenceDoc;\n }\n\n // --- Dry run: emit the real prompt without calling the LLM ---\n if (options.dryRun) {\n const agent = agentRegistry[\"llm-feature-implementer\"];\n const task = taskRegistry[\"implement-llm-feature\"];\n const prompt = buildTaskPrompt(agent, task, context, { handoffSchemas });\n\n return {\n status: \"dry_run\",\n exitCode: 0,\n data: {\n files_created: [],\n files_modified: [],\n summary: prompt,\n },\n };\n }\n\n // --- Create adapter ---\n let guardrailHooks: GuardrailHooks | undefined;\n const rawRules = resolvedDsl._guardrailRules as GuardrailRuleData | undefined;\n if (\n rawRules &&\n (rawRules.commandRules?.length ||\n rawRules.fileRules?.length ||\n rawRules.contentRules?.length)\n ) {\n guardrailHooks = createGuardrailHooksFromRules(rawRules);\n }\n\n let adapter: SdkAdapter;\n try {\n adapter = await createImplementAdapter(\n options.adapter,\n projectDir,\n options.model,\n guardrailHooks,\n );\n } catch (err) {\n return { status: \"failed\", exitCode: 12, error: m.adapterError((err as Error).message) };\n }\n\n if (!options.verbose) {\n console.error(m.implementStarting(options.adapter));\n }\n\n const registries = {\n workflowRegistry,\n taskRegistry,\n agentRegistry,\n handoffSchemas,\n };\n\n // --- Run workflow ---\n const invocation: WorkflowInvocation = {\n workflow: \"implement-llm-feature\",\n user_request: userRequest,\n runtime: {\n maxFollowUps: 3,\n maxRetries: 1,\n },\n hooks: {\n onGate: async () => true,\n },\n context: {\n cwd: projectDir,\n },\n progressOutput: options.progressOutput,\n };\n\n const result = await runWorkflow(adapter, invocation, registries);\n\n if (result.status !== \"completed\") {\n const reason = result.escalation_reason ?? result.error_message ?? result.status;\n return { status: \"failed\", exitCode: 1, error: m.implementFailed(reason) };\n }\n\n // Extract structured result from the last successful step\n const lastStep = result.steps[result.steps.length - 1];\n const outcomeData = (lastStep?.outcome as Record<string, unknown>)?.data as\n | ImplementationResult\n | undefined;\n\n return {\n status: \"success\",\n exitCode: 0,\n data: outcomeData ?? {\n files_created: [],\n files_modified: [],\n summary: m.implementSuccess,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Text formatter\n// ---------------------------------------------------------------------------\n\nexport function formatImplementResult(result: ImplementRunResult): string {\n const m = msg();\n\n if (result.status === \"dry_run\") {\n return result.data?.summary ?? m.dryRunHeader;\n }\n\n if (result.status === \"failed\") {\n return result.error ?? m.implementFailed(\"unknown\");\n }\n\n const data = result.data;\n if (!data) return m.implementSuccess;\n\n const lines: string[] = [data.summary, \"\"];\n\n if (data.files_created.length > 0) {\n lines.push(m.filesCreated);\n for (const f of data.files_created) lines.push(` + ${f}`);\n lines.push(\"\");\n }\n\n if (data.files_modified.length > 0) {\n lines.push(m.filesModified);\n for (const f of data.files_modified) lines.push(` ~ ${f}`);\n lines.push(\"\");\n }\n\n if (data.commands_added && data.commands_added.length > 0) {\n lines.push(m.commandsAdded);\n for (const c of data.commands_added) {\n lines.push(` - ${c.name} [${c.type}]${c.description ? ` — ${c.description}` : \"\"}`);\n }\n lines.push(\"\");\n }\n\n if (data.next_steps && data.next_steps.length > 0) {\n lines.push(m.nextSteps);\n for (const s of data.next_steps) lines.push(` ${s}`);\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\nexport interface AgentRule {\n readonly id: string;\n readonly description: string;\n readonly severity: \"mandatory\" | \"recommended\" | \"optional\";\n}\n\nexport interface EscalationCriterion {\n readonly condition: string;\n readonly action: \"stop_and_report\" | \"report_to_architect\" | \"wait_for_approval\";\n}\n\nexport interface AgentContract {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly dispatch_only: boolean;\n readonly can_read_artifacts: readonly string[];\n readonly can_write_artifacts: readonly string[];\n readonly can_execute_tools: readonly string[];\n readonly can_invoke_agents: readonly string[];\n readonly can_return_handoffs: readonly string[];\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n readonly rules: readonly AgentRule[];\n readonly escalation_criteria: readonly EscalationCriterion[];\n}\n\nexport const implementationAuditor: AgentContract = {\n id: \"implementation-auditor\",\n role_name: \"Implementation Auditor\",\n purpose: \"Audits an existing LLM command integration to verify it correctly\\nfollows the agent-contracts + agent-contracts-runtime + cli-contracts\\nstack conventions. Detects architectural violations, missing patterns,\\nincorrect API usage, and deviations from the canonical\\nintegrate-llm-commands pattern.\\n\\nThis agent is read-only — it analyzes code but does not modify it.\\nIt produces structured findings (AgentAuditResult) that identify\\nexactly what is wrong and how to fix it.\\n\\n## What This Agent Checks\\n\\n### Layer 1: agent-contracts DSL\\n- DSL entry has version:1 and system block with id/name\\n- Agents defined with all required fields (role_name, purpose, mode,\\n can_read_artifacts, can_write_artifacts, responsibilities, constraints)\\n- Tasks have target_agent, workflow, result_handoff, completion_criteria\\n- Handoff type schemas conform to AgentAuditResult base shape\\n- Workflows define steps with correct task/agent cross-references\\n- Guardrails and guardrail_policies are defined\\n- agent-runtime.config.yaml exists with dsl and generated_dir\\n\\n### Layer 2: agent-contracts-runtime Integration\\n- orchestrator.ts uses runWorkflow(), NOT runTask() or adapter.send()\\n- runTask() is a low-level internal API — consumer projects must\\n use runWorkflow() which handles workflow DAG, plugin hooks, gates\\n- Adapters imported from agent-contracts-runtime/adapters/*, not custom\\n- Dynamic import pattern for graceful degradation (exit 11/12)\\n- Generated registries imported from src/generated/dsl/index.js\\n- Registries (including workflowRegistry) passed to runWorkflow\\n- Plugin hooks not bypassed\\n- No hand-rolled prompt building (use buildTaskPrompt or let runWorkflow do it)\\n\\n### Layer 3: cli-contracts Compliance\\n- cli-contract.yaml has LLM commands with all standard options:\\n --adapter, --model, --show-prompt, --fail-on, --output, --report-format\\n- x-agent metadata present (riskLevel, safeDryRunOption, expectedDurationMs)\\n- Exit codes follow convention (0, 1, 3, 10, 11, 12)\\n- components/schemas includes AgentAuditResult and related types\\n- --report-format used (not --format) for LLM commands\\n\\n### Architecture & Patterns\\n- src/agents/ module structure (orchestrator, context-builder, formatter, types)\\n- Context builder caps input at 16KB\\n- Formatter implements computeExitCode with correct threshold logic\\n- --show-prompt returns prompt without LLM call\\n- No direct LLM API calls anywhere in the codebase\\n\\n### Semantic Design Coherence\\n- Context-builder must contain only domain DATA (file contents,\\n config, scan results) — never agent INSTRUCTIONS (evaluation\\n criteria, rules, anti-patterns, output format specifications).\\n These belong in the DSL agent definition and are injected by\\n buildTaskPrompt / runWorkflow. Hardcoding instructions in\\n context-builder defeats the purpose of using DSL.\\n- Agent mode must match purpose: read-only agents must not have\\n write-oriented purposes, read-write agents must propagate cwd\\n to their adapter so file tools operate in the project directory.\\n- CLI must use cli-contracts' generated CommandHandlers interface\\n and createProgram() — not manually wired Commander commands.\\n\",\n mode: \"read-only\",\n dispatch_only: false,\n can_read_artifacts: [],\n can_write_artifacts: [],\n can_execute_tools: [],\n can_invoke_agents: [],\n can_return_handoffs: [\n \"audit-result\"\n],\n responsibilities: [\n \"Verify the DSL directory structure exists: dsl/{project}-dsl.yaml, dsl/agents/*.yaml, dsl/tasks.yaml, dsl/handoff-types.yaml, dsl/agent-runtime.config.yaml.\",\n \"Check that the main DSL entry has version:1, a system block with id and name, and uses $ref for agents/tasks/handoff_types.\",\n \"Validate agent definitions have all required fields: role_name, purpose, mode, can_read_artifacts:[], can_write_artifacts:[], responsibilities, constraints. Check that rules use R-PREFIX-NNN format and severity is mandatory|recommended|optional.\",\n \"Validate task definitions: target_agent matches a defined agent, workflow matches a defined workflow, result_handoff matches a defined handoff type, completion_criteria are specific and testable.\",\n \"Verify handoff type schemas conform to AgentAuditResult shape when applicable (summary, riskLevel, findings[], recommendedActions[], metadata). Check $ref usage and SSoT comments for inlined schemas.\",\n \"Check that guardrails and guardrail_policies are defined, and that output-schema-conformance is included.\",\n \"Scan src/agents/orchestrator.ts for: (1) imports from agent-contracts-runtime (not custom SDK wrappers), (2) usage of runWorkflow() — NOT runTask() which is a low-level internal API that bypasses workflow orchestration, plugin hooks, and gate steps, (3) dynamic import pattern with exit code 11 for missing runtime and exit code 12 for adapter errors, (4) generated registries (including workflowRegistry) imported and passed to runWorkflow.\",\n \"Verify no file in the project calls adapter.send(), adapter.followUp(), adapter.sendExecution(), or runTask() directly — all LLM invocations must go through runWorkflow().\",\n \"Check that src/generated/dsl/ exists and contains the expected files (agents.ts, tasks.ts, workflows.ts, handoffs.ts, index.ts). Verify the .manifest.json exists and is not stale.\",\n \"Verify adapter creation uses the correct constructors: ClaudeAgentSdkAdapter constructor, OpenAIAgentsSdkAdapter constructor, etc.\",\n \"Check cli-contract.yaml for each LLM command: all six standard options present (--adapter, --model, --show-prompt, --fail-on, --output, --report-format). Verify --report-format is used (not --format).\",\n \"Verify x-agent metadata on each LLM command: riskLevel, safeDryRunOption (must be \\\"show-prompt\\\"), expectedDurationMs. Flag high-risk commands without requiresConfirmation.\",\n \"Check exit code definitions: 0 (success), 1 (error), 3 (validation), 10 (findings), 11 (runtime missing), 12 (adapter error).\",\n \"Verify components/schemas includes AgentAuditResult, AgentFinding, AgentRecommendedAction, and AgentEvidence definitions.\",\n \"Verify src/agents/ directory structure: types.ts (TaskId, AgentConfig, AgentOptions, AgentRunResult), orchestrator.ts (createAdapter, runAgentTask with dynamic imports), context-builder.ts (build*Context functions with 16KB cap), formatter.ts (computeExitCode, formatResultText, formatResultJson).\",\n \"Check that --show-prompt mode returns the constructed prompt without making any LLM API call.\",\n \"Scan for direct LLM API imports (@anthropic-ai/sdk, openai, @google/genai) used outside of adapter files — application code must not import these directly.\",\n \"Audit context-builder for SSoT violations: scan for hardcoded agent instructions (sections titled \\\"## Instructions\\\", \\\"## Required Patterns\\\", \\\"## Output Format\\\", evaluation criteria, checklists, anti-pattern definitions, API references, or output schema descriptions). These belong in the DSL agent definition and are injected by buildTaskPrompt. Context-builder should contain only domain-specific data (file contents, configuration, scan results, project metadata).\",\n \"Check agent mode-purpose coherence: for each agent in the DSL, verify that mode: read-only agents do not have purposes or responsibilities describing file writing/editing/creation, and that mode: read-write agents propagate cwd through AgentConfig to the adapter so file tools operate in the correct directory.\",\n \"Verify cwd propagation: command handlers must set cwd in AgentConfig (e.g. process.cwd() or resolve(projectDir)), createAdapter must pass cwd to adapter constructors/factories, and AgentConfig type must include a cwd field.\",\n \"Verify cli-contracts handler wiring: if the project uses cli-contracts (has src/generated/program.ts or src/generated/cli/program.ts exporting CommandHandlers and createProgram), the CLI entry point must use createProgram(handlers, version) with a handlers object implementing the CommandHandlers interface — not manually created Commander commands.\"\n],\n constraints: [\n \"This agent is read-only. It must not create, modify, or delete any files. Output is a structured audit report only.\",\n \"Findings must include specific file paths, line references where possible, and concrete remediation steps.\",\n \"Severity classification: critical = breaks the integration pattern (direct API calls, missing runtime usage), error = missing required element (no x-agent, missing standard option), warning = deviation from best practice (context not capped, missing guardrail), info = improvement suggestion.\",\n \"Category vocabulary: dsl-structure, dsl-agent, dsl-task, dsl-handoff, dsl-workflow, dsl-guardrail, runtime-adapter, runtime-orchestrator, runtime-registry, runtime-handler, runtime-plugin, cli-contract-options, cli-contract-xagent, cli-contract-exits, cli-contract-schema, architecture-modules, architecture-dry-run, architecture-context-builder, architecture-agent-coherence, architecture-adapter-cwd, architecture-handler, architecture-formatter.\",\n \"Every finding with severity warning or above must include a recommendation field with a concrete fix.\",\n \"The confidence field should reflect how certain the finding is: 1.0 for pattern matches (e.g., adapter.send() found in code), 0.8+ for structural checks (e.g., missing file), 0.5-0.8 for heuristic assessments (e.g., context might exceed 16KB).\"\n],\n rules: [\n {\n \"id\": \"R-AUDIT-001\",\n \"description\": \"Every finding must specify target (file path) and category (from the defined category vocabulary). Findings without a target are not actionable.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-002\",\n \"description\": \"The audit must check all four layers (DSL, runtime, CLI contract, architecture). Skipping a layer or returning partial results is not acceptable.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-003\",\n \"description\": \"Critical findings must be surfaced for: (1) direct adapter.send() calls bypassing runWorkflow, (2) runTask() used instead of runWorkflow() — runTask is a low-level internal API that bypasses workflow orchestration, (3) custom adapter classes not from agent-contracts-runtime, (4) missing generated registries in runWorkflow calls.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-004\",\n \"description\": \"The riskLevel in the audit result must be derived from the most severe finding: any critical → critical, any error → high, any warning → medium, info only → low.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-005\",\n \"description\": \"Context-builder must be audited for SSoT violations. Any hardcoded agent instructions (evaluation criteria, rules, anti-patterns, output format specs) in context-builder is a critical finding — these belong in the DSL agent definition and are injected by buildTaskPrompt / runWorkflow. Context-builder may only contain domain-specific data (file contents, configuration, scan results, project metadata).\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-007\",\n \"description\": \"runTask() usage in consumer projects is a CRITICAL finding. Consumer projects integrating with cli-contracts must use runWorkflow() exclusively. runTask() is a low-level internal API that bypasses workflow DAG orchestration, workflow-level plugin hooks (beforeWorkflow/afterWorkflow), gate steps, and step dependencies. Any occurrence of runTask import or call in orchestrator, command handler, or CLI entry point code must be reported as severity: critical.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-006\",\n \"description\": \"Agent mode-purpose coherence must be verified. A read-only agent whose purpose describes file writing is a critical finding because the adapter's tool set (Read/Glob/Grep only) makes the stated purpose impossible to fulfil.\",\n \"severity\": \"mandatory\"\n }\n],\n escalation_criteria: [\n {\n \"condition\": \"Target project has no LLM command integration to audit\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project uses a completely different integration pattern (not agent-contracts stack)\",\n \"action\": \"stop_and_report\"\n }\n],\n} as const;\n\nexport const llmFeatureImplementer: AgentContract = {\n id: \"llm-feature-implementer\",\n role_name: \"LLM Feature Implementer\",\n purpose: \"Expert implementation agent for the agent-contracts toolchain.\\nAdds LLM-powered commands (audit, propose, explain, etc.) to CLI tools\\nusing the three-layer stack:\\n\\n1. **agent-contracts** — DSL package. Defines agents, tasks, workflows,\\n handoff types, guardrails, and guardrail policies in YAML. The\\n `resolve()` function handles `$ref`, `extends`, and merge operators.\\n Installed as a devDependency. CLI: `agent-contracts audit`.\\n\\n2. **agent-contracts-runtime** — Runtime bridge. Generates typed\\n TypeScript contracts from DSL via Handlebars templates, then\\n executes workflows through pluggable SDK adapters. Provides\\n `runTask()`, `runWorkflow()`, `createRuntime()`, plugin system,\\n and guardrail hooks. CLI: `agent-runtime generate|run|list|doctor`.\\n\\n3. **cli-contracts** — CLI contract package. Defines command-line\\n interfaces in YAML (`cli-contract.yaml`): command sets, arguments,\\n options, exit codes, stdout/stderr schemas, `x-agent` metadata,\\n and `effects`. Generates typed Commander programs, Zod validators,\\n and markdown docs. CLI: `cli-contracts init|generate|validate`.\\n\\nThe canonical integration pattern (\\\"integrate-llm-commands\\\") produces:\\n- DSL definitions under `dsl/` (agents, tasks, workflows, handoff-types)\\n- Pre-generated TypeScript contracts under `src/generated/dsl/`\\n- Runtime integration module under `src/agents/` (orchestrator,\\n context-builder, formatter, types)\\n- CLI command handlers under `src/commands/`\\n- Updated `cli-contract.yaml` with new commands and `x-agent` metadata\\n\",\n mode: \"read-write\",\n dispatch_only: false,\n can_read_artifacts: [],\n can_write_artifacts: [],\n can_execute_tools: [],\n can_invoke_agents: [],\n can_return_handoffs: [\n \"implementation-result\"\n],\n responsibilities: [\n \"Read and analyze the target project's cli-contract.yaml, package.json, tsconfig.json, and existing source code to understand the CLI structure, existing commands, component schemas, and TypeScript configuration.\",\n \"Identify which LLM commands to add based on the user's description. Canonical command types: audit (semantic review), propose (structured proposal generation), explain (human-readable explanation of machine output).\",\n \"Create the DSL directory structure: dsl/{project}-dsl.yaml (main entry with version:1, system block, $ref to sub-files), dsl/agents/{name}.yaml, dsl/tasks.yaml, dsl/handoff-types.yaml, dsl/agent-runtime.config.yaml.\",\n \"Define agents with: role_name, purpose (domain expertise), mode (read-only for analysis agents), can_read_artifacts:[], can_write_artifacts:[], can_return_handoffs, responsibilities, constraints, rules (R-PREFIX-NNN format), escalation_criteria.\",\n \"Define tasks with: description, target_agent, allowed_from_agents, workflow (must match a workflow ID), invocation_handoff, result_handoff, responsibilities, completion_criteria.\",\n \"Define handoff types with: version:1, description, schema (JSON Schema). Result types should conform to AgentAuditResult shape (summary, riskLevel, findings[], recommendedActions[], metadata). Use $ref to cli-contract.yaml components/schemas as SSoT when possible; inline with SSoT comment as fallback.\",\n \"Define workflows with trigger, entry_conditions, and steps (delegate or gate). Each delegate step references a task and from_agent. Gate steps pause for user approval.\",\n \"Define guardrails (output-schema-conformance, domain-specific safety) and guardrail_policies grouping them with severity and action.\",\n \"Create agent-runtime.config.yaml: dsl points to main DSL file, generated_dir points to src/generated/dsl.\",\n \"Implement src/agents/types.ts: TaskId union type, AgentConfig interface (adapter, model, temperature), AgentOptions interface (dryRun, failOn), AgentRunResult interface (taskId, data, raw, prompt, dryRun, status, errorMessage, followUpsUsed, retriesUsed).\",\n \"Implement src/agents/orchestrator.ts: createAdapter() with dynamic imports from agent-contracts-runtime/adapters/*, runAgentWorkflow() that imports runWorkflow from agent-contracts-runtime, loads generated registries (including workflowRegistry) from src/generated/dsl/index.js, and calls runWorkflow with registries. NEVER use runTask — it is a low-level internal API that bypasses workflow orchestration.\",\n \"Implement src/agents/context-builder.ts: build{Command}Context() functions that transform CLI inputs into structured markdown prompts. Cap context at 16KB. Structure: # Request, ## Configuration, ## Target, ## Instructions.\",\n \"Implement src/agents/formatter.ts: computeExitCode() mapping findings to exit codes via --fail-on threshold, formatResultText() with severity icons, formatResultJson() for structured output.\",\n \"Create src/commands/{command}.ts handlers: load config, call context builder, call runAgentWorkflow, format output, compute exit code.\",\n \"Update cli-contract.yaml: add command definitions with standard LLM options (--adapter, --model, --show-prompt, --fail-on, --output, --report-format), exit codes (0, 1, 3, 10, 11, 12), x-agent metadata, and register AgentAuditResult/AgentFinding/AgentRecommendedAction in components/schemas.\",\n \"Add npm scripts: \\\"dsl:generate\\\" running agent-runtime generate --config dsl/agent-runtime.config.yaml. Add agent-contracts and agent-contracts-runtime as devDependencies. Add SDK packages as optional peerDependencies.\"\n],\n constraints: [\n \"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk, GeminiSdkAdapter from agent-contracts-runtime/adapters/gemini-sdk, MockAdapter from agent-contracts-runtime/adapters/mock.\",\n \"NEVER call adapter.send() or adapter.sendExecution() directly. All LLM invocations must go through runWorkflow() imported from agent-contracts-runtime. NEVER use runTask() — it is a low-level internal API. runWorkflow() handles prompt building, handoff validation, retry/followUp, workflow DAG, and plugin hooks.\",\n \"Dynamic-import both agent-contracts-runtime and adapter packages. The tool must work without them installed (graceful degradation). Pattern: const RUNTIME = \\\"agent-contracts-runtime\\\"; try { const { runWorkflow } = await import(RUNTIME); } catch { exit(11); }\",\n \"LLM commands use --report-format (json|text|yaml) for output format. --format is reserved for deterministic commands. Never mix them.\",\n \"Exit code convention: 0=success (no findings above threshold), 1=general error, 3=input validation/parse failed, 10=findings detected above --fail-on threshold, 11=agent-contracts-runtime not installed, 12=adapter initialization error (missing API key, etc.).\",\n \"Standard LLM command options (all must be present): --adapter <name> (mock|claude|openai|gemini, default varies), --model <name> (optional override), --show-prompt (output prompt without LLM call), --fail-on <level> (warning|error|critical, default error), --output/-o <file> (write to file instead of stdout), --report-format <fmt> (json|text|yaml, default json).\",\n \"Result handoff schemas must extend the AgentAuditResult base shape: summary (string, required), riskLevel (enum: low|medium|high|critical, required), findings (AgentFinding[], required), recommendedActions (AgentRecommendedAction[], optional), metadata (object with tool, command, version, generatedAt, adapter, model fields, optional).\",\n \"AgentFinding shape: id?, severity (info|warning|error|critical), category (domain vocabulary), target?, location?, message (required), recommendation?, confidence? (0-1), evidence? (array of {type,content,source}), details? (object).\",\n \"AgentRecommendedAction shape: kind (run_command|edit_file|review|confirm| block|ignore), title (required), command?, target?, rationale?.\",\n \"Main DSL entry must have version:1 and a system block with id and name. Without these, the generator produces numbered files instead of named ones.\",\n \"Every task must have a workflow field matching a defined workflow ID. Every workflow step's from_agent must match a defined agent ID. can_read_artifacts and can_write_artifacts must be empty arrays ([]) when no artifact registry is defined.\",\n \"agent-runtime.config.yaml format: dsl: ./{project}-dsl.yaml generated_dir: ../src/generated/dsl Optional: plugins (array of paths), recovery ({max_follow_ups, max_retries}).\",\n \"runWorkflow (the ONLY API consumer projects should use): Overloads: (1) runWorkflow(adapter, workflowId, options, registries?) — legacy. (2) runWorkflow(adapter, invocation, registries?) — structured (preferred). WorkflowInvocation: { workflow, handoff?, user_request?, runtime? {maxFollowUps,maxRetries,timeoutMs,readonly, dryRun}, hooks? {onStepComplete,onGate,onOptionalStep}, context? {cwd,environment,artifacts,variables} }. WorkflowResult: { workflow_id, status (completed|escalated|gate_rejected|error), steps[], total_elapsed_ms, escalation_reason?, error_message? }. NEVER use runTask() — it is a low-level internal API.\",\n \"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?}), GeminiSdkAdapter({apiKey?, model?, systemInstruction?, temperature?, maxOutputTokens?, guardrailHooks?}).\",\n \"Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from \\\"../generated/dsl/index.js\\\". Pass these as registries to runWorkflow: { workflowRegistry, taskRegistry, agentRegistry, handoffSchemas }.\",\n \"Plugin interface (AgentPlugin): id (string), beforeTask?(taskId, context), afterTask?(taskId, outcome), contextEnhancer?(taskId, context), promptEnhancer?(taskId, prompt, context), promptBuilder?(args), customGuardrails?, beforeWorkflow?(workflowId, userRequest), afterWorkflow?(workflowId, result).\",\n \"x-agent fields for LLM commands in cli-contract.yaml: riskLevel (low for read-only analysis), requiresConfirmation (false for read-only), idempotent (true for analysis), sideEffects ([network]), sideEffectNote (describe network call and optional file write), safeDryRunOption (show-prompt), expectedDurationMs (120000 typical), retryableExitCodes ([1, 12]).\"\n],\n rules: [\n {\n \"id\": \"R-IMPL-001\",\n \"description\": \"Import SDK adapters exclusively from agent-contracts-runtime/adapters/*. Never create adapter classes, wrapper functions, or API client code.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-002\",\n \"description\": \"All LLM invocations must use runWorkflow() from agent-contracts-runtime. NEVER use runTask() — it is a low-level internal API that bypasses workflow orchestration. Never call adapter.send(), adapter.followUp(), or adapter.sendExecution() directly. The runtime handles prompt building, schema validation, retry, followUp, workflow DAG, and plugin hooks.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-003\",\n \"description\": \"Every LLM command in cli-contract.yaml must have x-agent metadata with at minimum: riskLevel, safeDryRunOption, expectedDurationMs.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-004\",\n \"description\": \"Handoff type schemas must use $ref to cli-contract.yaml components/schemas as SSoT. If $ref resolution fails at generate time, inline the schema and add a YAML comment noting the SSoT path.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-005\",\n \"description\": \"Context builder must cap prompt input at 16KB. Filter large contexts (schema dumps, lint output, etc.) to relevant portions before inclusion.\",\n \"severity\": \"recommended\"\n },\n {\n \"id\": \"R-IMPL-006\",\n \"description\": \"The orchestrator must dynamic-import agent-contracts-runtime as a single string variable (const PKG = \\\"agent-contracts-runtime\\\") to enable graceful degradation. Exit with code 11 when the import fails, code 12 when the adapter fails to initialize.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-007\",\n \"description\": \"Generated DSL contracts must be imported from src/generated/dsl/index.js and passed as registries to runWorkflow. Never hard-code agent definitions, task definitions, or handoff schemas in application code.\",\n \"severity\": \"mandatory\"\n }\n],\n escalation_criteria: [\n {\n \"condition\": \"Target project has no cli-contract.yaml and user did not request creating one\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project is not a TypeScript / Node.js stack\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project already has src/agents/ with a different integration pattern\",\n \"action\": \"stop_and_report\"\n }\n],\n} as const;\n\nexport const agentRegistry: Record<string, AgentContract> = {\n \"implementation-auditor\": implementationAuditor,\n \"llm-feature-implementer\": llmFeatureImplementer,\n} as const;\n\nexport type AgentId = keyof typeof agentRegistry;\n","/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\nimport type { AgentId } from \"./agents\";\nimport type { HandoffTypeId } from \"./handoffs\";\n\nexport type ModelClass = \"fast\" | \"standard\" | \"thinking\";\n\nexport interface TaskContract {\n readonly id: string;\n readonly description: string;\n readonly target_agent: AgentId;\n readonly allowed_from_agents: readonly AgentId[];\n readonly workflow: string;\n readonly invocation_handoff: HandoffTypeId;\n readonly result_handoff: HandoffTypeId;\n readonly input_artifacts: readonly string[];\n readonly responsibilities: readonly string[];\n readonly completion_criteria: readonly string[];\n readonly optional: boolean;\n readonly model_class?: ModelClass;\n}\n\nexport const implementLlmFeature: TaskContract = {\n id: \"implement-llm-feature\",\n description: \"Implement LLM-powered commands in a target CLI tool using the\\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\\n\\n## Implementation Procedure\\n\\n### Step 1: Project Analysis\\n\\nRead these files from the target project:\\n- cli-contract.yaml — existing commands, components/schemas, x-agent usage\\n- package.json — dependencies, scripts, bin entries, type:\\\"module\\\" check\\n- tsconfig.json — module resolution, paths, outDir\\n- src/ directory structure — understand existing command handler pattern\\n\\nDetermine:\\n- Which LLM commands to add (audit / propose / explain)\\n- What domain-specific context each command needs\\n- What structured output schema each command returns\\n- Whether the project already has agent-contracts integration\\n\\n### Step 2: Install Dependencies\\n\\nAdd to package.json devDependencies:\\n- agent-contracts: ^0.32.0\\n- agent-contracts-runtime: ^0.31.0\\n- zod: ^4.0.0\\n\\nAdd optional peerDependencies for SDK packages:\\n- @anthropic-ai/claude-agent-sdk: >=0.2.0\\n- @openai/agents: >=0.10.0\\n- @google/genai: >=2.0.0\\n\\n### Step 3: Create DSL Definitions\\n\\nCreate directory structure:\\n\\n dsl/\\n ├── {project}-dsl.yaml\\n ├── agent-runtime.config.yaml\\n ├── agents/\\n │ └── {agent-name}.yaml\\n ├── tasks.yaml\\n └── handoff-types.yaml\\n\\n**Main DSL entry** (`dsl/{project}-dsl.yaml`):\\n\\n version: 1\\n system:\\n id: {project}\\n name: \\\"{Project} Agent System\\\"\\n default_workflow_order:\\n - {workflow-ids}\\n agents: { $ref: \\\"./agents/\\\" }\\n tasks: { $ref: \\\"./tasks.yaml\\\" }\\n handoff_types: { $ref: \\\"./handoff-types.yaml\\\" }\\n guardrails:\\n output-schema-conformance:\\n description: ...\\n scope: { agents: [...], tasks: [...] }\\n rationale: ...\\n guardrail_policies:\\n {domain}-safety-policy:\\n rules:\\n - guardrail: output-schema-conformance\\n severity: critical\\n action: block\\n workflow:\\n {workflow-id}:\\n description: ...\\n trigger: cli-command\\n entry_conditions: [...]\\n steps:\\n - type: delegate\\n task: {task-id}\\n from_agent: {agent-id}\\n\\n**Agent definition** (`dsl/agents/{agent-name}.yaml`):\\n\\n {agent-name}:\\n role_name: \\\"{Role Name}\\\"\\n purpose: >-\\n Domain-specific purpose describing what the agent knows\\n and what it can do that static rules cannot.\\n mode: read-only\\n can_read_artifacts: []\\n can_write_artifacts: []\\n can_invoke_agents: []\\n can_execute_tools: []\\n can_return_handoffs: [{result-handoff-ids}]\\n responsibilities: [...]\\n constraints: [...]\\n rules:\\n - id: \\\"R-{PREFIX}-001\\\"\\n description: ...\\n severity: mandatory\\n escalation_criteria:\\n - condition: ...\\n action: stop_and_report\\n\\n**Tasks** (`dsl/tasks.yaml`):\\n\\n {task-id}:\\n description: ...\\n target_agent: {agent-name}\\n allowed_from_agents: [{agent-name}]\\n workflow: {workflow-id}\\n input_artifacts: []\\n invocation_handoff: {request-handoff}\\n result_handoff: {result-handoff}\\n responsibilities: [...]\\n completion_criteria: [...]\\n\\n**Handoff types** (`dsl/handoff-types.yaml`):\\nUse AgentAuditResult shape as the base for result types:\\n\\n {result-handoff}:\\n version: 1\\n description: ...\\n schema:\\n type: object\\n required: [summary, riskLevel, findings]\\n properties:\\n summary: { type: string }\\n riskLevel:\\n type: string\\n enum: [low, medium, high, critical]\\n findings:\\n type: array\\n items:\\n type: object\\n required: [severity, category, message]\\n properties:\\n id: { type: string }\\n severity:\\n type: string\\n enum: [info, warning, error, critical]\\n category: { type: string }\\n target: { type: string }\\n location: { type: string }\\n message: { type: string }\\n recommendation: { type: string }\\n confidence: { type: number, minimum: 0, maximum: 1 }\\n recommendedActions:\\n type: array\\n items:\\n type: object\\n required: [kind, title]\\n properties:\\n kind:\\n type: string\\n enum: [run_command, edit_file, review, confirm, block, ignore]\\n title: { type: string }\\n command: { type: string }\\n target: { type: string }\\n rationale: { type: string }\\n metadata:\\n type: object\\n properties:\\n tool: { type: string }\\n command: { type: string }\\n version: { type: string }\\n generatedAt: { type: string }\\n adapter: { type: string }\\n model: { type: string }\\n\\nDomain-specific result types add properties alongside the base fields.\\n\\n**Runtime config** (`dsl/agent-runtime.config.yaml`):\\n\\n dsl: ./{project}-dsl.yaml\\n generated_dir: ../src/generated/dsl\\n\\n### Step 4: Generate TypeScript Contracts\\n\\nAdd to package.json scripts:\\n\\n \\\"dsl:generate\\\": \\\"agent-runtime generate --config dsl/agent-runtime.config.yaml\\\"\\n\\nRun: npm run dsl:generate\\n\\nThis produces src/generated/dsl/ containing:\\n- agents.ts (AgentContract interface + agentRegistry)\\n- tasks.ts (TaskContract interface + taskRegistry)\\n- workflows.ts (WorkflowContract + workflowRegistry)\\n- handoffs.ts (Zod schemas + handoffSchemas + factory functions)\\n- index.ts (barrel re-exports)\\n\\n### Step 5: Implement src/agents/ Module\\n\\n**src/agents/types.ts**:\\n\\n import type { {ResultType} } from \\\"../generated/dsl/handoffs.js\\\";\\n\\n export type TaskId = \\\"{task-1}\\\" | \\\"{task-2}\\\" | ...;\\n\\n export interface AgentConfig {\\n adapter?: string;\\n model?: string;\\n temperature?: number;\\n }\\n\\n export interface AgentOptions {\\n dryRun?: boolean;\\n failOn?: \\\"warning\\\" | \\\"error\\\" | \\\"critical\\\";\\n }\\n\\n export interface AgentRunResult {\\n taskId: TaskId;\\n data: {ResultType} | null;\\n raw: string;\\n prompt: string;\\n dryRun: boolean;\\n status: \\\"success\\\" | \\\"error\\\" | \\\"escalation\\\" | \\\"validation_error\\\";\\n errorMessage?: string;\\n followUpsUsed: number;\\n retriesUsed: number;\\n }\\n\\n**src/agents/orchestrator.ts**:\\n\\n export const EXIT_RUNTIME_MISSING = 11;\\n export const EXIT_ADAPTER_ERROR = 12;\\n\\n async function createAdapter(pkg: string, name: string, config: AgentConfig) {\\n switch (name) {\\n case \\\"mock\\\": {\\n const m = await import(`${pkg}/adapters/mock`);\\n return new m.MockAdapter();\\n }\\n case \\\"claude\\\": {\\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\\n }\\n case \\\"openai\\\": {\\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\\n }\\n case \\\"gemini\\\": {\\n const m = await import(`${pkg}/adapters/gemini-sdk`);\\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\\n }\\n }\\n }\\n\\n export async function runAgentWorkflow(\\n userRequest: string, workflowId: WorkflowId, config: AgentConfig, options: AgentOptions,\\n ): Promise<AgentRunResult> {\\n if (options.dryRun) return { workflowId, data:null, raw:\\\"\\\", prompt:userRequest, dryRun:true, status:\\\"success\\\" };\\n\\n const PKG = \\\"agent-contracts-runtime\\\";\\n let runWorkflow;\\n try { ({ runWorkflow } = await import(PKG)); }\\n catch { throw Object.assign(new Error(\\\"agent-contracts-runtime not installed\\\"), { exitCode: EXIT_RUNTIME_MISSING }); }\\n\\n let registries;\\n try {\\n const dsl = await import(\\\"../generated/dsl/index.js\\\");\\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas, workflowRegistry: dsl.workflowRegistry };\\n } catch { registries = {}; }\\n\\n const adapter = await createAdapter(PKG, config.adapter ?? \\\"mock\\\", config);\\n const result = await runWorkflow(adapter, { workflow: workflowId, user_request: userRequest, runtime: { maxFollowUps:3, maxRetries:1 } }, registries);\\n // map result to AgentRunResult\\n }\\n\\n**src/agents/context-builder.ts**:\\n\\nCRITICAL: context-builder builds the USER-SIDE prompt only.\\nAgent instructions (purpose, responsibilities, constraints, rules,\\nevaluation criteria, anti-patterns, output format) are defined in\\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\\nbuildTaskPrompt / runWorkflow. NEVER hardcode these in context-builder.\\n\\nContext-builder SHOULD contain:\\n- Domain-specific DATA: file contents, configuration, scan results\\n- Project metadata: target paths, dialect, directory structure\\n- Deterministic pre-analysis: lint results, schema excerpts\\n- Operational context: cwd, timestamps\\n- Brief task framing: \\\"# Migration Safety Audit Request\\\"\\n\\nContext-builder MUST NOT contain:\\n- \\\"## Instructions\\\" / \\\"## Required Patterns\\\" sections\\n- Output format specifications (handled by handoff schema)\\n- Evaluation criteria or checklists\\n- Anti-pattern definitions or rule sets\\n- API reference material\\n- Anything that duplicates DSL agent purpose/responsibilities/rules\\n\\n export function build{Command}Context(target, config): string {\\n const sections = [];\\n sections.push(\\\"# {Command} Request\\\");\\n sections.push(`## Target\\\\n\\\\n${target}`);\\n // Domain data only — no instructions here.\\n // Agent instructions come from DSL via buildTaskPrompt.\\n // Cap total context at 16KB\\n return sections.join(\\\"\\\\n\\\\n\\\");\\n }\\n\\n**src/agents/formatter.ts**:\\n\\n export function computeExitCode(result, options): number {\\n if (result.dryRun) return 0;\\n if (result.status !== \\\"success\\\") return 1;\\n const order = [\\\"info\\\",\\\"warning\\\",\\\"error\\\",\\\"critical\\\"];\\n const threshold = order.indexOf(options.failOn ?? \\\"error\\\");\\n return result.data.findings.some(f => order.indexOf(f.severity) >= threshold) ? 10 : 0;\\n }\\n\\n export function formatResultText(result): string { /* severity icons, structured output */ }\\n export function formatResultJson(result): string { return JSON.stringify(result.data, null, 2); }\\n\\n### Step 6: Create CLI Command Handlers\\n\\nFor each LLM command, create src/commands/{command}.ts:\\n\\n export async function command{Name}(target, opts) {\\n const cwd = process.cwd();\\n const context = build{Name}Context(target, config);\\n const agentConfig = { adapter: opts.adapter, model: opts.model, cwd };\\n const result = await runAgentWorkflow(context, \\\"{workflow-id}\\\", agentConfig, agentOpts);\\n if (opts.reportFormat === \\\"json\\\") console.log(formatResultJson(result));\\n else console.log(formatResultText(result));\\n process.exit(computeExitCode(result, opts));\\n }\\n\\nWire handlers through cli-contracts' generated program:\\n\\n import { createProgram, type CommandHandlers } from './generated/program.js';\\n\\n const handlers: CommandHandlers = {\\n {commandName}: async (target, opts) => {\\n await command{Name}(target, opts);\\n },\\n // ... other handlers\\n };\\n\\n createProgram(handlers, version).parse();\\n\\n### Step 7: Update cli-contract.yaml\\n\\nAdd each LLM command with standard options and x-agent metadata:\\n\\n {command-name}:\\n summary: \\\"{Command summary}\\\"\\n arguments: [...]\\n options:\\n - name: adapter\\n schema: { type: string, enum: [mock, claude, openai, gemini] }\\n - name: model\\n schema: { type: string }\\n - name: show-prompt\\n schema: { type: boolean, default: false }\\n - name: fail-on\\n schema: { type: string, enum: [warning, error, critical], default: error }\\n - name: output\\n aliases: [o]\\n schema: { type: string }\\n file: { mode: write }\\n - name: report-format\\n schema: { type: string, enum: [json, text, yaml], default: json }\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: [network]\\n sideEffectNote: >-\\n Network calls to LLM provider when adapter is not mock.\\n Filesystem write only when --output is specified.\\n safeDryRunOption: show-prompt\\n expectedDurationMs: 120000\\n retryableExitCodes: [1, 12]\\n exits:\\n '0': { description: \\\"No blocking findings.\\\", stdout: { format: json, schema: { $ref: '...' } } }\\n '1': { description: \\\"General error.\\\", stderr: { format: text } }\\n '3': { description: \\\"Input validation failed.\\\", stderr: { format: json } }\\n '10': { description: \\\"Blocking findings detected.\\\", stdout: { format: json, schema: { $ref: '...' } } }\\n '11': { description: \\\"Runtime not installed.\\\", stderr: { format: json } }\\n '12': { description: \\\"Adapter error.\\\", stderr: { format: json } }\\n\\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\\nto components/schemas if not already present.\\n\\n### Step 8: Update README\\n\\nAdd \\\"Agent-Native Toolchain\\\" section after mechanical features:\\n- Intro: tool encapsulates domain-specific semantic reasoning\\n- Deterministic checks first, then semantic audit\\n- Structured findings (AgentAuditResult/AgentFinding)\\n- LLM Adapter Configuration table\\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\\n\",\n target_agent: \"llm-feature-implementer\",\n allowed_from_agents: [\n \"llm-feature-implementer\"\n],\n workflow: \"implement-llm-feature\",\n invocation_handoff: \"implement-request\",\n result_handoff: \"implementation-result\",\n input_artifacts: [],\n responsibilities: [\n \"Analyze the target project and determine the right LLM commands to add\",\n \"Create all DSL definition files with correct cross-references\",\n \"Generate TypeScript contracts via agent-runtime generate\",\n \"Implement the complete src/agents/ module following the exact patterns\",\n \"Create CLI command handlers integrating with the project's existing CLI structure\",\n \"Update cli-contract.yaml with proper x-agent metadata and component schemas\",\n \"Ensure the implementation compiles and --show-prompt mode works\"\n],\n completion_criteria: [\n \"dsl/ directory contains valid DSL definitions that pass agent-runtime generate\",\n \"agent-runtime.config.yaml points to the DSL with correct generated_dir\",\n \"src/generated/dsl/ contains generated contracts (agentRegistry, taskRegistry, handoffSchemas, workflowRegistry)\",\n \"src/agents/orchestrator.ts uses runWorkflow from agent-contracts-runtime (never runTask directly, no direct adapter.send calls)\",\n \"src/agents/orchestrator.ts dynamic-imports the runtime and adapters with correct exit codes (11, 12)\",\n \"src/agents/context-builder.ts contains only domain data (file contents, config, scan results) — no hardcoded agent instructions, evaluation criteria, or output format specs\",\n \"src/agents/context-builder.ts caps input at 16KB\",\n \"src/agents/formatter.ts implements computeExitCode with the standard exit code mapping\",\n \"src/commands/ has a handler for each new LLM command, passing cwd to AgentConfig\",\n \"CLI entry point uses cli-contracts' createProgram(handlers, version) with CommandHandlers interface\",\n \"cli-contract.yaml has all new commands with --adapter, --model, --show-prompt, --fail-on, --output, --report-format options\",\n \"cli-contract.yaml has x-agent metadata on each new command (riskLevel, safeDryRunOption, expectedDurationMs)\",\n \"components/schemas includes AgentAuditResult and related schemas\",\n \"All generated TypeScript compiles without type errors\",\n \"--show-prompt returns the constructed prompt without calling the LLM\"\n],\n optional: false,\n};\n\nexport const auditDsl: TaskContract = {\n id: \"audit-dsl\",\n description: \"Audit the DSL layer of an LLM command integration.\\n\\nVerify these files exist and are well-formed:\\n- dsl/{project}-dsl.yaml — must have version:1, system:{id,name},\\n agents/tasks/handoff_types via $ref\\n- dsl/agents/*.yaml — each agent has role_name, purpose, mode,\\n can_read_artifacts:[], can_write_artifacts:[], responsibilities,\\n constraints, rules with R-PREFIX-NNN\\n- dsl/tasks.yaml — target_agent, workflow, result_handoff all\\n cross-reference valid IDs\\n- dsl/handoff-types.yaml — version:1, schema with JSON Schema,\\n result types follow AgentAuditResult shape\\n- dsl/agent-runtime.config.yaml — dsl and generated_dir fields\\n\\nSeverity classification:\\n- critical: missing version:1 or system block (generator will fail)\\n- critical: task references non-existent agent or workflow\\n- critical: agent mode contradicts its purpose (see below)\\n- error: agent missing constraints or rules\\n- error: handoff schema not following AgentAuditResult shape\\n- warning: missing guardrails or guardrail_policies\\n- warning: agent has no escalation_criteria\\n\\nCRITICAL: agent mode-purpose coherence (category: dsl-agent):\\n- Agent with mode: read-only has purpose or responsibilities\\n that describe file writing, editing, creation, or code\\n generation — the agent's adapter tools won't include Write/Edit\\n so the stated purpose is impossible to fulfil\\n- Agent with mode: read-write has purpose that is purely\\n analytical (audit, review, explain) with no file output —\\n unnecessarily broad permissions\\n\\nCategory vocabulary: dsl-structure, dsl-agent, dsl-task,\\ndsl-handoff, dsl-workflow, dsl-guardrail.\\n\\nOutput a partial audit-result with findings only from the DSL layer.\\n\",\n target_agent: \"implementation-auditor\",\n allowed_from_agents: [\n \"implementation-auditor\"\n],\n workflow: \"audit-implementation\",\n invocation_handoff: \"audit-request\",\n result_handoff: \"audit-result\",\n input_artifacts: [],\n responsibilities: [\n \"Check all DSL files for structural correctness\",\n \"Validate cross-references (agent↔task↔workflow↔handoff)\",\n \"Verify guardrails and guardrail_policies\",\n \"Check agent mode-purpose coherence (read-only agents must not have write-oriented purposes; read-write agents must justify their write permissions in their purpose)\"\n],\n completion_criteria: [\n \"Every dsl/* file checked for required fields\",\n \"Cross-references validated\",\n \"Agent mode is consistent with stated purpose and responsibilities\",\n \"Findings use dsl-* category vocabulary\"\n],\n optional: false,\n};\n\nexport const auditRuntime: TaskContract = {\n id: \"audit-runtime\",\n description: \"Audit the runtime integration layer of an LLM command integration.\\n\\nScan src/agents/orchestrator.ts (or equivalent runtime module):\\n\\nCRITICAL violations (category: runtime-orchestrator):\\n- adapter.send() or adapter.sendExecution() called directly\\n- adapter.followUp() called directly\\n- Custom adapter class defined (not imported from runtime)\\n- runWorkflow not imported from agent-contracts-runtime\\n- runTask used instead of runWorkflow — consumer projects must\\n use runWorkflow() which orchestrates through the DSL workflow\\n DAG, activates workflow-level plugin hooks (beforeWorkflow/\\n afterWorkflow), handles gate steps and step dependencies.\\n runTask() is a low-level internal API; calling it directly\\n bypasses workflow orchestration entirely\\n\\nERROR violations (category: runtime-registry):\\n- Generated registries not imported from src/generated/dsl/\\n- Registries not passed to runWorkflow options\\n- Hard-coded agent/task definitions instead of registry lookup\\n\\nERROR violations (category: runtime-adapter):\\n- Adapter packages imported statically (not dynamic import)\\n- Missing exit code 11 when runtime import fails\\n- Missing exit code 12 when adapter creation fails\\n\\nERROR violations (category: runtime-handler):\\n- Project has cli-contracts generated code (src/generated/program.ts\\n or src/generated/cli/program.ts exporting CommandHandlers and\\n createProgram) but CLI entry point manually creates Commander\\n commands instead of using createProgram(handlers, version)\\n- LLM command handlers are not wired through the generated\\n CommandHandlers interface — handler signatures drift from the\\n cli-contract.yaml definition without type errors\\n- CLI entry point calls runTask directly instead of going through\\n the command handler → context-builder → orchestrator chain\\n\\nWARNING violations (category: runtime-plugin):\\n- Plugin hooks explicitly bypassed or ignored\\n\\nCategory vocabulary: runtime-orchestrator, runtime-registry,\\nruntime-adapter, runtime-handler, runtime-plugin.\\n\\nOutput a partial audit-result with findings only from the runtime layer.\\n\",\n target_agent: \"implementation-auditor\",\n allowed_from_agents: [\n \"implementation-auditor\"\n],\n workflow: \"audit-implementation\",\n invocation_handoff: \"audit-request\",\n result_handoff: \"audit-result\",\n input_artifacts: [],\n responsibilities: [\n \"Scan orchestrator code for direct adapter usage\",\n \"Verify runWorkflow is used (not runTask) for LLM command execution\",\n \"Verify registry imports and passing\",\n \"Check adapter creation patterns and exit codes\",\n \"Verify cli-contracts handler wiring (CommandHandlers + createProgram used in CLI entry point)\"\n],\n completion_criteria: [\n \"All orchestrator files scanned for adapter.send / adapter.followUp\",\n \"No runTask usage found (runWorkflow must be used instead)\",\n \"Registry usage verified\",\n \"Exit code 11/12 patterns checked\",\n \"cli-contracts handler integration verified (CommandHandlers interface used, createProgram called)\"\n],\n optional: false,\n};\n\nexport const auditCliContract: TaskContract = {\n id: \"audit-cli-contract\",\n description: \"Audit the CLI contract layer of an LLM command integration.\\n\\nParse cli-contract.yaml and check each LLM command:\\n\\nERROR: missing standard options (category: cli-contract-options):\\n- --adapter, --model, --show-prompt, --fail-on, --output, --report-format\\n- Using --format instead of --report-format for LLM commands\\n\\nERROR: missing x-agent metadata (category: cli-contract-xagent):\\n- No x-agent block on LLM command\\n- Missing riskLevel, safeDryRunOption, or expectedDurationMs\\n- Using snake_case instead of camelCase for x-agent fields\\n\\nERROR: wrong exit codes (category: cli-contract-exits):\\n- Missing exit 0/1/3/10/11/12 definitions\\n- Exit 10 not defined for finding-based commands\\n\\nWARNING: missing schemas (category: cli-contract-schema):\\n- AgentAuditResult not in components/schemas\\n- AgentFinding, AgentRecommendedAction, AgentEvidence not defined\\n\\nCategory vocabulary: cli-contract-options, cli-contract-xagent,\\ncli-contract-exits, cli-contract-schema.\\n\\nOutput a partial audit-result with findings only from the CLI contract layer.\\n\",\n target_agent: \"implementation-auditor\",\n allowed_from_agents: [\n \"implementation-auditor\"\n],\n workflow: \"audit-implementation\",\n invocation_handoff: \"audit-request\",\n result_handoff: \"audit-result\",\n input_artifacts: [],\n responsibilities: [\n \"Check each LLM command for standard options\",\n \"Verify x-agent metadata fields and casing\",\n \"Validate exit code definitions\",\n \"Check components/schemas for canonical types\"\n],\n completion_criteria: [\n \"Every LLM command checked for all 6 standard options\",\n \"x-agent metadata validated on every LLM command\",\n \"Exit codes verified against convention\",\n \"Schema completeness checked\"\n],\n optional: false,\n};\n\nexport const auditArchitecture: TaskContract = {\n id: \"audit-architecture\",\n description: \"Audit the architecture and module structure of an LLM command integration.\\n\\nVerify module structure (category: architecture-modules):\\n- src/agents/types.ts exists with TaskId, AgentConfig, AgentOptions, AgentRunResult\\n- src/agents/orchestrator.ts exists\\n- src/agents/context-builder.ts exists\\n- src/agents/formatter.ts exists with computeExitCode\\n\\nVerify behavior (category: architecture-dry-run):\\n- --show-prompt path returns the constructed prompt without calling the adapter\\n- buildTaskPrompt is used (not a placeholder string)\\n\\nCRITICAL: context-builder SSoT violations (category: architecture-context-builder):\\n\\nThe context-builder's role is to assemble domain-specific DATA (file\\ncontents, configuration, scan results, schema context) into the user\\nprompt. Agent INSTRUCTIONS (how to evaluate, what rules to apply,\\nwhat patterns to look for, output format) belong in the DSL agent\\ndefinition and are injected by buildTaskPrompt / runWorkflow.\\n\\nDetect any of the following in context-builder source code:\\n- Sections titled \\\"## Instructions\\\", \\\"## Required Patterns\\\",\\n \\\"## Audit Instructions\\\", \\\"## Output Format\\\", or similar\\n behavioral directive headings — these are agent instructions\\n that belong in DSL (agent purpose, responsibilities, constraints,\\n rules) and must not be hardcoded in context-builder\\n- Output format specifications (field lists, JSON/YAML schema\\n descriptions, example output structures) — buildTaskPrompt\\n already generates \\\"Required Output Format\\\" from the handoff\\n Zod schema; duplicating this in context-builder causes conflicts\\n- Domain-specific evaluation criteria, checklists, anti-pattern\\n definitions, rule sets, or API reference material — these\\n belong in the DSL agent definition's purpose field\\n- Any string that duplicates or paraphrases content already\\n present in the DSL agent's purpose, responsibilities,\\n constraints, or rules fields\\n\\nWhat IS allowed in context-builder:\\n- File contents read from disk (migration SQL, schema, config)\\n- Project metadata (dialect, directories, file lists)\\n- Deterministic pre-analysis results (lint violations, scan output)\\n- Operational context (target path, cwd, timestamp)\\n- Brief task framing (\\\"# Migration Safety Audit Request\\\")\\n\\nERROR: mode-purpose coherence (category: architecture-agent-coherence):\\n- DSL agent with mode: read-only has purpose or responsibilities\\n that describe file writing, editing, creation, or modification\\n- DSL agent with mode: read-write but no cwd propagated to adapter\\n — the agent's file tools won't operate in the project directory\\n- Command handler doesn't pass cwd to AgentConfig when using an\\n agentic adapter (claude)\\n\\nERROR: adapter cwd propagation (category: architecture-adapter-cwd):\\n- AgentConfig type has no cwd field\\n- Command handlers don't set config.cwd = process.cwd() or\\n resolve(projectDir)\\n- createAdapter doesn't pass cwd to adapter constructor/factory\\n- Agentic adapters (claude) instantiated without cwd —\\n their file tools will operate in an undefined directory\\n\\nCRITICAL: runTask usage (category: architecture-handler):\\n- runTask() imported or called anywhere in the consumer project —\\n consumer projects must use runWorkflow() exclusively; runTask()\\n is a low-level internal API that bypasses workflow DAG\\n orchestration, workflow-level plugin hooks, and gate steps\\n\\nERROR: cli-contracts handler wiring (category: architecture-handler):\\n- Project has cli-contracts generated code (src/generated/program.ts\\n or src/generated/cli/program.ts with CommandHandlers) but CLI\\n entry point manually creates Commander commands instead of\\n calling createProgram(handlers, version)\\n- Command handlers bypass the generated CommandHandlers interface\\n\\nScan for direct SDK imports (category: architecture-modules):\\n- @anthropic-ai/sdk or @anthropic-ai/claude-agent-sdk imported\\n outside src/agents/orchestrator.ts or adapter files\\n- openai or @openai/agents imported outside adapters\\n- @google/genai imported outside adapters\\n\\nCategory vocabulary: architecture-modules, architecture-dry-run,\\narchitecture-context-builder, architecture-agent-coherence,\\narchitecture-adapter-cwd, architecture-handler,\\narchitecture-formatter.\\n\\nOutput a partial audit-result with findings only from the architecture layer.\\n\",\n target_agent: \"implementation-auditor\",\n allowed_from_agents: [\n \"implementation-auditor\"\n],\n workflow: \"audit-implementation\",\n invocation_handoff: \"audit-request\",\n result_handoff: \"audit-result\",\n input_artifacts: [],\n responsibilities: [\n \"Verify module structure\",\n \"Check dry-run behavior\",\n \"Audit context-builder for SSoT violations (hardcoded instructions, output format specs, domain rules that belong in DSL)\",\n \"Check mode-purpose coherence across DSL definitions and runtime code\",\n \"Verify cwd propagation from command handler through adapter config\",\n \"Verify cli-contracts handler wiring (CommandHandlers + createProgram)\",\n \"Scan for direct SDK imports\"\n],\n completion_criteria: [\n \"Module structure verified\",\n \"Dry-run behavior confirmed\",\n \"Context-builder contains only domain data, not agent instructions\",\n \"Agent mode is consistent with purpose and tool usage\",\n \"cwd is propagated to agentic adapters\",\n \"cli-contracts handler integration verified\",\n \"No direct SDK imports outside adapter files\"\n],\n optional: false,\n};\n\nexport const auditMerge: TaskContract = {\n id: \"audit-merge\",\n description: \"Merge the partial audit results from the four parallel layer audits\\n(DSL, runtime, CLI contract, architecture) into a single unified\\naudit-result.\\n\\nThe prior_context contains the JSON output from each completed\\naudit step. Parse each one, combine all findings into a single\\narray, deduplicate by (target + message), assign sequential IDs\\n(F-001, F-002, ...), derive the overall riskLevel from the worst\\nfinding severity, and produce prioritized recommendedActions.\\n\\nMerging rules:\\n- Collect all findings from all layer results\\n- Sort: critical first, then error, warning, info\\n- Assign sequential IDs: F-001, F-002, ...\\n- Deduplicate: if two findings have the same target and message, keep one\\n- Derive riskLevel: any critical → critical, any error → high,\\n any warning → medium, info only → low\\n- Merge recommendedActions from all layers, deduplicate by title\\n- Set metadata: { tool: \\\"agent-runtime\\\", command: \\\"audit-implementation\\\" }\\n\",\n target_agent: \"implementation-auditor\",\n allowed_from_agents: [\n \"implementation-auditor\"\n],\n workflow: \"audit-implementation\",\n invocation_handoff: \"audit-request\",\n result_handoff: \"audit-result\",\n input_artifacts: [],\n responsibilities: [\n \"Parse prior_context JSON from each layer audit step\",\n \"Merge and deduplicate findings\",\n \"Derive overall riskLevel\",\n \"Produce a single coherent summary paragraph\"\n],\n completion_criteria: [\n \"All findings from all layers included\",\n \"No duplicate findings\",\n \"riskLevel correctly derived from worst finding\",\n \"Summary paragraph covers all audited layers\"\n],\n optional: false,\n};\n\nexport const taskRegistry: Record<string, TaskContract> = {\n \"implement-llm-feature\": implementLlmFeature,\n \"audit-dsl\": auditDsl,\n \"audit-runtime\": auditRuntime,\n \"audit-cli-contract\": auditCliContract,\n \"audit-architecture\": auditArchitecture,\n \"audit-merge\": auditMerge,\n};\n","/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\nimport { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// implement-request\n// ---------------------------------------------------------------------------\n\nexport const ImplementRequestSchema = z.object({\n description: z.string(),\n project_dir: z.string(),\n reference_doc: z.string().optional(),\n});\n\nexport type ImplementRequest = z.infer<typeof ImplementRequestSchema>;\n\n// ---------------------------------------------------------------------------\n// audit-request\n// ---------------------------------------------------------------------------\n\nexport const AuditRequestSchema = z.object({\n project_dir: z.string(),\n focus: z.enum([\"all\", \"dsl\", \"runtime\", \"cli-contract\", \"architecture\"]).optional(),\n});\n\nexport type AuditRequest = z.infer<typeof AuditRequestSchema>;\n\n// ---------------------------------------------------------------------------\n// audit-result\n// ---------------------------------------------------------------------------\n\nexport const AuditResultSchema = z.object({\n summary: z.string(),\n riskLevel: z.enum([\"low\", \"medium\", \"high\", \"critical\"]),\n findings: z.array(z.object({\n id: z.string().optional(),\n severity: z.enum([\"info\", \"warning\", \"error\", \"critical\"]),\n category: z.string(),\n target: z.string().optional(),\n location: z.string().optional(),\n message: z.string(),\n recommendation: z.string().optional(),\n confidence: z.number().min(0).max(1).optional(),\n})),\n recommendedActions: z.array(z.object({\n kind: z.enum([\"run_command\", \"edit_file\", \"review\", \"confirm\", \"block\", \"ignore\"]),\n title: z.string(),\n command: z.string().optional(),\n target: z.string().optional(),\n rationale: z.string().optional(),\n})).optional(),\n metadata: z.object({\n tool: z.string().optional(),\n command: z.string().optional(),\n version: z.string().optional(),\n generatedAt: z.string().optional(),\n adapter: z.string().optional(),\n model: z.string().optional(),\n}).optional(),\n});\n\nexport type AuditResult = z.infer<typeof AuditResultSchema>;\n\n// ---------------------------------------------------------------------------\n// implementation-result\n// ---------------------------------------------------------------------------\n\nexport const ImplementationResultSchema = z.object({\n files_created: z.array(z.string()),\n files_modified: z.array(z.string()),\n summary: z.string(),\n commands_added: z.array(z.object({\n name: z.string(),\n type: z.enum([\"audit\", \"propose\", \"explain\"]),\n description: z.string().optional(),\n})).optional(),\n next_steps: z.array(z.string()).optional(),\n});\n\nexport type ImplementationResult = z.infer<typeof ImplementationResultSchema>;\n\n// ---------------------------------------------------------------------------\n// Schema registry\n// ---------------------------------------------------------------------------\n\nexport const handoffSchemas = {\n \"implement-request\": ImplementRequestSchema,\n \"audit-request\": AuditRequestSchema,\n \"audit-result\": AuditResultSchema,\n \"implementation-result\": ImplementationResultSchema,\n} as const;\n\nexport type HandoffTypeId = keyof typeof handoffSchemas;\n\n// ---------------------------------------------------------------------------\n// Handoff envelope\n// ---------------------------------------------------------------------------\n\nexport interface HandoffEnvelope<T extends HandoffTypeId = HandoffTypeId> {\n readonly type: T;\n readonly version: number;\n readonly payload: z.infer<(typeof handoffSchemas)[T]>;\n}\n\n// ---------------------------------------------------------------------------\n// Factory functions — type-safe constructors with runtime validation\n// ---------------------------------------------------------------------------\n\nexport const handoffs = {\n implementRequest(payload: ImplementRequest): HandoffEnvelope<\"implement-request\"> {\n return {\n type: \"implement-request\" as const,\n version: 1,\n payload: ImplementRequestSchema.parse(payload),\n };\n },\n auditRequest(payload: AuditRequest): HandoffEnvelope<\"audit-request\"> {\n return {\n type: \"audit-request\" as const,\n version: 1,\n payload: AuditRequestSchema.parse(payload),\n };\n },\n auditResult(payload: AuditResult): HandoffEnvelope<\"audit-result\"> {\n return {\n type: \"audit-result\" as const,\n version: 1,\n payload: AuditResultSchema.parse(payload),\n };\n },\n implementationResult(payload: ImplementationResult): HandoffEnvelope<\"implementation-result\"> {\n return {\n type: \"implementation-result\" as const,\n version: 1,\n payload: ImplementationResultSchema.parse(payload),\n };\n },\n} as const;\n","/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\nexport interface DelegateStep {\n readonly type: \"delegate\";\n readonly task: string;\n readonly from_agent: string;\n readonly description: string;\n readonly optional: boolean;\n readonly max_retries: number;\n readonly depends_on?: readonly string[];\n}\n\nexport interface GateStep {\n readonly type: \"gate\";\n readonly gate_kind: string;\n readonly description: string;\n readonly depends_on?: readonly string[];\n}\n\nexport type WorkflowStep = DelegateStep | GateStep;\n\nexport interface WorkflowContract {\n readonly id: string;\n readonly description: string;\n readonly trigger: string;\n readonly entry_conditions: readonly string[];\n readonly steps: readonly WorkflowStep[];\n}\n\nexport const implementLlmFeature: WorkflowContract = {\n id: \"implement-llm-feature\",\n description: \"Implement LLM-powered commands in a CLI tool\",\n trigger: \"cli-command\",\n entry_conditions: [\n \"Target project is a TypeScript / Node.js project\",\n \"cli-contract.yaml exists or is being created\"\n],\n steps: [\n {\n type: \"delegate\",\n task: \"implement-llm-feature\",\n from_agent: \"llm-feature-implementer\",\n description: \"\",\n optional: false,\n max_retries: 0,\n },\n ],\n};\n\nexport const auditImplementation: WorkflowContract = {\n id: \"audit-implementation\",\n description: \"Audit an LLM command integration for pattern conformance\",\n trigger: \"cli-command\",\n entry_conditions: [\n \"Target project has LLM command integration to audit\"\n],\n steps: [\n {\n type: \"delegate\",\n task: \"audit-dsl\",\n from_agent: \"implementation-auditor\",\n description: \"\",\n optional: false,\n max_retries: 0,\n depends_on: [],\n },\n {\n type: \"delegate\",\n task: \"audit-runtime\",\n from_agent: \"implementation-auditor\",\n description: \"\",\n optional: false,\n max_retries: 0,\n depends_on: [],\n },\n {\n type: \"delegate\",\n task: \"audit-cli-contract\",\n from_agent: \"implementation-auditor\",\n description: \"\",\n optional: false,\n max_retries: 0,\n depends_on: [],\n },\n {\n type: \"delegate\",\n task: \"audit-architecture\",\n from_agent: \"implementation-auditor\",\n description: \"\",\n optional: false,\n max_retries: 0,\n depends_on: [],\n },\n {\n type: \"delegate\",\n task: \"audit-merge\",\n from_agent: \"implementation-auditor\",\n description: \"\",\n optional: false,\n max_retries: 0,\n depends_on: [\n \"audit-dsl\",\n \"audit-runtime\",\n \"audit-cli-contract\",\n \"audit-architecture\"\n],\n },\n ],\n};\n\nexport const workflowRegistry: Record<string, WorkflowContract> = {\n \"implement-llm-feature\": implementLlmFeature,\n \"audit-implementation\": auditImplementation,\n};\n","/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\nexport const resolvedDsl: Record<string, unknown> = {\n \"version\": 1,\n \"system\": {\n \"id\": \"agent-runtime-builtin\",\n \"name\": \"agent-runtime Built-in Agents\",\n \"default_workflow_order\": [\n \"implement-llm-feature\",\n \"audit-implementation\"\n ]\n },\n \"agents\": {\n \"implementation-auditor\": {\n \"role_name\": \"Implementation Auditor\",\n \"purpose\": \"Audits an existing LLM command integration to verify it correctly\\nfollows the agent-contracts + agent-contracts-runtime + cli-contracts\\nstack conventions. Detects architectural violations, missing patterns,\\nincorrect API usage, and deviations from the canonical\\nintegrate-llm-commands pattern.\\n\\nThis agent is read-only — it analyzes code but does not modify it.\\nIt produces structured findings (AgentAuditResult) that identify\\nexactly what is wrong and how to fix it.\\n\\n## What This Agent Checks\\n\\n### Layer 1: agent-contracts DSL\\n- DSL entry has version:1 and system block with id/name\\n- Agents defined with all required fields (role_name, purpose, mode,\\n can_read_artifacts, can_write_artifacts, responsibilities, constraints)\\n- Tasks have target_agent, workflow, result_handoff, completion_criteria\\n- Handoff type schemas conform to AgentAuditResult base shape\\n- Workflows define steps with correct task/agent cross-references\\n- Guardrails and guardrail_policies are defined\\n- agent-runtime.config.yaml exists with dsl and generated_dir\\n\\n### Layer 2: agent-contracts-runtime Integration\\n- orchestrator.ts uses runWorkflow(), NOT runTask() or adapter.send()\\n- runTask() is a low-level internal API — consumer projects must\\n use runWorkflow() which handles workflow DAG, plugin hooks, gates\\n- Adapters imported from agent-contracts-runtime/adapters/*, not custom\\n- Dynamic import pattern for graceful degradation (exit 11/12)\\n- Generated registries imported from src/generated/dsl/index.js\\n- Registries (including workflowRegistry) passed to runWorkflow\\n- Plugin hooks not bypassed\\n- No hand-rolled prompt building (use buildTaskPrompt or let runWorkflow do it)\\n\\n### Layer 3: cli-contracts Compliance\\n- cli-contract.yaml has LLM commands with all standard options:\\n --adapter, --model, --show-prompt, --fail-on, --output, --report-format\\n- x-agent metadata present (riskLevel, safeDryRunOption, expectedDurationMs)\\n- Exit codes follow convention (0, 1, 3, 10, 11, 12)\\n- components/schemas includes AgentAuditResult and related types\\n- --report-format used (not --format) for LLM commands\\n\\n### Architecture & Patterns\\n- src/agents/ module structure (orchestrator, context-builder, formatter, types)\\n- Context builder caps input at 16KB\\n- Formatter implements computeExitCode with correct threshold logic\\n- --show-prompt returns prompt without LLM call\\n- No direct LLM API calls anywhere in the codebase\\n\\n### Semantic Design Coherence\\n- Context-builder must contain only domain DATA (file contents,\\n config, scan results) — never agent INSTRUCTIONS (evaluation\\n criteria, rules, anti-patterns, output format specifications).\\n These belong in the DSL agent definition and are injected by\\n buildTaskPrompt / runWorkflow. Hardcoding instructions in\\n context-builder defeats the purpose of using DSL.\\n- Agent mode must match purpose: read-only agents must not have\\n write-oriented purposes, read-write agents must propagate cwd\\n to their adapter so file tools operate in the project directory.\\n- CLI must use cli-contracts' generated CommandHandlers interface\\n and createProgram() — not manually wired Commander commands.\\n\",\n \"mode\": \"read-only\",\n \"can_read_artifacts\": [],\n \"can_write_artifacts\": [],\n \"can_invoke_agents\": [],\n \"can_execute_tools\": [],\n \"can_return_handoffs\": [\n \"audit-result\"\n ],\n \"responsibilities\": [\n \"Verify the DSL directory structure exists: dsl/{project}-dsl.yaml, dsl/agents/*.yaml, dsl/tasks.yaml, dsl/handoff-types.yaml, dsl/agent-runtime.config.yaml.\",\n \"Check that the main DSL entry has version:1, a system block with id and name, and uses $ref for agents/tasks/handoff_types.\",\n \"Validate agent definitions have all required fields: role_name, purpose, mode, can_read_artifacts:[], can_write_artifacts:[], responsibilities, constraints. Check that rules use R-PREFIX-NNN format and severity is mandatory|recommended|optional.\",\n \"Validate task definitions: target_agent matches a defined agent, workflow matches a defined workflow, result_handoff matches a defined handoff type, completion_criteria are specific and testable.\",\n \"Verify handoff type schemas conform to AgentAuditResult shape when applicable (summary, riskLevel, findings[], recommendedActions[], metadata). Check $ref usage and SSoT comments for inlined schemas.\",\n \"Check that guardrails and guardrail_policies are defined, and that output-schema-conformance is included.\",\n \"Scan src/agents/orchestrator.ts for: (1) imports from agent-contracts-runtime (not custom SDK wrappers), (2) usage of runWorkflow() — NOT runTask() which is a low-level internal API that bypasses workflow orchestration, plugin hooks, and gate steps, (3) dynamic import pattern with exit code 11 for missing runtime and exit code 12 for adapter errors, (4) generated registries (including workflowRegistry) imported and passed to runWorkflow.\",\n \"Verify no file in the project calls adapter.send(), adapter.followUp(), adapter.sendExecution(), or runTask() directly — all LLM invocations must go through runWorkflow().\",\n \"Check that src/generated/dsl/ exists and contains the expected files (agents.ts, tasks.ts, workflows.ts, handoffs.ts, index.ts). Verify the .manifest.json exists and is not stale.\",\n \"Verify adapter creation uses the correct constructors: ClaudeAgentSdkAdapter constructor, OpenAIAgentsSdkAdapter constructor, etc.\",\n \"Check cli-contract.yaml for each LLM command: all six standard options present (--adapter, --model, --show-prompt, --fail-on, --output, --report-format). Verify --report-format is used (not --format).\",\n \"Verify x-agent metadata on each LLM command: riskLevel, safeDryRunOption (must be \\\"show-prompt\\\"), expectedDurationMs. Flag high-risk commands without requiresConfirmation.\",\n \"Check exit code definitions: 0 (success), 1 (error), 3 (validation), 10 (findings), 11 (runtime missing), 12 (adapter error).\",\n \"Verify components/schemas includes AgentAuditResult, AgentFinding, AgentRecommendedAction, and AgentEvidence definitions.\",\n \"Verify src/agents/ directory structure: types.ts (TaskId, AgentConfig, AgentOptions, AgentRunResult), orchestrator.ts (createAdapter, runAgentTask with dynamic imports), context-builder.ts (build*Context functions with 16KB cap), formatter.ts (computeExitCode, formatResultText, formatResultJson).\",\n \"Check that --show-prompt mode returns the constructed prompt without making any LLM API call.\",\n \"Scan for direct LLM API imports (@anthropic-ai/sdk, openai, @google/genai) used outside of adapter files — application code must not import these directly.\",\n \"Audit context-builder for SSoT violations: scan for hardcoded agent instructions (sections titled \\\"## Instructions\\\", \\\"## Required Patterns\\\", \\\"## Output Format\\\", evaluation criteria, checklists, anti-pattern definitions, API references, or output schema descriptions). These belong in the DSL agent definition and are injected by buildTaskPrompt. Context-builder should contain only domain-specific data (file contents, configuration, scan results, project metadata).\",\n \"Check agent mode-purpose coherence: for each agent in the DSL, verify that mode: read-only agents do not have purposes or responsibilities describing file writing/editing/creation, and that mode: read-write agents propagate cwd through AgentConfig to the adapter so file tools operate in the correct directory.\",\n \"Verify cwd propagation: command handlers must set cwd in AgentConfig (e.g. process.cwd() or resolve(projectDir)), createAdapter must pass cwd to adapter constructors/factories, and AgentConfig type must include a cwd field.\",\n \"Verify cli-contracts handler wiring: if the project uses cli-contracts (has src/generated/program.ts or src/generated/cli/program.ts exporting CommandHandlers and createProgram), the CLI entry point must use createProgram(handlers, version) with a handlers object implementing the CommandHandlers interface — not manually created Commander commands.\"\n ],\n \"constraints\": [\n \"This agent is read-only. It must not create, modify, or delete any files. Output is a structured audit report only.\",\n \"Findings must include specific file paths, line references where possible, and concrete remediation steps.\",\n \"Severity classification: critical = breaks the integration pattern (direct API calls, missing runtime usage), error = missing required element (no x-agent, missing standard option), warning = deviation from best practice (context not capped, missing guardrail), info = improvement suggestion.\",\n \"Category vocabulary: dsl-structure, dsl-agent, dsl-task, dsl-handoff, dsl-workflow, dsl-guardrail, runtime-adapter, runtime-orchestrator, runtime-registry, runtime-handler, runtime-plugin, cli-contract-options, cli-contract-xagent, cli-contract-exits, cli-contract-schema, architecture-modules, architecture-dry-run, architecture-context-builder, architecture-agent-coherence, architecture-adapter-cwd, architecture-handler, architecture-formatter.\",\n \"Every finding with severity warning or above must include a recommendation field with a concrete fix.\",\n \"The confidence field should reflect how certain the finding is: 1.0 for pattern matches (e.g., adapter.send() found in code), 0.8+ for structural checks (e.g., missing file), 0.5-0.8 for heuristic assessments (e.g., context might exceed 16KB).\"\n ],\n \"rules\": [\n {\n \"id\": \"R-AUDIT-001\",\n \"description\": \"Every finding must specify target (file path) and category (from the defined category vocabulary). Findings without a target are not actionable.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-002\",\n \"description\": \"The audit must check all four layers (DSL, runtime, CLI contract, architecture). Skipping a layer or returning partial results is not acceptable.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-003\",\n \"description\": \"Critical findings must be surfaced for: (1) direct adapter.send() calls bypassing runWorkflow, (2) runTask() used instead of runWorkflow() — runTask is a low-level internal API that bypasses workflow orchestration, (3) custom adapter classes not from agent-contracts-runtime, (4) missing generated registries in runWorkflow calls.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-004\",\n \"description\": \"The riskLevel in the audit result must be derived from the most severe finding: any critical → critical, any error → high, any warning → medium, info only → low.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-005\",\n \"description\": \"Context-builder must be audited for SSoT violations. Any hardcoded agent instructions (evaluation criteria, rules, anti-patterns, output format specs) in context-builder is a critical finding — these belong in the DSL agent definition and are injected by buildTaskPrompt / runWorkflow. Context-builder may only contain domain-specific data (file contents, configuration, scan results, project metadata).\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-007\",\n \"description\": \"runTask() usage in consumer projects is a CRITICAL finding. Consumer projects integrating with cli-contracts must use runWorkflow() exclusively. runTask() is a low-level internal API that bypasses workflow DAG orchestration, workflow-level plugin hooks (beforeWorkflow/afterWorkflow), gate steps, and step dependencies. Any occurrence of runTask import or call in orchestrator, command handler, or CLI entry point code must be reported as severity: critical.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-006\",\n \"description\": \"Agent mode-purpose coherence must be verified. A read-only agent whose purpose describes file writing is a critical finding because the adapter's tool set (Read/Glob/Grep only) makes the stated purpose impossible to fulfil.\",\n \"severity\": \"mandatory\"\n }\n ],\n \"escalation_criteria\": [\n {\n \"condition\": \"Target project has no LLM command integration to audit\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project uses a completely different integration pattern (not agent-contracts stack)\",\n \"action\": \"stop_and_report\"\n }\n ]\n },\n \"llm-feature-implementer\": {\n \"role_name\": \"LLM Feature Implementer\",\n \"purpose\": \"Expert implementation agent for the agent-contracts toolchain.\\nAdds LLM-powered commands (audit, propose, explain, etc.) to CLI tools\\nusing the three-layer stack:\\n\\n1. **agent-contracts** — DSL package. Defines agents, tasks, workflows,\\n handoff types, guardrails, and guardrail policies in YAML. The\\n `resolve()` function handles `$ref`, `extends`, and merge operators.\\n Installed as a devDependency. CLI: `agent-contracts audit`.\\n\\n2. **agent-contracts-runtime** — Runtime bridge. Generates typed\\n TypeScript contracts from DSL via Handlebars templates, then\\n executes workflows through pluggable SDK adapters. Provides\\n `runTask()`, `runWorkflow()`, `createRuntime()`, plugin system,\\n and guardrail hooks. CLI: `agent-runtime generate|run|list|doctor`.\\n\\n3. **cli-contracts** — CLI contract package. Defines command-line\\n interfaces in YAML (`cli-contract.yaml`): command sets, arguments,\\n options, exit codes, stdout/stderr schemas, `x-agent` metadata,\\n and `effects`. Generates typed Commander programs, Zod validators,\\n and markdown docs. CLI: `cli-contracts init|generate|validate`.\\n\\nThe canonical integration pattern (\\\"integrate-llm-commands\\\") produces:\\n- DSL definitions under `dsl/` (agents, tasks, workflows, handoff-types)\\n- Pre-generated TypeScript contracts under `src/generated/dsl/`\\n- Runtime integration module under `src/agents/` (orchestrator,\\n context-builder, formatter, types)\\n- CLI command handlers under `src/commands/`\\n- Updated `cli-contract.yaml` with new commands and `x-agent` metadata\\n\",\n \"mode\": \"read-write\",\n \"can_read_artifacts\": [],\n \"can_write_artifacts\": [],\n \"can_invoke_agents\": [],\n \"can_execute_tools\": [],\n \"can_return_handoffs\": [\n \"implementation-result\"\n ],\n \"responsibilities\": [\n \"Read and analyze the target project's cli-contract.yaml, package.json, tsconfig.json, and existing source code to understand the CLI structure, existing commands, component schemas, and TypeScript configuration.\",\n \"Identify which LLM commands to add based on the user's description. Canonical command types: audit (semantic review), propose (structured proposal generation), explain (human-readable explanation of machine output).\",\n \"Create the DSL directory structure: dsl/{project}-dsl.yaml (main entry with version:1, system block, $ref to sub-files), dsl/agents/{name}.yaml, dsl/tasks.yaml, dsl/handoff-types.yaml, dsl/agent-runtime.config.yaml.\",\n \"Define agents with: role_name, purpose (domain expertise), mode (read-only for analysis agents), can_read_artifacts:[], can_write_artifacts:[], can_return_handoffs, responsibilities, constraints, rules (R-PREFIX-NNN format), escalation_criteria.\",\n \"Define tasks with: description, target_agent, allowed_from_agents, workflow (must match a workflow ID), invocation_handoff, result_handoff, responsibilities, completion_criteria.\",\n \"Define handoff types with: version:1, description, schema (JSON Schema). Result types should conform to AgentAuditResult shape (summary, riskLevel, findings[], recommendedActions[], metadata). Use $ref to cli-contract.yaml components/schemas as SSoT when possible; inline with SSoT comment as fallback.\",\n \"Define workflows with trigger, entry_conditions, and steps (delegate or gate). Each delegate step references a task and from_agent. Gate steps pause for user approval.\",\n \"Define guardrails (output-schema-conformance, domain-specific safety) and guardrail_policies grouping them with severity and action.\",\n \"Create agent-runtime.config.yaml: dsl points to main DSL file, generated_dir points to src/generated/dsl.\",\n \"Implement src/agents/types.ts: TaskId union type, AgentConfig interface (adapter, model, temperature), AgentOptions interface (dryRun, failOn), AgentRunResult interface (taskId, data, raw, prompt, dryRun, status, errorMessage, followUpsUsed, retriesUsed).\",\n \"Implement src/agents/orchestrator.ts: createAdapter() with dynamic imports from agent-contracts-runtime/adapters/*, runAgentWorkflow() that imports runWorkflow from agent-contracts-runtime, loads generated registries (including workflowRegistry) from src/generated/dsl/index.js, and calls runWorkflow with registries. NEVER use runTask — it is a low-level internal API that bypasses workflow orchestration.\",\n \"Implement src/agents/context-builder.ts: build{Command}Context() functions that transform CLI inputs into structured markdown prompts. Cap context at 16KB. Structure: # Request, ## Configuration, ## Target, ## Instructions.\",\n \"Implement src/agents/formatter.ts: computeExitCode() mapping findings to exit codes via --fail-on threshold, formatResultText() with severity icons, formatResultJson() for structured output.\",\n \"Create src/commands/{command}.ts handlers: load config, call context builder, call runAgentWorkflow, format output, compute exit code.\",\n \"Update cli-contract.yaml: add command definitions with standard LLM options (--adapter, --model, --show-prompt, --fail-on, --output, --report-format), exit codes (0, 1, 3, 10, 11, 12), x-agent metadata, and register AgentAuditResult/AgentFinding/AgentRecommendedAction in components/schemas.\",\n \"Add npm scripts: \\\"dsl:generate\\\" running agent-runtime generate --config dsl/agent-runtime.config.yaml. Add agent-contracts and agent-contracts-runtime as devDependencies. Add SDK packages as optional peerDependencies.\"\n ],\n \"constraints\": [\n \"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk, GeminiSdkAdapter from agent-contracts-runtime/adapters/gemini-sdk, MockAdapter from agent-contracts-runtime/adapters/mock.\",\n \"NEVER call adapter.send() or adapter.sendExecution() directly. All LLM invocations must go through runWorkflow() imported from agent-contracts-runtime. NEVER use runTask() — it is a low-level internal API. runWorkflow() handles prompt building, handoff validation, retry/followUp, workflow DAG, and plugin hooks.\",\n \"Dynamic-import both agent-contracts-runtime and adapter packages. The tool must work without them installed (graceful degradation). Pattern: const RUNTIME = \\\"agent-contracts-runtime\\\"; try { const { runWorkflow } = await import(RUNTIME); } catch { exit(11); }\",\n \"LLM commands use --report-format (json|text|yaml) for output format. --format is reserved for deterministic commands. Never mix them.\",\n \"Exit code convention: 0=success (no findings above threshold), 1=general error, 3=input validation/parse failed, 10=findings detected above --fail-on threshold, 11=agent-contracts-runtime not installed, 12=adapter initialization error (missing API key, etc.).\",\n \"Standard LLM command options (all must be present): --adapter <name> (mock|claude|openai|gemini, default varies), --model <name> (optional override), --show-prompt (output prompt without LLM call), --fail-on <level> (warning|error|critical, default error), --output/-o <file> (write to file instead of stdout), --report-format <fmt> (json|text|yaml, default json).\",\n \"Result handoff schemas must extend the AgentAuditResult base shape: summary (string, required), riskLevel (enum: low|medium|high|critical, required), findings (AgentFinding[], required), recommendedActions (AgentRecommendedAction[], optional), metadata (object with tool, command, version, generatedAt, adapter, model fields, optional).\",\n \"AgentFinding shape: id?, severity (info|warning|error|critical), category (domain vocabulary), target?, location?, message (required), recommendation?, confidence? (0-1), evidence? (array of {type,content,source}), details? (object).\",\n \"AgentRecommendedAction shape: kind (run_command|edit_file|review|confirm| block|ignore), title (required), command?, target?, rationale?.\",\n \"Main DSL entry must have version:1 and a system block with id and name. Without these, the generator produces numbered files instead of named ones.\",\n \"Every task must have a workflow field matching a defined workflow ID. Every workflow step's from_agent must match a defined agent ID. can_read_artifacts and can_write_artifacts must be empty arrays ([]) when no artifact registry is defined.\",\n \"agent-runtime.config.yaml format: dsl: ./{project}-dsl.yaml generated_dir: ../src/generated/dsl Optional: plugins (array of paths), recovery ({max_follow_ups, max_retries}).\",\n \"runWorkflow (the ONLY API consumer projects should use): Overloads: (1) runWorkflow(adapter, workflowId, options, registries?) — legacy. (2) runWorkflow(adapter, invocation, registries?) — structured (preferred). WorkflowInvocation: { workflow, handoff?, user_request?, runtime? {maxFollowUps,maxRetries,timeoutMs,readonly, dryRun}, hooks? {onStepComplete,onGate,onOptionalStep}, context? {cwd,environment,artifacts,variables} }. WorkflowResult: { workflow_id, status (completed|escalated|gate_rejected|error), steps[], total_elapsed_ms, escalation_reason?, error_message? }. NEVER use runTask() — it is a low-level internal API.\",\n \"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?}), GeminiSdkAdapter({apiKey?, model?, systemInstruction?, temperature?, maxOutputTokens?, guardrailHooks?}).\",\n \"Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from \\\"../generated/dsl/index.js\\\". Pass these as registries to runWorkflow: { workflowRegistry, taskRegistry, agentRegistry, handoffSchemas }.\",\n \"Plugin interface (AgentPlugin): id (string), beforeTask?(taskId, context), afterTask?(taskId, outcome), contextEnhancer?(taskId, context), promptEnhancer?(taskId, prompt, context), promptBuilder?(args), customGuardrails?, beforeWorkflow?(workflowId, userRequest), afterWorkflow?(workflowId, result).\",\n \"x-agent fields for LLM commands in cli-contract.yaml: riskLevel (low for read-only analysis), requiresConfirmation (false for read-only), idempotent (true for analysis), sideEffects ([network]), sideEffectNote (describe network call and optional file write), safeDryRunOption (show-prompt), expectedDurationMs (120000 typical), retryableExitCodes ([1, 12]).\"\n ],\n \"rules\": [\n {\n \"id\": \"R-IMPL-001\",\n \"description\": \"Import SDK adapters exclusively from agent-contracts-runtime/adapters/*. Never create adapter classes, wrapper functions, or API client code.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-002\",\n \"description\": \"All LLM invocations must use runWorkflow() from agent-contracts-runtime. NEVER use runTask() — it is a low-level internal API that bypasses workflow orchestration. Never call adapter.send(), adapter.followUp(), or adapter.sendExecution() directly. The runtime handles prompt building, schema validation, retry, followUp, workflow DAG, and plugin hooks.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-003\",\n \"description\": \"Every LLM command in cli-contract.yaml must have x-agent metadata with at minimum: riskLevel, safeDryRunOption, expectedDurationMs.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-004\",\n \"description\": \"Handoff type schemas must use $ref to cli-contract.yaml components/schemas as SSoT. If $ref resolution fails at generate time, inline the schema and add a YAML comment noting the SSoT path.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-005\",\n \"description\": \"Context builder must cap prompt input at 16KB. Filter large contexts (schema dumps, lint output, etc.) to relevant portions before inclusion.\",\n \"severity\": \"recommended\"\n },\n {\n \"id\": \"R-IMPL-006\",\n \"description\": \"The orchestrator must dynamic-import agent-contracts-runtime as a single string variable (const PKG = \\\"agent-contracts-runtime\\\") to enable graceful degradation. Exit with code 11 when the import fails, code 12 when the adapter fails to initialize.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-007\",\n \"description\": \"Generated DSL contracts must be imported from src/generated/dsl/index.js and passed as registries to runWorkflow. Never hard-code agent definitions, task definitions, or handoff schemas in application code.\",\n \"severity\": \"mandatory\"\n }\n ],\n \"escalation_criteria\": [\n {\n \"condition\": \"Target project has no cli-contract.yaml and user did not request creating one\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project is not a TypeScript / Node.js stack\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project already has src/agents/ with a different integration pattern\",\n \"action\": \"stop_and_report\"\n }\n ]\n }\n },\n \"tasks\": {\n \"implement-llm-feature\": {\n \"description\": \"Implement LLM-powered commands in a target CLI tool using the\\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\\n\\n## Implementation Procedure\\n\\n### Step 1: Project Analysis\\n\\nRead these files from the target project:\\n- cli-contract.yaml — existing commands, components/schemas, x-agent usage\\n- package.json — dependencies, scripts, bin entries, type:\\\"module\\\" check\\n- tsconfig.json — module resolution, paths, outDir\\n- src/ directory structure — understand existing command handler pattern\\n\\nDetermine:\\n- Which LLM commands to add (audit / propose / explain)\\n- What domain-specific context each command needs\\n- What structured output schema each command returns\\n- Whether the project already has agent-contracts integration\\n\\n### Step 2: Install Dependencies\\n\\nAdd to package.json devDependencies:\\n- agent-contracts: ^0.32.0\\n- agent-contracts-runtime: ^0.31.0\\n- zod: ^4.0.0\\n\\nAdd optional peerDependencies for SDK packages:\\n- @anthropic-ai/claude-agent-sdk: >=0.2.0\\n- @openai/agents: >=0.10.0\\n- @google/genai: >=2.0.0\\n\\n### Step 3: Create DSL Definitions\\n\\nCreate directory structure:\\n\\n dsl/\\n ├── {project}-dsl.yaml\\n ├── agent-runtime.config.yaml\\n ├── agents/\\n │ └── {agent-name}.yaml\\n ├── tasks.yaml\\n └── handoff-types.yaml\\n\\n**Main DSL entry** (`dsl/{project}-dsl.yaml`):\\n\\n version: 1\\n system:\\n id: {project}\\n name: \\\"{Project} Agent System\\\"\\n default_workflow_order:\\n - {workflow-ids}\\n agents: { $ref: \\\"./agents/\\\" }\\n tasks: { $ref: \\\"./tasks.yaml\\\" }\\n handoff_types: { $ref: \\\"./handoff-types.yaml\\\" }\\n guardrails:\\n output-schema-conformance:\\n description: ...\\n scope: { agents: [...], tasks: [...] }\\n rationale: ...\\n guardrail_policies:\\n {domain}-safety-policy:\\n rules:\\n - guardrail: output-schema-conformance\\n severity: critical\\n action: block\\n workflow:\\n {workflow-id}:\\n description: ...\\n trigger: cli-command\\n entry_conditions: [...]\\n steps:\\n - type: delegate\\n task: {task-id}\\n from_agent: {agent-id}\\n\\n**Agent definition** (`dsl/agents/{agent-name}.yaml`):\\n\\n {agent-name}:\\n role_name: \\\"{Role Name}\\\"\\n purpose: >-\\n Domain-specific purpose describing what the agent knows\\n and what it can do that static rules cannot.\\n mode: read-only\\n can_read_artifacts: []\\n can_write_artifacts: []\\n can_invoke_agents: []\\n can_execute_tools: []\\n can_return_handoffs: [{result-handoff-ids}]\\n responsibilities: [...]\\n constraints: [...]\\n rules:\\n - id: \\\"R-{PREFIX}-001\\\"\\n description: ...\\n severity: mandatory\\n escalation_criteria:\\n - condition: ...\\n action: stop_and_report\\n\\n**Tasks** (`dsl/tasks.yaml`):\\n\\n {task-id}:\\n description: ...\\n target_agent: {agent-name}\\n allowed_from_agents: [{agent-name}]\\n workflow: {workflow-id}\\n input_artifacts: []\\n invocation_handoff: {request-handoff}\\n result_handoff: {result-handoff}\\n responsibilities: [...]\\n completion_criteria: [...]\\n\\n**Handoff types** (`dsl/handoff-types.yaml`):\\nUse AgentAuditResult shape as the base for result types:\\n\\n {result-handoff}:\\n version: 1\\n description: ...\\n schema:\\n type: object\\n required: [summary, riskLevel, findings]\\n properties:\\n summary: { type: string }\\n riskLevel:\\n type: string\\n enum: [low, medium, high, critical]\\n findings:\\n type: array\\n items:\\n type: object\\n required: [severity, category, message]\\n properties:\\n id: { type: string }\\n severity:\\n type: string\\n enum: [info, warning, error, critical]\\n category: { type: string }\\n target: { type: string }\\n location: { type: string }\\n message: { type: string }\\n recommendation: { type: string }\\n confidence: { type: number, minimum: 0, maximum: 1 }\\n recommendedActions:\\n type: array\\n items:\\n type: object\\n required: [kind, title]\\n properties:\\n kind:\\n type: string\\n enum: [run_command, edit_file, review, confirm, block, ignore]\\n title: { type: string }\\n command: { type: string }\\n target: { type: string }\\n rationale: { type: string }\\n metadata:\\n type: object\\n properties:\\n tool: { type: string }\\n command: { type: string }\\n version: { type: string }\\n generatedAt: { type: string }\\n adapter: { type: string }\\n model: { type: string }\\n\\nDomain-specific result types add properties alongside the base fields.\\n\\n**Runtime config** (`dsl/agent-runtime.config.yaml`):\\n\\n dsl: ./{project}-dsl.yaml\\n generated_dir: ../src/generated/dsl\\n\\n### Step 4: Generate TypeScript Contracts\\n\\nAdd to package.json scripts:\\n\\n \\\"dsl:generate\\\": \\\"agent-runtime generate --config dsl/agent-runtime.config.yaml\\\"\\n\\nRun: npm run dsl:generate\\n\\nThis produces src/generated/dsl/ containing:\\n- agents.ts (AgentContract interface + agentRegistry)\\n- tasks.ts (TaskContract interface + taskRegistry)\\n- workflows.ts (WorkflowContract + workflowRegistry)\\n- handoffs.ts (Zod schemas + handoffSchemas + factory functions)\\n- index.ts (barrel re-exports)\\n\\n### Step 5: Implement src/agents/ Module\\n\\n**src/agents/types.ts**:\\n\\n import type { {ResultType} } from \\\"../generated/dsl/handoffs.js\\\";\\n\\n export type TaskId = \\\"{task-1}\\\" | \\\"{task-2}\\\" | ...;\\n\\n export interface AgentConfig {\\n adapter?: string;\\n model?: string;\\n temperature?: number;\\n }\\n\\n export interface AgentOptions {\\n dryRun?: boolean;\\n failOn?: \\\"warning\\\" | \\\"error\\\" | \\\"critical\\\";\\n }\\n\\n export interface AgentRunResult {\\n taskId: TaskId;\\n data: {ResultType} | null;\\n raw: string;\\n prompt: string;\\n dryRun: boolean;\\n status: \\\"success\\\" | \\\"error\\\" | \\\"escalation\\\" | \\\"validation_error\\\";\\n errorMessage?: string;\\n followUpsUsed: number;\\n retriesUsed: number;\\n }\\n\\n**src/agents/orchestrator.ts**:\\n\\n export const EXIT_RUNTIME_MISSING = 11;\\n export const EXIT_ADAPTER_ERROR = 12;\\n\\n async function createAdapter(pkg: string, name: string, config: AgentConfig) {\\n switch (name) {\\n case \\\"mock\\\": {\\n const m = await import(`${pkg}/adapters/mock`);\\n return new m.MockAdapter();\\n }\\n case \\\"claude\\\": {\\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\\n }\\n case \\\"openai\\\": {\\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\\n }\\n case \\\"gemini\\\": {\\n const m = await import(`${pkg}/adapters/gemini-sdk`);\\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\\n }\\n }\\n }\\n\\n export async function runAgentWorkflow(\\n userRequest: string, workflowId: WorkflowId, config: AgentConfig, options: AgentOptions,\\n ): Promise<AgentRunResult> {\\n if (options.dryRun) return { workflowId, data:null, raw:\\\"\\\", prompt:userRequest, dryRun:true, status:\\\"success\\\" };\\n\\n const PKG = \\\"agent-contracts-runtime\\\";\\n let runWorkflow;\\n try { ({ runWorkflow } = await import(PKG)); }\\n catch { throw Object.assign(new Error(\\\"agent-contracts-runtime not installed\\\"), { exitCode: EXIT_RUNTIME_MISSING }); }\\n\\n let registries;\\n try {\\n const dsl = await import(\\\"../generated/dsl/index.js\\\");\\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas, workflowRegistry: dsl.workflowRegistry };\\n } catch { registries = {}; }\\n\\n const adapter = await createAdapter(PKG, config.adapter ?? \\\"mock\\\", config);\\n const result = await runWorkflow(adapter, { workflow: workflowId, user_request: userRequest, runtime: { maxFollowUps:3, maxRetries:1 } }, registries);\\n // map result to AgentRunResult\\n }\\n\\n**src/agents/context-builder.ts**:\\n\\nCRITICAL: context-builder builds the USER-SIDE prompt only.\\nAgent instructions (purpose, responsibilities, constraints, rules,\\nevaluation criteria, anti-patterns, output format) are defined in\\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\\nbuildTaskPrompt / runWorkflow. NEVER hardcode these in context-builder.\\n\\nContext-builder SHOULD contain:\\n- Domain-specific DATA: file contents, configuration, scan results\\n- Project metadata: target paths, dialect, directory structure\\n- Deterministic pre-analysis: lint results, schema excerpts\\n- Operational context: cwd, timestamps\\n- Brief task framing: \\\"# Migration Safety Audit Request\\\"\\n\\nContext-builder MUST NOT contain:\\n- \\\"## Instructions\\\" / \\\"## Required Patterns\\\" sections\\n- Output format specifications (handled by handoff schema)\\n- Evaluation criteria or checklists\\n- Anti-pattern definitions or rule sets\\n- API reference material\\n- Anything that duplicates DSL agent purpose/responsibilities/rules\\n\\n export function build{Command}Context(target, config): string {\\n const sections = [];\\n sections.push(\\\"# {Command} Request\\\");\\n sections.push(`## Target\\\\n\\\\n${target}`);\\n // Domain data only — no instructions here.\\n // Agent instructions come from DSL via buildTaskPrompt.\\n // Cap total context at 16KB\\n return sections.join(\\\"\\\\n\\\\n\\\");\\n }\\n\\n**src/agents/formatter.ts**:\\n\\n export function computeExitCode(result, options): number {\\n if (result.dryRun) return 0;\\n if (result.status !== \\\"success\\\") return 1;\\n const order = [\\\"info\\\",\\\"warning\\\",\\\"error\\\",\\\"critical\\\"];\\n const threshold = order.indexOf(options.failOn ?? \\\"error\\\");\\n return result.data.findings.some(f => order.indexOf(f.severity) >= threshold) ? 10 : 0;\\n }\\n\\n export function formatResultText(result): string { /* severity icons, structured output */ }\\n export function formatResultJson(result): string { return JSON.stringify(result.data, null, 2); }\\n\\n### Step 6: Create CLI Command Handlers\\n\\nFor each LLM command, create src/commands/{command}.ts:\\n\\n export async function command{Name}(target, opts) {\\n const cwd = process.cwd();\\n const context = build{Name}Context(target, config);\\n const agentConfig = { adapter: opts.adapter, model: opts.model, cwd };\\n const result = await runAgentWorkflow(context, \\\"{workflow-id}\\\", agentConfig, agentOpts);\\n if (opts.reportFormat === \\\"json\\\") console.log(formatResultJson(result));\\n else console.log(formatResultText(result));\\n process.exit(computeExitCode(result, opts));\\n }\\n\\nWire handlers through cli-contracts' generated program:\\n\\n import { createProgram, type CommandHandlers } from './generated/program.js';\\n\\n const handlers: CommandHandlers = {\\n {commandName}: async (target, opts) => {\\n await command{Name}(target, opts);\\n },\\n // ... other handlers\\n };\\n\\n createProgram(handlers, version).parse();\\n\\n### Step 7: Update cli-contract.yaml\\n\\nAdd each LLM command with standard options and x-agent metadata:\\n\\n {command-name}:\\n summary: \\\"{Command summary}\\\"\\n arguments: [...]\\n options:\\n - name: adapter\\n schema: { type: string, enum: [mock, claude, openai, gemini] }\\n - name: model\\n schema: { type: string }\\n - name: show-prompt\\n schema: { type: boolean, default: false }\\n - name: fail-on\\n schema: { type: string, enum: [warning, error, critical], default: error }\\n - name: output\\n aliases: [o]\\n schema: { type: string }\\n file: { mode: write }\\n - name: report-format\\n schema: { type: string, enum: [json, text, yaml], default: json }\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: [network]\\n sideEffectNote: >-\\n Network calls to LLM provider when adapter is not mock.\\n Filesystem write only when --output is specified.\\n safeDryRunOption: show-prompt\\n expectedDurationMs: 120000\\n retryableExitCodes: [1, 12]\\n exits:\\n '0': { description: \\\"No blocking findings.\\\", stdout: { format: json, schema: { $ref: '...' } } }\\n '1': { description: \\\"General error.\\\", stderr: { format: text } }\\n '3': { description: \\\"Input validation failed.\\\", stderr: { format: json } }\\n '10': { description: \\\"Blocking findings detected.\\\", stdout: { format: json, schema: { $ref: '...' } } }\\n '11': { description: \\\"Runtime not installed.\\\", stderr: { format: json } }\\n '12': { description: \\\"Adapter error.\\\", stderr: { format: json } }\\n\\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\\nto components/schemas if not already present.\\n\\n### Step 8: Update README\\n\\nAdd \\\"Agent-Native Toolchain\\\" section after mechanical features:\\n- Intro: tool encapsulates domain-specific semantic reasoning\\n- Deterministic checks first, then semantic audit\\n- Structured findings (AgentAuditResult/AgentFinding)\\n- LLM Adapter Configuration table\\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\\n\",\n \"target_agent\": \"llm-feature-implementer\",\n \"allowed_from_agents\": [\n \"llm-feature-implementer\"\n ],\n \"workflow\": \"implement-llm-feature\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"implement-request\",\n \"result_handoff\": \"implementation-result\",\n \"responsibilities\": [\n \"Analyze the target project and determine the right LLM commands to add\",\n \"Create all DSL definition files with correct cross-references\",\n \"Generate TypeScript contracts via agent-runtime generate\",\n \"Implement the complete src/agents/ module following the exact patterns\",\n \"Create CLI command handlers integrating with the project's existing CLI structure\",\n \"Update cli-contract.yaml with proper x-agent metadata and component schemas\",\n \"Ensure the implementation compiles and --show-prompt mode works\"\n ],\n \"completion_criteria\": [\n \"dsl/ directory contains valid DSL definitions that pass agent-runtime generate\",\n \"agent-runtime.config.yaml points to the DSL with correct generated_dir\",\n \"src/generated/dsl/ contains generated contracts (agentRegistry, taskRegistry, handoffSchemas, workflowRegistry)\",\n \"src/agents/orchestrator.ts uses runWorkflow from agent-contracts-runtime (never runTask directly, no direct adapter.send calls)\",\n \"src/agents/orchestrator.ts dynamic-imports the runtime and adapters with correct exit codes (11, 12)\",\n \"src/agents/context-builder.ts contains only domain data (file contents, config, scan results) — no hardcoded agent instructions, evaluation criteria, or output format specs\",\n \"src/agents/context-builder.ts caps input at 16KB\",\n \"src/agents/formatter.ts implements computeExitCode with the standard exit code mapping\",\n \"src/commands/ has a handler for each new LLM command, passing cwd to AgentConfig\",\n \"CLI entry point uses cli-contracts' createProgram(handlers, version) with CommandHandlers interface\",\n \"cli-contract.yaml has all new commands with --adapter, --model, --show-prompt, --fail-on, --output, --report-format options\",\n \"cli-contract.yaml has x-agent metadata on each new command (riskLevel, safeDryRunOption, expectedDurationMs)\",\n \"components/schemas includes AgentAuditResult and related schemas\",\n \"All generated TypeScript compiles without type errors\",\n \"--show-prompt returns the constructed prompt without calling the LLM\"\n ]\n },\n \"audit-dsl\": {\n \"description\": \"Audit the DSL layer of an LLM command integration.\\n\\nVerify these files exist and are well-formed:\\n- dsl/{project}-dsl.yaml — must have version:1, system:{id,name},\\n agents/tasks/handoff_types via $ref\\n- dsl/agents/*.yaml — each agent has role_name, purpose, mode,\\n can_read_artifacts:[], can_write_artifacts:[], responsibilities,\\n constraints, rules with R-PREFIX-NNN\\n- dsl/tasks.yaml — target_agent, workflow, result_handoff all\\n cross-reference valid IDs\\n- dsl/handoff-types.yaml — version:1, schema with JSON Schema,\\n result types follow AgentAuditResult shape\\n- dsl/agent-runtime.config.yaml — dsl and generated_dir fields\\n\\nSeverity classification:\\n- critical: missing version:1 or system block (generator will fail)\\n- critical: task references non-existent agent or workflow\\n- critical: agent mode contradicts its purpose (see below)\\n- error: agent missing constraints or rules\\n- error: handoff schema not following AgentAuditResult shape\\n- warning: missing guardrails or guardrail_policies\\n- warning: agent has no escalation_criteria\\n\\nCRITICAL: agent mode-purpose coherence (category: dsl-agent):\\n- Agent with mode: read-only has purpose or responsibilities\\n that describe file writing, editing, creation, or code\\n generation — the agent's adapter tools won't include Write/Edit\\n so the stated purpose is impossible to fulfil\\n- Agent with mode: read-write has purpose that is purely\\n analytical (audit, review, explain) with no file output —\\n unnecessarily broad permissions\\n\\nCategory vocabulary: dsl-structure, dsl-agent, dsl-task,\\ndsl-handoff, dsl-workflow, dsl-guardrail.\\n\\nOutput a partial audit-result with findings only from the DSL layer.\\n\",\n \"target_agent\": \"implementation-auditor\",\n \"allowed_from_agents\": [\n \"implementation-auditor\"\n ],\n \"workflow\": \"audit-implementation\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"audit-request\",\n \"result_handoff\": \"audit-result\",\n \"responsibilities\": [\n \"Check all DSL files for structural correctness\",\n \"Validate cross-references (agent↔task↔workflow↔handoff)\",\n \"Verify guardrails and guardrail_policies\",\n \"Check agent mode-purpose coherence (read-only agents must not have write-oriented purposes; read-write agents must justify their write permissions in their purpose)\"\n ],\n \"completion_criteria\": [\n \"Every dsl/* file checked for required fields\",\n \"Cross-references validated\",\n \"Agent mode is consistent with stated purpose and responsibilities\",\n \"Findings use dsl-* category vocabulary\"\n ]\n },\n \"audit-runtime\": {\n \"description\": \"Audit the runtime integration layer of an LLM command integration.\\n\\nScan src/agents/orchestrator.ts (or equivalent runtime module):\\n\\nCRITICAL violations (category: runtime-orchestrator):\\n- adapter.send() or adapter.sendExecution() called directly\\n- adapter.followUp() called directly\\n- Custom adapter class defined (not imported from runtime)\\n- runWorkflow not imported from agent-contracts-runtime\\n- runTask used instead of runWorkflow — consumer projects must\\n use runWorkflow() which orchestrates through the DSL workflow\\n DAG, activates workflow-level plugin hooks (beforeWorkflow/\\n afterWorkflow), handles gate steps and step dependencies.\\n runTask() is a low-level internal API; calling it directly\\n bypasses workflow orchestration entirely\\n\\nERROR violations (category: runtime-registry):\\n- Generated registries not imported from src/generated/dsl/\\n- Registries not passed to runWorkflow options\\n- Hard-coded agent/task definitions instead of registry lookup\\n\\nERROR violations (category: runtime-adapter):\\n- Adapter packages imported statically (not dynamic import)\\n- Missing exit code 11 when runtime import fails\\n- Missing exit code 12 when adapter creation fails\\n\\nERROR violations (category: runtime-handler):\\n- Project has cli-contracts generated code (src/generated/program.ts\\n or src/generated/cli/program.ts exporting CommandHandlers and\\n createProgram) but CLI entry point manually creates Commander\\n commands instead of using createProgram(handlers, version)\\n- LLM command handlers are not wired through the generated\\n CommandHandlers interface — handler signatures drift from the\\n cli-contract.yaml definition without type errors\\n- CLI entry point calls runTask directly instead of going through\\n the command handler → context-builder → orchestrator chain\\n\\nWARNING violations (category: runtime-plugin):\\n- Plugin hooks explicitly bypassed or ignored\\n\\nCategory vocabulary: runtime-orchestrator, runtime-registry,\\nruntime-adapter, runtime-handler, runtime-plugin.\\n\\nOutput a partial audit-result with findings only from the runtime layer.\\n\",\n \"target_agent\": \"implementation-auditor\",\n \"allowed_from_agents\": [\n \"implementation-auditor\"\n ],\n \"workflow\": \"audit-implementation\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"audit-request\",\n \"result_handoff\": \"audit-result\",\n \"responsibilities\": [\n \"Scan orchestrator code for direct adapter usage\",\n \"Verify runWorkflow is used (not runTask) for LLM command execution\",\n \"Verify registry imports and passing\",\n \"Check adapter creation patterns and exit codes\",\n \"Verify cli-contracts handler wiring (CommandHandlers + createProgram used in CLI entry point)\"\n ],\n \"completion_criteria\": [\n \"All orchestrator files scanned for adapter.send / adapter.followUp\",\n \"No runTask usage found (runWorkflow must be used instead)\",\n \"Registry usage verified\",\n \"Exit code 11/12 patterns checked\",\n \"cli-contracts handler integration verified (CommandHandlers interface used, createProgram called)\"\n ]\n },\n \"audit-cli-contract\": {\n \"description\": \"Audit the CLI contract layer of an LLM command integration.\\n\\nParse cli-contract.yaml and check each LLM command:\\n\\nERROR: missing standard options (category: cli-contract-options):\\n- --adapter, --model, --show-prompt, --fail-on, --output, --report-format\\n- Using --format instead of --report-format for LLM commands\\n\\nERROR: missing x-agent metadata (category: cli-contract-xagent):\\n- No x-agent block on LLM command\\n- Missing riskLevel, safeDryRunOption, or expectedDurationMs\\n- Using snake_case instead of camelCase for x-agent fields\\n\\nERROR: wrong exit codes (category: cli-contract-exits):\\n- Missing exit 0/1/3/10/11/12 definitions\\n- Exit 10 not defined for finding-based commands\\n\\nWARNING: missing schemas (category: cli-contract-schema):\\n- AgentAuditResult not in components/schemas\\n- AgentFinding, AgentRecommendedAction, AgentEvidence not defined\\n\\nCategory vocabulary: cli-contract-options, cli-contract-xagent,\\ncli-contract-exits, cli-contract-schema.\\n\\nOutput a partial audit-result with findings only from the CLI contract layer.\\n\",\n \"target_agent\": \"implementation-auditor\",\n \"allowed_from_agents\": [\n \"implementation-auditor\"\n ],\n \"workflow\": \"audit-implementation\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"audit-request\",\n \"result_handoff\": \"audit-result\",\n \"responsibilities\": [\n \"Check each LLM command for standard options\",\n \"Verify x-agent metadata fields and casing\",\n \"Validate exit code definitions\",\n \"Check components/schemas for canonical types\"\n ],\n \"completion_criteria\": [\n \"Every LLM command checked for all 6 standard options\",\n \"x-agent metadata validated on every LLM command\",\n \"Exit codes verified against convention\",\n \"Schema completeness checked\"\n ]\n },\n \"audit-architecture\": {\n \"description\": \"Audit the architecture and module structure of an LLM command integration.\\n\\nVerify module structure (category: architecture-modules):\\n- src/agents/types.ts exists with TaskId, AgentConfig, AgentOptions, AgentRunResult\\n- src/agents/orchestrator.ts exists\\n- src/agents/context-builder.ts exists\\n- src/agents/formatter.ts exists with computeExitCode\\n\\nVerify behavior (category: architecture-dry-run):\\n- --show-prompt path returns the constructed prompt without calling the adapter\\n- buildTaskPrompt is used (not a placeholder string)\\n\\nCRITICAL: context-builder SSoT violations (category: architecture-context-builder):\\n\\nThe context-builder's role is to assemble domain-specific DATA (file\\ncontents, configuration, scan results, schema context) into the user\\nprompt. Agent INSTRUCTIONS (how to evaluate, what rules to apply,\\nwhat patterns to look for, output format) belong in the DSL agent\\ndefinition and are injected by buildTaskPrompt / runWorkflow.\\n\\nDetect any of the following in context-builder source code:\\n- Sections titled \\\"## Instructions\\\", \\\"## Required Patterns\\\",\\n \\\"## Audit Instructions\\\", \\\"## Output Format\\\", or similar\\n behavioral directive headings — these are agent instructions\\n that belong in DSL (agent purpose, responsibilities, constraints,\\n rules) and must not be hardcoded in context-builder\\n- Output format specifications (field lists, JSON/YAML schema\\n descriptions, example output structures) — buildTaskPrompt\\n already generates \\\"Required Output Format\\\" from the handoff\\n Zod schema; duplicating this in context-builder causes conflicts\\n- Domain-specific evaluation criteria, checklists, anti-pattern\\n definitions, rule sets, or API reference material — these\\n belong in the DSL agent definition's purpose field\\n- Any string that duplicates or paraphrases content already\\n present in the DSL agent's purpose, responsibilities,\\n constraints, or rules fields\\n\\nWhat IS allowed in context-builder:\\n- File contents read from disk (migration SQL, schema, config)\\n- Project metadata (dialect, directories, file lists)\\n- Deterministic pre-analysis results (lint violations, scan output)\\n- Operational context (target path, cwd, timestamp)\\n- Brief task framing (\\\"# Migration Safety Audit Request\\\")\\n\\nERROR: mode-purpose coherence (category: architecture-agent-coherence):\\n- DSL agent with mode: read-only has purpose or responsibilities\\n that describe file writing, editing, creation, or modification\\n- DSL agent with mode: read-write but no cwd propagated to adapter\\n — the agent's file tools won't operate in the project directory\\n- Command handler doesn't pass cwd to AgentConfig when using an\\n agentic adapter (claude)\\n\\nERROR: adapter cwd propagation (category: architecture-adapter-cwd):\\n- AgentConfig type has no cwd field\\n- Command handlers don't set config.cwd = process.cwd() or\\n resolve(projectDir)\\n- createAdapter doesn't pass cwd to adapter constructor/factory\\n- Agentic adapters (claude) instantiated without cwd —\\n their file tools will operate in an undefined directory\\n\\nCRITICAL: runTask usage (category: architecture-handler):\\n- runTask() imported or called anywhere in the consumer project —\\n consumer projects must use runWorkflow() exclusively; runTask()\\n is a low-level internal API that bypasses workflow DAG\\n orchestration, workflow-level plugin hooks, and gate steps\\n\\nERROR: cli-contracts handler wiring (category: architecture-handler):\\n- Project has cli-contracts generated code (src/generated/program.ts\\n or src/generated/cli/program.ts with CommandHandlers) but CLI\\n entry point manually creates Commander commands instead of\\n calling createProgram(handlers, version)\\n- Command handlers bypass the generated CommandHandlers interface\\n\\nScan for direct SDK imports (category: architecture-modules):\\n- @anthropic-ai/sdk or @anthropic-ai/claude-agent-sdk imported\\n outside src/agents/orchestrator.ts or adapter files\\n- openai or @openai/agents imported outside adapters\\n- @google/genai imported outside adapters\\n\\nCategory vocabulary: architecture-modules, architecture-dry-run,\\narchitecture-context-builder, architecture-agent-coherence,\\narchitecture-adapter-cwd, architecture-handler,\\narchitecture-formatter.\\n\\nOutput a partial audit-result with findings only from the architecture layer.\\n\",\n \"target_agent\": \"implementation-auditor\",\n \"allowed_from_agents\": [\n \"implementation-auditor\"\n ],\n \"workflow\": \"audit-implementation\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"audit-request\",\n \"result_handoff\": \"audit-result\",\n \"responsibilities\": [\n \"Verify module structure\",\n \"Check dry-run behavior\",\n \"Audit context-builder for SSoT violations (hardcoded instructions, output format specs, domain rules that belong in DSL)\",\n \"Check mode-purpose coherence across DSL definitions and runtime code\",\n \"Verify cwd propagation from command handler through adapter config\",\n \"Verify cli-contracts handler wiring (CommandHandlers + createProgram)\",\n \"Scan for direct SDK imports\"\n ],\n \"completion_criteria\": [\n \"Module structure verified\",\n \"Dry-run behavior confirmed\",\n \"Context-builder contains only domain data, not agent instructions\",\n \"Agent mode is consistent with purpose and tool usage\",\n \"cwd is propagated to agentic adapters\",\n \"cli-contracts handler integration verified\",\n \"No direct SDK imports outside adapter files\"\n ]\n },\n \"audit-merge\": {\n \"description\": \"Merge the partial audit results from the four parallel layer audits\\n(DSL, runtime, CLI contract, architecture) into a single unified\\naudit-result.\\n\\nThe prior_context contains the JSON output from each completed\\naudit step. Parse each one, combine all findings into a single\\narray, deduplicate by (target + message), assign sequential IDs\\n(F-001, F-002, ...), derive the overall riskLevel from the worst\\nfinding severity, and produce prioritized recommendedActions.\\n\\nMerging rules:\\n- Collect all findings from all layer results\\n- Sort: critical first, then error, warning, info\\n- Assign sequential IDs: F-001, F-002, ...\\n- Deduplicate: if two findings have the same target and message, keep one\\n- Derive riskLevel: any critical → critical, any error → high,\\n any warning → medium, info only → low\\n- Merge recommendedActions from all layers, deduplicate by title\\n- Set metadata: { tool: \\\"agent-runtime\\\", command: \\\"audit-implementation\\\" }\\n\",\n \"target_agent\": \"implementation-auditor\",\n \"allowed_from_agents\": [\n \"implementation-auditor\"\n ],\n \"workflow\": \"audit-implementation\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"audit-request\",\n \"result_handoff\": \"audit-result\",\n \"responsibilities\": [\n \"Parse prior_context JSON from each layer audit step\",\n \"Merge and deduplicate findings\",\n \"Derive overall riskLevel\",\n \"Produce a single coherent summary paragraph\"\n ],\n \"completion_criteria\": [\n \"All findings from all layers included\",\n \"No duplicate findings\",\n \"riskLevel correctly derived from worst finding\",\n \"Summary paragraph covers all audited layers\"\n ]\n }\n },\n \"handoff_types\": {\n \"implement-request\": {\n \"version\": 1,\n \"description\": \"Request to implement LLM-powered features in a CLI tool\",\n \"schema\": {\n \"type\": \"object\",\n \"required\": [\n \"description\",\n \"project_dir\"\n ],\n \"properties\": {\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Description of the LLM feature(s) to implement\"\n },\n \"project_dir\": {\n \"type\": \"string\",\n \"description\": \"Absolute path to the target project directory\"\n },\n \"reference_doc\": {\n \"type\": \"string\",\n \"description\": \"Content of the integrate-llm-commands reference documentation\"\n }\n }\n }\n },\n \"audit-request\": {\n \"version\": 1,\n \"description\": \"Request to audit an LLM command integration\",\n \"schema\": {\n \"type\": \"object\",\n \"required\": [\n \"project_dir\"\n ],\n \"properties\": {\n \"project_dir\": {\n \"type\": \"string\",\n \"description\": \"Absolute path to the target project directory\"\n },\n \"focus\": {\n \"type\": \"string\",\n \"description\": \"Optional focus area (dsl, runtime, cli-contract, architecture, or all). Defaults to all.\",\n \"enum\": [\n \"all\",\n \"dsl\",\n \"runtime\",\n \"cli-contract\",\n \"architecture\"\n ]\n }\n }\n }\n },\n \"audit-result\": {\n \"version\": 1,\n \"description\": \"Structured audit result following AgentAuditResult shape. Conforms to cli-contracts reference schema.\",\n \"schema\": {\n \"type\": \"object\",\n \"required\": [\n \"summary\",\n \"riskLevel\",\n \"findings\"\n ],\n \"properties\": {\n \"summary\": {\n \"type\": \"string\",\n \"description\": \"One-paragraph overall assessment\"\n },\n \"riskLevel\": {\n \"type\": \"string\",\n \"enum\": [\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Derived from worst finding: any critical → critical, any error → high, any warning → medium, info only → low\"\n },\n \"findings\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"severity\",\n \"category\",\n \"message\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique finding identifier (e.g. AUDIT-001)\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"warning\",\n \"error\",\n \"critical\"\n ]\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"One of: dsl-structure, dsl-agent, dsl-task, dsl-handoff, dsl-workflow, dsl-guardrail, runtime-adapter, runtime-orchestrator, runtime-registry, runtime-handler, runtime-plugin, cli-contract-options, cli-contract-xagent, cli-contract-exits, cli-contract-schema, architecture-modules, architecture-dry-run, architecture-context-builder, architecture-agent-coherence, architecture-adapter-cwd, architecture-handler, architecture-formatter\"\n },\n \"target\": {\n \"type\": \"string\",\n \"description\": \"File path where the issue was found\"\n },\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Line number or section within the file\"\n },\n \"message\": {\n \"type\": \"string\",\n \"description\": \"Concise description of the issue\"\n },\n \"recommendation\": {\n \"type\": \"string\",\n \"description\": \"Concrete fix or remediation step\"\n },\n \"confidence\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 1,\n \"description\": \"1.0 for pattern match, 0.8+ for structural check, 0.5-0.8 for heuristic assessment\"\n }\n }\n }\n },\n \"recommendedActions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"kind\",\n \"title\"\n ],\n \"properties\": {\n \"kind\": {\n \"type\": \"string\",\n \"enum\": [\n \"run_command\",\n \"edit_file\",\n \"review\",\n \"confirm\",\n \"block\",\n \"ignore\"\n ]\n },\n \"title\": {\n \"type\": \"string\"\n },\n \"command\": {\n \"type\": \"string\",\n \"description\": \"CLI command to run (for run_command kind)\"\n },\n \"target\": {\n \"type\": \"string\",\n \"description\": \"Target file or resource\"\n },\n \"rationale\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"metadata\": {\n \"type\": \"object\",\n \"properties\": {\n \"tool\": {\n \"type\": \"string\"\n },\n \"command\": {\n \"type\": \"string\"\n },\n \"version\": {\n \"type\": \"string\"\n },\n \"generatedAt\": {\n \"type\": \"string\"\n },\n \"adapter\": {\n \"type\": \"string\"\n },\n \"model\": {\n \"type\": \"string\"\n }\n }\n }\n }\n }\n },\n \"implementation-result\": {\n \"version\": 1,\n \"description\": \"Result of the LLM feature implementation\",\n \"schema\": {\n \"type\": \"object\",\n \"required\": [\n \"files_created\",\n \"files_modified\",\n \"summary\"\n ],\n \"properties\": {\n \"files_created\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"description\": \"List of newly created files\"\n },\n \"files_modified\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"description\": \"List of modified existing files\"\n },\n \"summary\": {\n \"type\": \"string\",\n \"description\": \"Human-readable summary of the implementation\"\n },\n \"commands_added\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"name\",\n \"type\"\n ],\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Command name\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"audit\",\n \"propose\",\n \"explain\"\n ],\n \"description\": \"Command type\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Command description\"\n }\n }\n }\n },\n \"next_steps\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"description\": \"Recommended next steps for the developer\"\n }\n }\n }\n }\n },\n \"guardrails\": {\n \"output-schema-conformance\": {\n \"description\": \"Ensure all agent outputs conform to their respective handoff schemas. Validation is performed at runtime via Zod.\",\n \"scope\": {\n \"agents\": [\n \"llm-feature-implementer\",\n \"implementation-auditor\"\n ],\n \"tasks\": [\n \"implement-llm-feature\",\n \"audit-dsl\",\n \"audit-runtime\",\n \"audit-cli-contract\",\n \"audit-architecture\",\n \"audit-merge\"\n ]\n },\n \"rationale\": \"Structured output conformance is critical for CLI parsing and downstream tooling integration.\"\n },\n \"no-direct-api-call\": {\n \"description\": \"The implementer agent must not generate code that calls LLM APIs directly. All LLM invocations must go through agent-contracts-runtime runWorkflow().\",\n \"scope\": {\n \"agents\": [\n \"llm-feature-implementer\"\n ]\n },\n \"rationale\": \"Preserves SDK adapter abstraction, enabling adapter swap, plugin hooks, and guardrail enforcement.\"\n },\n \"audit-read-only\": {\n \"description\": \"The auditor agent must not create, modify, or delete any files. It operates in read-only mode and produces findings only.\",\n \"scope\": {\n \"agents\": [\n \"implementation-auditor\"\n ]\n },\n \"rationale\": \"Audit results must be reviewed by the developer before changes are applied. The auditor observes; the developer decides.\"\n }\n },\n \"guardrail_policies\": {\n \"implement-safety-policy\": {\n \"description\": \"Guardrail policy for the LLM feature implementation agent\",\n \"rules\": [\n {\n \"guardrail\": \"output-schema-conformance\",\n \"severity\": \"critical\",\n \"action\": \"block\"\n },\n {\n \"guardrail\": \"no-direct-api-call\",\n \"severity\": \"critical\",\n \"action\": \"block\"\n }\n ]\n },\n \"audit-safety-policy\": {\n \"description\": \"Guardrail policy for the implementation auditor agent\",\n \"rules\": [\n {\n \"guardrail\": \"output-schema-conformance\",\n \"severity\": \"critical\",\n \"action\": \"block\"\n },\n {\n \"guardrail\": \"audit-read-only\",\n \"severity\": \"critical\",\n \"action\": \"block\"\n }\n ]\n }\n },\n \"workflow\": {\n \"implement-llm-feature\": {\n \"description\": \"Implement LLM-powered commands in a CLI tool\",\n \"trigger\": \"cli-command\",\n \"entry_conditions\": [\n \"Target project is a TypeScript / Node.js project\",\n \"cli-contract.yaml exists or is being created\"\n ],\n \"steps\": [\n {\n \"type\": \"delegate\",\n \"task\": \"implement-llm-feature\",\n \"from_agent\": \"llm-feature-implementer\"\n }\n ]\n },\n \"audit-implementation\": {\n \"description\": \"Audit an LLM command integration for pattern conformance\",\n \"trigger\": \"cli-command\",\n \"entry_conditions\": [\n \"Target project has LLM command integration to audit\"\n ],\n \"steps\": [\n {\n \"type\": \"delegate\",\n \"task\": \"audit-dsl\",\n \"from_agent\": \"implementation-auditor\",\n \"depends_on\": []\n },\n {\n \"type\": \"delegate\",\n \"task\": \"audit-runtime\",\n \"from_agent\": \"implementation-auditor\",\n \"depends_on\": []\n },\n {\n \"type\": \"delegate\",\n \"task\": \"audit-cli-contract\",\n \"from_agent\": \"implementation-auditor\",\n \"depends_on\": []\n },\n {\n \"type\": \"delegate\",\n \"task\": \"audit-architecture\",\n \"from_agent\": \"implementation-auditor\",\n \"depends_on\": []\n },\n {\n \"type\": \"delegate\",\n \"task\": \"audit-merge\",\n \"from_agent\": \"implementation-auditor\",\n \"depends_on\": [\n \"audit-dsl\",\n \"audit-runtime\",\n \"audit-cli-contract\",\n \"audit-architecture\"\n ]\n }\n ]\n }\n }\n} as const;\n","/**\n * audit-implementation command — uses the built-in Implementation Auditor agent\n * to verify an LLM command integration follows the agent-contracts stack.\n *\n * The agent is read-only: it analyzes but does not modify files.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nimport { runWorkflow } from \"./workflow-runner.js\";\nimport { buildTaskPrompt } from \"./task-runner.js\";\nimport type { SdkAdapter, TaskContext } from \"./task-runner.js\";\nimport type { WorkflowInvocation } from \"./workflow-runner.js\";\nimport {\n agentRegistry,\n taskRegistry,\n handoffSchemas,\n workflowRegistry,\n resolvedDsl,\n} from \"../builtin-agents/generated/index.js\";\nimport {\n createGuardrailHooksFromRules,\n type GuardrailHooks,\n type GuardrailRuleData,\n} from \"./guardrail-hooks.js\";\nimport type { AuditResult } from \"../builtin-agents/generated/handoffs.js\";\n\n// ---------------------------------------------------------------------------\n// Locale detection\n// ---------------------------------------------------------------------------\n\nfunction getLocale(): string {\n return (\n process.env.LANG?.split(\".\")[0] ??\n process.env.LC_ALL?.split(\".\")[0] ??\n process.env.LANGUAGE?.split(\":\")[0] ??\n \"en_US\"\n );\n}\n\nfunction isJapanese(): boolean {\n return getLocale().startsWith(\"ja\");\n}\n\n// ---------------------------------------------------------------------------\n// Messages — locale-aware\n// ---------------------------------------------------------------------------\n\ninterface Messages {\n noProjectDir: (dir: string) => string;\n adapterError: (msg: string) => string;\n dryRunHeader: string;\n dryRunProjectDir: (dir: string) => string;\n dryRunFocus: (focus: string) => string;\n auditStarting: (adapter: string) => string;\n auditSuccess: string;\n auditFailed: (reason: string) => string;\n riskLevel: (level: string) => string;\n findingsHeader: (count: number) => string;\n noFindings: string;\n recommendedActionsHeader: string;\n}\n\nconst en: Messages = {\n noProjectDir: (dir) => `Project directory not found: ${dir}`,\n adapterError: (msg) => `Adapter initialization failed: ${msg}`,\n dryRunHeader: \"=== Dry Run (audit-implementation) ===\",\n dryRunProjectDir: (dir) => `Project: ${dir}`,\n dryRunFocus: (focus) => `Focus: ${focus}`,\n auditStarting: (adapter) => `Starting audit with ${adapter} adapter...`,\n auditSuccess: \"Audit completed.\",\n auditFailed: (reason) => `Audit failed: ${reason}`,\n riskLevel: (level) => `Risk level: ${level}`,\n findingsHeader: (count) => `Findings (${count}):`,\n noFindings: \"No findings.\",\n recommendedActionsHeader: \"Recommended actions:\",\n};\n\nconst ja: Messages = {\n noProjectDir: (dir) => `プロジェクトディレクトリが見つかりません: ${dir}`,\n adapterError: (msg) => `アダプター初期化に失敗しました: ${msg}`,\n dryRunHeader: \"=== ドライラン (audit-implementation) ===\",\n dryRunProjectDir: (dir) => `プロジェクト: ${dir}`,\n dryRunFocus: (focus) => `フォーカス: ${focus}`,\n auditStarting: (adapter) => `${adapter} アダプターで監査を開始します...`,\n auditSuccess: \"監査が完了しました。\",\n auditFailed: (reason) => `監査に失敗しました: ${reason}`,\n riskLevel: (level) => `リスクレベル: ${level}`,\n findingsHeader: (count) => `検出事項 (${count}件):`,\n noFindings: \"検出事項はありません。\",\n recommendedActionsHeader: \"推奨アクション:\",\n};\n\nfunction msg(): Messages {\n return isJapanese() ? ja : en;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\nasync function createAuditAdapter(\n adapterName: string,\n projectDir: string,\n model?: string,\n guardrailHooks?: GuardrailHooks,\n): Promise<SdkAdapter> {\n switch (adapterName) {\n case \"claude\": {\n const { ClaudeAgentSdkAdapter } = await import(\"../adapters/claude-agent-sdk.js\");\n return new ClaudeAgentSdkAdapter({\n cwd: projectDir,\n model,\n guardrailHooks,\n });\n }\n case \"mock\": {\n const { MockAdapter } = await import(\"../adapters/mock.js\");\n return new MockAdapter();\n }\n default:\n throw new Error(\n `Unsupported adapter for audit-implementation: \"${adapterName}\". ` +\n `Available: claude, mock`,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface AuditOptions {\n adapter: string;\n projectDir: string;\n focus: \"all\" | \"dsl\" | \"runtime\" | \"cli-contract\" | \"architecture\";\n dryRun: boolean;\n failOn: \"warning\" | \"error\" | \"critical\";\n reportFormat: \"json\" | \"text\" | \"yaml\";\n model?: string;\n progressOutput?: { write(chunk: string): unknown };\n}\n\nexport interface AuditRunResult {\n status: \"success\" | \"failed\" | \"dry_run\";\n exitCode: number;\n data?: AuditResult;\n error?: string;\n}\n\nconst SEVERITY_ORDER: Record<string, number> = {\n info: 0,\n warning: 1,\n error: 2,\n critical: 3,\n};\n\nfunction hasFindings(result: AuditResult, failOn: string): boolean {\n const threshold = SEVERITY_ORDER[failOn] ?? 2;\n return result.findings.some(\n (f) => (SEVERITY_ORDER[f.severity] ?? 0) >= threshold,\n );\n}\n\nexport async function runAuditImplementation(\n options: AuditOptions,\n): Promise<AuditRunResult> {\n const m = msg();\n const projectDir = resolve(options.projectDir);\n\n if (!existsSync(projectDir)) {\n return { status: \"failed\", exitCode: 3, error: m.noProjectDir(projectDir) };\n }\n\n // --- Build invocation context (shared between dry-run and live run) ---\n const focusInstruction = options.focus !== \"all\"\n ? `\\n\\nFocus the audit on the \"${options.focus}\" layer only.`\n : \"\";\n\n const userRequest = [\n `Audit the LLM command integration in the following project.`,\n `Project directory: ${projectDir}`,\n focusInstruction,\n ].join(\"\\n\");\n\n const context: TaskContext = {\n user_request: userRequest,\n relevant_paths: [projectDir],\n };\n\n // --- Dry run: emit prompts for all parallel audit tasks ---\n if (options.dryRun) {\n const agent = agentRegistry[\"implementation-auditor\"];\n const auditTasks = [\"audit-dsl\", \"audit-runtime\", \"audit-cli-contract\", \"audit-architecture\"];\n const prompts = auditTasks.map((taskId) => {\n const task = taskRegistry[taskId];\n if (!task) return `# [Task not found: ${taskId}]`;\n return buildTaskPrompt(agent, task, context, { handoffSchemas });\n });\n const separator = \"\\n\\n\" + \"=\".repeat(72) + \"\\n\\n\";\n const fullPrompt = prompts.join(separator);\n\n return {\n status: \"dry_run\",\n exitCode: 0,\n data: {\n summary: fullPrompt,\n riskLevel: \"low\",\n findings: [],\n },\n };\n }\n\n // --- Create adapter ---\n let guardrailHooks: GuardrailHooks | undefined;\n const rawRules = resolvedDsl._guardrailRules as GuardrailRuleData | undefined;\n if (\n rawRules &&\n (rawRules.commandRules?.length ||\n rawRules.fileRules?.length ||\n rawRules.contentRules?.length)\n ) {\n guardrailHooks = createGuardrailHooksFromRules(rawRules);\n }\n\n let adapter: SdkAdapter;\n try {\n adapter = await createAuditAdapter(\n options.adapter,\n projectDir,\n options.model,\n guardrailHooks,\n );\n } catch (err) {\n return { status: \"failed\", exitCode: 12, error: m.adapterError((err as Error).message) };\n }\n\n console.error(m.auditStarting(options.adapter));\n\n const registries = {\n workflowRegistry,\n taskRegistry,\n agentRegistry,\n handoffSchemas,\n };\n\n // --- Run workflow ---\n const invocation: WorkflowInvocation = {\n workflow: \"audit-implementation\",\n user_request: userRequest,\n runtime: {\n maxFollowUps: 2,\n maxRetries: 1,\n },\n hooks: {\n onGate: async () => true,\n },\n context: {\n cwd: projectDir,\n },\n progressOutput: options.progressOutput,\n };\n\n const result = await runWorkflow(adapter, invocation, registries);\n\n if (result.status !== \"completed\") {\n const reason = result.escalation_reason ?? result.error_message ?? result.status;\n return { status: \"failed\", exitCode: 1, error: m.auditFailed(reason) };\n }\n\n const lastStep = result.steps[result.steps.length - 1];\n const outcomeData = (lastStep?.outcome as Record<string, unknown>)?.data as\n | AuditResult\n | undefined;\n\n const auditData: AuditResult = outcomeData ?? {\n summary: m.auditSuccess,\n riskLevel: \"low\",\n findings: [],\n };\n\n const exitCode = hasFindings(auditData, options.failOn) ? 10 : 0;\n\n return {\n status: \"success\",\n exitCode,\n data: auditData,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Text formatter\n// ---------------------------------------------------------------------------\n\nconst SEVERITY_ICON: Record<string, string> = {\n critical: \"✗\",\n error: \"✗\",\n warning: \"!\",\n info: \"·\",\n};\n\nexport function formatAuditResult(result: AuditRunResult): string {\n const m = msg();\n\n if (result.status === \"dry_run\") {\n return result.data?.summary ?? m.dryRunHeader;\n }\n\n if (result.status === \"failed\") {\n return result.error ?? m.auditFailed(\"unknown\");\n }\n\n const data = result.data;\n if (!data) return m.auditSuccess;\n\n const lines: string[] = [data.summary, \"\"];\n\n lines.push(m.riskLevel(data.riskLevel));\n lines.push(\"\");\n\n if (data.findings.length === 0) {\n lines.push(m.noFindings);\n } else {\n lines.push(m.findingsHeader(data.findings.length));\n for (const f of data.findings) {\n const icon = SEVERITY_ICON[f.severity] ?? \"·\";\n const id = f.id ? `[${f.id}] ` : \"\";\n const target = f.target ? ` (${f.target})` : \"\";\n lines.push(` ${icon} ${id}${f.severity.toUpperCase()}: ${f.message}${target}`);\n if (f.recommendation) {\n lines.push(` → ${f.recommendation}`);\n }\n }\n lines.push(\"\");\n }\n\n if (data.recommendedActions && data.recommendedActions.length > 0) {\n lines.push(m.recommendedActionsHeader);\n for (const a of data.recommendedActions) {\n const cmd = a.command ? ` — ${a.command}` : \"\";\n lines.push(` [${a.kind}] ${a.title}${cmd}`);\n }\n }\n\n return lines.join(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IACrB;AAAA,EACF;AAEF;AAEA,IAAM,UAAU,cAAc,UAAU,OAAO;AAC/C,MAAM,QAAQ,WAAW;","names":["existsSync","readFileSync","resolve","handlers","program","existsSync","readFile","join","existsSync","resolve","join","implementLlmFeature","msg","join","existsSync","resolve","existsSync","resolve","getLocale","isJapanese","en","msg","ja","resolve","existsSync","YAML","existsSync","resolvedDsl","resolve","readFileSync","msg"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/index.ts","../../src/generated/cli/program.ts","../../src/generated/cli/contract.ts","../../src/lib/doctor.ts","../../src/lib/init.ts","../../src/lib/implement.ts","../../src/builtin-agents/generated/agents.ts","../../src/builtin-agents/generated/tasks.ts","../../src/builtin-agents/generated/handoffs.ts","../../src/builtin-agents/generated/workflows.ts","../../src/builtin-agents/generated/dsl-data.ts","../../src/lib/audit-implementation.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * agent-runtime CLI entry point\n *\n * Uses auto-generated program from cli-contract.yaml.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { register } from \"tsx/esm/api\";\nimport { createProgram, type CommandHandlers } from \"../generated/cli/program.js\";\nimport { generate, loadConfig, checkFreshness } from \"../generator/index.js\";\nimport {\n buildTaskPrompt,\n pluginRegistry,\n runWorkflow,\n createGuardrailHooksFromRules,\n type AgentContractLike,\n type TaskContractLike,\n type SdkAdapter,\n type TaskContext,\n type WorkflowContractLike,\n type WorkflowInvocation,\n type WorkflowRegistries,\n type GuardrailHooks,\n type GuardrailRuleData,\n} from \"../index.js\";\nimport { loadPlugins } from \"../lib/plugin-loader.js\";\nimport { runDoctor } from \"../lib/doctor.js\";\nimport { runInit } from \"../lib/init.js\";\nimport { runImplement, formatImplementResult } from \"../lib/implement.js\";\nimport { runAuditImplementation, formatAuditResult } from \"../lib/audit-implementation.js\";\nimport { resolvedDsl } from \"../builtin-agents/generated/index.js\";\nimport { createProgressSink, type ProgressSink } from \"../lib/progress-sink.js\";\nimport type { ResolvedProgressLog } from \"../generator/config.js\";\nimport type { z } from \"zod\";\nimport YAML from \"yaml\";\n\nregister();\n\nconst VERSION = \"0.36.5\";\n\n/**\n * Dynamically import the generated contracts from the configured generated_dir.\n * Handles both .ts (via tsx/ts-node) and .js (compiled) files,\n * and both flat exports and namespace exports.\n */\nasync function loadGeneratedContracts(configPath: string): Promise<{\n agentRegistry: Record<string, AgentContractLike>;\n taskRegistry: Record<string, TaskContractLike>;\n handoffSchemas: Record<string, z.ZodType>;\n workflowRegistry: Record<string, WorkflowContractLike>;\n guardrailHooks?: GuardrailHooks;\n resolvedDsl?: Record<string, unknown>;\n}> {\n const config = await loadConfig(configPath);\n const basePath = `${config.generatedDir}/index`;\n\n let indexPath: string;\n if (existsSync(`${basePath}.js`)) {\n indexPath = `${basePath}.js`;\n } else if (existsSync(`${basePath}.ts`)) {\n indexPath = `${basePath}.ts`;\n } else {\n throw new Error(\n `Generated index file not found at ${basePath}.{js,ts}. Run \\`agent-runtime generate\\` first.`,\n );\n }\n\n const mod = await import(new URL(`file://${indexPath}`).href);\n\n let guardrailHooks: GuardrailHooks | undefined;\n const resolvedDsl = mod.resolvedDsl as Record<string, unknown> | undefined;\n if (resolvedDsl) {\n const rawRules = resolvedDsl._guardrailRules as GuardrailRuleData | undefined;\n if (\n rawRules &&\n (rawRules.commandRules?.length ||\n rawRules.fileRules?.length ||\n rawRules.contentRules?.length)\n ) {\n guardrailHooks = createGuardrailHooksFromRules(rawRules);\n }\n }\n\n return {\n agentRegistry: mod.agentRegistry ?? mod.agents?.agentRegistry ?? {},\n taskRegistry: mod.taskRegistry ?? mod.tasks?.taskRegistry ?? {},\n handoffSchemas: mod.handoffSchemas ?? mod.handoffs?.handoffSchemas ?? {},\n workflowRegistry: mod.workflowRegistry ?? mod.workflows?.workflowRegistry ?? {},\n guardrailHooks,\n resolvedDsl,\n };\n}\n\nasync function createAdapter(\n adapterName: string,\n guardrailHooks?: GuardrailHooks,\n cwd?: string,\n model?: string,\n): Promise<SdkAdapter> {\n switch (adapterName) {\n case \"mock\": {\n const { MockAdapter } = await import(\"../adapters/mock.js\");\n return new MockAdapter();\n }\n case \"claude\": {\n const { ClaudeAgentSdkAdapter } = await import(\"../adapters/claude-agent-sdk.js\");\n return new ClaudeAgentSdkAdapter({ cwd, guardrailHooks, ...(model ? { model } : {}) });\n }\n case \"gemini\": {\n // The \"gemini\" selector now targets Gemini models via Google ADK, which\n // provides the native subagent mechanism required for LLM-internal routing.\n const { AdkSdkAdapter } = await import(\"../adapters/adk-sdk.js\");\n return new AdkSdkAdapter({ guardrailHooks, ...(model ? { model } : {}) });\n }\n case \"openai\": {\n const { OpenAIAgentsSdkAdapter } = await import(\"../adapters/openai-agents-sdk.js\");\n return new OpenAIAgentsSdkAdapter({ guardrailHooks, ...(model ? { model } : {}) });\n }\n default:\n throw new Error(`Unknown adapter: ${adapterName}. Available: mock, claude, gemini, openai`);\n }\n}\n\nfunction formatTable(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n const sep = widths.map((w) => \"-\".repeat(w)).join(\" \");\n const pad = (s: string, w: number) => s.padEnd(w);\n const headerLine = headers.map((h, i) => pad(h, widths[i])).join(\" \");\n const dataLines = rows.map((r) =>\n r.map((c, i) => pad(c ?? \"\", widths[i])).join(\" \"),\n );\n return [headerLine, sep, ...dataLines].join(\"\\n\");\n}\n\nfunction resolveProgressSink(\n cliLogFile: string | undefined,\n configLog: ResolvedProgressLog | undefined,\n quiet: boolean,\n label: string,\n): ProgressSink | undefined {\n if (cliLogFile) {\n return createProgressSink({\n stderr: !quiet,\n file: resolve(cliLogFile),\n naming: \"single\",\n label,\n });\n }\n\n if (configLog && configLog.destination !== \"none\") {\n const dest = configLog.destination;\n return createProgressSink({\n stderr: !quiet && (dest === \"stderr\" || dest === \"both\"),\n file: (dest === \"file\" || dest === \"both\") ? configLog.file : undefined,\n naming: configLog.naming,\n label,\n });\n }\n\n if (quiet) return undefined;\n return createProgressSink({ stderr: true });\n}\n\nconst handlers: CommandHandlers = {\n async init(options, _globalOpts) {\n try {\n const outputDir = resolve(options.output ?? \".\");\n const result = await runInit({\n adapter: options.adapter ?? \"mock\",\n outputDir,\n force: options.force ?? false,\n });\n console.log(JSON.stringify(result, null, 2));\n } catch (err) {\n console.error((err as Error).message);\n process.exit(1);\n }\n },\n\n async generate(options, globalOpts) {\n try {\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n const result = await generate({\n clean: options.clean,\n check: options.check,\n templates: options.templates,\n configPath,\n });\n\n if (result.check_mode) {\n if (result.has_differences) {\n console.error(\"Generated files are out of date. Run `agent-runtime generate` to update.\");\n process.exit(1);\n }\n console.log(JSON.stringify({ ...result, status: \"up-to-date\" }, null, 2));\n } else {\n console.log(JSON.stringify(result, null, 2));\n }\n } catch (err) {\n console.error(\"Generate failed:\", (err as Error).message);\n process.exit(1);\n }\n },\n\n async run(workflowId, userRequest, options, globalOpts) {\n // --- Resolve input: --file takes precedence over positional args ---\n let resolvedWorkflowId = workflowId;\n let resolvedUserRequest = userRequest;\n let fileInvocation: WorkflowInvocation | undefined;\n\n if (options.file) {\n try {\n const raw = readFileSync(options.file, \"utf8\");\n const parsed = YAML.parse(raw) as Record<string, unknown>;\n resolvedWorkflowId = parsed.workflow as string;\n if (!resolvedWorkflowId) {\n console.error(`Error: invocation file \"${options.file}\" must contain a \"workflow\" field.`);\n process.exit(3);\n }\n fileInvocation = {\n workflow: resolvedWorkflowId,\n user_request: parsed.user_request as string | undefined,\n handoff: parsed.handoff as WorkflowInvocation[\"handoff\"],\n runtime: parsed.runtime as WorkflowInvocation[\"runtime\"],\n context: parsed.context as WorkflowInvocation[\"context\"],\n };\n resolvedUserRequest = fileInvocation.user_request ?? \"\";\n } catch (err) {\n console.error(`Failed to read invocation file: ${(err as Error).message}`);\n process.exit(3);\n }\n }\n\n if (!resolvedWorkflowId) {\n console.error(\"Error: workflow-id is required (provide as argument or via --file)\");\n process.exit(3);\n }\n if (!fileInvocation && !resolvedUserRequest) {\n console.error(\"Error: user-request is required (provide as argument or via --file)\");\n process.exit(3);\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n\n const fresh = await checkFreshness(configPath);\n if (!fresh) {\n console.error(\"Generated files are stale or missing. Run `agent-runtime generate` first.\");\n process.exit(3);\n }\n\n const config = await loadConfig(configPath);\n\n const pluginResult = await loadPlugins({\n pluginPaths: config.pluginPaths.length > 0 ? config.pluginPaths : undefined,\n projectDir: config.configDir,\n });\n if (pluginResult.loaded > 0 && !(globalOpts.quiet as boolean)) {\n console.error(`Loaded ${pluginResult.loaded} plugin(s) from ${pluginResult.files.length} file(s)`);\n }\n for (const err of pluginResult.errors) {\n console.error(`Plugin load error (${err.file}): ${err.error}`);\n }\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n process.exit(1);\n return;\n }\n\n if (!contracts.workflowRegistry[resolvedWorkflowId]) {\n console.error(`Unknown workflow: ${resolvedWorkflowId}`);\n console.error(`Available workflows: ${Object.keys(contracts.workflowRegistry).join(\", \")}`);\n process.exit(3);\n return;\n }\n\n const useBoundResolver =\n config.artifactBinding || config.bindingPaths.length > 0;\n\n let registries: WorkflowRegistries = {\n workflowRegistry: contracts.workflowRegistry,\n taskRegistry: contracts.taskRegistry,\n agentRegistry: contracts.agentRegistry,\n handoffSchemas: contracts.handoffSchemas,\n };\n let guardrailHooks = contracts.guardrailHooks;\n\n if (useBoundResolver) {\n const { BoundResolver } = await import(\"../lib/bound-resolver.js\");\n const { buildGuardrailRulesFromDsl } = await import(\"../lib/dsl-context.js\");\n\n const embeddedDsl = contracts.resolvedDsl ?? (resolvedDsl as Record<string, unknown>);\n const component = await new BoundResolver().resolve({\n id: config.configDir,\n embeddedDsl,\n bindingPaths: config.bindingPaths.length > 0 ? config.bindingPaths : undefined,\n activeGuardrailPolicy: config.active_guardrail_policy,\n artifactBinding: config.artifactBinding,\n paths: config.paths,\n });\n\n registries = component.registries;\n\n const rules = buildGuardrailRulesFromDsl(component.dsl);\n if (\n rules &&\n (rules.commandRules.length > 0 ||\n rules.fileRules.length > 0 ||\n rules.contentRules.length > 0)\n ) {\n guardrailHooks = createGuardrailHooksFromRules(rules);\n } else if (component.guardrails.perAgent.size > 0) {\n const firstRules = component.guardrails.perAgent.values().next().value;\n if (firstRules) {\n guardrailHooks = createGuardrailHooksFromRules(firstRules);\n }\n }\n }\n\n const adapterName = (options.adapter as string) ?? \"mock\";\n const adapterCwd = fileInvocation?.context?.cwd ?? process.cwd();\n\n const { createModelResolver } = await import(\"../lib/model-resolver.js\");\n type ModelClassType = import(\"../lib/model-resolver.js\").ModelClass;\n const modelResolver = createModelResolver({\n modelMapping: config.model_mapping,\n fallbackAdapter: adapterName,\n });\n\n const adapterCache = new Map<string, SdkAdapter>();\n const modelAwareFactory = async (modelClass?: ModelClassType): Promise<SdkAdapter> => {\n const resolved = modelResolver.resolve(modelClass);\n const cacheKey = `${resolved.adapter}:${resolved.model ?? \"\"}`;\n const cached = adapterCache.get(cacheKey);\n if (cached) return cached;\n const adapter = await createAdapter(resolved.adapter, guardrailHooks, adapterCwd, resolved.model);\n adapterCache.set(cacheKey, adapter);\n return adapter;\n };\n\n let defaultAdapter: SdkAdapter;\n try {\n defaultAdapter = await modelAwareFactory();\n } catch (err) {\n console.error((err as Error).message);\n process.exit(12);\n return;\n }\n\n const hasModelMapping = Object.values(config.model_mapping).some(Boolean)\n || process.env.AGENT_RUNTIME_MODEL\n || process.env.AGENT_RUNTIME_MODEL_FAST\n || process.env.AGENT_RUNTIME_MODEL_STANDARD\n || process.env.AGENT_RUNTIME_MODEL_THINKING;\n\n const adapterOrFactory = hasModelMapping ? modelAwareFactory : defaultAdapter;\n\n const recovery = config.recovery;\n const maxRetries = options.maxRetries\n ? parseInt(options.maxRetries, 10)\n : undefined;\n const maxFollowUps = options.maxFollowUps\n ? parseInt(options.maxFollowUps, 10)\n : undefined;\n\n const onGate = options.autoApproveGates\n ? async () => true\n : async (gateKind: string, description: string) => {\n console.error(`Gate \"${gateKind}\": ${description}`);\n console.error(\"Use --auto-approve-gates to auto-approve. Rejecting by default.\");\n return false;\n };\n\n const progressSink = resolveProgressSink(\n options.logFile as string | undefined,\n config.resolvedLogging.progressLog,\n globalOpts.quiet as boolean,\n resolvedWorkflowId,\n );\n\n let result;\n try {\n if (fileInvocation) {\n const invocation: WorkflowInvocation = {\n ...fileInvocation,\n runtime: {\n ...fileInvocation.runtime,\n maxFollowUps: maxFollowUps ?? fileInvocation.runtime?.maxFollowUps ?? recovery.max_follow_ups,\n maxRetries: maxRetries ?? fileInvocation.runtime?.maxRetries ?? recovery.max_retries,\n },\n hooks: { onGate },\n progressOutput: progressSink,\n };\n result = await runWorkflow(adapterOrFactory, invocation, registries);\n } else {\n result = await runWorkflow(adapterOrFactory, resolvedWorkflowId, {\n user_request: resolvedUserRequest!,\n maxRetries: maxRetries ?? recovery.max_retries,\n maxFollowUps: maxFollowUps ?? recovery.max_follow_ups,\n onGate,\n progressOutput: progressSink,\n }, registries);\n }\n } finally {\n progressSink?.close();\n }\n\n console.log(JSON.stringify(result, null, 2));\n\n if (result.status !== \"completed\") {\n process.exit(1);\n }\n },\n\n async list(resource, options, globalOpts) {\n if (!resource) {\n console.error(\"Error: resource is required (workflows, tasks, agents)\");\n process.exit(1);\n }\n\n const validResources = [\"workflows\", \"tasks\", \"agents\"];\n if (!validResources.includes(resource)) {\n console.error(`Unknown resource: ${resource}`);\n console.error(`Available resources: ${validResources.join(\", \")}`);\n process.exit(1);\n return;\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n console.error(\"Run `agent-runtime generate` first.\");\n process.exit(1);\n return;\n }\n\n const format = options.format ?? \"table\";\n\n if (resource === \"agents\") {\n const agents = Object.values(contracts.agentRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(agents, null, 2));\n } else {\n if (agents.length === 0) {\n console.log(\"No agents defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Role\", \"Mode\", \"Purpose\"],\n agents.map((a) => [a.id, a.role_name, a.mode, a.purpose]),\n ));\n }\n } else if (resource === \"tasks\") {\n const tasks = Object.values(contracts.taskRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(tasks, null, 2));\n } else {\n if (tasks.length === 0) {\n console.log(\"No tasks defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Agent\", \"Description\"],\n tasks.map((t) => [t.id, t.target_agent, t.description]),\n ));\n }\n } else {\n const workflows = Object.values(contracts.workflowRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(workflows, null, 2));\n } else {\n if (workflows.length === 0) {\n console.log(\"No workflows defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Steps\", \"Description\"],\n workflows.map((w) => [w.id, String(w.steps.length), w.description]),\n ));\n }\n }\n },\n\n async showPrompt(taskId, options, globalOpts) {\n if (!taskId) {\n console.error(\"Error: task-id is required\");\n process.exit(1);\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n console.error(\"Run `agent-runtime generate` first.\");\n process.exit(1);\n return;\n }\n\n const task = contracts.taskRegistry[taskId];\n if (!task) {\n console.error(`Unknown task: ${taskId}`);\n console.error(`Available tasks: ${Object.keys(contracts.taskRegistry).join(\", \")}`);\n process.exit(1);\n return;\n }\n\n const agent = contracts.agentRegistry[task.target_agent];\n if (!agent) {\n console.error(`Unknown agent: ${task.target_agent} (referenced by task ${taskId})`);\n process.exit(1);\n return;\n }\n\n const showPromptConfig = await loadConfig(configPath);\n const pluginsApplied = options.withPlugins ?? false;\n if (pluginsApplied) {\n await loadPlugins({\n pluginPaths: showPromptConfig.pluginPaths.length > 0 ? showPromptConfig.pluginPaths : undefined,\n projectDir: showPromptConfig.configDir,\n });\n }\n\n const userRequest = options.userRequest ?? \"(preview)\";\n let context: TaskContext = { user_request: userRequest };\n\n if (pluginsApplied) {\n const modified = await pluginRegistry.runBeforeTask(taskId, context);\n if (modified === null) {\n console.error(`Task \"${taskId}\" skipped by plugin`);\n process.exit(1);\n return;\n }\n context = pluginRegistry.applyContextEnhancers(taskId, modified);\n }\n\n let prompt = buildTaskPrompt(agent, task, context, {\n handoffSchemas: contracts.handoffSchemas,\n });\n\n if (pluginsApplied) {\n prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, context);\n }\n\n const format = options.format ?? \"markdown\";\n if (format === \"json\") {\n console.log(JSON.stringify({\n task_id: taskId,\n agent_id: task.target_agent,\n prompt,\n handoff_schema: task.result_handoff,\n plugins_applied: pluginsApplied,\n }, null, 2));\n } else {\n console.log(prompt);\n }\n },\n\n async implement(description, options, globalOpts) {\n if (!description) {\n console.error(\"Error: description is required\");\n process.exit(3);\n }\n\n const quiet = globalOpts.quiet as boolean;\n const progressSink = options.logFile\n ? createProgressSink({ stderr: !quiet, file: resolve(options.logFile), naming: \"single\" })\n : quiet ? undefined : createProgressSink({ stderr: true });\n\n let result;\n try {\n result = await runImplement(description, {\n adapter: options.adapter ?? \"claude\",\n projectDir: options.projectDir ?? \".\",\n dryRun: options.dryRun ?? false,\n model: options.model as string | undefined,\n reportFormat: (options.reportFormat as \"json\" | \"text\" | \"yaml\") ?? \"text\",\n progressOutput: progressSink,\n });\n } finally {\n progressSink?.close();\n }\n\n if (result.status === \"failed\") {\n if (options.reportFormat === \"json\") {\n console.log(JSON.stringify({ error: result.error, status: \"failed\" }, null, 2));\n } else if (options.reportFormat === \"yaml\") {\n console.log(YAML.stringify({ error: result.error, status: \"failed\" }));\n } else {\n console.error(formatImplementResult(result));\n }\n process.exit(result.exitCode ?? 1);\n }\n\n const outputData = result.data ?? { status: result.status };\n let output: string;\n if (options.reportFormat === \"json\") {\n output = JSON.stringify(outputData, null, 2);\n } else if (options.reportFormat === \"yaml\") {\n output = YAML.stringify(outputData);\n } else {\n output = formatImplementResult(result);\n }\n\n const outputPath = options.output as string | undefined;\n if (outputPath) {\n writeFileSync(outputPath, output + \"\\n\");\n } else {\n console.log(output);\n }\n },\n\n async auditImplementation(projectDir, options, globalOpts) {\n const quiet = globalOpts.quiet as boolean;\n const progressSink = options.logFile\n ? createProgressSink({ stderr: !quiet, file: resolve(options.logFile), naming: \"single\" })\n : quiet ? undefined : createProgressSink({ stderr: true });\n\n let result;\n try {\n result = await runAuditImplementation({\n adapter: options.adapter ?? \"claude\",\n projectDir: projectDir ?? \".\",\n focus: (options.focus as \"all\" | \"dsl\" | \"runtime\" | \"cli-contract\" | \"architecture\") ?? \"all\",\n dryRun: options.dryRun ?? false,\n failOn: (options.failOn as \"warning\" | \"error\" | \"critical\") ?? \"error\",\n model: options.model as string | undefined,\n reportFormat: (options.reportFormat as \"json\" | \"text\" | \"yaml\") ?? \"text\",\n progressOutput: progressSink,\n });\n } finally {\n progressSink?.close();\n }\n\n if (result.status === \"failed\") {\n if (options.reportFormat === \"json\") {\n console.log(JSON.stringify({ error: result.error, status: \"failed\" }, null, 2));\n } else if (options.reportFormat === \"yaml\") {\n console.log(YAML.stringify({ error: result.error, status: \"failed\" }));\n } else {\n console.error(formatAuditResult(result));\n }\n process.exit(result.exitCode);\n }\n\n const outputData = result.data ?? { status: result.status };\n let output: string;\n if (options.reportFormat === \"json\") {\n output = JSON.stringify(outputData, null, 2);\n } else if (options.reportFormat === \"yaml\") {\n output = YAML.stringify(outputData);\n } else {\n output = formatAuditResult(result);\n }\n\n const outputPath = options.output as string | undefined;\n if (outputPath) {\n writeFileSync(outputPath, output + \"\\n\");\n } else {\n console.log(output);\n }\n\n if (result.exitCode !== 0) {\n process.exit(result.exitCode);\n }\n },\n\n async agents(options, _globalOpts) {\n const format = options.format ?? \"yaml\";\n try {\n if (format === \"json\") {\n console.log(JSON.stringify(resolvedDsl, null, 2));\n } else {\n console.log(YAML.stringify(resolvedDsl, { lineWidth: 120 }));\n }\n } catch (err) {\n console.error(`Failed to output DSL: ${(err as Error).message}`);\n process.exit(1);\n }\n },\n\n async doctor(globalOpts) {\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n const result = await runDoctor(configPath);\n\n const statusIcon = (s: string) =>\n s === \"pass\" ? \"✓\" : s === \"warn\" ? \"!\" : \"✗\";\n\n for (const check of result.checks) {\n const icon = statusIcon(check.status);\n const msg = check.message ? ` ${check.message}` : \"\";\n console.log(` ${icon} ${check.name.padEnd(20)} ${check.status.toUpperCase()}${msg}`);\n }\n\n console.log(\"\");\n if (result.all_passed) {\n console.log(\"All checks passed.\");\n } else {\n console.log(\"Some checks failed.\");\n }\n\n console.log(JSON.stringify(result));\n\n if (!result.all_passed) {\n process.exitCode = 1;\n }\n },\n\n async navigationIndex(options, globalOpts) {\n const configPath = (globalOpts.config as string) ?? \"./agents.conf.yaml\";\n const format = options.format ?? \"json\";\n\n try {\n const config = await loadConfig(configPath);\n\n let dsl: Record<string, unknown> = resolvedDsl as Record<string, unknown>;\n\n if (config.dsl !== \"embedded\" && existsSync(config.dslPath)) {\n const { resolve: resolveDslFn } = await import(\"agent-contracts\");\n const resolved = await resolveDslFn(config.dslPath);\n dsl = resolved.data;\n }\n\n if (config.artifactBinding) {\n const { resolveBound } = await import(\"agent-contracts\");\n const boundResult = await resolveBound(dsl, {\n artifactBinding: config.artifactBinding,\n paths: config.paths,\n });\n dsl = boundResult.data;\n }\n\n const { buildNavigationIndex, validateSchema } = await import(\"agent-contracts\");\n\n const schemaResult = validateSchema(dsl);\n if (!schemaResult.success) {\n const issues = schemaResult.diagnostics.map((d) => ` ${d.path}: ${d.message}`).join(\"\\n\");\n console.error(`Schema validation failed:\\n${issues}`);\n process.exit(1);\n }\n\n let index = buildNavigationIndex(schemaResult.data!);\n\n if (options.artifact) {\n const node = index.artifacts[options.artifact];\n if (!node) {\n console.error(`Artifact not found: ${options.artifact}`);\n process.exit(1);\n }\n index = { ...index, artifacts: { [options.artifact]: node } };\n }\n\n const output = format === \"json\"\n ? JSON.stringify(index, null, 2)\n : YAML.stringify(index, { lineWidth: 120 });\n\n if (options.output) {\n writeFileSync(options.output, output + \"\\n\");\n } else {\n console.log(output);\n }\n } catch (err) {\n console.error(`Failed to build navigation index: ${(err as Error).message}`);\n process.exit(1);\n }\n },\n\n};\n\nconst program = createProgram(handlers, VERSION);\nawait program.parseAsync();\n","// Auto-generated by cli-contracts. Do not edit.\nimport { Command } from \"commander\";\nimport { CONTRACT_YAML, CONTRACT_JSON_STR } from \"./contract.js\";\n\nexport interface CommandHandlers {\n init: (options: { adapter?: string; output?: string; force?: boolean; showPrompt?: boolean }, parentOpts: Record<string, unknown>) => Promise<void | string>;\n generate: (options: { clean?: boolean; check?: boolean; templates?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n run: (workflowId: string | undefined, userRequest: string | undefined, options: { adapter?: string; maxRetries?: string; maxFollowUps?: string; dryRun?: boolean; autoApproveGates?: boolean; file?: string; logFile?: string; showPrompt?: boolean }, parentOpts: Record<string, unknown>) => Promise<void | string>;\n list: (resource: string | undefined, options: { format?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n showPrompt: (taskId: string | undefined, options: { userRequest?: string; format?: string; withPlugins?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n implement: (description: string | undefined, options: { adapter?: string; projectDir?: string; dryRun?: boolean; model?: string; output?: string; reportFormat?: string; logFile?: string; showPrompt?: boolean }, parentOpts: Record<string, unknown>) => Promise<void | string>;\n auditImplementation: (projectDir: string | undefined, options: { adapter?: string; focus?: string; dryRun?: boolean; failOn?: string; model?: string; output?: string; reportFormat?: string; logFile?: string; showPrompt?: boolean }, parentOpts: Record<string, unknown>) => Promise<void | string>;\n agents: (options: { format?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n doctor: (options: Record<string, never>, parentOpts: Record<string, unknown>) => Promise<void>;\n navigationIndex: (options: { format?: string; artifact?: string; output?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n}\n\nexport function createProgram(\n handlers: CommandHandlers,\n version: string,\n): Command {\n const program = new Command();\n program\n .name(\"agent-runtime\")\n .version(version, \"-V, --version\")\n .description(\"CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\");\n\n program.option(\"-c, --config <value>\", \"Path to agents.conf.yaml (project runtime config).\", \"./agents.conf.yaml\");\n program.option(\"-v, --verbose\", \"Enable verbose output.\", false);\n program.option(\"-q, --quiet\", \"Suppress non-error output.\", false);\n\n program\n .command(\"init\")\n .description(\"Initialize runtime scaffolding for a project.\")\n .option(\"-a, --adapter <value>\", \"Default SDK adapter to configure.\", \"mock\")\n .option(\"-o, --output <value>\", \"Output directory for generated scaffolding.\", \".\")\n .option(\"-f, --force\", \"Overwrite existing files without prompting.\", false)\n .option(\"--show-prompt\", \"Output the constructed prompt without calling the LLM API.\", false)\n .action(async (opts, cmd) => {\n if (opts.showPrompt) {\n const prompt = await handlers.init(opts, cmd.optsWithGlobals());\n if (typeof prompt === \"string\") process.stdout.write(prompt + \"\\n\");\n return;\n }\n await handlers.init(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"generate\")\n .description(\"Generate runtime contracts and hooks from DSL.\")\n .option(\"--clean\", \"Delete generated_dir before regenerating.\\nRemoves stale files that may remain from previous generations.\\n\", false)\n .option(\"--check\", \"Dry-run mode for CI. Does not write files.\\nCompares current generated output with what would be regenerated.\\nExits with code 1 if any differences are found.\\n\", false)\n .option(\"-t, --templates <value>\", \"Custom templates directory. Overrides built-in templates.\")\n .action(async (opts, cmd) => {\n await handlers.generate(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"run\")\n .description(\"Execute a workflow.\")\n .argument(\"[workflow-id]\", \"ID of the workflow to execute. Required unless --file is used.\")\n .argument(\"[user-request]\", \"Natural language description of what to do. Required unless --file is used.\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use. Overrides config.\")\n .option(\"-r, --max-retries <value>\", \"Override default max retries per step.\")\n .option(\"-f, --max-follow-ups <value>\", \"Override default max follow-ups per step.\")\n .option(\"-n, --dry-run\", \"Simulate execution without calling the SDK adapter.\", false)\n .option(\"--auto-approve-gates\", \"Automatically approve all gate steps.\", false)\n .option(\"--file <value>\", \"Path to a YAML invocation file. When provided, workflow-id and\\nuser-request arguments are read from the file instead of CLI args.\\n\")\n .option(\"-l, --log-file <value>\", \"Write agent progress log to this file. Overrides config logging.progress_log.\")\n .option(\"--show-prompt\", \"Output the constructed prompt without calling the LLM API.\", false)\n .action(async (workflowId, userRequest, opts, cmd) => {\n if (opts.showPrompt) {\n const prompt = await handlers.run(workflowId, userRequest, opts, cmd.optsWithGlobals());\n if (typeof prompt === \"string\") process.stdout.write(prompt + \"\\n\");\n return;\n }\n await handlers.run(workflowId, userRequest, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"list\")\n .description(\"List available workflows, tasks, or agents.\")\n .argument(\"<resource>\", \"Type of resource to list.\")\n .option(\"--format <value>\", \"Output format.\", \"table\")\n .action(async (resource, opts, cmd) => {\n await handlers.list(resource, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"show-prompt\")\n .description(\"Display the generated prompt for a task.\")\n .argument(\"<task-id>\", \"ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).\")\n .option(\"-u, --user-request <value>\", \"User request text to include in the prompt preview.\", \"(preview)\")\n .option(\"--format <value>\", \"Output format.\", \"markdown\")\n .option(\"--with-plugins\", \"Apply registered plugin prompt enhancers to the output.\", false)\n .action(async (taskId, opts, cmd) => {\n await handlers.showPrompt(taskId, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"implement\")\n .description(\"Implement LLM-powered commands in a CLI tool.\")\n .argument(\"<description>\", \"Natural language description of the LLM feature(s) to implement. Examples: \\\"Add an audit command for migration safety\\\", \\\"Add propose and explain commands for SQL optimization\\\".\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use. Must be an agentic adapter (claude).\", \"claude\")\n .option(\"-p, --project-dir <value>\", \"Path to the target project directory.\", \".\")\n .option(\"-n, --dry-run\", \"Output the prompt context without calling the LLM.\", false)\n .option(\"--model <value>\", \"Model name override for the selected adapter.\")\n .option(\"-o, --output <value>\", \"Write the result to a file instead of stdout.\")\n .option(\"--report-format <value>\", \"Output format for the result.\", \"text\")\n .option(\"-l, --log-file <value>\", \"Write agent progress log to this file.\")\n .option(\"--show-prompt\", \"Output the constructed prompt without calling the LLM API.\", false)\n .action(async (description, opts, cmd) => {\n if (opts.showPrompt) {\n const prompt = await handlers.implement(description, opts, cmd.optsWithGlobals());\n if (typeof prompt === \"string\") process.stdout.write(prompt + \"\\n\");\n return;\n }\n await handlers.implement(description, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"audit-implementation\")\n .description(\"Audit an LLM command integration for pattern conformance.\")\n .argument(\"[project-dir]\", \"Path to the project directory to audit. Defaults to current directory.\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use for the audit agent.\", \"claude\")\n .option(\"--focus <value>\", \"Limit audit to a specific layer. Defaults to all layers.\", \"all\")\n .option(\"-n, --dry-run\", \"Output the prompt context without calling the LLM.\", false)\n .option(\"--fail-on <value>\", \"Minimum finding severity that causes a non-zero exit.\", \"error\")\n .option(\"--model <value>\", \"Model name override for the selected adapter.\")\n .option(\"-o, --output <value>\", \"Write the result to a file instead of stdout.\")\n .option(\"--report-format <value>\", \"Output format for the audit report.\", \"text\")\n .option(\"-l, --log-file <value>\", \"Write agent progress log to this file.\")\n .option(\"--show-prompt\", \"Output the constructed prompt without calling the LLM API.\", false)\n .action(async (projectDir, opts, cmd) => {\n if (opts.showPrompt) {\n const prompt = await handlers.auditImplementation(projectDir, opts, cmd.optsWithGlobals());\n if (typeof prompt === \"string\") process.stdout.write(prompt + \"\\n\");\n return;\n }\n await handlers.auditImplementation(projectDir, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"agents\")\n .description(\"Output the full resolved DSL as structured data.\")\n .option(\"-F, --format <value>\", \"Output format.\", \"yaml\")\n .action(async (opts, cmd) => {\n await handlers.agents(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"doctor\")\n .description(\"Verify configuration, generated files, and SDK connectivity.\")\n .action(async (opts, cmd) => {\n await handlers.doctor({}, cmd.optsWithGlobals());\n });\n\n program\n .command(\"navigation-index\")\n .description(\"Build artifact navigation index from resolved DSL.\")\n .option(\"-F, --format <value>\", \"Output format.\", \"json\")\n .option(\"--artifact <value>\", \"Filter output to a single artifact by ID.\")\n .option(\"-o, --output <value>\", \"Write output to a file instead of stdout.\")\n .action(async (opts, cmd) => {\n await handlers.navigationIndex(opts, cmd.optsWithGlobals());\n });\n\n\n // Built-in extract command (auto-injected by cli-contracts)\n program\n .command(\"extract\")\n .description(\"Extract contract specification for this CLI tool.\")\n .argument(\"[commands...]\", \"Command IDs to extract. Use dot notation.\")\n .option(\"-a, --all\", \"Extract all commands.\", false)\n .option(\"--include-meta\", \"Include extraction metadata.\", true)\n .option(\"-F, --format <format>\", \"Output format (yaml or json).\", \"yaml\")\n .action(async (commands: string[], opts: { all?: boolean; includeMeta?: boolean; format?: string }, cmd: Command) => {\n if (commands.length === 0 && !opts.all) {\n process.stderr.write(JSON.stringify({ code: \"INVALID_ARGS\", message: \"Specify command IDs or use --all\" }) + \"\\n\");\n process.exit(2);\n }\n\n const format = opts.format || \"yaml\";\n const doc = JSON.parse(CONTRACT_JSON_STR);\n const cmdIds = opts.all ? [] : commands;\n\n if (cmdIds.length === 0) {\n // --all: output full contract\n if (format === \"json\") {\n const out: Record<string, unknown> = {};\n if (opts.includeMeta) {\n out._meta = {\n source: \"embedded\",\n type: \"cli-contracts/extract\",\n extractedAt: new Date().toISOString(),\n specVersion: doc.cli_contracts ?? \"0.1.0\",\n commands: [\"agent-runtime.init\",\"agent-runtime.generate\",\"agent-runtime.run\",\"agent-runtime.list\",\"agent-runtime.show-prompt\",\"agent-runtime.implement\",\"agent-runtime.audit-implementation\",\"agent-runtime.agents\",\"agent-runtime.doctor\",\"agent-runtime.navigation-index\"],\n };\n }\n Object.assign(out, doc);\n process.stdout.write(JSON.stringify(out, null, 2) + \"\\n\");\n } else {\n // YAML output\n const yamlLines: string[] = [];\n yamlLines.push(\"# agent-runtime extract\");\n yamlLines.push(\"# source: embedded\");\n yamlLines.push(\"# type: cli-contracts/command-extract\");\n if (opts.includeMeta) {\n yamlLines.push(\"---\");\n yamlLines.push(\"source: embedded\");\n yamlLines.push(\"type: cli-contracts/command-extract\");\n yamlLines.push(\"extractedAt: \" + new Date().toISOString());\n yamlLines.push(\"spec_version: \" + (doc.cli_contracts ?? \"0.1.0\"));\n yamlLines.push(\"commands:\");\n for (const id of [\"agent-runtime.init\",\"agent-runtime.generate\",\"agent-runtime.run\",\"agent-runtime.list\",\"agent-runtime.show-prompt\",\"agent-runtime.implement\",\"agent-runtime.audit-implementation\",\"agent-runtime.agents\",\"agent-runtime.doctor\",\"agent-runtime.navigation-index\"]) {\n yamlLines.push(\" - \" + id);\n }\n }\n yamlLines.push(\"---\");\n yamlLines.push(CONTRACT_YAML);\n process.stdout.write(yamlLines.join(\"\\n\") + \"\\n\");\n }\n } else {\n // Filter specific commands\n const filtered: Record<string, unknown> = {\n cli_contracts: doc.cli_contracts,\n info: doc.info,\n command_sets: {},\n };\n const fcs = filtered.command_sets as Record<string, Record<string, unknown>>;\n for (const [setId, cs] of Object.entries(doc.command_sets ?? {})) {\n const cmds = (cs as Record<string, unknown>).commands as Record<string, unknown> | undefined;\n if (!cmds) continue;\n const matched: Record<string, unknown> = {};\n for (const [cmdId, cmdDef] of Object.entries(cmds)) {\n const fullId = setId + \".\" + cmdId;\n if (cmdIds.some((id) => id === cmdId || id === fullId || cmdId.startsWith(id + \".\"))) {\n matched[cmdId] = cmdDef;\n }\n }\n if (Object.keys(matched).length > 0) {\n const setCopy = { ...(cs as Record<string, unknown>) };\n setCopy.commands = matched;\n fcs[setId] = setCopy;\n }\n }\n if (doc.components) filtered.components = doc.components;\n process.stdout.write(JSON.stringify(filtered, null, 2) + \"\\n\");\n }\n process.exit(0);\n });\n return program;\n}\n","// Auto-generated by cli-contracts. Do not edit.\n// Embedded contract for the extract subcommand.\n\nexport const CONTRACT_YAML: string = \"cli_contracts: 0.1.0\\n\\ninfo:\\n title: agent-runtime CLI\\n version: 0.36.0\\n description: |\\n Runtime bridge for executing agent-contracts workflows on Agent SDKs.\\n Generates typed contracts, handoff validators, and guardrail hooks from DSL,\\n then runs workflows through pluggable SDK adapters.\\n license:\\n name: MIT\\n\\ncommand_sets:\\n agent-runtime:\\n summary: CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\\n global_options:\\n - name: config\\n aliases: [c]\\n description: Path to agents.conf.yaml (project runtime config).\\n schema:\\n type: string\\n default: ./agents.conf.yaml\\n file:\\n mode: read\\n exists: true\\n media_type: application/yaml\\n\\n - name: verbose\\n aliases: [v]\\n description: Enable verbose output.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: quiet\\n aliases: [q]\\n description: Suppress non-error output.\\n schema:\\n type: boolean\\n default: false\\n\\n commands:\\n # -----------------------------------------------------------------------\\n # init\\n # -----------------------------------------------------------------------\\n init:\\n summary: Initialize runtime scaffolding for a project.\\n description: |\\n Generates the initial directory structure and configuration files\\n for using agent-contracts-runtime in a project.\\n Creates agents.conf.yaml and agent/src/ user code templates.\\n options:\\n - name: adapter\\n aliases: [a]\\n description: Default SDK adapter to configure.\\n schema:\\n type: string\\n enum: [claude, gemini, openai, mock]\\n default: mock\\n\\n - name: output\\n aliases: [o]\\n description: Output directory for generated scaffolding.\\n schema:\\n type: string\\n default: \\\".\\\"\\n\\n - name: force\\n aliases: [f]\\n description: Overwrite existing files without prompting.\\n schema:\\n type: boolean\\n default: false\\n\\n exits:\\n \\\"0\\\":\\n description: Scaffolding generated successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/InitResult\\\"\\n\\n \\\"1\\\":\\n description: Initialization failed (existing files, permission error, etc.).\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: false\\n sideEffects:\\n - filesystem_write\\n safeDryRunOption: \\\"\\\"\\n\\n # -----------------------------------------------------------------------\\n # generate\\n # -----------------------------------------------------------------------\\n generate:\\n summary: Generate runtime contracts and hooks from DSL.\\n description: |\\n Reads agent-contracts.yaml, resolves the DSL, validates it,\\n and generates typed contracts, handoff schemas, guardrail hooks,\\n and a runtime manifest into the configured generated_dir.\\n\\n Each generated file includes a DO NOT EDIT header.\\n options:\\n - name: clean\\n description: |\\n Delete generated_dir before regenerating.\\n Removes stale files that may remain from previous generations.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: check\\n description: |\\n Dry-run mode for CI. Does not write files.\\n Compares current generated output with what would be regenerated.\\n Exits with code 1 if any differences are found.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: templates\\n aliases: [t]\\n description: Custom templates directory. Overrides built-in templates.\\n schema:\\n type: string\\n\\n exits:\\n \\\"0\\\":\\n description: Generation completed successfully (or --check found no differences).\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/GenerateResult\\\"\\n\\n \\\"1\\\":\\n description: |\\n Generation failed, or --check detected differences between\\n current generated files and expected output.\\n stderr:\\n format: text\\n\\n \\\"2\\\":\\n description: DSL validation error. The input DSL has structural or semantic issues.\\n stderr:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/ValidationError\\\"\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects:\\n - filesystem_write\\n safeDryRunOption: check\\n\\n # -----------------------------------------------------------------------\\n # run\\n # -----------------------------------------------------------------------\\n run:\\n summary: Execute a workflow.\\n description: |\\n Loads generated contracts, creates an SDK adapter, registers user plugins,\\n and executes the specified workflow with the given user request.\\n\\n The workflow runner orchestrates task delegation, retry, gate handling,\\n and handoff validation mechanically.\\n arguments:\\n - name: workflow-id\\n required: false\\n description: ID of the workflow to execute. Required unless --file is used.\\n schema:\\n type: string\\n\\n - name: user-request\\n required: false\\n description: Natural language description of what to do. Required unless --file is used.\\n schema:\\n type: string\\n\\n options:\\n - name: adapter\\n aliases: [a]\\n description: SDK adapter to use. Overrides config.\\n schema:\\n type: string\\n enum: [claude, gemini, openai, mock]\\n\\n - name: max-retries\\n aliases: [r]\\n description: Override default max retries per step.\\n schema:\\n type: integer\\n minimum: 0\\n maximum: 10\\n\\n - name: max-follow-ups\\n aliases: [f]\\n description: Override default max follow-ups per step.\\n schema:\\n type: integer\\n minimum: 0\\n maximum: 10\\n\\n - name: dry-run\\n aliases: [n]\\n description: Simulate execution without calling the SDK adapter.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: auto-approve-gates\\n description: Automatically approve all gate steps.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: file\\n description: |\\n Path to a YAML invocation file. When provided, workflow-id and\\n user-request arguments are read from the file instead of CLI args.\\n schema:\\n type: string\\n file:\\n mode: read\\n exists: true\\n media_type: application/yaml\\n\\n - name: log-file\\n aliases: [l]\\n description: Write agent progress log to this file. Overrides config logging.progress_log.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n exits:\\n \\\"0\\\":\\n description: Workflow completed successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/WorkflowResult\\\"\\n\\n \\\"1\\\":\\n description: Workflow failed (escalation, error, or gate rejection).\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/WorkflowResult\\\"\\n stderr:\\n format: text\\n\\n \\\"3\\\":\\n description: >-\\n Input validation failed (invalid arguments, unknown workflow/adapter,\\n or generated files outdated).\\n stderr:\\n format: text\\n\\n \\\"12\\\":\\n description: Adapter initialization error (missing API key, etc.).\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: high\\n requiresConfirmation: true\\n idempotent: false\\n sideEffects:\\n - sdk_call\\n - filesystem_write\\n safeDryRunOption: dry-run\\n expectedDurationMs: 300000\\n recommendedBeforeUse:\\n - Run `agent-runtime generate --check` to ensure contracts are up to date.\\n - Run `agent-runtime doctor` to verify SDK configuration.\\n\\n # -----------------------------------------------------------------------\\n # list\\n # -----------------------------------------------------------------------\\n list:\\n summary: List available workflows, tasks, or agents.\\n description: |\\n Reads generated contracts and displays available resources.\\n Useful for discovering what workflows, tasks, and agents\\n are defined in the current project.\\n arguments:\\n - name: resource\\n required: true\\n description: Type of resource to list.\\n schema:\\n type: string\\n enum: [workflows, tasks, agents]\\n\\n options:\\n - name: format\\n description: Output format.\\n schema:\\n type: string\\n enum: [table, json]\\n default: table\\n\\n exits:\\n \\\"0\\\":\\n description: Resources listed successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/ListResult\\\"\\n\\n \\\"1\\\":\\n description: Failed to load contracts.\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: []\\n\\n # -----------------------------------------------------------------------\\n # show-prompt\\n # -----------------------------------------------------------------------\\n show-prompt:\\n summary: Display the generated prompt for a task.\\n description: |\\n Builds and displays the full prompt that would be sent to an SDK agent\\n for a given task. Useful for inspecting, debugging, and validating\\n prompt content before execution.\\n\\n Shows the agent role, responsibilities, constraints, task details,\\n completion criteria, handoff schema fields, and output format example.\\n arguments:\\n - name: task-id\\n required: true\\n description: ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).\\n schema:\\n type: string\\n\\n options:\\n - name: user-request\\n aliases: [u]\\n description: User request text to include in the prompt preview.\\n schema:\\n type: string\\n default: \\\"(preview)\\\"\\n\\n - name: format\\n description: Output format.\\n schema:\\n type: string\\n enum: [markdown, raw, json]\\n default: markdown\\n\\n - name: with-plugins\\n description: Apply registered plugin prompt enhancers to the output.\\n schema:\\n type: boolean\\n default: false\\n\\n exits:\\n \\\"0\\\":\\n description: Prompt displayed successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/ShowPromptResult\\\"\\n\\n \\\"1\\\":\\n description: Failed to build prompt (unknown task, missing contracts, etc.).\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: []\\n\\n # -----------------------------------------------------------------------\\n # implement\\n # -----------------------------------------------------------------------\\n implement:\\n summary: Implement LLM-powered commands in a CLI tool.\\n description: |\\n Uses an agentic LLM adapter (Claude, etc.) to analyze the\\n target project and implement LLM-powered commands following the\\n agent-contracts + agent-contracts-runtime + cli-contracts stack.\\n\\n The agent reads the project structure, cli-contract.yaml, and existing\\n code, then generates DSL definitions, TypeScript modules (orchestrator,\\n context-builder, formatter), CLI command handlers, and updates the\\n CLI contract with x-agent metadata.\\n\\n Requires an agentic adapter that supports tool use (file read/write).\\n arguments:\\n - name: description\\n required: true\\n description: >-\\n Natural language description of the LLM feature(s) to implement.\\n Examples: \\\"Add an audit command for migration safety\\\",\\n \\\"Add propose and explain commands for SQL optimization\\\".\\n schema:\\n type: string\\n\\n options:\\n - name: adapter\\n aliases: [a]\\n description: SDK adapter to use. Must be an agentic adapter (claude).\\n schema:\\n type: string\\n enum: [claude, mock]\\n default: claude\\n\\n - name: project-dir\\n aliases: [p]\\n description: Path to the target project directory.\\n schema:\\n type: string\\n default: \\\".\\\"\\n\\n - name: dry-run\\n aliases: [n]\\n description: Output the prompt context without calling the LLM.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: model\\n description: Model name override for the selected adapter.\\n schema:\\n type: string\\n\\n - name: output\\n aliases: [o]\\n description: Write the result to a file instead of stdout.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n - name: report-format\\n description: Output format for the result.\\n schema:\\n type: string\\n enum: [json, text, yaml]\\n default: text\\n\\n - name: log-file\\n aliases: [l]\\n description: Write agent progress log to this file.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n exits:\\n \\\"0\\\":\\n description: Implementation completed successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/ImplementResult\\\"\\n\\n \\\"1\\\":\\n description: Implementation failed.\\n stderr:\\n format: text\\n\\n \\\"3\\\":\\n description: Input validation failed (e.g. project directory not found).\\n stderr:\\n format: text\\n\\n \\\"12\\\":\\n description: Adapter initialization error.\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: high\\n requiresConfirmation: true\\n idempotent: false\\n sideEffects:\\n - sdk_call\\n - filesystem_write\\n safeDryRunOption: dry-run\\n expectedDurationMs: 300000\\n retryableExitCodes: [1, 12]\\n recommendedBeforeUse:\\n - Ensure the target project has a cli-contract.yaml or plan to create one.\\n - Run in a clean git working tree so changes can be reviewed.\\n\\n # -----------------------------------------------------------------------\\n # audit-implementation\\n # -----------------------------------------------------------------------\\n audit-implementation:\\n summary: Audit an LLM command integration for pattern conformance.\\n description: |\\n Analyzes a target project's LLM command integration to verify it\\n correctly follows the agent-contracts + agent-contracts-runtime +\\n cli-contracts stack conventions.\\n\\n Checks all three layers:\\n 1. DSL definitions (agents, tasks, workflows, handoff schemas)\\n 2. Runtime integration (adapter usage, runTask/runWorkflow, registries)\\n 3. CLI contract (standard options, x-agent metadata, exit codes)\\n\\n Produces structured findings with severity, category, and\\n concrete remediation steps. Read-only — does not modify files.\\n arguments:\\n - name: project-dir\\n required: false\\n description: >-\\n Path to the project directory to audit. Defaults to current directory.\\n schema:\\n type: string\\n\\n options:\\n - name: adapter\\n aliases: [a]\\n description: SDK adapter to use for the audit agent.\\n schema:\\n type: string\\n enum: [claude, mock]\\n default: claude\\n\\n - name: focus\\n description: >-\\n Limit audit to a specific layer. Defaults to all layers.\\n schema:\\n type: string\\n enum: [all, dsl, runtime, cli-contract, architecture]\\n default: all\\n\\n - name: dry-run\\n aliases: [n]\\n description: Output the prompt context without calling the LLM.\\n schema:\\n type: boolean\\n default: false\\n\\n - name: fail-on\\n description: Minimum finding severity that causes a non-zero exit.\\n schema:\\n type: string\\n enum: [warning, error, critical]\\n default: error\\n\\n - name: model\\n description: Model name override for the selected adapter.\\n schema:\\n type: string\\n\\n - name: output\\n aliases: [o]\\n description: Write the result to a file instead of stdout.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n - name: report-format\\n description: Output format for the audit report.\\n schema:\\n type: string\\n enum: [json, text, yaml]\\n default: text\\n\\n - name: log-file\\n aliases: [l]\\n description: Write agent progress log to this file.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n exits:\\n \\\"0\\\":\\n description: Audit completed with no findings above threshold.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/AuditImplementationResult\\\"\\n\\n \\\"1\\\":\\n description: Audit failed (agent error, unexpected failure).\\n stderr:\\n format: text\\n\\n \\\"3\\\":\\n description: Input validation failed (e.g. project directory not found).\\n stderr:\\n format: text\\n\\n \\\"10\\\":\\n description: Audit completed with findings above --fail-on threshold.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/AuditImplementationResult\\\"\\n\\n \\\"12\\\":\\n description: Adapter initialization error.\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects:\\n - network\\n sideEffectNote: >-\\n Network calls to LLM provider when adapter is not mock.\\n Filesystem write only when --output is specified.\\n safeDryRunOption: dry-run\\n expectedDurationMs: 180000\\n retryableExitCodes: [1, 12]\\n\\n # -----------------------------------------------------------------------\\n # agents\\n # -----------------------------------------------------------------------\\n agents:\\n summary: Output the full resolved DSL as structured data.\\n description: |\\n Outputs the complete resolved DSL (agents, tasks, workflows,\\n handoff_types, etc.) embedded in this CLI binary.\\n\\n Useful for debugging, external tooling integration, and DSL\\n inspection. Unlike `list`, which shows tabular summaries,\\n this command outputs the full DSL structure.\\n options:\\n - name: format\\n aliases: [F]\\n description: Output format.\\n schema:\\n type: string\\n enum: [yaml, json]\\n default: yaml\\n\\n exits:\\n \\\"0\\\":\\n description: DSL output successfully.\\n stdout:\\n format: text\\n\\n \\\"1\\\":\\n description: Failed to load embedded DSL.\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: []\\n\\n # -----------------------------------------------------------------------\\n # doctor\\n # -----------------------------------------------------------------------\\n doctor:\\n summary: Verify configuration, generated files, and SDK connectivity.\\n description: |\\n Runs a series of diagnostic checks to verify that the project\\n is correctly configured for agent-runtime execution.\\n\\n Checks: config existence, DSL existence, generated manifest freshness,\\n adapter configuration, API key environment variables, plugin entrypoint.\\n exits:\\n \\\"0\\\":\\n description: All checks passed.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/DoctorResult\\\"\\n\\n \\\"1\\\":\\n description: One or more checks failed.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/DoctorResult\\\"\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: []\\n\\n # -----------------------------------------------------------------------\\n # navigation-index\\n # -----------------------------------------------------------------------\\n navigation-index:\\n summary: Build artifact navigation index from resolved DSL.\\n description: |\\n Resolves the embedded DSL (merged with project overlay if configured),\\n applies artifact binding, and builds a navigation index showing\\n artifact-to-tool-to-agent mappings.\\n\\n The output is a JSON/YAML structure suitable for IDE integration,\\n routing rules, and artifact coverage analysis.\\n options:\\n - name: format\\n aliases: [F]\\n description: Output format.\\n schema:\\n type: string\\n enum: [json, yaml]\\n default: json\\n\\n - name: artifact\\n description: Filter output to a single artifact by ID.\\n schema:\\n type: string\\n\\n - name: output\\n aliases: [o]\\n description: Write output to a file instead of stdout.\\n schema:\\n type: string\\n file:\\n mode: write\\n\\n exits:\\n \\\"0\\\":\\n description: Navigation index built successfully.\\n stdout:\\n format: json\\n schema:\\n $ref: \\\"#/components/schemas/NavigationIndexResult\\\"\\n\\n \\\"1\\\":\\n description: Failed to build navigation index.\\n stderr:\\n format: text\\n\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: []\\n\\n\\n# =============================================================================\\n# Components\\n# =============================================================================\\n\\ncomponents:\\n schemas:\\n # -------------------------------------------------------------------------\\n # init\\n # -------------------------------------------------------------------------\\n InitResult:\\n type: object\\n required: [files_created]\\n properties:\\n files_created:\\n type: array\\n items:\\n type: string\\n description: List of files created by init.\\n\\n # -------------------------------------------------------------------------\\n # generate\\n # -------------------------------------------------------------------------\\n GenerateResult:\\n type: object\\n required: [files_generated, dsl_hash, generation_input_hash]\\n properties:\\n files_generated:\\n type: array\\n items:\\n type: string\\n description: List of generated file paths.\\n dsl_hash:\\n type: string\\n description: SHA-256 hash of the resolved DSL (canonical stringify).\\n generation_input_hash:\\n type: string\\n description: SHA-256 hash of all generation inputs.\\n cleaned:\\n type: boolean\\n description: Whether --clean was used.\\n check_mode:\\n type: boolean\\n description: Whether --check was used.\\n has_differences:\\n type: boolean\\n description: In --check mode, whether differences were found.\\n\\n ValidationError:\\n type: object\\n required: [errors]\\n properties:\\n errors:\\n type: array\\n items:\\n type: object\\n required: [code, message]\\n properties:\\n code:\\n type: string\\n message:\\n type: string\\n path:\\n type: string\\n description: JSON path to the invalid element.\\n\\n # -------------------------------------------------------------------------\\n # run\\n # -------------------------------------------------------------------------\\n WorkflowResult:\\n type: object\\n required: [workflow_id, status, steps, total_elapsed_ms]\\n properties:\\n workflow_id:\\n type: string\\n status:\\n type: string\\n enum: [completed, escalated, gate_rejected, error]\\n steps:\\n type: array\\n items:\\n $ref: \\\"#/components/schemas/StepResult\\\"\\n total_elapsed_ms:\\n type: integer\\n minimum: 0\\n escalation_reason:\\n type: string\\n error_message:\\n type: string\\n\\n StepResult:\\n type: object\\n required: [step_index, retries_used, elapsed_ms, outcome]\\n properties:\\n step_index:\\n type: integer\\n minimum: 0\\n task_id:\\n type: string\\n gate_kind:\\n type: string\\n outcome:\\n type: object\\n required: [status]\\n properties:\\n status:\\n type: string\\n enum: [success, validation_error, escalation, error, gate_approved, gate_rejected, skipped]\\n retries_used:\\n type: integer\\n minimum: 0\\n elapsed_ms:\\n type: integer\\n minimum: 0\\n\\n # -------------------------------------------------------------------------\\n # list\\n # -------------------------------------------------------------------------\\n ListResult:\\n type: object\\n required: [resource, items]\\n properties:\\n resource:\\n type: string\\n enum: [workflows, tasks, agents]\\n items:\\n type: array\\n items:\\n type: object\\n required: [id, description]\\n properties:\\n id:\\n type: string\\n description:\\n type: string\\n\\n # -------------------------------------------------------------------------\\n # show-prompt\\n # -------------------------------------------------------------------------\\n ShowPromptResult:\\n type: object\\n required: [task_id, agent_id, prompt]\\n properties:\\n task_id:\\n type: string\\n description: The task ID used to build the prompt.\\n agent_id:\\n type: string\\n description: The target agent ID for this task.\\n prompt:\\n type: string\\n description: The full generated prompt text.\\n handoff_schema:\\n type: string\\n description: The handoff schema ID for the task result.\\n plugins_applied:\\n type: boolean\\n description: Whether plugin prompt enhancers were applied.\\n\\n # -------------------------------------------------------------------------\\n # doctor\\n # -------------------------------------------------------------------------\\n DoctorResult:\\n type: object\\n required: [checks, all_passed]\\n properties:\\n checks:\\n type: array\\n items:\\n $ref: \\\"#/components/schemas/DoctorCheck\\\"\\n all_passed:\\n type: boolean\\n\\n # -------------------------------------------------------------------------\\n # implement\\n # -------------------------------------------------------------------------\\n ImplementResult:\\n type: object\\n required: [files_created, files_modified, summary]\\n properties:\\n files_created:\\n type: array\\n items:\\n type: string\\n description: List of new files created.\\n files_modified:\\n type: array\\n items:\\n type: string\\n description: List of existing files modified.\\n summary:\\n type: string\\n description: Human-readable summary of what was implemented.\\n commands_added:\\n type: array\\n items:\\n type: object\\n required: [name, type]\\n properties:\\n name:\\n type: string\\n type:\\n type: string\\n enum: [audit, propose, explain]\\n description:\\n type: string\\n next_steps:\\n type: array\\n items:\\n type: string\\n description: Recommended next steps for the developer.\\n\\n # -------------------------------------------------------------------------\\n # audit-implementation\\n # -------------------------------------------------------------------------\\n AuditImplementationResult:\\n type: object\\n required: [summary, riskLevel, findings]\\n properties:\\n summary:\\n type: string\\n description: One-paragraph overall assessment.\\n riskLevel:\\n type: string\\n enum: [low, medium, high, critical]\\n description: Derived from worst finding severity.\\n findings:\\n type: array\\n items:\\n $ref: \\\"#/components/schemas/AgentFinding\\\"\\n recommendedActions:\\n type: array\\n items:\\n $ref: \\\"#/components/schemas/AgentRecommendedAction\\\"\\n metadata:\\n type: object\\n properties:\\n tool:\\n type: string\\n command:\\n type: string\\n version:\\n type: string\\n generatedAt:\\n type: string\\n adapter:\\n type: string\\n model:\\n type: string\\n\\n DoctorCheck:\\n type: object\\n required: [name, status]\\n properties:\\n name:\\n type: string\\n description: Check name (e.g. config_exists, dsl_exists, manifest_fresh).\\n status:\\n type: string\\n enum: [pass, fail, warn]\\n message:\\n type: string\\n description: Human-readable detail.\\n\\n # -------------------------------------------------------------------------\\n # navigation-index\\n # -------------------------------------------------------------------------\\n NavigationIndexResult:\\n type: object\\n required: [version, generated_at, system, artifacts]\\n properties:\\n version:\\n type: string\\n generated_at:\\n type: string\\n system:\\n type: object\\n required: [id, name]\\n properties:\\n id:\\n type: string\\n name:\\n type: string\\n artifacts:\\n type: object\\n additionalProperties: true\\n\\n # -------------------------------------------------------------------------\\n # Canonical agent result schemas (AgentAuditResult sub-types)\\n # -------------------------------------------------------------------------\\n AgentFinding:\\n type: object\\n required: [severity, category, message]\\n properties:\\n id:\\n type: string\\n description: Unique finding identifier (e.g. F-001).\\n severity:\\n type: string\\n enum: [info, warning, error, critical]\\n category:\\n type: string\\n description: Domain vocabulary category (e.g. cli-contract-options, runtime-adapter).\\n target:\\n type: string\\n description: File path or resource the finding applies to.\\n location:\\n type: string\\n description: Line range or specific location within the target.\\n message:\\n type: string\\n description: Human-readable description of the finding.\\n recommendation:\\n type: string\\n description: Concrete remediation step.\\n confidence:\\n type: number\\n minimum: 0\\n maximum: 1\\n description: Confidence score (0–1) for the finding.\\n evidence:\\n type: array\\n items:\\n $ref: \\\"#/components/schemas/AgentEvidence\\\"\\n details:\\n type: object\\n description: Additional structured details specific to the finding category.\\n\\n AgentRecommendedAction:\\n type: object\\n required: [kind, title]\\n properties:\\n kind:\\n type: string\\n enum: [run_command, edit_file, review, confirm, block, ignore]\\n title:\\n type: string\\n description: Short human-readable title for the action.\\n command:\\n type: string\\n description: Shell command to run (when kind is run_command).\\n target:\\n type: string\\n description: File path to edit (when kind is edit_file).\\n rationale:\\n type: string\\n description: Explanation of why this action is recommended.\\n\\n AgentEvidence:\\n type: object\\n required: [type, content]\\n properties:\\n type:\\n type: string\\n description: Evidence type (e.g. code_snippet, file_excerpt, lint_output).\\n content:\\n type: string\\n description: The evidence content.\\n source:\\n type: string\\n description: Source file path or URL for the evidence.\\n\";\n\nexport const CONTRACT_JSON_STR: string = \"{\\n \\\"cli_contracts\\\": \\\"0.1.0\\\",\\n \\\"info\\\": {\\n \\\"title\\\": \\\"agent-runtime CLI\\\",\\n \\\"version\\\": \\\"0.36.0\\\",\\n \\\"description\\\": \\\"Runtime bridge for executing agent-contracts workflows on Agent SDKs.\\\\nGenerates typed contracts, handoff validators, and guardrail hooks from DSL,\\\\nthen runs workflows through pluggable SDK adapters.\\\\n\\\",\\n \\\"license\\\": {\\n \\\"name\\\": \\\"MIT\\\"\\n }\\n },\\n \\\"command_sets\\\": {\\n \\\"agent-runtime\\\": {\\n \\\"summary\\\": \\\"CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\\\",\\n \\\"global_options\\\": [\\n {\\n \\\"name\\\": \\\"config\\\",\\n \\\"aliases\\\": [\\n \\\"c\\\"\\n ],\\n \\\"description\\\": \\\"Path to agents.conf.yaml (project runtime config).\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"default\\\": \\\"./agents.conf.yaml\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"read\\\",\\n \\\"exists\\\": true,\\n \\\"media_type\\\": \\\"application/yaml\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"verbose\\\",\\n \\\"aliases\\\": [\\n \\\"v\\\"\\n ],\\n \\\"description\\\": \\\"Enable verbose output.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"quiet\\\",\\n \\\"aliases\\\": [\\n \\\"q\\\"\\n ],\\n \\\"description\\\": \\\"Suppress non-error output.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n }\\n ],\\n \\\"commands\\\": {\\n \\\"init\\\": {\\n \\\"summary\\\": \\\"Initialize runtime scaffolding for a project.\\\",\\n \\\"description\\\": \\\"Generates the initial directory structure and configuration files\\\\nfor using agent-contracts-runtime in a project.\\\\nCreates agents.conf.yaml and agent/src/ user code templates.\\\\n\\\",\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"adapter\\\",\\n \\\"aliases\\\": [\\n \\\"a\\\"\\n ],\\n \\\"description\\\": \\\"Default SDK adapter to configure.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"claude\\\",\\n \\\"gemini\\\",\\n \\\"openai\\\",\\n \\\"mock\\\"\\n ],\\n \\\"default\\\": \\\"mock\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"output\\\",\\n \\\"aliases\\\": [\\n \\\"o\\\"\\n ],\\n \\\"description\\\": \\\"Output directory for generated scaffolding.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"default\\\": \\\".\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"force\\\",\\n \\\"aliases\\\": [\\n \\\"f\\\"\\n ],\\n \\\"description\\\": \\\"Overwrite existing files without prompting.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Scaffolding generated successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/InitResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Initialization failed (existing files, permission error, etc.).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": false,\\n \\\"sideEffects\\\": [\\n \\\"filesystem_write\\\"\\n ],\\n \\\"safeDryRunOption\\\": \\\"\\\"\\n }\\n },\\n \\\"generate\\\": {\\n \\\"summary\\\": \\\"Generate runtime contracts and hooks from DSL.\\\",\\n \\\"description\\\": \\\"Reads agent-contracts.yaml, resolves the DSL, validates it,\\\\nand generates typed contracts, handoff schemas, guardrail hooks,\\\\nand a runtime manifest into the configured generated_dir.\\\\n\\\\nEach generated file includes a DO NOT EDIT header.\\\\n\\\",\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"clean\\\",\\n \\\"description\\\": \\\"Delete generated_dir before regenerating.\\\\nRemoves stale files that may remain from previous generations.\\\\n\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"check\\\",\\n \\\"description\\\": \\\"Dry-run mode for CI. Does not write files.\\\\nCompares current generated output with what would be regenerated.\\\\nExits with code 1 if any differences are found.\\\\n\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"templates\\\",\\n \\\"aliases\\\": [\\n \\\"t\\\"\\n ],\\n \\\"description\\\": \\\"Custom templates directory. Overrides built-in templates.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Generation completed successfully (or --check found no differences).\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/GenerateResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Generation failed, or --check detected differences between\\\\ncurrent generated files and expected output.\\\\n\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"2\\\": {\\n \\\"description\\\": \\\"DSL validation error. The input DSL has structural or semantic issues.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/ValidationError\\\"\\n }\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": [\\n \\\"filesystem_write\\\"\\n ],\\n \\\"safeDryRunOption\\\": \\\"check\\\"\\n }\\n },\\n \\\"run\\\": {\\n \\\"summary\\\": \\\"Execute a workflow.\\\",\\n \\\"description\\\": \\\"Loads generated contracts, creates an SDK adapter, registers user plugins,\\\\nand executes the specified workflow with the given user request.\\\\n\\\\nThe workflow runner orchestrates task delegation, retry, gate handling,\\\\nand handoff validation mechanically.\\\\n\\\",\\n \\\"arguments\\\": [\\n {\\n \\\"name\\\": \\\"workflow-id\\\",\\n \\\"required\\\": false,\\n \\\"description\\\": \\\"ID of the workflow to execute. Required unless --file is used.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"user-request\\\",\\n \\\"required\\\": false,\\n \\\"description\\\": \\\"Natural language description of what to do. Required unless --file is used.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n ],\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"adapter\\\",\\n \\\"aliases\\\": [\\n \\\"a\\\"\\n ],\\n \\\"description\\\": \\\"SDK adapter to use. Overrides config.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"claude\\\",\\n \\\"gemini\\\",\\n \\\"openai\\\",\\n \\\"mock\\\"\\n ]\\n }\\n },\\n {\\n \\\"name\\\": \\\"max-retries\\\",\\n \\\"aliases\\\": [\\n \\\"r\\\"\\n ],\\n \\\"description\\\": \\\"Override default max retries per step.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0,\\n \\\"maximum\\\": 10\\n }\\n },\\n {\\n \\\"name\\\": \\\"max-follow-ups\\\",\\n \\\"aliases\\\": [\\n \\\"f\\\"\\n ],\\n \\\"description\\\": \\\"Override default max follow-ups per step.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0,\\n \\\"maximum\\\": 10\\n }\\n },\\n {\\n \\\"name\\\": \\\"dry-run\\\",\\n \\\"aliases\\\": [\\n \\\"n\\\"\\n ],\\n \\\"description\\\": \\\"Simulate execution without calling the SDK adapter.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"auto-approve-gates\\\",\\n \\\"description\\\": \\\"Automatically approve all gate steps.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"file\\\",\\n \\\"description\\\": \\\"Path to a YAML invocation file. When provided, workflow-id and\\\\nuser-request arguments are read from the file instead of CLI args.\\\\n\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"read\\\",\\n \\\"exists\\\": true,\\n \\\"media_type\\\": \\\"application/yaml\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"log-file\\\",\\n \\\"aliases\\\": [\\n \\\"l\\\"\\n ],\\n \\\"description\\\": \\\"Write agent progress log to this file. Overrides config logging.progress_log.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Workflow completed successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/WorkflowResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Workflow failed (escalation, error, or gate rejection).\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/WorkflowResult\\\"\\n }\\n },\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"3\\\": {\\n \\\"description\\\": \\\"Input validation failed (invalid arguments, unknown workflow/adapter, or generated files outdated).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"12\\\": {\\n \\\"description\\\": \\\"Adapter initialization error (missing API key, etc.).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"high\\\",\\n \\\"requiresConfirmation\\\": true,\\n \\\"idempotent\\\": false,\\n \\\"sideEffects\\\": [\\n \\\"sdk_call\\\",\\n \\\"filesystem_write\\\"\\n ],\\n \\\"safeDryRunOption\\\": \\\"dry-run\\\",\\n \\\"expectedDurationMs\\\": 300000,\\n \\\"recommendedBeforeUse\\\": [\\n \\\"Run `agent-runtime generate --check` to ensure contracts are up to date.\\\",\\n \\\"Run `agent-runtime doctor` to verify SDK configuration.\\\"\\n ]\\n }\\n },\\n \\\"list\\\": {\\n \\\"summary\\\": \\\"List available workflows, tasks, or agents.\\\",\\n \\\"description\\\": \\\"Reads generated contracts and displays available resources.\\\\nUseful for discovering what workflows, tasks, and agents\\\\nare defined in the current project.\\\\n\\\",\\n \\\"arguments\\\": [\\n {\\n \\\"name\\\": \\\"resource\\\",\\n \\\"required\\\": true,\\n \\\"description\\\": \\\"Type of resource to list.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"workflows\\\",\\n \\\"tasks\\\",\\n \\\"agents\\\"\\n ]\\n }\\n }\\n ],\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"format\\\",\\n \\\"description\\\": \\\"Output format.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"table\\\",\\n \\\"json\\\"\\n ],\\n \\\"default\\\": \\\"table\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Resources listed successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/ListResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Failed to load contracts.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": []\\n }\\n },\\n \\\"show-prompt\\\": {\\n \\\"summary\\\": \\\"Display the generated prompt for a task.\\\",\\n \\\"description\\\": \\\"Builds and displays the full prompt that would be sent to an SDK agent\\\\nfor a given task. Useful for inspecting, debugging, and validating\\\\nprompt content before execution.\\\\n\\\\nShows the agent role, responsibilities, constraints, task details,\\\\ncompletion criteria, handoff schema fields, and output format example.\\\\n\\\",\\n \\\"arguments\\\": [\\n {\\n \\\"name\\\": \\\"task-id\\\",\\n \\\"required\\\": true,\\n \\\"description\\\": \\\"ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n ],\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"user-request\\\",\\n \\\"aliases\\\": [\\n \\\"u\\\"\\n ],\\n \\\"description\\\": \\\"User request text to include in the prompt preview.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"default\\\": \\\"(preview)\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"format\\\",\\n \\\"description\\\": \\\"Output format.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"markdown\\\",\\n \\\"raw\\\",\\n \\\"json\\\"\\n ],\\n \\\"default\\\": \\\"markdown\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"with-plugins\\\",\\n \\\"description\\\": \\\"Apply registered plugin prompt enhancers to the output.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Prompt displayed successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/ShowPromptResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Failed to build prompt (unknown task, missing contracts, etc.).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": []\\n }\\n },\\n \\\"implement\\\": {\\n \\\"summary\\\": \\\"Implement LLM-powered commands in a CLI tool.\\\",\\n \\\"description\\\": \\\"Uses an agentic LLM adapter (Claude, etc.) to analyze the\\\\ntarget project and implement LLM-powered commands following the\\\\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\\\\n\\\\nThe agent reads the project structure, cli-contract.yaml, and existing\\\\ncode, then generates DSL definitions, TypeScript modules (orchestrator,\\\\ncontext-builder, formatter), CLI command handlers, and updates the\\\\nCLI contract with x-agent metadata.\\\\n\\\\nRequires an agentic adapter that supports tool use (file read/write).\\\\n\\\",\\n \\\"arguments\\\": [\\n {\\n \\\"name\\\": \\\"description\\\",\\n \\\"required\\\": true,\\n \\\"description\\\": \\\"Natural language description of the LLM feature(s) to implement. Examples: \\\\\\\"Add an audit command for migration safety\\\\\\\", \\\\\\\"Add propose and explain commands for SQL optimization\\\\\\\".\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n ],\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"adapter\\\",\\n \\\"aliases\\\": [\\n \\\"a\\\"\\n ],\\n \\\"description\\\": \\\"SDK adapter to use. Must be an agentic adapter (claude).\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"claude\\\",\\n \\\"mock\\\"\\n ],\\n \\\"default\\\": \\\"claude\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"project-dir\\\",\\n \\\"aliases\\\": [\\n \\\"p\\\"\\n ],\\n \\\"description\\\": \\\"Path to the target project directory.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"default\\\": \\\".\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"dry-run\\\",\\n \\\"aliases\\\": [\\n \\\"n\\\"\\n ],\\n \\\"description\\\": \\\"Output the prompt context without calling the LLM.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"model\\\",\\n \\\"description\\\": \\\"Model name override for the selected adapter.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"output\\\",\\n \\\"aliases\\\": [\\n \\\"o\\\"\\n ],\\n \\\"description\\\": \\\"Write the result to a file instead of stdout.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"report-format\\\",\\n \\\"description\\\": \\\"Output format for the result.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"json\\\",\\n \\\"text\\\",\\n \\\"yaml\\\"\\n ],\\n \\\"default\\\": \\\"text\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"log-file\\\",\\n \\\"aliases\\\": [\\n \\\"l\\\"\\n ],\\n \\\"description\\\": \\\"Write agent progress log to this file.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Implementation completed successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/ImplementResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Implementation failed.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"3\\\": {\\n \\\"description\\\": \\\"Input validation failed (e.g. project directory not found).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"12\\\": {\\n \\\"description\\\": \\\"Adapter initialization error.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"high\\\",\\n \\\"requiresConfirmation\\\": true,\\n \\\"idempotent\\\": false,\\n \\\"sideEffects\\\": [\\n \\\"sdk_call\\\",\\n \\\"filesystem_write\\\"\\n ],\\n \\\"safeDryRunOption\\\": \\\"dry-run\\\",\\n \\\"expectedDurationMs\\\": 300000,\\n \\\"retryableExitCodes\\\": [\\n 1,\\n 12\\n ],\\n \\\"recommendedBeforeUse\\\": [\\n \\\"Ensure the target project has a cli-contract.yaml or plan to create one.\\\",\\n \\\"Run in a clean git working tree so changes can be reviewed.\\\"\\n ]\\n }\\n },\\n \\\"audit-implementation\\\": {\\n \\\"summary\\\": \\\"Audit an LLM command integration for pattern conformance.\\\",\\n \\\"description\\\": \\\"Analyzes a target project's LLM command integration to verify it\\\\ncorrectly follows the agent-contracts + agent-contracts-runtime +\\\\ncli-contracts stack conventions.\\\\n\\\\nChecks all three layers:\\\\n1. DSL definitions (agents, tasks, workflows, handoff schemas)\\\\n2. Runtime integration (adapter usage, runTask/runWorkflow, registries)\\\\n3. CLI contract (standard options, x-agent metadata, exit codes)\\\\n\\\\nProduces structured findings with severity, category, and\\\\nconcrete remediation steps. Read-only — does not modify files.\\\\n\\\",\\n \\\"arguments\\\": [\\n {\\n \\\"name\\\": \\\"project-dir\\\",\\n \\\"required\\\": false,\\n \\\"description\\\": \\\"Path to the project directory to audit. Defaults to current directory.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n ],\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"adapter\\\",\\n \\\"aliases\\\": [\\n \\\"a\\\"\\n ],\\n \\\"description\\\": \\\"SDK adapter to use for the audit agent.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"claude\\\",\\n \\\"mock\\\"\\n ],\\n \\\"default\\\": \\\"claude\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"focus\\\",\\n \\\"description\\\": \\\"Limit audit to a specific layer. Defaults to all layers.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"all\\\",\\n \\\"dsl\\\",\\n \\\"runtime\\\",\\n \\\"cli-contract\\\",\\n \\\"architecture\\\"\\n ],\\n \\\"default\\\": \\\"all\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"dry-run\\\",\\n \\\"aliases\\\": [\\n \\\"n\\\"\\n ],\\n \\\"description\\\": \\\"Output the prompt context without calling the LLM.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"default\\\": false\\n }\\n },\\n {\\n \\\"name\\\": \\\"fail-on\\\",\\n \\\"description\\\": \\\"Minimum finding severity that causes a non-zero exit.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"warning\\\",\\n \\\"error\\\",\\n \\\"critical\\\"\\n ],\\n \\\"default\\\": \\\"error\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"model\\\",\\n \\\"description\\\": \\\"Model name override for the selected adapter.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"output\\\",\\n \\\"aliases\\\": [\\n \\\"o\\\"\\n ],\\n \\\"description\\\": \\\"Write the result to a file instead of stdout.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"report-format\\\",\\n \\\"description\\\": \\\"Output format for the audit report.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"json\\\",\\n \\\"text\\\",\\n \\\"yaml\\\"\\n ],\\n \\\"default\\\": \\\"text\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"log-file\\\",\\n \\\"aliases\\\": [\\n \\\"l\\\"\\n ],\\n \\\"description\\\": \\\"Write agent progress log to this file.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Audit completed with no findings above threshold.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/AuditImplementationResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Audit failed (agent error, unexpected failure).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"3\\\": {\\n \\\"description\\\": \\\"Input validation failed (e.g. project directory not found).\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"10\\\": {\\n \\\"description\\\": \\\"Audit completed with findings above --fail-on threshold.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/AuditImplementationResult\\\"\\n }\\n }\\n },\\n \\\"12\\\": {\\n \\\"description\\\": \\\"Adapter initialization error.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": [\\n \\\"network\\\"\\n ],\\n \\\"sideEffectNote\\\": \\\"Network calls to LLM provider when adapter is not mock. Filesystem write only when --output is specified.\\\",\\n \\\"safeDryRunOption\\\": \\\"dry-run\\\",\\n \\\"expectedDurationMs\\\": 180000,\\n \\\"retryableExitCodes\\\": [\\n 1,\\n 12\\n ]\\n }\\n },\\n \\\"agents\\\": {\\n \\\"summary\\\": \\\"Output the full resolved DSL as structured data.\\\",\\n \\\"description\\\": \\\"Outputs the complete resolved DSL (agents, tasks, workflows,\\\\nhandoff_types, etc.) embedded in this CLI binary.\\\\n\\\\nUseful for debugging, external tooling integration, and DSL\\\\ninspection. Unlike `list`, which shows tabular summaries,\\\\nthis command outputs the full DSL structure.\\\\n\\\",\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"format\\\",\\n \\\"aliases\\\": [\\n \\\"F\\\"\\n ],\\n \\\"description\\\": \\\"Output format.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"yaml\\\",\\n \\\"json\\\"\\n ],\\n \\\"default\\\": \\\"yaml\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"DSL output successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Failed to load embedded DSL.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": []\\n }\\n },\\n \\\"doctor\\\": {\\n \\\"summary\\\": \\\"Verify configuration, generated files, and SDK connectivity.\\\",\\n \\\"description\\\": \\\"Runs a series of diagnostic checks to verify that the project\\\\nis correctly configured for agent-runtime execution.\\\\n\\\\nChecks: config existence, DSL existence, generated manifest freshness,\\\\nadapter configuration, API key environment variables, plugin entrypoint.\\\\n\\\",\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"All checks passed.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/DoctorResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"One or more checks failed.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/DoctorResult\\\"\\n }\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": []\\n }\\n },\\n \\\"navigation-index\\\": {\\n \\\"summary\\\": \\\"Build artifact navigation index from resolved DSL.\\\",\\n \\\"description\\\": \\\"Resolves the embedded DSL (merged with project overlay if configured),\\\\napplies artifact binding, and builds a navigation index showing\\\\nartifact-to-tool-to-agent mappings.\\\\n\\\\nThe output is a JSON/YAML structure suitable for IDE integration,\\\\nrouting rules, and artifact coverage analysis.\\\\n\\\",\\n \\\"options\\\": [\\n {\\n \\\"name\\\": \\\"format\\\",\\n \\\"aliases\\\": [\\n \\\"F\\\"\\n ],\\n \\\"description\\\": \\\"Output format.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"json\\\",\\n \\\"yaml\\\"\\n ],\\n \\\"default\\\": \\\"json\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"artifact\\\",\\n \\\"description\\\": \\\"Filter output to a single artifact by ID.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n },\\n {\\n \\\"name\\\": \\\"output\\\",\\n \\\"aliases\\\": [\\n \\\"o\\\"\\n ],\\n \\\"description\\\": \\\"Write output to a file instead of stdout.\\\",\\n \\\"schema\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"file\\\": {\\n \\\"mode\\\": \\\"write\\\"\\n }\\n }\\n ],\\n \\\"exits\\\": {\\n \\\"0\\\": {\\n \\\"description\\\": \\\"Navigation index built successfully.\\\",\\n \\\"stdout\\\": {\\n \\\"format\\\": \\\"json\\\",\\n \\\"schema\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/NavigationIndexResult\\\"\\n }\\n }\\n },\\n \\\"1\\\": {\\n \\\"description\\\": \\\"Failed to build navigation index.\\\",\\n \\\"stderr\\\": {\\n \\\"format\\\": \\\"text\\\"\\n }\\n }\\n },\\n \\\"x-agent\\\": {\\n \\\"riskLevel\\\": \\\"low\\\",\\n \\\"requiresConfirmation\\\": false,\\n \\\"idempotent\\\": true,\\n \\\"sideEffects\\\": []\\n }\\n }\\n }\\n }\\n },\\n \\\"components\\\": {\\n \\\"schemas\\\": {\\n \\\"InitResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"files_created\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"files_created\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": \\\"List of files created by init.\\\"\\n }\\n }\\n },\\n \\\"GenerateResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"files_generated\\\",\\n \\\"dsl_hash\\\",\\n \\\"generation_input_hash\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"files_generated\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": \\\"List of generated file paths.\\\"\\n },\\n \\\"dsl_hash\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"SHA-256 hash of the resolved DSL (canonical stringify).\\\"\\n },\\n \\\"generation_input_hash\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"SHA-256 hash of all generation inputs.\\\"\\n },\\n \\\"cleaned\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"description\\\": \\\"Whether --clean was used.\\\"\\n },\\n \\\"check_mode\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"description\\\": \\\"Whether --check was used.\\\"\\n },\\n \\\"has_differences\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"description\\\": \\\"In --check mode, whether differences were found.\\\"\\n }\\n }\\n },\\n \\\"ValidationError\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"errors\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"errors\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"code\\\",\\n \\\"message\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"code\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"message\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"path\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"JSON path to the invalid element.\\\"\\n }\\n }\\n }\\n }\\n }\\n },\\n \\\"WorkflowResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"workflow_id\\\",\\n \\\"status\\\",\\n \\\"steps\\\",\\n \\\"total_elapsed_ms\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"workflow_id\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"status\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"completed\\\",\\n \\\"escalated\\\",\\n \\\"gate_rejected\\\",\\n \\\"error\\\"\\n ]\\n },\\n \\\"steps\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/StepResult\\\"\\n }\\n },\\n \\\"total_elapsed_ms\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0\\n },\\n \\\"escalation_reason\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"error_message\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n },\\n \\\"StepResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"step_index\\\",\\n \\\"retries_used\\\",\\n \\\"elapsed_ms\\\",\\n \\\"outcome\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"step_index\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0\\n },\\n \\\"task_id\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"gate_kind\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"outcome\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"status\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"status\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"success\\\",\\n \\\"validation_error\\\",\\n \\\"escalation\\\",\\n \\\"error\\\",\\n \\\"gate_approved\\\",\\n \\\"gate_rejected\\\",\\n \\\"skipped\\\"\\n ]\\n }\\n }\\n },\\n \\\"retries_used\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0\\n },\\n \\\"elapsed_ms\\\": {\\n \\\"type\\\": \\\"integer\\\",\\n \\\"minimum\\\": 0\\n }\\n }\\n },\\n \\\"ListResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"resource\\\",\\n \\\"items\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"resource\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"workflows\\\",\\n \\\"tasks\\\",\\n \\\"agents\\\"\\n ]\\n },\\n \\\"items\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"id\\\",\\n \\\"description\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"id\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n }\\n }\\n }\\n },\\n \\\"ShowPromptResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"task_id\\\",\\n \\\"agent_id\\\",\\n \\\"prompt\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"task_id\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The task ID used to build the prompt.\\\"\\n },\\n \\\"agent_id\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The target agent ID for this task.\\\"\\n },\\n \\\"prompt\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The full generated prompt text.\\\"\\n },\\n \\\"handoff_schema\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The handoff schema ID for the task result.\\\"\\n },\\n \\\"plugins_applied\\\": {\\n \\\"type\\\": \\\"boolean\\\",\\n \\\"description\\\": \\\"Whether plugin prompt enhancers were applied.\\\"\\n }\\n }\\n },\\n \\\"DoctorResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"checks\\\",\\n \\\"all_passed\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"checks\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/DoctorCheck\\\"\\n }\\n },\\n \\\"all_passed\\\": {\\n \\\"type\\\": \\\"boolean\\\"\\n }\\n }\\n },\\n \\\"ImplementResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"files_created\\\",\\n \\\"files_modified\\\",\\n \\\"summary\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"files_created\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": \\\"List of new files created.\\\"\\n },\\n \\\"files_modified\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": \\\"List of existing files modified.\\\"\\n },\\n \\\"summary\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Human-readable summary of what was implemented.\\\"\\n },\\n \\\"commands_added\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"name\\\",\\n \\\"type\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"name\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"type\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"audit\\\",\\n \\\"propose\\\",\\n \\\"explain\\\"\\n ]\\n },\\n \\\"description\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n }\\n },\\n \\\"next_steps\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"description\\\": \\\"Recommended next steps for the developer.\\\"\\n }\\n }\\n },\\n \\\"AuditImplementationResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"summary\\\",\\n \\\"riskLevel\\\",\\n \\\"findings\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"summary\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"One-paragraph overall assessment.\\\"\\n },\\n \\\"riskLevel\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"low\\\",\\n \\\"medium\\\",\\n \\\"high\\\",\\n \\\"critical\\\"\\n ],\\n \\\"description\\\": \\\"Derived from worst finding severity.\\\"\\n },\\n \\\"findings\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/AgentFinding\\\"\\n }\\n },\\n \\\"recommendedActions\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/AgentRecommendedAction\\\"\\n }\\n },\\n \\\"metadata\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"tool\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"command\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"version\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"generatedAt\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"adapter\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"model\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n }\\n }\\n },\\n \\\"DoctorCheck\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"name\\\",\\n \\\"status\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"name\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Check name (e.g. config_exists, dsl_exists, manifest_fresh).\\\"\\n },\\n \\\"status\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"pass\\\",\\n \\\"fail\\\",\\n \\\"warn\\\"\\n ]\\n },\\n \\\"message\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Human-readable detail.\\\"\\n }\\n }\\n },\\n \\\"NavigationIndexResult\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"version\\\",\\n \\\"generated_at\\\",\\n \\\"system\\\",\\n \\\"artifacts\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"version\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"generated_at\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"system\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"id\\\",\\n \\\"name\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"id\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"name\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n },\\n \\\"artifacts\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"additionalProperties\\\": true\\n }\\n }\\n },\\n \\\"AgentFinding\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"severity\\\",\\n \\\"category\\\",\\n \\\"message\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"id\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Unique finding identifier (e.g. F-001).\\\"\\n },\\n \\\"severity\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"info\\\",\\n \\\"warning\\\",\\n \\\"error\\\",\\n \\\"critical\\\"\\n ]\\n },\\n \\\"category\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Domain vocabulary category (e.g. cli-contract-options, runtime-adapter).\\\"\\n },\\n \\\"target\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"File path or resource the finding applies to.\\\"\\n },\\n \\\"location\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Line range or specific location within the target.\\\"\\n },\\n \\\"message\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Human-readable description of the finding.\\\"\\n },\\n \\\"recommendation\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Concrete remediation step.\\\"\\n },\\n \\\"confidence\\\": {\\n \\\"type\\\": \\\"number\\\",\\n \\\"minimum\\\": 0,\\n \\\"maximum\\\": 1,\\n \\\"description\\\": \\\"Confidence score (0–1) for the finding.\\\"\\n },\\n \\\"evidence\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"$ref\\\": \\\"#/components/schemas/AgentEvidence\\\"\\n }\\n },\\n \\\"details\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"description\\\": \\\"Additional structured details specific to the finding category.\\\"\\n }\\n }\\n },\\n \\\"AgentRecommendedAction\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"kind\\\",\\n \\\"title\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"kind\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"enum\\\": [\\n \\\"run_command\\\",\\n \\\"edit_file\\\",\\n \\\"review\\\",\\n \\\"confirm\\\",\\n \\\"block\\\",\\n \\\"ignore\\\"\\n ]\\n },\\n \\\"title\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Short human-readable title for the action.\\\"\\n },\\n \\\"command\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Shell command to run (when kind is run_command).\\\"\\n },\\n \\\"target\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"File path to edit (when kind is edit_file).\\\"\\n },\\n \\\"rationale\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Explanation of why this action is recommended.\\\"\\n }\\n }\\n },\\n \\\"AgentEvidence\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"required\\\": [\\n \\\"type\\\",\\n \\\"content\\\"\\n ],\\n \\\"properties\\\": {\\n \\\"type\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Evidence type (e.g. code_snippet, file_excerpt, lint_output).\\\"\\n },\\n \\\"content\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The evidence content.\\\"\\n },\\n \\\"source\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"Source file path or URL for the evidence.\\\"\\n }\\n }\\n }\\n }\\n }\\n}\";\n","/**\n * Doctor — diagnostic checks for agent-contracts-runtime configuration health\n *\n * Each check returns a DoctorCheck with pass/fail/warn status.\n * The runner collects all checks and determines overall health.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport YAML from \"yaml\";\nimport { loadConfig, RuntimeConfigSchema, type ResolvedConfig } from \"../generator/config.js\";\nimport { checkFreshness } from \"../generator/index.js\";\n\nexport interface DoctorCheck {\n name: string;\n status: \"pass\" | \"fail\" | \"warn\";\n message?: string;\n}\n\nexport interface DoctorResult {\n checks: DoctorCheck[];\n all_passed: boolean;\n}\n\nconst ADAPTER_ENV_VARS: Record<string, string> = {\n claude: \"ANTHROPIC_API_KEY\",\n openai: \"OPENAI_API_KEY\",\n};\n\nasync function checkConfigExists(configPath: string): Promise<{ check: DoctorCheck; config?: ResolvedConfig }> {\n try {\n const config = await loadConfig(configPath);\n return {\n check: { name: \"config_exists\", status: \"pass\", message: `Loaded ${configPath}` },\n config,\n };\n } catch (err) {\n const absPath = resolve(configPath);\n if (!existsSync(absPath)) {\n return {\n check: { name: \"config_exists\", status: \"fail\", message: `Config file not found: ${absPath}` },\n };\n }\n return {\n check: { name: \"config_exists\", status: \"fail\", message: `Config parse error: ${(err as Error).message}` },\n };\n }\n}\n\nasync function checkDslExists(config: ResolvedConfig): Promise<DoctorCheck> {\n if (!existsSync(config.dslPath)) {\n return { name: \"dsl_exists\", status: \"fail\", message: `DSL file not found: ${config.dslPath}` };\n }\n\n try {\n const raw = await readFile(config.dslPath, \"utf8\");\n const parsed = YAML.parse(raw);\n if (!parsed || typeof parsed !== \"object\") {\n return { name: \"dsl_exists\", status: \"fail\", message: \"DSL file is empty or not a valid YAML object\" };\n }\n const agentCount = Object.keys(parsed.agents ?? {}).length;\n const taskCount = Object.keys(parsed.tasks ?? {}).length;\n const workflowCount = Object.keys(parsed.workflow ?? {}).length;\n return {\n name: \"dsl_exists\",\n status: \"pass\",\n message: `Parsed OK — ${agentCount} agent(s), ${taskCount} task(s), ${workflowCount} workflow(s)`,\n };\n } catch (err) {\n return { name: \"dsl_exists\", status: \"fail\", message: `DSL parse error: ${(err as Error).message}` };\n }\n}\n\nasync function checkManifestFresh(configPath: string, config: ResolvedConfig): Promise<DoctorCheck> {\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n\n if (!existsSync(manifestPath)) {\n return {\n name: \"manifest_fresh\",\n status: \"fail\",\n message: \"Generated manifest not found. Run `agent-runtime generate` first.\",\n };\n }\n\n try {\n const fresh = await checkFreshness(configPath);\n if (fresh) {\n return { name: \"manifest_fresh\", status: \"pass\", message: \"Generated files are up to date\" };\n }\n return {\n name: \"manifest_fresh\",\n status: \"fail\",\n message: \"Generated files are stale. Run `agent-runtime generate` to update.\",\n };\n } catch (err) {\n return { name: \"manifest_fresh\", status: \"fail\", message: `Freshness check error: ${(err as Error).message}` };\n }\n}\n\nfunction checkAdapterConfigured(): DoctorCheck {\n const configured: string[] = [];\n const missing: string[] = [];\n\n for (const [adapter, envVar] of Object.entries(ADAPTER_ENV_VARS)) {\n if (process.env[envVar]) {\n configured.push(adapter);\n } else {\n missing.push(`${adapter} (${envVar})`);\n }\n }\n\n if (configured.length > 0) {\n return {\n name: \"adapter_configured\",\n status: \"pass\",\n message: `Configured: ${configured.join(\", \")}${missing.length > 0 ? ` | Not set: ${missing.join(\", \")}` : \"\"}`,\n };\n }\n\n return {\n name: \"adapter_configured\",\n status: \"warn\",\n message: `No SDK adapter API keys found. Set one of: ${Object.entries(ADAPTER_ENV_VARS).map(([a, e]) => `${e} (${a})`).join(\", \")}`,\n };\n}\n\nasync function checkTsxAvailable(): Promise<DoctorCheck> {\n try {\n await import(\"tsx/esm\");\n return { name: \"tsx_available\", status: \"pass\", message: \"tsx is installed\" };\n } catch {\n return {\n name: \"tsx_available\",\n status: \"fail\",\n message: \"tsx is not installed. Required for loading generated .ts files. Run: npm install tsx\",\n };\n }\n}\n\nfunction checkPluginEntrypoints(config: ResolvedConfig): DoctorCheck {\n if (config.pluginPaths.length === 0) {\n return { name: \"plugin_entrypoint\", status: \"pass\", message: \"No plugins configured\" };\n }\n\n const missing: string[] = [];\n for (const p of config.pluginPaths) {\n const absPath = resolve(config.configDir, p);\n if (!existsSync(absPath)) {\n missing.push(p);\n }\n }\n\n if (missing.length === 0) {\n return {\n name: \"plugin_entrypoint\",\n status: \"pass\",\n message: `All ${config.pluginPaths.length} plugin file(s) found`,\n };\n }\n\n return {\n name: \"plugin_entrypoint\",\n status: \"fail\",\n message: `Missing plugin file(s): ${missing.join(\", \")}`,\n };\n}\n\nasync function checkBindingsValid(config: ResolvedConfig): Promise<DoctorCheck> {\n if (config.bindingPaths.length === 0) {\n return { name: \"bindings_valid\", status: \"pass\", message: \"No bindings configured\" };\n }\n\n const errors: string[] = [];\n for (const bp of config.bindingPaths) {\n if (!existsSync(bp)) {\n errors.push(`Not found: ${bp}`);\n continue;\n }\n try {\n const raw = await readFile(bp, \"utf8\");\n const parsed = YAML.parse(raw);\n if (!parsed || typeof parsed !== \"object\") {\n errors.push(`Invalid YAML object: ${bp}`);\n }\n } catch (err) {\n errors.push(`Parse error in ${bp}: ${(err as Error).message}`);\n }\n }\n\n if (errors.length === 0) {\n return {\n name: \"bindings_valid\",\n status: \"pass\",\n message: `All ${config.bindingPaths.length} binding file(s) valid`,\n };\n }\n\n return {\n name: \"bindings_valid\",\n status: \"fail\",\n message: errors.join(\"; \"),\n };\n}\n\nfunction checkLogDirectory(config: ResolvedConfig): DoctorCheck {\n const pl = config.resolvedLogging.progressLog;\n\n if (pl.destination === \"none\" || pl.destination === \"stderr\") {\n return { name: \"log_directory\", status: \"pass\", message: `Progress log destination: ${pl.destination}` };\n }\n\n if (!pl.file) {\n return {\n name: \"log_directory\",\n status: \"fail\",\n message: \"logging.progress_log.file is required when destination is 'file' or 'both'\",\n };\n }\n\n const dir = join(pl.file, \"..\");\n if (!existsSync(dir)) {\n return {\n name: \"log_directory\",\n status: \"warn\",\n message: `Log directory does not exist: ${dir} (will be created on first run)`,\n };\n }\n\n return { name: \"log_directory\", status: \"pass\", message: `Log file: ${pl.file} (naming: ${pl.naming})` };\n}\n\nexport async function runDoctor(configPath: string): Promise<DoctorResult> {\n const checks: DoctorCheck[] = [];\n\n // 1. Config exists and parses\n const configResult = await checkConfigExists(configPath);\n checks.push(configResult.check);\n\n if (!configResult.config) {\n return { checks, all_passed: false };\n }\n\n const config = configResult.config;\n\n // 2–7 can run concurrently since they only read state\n const [dslCheck, manifestCheck, pluginCheck, bindingsCheck, tsxCheck] = await Promise.all([\n checkDslExists(config),\n checkManifestFresh(configPath, config),\n Promise.resolve(checkPluginEntrypoints(config)),\n checkBindingsValid(config),\n checkTsxAvailable(),\n ]);\n\n checks.push(dslCheck);\n checks.push(manifestCheck);\n checks.push(checkAdapterConfigured());\n checks.push(pluginCheck);\n checks.push(bindingsCheck);\n checks.push(tsxCheck);\n checks.push(checkLogDirectory(config));\n\n const all_passed = checks.every((c) => c.status !== \"fail\");\n\n return { checks, all_passed };\n}\n","/**\n * init — scaffold a new agent-contracts-runtime project\n */\n\nimport { existsSync } from \"node:fs\";\nimport { mkdir, writeFile, readFile, appendFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nexport interface InitOptions {\n adapter: string;\n outputDir: string;\n force: boolean;\n}\n\nexport interface InitResult {\n files_created: string[];\n}\n\ninterface FileEntry {\n relativePath: string;\n content: string;\n}\n\nfunction buildConfigYaml(_adapter: string): string {\n return `plugins:\n - ./agent/src/plugins/example-plugin.ts\nrecovery:\n max_follow_ups: 2\n max_retries: 0\n# model_mapping:\n# standard:\n# adapter: claude\n# model: claude-opus-4-6\nmodel_mapping: {}\n`;\n}\n\nconst EXAMPLE_PLUGIN_TS = `\\\nimport type { AgentPlugin } from \"agent-contracts-runtime\";\n\n/**\n * Example plugin — extend agent-contracts-runtime with custom hooks.\n *\n * Register lifecycle hooks for tasks and workflows:\n * beforeTask / afterTask — pre/post-process task execution\n * contextEnhancer — augment task context before prompt generation\n * promptEnhancer — post-process generated prompts\n * customGuardrails — add project-specific guardrail checks\n * beforeWorkflow / afterWorkflow — workflow lifecycle hooks\n *\n * See https://github.com/foo-log-inc/agent-contracts-runtime#plugins\n */\nexport const examplePlugin: AgentPlugin = {\n id: \"example-plugin\",\n\n // Uncomment hooks as needed:\n\n // async beforeTask(taskId, context) {\n // console.log(\\`[example-plugin] beforeTask: \\${taskId}\\`);\n // return context;\n // },\n\n // async afterTask(taskId, outcome) {\n // console.log(\\`[example-plugin] afterTask: \\${taskId} — \\${outcome.status}\\`);\n // return outcome;\n // },\n\n // promptEnhancer(taskId, prompt, _context) {\n // return prompt + \"\\\\n\\\\n<!-- enhanced by example-plugin -->\";\n // },\n};\n\nexport default examplePlugin;\n`;\n\nconst CUSTOM_GUARDRAILS_TS = `\\\nimport type { AgentPlugin, GuardrailResult } from \"agent-contracts-runtime\";\n\n/**\n * Custom guardrails — project-specific safety checks.\n *\n * Implement evaluateCommand, evaluateFilePath, or evaluateFileContent\n * to enforce project rules beyond the built-in guardrails.\n *\n * See https://github.com/foo-log-inc/agent-contracts-runtime#guardrails\n */\nexport const customGuardrailsPlugin: AgentPlugin = {\n id: \"custom-guardrails\",\n\n customGuardrails: {\n // evaluateCommand(command: string): GuardrailResult[] {\n // const results: GuardrailResult[] = [];\n // // Example: block dangerous patterns\n // if (command.includes(\"DROP TABLE\")) {\n // results.push({\n // matched: true,\n // guardrail_id: \"no-drop-table\",\n // severity: \"critical\",\n // action: \"block\",\n // message: \"DROP TABLE is forbidden\",\n // });\n // }\n // return results;\n // },\n },\n};\n\nexport default customGuardrailsPlugin;\n`;\n\nconst GITIGNORE_ENTRIES = [\n \"\",\n \"# agent-contracts-runtime generated files\",\n \"agent/generated/\",\n];\n\nfunction buildScaffoldFiles(adapter: string): FileEntry[] {\n return [\n {\n relativePath: \"agents.conf.yaml\",\n content: buildConfigYaml(adapter),\n },\n {\n relativePath: \"agent/src/plugins/example-plugin.ts\",\n content: EXAMPLE_PLUGIN_TS,\n },\n {\n relativePath: \"agent/src/guardrails/custom-guardrails.ts\",\n content: CUSTOM_GUARDRAILS_TS,\n },\n ];\n}\n\nexport async function runInit(options: InitOptions): Promise<InitResult> {\n const { adapter, outputDir, force } = options;\n const files_created: string[] = [];\n\n const entries = buildScaffoldFiles(adapter);\n\n for (const entry of entries) {\n const absPath = join(outputDir, entry.relativePath);\n if (!force && existsSync(absPath)) {\n throw new Error(\n `File already exists: ${entry.relativePath}. Use --force to overwrite.`,\n );\n }\n }\n\n for (const entry of entries) {\n const absPath = join(outputDir, entry.relativePath);\n const dir = join(absPath, \"..\");\n await mkdir(dir, { recursive: true });\n await writeFile(absPath, entry.content, \"utf8\");\n files_created.push(entry.relativePath);\n }\n\n const gitignorePath = join(outputDir, \".gitignore\");\n if (existsSync(gitignorePath)) {\n const existing = await readFile(gitignorePath, \"utf8\");\n if (!existing.includes(\"agent/generated/\")) {\n await appendFile(gitignorePath, GITIGNORE_ENTRIES.join(\"\\n\") + \"\\n\", \"utf8\");\n files_created.push(\".gitignore\");\n }\n } else {\n await writeFile(gitignorePath, GITIGNORE_ENTRIES.join(\"\\n\").trimStart() + \"\\n\", \"utf8\");\n files_created.push(\".gitignore\");\n }\n\n return { files_created };\n}\n","/**\n * implement command — uses the built-in LLM Feature Implementer agent\n * to add LLM-powered commands to a CLI tool project.\n *\n * The agent is defined in DSL (dsl/implement-dsl.yaml) and its contracts\n * are pre-generated into src/builtin-agents/generated/.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { runWorkflow } from \"./workflow-runner.js\";\nimport { buildTaskPrompt } from \"./task-runner.js\";\nimport type { SdkAdapter, TaskContext } from \"./task-runner.js\";\nimport type { WorkflowInvocation } from \"./workflow-runner.js\";\nimport {\n agentRegistry,\n taskRegistry,\n handoffSchemas,\n workflowRegistry,\n resolvedDsl,\n} from \"../builtin-agents/generated/index.js\";\nimport {\n createGuardrailHooksFromRules,\n type GuardrailHooks,\n type GuardrailRuleData,\n} from \"./guardrail-hooks.js\";\nimport type { ImplementationResult } from \"../builtin-agents/generated/handoffs.js\";\n\n// ---------------------------------------------------------------------------\n// Locale detection\n// ---------------------------------------------------------------------------\n\nfunction getLocale(): string {\n return (\n process.env.LANG?.split(\".\")[0] ??\n process.env.LC_ALL?.split(\".\")[0] ??\n process.env.LANGUAGE?.split(\":\")[0] ??\n \"en_US\"\n );\n}\n\nfunction isJapanese(): boolean {\n return getLocale().startsWith(\"ja\");\n}\n\n// ---------------------------------------------------------------------------\n// Messages — locale-aware\n// ---------------------------------------------------------------------------\n\ninterface Messages {\n noProjectDir: (dir: string) => string;\n adapterError: (msg: string) => string;\n dryRunHeader: string;\n dryRunProjectDir: (dir: string) => string;\n dryRunDescription: (desc: string) => string;\n dryRunRefIncluded: string;\n dryRunRefNotFound: string;\n implementStarting: (adapter: string) => string;\n implementSuccess: string;\n implementFailed: (reason: string) => string;\n filesCreated: string;\n filesModified: string;\n commandsAdded: string;\n nextSteps: string;\n}\n\nconst en: Messages = {\n noProjectDir: (dir) => `Project directory not found: ${dir}`,\n adapterError: (msg) => `Adapter initialization failed: ${msg}`,\n dryRunHeader: \"=== Dry Run ===\",\n dryRunProjectDir: (dir) => `Project: ${dir}`,\n dryRunDescription: (desc) => `Description: ${desc}`,\n dryRunRefIncluded: \"Reference: integrate-llm-commands (included)\",\n dryRunRefNotFound: \"Reference: integrate-llm-commands (not found, will proceed without)\",\n implementStarting: (adapter) => `Starting implementation with ${adapter} adapter...`,\n implementSuccess: \"Implementation completed successfully.\",\n implementFailed: (reason) => `Implementation failed: ${reason}`,\n filesCreated: \"Files created:\",\n filesModified: \"Files modified:\",\n commandsAdded: \"Commands added:\",\n nextSteps: \"Next steps:\",\n};\n\nconst ja: Messages = {\n noProjectDir: (dir) => `プロジェクトディレクトリが見つかりません: ${dir}`,\n adapterError: (msg) => `アダプター初期化に失敗しました: ${msg}`,\n dryRunHeader: \"=== ドライラン ===\",\n dryRunProjectDir: (dir) => `プロジェクト: ${dir}`,\n dryRunDescription: (desc) => `説明: ${desc}`,\n dryRunRefIncluded: \"リファレンス: integrate-llm-commands(含まれています)\",\n dryRunRefNotFound: \"リファレンス: integrate-llm-commands(未検出、リファレンスなしで続行)\",\n implementStarting: (adapter) => `${adapter} アダプターで実装を開始します...`,\n implementSuccess: \"実装が正常に完了しました。\",\n implementFailed: (reason) => `実装に失敗しました: ${reason}`,\n filesCreated: \"作成されたファイル:\",\n filesModified: \"変更されたファイル:\",\n commandsAdded: \"追加されたコマンド:\",\n nextSteps: \"次のステップ:\",\n};\n\nfunction msg(): Messages {\n return isJapanese() ? ja : en;\n}\n\n// ---------------------------------------------------------------------------\n// Reference document loader\n// ---------------------------------------------------------------------------\n\nfunction loadReferenceDoc(): string | undefined {\n const candidates = [\n // Shipped with the package (templates/ sibling of dist/)\n join(fileURLToPath(import.meta.url), \"..\", \"..\", \"..\", \"templates\", \"implement-reference.md\"),\n // Dev-time: from the skill directory\n join(process.env.HOME ?? \"\", \".cursor\", \"skills\", \"integrate-llm-commands\", \"SKILL.md\"),\n ];\n\n for (const candidate of candidates) {\n try {\n if (existsSync(candidate)) {\n return readFileSync(candidate, \"utf8\");\n }\n } catch {\n // continue\n }\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\nasync function createImplementAdapter(\n adapterName: string,\n projectDir: string,\n model?: string,\n guardrailHooks?: GuardrailHooks,\n): Promise<SdkAdapter> {\n switch (adapterName) {\n case \"claude\": {\n const { ClaudeAgentSdkAdapter } = await import(\"../adapters/claude-agent-sdk.js\");\n return new ClaudeAgentSdkAdapter({\n cwd: projectDir,\n permissionMode: \"bypassPermissions\",\n model,\n guardrailHooks,\n });\n }\n case \"mock\": {\n const { MockAdapter } = await import(\"../adapters/mock.js\");\n return new MockAdapter();\n }\n default:\n throw new Error(\n `Unsupported adapter for implement: \"${adapterName}\". ` +\n `Available: claude, mock`,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface ImplementOptions {\n adapter: string;\n projectDir: string;\n dryRun: boolean;\n reportFormat: \"json\" | \"text\" | \"yaml\";\n model?: string;\n verbose?: boolean;\n progressOutput?: { write(chunk: string): unknown };\n}\n\nexport interface ImplementRunResult {\n status: \"success\" | \"failed\" | \"dry_run\";\n exitCode: number;\n data?: ImplementationResult;\n error?: string;\n}\n\nexport async function runImplement(\n description: string,\n options: ImplementOptions,\n): Promise<ImplementRunResult> {\n const m = msg();\n const projectDir = resolve(options.projectDir);\n\n if (!existsSync(projectDir)) {\n return { status: \"failed\", exitCode: 3, error: m.noProjectDir(projectDir) };\n }\n\n const referenceDoc = loadReferenceDoc();\n\n // --- Build invocation context (shared between dry-run and live run) ---\n const userRequest = [\n description,\n \"\",\n `Project directory: ${projectDir}`,\n ].join(\"\\n\");\n\n const context: TaskContext = {\n user_request: userRequest,\n relevant_paths: [projectDir],\n };\n\n if (referenceDoc) {\n context.prior_context =\n \"# Reference: integrate-llm-commands pattern\\n\\n\" +\n \"Follow this reference exactly when implementing LLM commands.\\n\\n\" +\n referenceDoc;\n }\n\n // --- Dry run: emit the real prompt without calling the LLM ---\n if (options.dryRun) {\n const agent = agentRegistry[\"llm-feature-implementer\"];\n const task = taskRegistry[\"implement-llm-feature\"];\n const prompt = buildTaskPrompt(agent, task, context, { handoffSchemas });\n\n return {\n status: \"dry_run\",\n exitCode: 0,\n data: {\n files_created: [],\n files_modified: [],\n summary: prompt,\n },\n };\n }\n\n // --- Create adapter ---\n let guardrailHooks: GuardrailHooks | undefined;\n const rawRules = resolvedDsl._guardrailRules as GuardrailRuleData | undefined;\n if (\n rawRules &&\n (rawRules.commandRules?.length ||\n rawRules.fileRules?.length ||\n rawRules.contentRules?.length)\n ) {\n guardrailHooks = createGuardrailHooksFromRules(rawRules);\n }\n\n let adapter: SdkAdapter;\n try {\n adapter = await createImplementAdapter(\n options.adapter,\n projectDir,\n options.model,\n guardrailHooks,\n );\n } catch (err) {\n return { status: \"failed\", exitCode: 12, error: m.adapterError((err as Error).message) };\n }\n\n if (!options.verbose) {\n console.error(m.implementStarting(options.adapter));\n }\n\n const registries = {\n workflowRegistry,\n taskRegistry,\n agentRegistry,\n handoffSchemas,\n };\n\n // --- Run workflow ---\n const invocation: WorkflowInvocation = {\n workflow: \"implement-llm-feature\",\n user_request: userRequest,\n runtime: {\n maxFollowUps: 3,\n maxRetries: 1,\n },\n hooks: {\n onGate: async () => true,\n },\n context: {\n cwd: projectDir,\n },\n progressOutput: options.progressOutput,\n };\n\n const result = await runWorkflow(adapter, invocation, registries);\n\n if (result.status !== \"completed\") {\n const reason = result.escalation_reason ?? result.error_message ?? result.status;\n return { status: \"failed\", exitCode: 1, error: m.implementFailed(reason) };\n }\n\n // Extract structured result from the last successful step\n const lastStep = result.steps[result.steps.length - 1];\n const outcomeData = (lastStep?.outcome as Record<string, unknown>)?.data as\n | ImplementationResult\n | undefined;\n\n return {\n status: \"success\",\n exitCode: 0,\n data: outcomeData ?? {\n files_created: [],\n files_modified: [],\n summary: m.implementSuccess,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Text formatter\n// ---------------------------------------------------------------------------\n\nexport function formatImplementResult(result: ImplementRunResult): string {\n const m = msg();\n\n if (result.status === \"dry_run\") {\n return result.data?.summary ?? m.dryRunHeader;\n }\n\n if (result.status === \"failed\") {\n return result.error ?? m.implementFailed(\"unknown\");\n }\n\n const data = result.data;\n if (!data) return m.implementSuccess;\n\n const lines: string[] = [data.summary, \"\"];\n\n if (data.files_created.length > 0) {\n lines.push(m.filesCreated);\n for (const f of data.files_created) lines.push(` + ${f}`);\n lines.push(\"\");\n }\n\n if (data.files_modified.length > 0) {\n lines.push(m.filesModified);\n for (const f of data.files_modified) lines.push(` ~ ${f}`);\n lines.push(\"\");\n }\n\n if (data.commands_added && data.commands_added.length > 0) {\n lines.push(m.commandsAdded);\n for (const c of data.commands_added) {\n lines.push(` - ${c.name} [${c.type}]${c.description ? ` — ${c.description}` : \"\"}`);\n }\n lines.push(\"\");\n }\n\n if (data.next_steps && data.next_steps.length > 0) {\n lines.push(m.nextSteps);\n for (const s of data.next_steps) lines.push(` ${s}`);\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\nexport interface AgentRule {\n readonly id: string;\n readonly description: string;\n readonly severity: \"mandatory\" | \"recommended\" | \"optional\";\n}\n\nexport interface EscalationCriterion {\n readonly condition: string;\n readonly action: \"stop_and_report\" | \"report_to_architect\" | \"wait_for_approval\";\n}\n\nexport interface AgentContract {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly dispatch_only: boolean;\n readonly can_read_artifacts: readonly string[];\n readonly can_write_artifacts: readonly string[];\n readonly can_execute_tools: readonly string[];\n readonly can_invoke_agents: readonly string[];\n readonly can_return_handoffs: readonly string[];\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n readonly rules: readonly AgentRule[];\n readonly escalation_criteria: readonly EscalationCriterion[];\n}\n\nexport const implementationAuditor: AgentContract = {\n id: \"implementation-auditor\",\n role_name: \"Implementation Auditor\",\n purpose: \"Audits an existing LLM command integration to verify it correctly\\nfollows the agent-contracts + agent-contracts-runtime + cli-contracts\\nstack conventions. Detects architectural violations, missing patterns,\\nincorrect API usage, and deviations from the canonical\\nintegrate-llm-commands pattern.\\n\\nThis agent is read-only — it analyzes code but does not modify it.\\nIt produces structured findings (AgentAuditResult) that identify\\nexactly what is wrong and how to fix it.\\n\\n## What This Agent Checks\\n\\n### Layer 1: agent-contracts DSL\\n- DSL entry has version:1 and system block with id/name\\n- Agents defined with all required fields (role_name, purpose, mode,\\n can_read_artifacts, can_write_artifacts, responsibilities, constraints)\\n- Tasks have target_agent, workflow, result_handoff, completion_criteria\\n- Handoff type schemas conform to AgentAuditResult base shape\\n- Workflows define steps with correct task/agent cross-references\\n- Guardrails and guardrail_policies are defined\\n- agent-runtime.config.yaml exists with dsl and generated_dir\\n\\n### Layer 2: agent-contracts-runtime Integration\\n- orchestrator.ts uses runWorkflow(), NOT runTask() or adapter.send()\\n- runTask() is a low-level internal API — consumer projects must\\n use runWorkflow() which handles workflow DAG, plugin hooks, gates\\n- Adapters imported from agent-contracts-runtime/adapters/*, not custom\\n- Dynamic import pattern for graceful degradation (exit 11/12)\\n- Generated registries imported from src/generated/dsl/index.js\\n- Registries (including workflowRegistry) passed to runWorkflow\\n- Plugin hooks not bypassed\\n- No hand-rolled prompt building (use buildTaskPrompt or let runWorkflow do it)\\n\\n### Layer 3: cli-contracts Compliance\\n- cli-contract.yaml has LLM commands with all standard options:\\n --adapter, --model, --show-prompt, --fail-on, --output, --report-format\\n- x-agent metadata present (riskLevel, safeDryRunOption, expectedDurationMs)\\n- Exit codes follow convention (0, 1, 3, 10, 11, 12)\\n- components/schemas includes AgentAuditResult and related types\\n- --report-format used (not --format) for LLM commands\\n\\n### Architecture & Patterns\\n- src/agents/ module structure (orchestrator, context-builder, formatter, types)\\n- Context builder caps input at 16KB\\n- Formatter implements computeExitCode with correct threshold logic\\n- --show-prompt returns prompt without LLM call\\n- No direct LLM API calls anywhere in the codebase\\n\\n### Semantic Design Coherence\\n- Context-builder must contain only domain DATA (file contents,\\n config, scan results) — never agent INSTRUCTIONS (evaluation\\n criteria, rules, anti-patterns, output format specifications).\\n These belong in the DSL agent definition and are injected by\\n buildTaskPrompt / runWorkflow. Hardcoding instructions in\\n context-builder defeats the purpose of using DSL.\\n- Agent mode must match purpose: read-only agents must not have\\n write-oriented purposes, read-write agents must propagate cwd\\n to their adapter so file tools operate in the project directory.\\n- CLI must use cli-contracts' generated CommandHandlers interface\\n and createProgram() — not manually wired Commander commands.\\n\",\n mode: \"read-only\",\n dispatch_only: false,\n can_read_artifacts: [],\n can_write_artifacts: [],\n can_execute_tools: [],\n can_invoke_agents: [],\n can_return_handoffs: [\n \"audit-result\"\n],\n responsibilities: [\n \"Verify the DSL directory structure exists: dsl/{project}-dsl.yaml, dsl/agents/*.yaml, dsl/tasks.yaml, dsl/handoff-types.yaml, dsl/agent-runtime.config.yaml.\",\n \"Check that the main DSL entry has version:1, a system block with id and name, and uses $ref for agents/tasks/handoff_types.\",\n \"Validate agent definitions have all required fields: role_name, purpose, mode, can_read_artifacts:[], can_write_artifacts:[], responsibilities, constraints. Check that rules use R-PREFIX-NNN format and severity is mandatory|recommended|optional.\",\n \"Validate task definitions: target_agent matches a defined agent, workflow matches a defined workflow, result_handoff matches a defined handoff type, completion_criteria are specific and testable.\",\n \"Verify handoff type schemas conform to AgentAuditResult shape when applicable (summary, riskLevel, findings[], recommendedActions[], metadata). Check $ref usage and SSoT comments for inlined schemas.\",\n \"Check that guardrails and guardrail_policies are defined, and that output-schema-conformance is included.\",\n \"Scan src/agents/orchestrator.ts for: (1) imports from agent-contracts-runtime (not custom SDK wrappers), (2) usage of runWorkflow() — NOT runTask() which is a low-level internal API that bypasses workflow orchestration, plugin hooks, and gate steps, (3) dynamic import pattern with exit code 11 for missing runtime and exit code 12 for adapter errors, (4) generated registries (including workflowRegistry) imported and passed to runWorkflow.\",\n \"Verify no file in the project calls adapter.send(), adapter.followUp(), adapter.sendExecution(), or runTask() directly — all LLM invocations must go through runWorkflow().\",\n \"Check that src/generated/dsl/ exists and contains the expected files (agents.ts, tasks.ts, workflows.ts, handoffs.ts, index.ts). Verify the .manifest.json exists and is not stale.\",\n \"Verify adapter creation uses the correct constructors: ClaudeAgentSdkAdapter constructor, OpenAIAgentsSdkAdapter constructor, etc.\",\n \"Check cli-contract.yaml for each LLM command: all six standard options present (--adapter, --model, --show-prompt, --fail-on, --output, --report-format). Verify --report-format is used (not --format).\",\n \"Verify x-agent metadata on each LLM command: riskLevel, safeDryRunOption (must be \\\"show-prompt\\\"), expectedDurationMs. Flag high-risk commands without requiresConfirmation.\",\n \"Check exit code definitions: 0 (success), 1 (error), 3 (validation), 10 (findings), 11 (runtime missing), 12 (adapter error).\",\n \"Verify components/schemas includes AgentAuditResult, AgentFinding, AgentRecommendedAction, and AgentEvidence definitions.\",\n \"Verify src/agents/ directory structure: types.ts (TaskId, AgentConfig, AgentOptions, AgentRunResult), orchestrator.ts (createAdapter, runAgentTask with dynamic imports), context-builder.ts (build*Context functions with 16KB cap), formatter.ts (computeExitCode, formatResultText, formatResultJson).\",\n \"Check that --show-prompt mode returns the constructed prompt without making any LLM API call.\",\n \"Scan for direct LLM API imports (@anthropic-ai/sdk, openai, @google/genai) used outside of adapter files — application code must not import these directly.\",\n \"Audit context-builder for SSoT violations: scan for hardcoded agent instructions (sections titled \\\"## Instructions\\\", \\\"## Required Patterns\\\", \\\"## Output Format\\\", evaluation criteria, checklists, anti-pattern definitions, API references, or output schema descriptions). These belong in the DSL agent definition and are injected by buildTaskPrompt. Context-builder should contain only domain-specific data (file contents, configuration, scan results, project metadata).\",\n \"Check agent mode-purpose coherence: for each agent in the DSL, verify that mode: read-only agents do not have purposes or responsibilities describing file writing/editing/creation, and that mode: read-write agents propagate cwd through AgentConfig to the adapter so file tools operate in the correct directory.\",\n \"Verify cwd propagation: command handlers must set cwd in AgentConfig (e.g. process.cwd() or resolve(projectDir)), createAdapter must pass cwd to adapter constructors/factories, and AgentConfig type must include a cwd field.\",\n \"Verify cli-contracts handler wiring: if the project uses cli-contracts (has src/generated/program.ts or src/generated/cli/program.ts exporting CommandHandlers and createProgram), the CLI entry point must use createProgram(handlers, version) with a handlers object implementing the CommandHandlers interface — not manually created Commander commands.\"\n],\n constraints: [\n \"This agent is read-only. It must not create, modify, or delete any files. Output is a structured audit report only.\",\n \"Findings must include specific file paths, line references where possible, and concrete remediation steps.\",\n \"Severity classification: critical = breaks the integration pattern (direct API calls, missing runtime usage), error = missing required element (no x-agent, missing standard option), warning = deviation from best practice (context not capped, missing guardrail), info = improvement suggestion.\",\n \"Category vocabulary: dsl-structure, dsl-agent, dsl-task, dsl-handoff, dsl-workflow, dsl-guardrail, runtime-adapter, runtime-orchestrator, runtime-registry, runtime-handler, runtime-plugin, cli-contract-options, cli-contract-xagent, cli-contract-exits, cli-contract-schema, architecture-modules, architecture-dry-run, architecture-context-builder, architecture-agent-coherence, architecture-adapter-cwd, architecture-handler, architecture-formatter.\",\n \"Every finding with severity warning or above must include a recommendation field with a concrete fix.\",\n \"The confidence field should reflect how certain the finding is: 1.0 for pattern matches (e.g., adapter.send() found in code), 0.8+ for structural checks (e.g., missing file), 0.5-0.8 for heuristic assessments (e.g., context might exceed 16KB).\"\n],\n rules: [\n {\n \"id\": \"R-AUDIT-001\",\n \"description\": \"Every finding must specify target (file path) and category (from the defined category vocabulary). Findings without a target are not actionable.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-002\",\n \"description\": \"The audit must check all four layers (DSL, runtime, CLI contract, architecture). Skipping a layer or returning partial results is not acceptable.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-003\",\n \"description\": \"Critical findings must be surfaced for: (1) direct adapter.send() calls bypassing runWorkflow, (2) runTask() used instead of runWorkflow() — runTask is a low-level internal API that bypasses workflow orchestration, (3) custom adapter classes not from agent-contracts-runtime, (4) missing generated registries in runWorkflow calls.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-004\",\n \"description\": \"The riskLevel in the audit result must be derived from the most severe finding: any critical → critical, any error → high, any warning → medium, info only → low.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-005\",\n \"description\": \"Context-builder must be audited for SSoT violations. Any hardcoded agent instructions (evaluation criteria, rules, anti-patterns, output format specs) in context-builder is a critical finding — these belong in the DSL agent definition and are injected by buildTaskPrompt / runWorkflow. Context-builder may only contain domain-specific data (file contents, configuration, scan results, project metadata).\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-007\",\n \"description\": \"runTask() usage in consumer projects is a CRITICAL finding. Consumer projects integrating with cli-contracts must use runWorkflow() exclusively. runTask() is a low-level internal API that bypasses workflow DAG orchestration, workflow-level plugin hooks (beforeWorkflow/afterWorkflow), gate steps, and step dependencies. Any occurrence of runTask import or call in orchestrator, command handler, or CLI entry point code must be reported as severity: critical.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-006\",\n \"description\": \"Agent mode-purpose coherence must be verified. A read-only agent whose purpose describes file writing is a critical finding because the adapter's tool set (Read/Glob/Grep only) makes the stated purpose impossible to fulfil.\",\n \"severity\": \"mandatory\"\n }\n],\n escalation_criteria: [\n {\n \"condition\": \"Target project has no LLM command integration to audit\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project uses a completely different integration pattern (not agent-contracts stack)\",\n \"action\": \"stop_and_report\"\n }\n],\n} as const;\n\nexport const llmFeatureImplementer: AgentContract = {\n id: \"llm-feature-implementer\",\n role_name: \"LLM Feature Implementer\",\n purpose: \"Expert implementation agent for the agent-contracts toolchain.\\nAdds LLM-powered commands (audit, propose, explain, etc.) to CLI tools\\nusing the three-layer stack:\\n\\n1. **agent-contracts** — DSL package. Defines agents, tasks, workflows,\\n handoff types, guardrails, and guardrail policies in YAML. The\\n `resolve()` function handles `$ref`, `extends`, and merge operators.\\n Installed as a devDependency. CLI: `agent-contracts audit`.\\n\\n2. **agent-contracts-runtime** — Runtime bridge. Generates typed\\n TypeScript contracts from DSL via Handlebars templates, then\\n executes workflows through pluggable SDK adapters. Provides\\n `runTask()`, `runWorkflow()`, `createRuntime()`, plugin system,\\n and guardrail hooks. CLI: `agent-runtime generate|run|list|doctor`.\\n\\n3. **cli-contracts** — CLI contract package. Defines command-line\\n interfaces in YAML (`cli-contract.yaml`): command sets, arguments,\\n options, exit codes, stdout/stderr schemas, `x-agent` metadata,\\n and `effects`. Generates typed Commander programs, Zod validators,\\n and markdown docs. CLI: `cli-contracts init|generate|validate`.\\n\\nThe canonical integration pattern (\\\"integrate-llm-commands\\\") produces:\\n- DSL definitions under `dsl/` (agents, tasks, workflows, handoff-types)\\n- Pre-generated TypeScript contracts under `src/generated/dsl/`\\n- Runtime integration module under `src/agents/` (orchestrator,\\n context-builder, formatter, types)\\n- CLI command handlers under `src/commands/`\\n- Updated `cli-contract.yaml` with new commands and `x-agent` metadata\\n\",\n mode: \"read-write\",\n dispatch_only: false,\n can_read_artifacts: [],\n can_write_artifacts: [],\n can_execute_tools: [],\n can_invoke_agents: [],\n can_return_handoffs: [\n \"implementation-result\"\n],\n responsibilities: [\n \"Read and analyze the target project's cli-contract.yaml, package.json, tsconfig.json, and existing source code to understand the CLI structure, existing commands, component schemas, and TypeScript configuration.\",\n \"Identify which LLM commands to add based on the user's description. Canonical command types: audit (semantic review), propose (structured proposal generation), explain (human-readable explanation of machine output).\",\n \"Create the DSL directory structure: dsl/{project}-dsl.yaml (main entry with version:1, system block, $ref to sub-files), dsl/agents/{name}.yaml, dsl/tasks.yaml, dsl/handoff-types.yaml, dsl/agent-runtime.config.yaml.\",\n \"Define agents with: role_name, purpose (domain expertise), mode (read-only for analysis agents), can_read_artifacts:[], can_write_artifacts:[], can_return_handoffs, responsibilities, constraints, rules (R-PREFIX-NNN format), escalation_criteria.\",\n \"Define tasks with: description, target_agent, allowed_from_agents, workflow (must match a workflow ID), invocation_handoff, result_handoff, responsibilities, completion_criteria.\",\n \"Define handoff types with: version:1, description, schema (JSON Schema). Result types should conform to AgentAuditResult shape (summary, riskLevel, findings[], recommendedActions[], metadata). Use $ref to cli-contract.yaml components/schemas as SSoT when possible; inline with SSoT comment as fallback.\",\n \"Define workflows with trigger, entry_conditions, and steps (delegate or gate). Each delegate step references a task and from_agent. Gate steps pause for user approval.\",\n \"Define guardrails (output-schema-conformance, domain-specific safety) and guardrail_policies grouping them with severity and action.\",\n \"Create agent-runtime.config.yaml: dsl points to main DSL file, generated_dir points to src/generated/dsl.\",\n \"Implement src/agents/types.ts: TaskId union type, AgentConfig interface (adapter, model, temperature), AgentOptions interface (dryRun, failOn), AgentRunResult interface (taskId, data, raw, prompt, dryRun, status, errorMessage, followUpsUsed, retriesUsed).\",\n \"Implement src/agents/orchestrator.ts: createAdapter() with dynamic imports from agent-contracts-runtime/adapters/*, runAgentWorkflow() that imports runWorkflow from agent-contracts-runtime, loads generated registries (including workflowRegistry) from src/generated/dsl/index.js, and calls runWorkflow with registries. NEVER use runTask — it is a low-level internal API that bypasses workflow orchestration.\",\n \"Implement src/agents/context-builder.ts: build{Command}Context() functions that transform CLI inputs into structured markdown prompts. Cap context at 16KB. Structure: # Request, ## Configuration, ## Target, ## Instructions.\",\n \"Implement src/agents/formatter.ts: computeExitCode() mapping findings to exit codes via --fail-on threshold, formatResultText() with severity icons, formatResultJson() for structured output.\",\n \"Create src/commands/{command}.ts handlers: load config, call context builder, call runAgentWorkflow, format output, compute exit code.\",\n \"Update cli-contract.yaml: add command definitions with standard LLM options (--adapter, --model, --show-prompt, --fail-on, --output, --report-format), exit codes (0, 1, 3, 10, 11, 12), x-agent metadata, and register AgentAuditResult/AgentFinding/AgentRecommendedAction in components/schemas.\",\n \"Add npm scripts: \\\"dsl:generate\\\" running agent-runtime generate --config dsl/agent-runtime.config.yaml. Add agent-contracts and agent-contracts-runtime as devDependencies. Add SDK packages as optional peerDependencies.\"\n],\n constraints: [\n \"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk, GeminiSdkAdapter from agent-contracts-runtime/adapters/gemini-sdk, MockAdapter from agent-contracts-runtime/adapters/mock.\",\n \"NEVER call adapter.send() or adapter.sendExecution() directly. All LLM invocations must go through runWorkflow() imported from agent-contracts-runtime. NEVER use runTask() — it is a low-level internal API. runWorkflow() handles prompt building, handoff validation, retry/followUp, workflow DAG, and plugin hooks.\",\n \"Dynamic-import both agent-contracts-runtime and adapter packages. The tool must work without them installed (graceful degradation). Pattern: const RUNTIME = \\\"agent-contracts-runtime\\\"; try { const { runWorkflow } = await import(RUNTIME); } catch { exit(11); }\",\n \"LLM commands use --report-format (json|text|yaml) for output format. --format is reserved for deterministic commands. Never mix them.\",\n \"Exit code convention: 0=success (no findings above threshold), 1=general error, 3=input validation/parse failed, 10=findings detected above --fail-on threshold, 11=agent-contracts-runtime not installed, 12=adapter initialization error (missing API key, etc.).\",\n \"Standard LLM command options (all must be present): --adapter <name> (mock|claude|openai|gemini, default varies), --model <name> (optional override), --show-prompt (output prompt without LLM call), --fail-on <level> (warning|error|critical, default error), --output/-o <file> (write to file instead of stdout), --report-format <fmt> (json|text|yaml, default json).\",\n \"Result handoff schemas must extend the AgentAuditResult base shape: summary (string, required), riskLevel (enum: low|medium|high|critical, required), findings (AgentFinding[], required), recommendedActions (AgentRecommendedAction[], optional), metadata (object with tool, command, version, generatedAt, adapter, model fields, optional).\",\n \"AgentFinding shape: id?, severity (info|warning|error|critical), category (domain vocabulary), target?, location?, message (required), recommendation?, confidence? (0-1), evidence? (array of {type,content,source}), details? (object).\",\n \"AgentRecommendedAction shape: kind (run_command|edit_file|review|confirm| block|ignore), title (required), command?, target?, rationale?.\",\n \"Main DSL entry must have version:1 and a system block with id and name. Without these, the generator produces numbered files instead of named ones.\",\n \"Every task must have a workflow field matching a defined workflow ID. Every workflow step's from_agent must match a defined agent ID. can_read_artifacts and can_write_artifacts must be empty arrays ([]) when no artifact registry is defined.\",\n \"agent-runtime.config.yaml format: dsl: ./{project}-dsl.yaml generated_dir: ../src/generated/dsl Optional: plugins (array of paths), recovery ({max_follow_ups, max_retries}).\",\n \"runWorkflow (the ONLY API consumer projects should use): Overloads: (1) runWorkflow(adapter, workflowId, options, registries?) — legacy. (2) runWorkflow(adapter, invocation, registries?) — structured (preferred). WorkflowInvocation: { workflow, handoff?, user_request?, runtime? {maxFollowUps,maxRetries,timeoutMs,readonly, dryRun}, hooks? {onStepComplete,onGate,onOptionalStep}, context? {cwd,environment,artifacts,variables} }. WorkflowResult: { workflow_id, status (completed|escalated|gate_rejected|error), steps[], total_elapsed_ms, escalation_reason?, error_message? }. NEVER use runTask() — it is a low-level internal API.\",\n \"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?}), GeminiSdkAdapter({apiKey?, model?, systemInstruction?, temperature?, maxOutputTokens?, guardrailHooks?}).\",\n \"Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from \\\"../generated/dsl/index.js\\\". Pass these as registries to runWorkflow: { workflowRegistry, taskRegistry, agentRegistry, handoffSchemas }.\",\n \"Plugin interface (AgentPlugin): id (string), beforeTask?(taskId, context), afterTask?(taskId, outcome), contextEnhancer?(taskId, context), promptEnhancer?(taskId, prompt, context), promptBuilder?(args), customGuardrails?, beforeWorkflow?(workflowId, userRequest), afterWorkflow?(workflowId, result).\",\n \"x-agent fields for LLM commands in cli-contract.yaml: riskLevel (low for read-only analysis), requiresConfirmation (false for read-only), idempotent (true for analysis), sideEffects ([network]), sideEffectNote (describe network call and optional file write), safeDryRunOption (show-prompt), expectedDurationMs (120000 typical), retryableExitCodes ([1, 12]).\"\n],\n rules: [\n {\n \"id\": \"R-IMPL-001\",\n \"description\": \"Import SDK adapters exclusively from agent-contracts-runtime/adapters/*. Never create adapter classes, wrapper functions, or API client code.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-002\",\n \"description\": \"All LLM invocations must use runWorkflow() from agent-contracts-runtime. NEVER use runTask() — it is a low-level internal API that bypasses workflow orchestration. Never call adapter.send(), adapter.followUp(), or adapter.sendExecution() directly. The runtime handles prompt building, schema validation, retry, followUp, workflow DAG, and plugin hooks.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-003\",\n \"description\": \"Every LLM command in cli-contract.yaml must have x-agent metadata with at minimum: riskLevel, safeDryRunOption, expectedDurationMs.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-004\",\n \"description\": \"Handoff type schemas must use $ref to cli-contract.yaml components/schemas as SSoT. If $ref resolution fails at generate time, inline the schema and add a YAML comment noting the SSoT path.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-005\",\n \"description\": \"Context builder must cap prompt input at 16KB. Filter large contexts (schema dumps, lint output, etc.) to relevant portions before inclusion.\",\n \"severity\": \"recommended\"\n },\n {\n \"id\": \"R-IMPL-006\",\n \"description\": \"The orchestrator must dynamic-import agent-contracts-runtime as a single string variable (const PKG = \\\"agent-contracts-runtime\\\") to enable graceful degradation. Exit with code 11 when the import fails, code 12 when the adapter fails to initialize.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-007\",\n \"description\": \"Generated DSL contracts must be imported from src/generated/dsl/index.js and passed as registries to runWorkflow. Never hard-code agent definitions, task definitions, or handoff schemas in application code.\",\n \"severity\": \"mandatory\"\n }\n],\n escalation_criteria: [\n {\n \"condition\": \"Target project has no cli-contract.yaml and user did not request creating one\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project is not a TypeScript / Node.js stack\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project already has src/agents/ with a different integration pattern\",\n \"action\": \"stop_and_report\"\n }\n],\n} as const;\n\nexport const agentRegistry: Record<string, AgentContract> = {\n \"implementation-auditor\": implementationAuditor,\n \"llm-feature-implementer\": llmFeatureImplementer,\n} as const;\n\nexport type AgentId = keyof typeof agentRegistry;\n","/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\nimport type { AgentId } from \"./agents\";\nimport type { HandoffTypeId } from \"./handoffs\";\n\nexport type ModelClass = \"fast\" | \"standard\" | \"thinking\";\n\nexport interface TaskContract {\n readonly id: string;\n readonly description: string;\n readonly target_agent: AgentId;\n readonly allowed_from_agents: readonly AgentId[];\n readonly workflow: string;\n readonly invocation_handoff: HandoffTypeId;\n readonly result_handoff: HandoffTypeId;\n readonly input_artifacts: readonly string[];\n readonly responsibilities: readonly string[];\n readonly completion_criteria: readonly string[];\n readonly optional: boolean;\n readonly model_class?: ModelClass;\n}\n\nexport const implementLlmFeature: TaskContract = {\n id: \"implement-llm-feature\",\n description: \"Implement LLM-powered commands in a target CLI tool using the\\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\\n\\n## Implementation Procedure\\n\\n### Step 1: Project Analysis\\n\\nRead these files from the target project:\\n- cli-contract.yaml — existing commands, components/schemas, x-agent usage\\n- package.json — dependencies, scripts, bin entries, type:\\\"module\\\" check\\n- tsconfig.json — module resolution, paths, outDir\\n- src/ directory structure — understand existing command handler pattern\\n\\nDetermine:\\n- Which LLM commands to add (audit / propose / explain)\\n- What domain-specific context each command needs\\n- What structured output schema each command returns\\n- Whether the project already has agent-contracts integration\\n\\n### Step 2: Install Dependencies\\n\\nAdd to package.json devDependencies:\\n- agent-contracts: ^0.32.0\\n- agent-contracts-runtime: ^0.31.0\\n- zod: ^4.0.0\\n\\nAdd optional peerDependencies for SDK packages:\\n- @anthropic-ai/claude-agent-sdk: >=0.2.0\\n- @openai/agents: >=0.10.0\\n- @google/genai: >=2.0.0\\n\\n### Step 3: Create DSL Definitions\\n\\nCreate directory structure:\\n\\n dsl/\\n ├── {project}-dsl.yaml\\n ├── agent-runtime.config.yaml\\n ├── agents/\\n │ └── {agent-name}.yaml\\n ├── tasks.yaml\\n └── handoff-types.yaml\\n\\n**Main DSL entry** (`dsl/{project}-dsl.yaml`):\\n\\n version: 1\\n system:\\n id: {project}\\n name: \\\"{Project} Agent System\\\"\\n default_workflow_order:\\n - {workflow-ids}\\n agents: { $ref: \\\"./agents/\\\" }\\n tasks: { $ref: \\\"./tasks.yaml\\\" }\\n handoff_types: { $ref: \\\"./handoff-types.yaml\\\" }\\n guardrails:\\n output-schema-conformance:\\n description: ...\\n scope: { agents: [...], tasks: [...] }\\n rationale: ...\\n guardrail_policies:\\n {domain}-safety-policy:\\n rules:\\n - guardrail: output-schema-conformance\\n severity: critical\\n action: block\\n workflow:\\n {workflow-id}:\\n description: ...\\n trigger: cli-command\\n entry_conditions: [...]\\n steps:\\n - type: delegate\\n task: {task-id}\\n from_agent: {agent-id}\\n\\n**Agent definition** (`dsl/agents/{agent-name}.yaml`):\\n\\n {agent-name}:\\n role_name: \\\"{Role Name}\\\"\\n purpose: >-\\n Domain-specific purpose describing what the agent knows\\n and what it can do that static rules cannot.\\n mode: read-only\\n can_read_artifacts: []\\n can_write_artifacts: []\\n can_invoke_agents: []\\n can_execute_tools: []\\n can_return_handoffs: [{result-handoff-ids}]\\n responsibilities: [...]\\n constraints: [...]\\n rules:\\n - id: \\\"R-{PREFIX}-001\\\"\\n description: ...\\n severity: mandatory\\n escalation_criteria:\\n - condition: ...\\n action: stop_and_report\\n\\n**Tasks** (`dsl/tasks.yaml`):\\n\\n {task-id}:\\n description: ...\\n target_agent: {agent-name}\\n allowed_from_agents: [{agent-name}]\\n workflow: {workflow-id}\\n input_artifacts: []\\n invocation_handoff: {request-handoff}\\n result_handoff: {result-handoff}\\n responsibilities: [...]\\n completion_criteria: [...]\\n\\n**Handoff types** (`dsl/handoff-types.yaml`):\\nUse AgentAuditResult shape as the base for result types:\\n\\n {result-handoff}:\\n version: 1\\n description: ...\\n schema:\\n type: object\\n required: [summary, riskLevel, findings]\\n properties:\\n summary: { type: string }\\n riskLevel:\\n type: string\\n enum: [low, medium, high, critical]\\n findings:\\n type: array\\n items:\\n type: object\\n required: [severity, category, message]\\n properties:\\n id: { type: string }\\n severity:\\n type: string\\n enum: [info, warning, error, critical]\\n category: { type: string }\\n target: { type: string }\\n location: { type: string }\\n message: { type: string }\\n recommendation: { type: string }\\n confidence: { type: number, minimum: 0, maximum: 1 }\\n recommendedActions:\\n type: array\\n items:\\n type: object\\n required: [kind, title]\\n properties:\\n kind:\\n type: string\\n enum: [run_command, edit_file, review, confirm, block, ignore]\\n title: { type: string }\\n command: { type: string }\\n target: { type: string }\\n rationale: { type: string }\\n metadata:\\n type: object\\n properties:\\n tool: { type: string }\\n command: { type: string }\\n version: { type: string }\\n generatedAt: { type: string }\\n adapter: { type: string }\\n model: { type: string }\\n\\nDomain-specific result types add properties alongside the base fields.\\n\\n**Runtime config** (`dsl/agent-runtime.config.yaml`):\\n\\n dsl: ./{project}-dsl.yaml\\n generated_dir: ../src/generated/dsl\\n\\n### Step 4: Generate TypeScript Contracts\\n\\nAdd to package.json scripts:\\n\\n \\\"dsl:generate\\\": \\\"agent-runtime generate --config dsl/agent-runtime.config.yaml\\\"\\n\\nRun: npm run dsl:generate\\n\\nThis produces src/generated/dsl/ containing:\\n- agents.ts (AgentContract interface + agentRegistry)\\n- tasks.ts (TaskContract interface + taskRegistry)\\n- workflows.ts (WorkflowContract + workflowRegistry)\\n- handoffs.ts (Zod schemas + handoffSchemas + factory functions)\\n- index.ts (barrel re-exports)\\n\\n### Step 5: Implement src/agents/ Module\\n\\n**src/agents/types.ts**:\\n\\n import type { {ResultType} } from \\\"../generated/dsl/handoffs.js\\\";\\n\\n export type TaskId = \\\"{task-1}\\\" | \\\"{task-2}\\\" | ...;\\n\\n export interface AgentConfig {\\n adapter?: string;\\n model?: string;\\n temperature?: number;\\n }\\n\\n export interface AgentOptions {\\n dryRun?: boolean;\\n failOn?: \\\"warning\\\" | \\\"error\\\" | \\\"critical\\\";\\n }\\n\\n export interface AgentRunResult {\\n taskId: TaskId;\\n data: {ResultType} | null;\\n raw: string;\\n prompt: string;\\n dryRun: boolean;\\n status: \\\"success\\\" | \\\"error\\\" | \\\"escalation\\\" | \\\"validation_error\\\";\\n errorMessage?: string;\\n followUpsUsed: number;\\n retriesUsed: number;\\n }\\n\\n**src/agents/orchestrator.ts**:\\n\\n export const EXIT_RUNTIME_MISSING = 11;\\n export const EXIT_ADAPTER_ERROR = 12;\\n\\n async function createAdapter(pkg: string, name: string, config: AgentConfig) {\\n switch (name) {\\n case \\\"mock\\\": {\\n const m = await import(`${pkg}/adapters/mock`);\\n return new m.MockAdapter();\\n }\\n case \\\"claude\\\": {\\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\\n }\\n case \\\"openai\\\": {\\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\\n }\\n case \\\"gemini\\\": {\\n const m = await import(`${pkg}/adapters/gemini-sdk`);\\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\\n }\\n }\\n }\\n\\n export async function runAgentWorkflow(\\n userRequest: string, workflowId: WorkflowId, config: AgentConfig, options: AgentOptions,\\n ): Promise<AgentRunResult> {\\n if (options.dryRun) return { workflowId, data:null, raw:\\\"\\\", prompt:userRequest, dryRun:true, status:\\\"success\\\" };\\n\\n const PKG = \\\"agent-contracts-runtime\\\";\\n let runWorkflow;\\n try { ({ runWorkflow } = await import(PKG)); }\\n catch { throw Object.assign(new Error(\\\"agent-contracts-runtime not installed\\\"), { exitCode: EXIT_RUNTIME_MISSING }); }\\n\\n let registries;\\n try {\\n const dsl = await import(\\\"../generated/dsl/index.js\\\");\\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas, workflowRegistry: dsl.workflowRegistry };\\n } catch { registries = {}; }\\n\\n const adapter = await createAdapter(PKG, config.adapter ?? \\\"mock\\\", config);\\n const result = await runWorkflow(adapter, { workflow: workflowId, user_request: userRequest, runtime: { maxFollowUps:3, maxRetries:1 } }, registries);\\n // map result to AgentRunResult\\n }\\n\\n**src/agents/context-builder.ts**:\\n\\nCRITICAL: context-builder builds the USER-SIDE prompt only.\\nAgent instructions (purpose, responsibilities, constraints, rules,\\nevaluation criteria, anti-patterns, output format) are defined in\\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\\nbuildTaskPrompt / runWorkflow. NEVER hardcode these in context-builder.\\n\\nContext-builder SHOULD contain:\\n- Domain-specific DATA: file contents, configuration, scan results\\n- Project metadata: target paths, dialect, directory structure\\n- Deterministic pre-analysis: lint results, schema excerpts\\n- Operational context: cwd, timestamps\\n- Brief task framing: \\\"# Migration Safety Audit Request\\\"\\n\\nContext-builder MUST NOT contain:\\n- \\\"## Instructions\\\" / \\\"## Required Patterns\\\" sections\\n- Output format specifications (handled by handoff schema)\\n- Evaluation criteria or checklists\\n- Anti-pattern definitions or rule sets\\n- API reference material\\n- Anything that duplicates DSL agent purpose/responsibilities/rules\\n\\n export function build{Command}Context(target, config): string {\\n const sections = [];\\n sections.push(\\\"# {Command} Request\\\");\\n sections.push(`## Target\\\\n\\\\n${target}`);\\n // Domain data only — no instructions here.\\n // Agent instructions come from DSL via buildTaskPrompt.\\n // Cap total context at 16KB\\n return sections.join(\\\"\\\\n\\\\n\\\");\\n }\\n\\n**src/agents/formatter.ts**:\\n\\n export function computeExitCode(result, options): number {\\n if (result.dryRun) return 0;\\n if (result.status !== \\\"success\\\") return 1;\\n const order = [\\\"info\\\",\\\"warning\\\",\\\"error\\\",\\\"critical\\\"];\\n const threshold = order.indexOf(options.failOn ?? \\\"error\\\");\\n return result.data.findings.some(f => order.indexOf(f.severity) >= threshold) ? 10 : 0;\\n }\\n\\n export function formatResultText(result): string { /* severity icons, structured output */ }\\n export function formatResultJson(result): string { return JSON.stringify(result.data, null, 2); }\\n\\n### Step 6: Create CLI Command Handlers\\n\\nFor each LLM command, create src/commands/{command}.ts:\\n\\n export async function command{Name}(target, opts) {\\n const cwd = process.cwd();\\n const context = build{Name}Context(target, config);\\n const agentConfig = { adapter: opts.adapter, model: opts.model, cwd };\\n const result = await runAgentWorkflow(context, \\\"{workflow-id}\\\", agentConfig, agentOpts);\\n if (opts.reportFormat === \\\"json\\\") console.log(formatResultJson(result));\\n else console.log(formatResultText(result));\\n process.exit(computeExitCode(result, opts));\\n }\\n\\nWire handlers through cli-contracts' generated program:\\n\\n import { createProgram, type CommandHandlers } from './generated/program.js';\\n\\n const handlers: CommandHandlers = {\\n {commandName}: async (target, opts) => {\\n await command{Name}(target, opts);\\n },\\n // ... other handlers\\n };\\n\\n createProgram(handlers, version).parse();\\n\\n### Step 7: Update cli-contract.yaml\\n\\nAdd each LLM command with standard options and x-agent metadata:\\n\\n {command-name}:\\n summary: \\\"{Command summary}\\\"\\n arguments: [...]\\n options:\\n - name: adapter\\n schema: { type: string, enum: [mock, claude, openai, gemini] }\\n - name: model\\n schema: { type: string }\\n - name: show-prompt\\n schema: { type: boolean, default: false }\\n - name: fail-on\\n schema: { type: string, enum: [warning, error, critical], default: error }\\n - name: output\\n aliases: [o]\\n schema: { type: string }\\n file: { mode: write }\\n - name: report-format\\n schema: { type: string, enum: [json, text, yaml], default: json }\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: [network]\\n sideEffectNote: >-\\n Network calls to LLM provider when adapter is not mock.\\n Filesystem write only when --output is specified.\\n safeDryRunOption: show-prompt\\n expectedDurationMs: 120000\\n retryableExitCodes: [1, 12]\\n exits:\\n '0': { description: \\\"No blocking findings.\\\", stdout: { format: json, schema: { $ref: '...' } } }\\n '1': { description: \\\"General error.\\\", stderr: { format: text } }\\n '3': { description: \\\"Input validation failed.\\\", stderr: { format: json } }\\n '10': { description: \\\"Blocking findings detected.\\\", stdout: { format: json, schema: { $ref: '...' } } }\\n '11': { description: \\\"Runtime not installed.\\\", stderr: { format: json } }\\n '12': { description: \\\"Adapter error.\\\", stderr: { format: json } }\\n\\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\\nto components/schemas if not already present.\\n\\n### Step 8: Update README\\n\\nAdd \\\"Agent-Native Toolchain\\\" section after mechanical features:\\n- Intro: tool encapsulates domain-specific semantic reasoning\\n- Deterministic checks first, then semantic audit\\n- Structured findings (AgentAuditResult/AgentFinding)\\n- LLM Adapter Configuration table\\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\\n\",\n target_agent: \"llm-feature-implementer\",\n allowed_from_agents: [\n \"llm-feature-implementer\"\n],\n workflow: \"implement-llm-feature\",\n invocation_handoff: \"implement-request\",\n result_handoff: \"implementation-result\",\n input_artifacts: [],\n responsibilities: [\n \"Analyze the target project and determine the right LLM commands to add\",\n \"Create all DSL definition files with correct cross-references\",\n \"Generate TypeScript contracts via agent-runtime generate\",\n \"Implement the complete src/agents/ module following the exact patterns\",\n \"Create CLI command handlers integrating with the project's existing CLI structure\",\n \"Update cli-contract.yaml with proper x-agent metadata and component schemas\",\n \"Ensure the implementation compiles and --show-prompt mode works\"\n],\n completion_criteria: [\n \"dsl/ directory contains valid DSL definitions that pass agent-runtime generate\",\n \"agent-runtime.config.yaml points to the DSL with correct generated_dir\",\n \"src/generated/dsl/ contains generated contracts (agentRegistry, taskRegistry, handoffSchemas, workflowRegistry)\",\n \"src/agents/orchestrator.ts uses runWorkflow from agent-contracts-runtime (never runTask directly, no direct adapter.send calls)\",\n \"src/agents/orchestrator.ts dynamic-imports the runtime and adapters with correct exit codes (11, 12)\",\n \"src/agents/context-builder.ts contains only domain data (file contents, config, scan results) — no hardcoded agent instructions, evaluation criteria, or output format specs\",\n \"src/agents/context-builder.ts caps input at 16KB\",\n \"src/agents/formatter.ts implements computeExitCode with the standard exit code mapping\",\n \"src/commands/ has a handler for each new LLM command, passing cwd to AgentConfig\",\n \"CLI entry point uses cli-contracts' createProgram(handlers, version) with CommandHandlers interface\",\n \"cli-contract.yaml has all new commands with --adapter, --model, --show-prompt, --fail-on, --output, --report-format options\",\n \"cli-contract.yaml has x-agent metadata on each new command (riskLevel, safeDryRunOption, expectedDurationMs)\",\n \"components/schemas includes AgentAuditResult and related schemas\",\n \"All generated TypeScript compiles without type errors\",\n \"--show-prompt returns the constructed prompt without calling the LLM\"\n],\n optional: false,\n};\n\nexport const auditDsl: TaskContract = {\n id: \"audit-dsl\",\n description: \"Audit the DSL layer of an LLM command integration.\\n\\nVerify these files exist and are well-formed:\\n- dsl/{project}-dsl.yaml — must have version:1, system:{id,name},\\n agents/tasks/handoff_types via $ref\\n- dsl/agents/*.yaml — each agent has role_name, purpose, mode,\\n can_read_artifacts:[], can_write_artifacts:[], responsibilities,\\n constraints, rules with R-PREFIX-NNN\\n- dsl/tasks.yaml — target_agent, workflow, result_handoff all\\n cross-reference valid IDs\\n- dsl/handoff-types.yaml — version:1, schema with JSON Schema,\\n result types follow AgentAuditResult shape\\n- dsl/agent-runtime.config.yaml — dsl and generated_dir fields\\n\\nSeverity classification:\\n- critical: missing version:1 or system block (generator will fail)\\n- critical: task references non-existent agent or workflow\\n- critical: agent mode contradicts its purpose (see below)\\n- error: agent missing constraints or rules\\n- error: handoff schema not following AgentAuditResult shape\\n- warning: missing guardrails or guardrail_policies\\n- warning: agent has no escalation_criteria\\n\\nCRITICAL: agent mode-purpose coherence (category: dsl-agent):\\n- Agent with mode: read-only has purpose or responsibilities\\n that describe file writing, editing, creation, or code\\n generation — the agent's adapter tools won't include Write/Edit\\n so the stated purpose is impossible to fulfil\\n- Agent with mode: read-write has purpose that is purely\\n analytical (audit, review, explain) with no file output —\\n unnecessarily broad permissions\\n\\nCategory vocabulary: dsl-structure, dsl-agent, dsl-task,\\ndsl-handoff, dsl-workflow, dsl-guardrail.\\n\\nOutput a partial audit-result with findings only from the DSL layer.\\n\",\n target_agent: \"implementation-auditor\",\n allowed_from_agents: [\n \"implementation-auditor\"\n],\n workflow: \"audit-implementation\",\n invocation_handoff: \"audit-request\",\n result_handoff: \"audit-result\",\n input_artifacts: [],\n responsibilities: [\n \"Check all DSL files for structural correctness\",\n \"Validate cross-references (agent↔task↔workflow↔handoff)\",\n \"Verify guardrails and guardrail_policies\",\n \"Check agent mode-purpose coherence (read-only agents must not have write-oriented purposes; read-write agents must justify their write permissions in their purpose)\"\n],\n completion_criteria: [\n \"Every dsl/* file checked for required fields\",\n \"Cross-references validated\",\n \"Agent mode is consistent with stated purpose and responsibilities\",\n \"Findings use dsl-* category vocabulary\"\n],\n optional: false,\n};\n\nexport const auditRuntime: TaskContract = {\n id: \"audit-runtime\",\n description: \"Audit the runtime integration layer of an LLM command integration.\\n\\nScan src/agents/orchestrator.ts (or equivalent runtime module):\\n\\nCRITICAL violations (category: runtime-orchestrator):\\n- adapter.send() or adapter.sendExecution() called directly\\n- adapter.followUp() called directly\\n- Custom adapter class defined (not imported from runtime)\\n- runWorkflow not imported from agent-contracts-runtime\\n- runTask used instead of runWorkflow — consumer projects must\\n use runWorkflow() which orchestrates through the DSL workflow\\n DAG, activates workflow-level plugin hooks (beforeWorkflow/\\n afterWorkflow), handles gate steps and step dependencies.\\n runTask() is a low-level internal API; calling it directly\\n bypasses workflow orchestration entirely\\n\\nERROR violations (category: runtime-registry):\\n- Generated registries not imported from src/generated/dsl/\\n- Registries not passed to runWorkflow options\\n- Hard-coded agent/task definitions instead of registry lookup\\n\\nERROR violations (category: runtime-adapter):\\n- Adapter packages imported statically (not dynamic import)\\n- Missing exit code 11 when runtime import fails\\n- Missing exit code 12 when adapter creation fails\\n\\nERROR violations (category: runtime-handler):\\n- Project has cli-contracts generated code (src/generated/program.ts\\n or src/generated/cli/program.ts exporting CommandHandlers and\\n createProgram) but CLI entry point manually creates Commander\\n commands instead of using createProgram(handlers, version)\\n- LLM command handlers are not wired through the generated\\n CommandHandlers interface — handler signatures drift from the\\n cli-contract.yaml definition without type errors\\n- CLI entry point calls runTask directly instead of going through\\n the command handler → context-builder → orchestrator chain\\n\\nWARNING violations (category: runtime-plugin):\\n- Plugin hooks explicitly bypassed or ignored\\n\\nCategory vocabulary: runtime-orchestrator, runtime-registry,\\nruntime-adapter, runtime-handler, runtime-plugin.\\n\\nOutput a partial audit-result with findings only from the runtime layer.\\n\",\n target_agent: \"implementation-auditor\",\n allowed_from_agents: [\n \"implementation-auditor\"\n],\n workflow: \"audit-implementation\",\n invocation_handoff: \"audit-request\",\n result_handoff: \"audit-result\",\n input_artifacts: [],\n responsibilities: [\n \"Scan orchestrator code for direct adapter usage\",\n \"Verify runWorkflow is used (not runTask) for LLM command execution\",\n \"Verify registry imports and passing\",\n \"Check adapter creation patterns and exit codes\",\n \"Verify cli-contracts handler wiring (CommandHandlers + createProgram used in CLI entry point)\"\n],\n completion_criteria: [\n \"All orchestrator files scanned for adapter.send / adapter.followUp\",\n \"No runTask usage found (runWorkflow must be used instead)\",\n \"Registry usage verified\",\n \"Exit code 11/12 patterns checked\",\n \"cli-contracts handler integration verified (CommandHandlers interface used, createProgram called)\"\n],\n optional: false,\n};\n\nexport const auditCliContract: TaskContract = {\n id: \"audit-cli-contract\",\n description: \"Audit the CLI contract layer of an LLM command integration.\\n\\nParse cli-contract.yaml and check each LLM command:\\n\\nERROR: missing standard options (category: cli-contract-options):\\n- --adapter, --model, --show-prompt, --fail-on, --output, --report-format\\n- Using --format instead of --report-format for LLM commands\\n\\nERROR: missing x-agent metadata (category: cli-contract-xagent):\\n- No x-agent block on LLM command\\n- Missing riskLevel, safeDryRunOption, or expectedDurationMs\\n- Using snake_case instead of camelCase for x-agent fields\\n\\nERROR: wrong exit codes (category: cli-contract-exits):\\n- Missing exit 0/1/3/10/11/12 definitions\\n- Exit 10 not defined for finding-based commands\\n\\nWARNING: missing schemas (category: cli-contract-schema):\\n- AgentAuditResult not in components/schemas\\n- AgentFinding, AgentRecommendedAction, AgentEvidence not defined\\n\\nCategory vocabulary: cli-contract-options, cli-contract-xagent,\\ncli-contract-exits, cli-contract-schema.\\n\\nOutput a partial audit-result with findings only from the CLI contract layer.\\n\",\n target_agent: \"implementation-auditor\",\n allowed_from_agents: [\n \"implementation-auditor\"\n],\n workflow: \"audit-implementation\",\n invocation_handoff: \"audit-request\",\n result_handoff: \"audit-result\",\n input_artifacts: [],\n responsibilities: [\n \"Check each LLM command for standard options\",\n \"Verify x-agent metadata fields and casing\",\n \"Validate exit code definitions\",\n \"Check components/schemas for canonical types\"\n],\n completion_criteria: [\n \"Every LLM command checked for all 6 standard options\",\n \"x-agent metadata validated on every LLM command\",\n \"Exit codes verified against convention\",\n \"Schema completeness checked\"\n],\n optional: false,\n};\n\nexport const auditArchitecture: TaskContract = {\n id: \"audit-architecture\",\n description: \"Audit the architecture and module structure of an LLM command integration.\\n\\nVerify module structure (category: architecture-modules):\\n- src/agents/types.ts exists with TaskId, AgentConfig, AgentOptions, AgentRunResult\\n- src/agents/orchestrator.ts exists\\n- src/agents/context-builder.ts exists\\n- src/agents/formatter.ts exists with computeExitCode\\n\\nVerify behavior (category: architecture-dry-run):\\n- --show-prompt path returns the constructed prompt without calling the adapter\\n- buildTaskPrompt is used (not a placeholder string)\\n\\nCRITICAL: context-builder SSoT violations (category: architecture-context-builder):\\n\\nThe context-builder's role is to assemble domain-specific DATA (file\\ncontents, configuration, scan results, schema context) into the user\\nprompt. Agent INSTRUCTIONS (how to evaluate, what rules to apply,\\nwhat patterns to look for, output format) belong in the DSL agent\\ndefinition and are injected by buildTaskPrompt / runWorkflow.\\n\\nDetect any of the following in context-builder source code:\\n- Sections titled \\\"## Instructions\\\", \\\"## Required Patterns\\\",\\n \\\"## Audit Instructions\\\", \\\"## Output Format\\\", or similar\\n behavioral directive headings — these are agent instructions\\n that belong in DSL (agent purpose, responsibilities, constraints,\\n rules) and must not be hardcoded in context-builder\\n- Output format specifications (field lists, JSON/YAML schema\\n descriptions, example output structures) — buildTaskPrompt\\n already generates \\\"Required Output Format\\\" from the handoff\\n Zod schema; duplicating this in context-builder causes conflicts\\n- Domain-specific evaluation criteria, checklists, anti-pattern\\n definitions, rule sets, or API reference material — these\\n belong in the DSL agent definition's purpose field\\n- Any string that duplicates or paraphrases content already\\n present in the DSL agent's purpose, responsibilities,\\n constraints, or rules fields\\n\\nWhat IS allowed in context-builder:\\n- File contents read from disk (migration SQL, schema, config)\\n- Project metadata (dialect, directories, file lists)\\n- Deterministic pre-analysis results (lint violations, scan output)\\n- Operational context (target path, cwd, timestamp)\\n- Brief task framing (\\\"# Migration Safety Audit Request\\\")\\n\\nERROR: mode-purpose coherence (category: architecture-agent-coherence):\\n- DSL agent with mode: read-only has purpose or responsibilities\\n that describe file writing, editing, creation, or modification\\n- DSL agent with mode: read-write but no cwd propagated to adapter\\n — the agent's file tools won't operate in the project directory\\n- Command handler doesn't pass cwd to AgentConfig when using an\\n agentic adapter (claude)\\n\\nERROR: adapter cwd propagation (category: architecture-adapter-cwd):\\n- AgentConfig type has no cwd field\\n- Command handlers don't set config.cwd = process.cwd() or\\n resolve(projectDir)\\n- createAdapter doesn't pass cwd to adapter constructor/factory\\n- Agentic adapters (claude) instantiated without cwd —\\n their file tools will operate in an undefined directory\\n\\nCRITICAL: runTask usage (category: architecture-handler):\\n- runTask() imported or called anywhere in the consumer project —\\n consumer projects must use runWorkflow() exclusively; runTask()\\n is a low-level internal API that bypasses workflow DAG\\n orchestration, workflow-level plugin hooks, and gate steps\\n\\nERROR: cli-contracts handler wiring (category: architecture-handler):\\n- Project has cli-contracts generated code (src/generated/program.ts\\n or src/generated/cli/program.ts with CommandHandlers) but CLI\\n entry point manually creates Commander commands instead of\\n calling createProgram(handlers, version)\\n- Command handlers bypass the generated CommandHandlers interface\\n\\nScan for direct SDK imports (category: architecture-modules):\\n- @anthropic-ai/sdk or @anthropic-ai/claude-agent-sdk imported\\n outside src/agents/orchestrator.ts or adapter files\\n- openai or @openai/agents imported outside adapters\\n- @google/genai imported outside adapters\\n\\nCategory vocabulary: architecture-modules, architecture-dry-run,\\narchitecture-context-builder, architecture-agent-coherence,\\narchitecture-adapter-cwd, architecture-handler,\\narchitecture-formatter.\\n\\nOutput a partial audit-result with findings only from the architecture layer.\\n\",\n target_agent: \"implementation-auditor\",\n allowed_from_agents: [\n \"implementation-auditor\"\n],\n workflow: \"audit-implementation\",\n invocation_handoff: \"audit-request\",\n result_handoff: \"audit-result\",\n input_artifacts: [],\n responsibilities: [\n \"Verify module structure\",\n \"Check dry-run behavior\",\n \"Audit context-builder for SSoT violations (hardcoded instructions, output format specs, domain rules that belong in DSL)\",\n \"Check mode-purpose coherence across DSL definitions and runtime code\",\n \"Verify cwd propagation from command handler through adapter config\",\n \"Verify cli-contracts handler wiring (CommandHandlers + createProgram)\",\n \"Scan for direct SDK imports\"\n],\n completion_criteria: [\n \"Module structure verified\",\n \"Dry-run behavior confirmed\",\n \"Context-builder contains only domain data, not agent instructions\",\n \"Agent mode is consistent with purpose and tool usage\",\n \"cwd is propagated to agentic adapters\",\n \"cli-contracts handler integration verified\",\n \"No direct SDK imports outside adapter files\"\n],\n optional: false,\n};\n\nexport const auditMerge: TaskContract = {\n id: \"audit-merge\",\n description: \"Merge the partial audit results from the four parallel layer audits\\n(DSL, runtime, CLI contract, architecture) into a single unified\\naudit-result.\\n\\nThe prior_context contains the JSON output from each completed\\naudit step. Parse each one, combine all findings into a single\\narray, deduplicate by (target + message), assign sequential IDs\\n(F-001, F-002, ...), derive the overall riskLevel from the worst\\nfinding severity, and produce prioritized recommendedActions.\\n\\nMerging rules:\\n- Collect all findings from all layer results\\n- Sort: critical first, then error, warning, info\\n- Assign sequential IDs: F-001, F-002, ...\\n- Deduplicate: if two findings have the same target and message, keep one\\n- Derive riskLevel: any critical → critical, any error → high,\\n any warning → medium, info only → low\\n- Merge recommendedActions from all layers, deduplicate by title\\n- Set metadata: { tool: \\\"agent-runtime\\\", command: \\\"audit-implementation\\\" }\\n\",\n target_agent: \"implementation-auditor\",\n allowed_from_agents: [\n \"implementation-auditor\"\n],\n workflow: \"audit-implementation\",\n invocation_handoff: \"audit-request\",\n result_handoff: \"audit-result\",\n input_artifacts: [],\n responsibilities: [\n \"Parse prior_context JSON from each layer audit step\",\n \"Merge and deduplicate findings\",\n \"Derive overall riskLevel\",\n \"Produce a single coherent summary paragraph\"\n],\n completion_criteria: [\n \"All findings from all layers included\",\n \"No duplicate findings\",\n \"riskLevel correctly derived from worst finding\",\n \"Summary paragraph covers all audited layers\"\n],\n optional: false,\n};\n\nexport const taskRegistry: Record<string, TaskContract> = {\n \"implement-llm-feature\": implementLlmFeature,\n \"audit-dsl\": auditDsl,\n \"audit-runtime\": auditRuntime,\n \"audit-cli-contract\": auditCliContract,\n \"audit-architecture\": auditArchitecture,\n \"audit-merge\": auditMerge,\n};\n","/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\nimport { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// implement-request\n// ---------------------------------------------------------------------------\n\nexport const ImplementRequestSchema = z.object({\n description: z.string(),\n project_dir: z.string(),\n reference_doc: z.string().optional(),\n});\n\nexport type ImplementRequest = z.infer<typeof ImplementRequestSchema>;\n\n// ---------------------------------------------------------------------------\n// audit-request\n// ---------------------------------------------------------------------------\n\nexport const AuditRequestSchema = z.object({\n project_dir: z.string(),\n focus: z.enum([\"all\", \"dsl\", \"runtime\", \"cli-contract\", \"architecture\"]).optional(),\n});\n\nexport type AuditRequest = z.infer<typeof AuditRequestSchema>;\n\n// ---------------------------------------------------------------------------\n// audit-result\n// ---------------------------------------------------------------------------\n\nexport const AuditResultSchema = z.object({\n summary: z.string(),\n riskLevel: z.enum([\"low\", \"medium\", \"high\", \"critical\"]),\n findings: z.array(z.object({\n id: z.string().optional(),\n severity: z.enum([\"info\", \"warning\", \"error\", \"critical\"]),\n category: z.string(),\n target: z.string().optional(),\n location: z.string().optional(),\n message: z.string(),\n recommendation: z.string().optional(),\n confidence: z.number().min(0).max(1).optional(),\n})),\n recommendedActions: z.array(z.object({\n kind: z.enum([\"run_command\", \"edit_file\", \"review\", \"confirm\", \"block\", \"ignore\"]),\n title: z.string(),\n command: z.string().optional(),\n target: z.string().optional(),\n rationale: z.string().optional(),\n})).optional(),\n metadata: z.object({\n tool: z.string().optional(),\n command: z.string().optional(),\n version: z.string().optional(),\n generatedAt: z.string().optional(),\n adapter: z.string().optional(),\n model: z.string().optional(),\n}).optional(),\n});\n\nexport type AuditResult = z.infer<typeof AuditResultSchema>;\n\n// ---------------------------------------------------------------------------\n// implementation-result\n// ---------------------------------------------------------------------------\n\nexport const ImplementationResultSchema = z.object({\n files_created: z.array(z.string()),\n files_modified: z.array(z.string()),\n summary: z.string(),\n commands_added: z.array(z.object({\n name: z.string(),\n type: z.enum([\"audit\", \"propose\", \"explain\"]),\n description: z.string().optional(),\n})).optional(),\n next_steps: z.array(z.string()).optional(),\n});\n\nexport type ImplementationResult = z.infer<typeof ImplementationResultSchema>;\n\n// ---------------------------------------------------------------------------\n// Schema registry\n// ---------------------------------------------------------------------------\n\nexport const handoffSchemas = {\n \"implement-request\": ImplementRequestSchema,\n \"audit-request\": AuditRequestSchema,\n \"audit-result\": AuditResultSchema,\n \"implementation-result\": ImplementationResultSchema,\n} as const;\n\nexport type HandoffTypeId = keyof typeof handoffSchemas;\n\n// ---------------------------------------------------------------------------\n// Handoff envelope\n// ---------------------------------------------------------------------------\n\nexport interface HandoffEnvelope<T extends HandoffTypeId = HandoffTypeId> {\n readonly type: T;\n readonly version: number;\n readonly payload: z.infer<(typeof handoffSchemas)[T]>;\n}\n\n// ---------------------------------------------------------------------------\n// Factory functions — type-safe constructors with runtime validation\n// ---------------------------------------------------------------------------\n\nexport const handoffs = {\n implementRequest(payload: ImplementRequest): HandoffEnvelope<\"implement-request\"> {\n return {\n type: \"implement-request\" as const,\n version: 1,\n payload: ImplementRequestSchema.parse(payload),\n };\n },\n auditRequest(payload: AuditRequest): HandoffEnvelope<\"audit-request\"> {\n return {\n type: \"audit-request\" as const,\n version: 1,\n payload: AuditRequestSchema.parse(payload),\n };\n },\n auditResult(payload: AuditResult): HandoffEnvelope<\"audit-result\"> {\n return {\n type: \"audit-result\" as const,\n version: 1,\n payload: AuditResultSchema.parse(payload),\n };\n },\n implementationResult(payload: ImplementationResult): HandoffEnvelope<\"implementation-result\"> {\n return {\n type: \"implementation-result\" as const,\n version: 1,\n payload: ImplementationResultSchema.parse(payload),\n };\n },\n} as const;\n","/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\nexport interface DelegateStep {\n readonly type: \"delegate\";\n readonly task: string;\n readonly from_agent: string;\n readonly description: string;\n readonly optional: boolean;\n readonly max_retries: number;\n readonly depends_on?: readonly string[];\n}\n\nexport interface GateStep {\n readonly type: \"gate\";\n readonly gate_kind: string;\n readonly description: string;\n readonly depends_on?: readonly string[];\n}\n\nexport type WorkflowStep = DelegateStep | GateStep;\n\nexport interface WorkflowContract {\n readonly id: string;\n readonly description: string;\n readonly trigger: string;\n readonly entry_conditions: readonly string[];\n readonly steps: readonly WorkflowStep[];\n}\n\nexport const implementLlmFeature: WorkflowContract = {\n id: \"implement-llm-feature\",\n description: \"Implement LLM-powered commands in a CLI tool\",\n trigger: \"cli-command\",\n entry_conditions: [\n \"Target project is a TypeScript / Node.js project\",\n \"cli-contract.yaml exists or is being created\"\n],\n steps: [\n {\n type: \"delegate\",\n task: \"implement-llm-feature\",\n from_agent: \"llm-feature-implementer\",\n description: \"\",\n optional: false,\n max_retries: 0,\n },\n ],\n};\n\nexport const auditImplementation: WorkflowContract = {\n id: \"audit-implementation\",\n description: \"Audit an LLM command integration for pattern conformance\",\n trigger: \"cli-command\",\n entry_conditions: [\n \"Target project has LLM command integration to audit\"\n],\n steps: [\n {\n type: \"delegate\",\n task: \"audit-dsl\",\n from_agent: \"implementation-auditor\",\n description: \"\",\n optional: false,\n max_retries: 0,\n depends_on: [],\n },\n {\n type: \"delegate\",\n task: \"audit-runtime\",\n from_agent: \"implementation-auditor\",\n description: \"\",\n optional: false,\n max_retries: 0,\n depends_on: [],\n },\n {\n type: \"delegate\",\n task: \"audit-cli-contract\",\n from_agent: \"implementation-auditor\",\n description: \"\",\n optional: false,\n max_retries: 0,\n depends_on: [],\n },\n {\n type: \"delegate\",\n task: \"audit-architecture\",\n from_agent: \"implementation-auditor\",\n description: \"\",\n optional: false,\n max_retries: 0,\n depends_on: [],\n },\n {\n type: \"delegate\",\n task: \"audit-merge\",\n from_agent: \"implementation-auditor\",\n description: \"\",\n optional: false,\n max_retries: 0,\n depends_on: [\n \"audit-dsl\",\n \"audit-runtime\",\n \"audit-cli-contract\",\n \"audit-architecture\"\n],\n },\n ],\n};\n\nexport const workflowRegistry: Record<string, WorkflowContract> = {\n \"implement-llm-feature\": implementLlmFeature,\n \"audit-implementation\": auditImplementation,\n};\n","/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\nexport const resolvedDsl: Record<string, unknown> = {\n \"version\": 1,\n \"system\": {\n \"id\": \"agent-runtime-builtin\",\n \"name\": \"agent-runtime Built-in Agents\",\n \"default_workflow_order\": [\n \"implement-llm-feature\",\n \"audit-implementation\"\n ]\n },\n \"agents\": {\n \"implementation-auditor\": {\n \"role_name\": \"Implementation Auditor\",\n \"purpose\": \"Audits an existing LLM command integration to verify it correctly\\nfollows the agent-contracts + agent-contracts-runtime + cli-contracts\\nstack conventions. Detects architectural violations, missing patterns,\\nincorrect API usage, and deviations from the canonical\\nintegrate-llm-commands pattern.\\n\\nThis agent is read-only — it analyzes code but does not modify it.\\nIt produces structured findings (AgentAuditResult) that identify\\nexactly what is wrong and how to fix it.\\n\\n## What This Agent Checks\\n\\n### Layer 1: agent-contracts DSL\\n- DSL entry has version:1 and system block with id/name\\n- Agents defined with all required fields (role_name, purpose, mode,\\n can_read_artifacts, can_write_artifacts, responsibilities, constraints)\\n- Tasks have target_agent, workflow, result_handoff, completion_criteria\\n- Handoff type schemas conform to AgentAuditResult base shape\\n- Workflows define steps with correct task/agent cross-references\\n- Guardrails and guardrail_policies are defined\\n- agent-runtime.config.yaml exists with dsl and generated_dir\\n\\n### Layer 2: agent-contracts-runtime Integration\\n- orchestrator.ts uses runWorkflow(), NOT runTask() or adapter.send()\\n- runTask() is a low-level internal API — consumer projects must\\n use runWorkflow() which handles workflow DAG, plugin hooks, gates\\n- Adapters imported from agent-contracts-runtime/adapters/*, not custom\\n- Dynamic import pattern for graceful degradation (exit 11/12)\\n- Generated registries imported from src/generated/dsl/index.js\\n- Registries (including workflowRegistry) passed to runWorkflow\\n- Plugin hooks not bypassed\\n- No hand-rolled prompt building (use buildTaskPrompt or let runWorkflow do it)\\n\\n### Layer 3: cli-contracts Compliance\\n- cli-contract.yaml has LLM commands with all standard options:\\n --adapter, --model, --show-prompt, --fail-on, --output, --report-format\\n- x-agent metadata present (riskLevel, safeDryRunOption, expectedDurationMs)\\n- Exit codes follow convention (0, 1, 3, 10, 11, 12)\\n- components/schemas includes AgentAuditResult and related types\\n- --report-format used (not --format) for LLM commands\\n\\n### Architecture & Patterns\\n- src/agents/ module structure (orchestrator, context-builder, formatter, types)\\n- Context builder caps input at 16KB\\n- Formatter implements computeExitCode with correct threshold logic\\n- --show-prompt returns prompt without LLM call\\n- No direct LLM API calls anywhere in the codebase\\n\\n### Semantic Design Coherence\\n- Context-builder must contain only domain DATA (file contents,\\n config, scan results) — never agent INSTRUCTIONS (evaluation\\n criteria, rules, anti-patterns, output format specifications).\\n These belong in the DSL agent definition and are injected by\\n buildTaskPrompt / runWorkflow. Hardcoding instructions in\\n context-builder defeats the purpose of using DSL.\\n- Agent mode must match purpose: read-only agents must not have\\n write-oriented purposes, read-write agents must propagate cwd\\n to their adapter so file tools operate in the project directory.\\n- CLI must use cli-contracts' generated CommandHandlers interface\\n and createProgram() — not manually wired Commander commands.\\n\",\n \"mode\": \"read-only\",\n \"can_read_artifacts\": [],\n \"can_write_artifacts\": [],\n \"can_invoke_agents\": [],\n \"can_execute_tools\": [],\n \"can_return_handoffs\": [\n \"audit-result\"\n ],\n \"responsibilities\": [\n \"Verify the DSL directory structure exists: dsl/{project}-dsl.yaml, dsl/agents/*.yaml, dsl/tasks.yaml, dsl/handoff-types.yaml, dsl/agent-runtime.config.yaml.\",\n \"Check that the main DSL entry has version:1, a system block with id and name, and uses $ref for agents/tasks/handoff_types.\",\n \"Validate agent definitions have all required fields: role_name, purpose, mode, can_read_artifacts:[], can_write_artifacts:[], responsibilities, constraints. Check that rules use R-PREFIX-NNN format and severity is mandatory|recommended|optional.\",\n \"Validate task definitions: target_agent matches a defined agent, workflow matches a defined workflow, result_handoff matches a defined handoff type, completion_criteria are specific and testable.\",\n \"Verify handoff type schemas conform to AgentAuditResult shape when applicable (summary, riskLevel, findings[], recommendedActions[], metadata). Check $ref usage and SSoT comments for inlined schemas.\",\n \"Check that guardrails and guardrail_policies are defined, and that output-schema-conformance is included.\",\n \"Scan src/agents/orchestrator.ts for: (1) imports from agent-contracts-runtime (not custom SDK wrappers), (2) usage of runWorkflow() — NOT runTask() which is a low-level internal API that bypasses workflow orchestration, plugin hooks, and gate steps, (3) dynamic import pattern with exit code 11 for missing runtime and exit code 12 for adapter errors, (4) generated registries (including workflowRegistry) imported and passed to runWorkflow.\",\n \"Verify no file in the project calls adapter.send(), adapter.followUp(), adapter.sendExecution(), or runTask() directly — all LLM invocations must go through runWorkflow().\",\n \"Check that src/generated/dsl/ exists and contains the expected files (agents.ts, tasks.ts, workflows.ts, handoffs.ts, index.ts). Verify the .manifest.json exists and is not stale.\",\n \"Verify adapter creation uses the correct constructors: ClaudeAgentSdkAdapter constructor, OpenAIAgentsSdkAdapter constructor, etc.\",\n \"Check cli-contract.yaml for each LLM command: all six standard options present (--adapter, --model, --show-prompt, --fail-on, --output, --report-format). Verify --report-format is used (not --format).\",\n \"Verify x-agent metadata on each LLM command: riskLevel, safeDryRunOption (must be \\\"show-prompt\\\"), expectedDurationMs. Flag high-risk commands without requiresConfirmation.\",\n \"Check exit code definitions: 0 (success), 1 (error), 3 (validation), 10 (findings), 11 (runtime missing), 12 (adapter error).\",\n \"Verify components/schemas includes AgentAuditResult, AgentFinding, AgentRecommendedAction, and AgentEvidence definitions.\",\n \"Verify src/agents/ directory structure: types.ts (TaskId, AgentConfig, AgentOptions, AgentRunResult), orchestrator.ts (createAdapter, runAgentTask with dynamic imports), context-builder.ts (build*Context functions with 16KB cap), formatter.ts (computeExitCode, formatResultText, formatResultJson).\",\n \"Check that --show-prompt mode returns the constructed prompt without making any LLM API call.\",\n \"Scan for direct LLM API imports (@anthropic-ai/sdk, openai, @google/genai) used outside of adapter files — application code must not import these directly.\",\n \"Audit context-builder for SSoT violations: scan for hardcoded agent instructions (sections titled \\\"## Instructions\\\", \\\"## Required Patterns\\\", \\\"## Output Format\\\", evaluation criteria, checklists, anti-pattern definitions, API references, or output schema descriptions). These belong in the DSL agent definition and are injected by buildTaskPrompt. Context-builder should contain only domain-specific data (file contents, configuration, scan results, project metadata).\",\n \"Check agent mode-purpose coherence: for each agent in the DSL, verify that mode: read-only agents do not have purposes or responsibilities describing file writing/editing/creation, and that mode: read-write agents propagate cwd through AgentConfig to the adapter so file tools operate in the correct directory.\",\n \"Verify cwd propagation: command handlers must set cwd in AgentConfig (e.g. process.cwd() or resolve(projectDir)), createAdapter must pass cwd to adapter constructors/factories, and AgentConfig type must include a cwd field.\",\n \"Verify cli-contracts handler wiring: if the project uses cli-contracts (has src/generated/program.ts or src/generated/cli/program.ts exporting CommandHandlers and createProgram), the CLI entry point must use createProgram(handlers, version) with a handlers object implementing the CommandHandlers interface — not manually created Commander commands.\"\n ],\n \"constraints\": [\n \"This agent is read-only. It must not create, modify, or delete any files. Output is a structured audit report only.\",\n \"Findings must include specific file paths, line references where possible, and concrete remediation steps.\",\n \"Severity classification: critical = breaks the integration pattern (direct API calls, missing runtime usage), error = missing required element (no x-agent, missing standard option), warning = deviation from best practice (context not capped, missing guardrail), info = improvement suggestion.\",\n \"Category vocabulary: dsl-structure, dsl-agent, dsl-task, dsl-handoff, dsl-workflow, dsl-guardrail, runtime-adapter, runtime-orchestrator, runtime-registry, runtime-handler, runtime-plugin, cli-contract-options, cli-contract-xagent, cli-contract-exits, cli-contract-schema, architecture-modules, architecture-dry-run, architecture-context-builder, architecture-agent-coherence, architecture-adapter-cwd, architecture-handler, architecture-formatter.\",\n \"Every finding with severity warning or above must include a recommendation field with a concrete fix.\",\n \"The confidence field should reflect how certain the finding is: 1.0 for pattern matches (e.g., adapter.send() found in code), 0.8+ for structural checks (e.g., missing file), 0.5-0.8 for heuristic assessments (e.g., context might exceed 16KB).\"\n ],\n \"rules\": [\n {\n \"id\": \"R-AUDIT-001\",\n \"description\": \"Every finding must specify target (file path) and category (from the defined category vocabulary). Findings without a target are not actionable.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-002\",\n \"description\": \"The audit must check all four layers (DSL, runtime, CLI contract, architecture). Skipping a layer or returning partial results is not acceptable.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-003\",\n \"description\": \"Critical findings must be surfaced for: (1) direct adapter.send() calls bypassing runWorkflow, (2) runTask() used instead of runWorkflow() — runTask is a low-level internal API that bypasses workflow orchestration, (3) custom adapter classes not from agent-contracts-runtime, (4) missing generated registries in runWorkflow calls.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-004\",\n \"description\": \"The riskLevel in the audit result must be derived from the most severe finding: any critical → critical, any error → high, any warning → medium, info only → low.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-005\",\n \"description\": \"Context-builder must be audited for SSoT violations. Any hardcoded agent instructions (evaluation criteria, rules, anti-patterns, output format specs) in context-builder is a critical finding — these belong in the DSL agent definition and are injected by buildTaskPrompt / runWorkflow. Context-builder may only contain domain-specific data (file contents, configuration, scan results, project metadata).\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-007\",\n \"description\": \"runTask() usage in consumer projects is a CRITICAL finding. Consumer projects integrating with cli-contracts must use runWorkflow() exclusively. runTask() is a low-level internal API that bypasses workflow DAG orchestration, workflow-level plugin hooks (beforeWorkflow/afterWorkflow), gate steps, and step dependencies. Any occurrence of runTask import or call in orchestrator, command handler, or CLI entry point code must be reported as severity: critical.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-AUDIT-006\",\n \"description\": \"Agent mode-purpose coherence must be verified. A read-only agent whose purpose describes file writing is a critical finding because the adapter's tool set (Read/Glob/Grep only) makes the stated purpose impossible to fulfil.\",\n \"severity\": \"mandatory\"\n }\n ],\n \"escalation_criteria\": [\n {\n \"condition\": \"Target project has no LLM command integration to audit\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project uses a completely different integration pattern (not agent-contracts stack)\",\n \"action\": \"stop_and_report\"\n }\n ]\n },\n \"llm-feature-implementer\": {\n \"role_name\": \"LLM Feature Implementer\",\n \"purpose\": \"Expert implementation agent for the agent-contracts toolchain.\\nAdds LLM-powered commands (audit, propose, explain, etc.) to CLI tools\\nusing the three-layer stack:\\n\\n1. **agent-contracts** — DSL package. Defines agents, tasks, workflows,\\n handoff types, guardrails, and guardrail policies in YAML. The\\n `resolve()` function handles `$ref`, `extends`, and merge operators.\\n Installed as a devDependency. CLI: `agent-contracts audit`.\\n\\n2. **agent-contracts-runtime** — Runtime bridge. Generates typed\\n TypeScript contracts from DSL via Handlebars templates, then\\n executes workflows through pluggable SDK adapters. Provides\\n `runTask()`, `runWorkflow()`, `createRuntime()`, plugin system,\\n and guardrail hooks. CLI: `agent-runtime generate|run|list|doctor`.\\n\\n3. **cli-contracts** — CLI contract package. Defines command-line\\n interfaces in YAML (`cli-contract.yaml`): command sets, arguments,\\n options, exit codes, stdout/stderr schemas, `x-agent` metadata,\\n and `effects`. Generates typed Commander programs, Zod validators,\\n and markdown docs. CLI: `cli-contracts init|generate|validate`.\\n\\nThe canonical integration pattern (\\\"integrate-llm-commands\\\") produces:\\n- DSL definitions under `dsl/` (agents, tasks, workflows, handoff-types)\\n- Pre-generated TypeScript contracts under `src/generated/dsl/`\\n- Runtime integration module under `src/agents/` (orchestrator,\\n context-builder, formatter, types)\\n- CLI command handlers under `src/commands/`\\n- Updated `cli-contract.yaml` with new commands and `x-agent` metadata\\n\",\n \"mode\": \"read-write\",\n \"can_read_artifacts\": [],\n \"can_write_artifacts\": [],\n \"can_invoke_agents\": [],\n \"can_execute_tools\": [],\n \"can_return_handoffs\": [\n \"implementation-result\"\n ],\n \"responsibilities\": [\n \"Read and analyze the target project's cli-contract.yaml, package.json, tsconfig.json, and existing source code to understand the CLI structure, existing commands, component schemas, and TypeScript configuration.\",\n \"Identify which LLM commands to add based on the user's description. Canonical command types: audit (semantic review), propose (structured proposal generation), explain (human-readable explanation of machine output).\",\n \"Create the DSL directory structure: dsl/{project}-dsl.yaml (main entry with version:1, system block, $ref to sub-files), dsl/agents/{name}.yaml, dsl/tasks.yaml, dsl/handoff-types.yaml, dsl/agent-runtime.config.yaml.\",\n \"Define agents with: role_name, purpose (domain expertise), mode (read-only for analysis agents), can_read_artifacts:[], can_write_artifacts:[], can_return_handoffs, responsibilities, constraints, rules (R-PREFIX-NNN format), escalation_criteria.\",\n \"Define tasks with: description, target_agent, allowed_from_agents, workflow (must match a workflow ID), invocation_handoff, result_handoff, responsibilities, completion_criteria.\",\n \"Define handoff types with: version:1, description, schema (JSON Schema). Result types should conform to AgentAuditResult shape (summary, riskLevel, findings[], recommendedActions[], metadata). Use $ref to cli-contract.yaml components/schemas as SSoT when possible; inline with SSoT comment as fallback.\",\n \"Define workflows with trigger, entry_conditions, and steps (delegate or gate). Each delegate step references a task and from_agent. Gate steps pause for user approval.\",\n \"Define guardrails (output-schema-conformance, domain-specific safety) and guardrail_policies grouping them with severity and action.\",\n \"Create agent-runtime.config.yaml: dsl points to main DSL file, generated_dir points to src/generated/dsl.\",\n \"Implement src/agents/types.ts: TaskId union type, AgentConfig interface (adapter, model, temperature), AgentOptions interface (dryRun, failOn), AgentRunResult interface (taskId, data, raw, prompt, dryRun, status, errorMessage, followUpsUsed, retriesUsed).\",\n \"Implement src/agents/orchestrator.ts: createAdapter() with dynamic imports from agent-contracts-runtime/adapters/*, runAgentWorkflow() that imports runWorkflow from agent-contracts-runtime, loads generated registries (including workflowRegistry) from src/generated/dsl/index.js, and calls runWorkflow with registries. NEVER use runTask — it is a low-level internal API that bypasses workflow orchestration.\",\n \"Implement src/agents/context-builder.ts: build{Command}Context() functions that transform CLI inputs into structured markdown prompts. Cap context at 16KB. Structure: # Request, ## Configuration, ## Target, ## Instructions.\",\n \"Implement src/agents/formatter.ts: computeExitCode() mapping findings to exit codes via --fail-on threshold, formatResultText() with severity icons, formatResultJson() for structured output.\",\n \"Create src/commands/{command}.ts handlers: load config, call context builder, call runAgentWorkflow, format output, compute exit code.\",\n \"Update cli-contract.yaml: add command definitions with standard LLM options (--adapter, --model, --show-prompt, --fail-on, --output, --report-format), exit codes (0, 1, 3, 10, 11, 12), x-agent metadata, and register AgentAuditResult/AgentFinding/AgentRecommendedAction in components/schemas.\",\n \"Add npm scripts: \\\"dsl:generate\\\" running agent-runtime generate --config dsl/agent-runtime.config.yaml. Add agent-contracts and agent-contracts-runtime as devDependencies. Add SDK packages as optional peerDependencies.\"\n ],\n \"constraints\": [\n \"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk, GeminiSdkAdapter from agent-contracts-runtime/adapters/gemini-sdk, MockAdapter from agent-contracts-runtime/adapters/mock.\",\n \"NEVER call adapter.send() or adapter.sendExecution() directly. All LLM invocations must go through runWorkflow() imported from agent-contracts-runtime. NEVER use runTask() — it is a low-level internal API. runWorkflow() handles prompt building, handoff validation, retry/followUp, workflow DAG, and plugin hooks.\",\n \"Dynamic-import both agent-contracts-runtime and adapter packages. The tool must work without them installed (graceful degradation). Pattern: const RUNTIME = \\\"agent-contracts-runtime\\\"; try { const { runWorkflow } = await import(RUNTIME); } catch { exit(11); }\",\n \"LLM commands use --report-format (json|text|yaml) for output format. --format is reserved for deterministic commands. Never mix them.\",\n \"Exit code convention: 0=success (no findings above threshold), 1=general error, 3=input validation/parse failed, 10=findings detected above --fail-on threshold, 11=agent-contracts-runtime not installed, 12=adapter initialization error (missing API key, etc.).\",\n \"Standard LLM command options (all must be present): --adapter <name> (mock|claude|openai|gemini, default varies), --model <name> (optional override), --show-prompt (output prompt without LLM call), --fail-on <level> (warning|error|critical, default error), --output/-o <file> (write to file instead of stdout), --report-format <fmt> (json|text|yaml, default json).\",\n \"Result handoff schemas must extend the AgentAuditResult base shape: summary (string, required), riskLevel (enum: low|medium|high|critical, required), findings (AgentFinding[], required), recommendedActions (AgentRecommendedAction[], optional), metadata (object with tool, command, version, generatedAt, adapter, model fields, optional).\",\n \"AgentFinding shape: id?, severity (info|warning|error|critical), category (domain vocabulary), target?, location?, message (required), recommendation?, confidence? (0-1), evidence? (array of {type,content,source}), details? (object).\",\n \"AgentRecommendedAction shape: kind (run_command|edit_file|review|confirm| block|ignore), title (required), command?, target?, rationale?.\",\n \"Main DSL entry must have version:1 and a system block with id and name. Without these, the generator produces numbered files instead of named ones.\",\n \"Every task must have a workflow field matching a defined workflow ID. Every workflow step's from_agent must match a defined agent ID. can_read_artifacts and can_write_artifacts must be empty arrays ([]) when no artifact registry is defined.\",\n \"agent-runtime.config.yaml format: dsl: ./{project}-dsl.yaml generated_dir: ../src/generated/dsl Optional: plugins (array of paths), recovery ({max_follow_ups, max_retries}).\",\n \"runWorkflow (the ONLY API consumer projects should use): Overloads: (1) runWorkflow(adapter, workflowId, options, registries?) — legacy. (2) runWorkflow(adapter, invocation, registries?) — structured (preferred). WorkflowInvocation: { workflow, handoff?, user_request?, runtime? {maxFollowUps,maxRetries,timeoutMs,readonly, dryRun}, hooks? {onStepComplete,onGate,onOptionalStep}, context? {cwd,environment,artifacts,variables} }. WorkflowResult: { workflow_id, status (completed|escalated|gate_rejected|error), steps[], total_elapsed_ms, escalation_reason?, error_message? }. NEVER use runTask() — it is a low-level internal API.\",\n \"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?}), GeminiSdkAdapter({apiKey?, model?, systemInstruction?, temperature?, maxOutputTokens?, guardrailHooks?}).\",\n \"Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from \\\"../generated/dsl/index.js\\\". Pass these as registries to runWorkflow: { workflowRegistry, taskRegistry, agentRegistry, handoffSchemas }.\",\n \"Plugin interface (AgentPlugin): id (string), beforeTask?(taskId, context), afterTask?(taskId, outcome), contextEnhancer?(taskId, context), promptEnhancer?(taskId, prompt, context), promptBuilder?(args), customGuardrails?, beforeWorkflow?(workflowId, userRequest), afterWorkflow?(workflowId, result).\",\n \"x-agent fields for LLM commands in cli-contract.yaml: riskLevel (low for read-only analysis), requiresConfirmation (false for read-only), idempotent (true for analysis), sideEffects ([network]), sideEffectNote (describe network call and optional file write), safeDryRunOption (show-prompt), expectedDurationMs (120000 typical), retryableExitCodes ([1, 12]).\"\n ],\n \"rules\": [\n {\n \"id\": \"R-IMPL-001\",\n \"description\": \"Import SDK adapters exclusively from agent-contracts-runtime/adapters/*. Never create adapter classes, wrapper functions, or API client code.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-002\",\n \"description\": \"All LLM invocations must use runWorkflow() from agent-contracts-runtime. NEVER use runTask() — it is a low-level internal API that bypasses workflow orchestration. Never call adapter.send(), adapter.followUp(), or adapter.sendExecution() directly. The runtime handles prompt building, schema validation, retry, followUp, workflow DAG, and plugin hooks.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-003\",\n \"description\": \"Every LLM command in cli-contract.yaml must have x-agent metadata with at minimum: riskLevel, safeDryRunOption, expectedDurationMs.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-004\",\n \"description\": \"Handoff type schemas must use $ref to cli-contract.yaml components/schemas as SSoT. If $ref resolution fails at generate time, inline the schema and add a YAML comment noting the SSoT path.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-005\",\n \"description\": \"Context builder must cap prompt input at 16KB. Filter large contexts (schema dumps, lint output, etc.) to relevant portions before inclusion.\",\n \"severity\": \"recommended\"\n },\n {\n \"id\": \"R-IMPL-006\",\n \"description\": \"The orchestrator must dynamic-import agent-contracts-runtime as a single string variable (const PKG = \\\"agent-contracts-runtime\\\") to enable graceful degradation. Exit with code 11 when the import fails, code 12 when the adapter fails to initialize.\",\n \"severity\": \"mandatory\"\n },\n {\n \"id\": \"R-IMPL-007\",\n \"description\": \"Generated DSL contracts must be imported from src/generated/dsl/index.js and passed as registries to runWorkflow. Never hard-code agent definitions, task definitions, or handoff schemas in application code.\",\n \"severity\": \"mandatory\"\n }\n ],\n \"escalation_criteria\": [\n {\n \"condition\": \"Target project has no cli-contract.yaml and user did not request creating one\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project is not a TypeScript / Node.js stack\",\n \"action\": \"stop_and_report\"\n },\n {\n \"condition\": \"Target project already has src/agents/ with a different integration pattern\",\n \"action\": \"stop_and_report\"\n }\n ]\n }\n },\n \"tasks\": {\n \"implement-llm-feature\": {\n \"description\": \"Implement LLM-powered commands in a target CLI tool using the\\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\\n\\n## Implementation Procedure\\n\\n### Step 1: Project Analysis\\n\\nRead these files from the target project:\\n- cli-contract.yaml — existing commands, components/schemas, x-agent usage\\n- package.json — dependencies, scripts, bin entries, type:\\\"module\\\" check\\n- tsconfig.json — module resolution, paths, outDir\\n- src/ directory structure — understand existing command handler pattern\\n\\nDetermine:\\n- Which LLM commands to add (audit / propose / explain)\\n- What domain-specific context each command needs\\n- What structured output schema each command returns\\n- Whether the project already has agent-contracts integration\\n\\n### Step 2: Install Dependencies\\n\\nAdd to package.json devDependencies:\\n- agent-contracts: ^0.32.0\\n- agent-contracts-runtime: ^0.31.0\\n- zod: ^4.0.0\\n\\nAdd optional peerDependencies for SDK packages:\\n- @anthropic-ai/claude-agent-sdk: >=0.2.0\\n- @openai/agents: >=0.10.0\\n- @google/genai: >=2.0.0\\n\\n### Step 3: Create DSL Definitions\\n\\nCreate directory structure:\\n\\n dsl/\\n ├── {project}-dsl.yaml\\n ├── agent-runtime.config.yaml\\n ├── agents/\\n │ └── {agent-name}.yaml\\n ├── tasks.yaml\\n └── handoff-types.yaml\\n\\n**Main DSL entry** (`dsl/{project}-dsl.yaml`):\\n\\n version: 1\\n system:\\n id: {project}\\n name: \\\"{Project} Agent System\\\"\\n default_workflow_order:\\n - {workflow-ids}\\n agents: { $ref: \\\"./agents/\\\" }\\n tasks: { $ref: \\\"./tasks.yaml\\\" }\\n handoff_types: { $ref: \\\"./handoff-types.yaml\\\" }\\n guardrails:\\n output-schema-conformance:\\n description: ...\\n scope: { agents: [...], tasks: [...] }\\n rationale: ...\\n guardrail_policies:\\n {domain}-safety-policy:\\n rules:\\n - guardrail: output-schema-conformance\\n severity: critical\\n action: block\\n workflow:\\n {workflow-id}:\\n description: ...\\n trigger: cli-command\\n entry_conditions: [...]\\n steps:\\n - type: delegate\\n task: {task-id}\\n from_agent: {agent-id}\\n\\n**Agent definition** (`dsl/agents/{agent-name}.yaml`):\\n\\n {agent-name}:\\n role_name: \\\"{Role Name}\\\"\\n purpose: >-\\n Domain-specific purpose describing what the agent knows\\n and what it can do that static rules cannot.\\n mode: read-only\\n can_read_artifacts: []\\n can_write_artifacts: []\\n can_invoke_agents: []\\n can_execute_tools: []\\n can_return_handoffs: [{result-handoff-ids}]\\n responsibilities: [...]\\n constraints: [...]\\n rules:\\n - id: \\\"R-{PREFIX}-001\\\"\\n description: ...\\n severity: mandatory\\n escalation_criteria:\\n - condition: ...\\n action: stop_and_report\\n\\n**Tasks** (`dsl/tasks.yaml`):\\n\\n {task-id}:\\n description: ...\\n target_agent: {agent-name}\\n allowed_from_agents: [{agent-name}]\\n workflow: {workflow-id}\\n input_artifacts: []\\n invocation_handoff: {request-handoff}\\n result_handoff: {result-handoff}\\n responsibilities: [...]\\n completion_criteria: [...]\\n\\n**Handoff types** (`dsl/handoff-types.yaml`):\\nUse AgentAuditResult shape as the base for result types:\\n\\n {result-handoff}:\\n version: 1\\n description: ...\\n schema:\\n type: object\\n required: [summary, riskLevel, findings]\\n properties:\\n summary: { type: string }\\n riskLevel:\\n type: string\\n enum: [low, medium, high, critical]\\n findings:\\n type: array\\n items:\\n type: object\\n required: [severity, category, message]\\n properties:\\n id: { type: string }\\n severity:\\n type: string\\n enum: [info, warning, error, critical]\\n category: { type: string }\\n target: { type: string }\\n location: { type: string }\\n message: { type: string }\\n recommendation: { type: string }\\n confidence: { type: number, minimum: 0, maximum: 1 }\\n recommendedActions:\\n type: array\\n items:\\n type: object\\n required: [kind, title]\\n properties:\\n kind:\\n type: string\\n enum: [run_command, edit_file, review, confirm, block, ignore]\\n title: { type: string }\\n command: { type: string }\\n target: { type: string }\\n rationale: { type: string }\\n metadata:\\n type: object\\n properties:\\n tool: { type: string }\\n command: { type: string }\\n version: { type: string }\\n generatedAt: { type: string }\\n adapter: { type: string }\\n model: { type: string }\\n\\nDomain-specific result types add properties alongside the base fields.\\n\\n**Runtime config** (`dsl/agent-runtime.config.yaml`):\\n\\n dsl: ./{project}-dsl.yaml\\n generated_dir: ../src/generated/dsl\\n\\n### Step 4: Generate TypeScript Contracts\\n\\nAdd to package.json scripts:\\n\\n \\\"dsl:generate\\\": \\\"agent-runtime generate --config dsl/agent-runtime.config.yaml\\\"\\n\\nRun: npm run dsl:generate\\n\\nThis produces src/generated/dsl/ containing:\\n- agents.ts (AgentContract interface + agentRegistry)\\n- tasks.ts (TaskContract interface + taskRegistry)\\n- workflows.ts (WorkflowContract + workflowRegistry)\\n- handoffs.ts (Zod schemas + handoffSchemas + factory functions)\\n- index.ts (barrel re-exports)\\n\\n### Step 5: Implement src/agents/ Module\\n\\n**src/agents/types.ts**:\\n\\n import type { {ResultType} } from \\\"../generated/dsl/handoffs.js\\\";\\n\\n export type TaskId = \\\"{task-1}\\\" | \\\"{task-2}\\\" | ...;\\n\\n export interface AgentConfig {\\n adapter?: string;\\n model?: string;\\n temperature?: number;\\n }\\n\\n export interface AgentOptions {\\n dryRun?: boolean;\\n failOn?: \\\"warning\\\" | \\\"error\\\" | \\\"critical\\\";\\n }\\n\\n export interface AgentRunResult {\\n taskId: TaskId;\\n data: {ResultType} | null;\\n raw: string;\\n prompt: string;\\n dryRun: boolean;\\n status: \\\"success\\\" | \\\"error\\\" | \\\"escalation\\\" | \\\"validation_error\\\";\\n errorMessage?: string;\\n followUpsUsed: number;\\n retriesUsed: number;\\n }\\n\\n**src/agents/orchestrator.ts**:\\n\\n export const EXIT_RUNTIME_MISSING = 11;\\n export const EXIT_ADAPTER_ERROR = 12;\\n\\n async function createAdapter(pkg: string, name: string, config: AgentConfig) {\\n switch (name) {\\n case \\\"mock\\\": {\\n const m = await import(`${pkg}/adapters/mock`);\\n return new m.MockAdapter();\\n }\\n case \\\"claude\\\": {\\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\\n }\\n case \\\"openai\\\": {\\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\\n }\\n case \\\"gemini\\\": {\\n const m = await import(`${pkg}/adapters/gemini-sdk`);\\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\\n }\\n }\\n }\\n\\n export async function runAgentWorkflow(\\n userRequest: string, workflowId: WorkflowId, config: AgentConfig, options: AgentOptions,\\n ): Promise<AgentRunResult> {\\n if (options.dryRun) return { workflowId, data:null, raw:\\\"\\\", prompt:userRequest, dryRun:true, status:\\\"success\\\" };\\n\\n const PKG = \\\"agent-contracts-runtime\\\";\\n let runWorkflow;\\n try { ({ runWorkflow } = await import(PKG)); }\\n catch { throw Object.assign(new Error(\\\"agent-contracts-runtime not installed\\\"), { exitCode: EXIT_RUNTIME_MISSING }); }\\n\\n let registries;\\n try {\\n const dsl = await import(\\\"../generated/dsl/index.js\\\");\\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas, workflowRegistry: dsl.workflowRegistry };\\n } catch { registries = {}; }\\n\\n const adapter = await createAdapter(PKG, config.adapter ?? \\\"mock\\\", config);\\n const result = await runWorkflow(adapter, { workflow: workflowId, user_request: userRequest, runtime: { maxFollowUps:3, maxRetries:1 } }, registries);\\n // map result to AgentRunResult\\n }\\n\\n**src/agents/context-builder.ts**:\\n\\nCRITICAL: context-builder builds the USER-SIDE prompt only.\\nAgent instructions (purpose, responsibilities, constraints, rules,\\nevaluation criteria, anti-patterns, output format) are defined in\\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\\nbuildTaskPrompt / runWorkflow. NEVER hardcode these in context-builder.\\n\\nContext-builder SHOULD contain:\\n- Domain-specific DATA: file contents, configuration, scan results\\n- Project metadata: target paths, dialect, directory structure\\n- Deterministic pre-analysis: lint results, schema excerpts\\n- Operational context: cwd, timestamps\\n- Brief task framing: \\\"# Migration Safety Audit Request\\\"\\n\\nContext-builder MUST NOT contain:\\n- \\\"## Instructions\\\" / \\\"## Required Patterns\\\" sections\\n- Output format specifications (handled by handoff schema)\\n- Evaluation criteria or checklists\\n- Anti-pattern definitions or rule sets\\n- API reference material\\n- Anything that duplicates DSL agent purpose/responsibilities/rules\\n\\n export function build{Command}Context(target, config): string {\\n const sections = [];\\n sections.push(\\\"# {Command} Request\\\");\\n sections.push(`## Target\\\\n\\\\n${target}`);\\n // Domain data only — no instructions here.\\n // Agent instructions come from DSL via buildTaskPrompt.\\n // Cap total context at 16KB\\n return sections.join(\\\"\\\\n\\\\n\\\");\\n }\\n\\n**src/agents/formatter.ts**:\\n\\n export function computeExitCode(result, options): number {\\n if (result.dryRun) return 0;\\n if (result.status !== \\\"success\\\") return 1;\\n const order = [\\\"info\\\",\\\"warning\\\",\\\"error\\\",\\\"critical\\\"];\\n const threshold = order.indexOf(options.failOn ?? \\\"error\\\");\\n return result.data.findings.some(f => order.indexOf(f.severity) >= threshold) ? 10 : 0;\\n }\\n\\n export function formatResultText(result): string { /* severity icons, structured output */ }\\n export function formatResultJson(result): string { return JSON.stringify(result.data, null, 2); }\\n\\n### Step 6: Create CLI Command Handlers\\n\\nFor each LLM command, create src/commands/{command}.ts:\\n\\n export async function command{Name}(target, opts) {\\n const cwd = process.cwd();\\n const context = build{Name}Context(target, config);\\n const agentConfig = { adapter: opts.adapter, model: opts.model, cwd };\\n const result = await runAgentWorkflow(context, \\\"{workflow-id}\\\", agentConfig, agentOpts);\\n if (opts.reportFormat === \\\"json\\\") console.log(formatResultJson(result));\\n else console.log(formatResultText(result));\\n process.exit(computeExitCode(result, opts));\\n }\\n\\nWire handlers through cli-contracts' generated program:\\n\\n import { createProgram, type CommandHandlers } from './generated/program.js';\\n\\n const handlers: CommandHandlers = {\\n {commandName}: async (target, opts) => {\\n await command{Name}(target, opts);\\n },\\n // ... other handlers\\n };\\n\\n createProgram(handlers, version).parse();\\n\\n### Step 7: Update cli-contract.yaml\\n\\nAdd each LLM command with standard options and x-agent metadata:\\n\\n {command-name}:\\n summary: \\\"{Command summary}\\\"\\n arguments: [...]\\n options:\\n - name: adapter\\n schema: { type: string, enum: [mock, claude, openai, gemini] }\\n - name: model\\n schema: { type: string }\\n - name: show-prompt\\n schema: { type: boolean, default: false }\\n - name: fail-on\\n schema: { type: string, enum: [warning, error, critical], default: error }\\n - name: output\\n aliases: [o]\\n schema: { type: string }\\n file: { mode: write }\\n - name: report-format\\n schema: { type: string, enum: [json, text, yaml], default: json }\\n x-agent:\\n riskLevel: low\\n requiresConfirmation: false\\n idempotent: true\\n sideEffects: [network]\\n sideEffectNote: >-\\n Network calls to LLM provider when adapter is not mock.\\n Filesystem write only when --output is specified.\\n safeDryRunOption: show-prompt\\n expectedDurationMs: 120000\\n retryableExitCodes: [1, 12]\\n exits:\\n '0': { description: \\\"No blocking findings.\\\", stdout: { format: json, schema: { $ref: '...' } } }\\n '1': { description: \\\"General error.\\\", stderr: { format: text } }\\n '3': { description: \\\"Input validation failed.\\\", stderr: { format: json } }\\n '10': { description: \\\"Blocking findings detected.\\\", stdout: { format: json, schema: { $ref: '...' } } }\\n '11': { description: \\\"Runtime not installed.\\\", stderr: { format: json } }\\n '12': { description: \\\"Adapter error.\\\", stderr: { format: json } }\\n\\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\\nto components/schemas if not already present.\\n\\n### Step 8: Update README\\n\\nAdd \\\"Agent-Native Toolchain\\\" section after mechanical features:\\n- Intro: tool encapsulates domain-specific semantic reasoning\\n- Deterministic checks first, then semantic audit\\n- Structured findings (AgentAuditResult/AgentFinding)\\n- LLM Adapter Configuration table\\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\\n\",\n \"target_agent\": \"llm-feature-implementer\",\n \"allowed_from_agents\": [\n \"llm-feature-implementer\"\n ],\n \"workflow\": \"implement-llm-feature\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"implement-request\",\n \"result_handoff\": \"implementation-result\",\n \"responsibilities\": [\n \"Analyze the target project and determine the right LLM commands to add\",\n \"Create all DSL definition files with correct cross-references\",\n \"Generate TypeScript contracts via agent-runtime generate\",\n \"Implement the complete src/agents/ module following the exact patterns\",\n \"Create CLI command handlers integrating with the project's existing CLI structure\",\n \"Update cli-contract.yaml with proper x-agent metadata and component schemas\",\n \"Ensure the implementation compiles and --show-prompt mode works\"\n ],\n \"completion_criteria\": [\n \"dsl/ directory contains valid DSL definitions that pass agent-runtime generate\",\n \"agent-runtime.config.yaml points to the DSL with correct generated_dir\",\n \"src/generated/dsl/ contains generated contracts (agentRegistry, taskRegistry, handoffSchemas, workflowRegistry)\",\n \"src/agents/orchestrator.ts uses runWorkflow from agent-contracts-runtime (never runTask directly, no direct adapter.send calls)\",\n \"src/agents/orchestrator.ts dynamic-imports the runtime and adapters with correct exit codes (11, 12)\",\n \"src/agents/context-builder.ts contains only domain data (file contents, config, scan results) — no hardcoded agent instructions, evaluation criteria, or output format specs\",\n \"src/agents/context-builder.ts caps input at 16KB\",\n \"src/agents/formatter.ts implements computeExitCode with the standard exit code mapping\",\n \"src/commands/ has a handler for each new LLM command, passing cwd to AgentConfig\",\n \"CLI entry point uses cli-contracts' createProgram(handlers, version) with CommandHandlers interface\",\n \"cli-contract.yaml has all new commands with --adapter, --model, --show-prompt, --fail-on, --output, --report-format options\",\n \"cli-contract.yaml has x-agent metadata on each new command (riskLevel, safeDryRunOption, expectedDurationMs)\",\n \"components/schemas includes AgentAuditResult and related schemas\",\n \"All generated TypeScript compiles without type errors\",\n \"--show-prompt returns the constructed prompt without calling the LLM\"\n ]\n },\n \"audit-dsl\": {\n \"description\": \"Audit the DSL layer of an LLM command integration.\\n\\nVerify these files exist and are well-formed:\\n- dsl/{project}-dsl.yaml — must have version:1, system:{id,name},\\n agents/tasks/handoff_types via $ref\\n- dsl/agents/*.yaml — each agent has role_name, purpose, mode,\\n can_read_artifacts:[], can_write_artifacts:[], responsibilities,\\n constraints, rules with R-PREFIX-NNN\\n- dsl/tasks.yaml — target_agent, workflow, result_handoff all\\n cross-reference valid IDs\\n- dsl/handoff-types.yaml — version:1, schema with JSON Schema,\\n result types follow AgentAuditResult shape\\n- dsl/agent-runtime.config.yaml — dsl and generated_dir fields\\n\\nSeverity classification:\\n- critical: missing version:1 or system block (generator will fail)\\n- critical: task references non-existent agent or workflow\\n- critical: agent mode contradicts its purpose (see below)\\n- error: agent missing constraints or rules\\n- error: handoff schema not following AgentAuditResult shape\\n- warning: missing guardrails or guardrail_policies\\n- warning: agent has no escalation_criteria\\n\\nCRITICAL: agent mode-purpose coherence (category: dsl-agent):\\n- Agent with mode: read-only has purpose or responsibilities\\n that describe file writing, editing, creation, or code\\n generation — the agent's adapter tools won't include Write/Edit\\n so the stated purpose is impossible to fulfil\\n- Agent with mode: read-write has purpose that is purely\\n analytical (audit, review, explain) with no file output —\\n unnecessarily broad permissions\\n\\nCategory vocabulary: dsl-structure, dsl-agent, dsl-task,\\ndsl-handoff, dsl-workflow, dsl-guardrail.\\n\\nOutput a partial audit-result with findings only from the DSL layer.\\n\",\n \"target_agent\": \"implementation-auditor\",\n \"allowed_from_agents\": [\n \"implementation-auditor\"\n ],\n \"workflow\": \"audit-implementation\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"audit-request\",\n \"result_handoff\": \"audit-result\",\n \"responsibilities\": [\n \"Check all DSL files for structural correctness\",\n \"Validate cross-references (agent↔task↔workflow↔handoff)\",\n \"Verify guardrails and guardrail_policies\",\n \"Check agent mode-purpose coherence (read-only agents must not have write-oriented purposes; read-write agents must justify their write permissions in their purpose)\"\n ],\n \"completion_criteria\": [\n \"Every dsl/* file checked for required fields\",\n \"Cross-references validated\",\n \"Agent mode is consistent with stated purpose and responsibilities\",\n \"Findings use dsl-* category vocabulary\"\n ]\n },\n \"audit-runtime\": {\n \"description\": \"Audit the runtime integration layer of an LLM command integration.\\n\\nScan src/agents/orchestrator.ts (or equivalent runtime module):\\n\\nCRITICAL violations (category: runtime-orchestrator):\\n- adapter.send() or adapter.sendExecution() called directly\\n- adapter.followUp() called directly\\n- Custom adapter class defined (not imported from runtime)\\n- runWorkflow not imported from agent-contracts-runtime\\n- runTask used instead of runWorkflow — consumer projects must\\n use runWorkflow() which orchestrates through the DSL workflow\\n DAG, activates workflow-level plugin hooks (beforeWorkflow/\\n afterWorkflow), handles gate steps and step dependencies.\\n runTask() is a low-level internal API; calling it directly\\n bypasses workflow orchestration entirely\\n\\nERROR violations (category: runtime-registry):\\n- Generated registries not imported from src/generated/dsl/\\n- Registries not passed to runWorkflow options\\n- Hard-coded agent/task definitions instead of registry lookup\\n\\nERROR violations (category: runtime-adapter):\\n- Adapter packages imported statically (not dynamic import)\\n- Missing exit code 11 when runtime import fails\\n- Missing exit code 12 when adapter creation fails\\n\\nERROR violations (category: runtime-handler):\\n- Project has cli-contracts generated code (src/generated/program.ts\\n or src/generated/cli/program.ts exporting CommandHandlers and\\n createProgram) but CLI entry point manually creates Commander\\n commands instead of using createProgram(handlers, version)\\n- LLM command handlers are not wired through the generated\\n CommandHandlers interface — handler signatures drift from the\\n cli-contract.yaml definition without type errors\\n- CLI entry point calls runTask directly instead of going through\\n the command handler → context-builder → orchestrator chain\\n\\nWARNING violations (category: runtime-plugin):\\n- Plugin hooks explicitly bypassed or ignored\\n\\nCategory vocabulary: runtime-orchestrator, runtime-registry,\\nruntime-adapter, runtime-handler, runtime-plugin.\\n\\nOutput a partial audit-result with findings only from the runtime layer.\\n\",\n \"target_agent\": \"implementation-auditor\",\n \"allowed_from_agents\": [\n \"implementation-auditor\"\n ],\n \"workflow\": \"audit-implementation\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"audit-request\",\n \"result_handoff\": \"audit-result\",\n \"responsibilities\": [\n \"Scan orchestrator code for direct adapter usage\",\n \"Verify runWorkflow is used (not runTask) for LLM command execution\",\n \"Verify registry imports and passing\",\n \"Check adapter creation patterns and exit codes\",\n \"Verify cli-contracts handler wiring (CommandHandlers + createProgram used in CLI entry point)\"\n ],\n \"completion_criteria\": [\n \"All orchestrator files scanned for adapter.send / adapter.followUp\",\n \"No runTask usage found (runWorkflow must be used instead)\",\n \"Registry usage verified\",\n \"Exit code 11/12 patterns checked\",\n \"cli-contracts handler integration verified (CommandHandlers interface used, createProgram called)\"\n ]\n },\n \"audit-cli-contract\": {\n \"description\": \"Audit the CLI contract layer of an LLM command integration.\\n\\nParse cli-contract.yaml and check each LLM command:\\n\\nERROR: missing standard options (category: cli-contract-options):\\n- --adapter, --model, --show-prompt, --fail-on, --output, --report-format\\n- Using --format instead of --report-format for LLM commands\\n\\nERROR: missing x-agent metadata (category: cli-contract-xagent):\\n- No x-agent block on LLM command\\n- Missing riskLevel, safeDryRunOption, or expectedDurationMs\\n- Using snake_case instead of camelCase for x-agent fields\\n\\nERROR: wrong exit codes (category: cli-contract-exits):\\n- Missing exit 0/1/3/10/11/12 definitions\\n- Exit 10 not defined for finding-based commands\\n\\nWARNING: missing schemas (category: cli-contract-schema):\\n- AgentAuditResult not in components/schemas\\n- AgentFinding, AgentRecommendedAction, AgentEvidence not defined\\n\\nCategory vocabulary: cli-contract-options, cli-contract-xagent,\\ncli-contract-exits, cli-contract-schema.\\n\\nOutput a partial audit-result with findings only from the CLI contract layer.\\n\",\n \"target_agent\": \"implementation-auditor\",\n \"allowed_from_agents\": [\n \"implementation-auditor\"\n ],\n \"workflow\": \"audit-implementation\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"audit-request\",\n \"result_handoff\": \"audit-result\",\n \"responsibilities\": [\n \"Check each LLM command for standard options\",\n \"Verify x-agent metadata fields and casing\",\n \"Validate exit code definitions\",\n \"Check components/schemas for canonical types\"\n ],\n \"completion_criteria\": [\n \"Every LLM command checked for all 6 standard options\",\n \"x-agent metadata validated on every LLM command\",\n \"Exit codes verified against convention\",\n \"Schema completeness checked\"\n ]\n },\n \"audit-architecture\": {\n \"description\": \"Audit the architecture and module structure of an LLM command integration.\\n\\nVerify module structure (category: architecture-modules):\\n- src/agents/types.ts exists with TaskId, AgentConfig, AgentOptions, AgentRunResult\\n- src/agents/orchestrator.ts exists\\n- src/agents/context-builder.ts exists\\n- src/agents/formatter.ts exists with computeExitCode\\n\\nVerify behavior (category: architecture-dry-run):\\n- --show-prompt path returns the constructed prompt without calling the adapter\\n- buildTaskPrompt is used (not a placeholder string)\\n\\nCRITICAL: context-builder SSoT violations (category: architecture-context-builder):\\n\\nThe context-builder's role is to assemble domain-specific DATA (file\\ncontents, configuration, scan results, schema context) into the user\\nprompt. Agent INSTRUCTIONS (how to evaluate, what rules to apply,\\nwhat patterns to look for, output format) belong in the DSL agent\\ndefinition and are injected by buildTaskPrompt / runWorkflow.\\n\\nDetect any of the following in context-builder source code:\\n- Sections titled \\\"## Instructions\\\", \\\"## Required Patterns\\\",\\n \\\"## Audit Instructions\\\", \\\"## Output Format\\\", or similar\\n behavioral directive headings — these are agent instructions\\n that belong in DSL (agent purpose, responsibilities, constraints,\\n rules) and must not be hardcoded in context-builder\\n- Output format specifications (field lists, JSON/YAML schema\\n descriptions, example output structures) — buildTaskPrompt\\n already generates \\\"Required Output Format\\\" from the handoff\\n Zod schema; duplicating this in context-builder causes conflicts\\n- Domain-specific evaluation criteria, checklists, anti-pattern\\n definitions, rule sets, or API reference material — these\\n belong in the DSL agent definition's purpose field\\n- Any string that duplicates or paraphrases content already\\n present in the DSL agent's purpose, responsibilities,\\n constraints, or rules fields\\n\\nWhat IS allowed in context-builder:\\n- File contents read from disk (migration SQL, schema, config)\\n- Project metadata (dialect, directories, file lists)\\n- Deterministic pre-analysis results (lint violations, scan output)\\n- Operational context (target path, cwd, timestamp)\\n- Brief task framing (\\\"# Migration Safety Audit Request\\\")\\n\\nERROR: mode-purpose coherence (category: architecture-agent-coherence):\\n- DSL agent with mode: read-only has purpose or responsibilities\\n that describe file writing, editing, creation, or modification\\n- DSL agent with mode: read-write but no cwd propagated to adapter\\n — the agent's file tools won't operate in the project directory\\n- Command handler doesn't pass cwd to AgentConfig when using an\\n agentic adapter (claude)\\n\\nERROR: adapter cwd propagation (category: architecture-adapter-cwd):\\n- AgentConfig type has no cwd field\\n- Command handlers don't set config.cwd = process.cwd() or\\n resolve(projectDir)\\n- createAdapter doesn't pass cwd to adapter constructor/factory\\n- Agentic adapters (claude) instantiated without cwd —\\n their file tools will operate in an undefined directory\\n\\nCRITICAL: runTask usage (category: architecture-handler):\\n- runTask() imported or called anywhere in the consumer project —\\n consumer projects must use runWorkflow() exclusively; runTask()\\n is a low-level internal API that bypasses workflow DAG\\n orchestration, workflow-level plugin hooks, and gate steps\\n\\nERROR: cli-contracts handler wiring (category: architecture-handler):\\n- Project has cli-contracts generated code (src/generated/program.ts\\n or src/generated/cli/program.ts with CommandHandlers) but CLI\\n entry point manually creates Commander commands instead of\\n calling createProgram(handlers, version)\\n- Command handlers bypass the generated CommandHandlers interface\\n\\nScan for direct SDK imports (category: architecture-modules):\\n- @anthropic-ai/sdk or @anthropic-ai/claude-agent-sdk imported\\n outside src/agents/orchestrator.ts or adapter files\\n- openai or @openai/agents imported outside adapters\\n- @google/genai imported outside adapters\\n\\nCategory vocabulary: architecture-modules, architecture-dry-run,\\narchitecture-context-builder, architecture-agent-coherence,\\narchitecture-adapter-cwd, architecture-handler,\\narchitecture-formatter.\\n\\nOutput a partial audit-result with findings only from the architecture layer.\\n\",\n \"target_agent\": \"implementation-auditor\",\n \"allowed_from_agents\": [\n \"implementation-auditor\"\n ],\n \"workflow\": \"audit-implementation\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"audit-request\",\n \"result_handoff\": \"audit-result\",\n \"responsibilities\": [\n \"Verify module structure\",\n \"Check dry-run behavior\",\n \"Audit context-builder for SSoT violations (hardcoded instructions, output format specs, domain rules that belong in DSL)\",\n \"Check mode-purpose coherence across DSL definitions and runtime code\",\n \"Verify cwd propagation from command handler through adapter config\",\n \"Verify cli-contracts handler wiring (CommandHandlers + createProgram)\",\n \"Scan for direct SDK imports\"\n ],\n \"completion_criteria\": [\n \"Module structure verified\",\n \"Dry-run behavior confirmed\",\n \"Context-builder contains only domain data, not agent instructions\",\n \"Agent mode is consistent with purpose and tool usage\",\n \"cwd is propagated to agentic adapters\",\n \"cli-contracts handler integration verified\",\n \"No direct SDK imports outside adapter files\"\n ]\n },\n \"audit-merge\": {\n \"description\": \"Merge the partial audit results from the four parallel layer audits\\n(DSL, runtime, CLI contract, architecture) into a single unified\\naudit-result.\\n\\nThe prior_context contains the JSON output from each completed\\naudit step. Parse each one, combine all findings into a single\\narray, deduplicate by (target + message), assign sequential IDs\\n(F-001, F-002, ...), derive the overall riskLevel from the worst\\nfinding severity, and produce prioritized recommendedActions.\\n\\nMerging rules:\\n- Collect all findings from all layer results\\n- Sort: critical first, then error, warning, info\\n- Assign sequential IDs: F-001, F-002, ...\\n- Deduplicate: if two findings have the same target and message, keep one\\n- Derive riskLevel: any critical → critical, any error → high,\\n any warning → medium, info only → low\\n- Merge recommendedActions from all layers, deduplicate by title\\n- Set metadata: { tool: \\\"agent-runtime\\\", command: \\\"audit-implementation\\\" }\\n\",\n \"target_agent\": \"implementation-auditor\",\n \"allowed_from_agents\": [\n \"implementation-auditor\"\n ],\n \"workflow\": \"audit-implementation\",\n \"input_artifacts\": [],\n \"invocation_handoff\": \"audit-request\",\n \"result_handoff\": \"audit-result\",\n \"responsibilities\": [\n \"Parse prior_context JSON from each layer audit step\",\n \"Merge and deduplicate findings\",\n \"Derive overall riskLevel\",\n \"Produce a single coherent summary paragraph\"\n ],\n \"completion_criteria\": [\n \"All findings from all layers included\",\n \"No duplicate findings\",\n \"riskLevel correctly derived from worst finding\",\n \"Summary paragraph covers all audited layers\"\n ]\n }\n },\n \"handoff_types\": {\n \"implement-request\": {\n \"version\": 1,\n \"description\": \"Request to implement LLM-powered features in a CLI tool\",\n \"schema\": {\n \"type\": \"object\",\n \"required\": [\n \"description\",\n \"project_dir\"\n ],\n \"properties\": {\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Description of the LLM feature(s) to implement\"\n },\n \"project_dir\": {\n \"type\": \"string\",\n \"description\": \"Absolute path to the target project directory\"\n },\n \"reference_doc\": {\n \"type\": \"string\",\n \"description\": \"Content of the integrate-llm-commands reference documentation\"\n }\n }\n }\n },\n \"audit-request\": {\n \"version\": 1,\n \"description\": \"Request to audit an LLM command integration\",\n \"schema\": {\n \"type\": \"object\",\n \"required\": [\n \"project_dir\"\n ],\n \"properties\": {\n \"project_dir\": {\n \"type\": \"string\",\n \"description\": \"Absolute path to the target project directory\"\n },\n \"focus\": {\n \"type\": \"string\",\n \"description\": \"Optional focus area (dsl, runtime, cli-contract, architecture, or all). Defaults to all.\",\n \"enum\": [\n \"all\",\n \"dsl\",\n \"runtime\",\n \"cli-contract\",\n \"architecture\"\n ]\n }\n }\n }\n },\n \"audit-result\": {\n \"version\": 1,\n \"description\": \"Structured audit result following AgentAuditResult shape. Conforms to cli-contracts reference schema.\",\n \"schema\": {\n \"type\": \"object\",\n \"required\": [\n \"summary\",\n \"riskLevel\",\n \"findings\"\n ],\n \"properties\": {\n \"summary\": {\n \"type\": \"string\",\n \"description\": \"One-paragraph overall assessment\"\n },\n \"riskLevel\": {\n \"type\": \"string\",\n \"enum\": [\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"description\": \"Derived from worst finding: any critical → critical, any error → high, any warning → medium, info only → low\"\n },\n \"findings\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"severity\",\n \"category\",\n \"message\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"Unique finding identifier (e.g. AUDIT-001)\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\n \"info\",\n \"warning\",\n \"error\",\n \"critical\"\n ]\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"One of: dsl-structure, dsl-agent, dsl-task, dsl-handoff, dsl-workflow, dsl-guardrail, runtime-adapter, runtime-orchestrator, runtime-registry, runtime-handler, runtime-plugin, cli-contract-options, cli-contract-xagent, cli-contract-exits, cli-contract-schema, architecture-modules, architecture-dry-run, architecture-context-builder, architecture-agent-coherence, architecture-adapter-cwd, architecture-handler, architecture-formatter\"\n },\n \"target\": {\n \"type\": \"string\",\n \"description\": \"File path where the issue was found\"\n },\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Line number or section within the file\"\n },\n \"message\": {\n \"type\": \"string\",\n \"description\": \"Concise description of the issue\"\n },\n \"recommendation\": {\n \"type\": \"string\",\n \"description\": \"Concrete fix or remediation step\"\n },\n \"confidence\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 1,\n \"description\": \"1.0 for pattern match, 0.8+ for structural check, 0.5-0.8 for heuristic assessment\"\n }\n }\n }\n },\n \"recommendedActions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"kind\",\n \"title\"\n ],\n \"properties\": {\n \"kind\": {\n \"type\": \"string\",\n \"enum\": [\n \"run_command\",\n \"edit_file\",\n \"review\",\n \"confirm\",\n \"block\",\n \"ignore\"\n ]\n },\n \"title\": {\n \"type\": \"string\"\n },\n \"command\": {\n \"type\": \"string\",\n \"description\": \"CLI command to run (for run_command kind)\"\n },\n \"target\": {\n \"type\": \"string\",\n \"description\": \"Target file or resource\"\n },\n \"rationale\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"metadata\": {\n \"type\": \"object\",\n \"properties\": {\n \"tool\": {\n \"type\": \"string\"\n },\n \"command\": {\n \"type\": \"string\"\n },\n \"version\": {\n \"type\": \"string\"\n },\n \"generatedAt\": {\n \"type\": \"string\"\n },\n \"adapter\": {\n \"type\": \"string\"\n },\n \"model\": {\n \"type\": \"string\"\n }\n }\n }\n }\n }\n },\n \"implementation-result\": {\n \"version\": 1,\n \"description\": \"Result of the LLM feature implementation\",\n \"schema\": {\n \"type\": \"object\",\n \"required\": [\n \"files_created\",\n \"files_modified\",\n \"summary\"\n ],\n \"properties\": {\n \"files_created\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"description\": \"List of newly created files\"\n },\n \"files_modified\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"description\": \"List of modified existing files\"\n },\n \"summary\": {\n \"type\": \"string\",\n \"description\": \"Human-readable summary of the implementation\"\n },\n \"commands_added\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"name\",\n \"type\"\n ],\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Command name\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"audit\",\n \"propose\",\n \"explain\"\n ],\n \"description\": \"Command type\"\n },\n \"description\": {\n \"type\": \"string\",\n \"description\": \"Command description\"\n }\n }\n }\n },\n \"next_steps\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"description\": \"Recommended next steps for the developer\"\n }\n }\n }\n }\n },\n \"guardrails\": {\n \"output-schema-conformance\": {\n \"description\": \"Ensure all agent outputs conform to their respective handoff schemas. Validation is performed at runtime via Zod.\",\n \"scope\": {\n \"agents\": [\n \"llm-feature-implementer\",\n \"implementation-auditor\"\n ],\n \"tasks\": [\n \"implement-llm-feature\",\n \"audit-dsl\",\n \"audit-runtime\",\n \"audit-cli-contract\",\n \"audit-architecture\",\n \"audit-merge\"\n ]\n },\n \"rationale\": \"Structured output conformance is critical for CLI parsing and downstream tooling integration.\"\n },\n \"no-direct-api-call\": {\n \"description\": \"The implementer agent must not generate code that calls LLM APIs directly. All LLM invocations must go through agent-contracts-runtime runWorkflow().\",\n \"scope\": {\n \"agents\": [\n \"llm-feature-implementer\"\n ]\n },\n \"rationale\": \"Preserves SDK adapter abstraction, enabling adapter swap, plugin hooks, and guardrail enforcement.\"\n },\n \"audit-read-only\": {\n \"description\": \"The auditor agent must not create, modify, or delete any files. It operates in read-only mode and produces findings only.\",\n \"scope\": {\n \"agents\": [\n \"implementation-auditor\"\n ]\n },\n \"rationale\": \"Audit results must be reviewed by the developer before changes are applied. The auditor observes; the developer decides.\"\n }\n },\n \"guardrail_policies\": {\n \"implement-safety-policy\": {\n \"description\": \"Guardrail policy for the LLM feature implementation agent\",\n \"rules\": [\n {\n \"guardrail\": \"output-schema-conformance\",\n \"severity\": \"critical\",\n \"action\": \"block\"\n },\n {\n \"guardrail\": \"no-direct-api-call\",\n \"severity\": \"critical\",\n \"action\": \"block\"\n }\n ]\n },\n \"audit-safety-policy\": {\n \"description\": \"Guardrail policy for the implementation auditor agent\",\n \"rules\": [\n {\n \"guardrail\": \"output-schema-conformance\",\n \"severity\": \"critical\",\n \"action\": \"block\"\n },\n {\n \"guardrail\": \"audit-read-only\",\n \"severity\": \"critical\",\n \"action\": \"block\"\n }\n ]\n }\n },\n \"workflow\": {\n \"implement-llm-feature\": {\n \"description\": \"Implement LLM-powered commands in a CLI tool\",\n \"trigger\": \"cli-command\",\n \"entry_conditions\": [\n \"Target project is a TypeScript / Node.js project\",\n \"cli-contract.yaml exists or is being created\"\n ],\n \"steps\": [\n {\n \"type\": \"delegate\",\n \"task\": \"implement-llm-feature\",\n \"from_agent\": \"llm-feature-implementer\"\n }\n ]\n },\n \"audit-implementation\": {\n \"description\": \"Audit an LLM command integration for pattern conformance\",\n \"trigger\": \"cli-command\",\n \"entry_conditions\": [\n \"Target project has LLM command integration to audit\"\n ],\n \"steps\": [\n {\n \"type\": \"delegate\",\n \"task\": \"audit-dsl\",\n \"from_agent\": \"implementation-auditor\",\n \"depends_on\": []\n },\n {\n \"type\": \"delegate\",\n \"task\": \"audit-runtime\",\n \"from_agent\": \"implementation-auditor\",\n \"depends_on\": []\n },\n {\n \"type\": \"delegate\",\n \"task\": \"audit-cli-contract\",\n \"from_agent\": \"implementation-auditor\",\n \"depends_on\": []\n },\n {\n \"type\": \"delegate\",\n \"task\": \"audit-architecture\",\n \"from_agent\": \"implementation-auditor\",\n \"depends_on\": []\n },\n {\n \"type\": \"delegate\",\n \"task\": \"audit-merge\",\n \"from_agent\": \"implementation-auditor\",\n \"depends_on\": [\n \"audit-dsl\",\n \"audit-runtime\",\n \"audit-cli-contract\",\n \"audit-architecture\"\n ]\n }\n ]\n }\n }\n} as const;\n","/**\n * audit-implementation command — uses the built-in Implementation Auditor agent\n * to verify an LLM command integration follows the agent-contracts stack.\n *\n * The agent is read-only: it analyzes but does not modify files.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nimport { runWorkflow } from \"./workflow-runner.js\";\nimport { buildTaskPrompt } from \"./task-runner.js\";\nimport type { SdkAdapter, TaskContext } from \"./task-runner.js\";\nimport type { WorkflowInvocation } from \"./workflow-runner.js\";\nimport {\n agentRegistry,\n taskRegistry,\n handoffSchemas,\n workflowRegistry,\n resolvedDsl,\n} from \"../builtin-agents/generated/index.js\";\nimport {\n createGuardrailHooksFromRules,\n type GuardrailHooks,\n type GuardrailRuleData,\n} from \"./guardrail-hooks.js\";\nimport type { AuditResult } from \"../builtin-agents/generated/handoffs.js\";\n\n// ---------------------------------------------------------------------------\n// Locale detection\n// ---------------------------------------------------------------------------\n\nfunction getLocale(): string {\n return (\n process.env.LANG?.split(\".\")[0] ??\n process.env.LC_ALL?.split(\".\")[0] ??\n process.env.LANGUAGE?.split(\":\")[0] ??\n \"en_US\"\n );\n}\n\nfunction isJapanese(): boolean {\n return getLocale().startsWith(\"ja\");\n}\n\n// ---------------------------------------------------------------------------\n// Messages — locale-aware\n// ---------------------------------------------------------------------------\n\ninterface Messages {\n noProjectDir: (dir: string) => string;\n adapterError: (msg: string) => string;\n dryRunHeader: string;\n dryRunProjectDir: (dir: string) => string;\n dryRunFocus: (focus: string) => string;\n auditStarting: (adapter: string) => string;\n auditSuccess: string;\n auditFailed: (reason: string) => string;\n riskLevel: (level: string) => string;\n findingsHeader: (count: number) => string;\n noFindings: string;\n recommendedActionsHeader: string;\n}\n\nconst en: Messages = {\n noProjectDir: (dir) => `Project directory not found: ${dir}`,\n adapterError: (msg) => `Adapter initialization failed: ${msg}`,\n dryRunHeader: \"=== Dry Run (audit-implementation) ===\",\n dryRunProjectDir: (dir) => `Project: ${dir}`,\n dryRunFocus: (focus) => `Focus: ${focus}`,\n auditStarting: (adapter) => `Starting audit with ${adapter} adapter...`,\n auditSuccess: \"Audit completed.\",\n auditFailed: (reason) => `Audit failed: ${reason}`,\n riskLevel: (level) => `Risk level: ${level}`,\n findingsHeader: (count) => `Findings (${count}):`,\n noFindings: \"No findings.\",\n recommendedActionsHeader: \"Recommended actions:\",\n};\n\nconst ja: Messages = {\n noProjectDir: (dir) => `プロジェクトディレクトリが見つかりません: ${dir}`,\n adapterError: (msg) => `アダプター初期化に失敗しました: ${msg}`,\n dryRunHeader: \"=== ドライラン (audit-implementation) ===\",\n dryRunProjectDir: (dir) => `プロジェクト: ${dir}`,\n dryRunFocus: (focus) => `フォーカス: ${focus}`,\n auditStarting: (adapter) => `${adapter} アダプターで監査を開始します...`,\n auditSuccess: \"監査が完了しました。\",\n auditFailed: (reason) => `監査に失敗しました: ${reason}`,\n riskLevel: (level) => `リスクレベル: ${level}`,\n findingsHeader: (count) => `検出事項 (${count}件):`,\n noFindings: \"検出事項はありません。\",\n recommendedActionsHeader: \"推奨アクション:\",\n};\n\nfunction msg(): Messages {\n return isJapanese() ? ja : en;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\nasync function createAuditAdapter(\n adapterName: string,\n projectDir: string,\n model?: string,\n guardrailHooks?: GuardrailHooks,\n): Promise<SdkAdapter> {\n switch (adapterName) {\n case \"claude\": {\n const { ClaudeAgentSdkAdapter } = await import(\"../adapters/claude-agent-sdk.js\");\n return new ClaudeAgentSdkAdapter({\n cwd: projectDir,\n model,\n guardrailHooks,\n });\n }\n case \"mock\": {\n const { MockAdapter } = await import(\"../adapters/mock.js\");\n return new MockAdapter();\n }\n default:\n throw new Error(\n `Unsupported adapter for audit-implementation: \"${adapterName}\". ` +\n `Available: claude, mock`,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface AuditOptions {\n adapter: string;\n projectDir: string;\n focus: \"all\" | \"dsl\" | \"runtime\" | \"cli-contract\" | \"architecture\";\n dryRun: boolean;\n failOn: \"warning\" | \"error\" | \"critical\";\n reportFormat: \"json\" | \"text\" | \"yaml\";\n model?: string;\n progressOutput?: { write(chunk: string): unknown };\n}\n\nexport interface AuditRunResult {\n status: \"success\" | \"failed\" | \"dry_run\";\n exitCode: number;\n data?: AuditResult;\n error?: string;\n}\n\nconst SEVERITY_ORDER: Record<string, number> = {\n info: 0,\n warning: 1,\n error: 2,\n critical: 3,\n};\n\nfunction hasFindings(result: AuditResult, failOn: string): boolean {\n const threshold = SEVERITY_ORDER[failOn] ?? 2;\n return result.findings.some(\n (f) => (SEVERITY_ORDER[f.severity] ?? 0) >= threshold,\n );\n}\n\nexport async function runAuditImplementation(\n options: AuditOptions,\n): Promise<AuditRunResult> {\n const m = msg();\n const projectDir = resolve(options.projectDir);\n\n if (!existsSync(projectDir)) {\n return { status: \"failed\", exitCode: 3, error: m.noProjectDir(projectDir) };\n }\n\n // --- Build invocation context (shared between dry-run and live run) ---\n const focusInstruction = options.focus !== \"all\"\n ? `\\n\\nFocus the audit on the \"${options.focus}\" layer only.`\n : \"\";\n\n const userRequest = [\n `Audit the LLM command integration in the following project.`,\n `Project directory: ${projectDir}`,\n focusInstruction,\n ].join(\"\\n\");\n\n const context: TaskContext = {\n user_request: userRequest,\n relevant_paths: [projectDir],\n };\n\n // --- Dry run: emit prompts for all parallel audit tasks ---\n if (options.dryRun) {\n const agent = agentRegistry[\"implementation-auditor\"];\n const auditTasks = [\"audit-dsl\", \"audit-runtime\", \"audit-cli-contract\", \"audit-architecture\"];\n const prompts = auditTasks.map((taskId) => {\n const task = taskRegistry[taskId];\n if (!task) return `# [Task not found: ${taskId}]`;\n return buildTaskPrompt(agent, task, context, { handoffSchemas });\n });\n const separator = \"\\n\\n\" + \"=\".repeat(72) + \"\\n\\n\";\n const fullPrompt = prompts.join(separator);\n\n return {\n status: \"dry_run\",\n exitCode: 0,\n data: {\n summary: fullPrompt,\n riskLevel: \"low\",\n findings: [],\n },\n };\n }\n\n // --- Create adapter ---\n let guardrailHooks: GuardrailHooks | undefined;\n const rawRules = resolvedDsl._guardrailRules as GuardrailRuleData | undefined;\n if (\n rawRules &&\n (rawRules.commandRules?.length ||\n rawRules.fileRules?.length ||\n rawRules.contentRules?.length)\n ) {\n guardrailHooks = createGuardrailHooksFromRules(rawRules);\n }\n\n let adapter: SdkAdapter;\n try {\n adapter = await createAuditAdapter(\n options.adapter,\n projectDir,\n options.model,\n guardrailHooks,\n );\n } catch (err) {\n return { status: \"failed\", exitCode: 12, error: m.adapterError((err as Error).message) };\n }\n\n console.error(m.auditStarting(options.adapter));\n\n const registries = {\n workflowRegistry,\n taskRegistry,\n agentRegistry,\n handoffSchemas,\n };\n\n // --- Run workflow ---\n const invocation: WorkflowInvocation = {\n workflow: \"audit-implementation\",\n user_request: userRequest,\n runtime: {\n maxFollowUps: 2,\n maxRetries: 1,\n },\n hooks: {\n onGate: async () => true,\n },\n context: {\n cwd: projectDir,\n },\n progressOutput: options.progressOutput,\n };\n\n const result = await runWorkflow(adapter, invocation, registries);\n\n if (result.status !== \"completed\") {\n const reason = result.escalation_reason ?? result.error_message ?? result.status;\n return { status: \"failed\", exitCode: 1, error: m.auditFailed(reason) };\n }\n\n const lastStep = result.steps[result.steps.length - 1];\n const outcomeData = (lastStep?.outcome as Record<string, unknown>)?.data as\n | AuditResult\n | undefined;\n\n const auditData: AuditResult = outcomeData ?? {\n summary: m.auditSuccess,\n riskLevel: \"low\",\n findings: [],\n };\n\n const exitCode = hasFindings(auditData, options.failOn) ? 10 : 0;\n\n return {\n status: \"success\",\n exitCode,\n data: auditData,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Text formatter\n// ---------------------------------------------------------------------------\n\nconst SEVERITY_ICON: Record<string, string> = {\n critical: \"✗\",\n error: \"✗\",\n warning: \"!\",\n info: \"·\",\n};\n\nexport function formatAuditResult(result: AuditRunResult): string {\n const m = msg();\n\n if (result.status === \"dry_run\") {\n return result.data?.summary ?? m.dryRunHeader;\n }\n\n if (result.status === \"failed\") {\n return result.error ?? m.auditFailed(\"unknown\");\n }\n\n const data = result.data;\n if (!data) return m.auditSuccess;\n\n const lines: string[] = [data.summary, \"\"];\n\n lines.push(m.riskLevel(data.riskLevel));\n lines.push(\"\");\n\n if (data.findings.length === 0) {\n lines.push(m.noFindings);\n } else {\n lines.push(m.findingsHeader(data.findings.length));\n for (const f of data.findings) {\n const icon = SEVERITY_ICON[f.severity] ?? \"·\";\n const id = f.id ? `[${f.id}] ` : \"\";\n const target = f.target ? ` (${f.target})` : \"\";\n lines.push(` ${icon} ${id}${f.severity.toUpperCase()}: ${f.message}${target}`);\n if (f.recommendation) {\n lines.push(` → ${f.recommendation}`);\n }\n }\n lines.push(\"\");\n }\n\n if (data.recommendedActions && data.recommendedActions.length > 0) {\n lines.push(m.recommendedActionsHeader);\n for (const a of data.recommendedActions) {\n const cmd = a.command ? ` — ${a.command}` : \"\";\n lines.push(` [${a.kind}] ${a.title}${cmd}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAQA,SAAS,cAAAA,aAAY,gBAAAC,eAAc,qBAAqB;AACxD,SAAS,WAAAC,gBAAe;AACxB,SAAS,gBAAgB;;;ACTzB,SAAS,eAAe;;;ACEjB,IAAM,g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AC3E,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AAEF;AAEA,IAAM,UAAU,cAAc,UAAU,OAAO;AAC/C,MAAM,QAAQ,WAAW;","names":["existsSync","readFileSync","resolve","handlers","program","existsSync","readFile","join","existsSync","resolve","join","implementLlmFeature","msg","join","existsSync","resolve","existsSync","resolve","getLocale","isJapanese","en","msg","ja","resolve","existsSync","YAML","existsSync","resolvedDsl","resolve","readFileSync","msg"]}
|