agent-contracts-runtime 0.31.4 → 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,16 +4,16 @@ 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,
11
11
  loadConfig
12
- } from "../chunk-IAIG5VCJ.js";
12
+ } from "../chunk-W5YWUFAH.js";
13
13
 
14
14
  // src/cli/index.ts
15
- import { existsSync as existsSync3, readFileSync } from "fs";
16
- import { resolve as resolve2 } from "path";
15
+ import { existsSync as existsSync5, readFileSync as readFileSync2, writeFileSync } from "fs";
16
+ import { resolve as resolve4 } from "path";
17
17
  import { register } from "tsx/esm/api";
18
18
 
19
19
  // src/generated/cli/program.ts
@@ -49,6 +49,22 @@ 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("-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
+ if (opts.showPrompt) {
54
+ const prompt = await handlers2.implement(description, opts, cmd.optsWithGlobals());
55
+ if (typeof prompt === "string") process.stdout.write(prompt + "\n");
56
+ return;
57
+ }
58
+ await handlers2.implement(description, opts, cmd.optsWithGlobals());
59
+ });
60
+ program2.command("audit-implementation").description("Audit an LLM command integration for pattern conformance.").argument("[project-dir]", "Path to the project directory to audit. Defaults to current directory.").option("-a, --adapter <value>", "SDK adapter to use for the audit agent.", "claude").option("--focus <value>", "Limit audit to a specific layer. Defaults to all layers.", "all").option("-n, --dry-run", "Output the prompt context without calling the LLM.", false).option("--fail-on <value>", "Minimum finding severity that causes a non-zero exit.", "error").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 audit report.", "text").option("--show-prompt", "Output the constructed prompt without calling the LLM API.", false).action(async (projectDir, opts, cmd) => {
61
+ if (opts.showPrompt) {
62
+ const prompt = await handlers2.auditImplementation(projectDir, opts, cmd.optsWithGlobals());
63
+ if (typeof prompt === "string") process.stdout.write(prompt + "\n");
64
+ return;
65
+ }
66
+ await handlers2.auditImplementation(projectDir, opts, cmd.optsWithGlobals());
67
+ });
52
68
  program2.command("doctor").description("Verify configuration, generated files, and SDK connectivity.").action(async (opts, cmd) => {
53
69
  await handlers2.doctor({}, cmd.optsWithGlobals());
54
70
  });
@@ -388,17 +404,1029 @@ async function runInit(options) {
388
404
  return { files_created };
389
405
  }
390
406
 
