agent-contracts-runtime 0.32.1 → 0.32.2

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/dist/cli/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  loadPlugins,
5
5
  pluginRegistry,
6
6
  runWorkflow
7
- } from "../chunk-NLVQ3OOT.js";
7
+ } from "../chunk-MINIXDVQ.js";
8
8
  import {
9
9
  checkFreshness,
10
10
  generate,
@@ -49,7 +49,7 @@ function createProgram(handlers2, version) {
49
49
  program2.command("show-prompt").description("Display the generated prompt for a task.").argument("<task-id>", "ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).").option("-u, --user-request <value>", "User request text to include in the prompt preview.", "(preview)").option("--format <value>", "Output format.", "markdown").option("--with-plugins", "Apply registered plugin prompt enhancers to the output.", false).action(async (taskId, opts, cmd) => {
50
50
  await handlers2.showPrompt(taskId, opts, cmd.optsWithGlobals());
51
51
  });
52
- program2.command("implement").description("Implement LLM-powered commands in a CLI tool.").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".').option("-a, --adapter <value>", "SDK adapter to use. Must be an agentic adapter (claude, cursor).", "claude").option("-p, --project-dir <value>", "Path to the target project directory.", ".").option("-n, --dry-run", "Output the prompt context without calling the LLM.", false).option("--model <value>", "Model name override for the selected adapter.").option("--fail-on <value>", "Minimum finding severity that causes a non-zero exit.", "error").option("-o, --output <value>", "Write the result to a file instead of stdout.").option("--report-format <value>", "Output format for the result.", "text").option("--show-prompt", "Output the constructed prompt without calling the LLM API.", false).action(async (description, opts, cmd) => {
52
+ program2.command("implement").description("Implement LLM-powered commands in a CLI tool.").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".').option("-a, --adapter <value>", "SDK adapter to use. Must be an agentic adapter (claude, cursor).", "claude").option("-p, --project-dir <value>", "Path to the target project directory.", ".").option("-n, --dry-run", "Output the prompt context without calling the LLM.", false).option("--model <value>", "Model name override for the selected adapter.").option("-o, --output <value>", "Write the result to a file instead of stdout.").option("--report-format <value>", "Output format for the result.", "text").option("--show-prompt", "Output the constructed prompt without calling the LLM API.", false).action(async (description, opts, cmd) => {
53
53
  if (opts.showPrompt) {
54
54
  const prompt = await handlers2.implement(description, opts, cmd.optsWithGlobals());
55
55
  if (typeof prompt === "string") process.stdout.write(prompt + "\n");
@@ -413,7 +413,7 @@ import { fileURLToPath } from "url";
413
413
  var implementationAuditor = {
414
414
  id: "implementation-auditor",
415
415
  role_name: "Implementation Auditor",
416
- 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 \u2014 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 runTask() or runWorkflow(), NOT adapter.send()\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 passed to runTask/runWorkflow as options\n- Plugin hooks not bypassed\n- No hand-rolled prompt building (use buildTaskPrompt or let runTask do it)\n\n### Layer 3: cli-contracts Compliance\n- cli-contract.yaml has LLM commands with all standard options:\n --adapter, --model, --dry-run, --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- --dry-run returns prompt without LLM call\n- No direct LLM API calls anywhere in the codebase\n",
416
+ 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 \u2014 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 runTask() or runWorkflow(), NOT adapter.send()\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 passed to runTask/runWorkflow as options\n- Plugin hooks not bypassed\n- No hand-rolled prompt building (use buildTaskPrompt or let runTask do it)\n\n### Layer 3: cli-contracts Compliance\n- cli-contract.yaml has LLM commands with all standard options:\n --adapter, --model, --dry-run, --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- --dry-run 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) \u2014 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 / runTask. 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() \u2014 not manually wired Commander commands.\n",
417
417
  mode: "read-only",
418
418
  dispatch_only: false,
419
419
  can_read_artifacts: [],
@@ -440,13 +440,17 @@ var implementationAuditor = {
440
440
  "Verify components/schemas includes AgentAuditResult, AgentFinding, AgentRecommendedAction, and AgentEvidence definitions.",
441
441
  "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).",
442
442
  "Check that --dry-run mode returns the constructed prompt without making any LLM API call.",
443
- "Scan for direct LLM API imports (@anthropic-ai/sdk, openai, @google/genai, @cursor/sdk) used outside of adapter files \u2014 application code must not import these directly."
443
+ "Scan for direct LLM API imports (@anthropic-ai/sdk, openai, @google/genai, @cursor/sdk) used outside of adapter files \u2014 application code must not import these directly.",
444
+ '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).',
445
+ "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.",
446
+ "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.",
447
+ "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 \u2014 not manually created Commander commands."
444
448
  ],
445
449
  constraints: [
446
450
  "This agent is read-only. It must not create, modify, or delete any files. Output is a structured audit report only.",
447
451
  "Findings must include specific file paths, line references where possible, and concrete remediation steps.",
448
452
  "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.",
449
- "Category vocabulary: dsl-structure, dsl-agent, dsl-task, dsl-handoff, dsl-workflow, dsl-guardrail, runtime-adapter, runtime-orchestrator, runtime-registry, runtime-plugin, cli-contract-options, cli-contract-xagent, cli-contract-exits, cli-contract-schema, architecture-modules, architecture-dry-run, architecture-context-builder, architecture-formatter.",
453
+ "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.",
450
454
  "Every finding with severity warning or above must include a recommendation field with a concrete fix.",
451
455
  "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)."
452
456
  ],
@@ -458,7 +462,7 @@ var implementationAuditor = {
458
462
  },
459
463
  {
460
464
  "id": "R-AUDIT-002",
461
- "description": "The audit must check all three layers (DSL, runtime, CLI contract). Skipping a layer or returning partial results is not acceptable.",
465
+ "description": "The audit must check all four layers (DSL, runtime, CLI contract, architecture). Skipping a layer or returning partial results is not acceptable.",
462
466
  "severity": "mandatory"
463
467
  },
464
468
  {
@@ -470,6 +474,16 @@ var implementationAuditor = {
470
474
  "id": "R-AUDIT-004",
471
475
  "description": "The riskLevel in the audit result must be derived from the most severe finding: any critical \u2192 critical, any error \u2192 high, any warning \u2192 medium, info only \u2192 low.",
472
476
  "severity": "mandatory"
477
+ },
478
+ {
479
+ "id": "R-AUDIT-005",
480
+ "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 \u2014 these belong in the DSL agent definition and are injected by buildTaskPrompt / runTask. Context-builder may only contain domain-specific data (file contents, configuration, scan results, project metadata).",
481
+ "severity": "mandatory"
482
+ },
483
+ {
484
+ "id": "R-AUDIT-006",
485
+ "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.",
486
+ "severity": "mandatory"
473
487
  }
474
488
  ],
475
489
  escalation_criteria: [
@@ -594,7 +608,7 @@ var agentRegistry = {
594
608
  // src/builtin-agents/generated/tasks.ts
595
609
  var implementLlmFeature = {
596
610
  id: "implement-llm-feature",
597
- 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 \u2014 existing commands, components/schemas, x-agent usage\n- package.json \u2014 dependencies, scripts, bin entries, type:"module" check\n- tsconfig.json \u2014 module resolution, paths, outDir\n- src/ directory structure \u2014 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- @cursor/sdk (no version constraint)\n\n### Step 3: Create DSL Definitions\n\nCreate directory structure:\n\n dsl/\n \u251C\u2500\u2500 {project}-dsl.yaml\n \u251C\u2500\u2500 agent-runtime.config.yaml\n \u251C\u2500\u2500 agents/\n \u2502 \u2514\u2500\u2500 {agent-name}.yaml\n \u251C\u2500\u2500 tasks.yaml\n \u2514\u2500\u2500 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 "cursor": {\n const m = await import(`${pkg}/adapters/cursor-sdk`);\n return m.CursorSdkAdapter.create({ apiKey: process.env.CURSOR_API_KEY, model: config.model });\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 runAgentTask(\n userRequest: string, taskId: TaskId, config: AgentConfig, options: AgentOptions,\n ): Promise<AgentRunResult> {\n if (options.dryRun) return { taskId, data:null, raw:"", prompt:userRequest, dryRun:true, status:"success", followUpsUsed:0, retriesUsed:0 };\n\n const PKG = "agent-contracts-runtime";\n let runTask;\n try { ({ runTask } = 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 };\n } catch { registries = { agentRegistry:{}, taskRegistry:{}, handoffSchemas:{} }; }\n\n const adapter = await createAdapter(PKG, config.adapter ?? "mock", config);\n const result = await runTask(adapter, taskId, { user_request: userRequest }, { maxFollowUps:3, maxRetries:1, ...registries });\n // map result.outcome to AgentRunResult\n }\n\n**src/agents/context-builder.ts**:\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 sections.push("## Instructions\\n\\n{domain-specific instructions}");\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}(config, target, opts) {\n const context = build{Name}Context(target, config);\n const result = await runAgentTask(context, "{task-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\nRegister in the CLI using Commander or the project\'s existing pattern.\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, cursor, claude, openai, gemini] }\n - name: model\n schema: { type: string }\n - name: dry-run\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: dry-run\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',
611
+ 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 \u2014 existing commands, components/schemas, x-agent usage\n- package.json \u2014 dependencies, scripts, bin entries, type:"module" check\n- tsconfig.json \u2014 module resolution, paths, outDir\n- src/ directory structure \u2014 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- @cursor/sdk (no version constraint)\n\n### Step 3: Create DSL Definitions\n\nCreate directory structure:\n\n dsl/\n \u251C\u2500\u2500 {project}-dsl.yaml\n \u251C\u2500\u2500 agent-runtime.config.yaml\n \u251C\u2500\u2500 agents/\n \u2502 \u2514\u2500\u2500 {agent-name}.yaml\n \u251C\u2500\u2500 tasks.yaml\n \u2514\u2500\u2500 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 "cursor": {\n const m = await import(`${pkg}/adapters/cursor-sdk`);\n return m.CursorSdkAdapter.create({ apiKey: process.env.CURSOR_API_KEY, model: config.model });\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 runAgentTask(\n userRequest: string, taskId: TaskId, config: AgentConfig, options: AgentOptions,\n ): Promise<AgentRunResult> {\n if (options.dryRun) return { taskId, data:null, raw:"", prompt:userRequest, dryRun:true, status:"success", followUpsUsed:0, retriesUsed:0 };\n\n const PKG = "agent-contracts-runtime";\n let runTask;\n try { ({ runTask } = 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 };\n } catch { registries = { agentRegistry:{}, taskRegistry:{}, handoffSchemas:{} }; }\n\n const adapter = await createAdapter(PKG, config.adapter ?? "mock", config);\n const result = await runTask(adapter, taskId, { user_request: userRequest }, { maxFollowUps:3, maxRetries:1, ...registries });\n // map result.outcome 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 / runTask. 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 \u2014 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 runAgentTask(context, "{task-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, cursor, claude, openai, gemini] }\n - name: model\n schema: { type: string }\n - name: dry-run\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: dry-run\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',
598
612
  target_agent: "llm-feature-implementer",
599
613
  allowed_from_agents: [
600
614
  "llm-feature-implementer"
@@ -618,9 +632,11 @@ var implementLlmFeature = {
618
632
  "src/generated/dsl/ contains generated contracts (agentRegistry, taskRegistry, handoffSchemas, workflowRegistry)",
619
633
  "src/agents/orchestrator.ts uses runTask from agent-contracts-runtime (no direct adapter.send calls)",
620
634
  "src/agents/orchestrator.ts dynamic-imports the runtime and adapters with correct exit codes (11, 12)",
635
+ "src/agents/context-builder.ts contains only domain data (file contents, config, scan results) \u2014 no hardcoded agent instructions, evaluation criteria, or output format specs",
621
636
  "src/agents/context-builder.ts caps input at 16KB",
622
637
  "src/agents/formatter.ts implements computeExitCode with the standard exit code mapping",
623
- "src/commands/ has a handler for each new LLM command",
638
+ "src/commands/ has a handler for each new LLM command, passing cwd to AgentConfig",
639
+ "CLI entry point uses cli-contracts' createProgram(handlers, version) with CommandHandlers interface",
624
640
  "cli-contract.yaml has all new commands with --adapter, --model, --dry-run, --fail-on, --output, --report-format options",
625
641
  "cli-contract.yaml has x-agent metadata on each new command (riskLevel, safeDryRunOption, expectedDurationMs)",
626
642
  "components/schemas includes AgentAuditResult and related schemas",
@@ -631,7 +647,7 @@ var implementLlmFeature = {
631
647
  };
632
648
  var auditDsl = {
633
649
  id: "audit-dsl",
634
- description: "Audit the DSL layer of an LLM command integration.\n\nVerify these files exist and are well-formed:\n- dsl/{project}-dsl.yaml \u2014 must have version:1, system:{id,name},\n agents/tasks/handoff_types via $ref\n- dsl/agents/*.yaml \u2014 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 \u2014 target_agent, workflow, result_handoff all\n cross-reference valid IDs\n- dsl/handoff-types.yaml \u2014 version:1, schema with JSON Schema,\n result types follow AgentAuditResult shape\n- dsl/agent-runtime.config.yaml \u2014 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- 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\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",
650
+ description: "Audit the DSL layer of an LLM command integration.\n\nVerify these files exist and are well-formed:\n- dsl/{project}-dsl.yaml \u2014 must have version:1, system:{id,name},\n agents/tasks/handoff_types via $ref\n- dsl/agents/*.yaml \u2014 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 \u2014 target_agent, workflow, result_handoff all\n cross-reference valid IDs\n- dsl/handoff-types.yaml \u2014 version:1, schema with JSON Schema,\n result types follow AgentAuditResult shape\n- dsl/agent-runtime.config.yaml \u2014 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 \u2014 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 \u2014\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",
635
651
  target_agent: "implementation-auditor",
636
652
  allowed_from_agents: [
637
653
  "implementation-auditor"
@@ -643,18 +659,20 @@ var auditDsl = {
643
659
  responsibilities: [
644
660
  "Check all DSL files for structural correctness",
645
661
  "Validate cross-references (agent\u2194task\u2194workflow\u2194handoff)",
646
- "Verify guardrails and guardrail_policies"
662
+ "Verify guardrails and guardrail_policies",
663
+ "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)"
647
664
  ],
648
665
  completion_criteria: [
649
666
  "Every dsl/* file checked for required fields",
650
667
  "Cross-references validated",
668
+ "Agent mode is consistent with stated purpose and responsibilities",
651
669
  "Findings use dsl-* category vocabulary"
652
670
  ],
653
671
  optional: false
654
672
  };
655
673
  var auditRuntime = {
656
674
  id: "audit-runtime",
657
- 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- runTask/runWorkflow not imported from agent-contracts-runtime\n\nERROR violations (category: runtime-registry):\n- Generated registries not imported from src/generated/dsl/\n- Registries not passed to runTask/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- CursorSdkAdapter created with constructor (must use static .create())\n\nWARNING violations (category: runtime-plugin):\n- Plugin hooks explicitly bypassed or ignored\n\nCategory vocabulary: runtime-orchestrator, runtime-registry,\nruntime-adapter, runtime-plugin.\n\nOutput a partial audit-result with findings only from the runtime layer.\n",
675
+ 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- runTask/runWorkflow not imported from agent-contracts-runtime\n\nERROR violations (category: runtime-registry):\n- Generated registries not imported from src/generated/dsl/\n- Registries not passed to runTask/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- CursorSdkAdapter created with constructor (must use static .create())\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 \u2014 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 \u2192 context-builder \u2192 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",
658
676
  target_agent: "implementation-auditor",
659
677
  allowed_from_agents: [
660
678
  "implementation-auditor"
@@ -666,12 +684,14 @@ var auditRuntime = {
666
684
  responsibilities: [
667
685
  "Scan orchestrator code for direct adapter usage",
668
686
  "Verify registry imports and passing",
669
- "Check adapter creation patterns and exit codes"
687
+ "Check adapter creation patterns and exit codes",
688
+ "Verify cli-contracts handler wiring (CommandHandlers + createProgram used in CLI entry point)"
670
689
  ],
671
690
  completion_criteria: [
672
691
  "All orchestrator files scanned for adapter.send / adapter.followUp",
673
692
  "Registry usage verified",
674
- "Exit code 11/12 patterns checked"
693
+ "Exit code 11/12 patterns checked",
694
+ "cli-contracts handler integration verified (CommandHandlers interface used, createProgram called)"
675
695
  ],
676
696
  optional: false
677
697
  };
@@ -702,7 +722,87 @@ var auditCliContract = {
702
722
  };
703
723
  var auditArchitecture = {
704
724
  id: "audit-architecture",
705
- 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- --dry-run path returns the constructed prompt without calling the adapter\n- buildTaskPrompt is used (not a placeholder string)\n\nVerify patterns (category: architecture-context-builder):\n- Context builder has size cap (16KB or similar)\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- @cursor/sdk imported outside adapters\n\nCategory vocabulary: architecture-modules, architecture-dry-run,\narchitecture-context-builder, architecture-formatter.\n\nOutput a partial audit-result with findings only from the architecture layer.\n",
725
+ description: `Audit the architecture and module structure of an LLM command integration.
726
+
727
+ Verify module structure (category: architecture-modules):
728
+ - src/agents/types.ts exists with TaskId, AgentConfig, AgentOptions, AgentRunResult
729
+ - src/agents/orchestrator.ts exists
730
+ - src/agents/context-builder.ts exists
731
+ - src/agents/formatter.ts exists with computeExitCode
732
+
733
+ Verify behavior (category: architecture-dry-run):
734
+ - --dry-run path returns the constructed prompt without calling the adapter
735
+ - buildTaskPrompt is used (not a placeholder string)
736
+
737
+ CRITICAL: context-builder SSoT violations (category: architecture-context-builder):
738
+
739
+ The context-builder's role is to assemble domain-specific DATA (file
740
+ contents, configuration, scan results, schema context) into the user
741
+ prompt. Agent INSTRUCTIONS (how to evaluate, what rules to apply,
742
+ what patterns to look for, output format) belong in the DSL agent
743
+ definition and are injected by buildTaskPrompt / runTask.
744
+
745
+ Detect any of the following in context-builder source code:
746
+ - Sections titled "## Instructions", "## Required Patterns",
747
+ "## Audit Instructions", "## Output Format", or similar
748
+ behavioral directive headings \u2014 these are agent instructions
749
+ that belong in DSL (agent purpose, responsibilities, constraints,
750
+ rules) and must not be hardcoded in context-builder
751
+ - Output format specifications (field lists, JSON/YAML schema
752
+ descriptions, example output structures) \u2014 buildTaskPrompt
753
+ already generates "Required Output Format" from the handoff
754
+ Zod schema; duplicating this in context-builder causes conflicts
755
+ - Domain-specific evaluation criteria, checklists, anti-pattern
756
+ definitions, rule sets, or API reference material \u2014 these
757
+ belong in the DSL agent definition's purpose field
758
+ - Any string that duplicates or paraphrases content already
759
+ present in the DSL agent's purpose, responsibilities,
760
+ constraints, or rules fields
761
+
762
+ What IS allowed in context-builder:
763
+ - File contents read from disk (migration SQL, schema, config)
764
+ - Project metadata (dialect, directories, file lists)
765
+ - Deterministic pre-analysis results (lint violations, scan output)
766
+ - Operational context (target path, cwd, timestamp)
767
+ - Brief task framing ("# Migration Safety Audit Request")
768
+
769
+ ERROR: mode-purpose coherence (category: architecture-agent-coherence):
770
+ - DSL agent with mode: read-only has purpose or responsibilities
771
+ that describe file writing, editing, creation, or modification
772
+ - DSL agent with mode: read-write but no cwd propagated to adapter
773
+ \u2014 the agent's file tools won't operate in the project directory
774
+ - Command handler doesn't pass cwd to AgentConfig when using an
775
+ agentic adapter (claude, cursor)
776
+
777
+ ERROR: adapter cwd propagation (category: architecture-adapter-cwd):
778
+ - AgentConfig type has no cwd field
779
+ - Command handlers don't set config.cwd = process.cwd() or
780
+ resolve(projectDir)
781
+ - createAdapter doesn't pass cwd to adapter constructor/factory
782
+ - Agentic adapters (claude, cursor) instantiated without cwd \u2014
783
+ their file tools will operate in an undefined directory
784
+
785
+ ERROR: cli-contracts handler wiring (category: architecture-handler):
786
+ - Project has cli-contracts generated code (src/generated/program.ts
787
+ or src/generated/cli/program.ts with CommandHandlers) but CLI
788
+ entry point manually creates Commander commands instead of
789
+ calling createProgram(handlers, version)
790
+ - Command handlers bypass the generated CommandHandlers interface
791
+
792
+ Scan for direct SDK imports (category: architecture-modules):
793
+ - @anthropic-ai/sdk or @anthropic-ai/claude-agent-sdk imported
794
+ outside src/agents/orchestrator.ts or adapter files
795
+ - openai or @openai/agents imported outside adapters
796
+ - @google/genai imported outside adapters
797
+ - @cursor/sdk imported outside adapters
798
+
799
+ Category vocabulary: architecture-modules, architecture-dry-run,
800
+ architecture-context-builder, architecture-agent-coherence,
801
+ architecture-adapter-cwd, architecture-handler,
802
+ architecture-formatter.
803
+
804
+ Output a partial audit-result with findings only from the architecture layer.
805
+ `,
706
806
  target_agent: "implementation-auditor",
707
807
  allowed_from_agents: [
708
808
  "implementation-auditor"
@@ -714,12 +814,19 @@ var auditArchitecture = {
714
814
  responsibilities: [
715
815
  "Verify module structure",
716
816
  "Check dry-run behavior",
717
- "Validate context size cap",
817
+ "Audit context-builder for SSoT violations (hardcoded instructions, output format specs, domain rules that belong in DSL)",
818
+ "Check mode-purpose coherence across DSL definitions and runtime code",
819
+ "Verify cwd propagation from command handler through adapter config",
820
+ "Verify cli-contracts handler wiring (CommandHandlers + createProgram)",
718
821
  "Scan for direct SDK imports"
719
822
  ],
720
823
  completion_criteria: [
721
824
  "Module structure verified",
722
825
  "Dry-run behavior confirmed",
826
+ "Context-builder contains only domain data, not agent instructions",
827
+ "Agent mode is consistent with purpose and tool usage",
828
+ "cwd is propagated to agentic adapters",
829
+ "cli-contracts handler integration verified",
723
830
  "No direct SDK imports outside adapter files"
724
831
  ],
725
832
  optional: false
@@ -1347,7 +1454,7 @@ async function loadGeneratedContracts(configPath) {
1347
1454
  guardrailHooks
1348
1455
  };
1349
1456
  }
1350
- async function createAdapter(adapterName, guardrailHooks) {
1457
+ async function createAdapter(adapterName, guardrailHooks, cwd) {
1351
1458
  switch (adapterName) {
1352
1459
  case "mock": {
1353
1460
  const { MockAdapter } = await import("../adapters/mock.js");
@@ -1355,7 +1462,7 @@ async function createAdapter(adapterName, guardrailHooks) {
1355
1462
  }
1356
1463
  case "claude": {
1357
1464
  const { ClaudeAgentSdkAdapter } = await import("../adapters/claude-agent-sdk.js");
1358
- return new ClaudeAgentSdkAdapter({ guardrailHooks });
1465
+ return new ClaudeAgentSdkAdapter({ cwd, guardrailHooks });
1359
1466
  }
1360
1467
  case "gemini": {
1361
1468
  const { GeminiSdkAdapter } = await import("../adapters/gemini-sdk.js");
@@ -1367,7 +1474,7 @@ async function createAdapter(adapterName, guardrailHooks) {
1367
1474
  if (!apiKey) {
1368
1475
  throw new Error("CURSOR_API_KEY environment variable is required for the cursor adapter");
1369
1476
  }
1370
- return CursorSdkAdapter.create({ apiKey, guardrailHooks });
1477
+ return CursorSdkAdapter.create({ apiKey, cwd, guardrailHooks });
1371
1478
  }
1372
1479
  default:
1373
1480
  throw new Error(`Unknown adapter: ${adapterName}. Available: mock, claude, gemini, cursor`);
@@ -1434,27 +1541,28 @@ var handlers = {
1434
1541
  resolvedWorkflowId = parsed.workflow;
1435
1542
  if (!resolvedWorkflowId) {
1436
1543
  console.error(`Error: invocation file "${options.file}" must contain a "workflow" field.`);
1437
- process.exit(1);
1544
+ process.exit(3);
1438
1545
  }
1439
1546
  fileInvocation = {
1440
1547
  workflow: resolvedWorkflowId,
1441
1548
  user_request: parsed.user_request,
1442
1549
  handoff: parsed.handoff,
1443
- runtime: parsed.runtime
1550
+ runtime: parsed.runtime,
1551
+ context: parsed.context
1444
1552
  };
1445
1553
  resolvedUserRequest = fileInvocation.user_request ?? "";
1446
1554
  } catch (err) {
1447
1555
  console.error(`Failed to read invocation file: ${err.message}`);
1448
- process.exit(1);
1556
+ process.exit(3);
1449
1557
  }
1450
1558
  }
1451
1559
  if (!resolvedWorkflowId) {
1452
1560
  console.error("Error: workflow-id is required (provide as argument or via --file)");
1453
- process.exit(1);
1561
+ process.exit(3);
1454
1562
  }
1455
1563
  if (!fileInvocation && !resolvedUserRequest) {
1456
1564
  console.error("Error: user-request is required (provide as argument or via --file)");
1457
- process.exit(1);
1565
+ process.exit(3);
1458
1566
  }
1459
1567
  const configPath = globalOpts.config ?? "./agent-runtime.config.yaml";
1460
1568
  const fresh = await checkFreshness(configPath);
@@ -1484,13 +1592,14 @@ var handlers = {
1484
1592
  if (!contracts.workflowRegistry[resolvedWorkflowId]) {
1485
1593
  console.error(`Unknown workflow: ${resolvedWorkflowId}`);
1486
1594
  console.error(`Available workflows: ${Object.keys(contracts.workflowRegistry).join(", ")}`);
1487
- process.exit(1);
1595
+ process.exit(3);
1488
1596
  return;
1489
1597
  }
1490
1598
  const adapterName = options.adapter ?? "mock";
1599
+ const adapterCwd = fileInvocation?.context?.cwd ?? process.cwd();
1491
1600
  let adapter;
1492
1601
  try {
1493
- adapter = await createAdapter(adapterName, contracts.guardrailHooks);
1602
+ adapter = await createAdapter(adapterName, contracts.guardrailHooks, adapterCwd);
1494
1603
  } catch (err) {
1495
1604
  console.error(err.message);
1496
1605
  process.exit(12);
@@ -1668,7 +1777,6 @@ var handlers = {
1668
1777
  projectDir: options.projectDir ?? ".",
1669
1778
  dryRun: options.dryRun ?? false,
1670
1779
  model: options.model,
1671
- failOn: options.failOn ?? "error",
1672
1780
  reportFormat: options.reportFormat ?? "text"
1673
1781
  });
1674
1782
  if (result.status === "failed") {