407
+ // src/lib/implement.ts
408
+ import { existsSync as existsSync3, readFileSync } from "fs";
409
+ import { resolve as resolve2, join as join3 } from "path";
410
+ import { fileURLToPath } from "url";
411
+
412
+ // src/builtin-agents/generated/agents.ts
413
+ var implementationAuditor = {
414
+ id: "implementation-auditor",
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\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
+ mode: "read-only",
418
+ dispatch_only: false,
419
+ can_read_artifacts: [],
420
+ can_write_artifacts: [],
421
+ can_execute_tools: [],
422
+ can_invoke_agents: [],
423
+ can_return_handoffs: [
424
+ "audit-result"
425
+ ],
426
+ responsibilities: [
427
+ "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.",
428
+ "Check that the main DSL entry has version:1, a system block with id and name, and uses $ref for agents/tasks/handoff_types.",
429
+ "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.",
430
+ "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.",
431
+ "Verify handoff type schemas conform to AgentAuditResult shape when applicable (summary, riskLevel, findings[], recommendedActions[], metadata). Check $ref usage and SSoT comments for inlined schemas.",
432
+ "Check that guardrails and guardrail_policies are defined, and that output-schema-conformance is included.",
433
+ "Scan src/agents/orchestrator.ts for: (1) imports from agent-contracts-runtime (not custom SDK wrappers), (2) usage of runTask() or runWorkflow() (not adapter.send/sendExecution), (3) dynamic import pattern with exit code 11 for missing runtime and exit code 12 for adapter errors, (4) generated registries imported and passed to runTask/runWorkflow.",
434
+ "Verify no file in the project calls adapter.send(), adapter.followUp(), or adapter.sendExecution() directly \u2014 all LLM invocations must go through the runtime's task/workflow runner.",
435
+ "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.",
436
+ "Verify adapter creation uses the correct constructors: CursorSdkAdapter.create() (async static), ClaudeAgentSdkAdapter constructor, OpenAIAgentsSdkAdapter constructor, etc.",
437
+ "Check cli-contract.yaml for each LLM command: all six standard options present (--adapter, --model, --dry-run, --fail-on, --output, --report-format). Verify --report-format is used (not --format).",
438
+ 'Verify x-agent metadata on each LLM command: riskLevel, safeDryRunOption (must be "dry-run"), expectedDurationMs. Flag high-risk commands without requiresConfirmation.',
439
+ "Check exit code definitions: 0 (success), 1 (error), 3 (validation), 10 (findings), 11 (runtime missing), 12 (adapter error).",
440
+ "Verify components/schemas includes AgentAuditResult, AgentFinding, AgentRecommendedAction, and AgentEvidence definitions.",
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
+ "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.",
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."
448
+ ],
449
+ constraints: [
450
+ "This agent is read-only. It must not create, modify, or delete any files. Output is a structured audit report only.",
451
+ "Findings must include specific file paths, line references where possible, and concrete remediation steps.",
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.",
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.",
454
+ "Every finding with severity warning or above must include a recommendation field with a concrete fix.",
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)."
456
+ ],
457
+ rules: [
458
+ {
459
+ "id": "R-AUDIT-001",
460
+ "description": "Every finding must specify target (file path) and category (from the defined category vocabulary). Findings without a target are not actionable.",
461
+ "severity": "mandatory"
462
+ },
463
+ {
464
+ "id": "R-AUDIT-002",
465
+ "description": "The audit must check all four layers (DSL, runtime, CLI contract, architecture). Skipping a layer or returning partial results is not acceptable.",
466
+ "severity": "mandatory"
467
+ },
468
+ {
469
+ "id": "R-AUDIT-003",
470
+ "description": "Critical findings must be surfaced for: (1) direct adapter.send() calls bypassing runTask, (2) custom adapter classes not from agent-contracts-runtime, (3) missing generated registries in runTask/runWorkflow calls.",
471
+ "severity": "mandatory"
472
+ },
473
+ {
474
+ "id": "R-AUDIT-004",
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.",
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"
487
+ }
488
+ ],
489
+ escalation_criteria: [
490
+ {
491
+ "condition": "Target project has no LLM command integration to audit",
492
+ "action": "stop_and_report"
493
+ },
494
+ {
495
+ "condition": "Target project uses a completely different integration pattern (not agent-contracts stack)",
496
+ "action": "stop_and_report"
497
+ }
498
+ ]
499
+ };
500
+ var llmFeatureImplementer = {
501
+ id: "llm-feature-implementer",
502
+ role_name: "LLM Feature Implementer",
503
+ 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** \u2014 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** \u2014 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** \u2014 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',
504
+ mode: "read-write",
505
+ dispatch_only: false,
506
+ can_read_artifacts: [],
507
+ can_write_artifacts: [],
508
+ can_execute_tools: [],
509
+ can_invoke_agents: [],
510
+ can_return_handoffs: [
511
+ "implementation-result"
512
+ ],
513
+ responsibilities: [
514
+ "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.",
515
+ "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).",
516
+ "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.",
517
+ "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.",
518
+ "Define tasks with: description, target_agent, allowed_from_agents, workflow (must match a workflow ID), invocation_handoff, result_handoff, responsibilities, completion_criteria.",
519
+ "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.",
520
+ "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.",
521
+ "Define guardrails (output-schema-conformance, domain-specific safety) and guardrail_policies grouping them with severity and action.",
522
+ "Create agent-runtime.config.yaml: dsl points to main DSL file, generated_dir points to src/generated/dsl.",
523
+ "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).",
524
+ "Implement src/agents/orchestrator.ts: createAdapter() with dynamic imports from agent-contracts-runtime/adapters/*, runAgentTask() that imports runTask from agent-contracts-runtime, loads generated registries from src/generated/dsl/index.js, and calls runTask with registries.",
525
+ "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.",
526
+ "Implement src/agents/formatter.ts: computeExitCode() mapping findings to exit codes via --fail-on threshold, formatResultText() with severity icons, formatResultJson() for structured output.",
527
+ "Create src/commands/{command}.ts handlers: load config, call context builder, call runAgentTask, format output, compute exit code.",
528
+ "Update cli-contract.yaml: add command definitions with standard LLM options (--adapter, --model, --dry-run, --fail-on, --output, --report-format), exit codes (0, 1, 3, 10, 11, 12), x-agent metadata, and register AgentAuditResult/AgentFinding/AgentRecommendedAction in components/schemas.",
529
+ '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.'
530
+ ],
531
+ constraints: [
532
+ "NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, CursorSdkAdapter from agent-contracts-runtime/adapters/cursor-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.",
533
+ "NEVER call adapter.send() or adapter.sendExecution() directly. All LLM invocations must go through runTask() or runWorkflow() imported from agent-contracts-runtime. These functions handle prompt building, handoff validation, retry/followUp, and plugin hooks.",
534
+ '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 { runTask } = await import(RUNTIME); } catch { exit(11); }',
535
+ "LLM commands use --report-format (json|text|yaml) for output format. --format is reserved for deterministic commands. Never mix them.",
536
+ "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.).",
537
+ "Standard LLM command options (all must be present): --adapter <name> (mock|cursor|claude|openai|gemini, default varies), --model <name> (optional override), --dry-run (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).",
538
+ "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).",
539
+ "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).",
540
+ "AgentRecommendedAction shape: kind (run_command|edit_file|review|confirm| block|ignore), title (required), command?, target?, rationale?.",
541
+ "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.",
542
+ "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.",
543
+ "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}).",
544
+ "runTask signature: runTask(adapter: SdkAdapter, taskId: string, context: TaskContext, options?: TaskRunOptions & { agentRegistry?, taskRegistry?, handoffSchemas?, retry? }): Promise<TaskRunResult>. TaskContext: { user_request, prior_context?, relevant_paths?, acceptance_criteria?, handoff_input?, variables? }. TaskRunResult: { outcome: TaskOutcome, follow_ups_used, retries_used }. TaskOutcome: success {data,raw} | validation_error {errors,raw} | escalation {reason,raw} | error {message}.",
545
+ "runWorkflow overloads: (1) runWorkflow(adapter, workflowId, options, registries?) \u2014 legacy. (2) runWorkflow(adapter, invocation, registries?) \u2014 structured. 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? }.",
546
+ "Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), CursorSdkAdapter.create({apiKey, model?, cwd?, guardrailHooks?}) \u2014 async static, ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?}), GeminiSdkAdapter({apiKey?, model?, systemInstruction?, temperature?, maxOutputTokens?, guardrailHooks?}).",
547
+ 'Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from "../generated/dsl/index.js". Pass these as options to runTask/runWorkflow: { agentRegistry, taskRegistry, handoffSchemas } for runTask; { workflowRegistry, taskRegistry, agentRegistry, handoffSchemas } for runWorkflow.',
548
+ "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).",
549
+ "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 (dry-run), expectedDurationMs (120000 typical), retryableExitCodes ([1, 12])."
550
+ ],
551
+ rules: [
552
+ {
553
+ "id": "R-IMPL-001",
554
+ "description": "Import SDK adapters exclusively from agent-contracts-runtime/adapters/*. Never create adapter classes, wrapper functions, or API client code.",
555
+ "severity": "mandatory"
556
+ },
557
+ {
558
+ "id": "R-IMPL-002",
559
+ "description": "All LLM invocations must use runTask() or runWorkflow() from agent-contracts-runtime. Never call adapter.send(), adapter.followUp(), or adapter.sendExecution() directly. The runtime handles prompt building, schema validation, retry, followUp, and plugin hooks.",
560
+ "severity": "mandatory"
561
+ },
562
+ {
563
+ "id": "R-IMPL-003",
564
+ "description": "Every LLM command in cli-contract.yaml must have x-agent metadata with at minimum: riskLevel, safeDryRunOption, expectedDurationMs.",
565
+ "severity": "mandatory"
566
+ },
567
+ {
568
+ "id": "R-IMPL-004",
569
+ "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.",
570
+ "severity": "mandatory"
571
+ },
572
+ {
573
+ "id": "R-IMPL-005",
574
+ "description": "Context builder must cap prompt input at 16KB. Filter large contexts (schema dumps, lint output, etc.) to relevant portions before inclusion.",
575
+ "severity": "recommended"
576
+ },
577
+ {
578
+ "id": "R-IMPL-006",
579
+ "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.',
580
+ "severity": "mandatory"
581
+ },
582
+ {
583
+ "id": "R-IMPL-007",
584
+ "description": "Generated DSL contracts must be imported from src/generated/dsl/index.js and passed as registries to runTask/runWorkflow. Never hard-code agent definitions, task definitions, or handoff schemas in application code.",
585
+ "severity": "mandatory"
586
+ }
587
+ ],
588
+ escalation_criteria: [
589
+ {
590
+ "condition": "Target project has no cli-contract.yaml and user did not request creating one",
591
+ "action": "stop_and_report"
592
+ },
593
+ {
594
+ "condition": "Target project is not a TypeScript / Node.js stack",
595
+ "action": "stop_and_report"
596
+ },
597
+ {
598
+ "condition": "Target project already has src/agents/ with a different integration pattern",
599
+ "action": "stop_and_report"
600
+ }
601
+ ]
602
+ };
603
+ var agentRegistry = {
604
+ "implementation-auditor": implementationAuditor,
605
+ "llm-feature-implementer": llmFeatureImplementer
606
+ };
607
+
608
+ // src/builtin-agents/generated/tasks.ts
609
+ var implementLlmFeature = {
610
+ id: "implement-llm-feature",
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',
612
+ target_agent: "llm-feature-implementer",
613
+ allowed_from_agents: [
614
+ "llm-feature-implementer"
615
+ ],
616
+ workflow: "implement-llm-feature",
617
+ invocation_handoff: "implement-request",
618
+ result_handoff: "implementation-result",
619
+ input_artifacts: [],
620
+ responsibilities: [
621
+ "Analyze the target project and determine the right LLM commands to add",
622
+ "Create all DSL definition files with correct cross-references",
623
+ "Generate TypeScript contracts via agent-runtime generate",
624
+ "Implement the complete src/agents/ module following the exact patterns",
625
+ "Create CLI command handlers integrating with the project's existing CLI structure",
626
+ "Update cli-contract.yaml with proper x-agent metadata and component schemas",
627
+ "Ensure the implementation compiles and --dry-run mode works"
628
+ ],
629
+ completion_criteria: [
630
+ "dsl/ directory contains valid DSL definitions that pass agent-runtime generate",
631
+ "agent-runtime.config.yaml points to the DSL with correct generated_dir",
632
+ "src/generated/dsl/ contains generated contracts (agentRegistry, taskRegistry, handoffSchemas, workflowRegistry)",
633
+ "src/agents/orchestrator.ts uses runTask from agent-contracts-runtime (no direct adapter.send calls)",
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",
636
+ "src/agents/context-builder.ts caps input at 16KB",
637
+ "src/agents/formatter.ts implements computeExitCode with the standard exit code mapping",
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",
640
+ "cli-contract.yaml has all new commands with --adapter, --model, --dry-run, --fail-on, --output, --report-format options",
641
+ "cli-contract.yaml has x-agent metadata on each new command (riskLevel, safeDryRunOption, expectedDurationMs)",
642
+ "components/schemas includes AgentAuditResult and related schemas",
643
+ "All generated TypeScript compiles without type errors",
644
+ "--dry-run returns the constructed prompt without calling the LLM"
645
+ ],
646
+ optional: false
647
+ };
648
+ var auditDsl = {
649
+ id: "audit-dsl",
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",
651
+ target_agent: "implementation-auditor",
652
+ allowed_from_agents: [
653
+ "implementation-auditor"
654
+ ],
655
+ workflow: "audit-implementation",
656
+ invocation_handoff: "audit-request",
657
+ result_handoff: "audit-result",
658
+ input_artifacts: [],
659
+ responsibilities: [
660
+ "Check all DSL files for structural correctness",
661
+ "Validate cross-references (agent\u2194task\u2194workflow\u2194handoff)",
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)"
664
+ ],
665
+ completion_criteria: [
666
+ "Every dsl/* file checked for required fields",
667
+ "Cross-references validated",
668
+ "Agent mode is consistent with stated purpose and responsibilities",
669
+ "Findings use dsl-* category vocabulary"
670
+ ],
671
+ optional: false
672
+ };
673
+ var auditRuntime = {
674
+ id: "audit-runtime",
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",
676
+ target_agent: "implementation-auditor",
677
+ allowed_from_agents: [
678
+ "implementation-auditor"
679
+ ],
680
+ workflow: "audit-implementation",
681
+ invocation_handoff: "audit-request",
682
+ result_handoff: "audit-result",
683
+ input_artifacts: [],
684
+ responsibilities: [
685
+ "Scan orchestrator code for direct adapter usage",
686
+ "Verify registry imports and passing",
687
+ "Check adapter creation patterns and exit codes",
688
+ "Verify cli-contracts handler wiring (CommandHandlers + createProgram used in CLI entry point)"
689
+ ],
690
+ completion_criteria: [
691
+ "All orchestrator files scanned for adapter.send / adapter.followUp",
692
+ "Registry usage verified",
693
+ "Exit code 11/12 patterns checked",
694
+ "cli-contracts handler integration verified (CommandHandlers interface used, createProgram called)"
695
+ ],
696
+ optional: false
697
+ };
698
+ var auditCliContract = {
699
+ id: "audit-cli-contract",
700
+ 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, --dry-run, --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",
701
+ target_agent: "implementation-auditor",
702
+ allowed_from_agents: [
703
+ "implementation-auditor"
704
+ ],
705
+ workflow: "audit-implementation",
706
+ invocation_handoff: "audit-request",
707
+ result_handoff: "audit-result",
708
+ input_artifacts: [],
709
+ responsibilities: [
710
+ "Check each LLM command for standard options",
711
+ "Verify x-agent metadata fields and casing",
712
+ "Validate exit code definitions",
713
+ "Check components/schemas for canonical types"
714
+ ],
715
+ completion_criteria: [
716
+ "Every LLM command checked for all 6 standard options",
717
+ "x-agent metadata validated on every LLM command",
718
+ "Exit codes verified against convention",
719
+ "Schema completeness checked"
720
+ ],
721
+ optional: false
722
+ };
723
+ var auditArchitecture = {
724
+ id: "audit-architecture",
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
+ `,
806
+ target_agent: "implementation-auditor",
807
+ allowed_from_agents: [
808
+ "implementation-auditor"
809
+ ],
810
+ workflow: "audit-implementation",
811
+ invocation_handoff: "audit-request",
812
+ result_handoff: "audit-result",
813
+ input_artifacts: [],
814
+ responsibilities: [
815
+ "Verify module structure",
816
+ "Check dry-run behavior",
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)",
821
+ "Scan for direct SDK imports"
822
+ ],
823
+ completion_criteria: [
824
+ "Module structure verified",
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",
830
+ "No direct SDK imports outside adapter files"
831
+ ],
832
+ optional: false
833
+ };
834
+ var auditMerge = {
835
+ id: "audit-merge",
836
+ 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 \u2192 critical, any error \u2192 high,\n any warning \u2192 medium, info only \u2192 low\n- Merge recommendedActions from all layers, deduplicate by title\n- Set metadata: { tool: "agent-runtime", command: "audit-implementation" }\n',
837
+ target_agent: "implementation-auditor",
838
+ allowed_from_agents: [
839
+ "implementation-auditor"
840
+ ],
841
+ workflow: "audit-implementation",
842
+ invocation_handoff: "audit-request",
843
+ result_handoff: "audit-result",
844
+ input_artifacts: [],
845
+ responsibilities: [
846
+ "Parse prior_context JSON from each layer audit step",
847
+ "Merge and deduplicate findings",
848
+ "Derive overall riskLevel",
849
+ "Produce a single coherent summary paragraph"
850
+ ],
851
+ completion_criteria: [
852
+ "All findings from all layers included",
853
+ "No duplicate findings",
854
+ "riskLevel correctly derived from worst finding",
855
+ "Summary paragraph covers all audited layers"
856
+ ],
857
+ optional: false
858
+ };
859
+ var taskRegistry = {
860
+ "implement-llm-feature": implementLlmFeature,
861
+ "audit-dsl": auditDsl,
862
+ "audit-runtime": auditRuntime,
863
+ "audit-cli-contract": auditCliContract,
864
+ "audit-architecture": auditArchitecture,
865
+ "audit-merge": auditMerge
866
+ };
867
+
868
+ // src/builtin-agents/generated/handoffs.ts
869
+ import { z } from "zod";
870
+ var ImplementRequestSchema = z.object({
871
+ description: z.string(),
872
+ project_dir: z.string(),
873
+ reference_doc: z.string().optional()
874
+ });
875
+ var AuditRequestSchema = z.object({
876
+ project_dir: z.string(),
877
+ focus: z.enum(["all", "dsl", "runtime", "cli-contract", "architecture"]).optional()
878
+ });
879
+ var AuditResultSchema = z.object({
880
+ summary: z.string(),
881
+ riskLevel: z.enum(["low", "medium", "high", "critical"]),
882
+ findings: z.array(z.object({
883
+ id: z.string().optional(),
884
+ severity: z.enum(["info", "warning", "error", "critical"]),
885
+ category: z.string(),
886
+ target: z.string().optional(),
887
+ location: z.string().optional(),
888
+ message: z.string(),
889
+ recommendation: z.string().optional(),
890
+ confidence: z.number().optional()
891
+ })),
892
+ recommendedActions: z.array(z.object({
893
+ kind: z.enum(["run_command", "edit_file", "review", "confirm", "block", "ignore"]),
894
+ title: z.string(),
895
+ command: z.string().optional(),
896
+ target: z.string().optional(),
897
+ rationale: z.string().optional()
898
+ })).optional(),
899
+ metadata: z.object({
900
+ tool: z.string().optional(),
901
+ command: z.string().optional(),
902
+ version: z.string().optional(),
903
+ generatedAt: z.string().optional(),
904
+ adapter: z.string().optional(),
905
+ model: z.string().optional()
906
+ }).optional()
907
+ });
908
+ var ImplementationResultSchema = z.object({
909
+ files_created: z.array(z.string()),
910
+ files_modified: z.array(z.string()),
911
+ summary: z.string(),
912
+ commands_added: z.array(z.object({
913
+ name: z.string(),
914
+ type: z.enum(["audit", "propose", "explain"]),
915
+ description: z.string().optional()
916
+ })).optional(),
917
+ next_steps: z.array(z.string()).optional()
918
+ });
919
+ var handoffSchemas = {
920
+ "implement-request": ImplementRequestSchema,
921
+ "audit-request": AuditRequestSchema,
922
+ "audit-result": AuditResultSchema,
923
+ "implementation-result": ImplementationResultSchema
924
+ };
925
+
926
+ // src/builtin-agents/generated/workflows.ts
927
+ var implementLlmFeature2 = {
928
+ id: "implement-llm-feature",
929
+ description: "Implement LLM-powered commands in a CLI tool",
930
+ trigger: "cli-command",
931
+ entry_conditions: [
932
+ "Target project is a TypeScript / Node.js project",
933
+ "cli-contract.yaml exists or is being created"
934
+ ],
935
+ steps: [
936
+ {
937
+ type: "delegate",
938
+ task: "implement-llm-feature",
939
+ from_agent: "llm-feature-implementer",
940
+ description: "",
941
+ optional: false,
942
+ max_retries: 0
943
+ }
944
+ ]
945
+ };
946
+ var auditImplementation = {
947
+ id: "audit-implementation",
948
+ description: "Audit an LLM command integration for pattern conformance",
949
+ trigger: "cli-command",
950
+ entry_conditions: [
951
+ "Target project has LLM command integration to audit"
952
+ ],
953
+ steps: [
954
+ {
955
+ type: "delegate",
956
+ task: "audit-dsl",
957
+ from_agent: "implementation-auditor",
958
+ description: "",
959
+ optional: false,
960
+ max_retries: 0,
961
+ depends_on: []
962
+ },
963
+ {
964
+ type: "delegate",
965
+ task: "audit-runtime",
966
+ from_agent: "implementation-auditor",
967
+ description: "",
968
+ optional: false,
969
+ max_retries: 0,
970
+ depends_on: []
971
+ },
972
+ {
973
+ type: "delegate",
974
+ task: "audit-cli-contract",
975
+ from_agent: "implementation-auditor",
976
+ description: "",
977
+ optional: false,
978
+ max_retries: 0,
979
+ depends_on: []
980
+ },
981
+ {
982
+ type: "delegate",
983
+ task: "audit-architecture",
984
+ from_agent: "implementation-auditor",
985
+ description: "",
986
+ optional: false,
987
+ max_retries: 0,
988
+ depends_on: []
989
+ },
990
+ {
991
+ type: "delegate",
992
+ task: "audit-merge",
993
+ from_agent: "implementation-auditor",
994
+ description: "",
995
+ optional: false,
996
+ max_retries: 0,
997
+ depends_on: [
998
+ "audit-dsl",
999
+ "audit-runtime",
1000
+ "audit-cli-contract",
1001
+ "audit-architecture"
1002
+ ]
1003
+ }
1004
+ ]
1005
+ };
1006
+ var workflowRegistry = {
1007
+ "implement-llm-feature": implementLlmFeature2,
1008
+ "audit-implementation": auditImplementation
1009
+ };
1010
+
1011
+ // src/lib/implement.ts
1012
+ function getLocale() {
1013
+ return process.env.LANG?.split(".")[0] ?? process.env.LC_ALL?.split(".")[0] ?? process.env.LANGUAGE?.split(":")[0] ?? "en_US";
1014
+ }
1015
+ function isJapanese() {
1016
+ return getLocale().startsWith("ja");
1017
+ }
1018
+ var en = {
1019
+ noProjectDir: (dir) => `Project directory not found: ${dir}`,
1020
+ adapterError: (msg3) => `Adapter initialization failed: ${msg3}`,
1021
+ dryRunHeader: "=== Dry Run ===",
1022
+ dryRunProjectDir: (dir) => `Project: ${dir}`,
1023
+ dryRunDescription: (desc) => `Description: ${desc}`,
1024
+ dryRunRefIncluded: "Reference: integrate-llm-commands (included)",
1025
+ dryRunRefNotFound: "Reference: integrate-llm-commands (not found, will proceed without)",
1026
+ implementStarting: (adapter) => `Starting implementation with ${adapter} adapter...`,
1027
+ implementSuccess: "Implementation completed successfully.",
1028
+ implementFailed: (reason) => `Implementation failed: ${reason}`,
1029
+ filesCreated: "Files created:",
1030
+ filesModified: "Files modified:",
1031
+ commandsAdded: "Commands added:",
1032
+ nextSteps: "Next steps:"
1033
+ };
1034
+ var ja = {
1035
+ noProjectDir: (dir) => `\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${dir}`,
1036
+ adapterError: (msg3) => `\u30A2\u30C0\u30D7\u30BF\u30FC\u521D\u671F\u5316\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${msg3}`,
1037
+ dryRunHeader: "=== \u30C9\u30E9\u30A4\u30E9\u30F3 ===",
1038
+ dryRunProjectDir: (dir) => `\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8: ${dir}`,
1039
+ dryRunDescription: (desc) => `\u8AAC\u660E: ${desc}`,
1040
+ dryRunRefIncluded: "\u30EA\u30D5\u30A1\u30EC\u30F3\u30B9: integrate-llm-commands\uFF08\u542B\u307E\u308C\u3066\u3044\u307E\u3059\uFF09",
1041
+ dryRunRefNotFound: "\u30EA\u30D5\u30A1\u30EC\u30F3\u30B9: integrate-llm-commands\uFF08\u672A\u691C\u51FA\u3001\u30EA\u30D5\u30A1\u30EC\u30F3\u30B9\u306A\u3057\u3067\u7D9A\u884C\uFF09",
1042
+ implementStarting: (adapter) => `${adapter} \u30A2\u30C0\u30D7\u30BF\u30FC\u3067\u5B9F\u88C5\u3092\u958B\u59CB\u3057\u307E\u3059...`,
1043
+ implementSuccess: "\u5B9F\u88C5\u304C\u6B63\u5E38\u306B\u5B8C\u4E86\u3057\u307E\u3057\u305F\u3002",
1044
+ implementFailed: (reason) => `\u5B9F\u88C5\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${reason}`,
1045
+ filesCreated: "\u4F5C\u6210\u3055\u308C\u305F\u30D5\u30A1\u30A4\u30EB:",
1046
+ filesModified: "\u5909\u66F4\u3055\u308C\u305F\u30D5\u30A1\u30A4\u30EB:",
1047
+ commandsAdded: "\u8FFD\u52A0\u3055\u308C\u305F\u30B3\u30DE\u30F3\u30C9:",
1048
+ nextSteps: "\u6B21\u306E\u30B9\u30C6\u30C3\u30D7:"
1049
+ };
1050
+ function msg() {
1051
+ return isJapanese() ? ja : en;
1052
+ }
1053
+ function loadReferenceDoc() {
1054
+ const candidates = [
1055
+ // Shipped with the package (templates/ sibling of dist/)
1056
+ join3(fileURLToPath(import.meta.url), "..", "..", "..", "templates", "implement-reference.md"),
1057
+ // Dev-time: from the skill directory
1058
+ join3(process.env.HOME ?? "", ".cursor", "skills", "integrate-llm-commands", "SKILL.md")
1059
+ ];
1060
+ for (const candidate of candidates) {
1061
+ try {
1062
+ if (existsSync3(candidate)) {
1063
+ return readFileSync(candidate, "utf8");
1064
+ }
1065
+ } catch {
1066
+ }
1067
+ }
1068
+ return void 0;
1069
+ }
1070
+ async function createImplementAdapter(adapterName, projectDir, model) {
1071
+ switch (adapterName) {
1072
+ case "claude": {
1073
+ const { ClaudeAgentSdkAdapter } = await import("../adapters/claude-agent-sdk.js");
1074
+ return new ClaudeAgentSdkAdapter({
1075
+ cwd: projectDir,
1076
+ permissionMode: "bypassPermissions",
1077
+ model
1078
+ });
1079
+ }
1080
+ case "cursor": {
1081
+ const { CursorSdkAdapter } = await import("../adapters/cursor-sdk.js");
1082
+ const apiKey = process.env.CURSOR_API_KEY;
1083
+ if (!apiKey) {
1084
+ throw new Error("CURSOR_API_KEY environment variable is required for the cursor adapter");
1085
+ }
1086
+ return CursorSdkAdapter.create({ apiKey, cwd: projectDir, model });
1087
+ }
1088
+ case "mock": {
1089
+ const { MockAdapter } = await import("../adapters/mock.js");
1090
+ return new MockAdapter();
1091
+ }
1092
+ default:
1093
+ throw new Error(
1094
+ `Unsupported adapter for implement: "${adapterName}". Available: claude, cursor, mock`
1095
+ );
1096
+ }
1097
+ }
1098
+ async function runImplement(description, options) {
1099
+ const m = msg();
1100
+ const projectDir = resolve2(options.projectDir);
1101
+ if (!existsSync3(projectDir)) {
1102
+ return { status: "failed", exitCode: 3, error: m.noProjectDir(projectDir) };
1103
+ }
1104
+ const referenceDoc = loadReferenceDoc();
1105
+ const userRequest = [
1106
+ description,
1107
+ "",
1108
+ `Project directory: ${projectDir}`
1109
+ ].join("\n");
1110
+ const context = {
1111
+ user_request: userRequest,
1112
+ relevant_paths: [projectDir]
1113
+ };
1114
+ if (referenceDoc) {
1115
+ context.prior_context = "# Reference: integrate-llm-commands pattern\n\nFollow this reference exactly when implementing LLM commands.\n\n" + referenceDoc;
1116
+ }
1117
+ if (options.dryRun) {
1118
+ const agent = agentRegistry["llm-feature-implementer"];
1119
+ const task = taskRegistry["implement-llm-feature"];
1120
+ const prompt = buildTaskPrompt(agent, task, context, { handoffSchemas });
1121
+ return {
1122
+ status: "dry_run",
1123
+ exitCode: 0,
1124
+ data: {
1125
+ files_created: [],
1126
+ files_modified: [],
1127
+ summary: prompt
1128
+ }
1129
+ };
1130
+ }
1131
+ let adapter;
1132
+ try {
1133
+ adapter = await createImplementAdapter(options.adapter, projectDir, options.model);
1134
+ } catch (err) {
1135
+ return { status: "failed", exitCode: 12, error: m.adapterError(err.message) };
1136
+ }
1137
+ if (!options.verbose) {
1138
+ console.error(m.implementStarting(options.adapter));
1139
+ }
1140
+ const registries = {
1141
+ workflowRegistry,
1142
+ taskRegistry,
1143
+ agentRegistry,
1144
+ handoffSchemas
1145
+ };
1146
+ const invocation = {
1147
+ workflow: "implement-llm-feature",
1148
+ user_request: userRequest,
1149
+ runtime: {
1150
+ maxFollowUps: 3,
1151
+ maxRetries: 1
1152
+ },
1153
+ hooks: {
1154
+ onGate: async () => true
1155
+ },
1156
+ context: {
1157
+ cwd: projectDir
1158
+ }
1159
+ };
1160
+ const result = await runWorkflow(adapter, invocation, registries);
1161
+ if (result.status !== "completed") {
1162
+ const reason = result.escalation_reason ?? result.error_message ?? result.status;
1163
+ return { status: "failed", exitCode: 1, error: m.implementFailed(reason) };
1164
+ }
1165
+ const lastStep = result.steps[result.steps.length - 1];
1166
+ const outcomeData = lastStep?.outcome?.data;
1167
+ return {
1168
+ status: "success",
1169
+ exitCode: 0,
1170
+ data: outcomeData ?? {
1171
+ files_created: [],
1172
+ files_modified: [],
1173
+ summary: m.implementSuccess
1174
+ }
1175
+ };
1176
+ }
1177
+ function formatImplementResult(result) {
1178
+ const m = msg();
1179
+ if (result.status === "dry_run") {
1180
+ return result.data?.summary ?? m.dryRunHeader;
1181
+ }
1182
+ if (result.status === "failed") {
1183
+ return result.error ?? m.implementFailed("unknown");
1184
+ }
1185
+ const data = result.data;
1186
+ if (!data) return m.implementSuccess;
1187
+ const lines = [data.summary, ""];
1188
+ if (data.files_created.length > 0) {
1189
+ lines.push(m.filesCreated);
1190
+ for (const f of data.files_created) lines.push(` + ${f}`);
1191
+ lines.push("");
1192
+ }
1193
+ if (data.files_modified.length > 0) {
1194
+ lines.push(m.filesModified);
1195
+ for (const f of data.files_modified) lines.push(` ~ ${f}`);
1196
+ lines.push("");
1197
+ }
1198
+ if (data.commands_added && data.commands_added.length > 0) {
1199
+ lines.push(m.commandsAdded);
1200
+ for (const c of data.commands_added) {
1201
+ lines.push(` - ${c.name} [${c.type}]${c.description ? ` \u2014 ${c.description}` : ""}`);
1202
+ }
1203
+ lines.push("");
1204
+ }
1205
+ if (data.next_steps && data.next_steps.length > 0) {
1206
+ lines.push(m.nextSteps);
1207
+ for (const s of data.next_steps) lines.push(` ${s}`);
1208
+ }
1209
+ return lines.join("\n");
1210
+ }
1211
+
1212
+ // src/lib/audit-implementation.ts
1213
+ import { existsSync as existsSync4 } from "fs";
1214
+ import { resolve as resolve3 } from "path";
1215
+ function getLocale2() {
1216
+ return process.env.LANG?.split(".")[0] ?? process.env.LC_ALL?.split(".")[0] ?? process.env.LANGUAGE?.split(":")[0] ?? "en_US";
1217
+ }
1218
+ function isJapanese2() {
1219
+ return getLocale2().startsWith("ja");
1220
+ }
1221
+ var en2 = {
1222
+ noProjectDir: (dir) => `Project directory not found: ${dir}`,
1223
+ adapterError: (msg3) => `Adapter initialization failed: ${msg3}`,
1224
+ dryRunHeader: "=== Dry Run (audit-implementation) ===",
1225
+ dryRunProjectDir: (dir) => `Project: ${dir}`,
1226
+ dryRunFocus: (focus) => `Focus: ${focus}`,
1227
+ auditStarting: (adapter) => `Starting audit with ${adapter} adapter...`,
1228
+ auditSuccess: "Audit completed.",
1229
+ auditFailed: (reason) => `Audit failed: ${reason}`,
1230
+ riskLevel: (level) => `Risk level: ${level}`,
1231
+ findingsHeader: (count) => `Findings (${count}):`,
1232
+ noFindings: "No findings.",
1233
+ recommendedActionsHeader: "Recommended actions:"
1234
+ };
1235
+ var ja2 = {
1236
+ noProjectDir: (dir) => `\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${dir}`,
1237
+ adapterError: (msg3) => `\u30A2\u30C0\u30D7\u30BF\u30FC\u521D\u671F\u5316\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${msg3}`,
1238
+ dryRunHeader: "=== \u30C9\u30E9\u30A4\u30E9\u30F3 (audit-implementation) ===",
1239
+ dryRunProjectDir: (dir) => `\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8: ${dir}`,
1240
+ dryRunFocus: (focus) => `\u30D5\u30A9\u30FC\u30AB\u30B9: ${focus}`,
1241
+ auditStarting: (adapter) => `${adapter} \u30A2\u30C0\u30D7\u30BF\u30FC\u3067\u76E3\u67FB\u3092\u958B\u59CB\u3057\u307E\u3059...`,
1242
+ auditSuccess: "\u76E3\u67FB\u304C\u5B8C\u4E86\u3057\u307E\u3057\u305F\u3002",
1243
+ auditFailed: (reason) => `\u76E3\u67FB\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${reason}`,
1244
+ riskLevel: (level) => `\u30EA\u30B9\u30AF\u30EC\u30D9\u30EB: ${level}`,
1245
+ findingsHeader: (count) => `\u691C\u51FA\u4E8B\u9805 (${count}\u4EF6):`,
1246
+ noFindings: "\u691C\u51FA\u4E8B\u9805\u306F\u3042\u308A\u307E\u305B\u3093\u3002",
1247
+ recommendedActionsHeader: "\u63A8\u5968\u30A2\u30AF\u30B7\u30E7\u30F3:"
1248
+ };
1249
+ function msg2() {
1250
+ return isJapanese2() ? ja2 : en2;
1251
+ }
1252
+ async function createAuditAdapter(adapterName, projectDir, model) {
1253
+ switch (adapterName) {
1254
+ case "claude": {
1255
+ const { ClaudeAgentSdkAdapter } = await import("../adapters/claude-agent-sdk.js");
1256
+ return new ClaudeAgentSdkAdapter({
1257
+ cwd: projectDir,
1258
+ model
1259
+ });
1260
+ }
1261
+ case "cursor": {
1262
+ const { CursorSdkAdapter } = await import("../adapters/cursor-sdk.js");
1263
+ const apiKey = process.env.CURSOR_API_KEY;
1264
+ if (!apiKey) {
1265
+ throw new Error("CURSOR_API_KEY environment variable is required for the cursor adapter");
1266
+ }
1267
+ return CursorSdkAdapter.create({ apiKey, cwd: projectDir, model });
1268
+ }
1269
+ case "mock": {
1270
+ const { MockAdapter } = await import("../adapters/mock.js");
1271
+ return new MockAdapter();
1272
+ }
1273
+ default:
1274
+ throw new Error(
1275
+ `Unsupported adapter for audit-implementation: "${adapterName}". Available: claude, cursor, mock`
1276
+ );
1277
+ }
1278
+ }
1279
+ var SEVERITY_ORDER = {
1280
+ info: 0,
1281
+ warning: 1,
1282
+ error: 2,
1283
+ critical: 3
1284
+ };
1285
+ function hasFindings(result, failOn) {
1286
+ const threshold = SEVERITY_ORDER[failOn] ?? 2;
1287
+ return result.findings.some(
1288
+ (f) => (SEVERITY_ORDER[f.severity] ?? 0) >= threshold
1289
+ );
1290
+ }
1291
+ async function runAuditImplementation(options) {
1292
+ const m = msg2();
1293
+ const projectDir = resolve3(options.projectDir);
1294
+ if (!existsSync4(projectDir)) {
1295
+ return { status: "failed", exitCode: 3, error: m.noProjectDir(projectDir) };
1296
+ }
1297
+ const focusInstruction = options.focus !== "all" ? `
1298
+
1299
+ Focus the audit on the "${options.focus}" layer only.` : "";
1300
+ const userRequest = [
1301
+ `Audit the LLM command integration in the following project.`,
1302
+ `Project directory: ${projectDir}`,
1303
+ focusInstruction
1304
+ ].join("\n");
1305
+ const context = {
1306
+ user_request: userRequest,
1307
+ relevant_paths: [projectDir]
1308
+ };
1309
+ if (options.dryRun) {
1310
+ const agent = agentRegistry["implementation-auditor"];
1311
+ const auditTasks = ["audit-dsl", "audit-runtime", "audit-cli-contract", "audit-architecture"];
1312
+ const prompts = auditTasks.map((taskId) => {
1313
+ const task = taskRegistry[taskId];
1314
+ if (!task) return `# [Task not found: ${taskId}]`;
1315
+ return buildTaskPrompt(agent, task, context, { handoffSchemas });
1316
+ });
1317
+ const separator = "\n\n" + "=".repeat(72) + "\n\n";
1318
+ const fullPrompt = prompts.join(separator);
1319
+ return {
1320
+ status: "dry_run",
1321
+ exitCode: 0,
1322
+ data: {
1323
+ summary: fullPrompt,
1324
+ riskLevel: "low",
1325
+ findings: []
1326
+ }
1327
+ };
1328
+ }
1329
+ let adapter;
1330
+ try {
1331
+ adapter = await createAuditAdapter(options.adapter, projectDir, options.model);
1332
+ } catch (err) {
1333
+ return { status: "failed", exitCode: 12, error: m.adapterError(err.message) };
1334
+ }
1335
+ console.error(m.auditStarting(options.adapter));
1336
+ const registries = {
1337
+ workflowRegistry,
1338
+ taskRegistry,
1339
+ agentRegistry,
1340
+ handoffSchemas
1341
+ };
1342
+ const invocation = {
1343
+ workflow: "audit-implementation",
1344
+ user_request: userRequest,
1345
+ runtime: {
1346
+ maxFollowUps: 2,
1347
+ maxRetries: 1
1348
+ },
1349
+ hooks: {
1350
+ onGate: async () => true
1351
+ },
1352
+ context: {
1353
+ cwd: projectDir
1354
+ }
1355
+ };
1356
+ const result = await runWorkflow(adapter, invocation, registries);
1357
+ if (result.status !== "completed") {
1358
+ const reason = result.escalation_reason ?? result.error_message ?? result.status;
1359
+ return { status: "failed", exitCode: 1, error: m.auditFailed(reason) };
1360
+ }
1361
+ const lastStep = result.steps[result.steps.length - 1];
1362
+ const outcomeData = lastStep?.outcome?.data;
1363
+ const auditData = outcomeData ?? {
1364
+ summary: m.auditSuccess,
1365
+ riskLevel: "low",
1366
+ findings: []
1367
+ };
1368
+ const exitCode = hasFindings(auditData, options.failOn) ? 10 : 0;
1369
+ return {
1370
+ status: "success",
1371
+ exitCode,
1372
+ data: auditData
1373
+ };
1374
+ }
1375
+ var SEVERITY_ICON = {
1376
+ critical: "\u2717",
1377
+ error: "\u2717",
1378
+ warning: "!",
1379
+ info: "\xB7"
1380
+ };
1381
+ function formatAuditResult(result) {
1382
+ const m = msg2();
1383
+ if (result.status === "dry_run") {
1384
+ return result.data?.summary ?? m.dryRunHeader;
1385
+ }
1386
+ if (result.status === "failed") {
1387
+ return result.error ?? m.auditFailed("unknown");
1388
+ }
1389
+ const data = result.data;
1390
+ if (!data) return m.auditSuccess;
1391
+ const lines = [data.summary, ""];
1392
+ lines.push(m.riskLevel(data.riskLevel));
1393
+ lines.push("");
1394
+ if (data.findings.length === 0) {
1395
+ lines.push(m.noFindings);
1396
+ } else {
1397
+ lines.push(m.findingsHeader(data.findings.length));
1398
+ for (const f of data.findings) {
1399
+ const icon = SEVERITY_ICON[f.severity] ?? "\xB7";
1400
+ const id = f.id ? `[${f.id}] ` : "";
1401
+ const target = f.target ? ` (${f.target})` : "";
1402
+ lines.push(` ${icon} ${id}${f.severity.toUpperCase()}: ${f.message}${target}`);
1403
+ if (f.recommendation) {
1404
+ lines.push(` \u2192 ${f.recommendation}`);
1405
+ }
1406
+ }
1407
+ lines.push("");
1408
+ }
1409
+ if (data.recommendedActions && data.recommendedActions.length > 0) {
1410
+ lines.push(m.recommendedActionsHeader);
1411
+ for (const a of data.recommendedActions) {
1412
+ const cmd = a.command ? ` \u2014 ${a.command}` : "";
1413
+ lines.push(` [${a.kind}] ${a.title}${cmd}`);
1414
+ }
1415
+ }
1416
+ return lines.join("\n");
1417
+ }
1418
+
391
1419
  // src/cli/index.ts
392
1420
  import YAML3 from "yaml";
393
1421
  register();
394
- var VERSION = "0.11.0";
1422
+ var VERSION = "0.32.1";
395
1423
  async function loadGeneratedContracts(configPath) {
396
1424
  const config = await loadConfig(configPath);
397
1425
  const basePath = `${config.generatedDir}/index`;
398
1426
  let indexPath;
399
- if (existsSync3(`${basePath}.js`)) {
1427
+ if (existsSync5(`${basePath}.js`)) {
400
1428
  indexPath = `${basePath}.js`;
401
- } else if (existsSync3(`${basePath}.ts`)) {
1429
+ } else if (existsSync5(`${basePath}.ts`)) {
402
1430
  indexPath = `${basePath}.ts`;
403
1431
  } else {
404
1432
  throw new Error(
@@ -408,7 +1436,7 @@ async function loadGeneratedContracts(configPath) {
408
1436
  const mod = await import(new URL(`file://${indexPath}`).href);
409
1437
  let guardrailHooks;
410
1438
  const hooksBasePath = `${config.generatedDir}/hooks/index`;
411
- const hooksPath = existsSync3(`${hooksBasePath}.js`) ? `${hooksBasePath}.js` : existsSync3(`${hooksBasePath}.ts`) ? `${hooksBasePath}.ts` : null;
1439
+ const hooksPath = existsSync5(`${hooksBasePath}.js`) ? `${hooksBasePath}.js` : existsSync5(`${hooksBasePath}.ts`) ? `${hooksBasePath}.ts` : null;
412
1440
  if (hooksPath) {
413
1441
  try {
414
1442
  const hooksMod = await import(new URL(`file://${hooksPath}`).href);
@@ -426,7 +1454,7 @@ async function loadGeneratedContracts(configPath) {
426
1454
  guardrailHooks
427
1455
  };
428
1456
  }
429
- async function createAdapter(adapterName, guardrailHooks) {
1457
+ async function createAdapter(adapterName, guardrailHooks, cwd) {
430
1458
  switch (adapterName) {
431
1459
  case "mock": {
432
1460
  const { MockAdapter } = await import("../adapters/mock.js");
@@ -434,7 +1462,7 @@ async function createAdapter(adapterName, guardrailHooks) {
434
1462
  }
435
1463
  case "claude": {
436
1464
  const { ClaudeAgentSdkAdapter } = await import("../adapters/claude-agent-sdk.js");
437
- return new ClaudeAgentSdkAdapter({ guardrailHooks });
1465
+ return new ClaudeAgentSdkAdapter({ cwd, guardrailHooks });
438
1466
  }
439
1467
  case "gemini": {
440
1468
  const { GeminiSdkAdapter } = await import("../adapters/gemini-sdk.js");
@@ -446,7 +1474,7 @@ async function createAdapter(adapterName, guardrailHooks) {
446
1474
  if (!apiKey) {
447
1475
  throw new Error("CURSOR_API_KEY environment variable is required for the cursor adapter");
448
1476
  }
449
- return CursorSdkAdapter.create({ apiKey, guardrailHooks });
1477
+ return CursorSdkAdapter.create({ apiKey, cwd, guardrailHooks });
450
1478
  }
451
1479
  default:
452
1480
  throw new Error(`Unknown adapter: ${adapterName}. Available: mock, claude, gemini, cursor`);
@@ -467,7 +1495,7 @@ function formatTable(headers, rows) {
467
1495
  var handlers = {
468
1496
  async init(options, _globalOpts) {
469
1497
  try {
470
- const outputDir = resolve2(options.output ?? ".");
1498
+ const outputDir = resolve4(options.output ?? ".");
471
1499
  const result = await runInit({
472
1500
  adapter: options.adapter ?? "mock",
473
1501
  outputDir,
@@ -508,32 +1536,33 @@ var handlers = {
508
1536
  let fileInvocation;
509
1537
  if (options.file) {
510
1538
  try {
511
- const raw = readFileSync(options.file, "utf8");
1539
+ const raw = readFileSync2(options.file, "utf8");
512
1540
  const parsed = YAML3.parse(raw);
513
1541
  resolvedWorkflowId = parsed.workflow;
514
1542
  if (!resolvedWorkflowId) {
515
1543
  console.error(`Error: invocation file "${options.file}" must contain a "workflow" field.`);
516
- process.exit(1);
1544
+ process.exit(3);
517
1545
  }
518
1546
  fileInvocation = {
519
1547
  workflow: resolvedWorkflowId,
520
1548
  user_request: parsed.user_request,
521
1549
  handoff: parsed.handoff,
522
- runtime: parsed.runtime
1550
+ runtime: parsed.runtime,
1551
+ context: parsed.context
523
1552
  };
524
1553
  resolvedUserRequest = fileInvocation.user_request ?? "";
525
1554
  } catch (err) {
526
1555
  console.error(`Failed to read invocation file: ${err.message}`);
527
- process.exit(1);
1556
+ process.exit(3);
528
1557
  }
529
1558
  }
530
1559
  if (!resolvedWorkflowId) {
531
1560
  console.error("Error: workflow-id is required (provide as argument or via --file)");
532
- process.exit(1);
1561
+ process.exit(3);
533
1562
  }
534
1563
  if (!fileInvocation && !resolvedUserRequest) {
535
1564
  console.error("Error: user-request is required (provide as argument or via --file)");
536
- process.exit(1);
1565
+ process.exit(3);
537
1566
  }
538
1567
  const configPath = globalOpts.config ?? "./agent-runtime.config.yaml";
539
1568
  const fresh = await checkFreshness(configPath);
@@ -563,16 +1592,17 @@ var handlers = {
563
1592
  if (!contracts.workflowRegistry[resolvedWorkflowId]) {
564
1593
  console.error(`Unknown workflow: ${resolvedWorkflowId}`);
565
1594
  console.error(`Available workflows: ${Object.keys(contracts.workflowRegistry).join(", ")}`);
566
- process.exit(1);
1595
+ process.exit(3);
567
1596
  return;
568
1597
  }
569
1598
  const adapterName = options.adapter ?? "mock";
1599
+ const adapterCwd = fileInvocation?.context?.cwd ?? process.cwd();
570
1600
  let adapter;
571
1601
  try {
572
- adapter = await createAdapter(adapterName, contracts.guardrailHooks);
1602
+ adapter = await createAdapter(adapterName, contracts.guardrailHooks, adapterCwd);
573
1603
  } catch (err) {
574
1604
  console.error(err.message);
575
- process.exit(1);
1605
+ process.exit(12);
576
1606
  return;
577
1607
  }
578
1608
  const recovery = config.recovery;
@@ -737,14 +1767,91 @@ var handlers = {
737
1767
  console.log(prompt);
738
1768
  }
739
1769
  },
1770
+ async implement(description, options, _globalOpts) {
1771
+ if (!description) {
1772
+ console.error("Error: description is required");
1773
+ process.exit(3);
1774
+ }
1775
+ const result = await runImplement(description, {
1776
+ adapter: options.adapter ?? "claude",
1777
+ projectDir: options.projectDir ?? ".",
1778
+ dryRun: options.dryRun ?? false,
1779
+ model: options.model,
1780
+ reportFormat: options.reportFormat ?? "text"
1781
+ });
1782
+ if (result.status === "failed") {
1783
+ if (options.reportFormat === "json") {
1784
+ console.log(JSON.stringify({ error: result.error, status: "failed" }, null, 2));
1785
+ } else if (options.reportFormat === "yaml") {
1786
+ console.log(YAML3.stringify({ error: result.error, status: "failed" }));
1787
+ } else {
1788
+ console.error(formatImplementResult(result));
1789
+ }
1790
+ process.exit(result.exitCode ?? 1);
1791
+ }
1792
+ const outputData = result.data ?? { status: result.status };
1793
+ let output;
1794
+ if (options.reportFormat === "json") {
1795
+ output = JSON.stringify(outputData, null, 2);
1796
+ } else if (options.reportFormat === "yaml") {
1797
+ output = YAML3.stringify(outputData);
1798
+ } else {
1799
+ output = formatImplementResult(result);
1800
+ }
1801
+ const outputPath = options.output;
1802
+ if (outputPath) {
1803
+ writeFileSync(outputPath, output + "\n");
1804
+ } else {
1805
+ console.log(output);
1806
+ }
1807
+ },
1808
+ async auditImplementation(projectDir, options, _globalOpts) {
1809
+ const result = await runAuditImplementation({
1810
+ adapter: options.adapter ?? "claude",
1811
+ projectDir: projectDir ?? ".",
1812
+ focus: options.focus ?? "all",
1813
+ dryRun: options.dryRun ?? false,
1814
+ failOn: options.failOn ?? "error",
1815
+ model: options.model,
1816
+ reportFormat: options.reportFormat ?? "text"
1817
+ });
1818
+ if (result.status === "failed") {
1819
+ if (options.reportFormat === "json") {
1820
+ console.log(JSON.stringify({ error: result.error, status: "failed" }, null, 2));
1821
+ } else if (options.reportFormat === "yaml") {
1822
+ console.log(YAML3.stringify({ error: result.error, status: "failed" }));
1823
+ } else {
1824
+ console.error(formatAuditResult(result));
1825
+ }
1826
+ process.exit(result.exitCode);
1827
+ }
1828
+ const outputData = result.data ?? { status: result.status };
1829
+ let output;
1830
+ if (options.reportFormat === "json") {
1831
+ output = JSON.stringify(outputData, null, 2);
1832
+ } else if (options.reportFormat === "yaml") {
1833
+ output = YAML3.stringify(outputData);
1834
+ } else {
1835
+ output = formatAuditResult(result);
1836
+ }
1837
+ const outputPath = options.output;
1838
+ if (outputPath) {
1839
+ writeFileSync(outputPath, output + "\n");
1840
+ } else {
1841
+ console.log(output);
1842
+ }
1843
+ if (result.exitCode !== 0) {
1844
+ process.exit(result.exitCode);
1845
+ }
1846
+ },
740
1847
  async doctor(globalOpts) {
741
1848
  const configPath = globalOpts.config ?? "./agent-runtime.config.yaml";
742
1849
  const result = await runDoctor(configPath);
743
1850
  const statusIcon = (s) => s === "pass" ? "\u2713" : s === "warn" ? "!" : "\u2717";
744
1851
  for (const check of result.checks) {
745
1852
  const icon = statusIcon(check.status);
746
- const msg = check.message ? ` ${check.message}` : "";
747
- console.log(` ${icon} ${check.name.padEnd(20)} ${check.status.toUpperCase()}${msg}`);
1853
+ const msg3 = check.message ? ` ${check.message}` : "";
1854
+ console.log(` ${icon} ${check.name.padEnd(20)} ${check.status.toUpperCase()}${msg3}`);
748
1855
  }
749
1856
  console.log("");
750
1857
  if (result.all_passed) {