agent-contracts-runtime 0.36.15 → 0.36.17
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/README.md +6 -65
- package/cli-contract.yaml +3 -3
- package/dist/adapters/claude-agent-sdk.d.ts +4 -3
- package/dist/adapters/claude-agent-sdk.js +17 -9
- package/dist/adapters/claude-agent-sdk.js.map +1 -1
- package/dist/adapters/mock.d.ts +1 -1
- package/dist/adapters/openai-agents-sdk.d.ts +4 -3
- package/dist/agent-runtime.bundle.mjs +528 -739
- package/dist/agent-runtime.bundle.mjs.map +4 -4
- package/dist/{chunk-AL2N7IM2.js → chunk-VKCNOSMQ.js} +324 -18
- package/dist/chunk-VKCNOSMQ.js.map +1 -0
- package/dist/cli/index.js +20 -25
- package/dist/cli/index.js.map +1 -1
- package/dist/{context-B_bekYiE.d.ts → context-BEisfYPn.d.ts} +2 -1
- package/dist/generator/index.d.ts +3 -2
- package/dist/{guardrail-hooks-C8G5NGsj.d.ts → guardrail-hooks-CFd3a8tQ.d.ts} +2 -1
- package/dist/index.d.ts +8 -7
- package/dist/index.js +12 -14
- package/dist/{task-runner-Bo37lS9q.d.ts → task-runner-DJW49UGZ.d.ts} +5 -5
- package/docs/cli-reference.md +1 -1
- package/docs/sdk-options-bridge-spec.md +4 -3
- package/dsl/agents/llm-feature-implementer.yaml +2 -4
- package/dsl/tasks.yaml +1 -5
- package/package.json +15 -29
- package/templates/implement-reference-templates.md +3 -17
- package/templates/implement-reference.md +3 -3
- package/dist/adapters/adk-sdk.d.ts +0 -128
- package/dist/adapters/adk-sdk.js +0 -185
- package/dist/adapters/adk-sdk.js.map +0 -1
- package/dist/chunk-AL2N7IM2.js.map +0 -1
- package/dist/chunk-MGRZBGQL.js +0 -321
- package/dist/chunk-MGRZBGQL.js.map +0 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,21 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
buildTaskPrompt,
|
|
4
|
+
createGuardrailHooksFromRules,
|
|
4
5
|
createProgressSink,
|
|
5
6
|
loadPlugins,
|
|
7
|
+
pluginRegistry,
|
|
6
8
|
runWorkflow
|
|
7
|
-
} from "../chunk-
|
|
8
|
-
import "../chunk-2E2LWE6C.js";
|
|
9
|
+
} from "../chunk-VKCNOSMQ.js";
|
|
9
10
|
import "../chunk-AWBHN3LI.js";
|
|
10
|
-
import {
|
|
11
|
-
createGuardrailHooksFromRules,
|
|
12
|
-
pluginRegistry
|
|
13
|
-
} from "../chunk-MGRZBGQL.js";
|
|
14
11
|
import {
|
|
15
12
|
checkFreshness,
|
|
16
13
|
generate,
|
|
17
14
|
loadConfig
|
|
18
15
|
} from "../chunk-S7MTKPBF.js";
|
|
16
|
+
import "../chunk-2E2LWE6C.js";
|
|
19
17
|
import "../chunk-KKJW4TE5.js";
|
|
20
18
|
import "../chunk-D2QTXQB2.js";
|
|
21
19
|
|
|
@@ -28,8 +26,8 @@ import { register } from "tsx/esm/api";
|
|
|
28
26
|
import { Command } from "commander";
|
|
29
27
|
|
|
30
28
|
// src/generated/cli/contract.ts
|
|
31
|
-
var CONTRACT_YAML = 'cli_contracts: 0.1.0\n\ninfo:\n title: agent-runtime CLI\n version: 0.36.15\n description: |\n Runtime bridge for executing agent-contracts workflows on Agent SDKs.\n Generates typed contracts, handoff validators, and guardrail hooks from DSL,\n then runs workflows through pluggable SDK adapters.\n license:\n name: MIT\n\ncommand_sets:\n agent-runtime:\n summary: CLI for agent-contracts-runtime \u2014 generate, run, and manage agent workflows.\n global_options:\n - name: config\n aliases: [c]\n description: Path to agents.conf.yaml (project runtime config).\n schema:\n type: string\n default: ./agents.conf.yaml\n file:\n mode: read\n exists: true\n media_type: application/yaml\n\n - name: verbose\n aliases: [v]\n description: Enable verbose output.\n schema:\n type: boolean\n default: false\n\n - name: quiet\n aliases: [q]\n description: Suppress non-error output.\n schema:\n type: boolean\n default: false\n\n commands:\n # -----------------------------------------------------------------------\n # init\n # -----------------------------------------------------------------------\n init:\n summary: Initialize runtime scaffolding for a project.\n description: |\n Generates the initial directory structure and configuration files\n for using agent-contracts-runtime in a project.\n Creates agents.conf.yaml and agent/src/ user code templates.\n options:\n - name: adapter\n aliases: [a]\n description: Default SDK adapter to configure.\n schema:\n type: string\n enum: [claude, gemini, openai, mock]\n default: mock\n\n - name: output\n aliases: [o]\n description: Output directory for generated scaffolding.\n schema:\n type: string\n default: "."\n\n - name: force\n aliases: [f]\n description: Overwrite existing files without prompting.\n schema:\n type: boolean\n default: false\n\n exits:\n "0":\n description: Scaffolding generated successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/InitResult"\n\n "1":\n description: Initialization failed (existing files, permission error, etc.).\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: false\n sideEffects:\n - filesystem_write\n safeDryRunOption: ""\n\n # -----------------------------------------------------------------------\n # generate\n # -----------------------------------------------------------------------\n generate:\n summary: Generate runtime contracts and hooks from DSL.\n description: |\n Reads agent-contracts.yaml, resolves the DSL, validates it,\n and generates typed contracts, handoff schemas, guardrail hooks,\n and a runtime manifest into the configured generated_dir.\n\n Each generated file includes a DO NOT EDIT header.\n options:\n - name: clean\n description: |\n Delete generated_dir before regenerating.\n Removes stale files that may remain from previous generations.\n schema:\n type: boolean\n default: false\n\n - name: check\n description: |\n Dry-run mode for CI. Does not write files.\n Compares current generated output with what would be regenerated.\n Exits with code 1 if any differences are found.\n schema:\n type: boolean\n default: false\n\n - name: templates\n aliases: [t]\n description: Custom templates directory. Overrides built-in templates.\n schema:\n type: string\n\n exits:\n "0":\n description: Generation completed successfully (or --check found no differences).\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/GenerateResult"\n\n "1":\n description: |\n Generation failed, or --check detected differences between\n current generated files and expected output.\n stderr:\n format: text\n\n "2":\n description: DSL validation error. The input DSL has structural or semantic issues.\n stderr:\n format: json\n schema:\n $ref: "#/components/schemas/ValidationError"\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects:\n - filesystem_write\n safeDryRunOption: check\n\n # -----------------------------------------------------------------------\n # run\n # -----------------------------------------------------------------------\n run:\n summary: Execute a workflow.\n description: |\n Loads generated contracts, creates an SDK adapter, registers user plugins,\n and executes the specified workflow with the given user request.\n\n The workflow runner orchestrates task delegation, retry, gate handling,\n and handoff validation mechanically.\n arguments:\n - name: workflow-id\n required: false\n description: ID of the workflow to execute. Required unless --file is used.\n schema:\n type: string\n\n - name: user-request\n required: false\n description: Natural language description of what to do. Required unless --file is used.\n schema:\n type: string\n\n options:\n - name: adapter\n aliases: [a]\n description: SDK adapter to use. Overrides config.\n schema:\n type: string\n enum: [claude, gemini, openai, mock]\n\n - name: max-retries\n aliases: [r]\n description: Override default max retries per step.\n schema:\n type: integer\n minimum: 0\n maximum: 10\n\n - name: max-follow-ups\n aliases: [f]\n description: Override default max follow-ups per step.\n schema:\n type: integer\n minimum: 0\n maximum: 10\n\n - name: dry-run\n aliases: [n]\n description: Simulate execution without calling the SDK adapter.\n schema:\n type: boolean\n default: false\n\n - name: auto-approve-gates\n description: Automatically approve all gate steps.\n schema:\n type: boolean\n default: false\n\n - name: file\n description: |\n Path to a YAML invocation file. When provided, workflow-id and\n user-request arguments are read from the file instead of CLI args.\n schema:\n type: string\n file:\n mode: read\n exists: true\n media_type: application/yaml\n\n - name: log-file\n aliases: [l]\n description: Write agent progress log to this file. Overrides config logging.progress_log.\n schema:\n type: string\n file:\n mode: write\n\n exits:\n "0":\n description: Workflow completed successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/WorkflowResult"\n\n "1":\n description: Workflow failed (escalation, error, or gate rejection).\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/WorkflowResult"\n stderr:\n format: text\n\n "3":\n description: >-\n Input validation failed (invalid arguments, unknown workflow/adapter,\n or generated files outdated).\n stderr:\n format: text\n\n "12":\n description: Adapter initialization error (missing API key, etc.).\n stderr:\n format: text\n\n x-agent:\n riskLevel: high\n requiresConfirmation: true\n idempotent: false\n sideEffects:\n - sdk_call\n - filesystem_write\n safeDryRunOption: dry-run\n expectedDurationMs: 300000\n recommendedBeforeUse:\n - Run `agent-runtime generate --check` to ensure contracts are up to date.\n - Run `agent-runtime doctor` to verify SDK configuration.\n\n # -----------------------------------------------------------------------\n # list\n # -----------------------------------------------------------------------\n list:\n summary: List available workflows, tasks, or agents.\n description: |\n Reads generated contracts and displays available resources.\n Useful for discovering what workflows, tasks, and agents\n are defined in the current project.\n arguments:\n - name: resource\n required: true\n description: Type of resource to list.\n schema:\n type: string\n enum: [workflows, tasks, agents]\n\n options:\n - name: format\n description: Output format.\n schema:\n type: string\n enum: [table, json]\n default: table\n\n exits:\n "0":\n description: Resources listed successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/ListResult"\n\n "1":\n description: Failed to load contracts.\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n # -----------------------------------------------------------------------\n # show-prompt\n # -----------------------------------------------------------------------\n show-prompt:\n summary: Display the generated prompt for a task.\n description: |\n Builds and displays the full prompt that would be sent to an SDK agent\n for a given task. Useful for inspecting, debugging, and validating\n prompt content before execution.\n\n Shows the agent role, responsibilities, constraints, task details,\n completion criteria, handoff schema fields, and output format example.\n arguments:\n - name: task-id\n required: true\n description: ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).\n schema:\n type: string\n\n options:\n - name: user-request\n aliases: [u]\n description: User request text to include in the prompt preview.\n schema:\n type: string\n default: "(preview)"\n\n - name: format\n description: Output format.\n schema:\n type: string\n enum: [markdown, raw, json]\n default: markdown\n\n - name: with-plugins\n description: Apply registered plugin prompt enhancers to the output.\n schema:\n type: boolean\n default: false\n\n exits:\n "0":\n description: Prompt displayed successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/ShowPromptResult"\n\n "1":\n description: Failed to build prompt (unknown task, missing contracts, etc.).\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n # -----------------------------------------------------------------------\n # implement\n # -----------------------------------------------------------------------\n implement:\n summary: Implement LLM-powered commands in a CLI tool.\n description: |\n Uses an agentic LLM adapter (Claude, etc.) to analyze the\n target project and implement LLM-powered commands following the\n agent-contracts + agent-contracts-runtime + cli-contracts stack.\n\n The agent reads the project structure, cli-contract.yaml, and existing\n code, then generates DSL definitions, TypeScript modules (orchestrator,\n context-builder, formatter), CLI command handlers, and updates the\n CLI contract with x-agent metadata.\n\n Requires an agentic adapter that supports tool use (file read/write).\n arguments:\n - name: description\n required: true\n description: >-\n Natural language description of the LLM feature(s) to implement.\n Examples: "Add an audit command for migration safety",\n "Add propose and explain commands for SQL optimization".\n schema:\n type: string\n\n options:\n - name: adapter\n aliases: [a]\n description: SDK adapter to use. Must be an agentic adapter (claude).\n schema:\n type: string\n enum: [claude, mock]\n default: claude\n\n - name: project-dir\n aliases: [p]\n description: Path to the target project directory.\n schema:\n type: string\n default: "."\n\n - name: dry-run\n aliases: [n]\n description: Output the prompt context without calling the LLM.\n schema:\n type: boolean\n default: false\n\n - name: model\n description: Model name override for the selected adapter.\n schema:\n type: string\n\n - name: output\n aliases: [o]\n description: Write the result to a file instead of stdout.\n schema:\n type: string\n file:\n mode: write\n\n - name: report-format\n description: Output format for the result.\n schema:\n type: string\n enum: [json, text, yaml]\n default: text\n\n - name: log-file\n aliases: [l]\n description: Write agent progress log to this file.\n schema:\n type: string\n file:\n mode: write\n\n exits:\n "0":\n description: Implementation completed successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/ImplementResult"\n\n "1":\n description: Implementation failed.\n stderr:\n format: text\n\n "3":\n description: Input validation failed (e.g. project directory not found).\n stderr:\n format: text\n\n "12":\n description: Adapter initialization error.\n stderr:\n format: text\n\n x-agent:\n riskLevel: high\n requiresConfirmation: true\n idempotent: false\n sideEffects:\n - sdk_call\n - filesystem_write\n safeDryRunOption: dry-run\n expectedDurationMs: 300000\n retryableExitCodes: [1, 12]\n recommendedBeforeUse:\n - Ensure the target project has a cli-contract.yaml or plan to create one.\n - Run in a clean git working tree so changes can be reviewed.\n\n # -----------------------------------------------------------------------\n # audit-implementation\n # -----------------------------------------------------------------------\n audit-implementation:\n summary: Audit an LLM command integration for pattern conformance.\n description: |\n Analyzes a target project\'s LLM command integration to verify it\n correctly follows the agent-contracts + agent-contracts-runtime +\n cli-contracts stack conventions.\n\n Checks all three layers:\n 1. DSL definitions (agents, tasks, workflows, handoff schemas)\n 2. Runtime integration (adapter usage, runTask/runWorkflow, registries)\n 3. CLI contract (standard options, x-agent metadata, exit codes)\n\n Produces structured findings with severity, category, and\n concrete remediation steps. Read-only \u2014 does not modify files.\n arguments:\n - name: project-dir\n required: false\n description: >-\n Path to the project directory to audit. Defaults to current directory.\n schema:\n type: string\n\n options:\n - name: adapter\n aliases: [a]\n description: SDK adapter to use for the audit agent.\n schema:\n type: string\n enum: [claude, mock]\n default: claude\n\n - name: focus\n description: >-\n Limit audit to a specific layer. Defaults to all layers.\n schema:\n type: string\n enum: [all, dsl, runtime, cli-contract, architecture]\n default: all\n\n - name: dry-run\n aliases: [n]\n description: Output the prompt context without calling the LLM.\n schema:\n type: boolean\n default: false\n\n - name: fail-on\n description: Minimum finding severity that causes a non-zero exit.\n schema:\n type: string\n enum: [warning, error, critical]\n default: error\n\n - name: model\n description: Model name override for the selected adapter.\n schema:\n type: string\n\n - name: output\n aliases: [o]\n description: Write the result to a file instead of stdout.\n schema:\n type: string\n file:\n mode: write\n\n - name: report-format\n description: Output format for the audit report.\n schema:\n type: string\n enum: [json, text, yaml]\n default: text\n\n - name: log-file\n aliases: [l]\n description: Write agent progress log to this file.\n schema:\n type: string\n file:\n mode: write\n\n exits:\n "0":\n description: Audit completed with no findings above threshold.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/AuditImplementationResult"\n\n "1":\n description: Audit failed (agent error, unexpected failure).\n stderr:\n format: text\n\n "3":\n description: Input validation failed (e.g. project directory not found).\n stderr:\n format: text\n\n "10":\n description: Audit completed with findings above --fail-on threshold.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/AuditImplementationResult"\n\n "12":\n description: Adapter initialization error.\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects:\n - network\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: dry-run\n expectedDurationMs: 180000\n retryableExitCodes: [1, 12]\n\n # -----------------------------------------------------------------------\n # agents\n # -----------------------------------------------------------------------\n agents:\n summary: Output the full resolved DSL as structured data.\n description: |\n Outputs the complete resolved DSL (agents, tasks, workflows,\n handoff_types, etc.) embedded in this CLI binary.\n\n Useful for debugging, external tooling integration, and DSL\n inspection. Unlike `list`, which shows tabular summaries,\n this command outputs the full DSL structure.\n options:\n - name: format\n aliases: [F]\n description: Output format.\n schema:\n type: string\n enum: [yaml, json]\n default: yaml\n\n exits:\n "0":\n description: DSL output successfully.\n stdout:\n format: text\n\n "1":\n description: Failed to load embedded DSL.\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n # -----------------------------------------------------------------------\n # doctor\n # -----------------------------------------------------------------------\n doctor:\n summary: Verify configuration, generated files, and SDK connectivity.\n description: |\n Runs a series of diagnostic checks to verify that the project\n is correctly configured for agent-runtime execution.\n\n Checks: config existence, DSL existence, generated manifest freshness,\n adapter configuration, API key environment variables, plugin entrypoint.\n exits:\n "0":\n description: All checks passed.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/DoctorResult"\n\n "1":\n description: One or more checks failed.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/DoctorResult"\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n # -----------------------------------------------------------------------\n # navigation-index\n # -----------------------------------------------------------------------\n navigation-index:\n summary: Build artifact navigation index from resolved DSL.\n description: |\n Resolves the embedded DSL (merged with project overlay if configured),\n applies artifact binding, and builds a navigation index showing\n artifact-to-tool-to-agent mappings.\n\n The output is a JSON/YAML structure suitable for IDE integration,\n routing rules, and artifact coverage analysis.\n options:\n - name: format\n aliases: [F]\n description: Output format.\n schema:\n type: string\n enum: [json, yaml]\n default: json\n\n - name: artifact\n description: Filter output to a single artifact by ID.\n schema:\n type: string\n\n - name: output\n aliases: [o]\n description: Write output to a file instead of stdout.\n schema:\n type: string\n file:\n mode: write\n\n exits:\n "0":\n description: Navigation index built successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/NavigationIndexResult"\n\n "1":\n description: Failed to build navigation index.\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n\n# =============================================================================\n# Components\n# =============================================================================\n\ncomponents:\n schemas:\n # -------------------------------------------------------------------------\n # init\n # -------------------------------------------------------------------------\n InitResult:\n type: object\n required: [files_created]\n properties:\n files_created:\n type: array\n items:\n type: string\n description: List of files created by init.\n\n # -------------------------------------------------------------------------\n # generate\n # -------------------------------------------------------------------------\n GenerateResult:\n type: object\n required: [files_generated, dsl_hash, generation_input_hash]\n properties:\n files_generated:\n type: array\n items:\n type: string\n description: List of generated file paths.\n dsl_hash:\n type: string\n description: SHA-256 hash of the resolved DSL (canonical stringify).\n generation_input_hash:\n type: string\n description: SHA-256 hash of all generation inputs.\n cleaned:\n type: boolean\n description: Whether --clean was used.\n check_mode:\n type: boolean\n description: Whether --check was used.\n has_differences:\n type: boolean\n description: In --check mode, whether differences were found.\n\n ValidationError:\n type: object\n required: [errors]\n properties:\n errors:\n type: array\n items:\n type: object\n required: [code, message]\n properties:\n code:\n type: string\n message:\n type: string\n path:\n type: string\n description: JSON path to the invalid element.\n\n # -------------------------------------------------------------------------\n # run\n # -------------------------------------------------------------------------\n WorkflowResult:\n type: object\n required: [workflow_id, status, steps, total_elapsed_ms]\n properties:\n workflow_id:\n type: string\n status:\n type: string\n enum: [completed, escalated, gate_rejected, error]\n steps:\n type: array\n items:\n $ref: "#/components/schemas/StepResult"\n total_elapsed_ms:\n type: integer\n minimum: 0\n escalation_reason:\n type: string\n error_message:\n type: string\n\n StepResult:\n type: object\n required: [step_index, retries_used, elapsed_ms, outcome]\n properties:\n step_index:\n type: integer\n minimum: 0\n task_id:\n type: string\n gate_kind:\n type: string\n outcome:\n type: object\n required: [status]\n properties:\n status:\n type: string\n enum: [success, validation_error, escalation, error, gate_approved, gate_rejected, skipped]\n retries_used:\n type: integer\n minimum: 0\n elapsed_ms:\n type: integer\n minimum: 0\n\n # -------------------------------------------------------------------------\n # list\n # -------------------------------------------------------------------------\n ListResult:\n type: object\n required: [resource, items]\n properties:\n resource:\n type: string\n enum: [workflows, tasks, agents]\n items:\n type: array\n items:\n type: object\n required: [id, description]\n properties:\n id:\n type: string\n description:\n type: string\n\n # -------------------------------------------------------------------------\n # show-prompt\n # -------------------------------------------------------------------------\n ShowPromptResult:\n type: object\n required: [task_id, agent_id, prompt]\n properties:\n task_id:\n type: string\n description: The task ID used to build the prompt.\n agent_id:\n type: string\n description: The target agent ID for this task.\n prompt:\n type: string\n description: The full generated prompt text.\n handoff_schema:\n type: string\n description: The handoff schema ID for the task result.\n plugins_applied:\n type: boolean\n description: Whether plugin prompt enhancers were applied.\n\n # -------------------------------------------------------------------------\n # doctor\n # -------------------------------------------------------------------------\n DoctorResult:\n type: object\n required: [checks, all_passed]\n properties:\n checks:\n type: array\n items:\n $ref: "#/components/schemas/DoctorCheck"\n all_passed:\n type: boolean\n\n # -------------------------------------------------------------------------\n # implement\n # -------------------------------------------------------------------------\n ImplementResult:\n type: object\n required: [files_created, files_modified, summary]\n properties:\n files_created:\n type: array\n items:\n type: string\n description: List of new files created.\n files_modified:\n type: array\n items:\n type: string\n description: List of existing files modified.\n summary:\n type: string\n description: Human-readable summary of what was implemented.\n commands_added:\n type: array\n items:\n type: object\n required: [name, type]\n properties:\n name:\n type: string\n type:\n type: string\n enum: [audit, propose, explain]\n description:\n type: string\n next_steps:\n type: array\n items:\n type: string\n description: Recommended next steps for the developer.\n\n # -------------------------------------------------------------------------\n # audit-implementation\n # -------------------------------------------------------------------------\n AuditImplementationResult:\n type: object\n required: [summary, riskLevel, findings]\n properties:\n summary:\n type: string\n description: One-paragraph overall assessment.\n riskLevel:\n type: string\n enum: [low, medium, high, critical]\n description: Derived from worst finding severity.\n findings:\n type: array\n items:\n $ref: "#/components/schemas/AgentFinding"\n recommendedActions:\n type: array\n items:\n $ref: "#/components/schemas/AgentRecommendedAction"\n metadata:\n type: object\n properties:\n tool:\n type: string\n command:\n type: string\n version:\n type: string\n generatedAt:\n type: string\n adapter:\n type: string\n model:\n type: string\n\n DoctorCheck:\n type: object\n required: [name, status]\n properties:\n name:\n type: string\n description: Check name (e.g. config_exists, dsl_exists, manifest_fresh).\n status:\n type: string\n enum: [pass, fail, warn]\n message:\n type: string\n description: Human-readable detail.\n\n # -------------------------------------------------------------------------\n # navigation-index\n # -------------------------------------------------------------------------\n NavigationIndexResult:\n type: object\n required: [version, generated_at, system, artifacts]\n properties:\n version:\n type: string\n generated_at:\n type: string\n system:\n type: object\n required: [id, name]\n properties:\n id:\n type: string\n name:\n type: string\n artifacts:\n type: object\n additionalProperties: true\n\n # -------------------------------------------------------------------------\n # Canonical agent result schemas (AgentAuditResult sub-types)\n # -------------------------------------------------------------------------\n AgentFinding:\n type: object\n required: [severity, category, message]\n properties:\n id:\n type: string\n description: Unique finding identifier (e.g. F-001).\n severity:\n type: string\n enum: [info, warning, error, critical]\n category:\n type: string\n description: Domain vocabulary category (e.g. cli-contract-options, runtime-adapter).\n target:\n type: string\n description: File path or resource the finding applies to.\n location:\n type: string\n description: Line range or specific location within the target.\n message:\n type: string\n description: Human-readable description of the finding.\n recommendation:\n type: string\n description: Concrete remediation step.\n confidence:\n type: number\n minimum: 0\n maximum: 1\n description: Confidence score (0\u20131) for the finding.\n evidence:\n type: array\n items:\n $ref: "#/components/schemas/AgentEvidence"\n details:\n type: object\n description: Additional structured details specific to the finding category.\n\n AgentRecommendedAction:\n type: object\n required: [kind, title]\n properties:\n kind:\n type: string\n enum: [run_command, edit_file, review, confirm, block, ignore]\n title:\n type: string\n description: Short human-readable title for the action.\n command:\n type: string\n description: Shell command to run (when kind is run_command).\n target:\n type: string\n description: File path to edit (when kind is edit_file).\n rationale:\n type: string\n description: Explanation of why this action is recommended.\n\n AgentEvidence:\n type: object\n required: [type, content]\n properties:\n type:\n type: string\n description: Evidence type (e.g. code_snippet, file_excerpt, lint_output).\n content:\n type: string\n description: The evidence content.\n source:\n type: string\n description: Source file path or URL for the evidence.\n';
|
|
32
|
-
var CONTRACT_JSON_STR = '{\n "cli_contracts": "0.1.0",\n "info": {\n "title": "agent-runtime CLI",\n "version": "0.36.15",\n "description": "Runtime bridge for executing agent-contracts workflows on Agent SDKs.\\nGenerates typed contracts, handoff validators, and guardrail hooks from DSL,\\nthen runs workflows through pluggable SDK adapters.\\n",\n "license": {\n "name": "MIT"\n }\n },\n "command_sets": {\n "agent-runtime": {\n "summary": "CLI for agent-contracts-runtime \u2014 generate, run, and manage agent workflows.",\n "global_options": [\n {\n "name": "config",\n "aliases": [\n "c"\n ],\n "description": "Path to agents.conf.yaml (project runtime config).",\n "schema": {\n "type": "string",\n "default": "./agents.conf.yaml"\n },\n "file": {\n "mode": "read",\n "exists": true,\n "media_type": "application/yaml"\n }\n },\n {\n "name": "verbose",\n "aliases": [\n "v"\n ],\n "description": "Enable verbose output.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "quiet",\n "aliases": [\n "q"\n ],\n "description": "Suppress non-error output.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n }\n ],\n "commands": {\n "init": {\n "summary": "Initialize runtime scaffolding for a project.",\n "description": "Generates the initial directory structure and configuration files\\nfor using agent-contracts-runtime in a project.\\nCreates agents.conf.yaml and agent/src/ user code templates.\\n",\n "options": [\n {\n "name": "adapter",\n "aliases": [\n "a"\n ],\n "description": "Default SDK adapter to configure.",\n "schema": {\n "type": "string",\n "enum": [\n "claude",\n "gemini",\n "openai",\n "mock"\n ],\n "default": "mock"\n }\n },\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Output directory for generated scaffolding.",\n "schema": {\n "type": "string",\n "default": "."\n }\n },\n {\n "name": "force",\n "aliases": [\n "f"\n ],\n "description": "Overwrite existing files without prompting.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Scaffolding generated successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/InitResult"\n }\n }\n },\n "1": {\n "description": "Initialization failed (existing files, permission error, etc.).",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": false,\n "sideEffects": [\n "filesystem_write"\n ],\n "safeDryRunOption": ""\n }\n },\n "generate": {\n "summary": "Generate runtime contracts and hooks from DSL.",\n "description": "Reads agent-contracts.yaml, resolves the DSL, validates it,\\nand generates typed contracts, handoff schemas, guardrail hooks,\\nand a runtime manifest into the configured generated_dir.\\n\\nEach generated file includes a DO NOT EDIT header.\\n",\n "options": [\n {\n "name": "clean",\n "description": "Delete generated_dir before regenerating.\\nRemoves stale files that may remain from previous generations.\\n",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "check",\n "description": "Dry-run mode for CI. Does not write files.\\nCompares current generated output with what would be regenerated.\\nExits with code 1 if any differences are found.\\n",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "templates",\n "aliases": [\n "t"\n ],\n "description": "Custom templates directory. Overrides built-in templates.",\n "schema": {\n "type": "string"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Generation completed successfully (or --check found no differences).",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/GenerateResult"\n }\n }\n },\n "1": {\n "description": "Generation failed, or --check detected differences between\\ncurrent generated files and expected output.\\n",\n "stderr": {\n "format": "text"\n }\n },\n "2": {\n "description": "DSL validation error. The input DSL has structural or semantic issues.",\n "stderr": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/ValidationError"\n }\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": [\n "filesystem_write"\n ],\n "safeDryRunOption": "check"\n }\n },\n "run": {\n "summary": "Execute a workflow.",\n "description": "Loads generated contracts, creates an SDK adapter, registers user plugins,\\nand executes the specified workflow with the given user request.\\n\\nThe workflow runner orchestrates task delegation, retry, gate handling,\\nand handoff validation mechanically.\\n",\n "arguments": [\n {\n "name": "workflow-id",\n "required": false,\n "description": "ID of the workflow to execute. Required unless --file is used.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "user-request",\n "required": false,\n "description": "Natural language description of what to do. Required unless --file is used.",\n "schema": {\n "type": "string"\n }\n }\n ],\n "options": [\n {\n "name": "adapter",\n "aliases": [\n "a"\n ],\n "description": "SDK adapter to use. Overrides config.",\n "schema": {\n "type": "string",\n "enum": [\n "claude",\n "gemini",\n "openai",\n "mock"\n ]\n }\n },\n {\n "name": "max-retries",\n "aliases": [\n "r"\n ],\n "description": "Override default max retries per step.",\n "schema": {\n "type": "integer",\n "minimum": 0,\n "maximum": 10\n }\n },\n {\n "name": "max-follow-ups",\n "aliases": [\n "f"\n ],\n "description": "Override default max follow-ups per step.",\n "schema": {\n "type": "integer",\n "minimum": 0,\n "maximum": 10\n }\n },\n {\n "name": "dry-run",\n "aliases": [\n "n"\n ],\n "description": "Simulate execution without calling the SDK adapter.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "auto-approve-gates",\n "description": "Automatically approve all gate steps.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "file",\n "description": "Path to a YAML invocation file. When provided, workflow-id and\\nuser-request arguments are read from the file instead of CLI args.\\n",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true,\n "media_type": "application/yaml"\n }\n },\n {\n "name": "log-file",\n "aliases": [\n "l"\n ],\n "description": "Write agent progress log to this file. Overrides config logging.progress_log.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Workflow completed successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/WorkflowResult"\n }\n }\n },\n "1": {\n "description": "Workflow failed (escalation, error, or gate rejection).",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/WorkflowResult"\n }\n },\n "stderr": {\n "format": "text"\n }\n },\n "3": {\n "description": "Input validation failed (invalid arguments, unknown workflow/adapter, or generated files outdated).",\n "stderr": {\n "format": "text"\n }\n },\n "12": {\n "description": "Adapter initialization error (missing API key, etc.).",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "high",\n "requiresConfirmation": true,\n "idempotent": false,\n "sideEffects": [\n "sdk_call",\n "filesystem_write"\n ],\n "safeDryRunOption": "dry-run",\n "expectedDurationMs": 300000,\n "recommendedBeforeUse": [\n "Run `agent-runtime generate --check` to ensure contracts are up to date.",\n "Run `agent-runtime doctor` to verify SDK configuration."\n ]\n }\n },\n "list": {\n "summary": "List available workflows, tasks, or agents.",\n "description": "Reads generated contracts and displays available resources.\\nUseful for discovering what workflows, tasks, and agents\\nare defined in the current project.\\n",\n "arguments": [\n {\n "name": "resource",\n "required": true,\n "description": "Type of resource to list.",\n "schema": {\n "type": "string",\n "enum": [\n "workflows",\n "tasks",\n "agents"\n ]\n }\n }\n ],\n "options": [\n {\n "name": "format",\n "description": "Output format.",\n "schema": {\n "type": "string",\n "enum": [\n "table",\n "json"\n ],\n "default": "table"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Resources listed successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/ListResult"\n }\n }\n },\n "1": {\n "description": "Failed to load contracts.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n },\n "show-prompt": {\n "summary": "Display the generated prompt for a task.",\n "description": "Builds and displays the full prompt that would be sent to an SDK agent\\nfor a given task. Useful for inspecting, debugging, and validating\\nprompt content before execution.\\n\\nShows the agent role, responsibilities, constraints, task details,\\ncompletion criteria, handoff schema fields, and output format example.\\n",\n "arguments": [\n {\n "name": "task-id",\n "required": true,\n "description": "ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).",\n "schema": {\n "type": "string"\n }\n }\n ],\n "options": [\n {\n "name": "user-request",\n "aliases": [\n "u"\n ],\n "description": "User request text to include in the prompt preview.",\n "schema": {\n "type": "string",\n "default": "(preview)"\n }\n },\n {\n "name": "format",\n "description": "Output format.",\n "schema": {\n "type": "string",\n "enum": [\n "markdown",\n "raw",\n "json"\n ],\n "default": "markdown"\n }\n },\n {\n "name": "with-plugins",\n "description": "Apply registered plugin prompt enhancers to the output.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Prompt displayed successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/ShowPromptResult"\n }\n }\n },\n "1": {\n "description": "Failed to build prompt (unknown task, missing contracts, etc.).",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n },\n "implement": {\n "summary": "Implement LLM-powered commands in a CLI tool.",\n "description": "Uses an agentic LLM adapter (Claude, etc.) to analyze the\\ntarget project and implement LLM-powered commands following the\\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\\n\\nThe agent reads the project structure, cli-contract.yaml, and existing\\ncode, then generates DSL definitions, TypeScript modules (orchestrator,\\ncontext-builder, formatter), CLI command handlers, and updates the\\nCLI contract with x-agent metadata.\\n\\nRequires an agentic adapter that supports tool use (file read/write).\\n",\n "arguments": [\n {\n "name": "description",\n "required": true,\n "description": "Natural language description of the LLM feature(s) to implement. Examples: \\"Add an audit command for migration safety\\", \\"Add propose and explain commands for SQL optimization\\".",\n "schema": {\n "type": "string"\n }\n }\n ],\n "options": [\n {\n "name": "adapter",\n "aliases": [\n "a"\n ],\n "description": "SDK adapter to use. Must be an agentic adapter (claude).",\n "schema": {\n "type": "string",\n "enum": [\n "claude",\n "mock"\n ],\n "default": "claude"\n }\n },\n {\n "name": "project-dir",\n "aliases": [\n "p"\n ],\n "description": "Path to the target project directory.",\n "schema": {\n "type": "string",\n "default": "."\n }\n },\n {\n "name": "dry-run",\n "aliases": [\n "n"\n ],\n "description": "Output the prompt context without calling the LLM.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "model",\n "description": "Model name override for the selected adapter.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Write the result to a file instead of stdout.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n },\n {\n "name": "report-format",\n "description": "Output format for the result.",\n "schema": {\n "type": "string",\n "enum": [\n "json",\n "text",\n "yaml"\n ],\n "default": "text"\n }\n },\n {\n "name": "log-file",\n "aliases": [\n "l"\n ],\n "description": "Write agent progress log to this file.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Implementation completed successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/ImplementResult"\n }\n }\n },\n "1": {\n "description": "Implementation failed.",\n "stderr": {\n "format": "text"\n }\n },\n "3": {\n "description": "Input validation failed (e.g. project directory not found).",\n "stderr": {\n "format": "text"\n }\n },\n "12": {\n "description": "Adapter initialization error.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "high",\n "requiresConfirmation": true,\n "idempotent": false,\n "sideEffects": [\n "sdk_call",\n "filesystem_write"\n ],\n "safeDryRunOption": "dry-run",\n "expectedDurationMs": 300000,\n "retryableExitCodes": [\n 1,\n 12\n ],\n "recommendedBeforeUse": [\n "Ensure the target project has a cli-contract.yaml or plan to create one.",\n "Run in a clean git working tree so changes can be reviewed."\n ]\n }\n },\n "audit-implementation": {\n "summary": "Audit an LLM command integration for pattern conformance.",\n "description": "Analyzes a target project\'s LLM command integration to verify it\\ncorrectly follows the agent-contracts + agent-contracts-runtime +\\ncli-contracts stack conventions.\\n\\nChecks all three layers:\\n1. DSL definitions (agents, tasks, workflows, handoff schemas)\\n2. Runtime integration (adapter usage, runTask/runWorkflow, registries)\\n3. CLI contract (standard options, x-agent metadata, exit codes)\\n\\nProduces structured findings with severity, category, and\\nconcrete remediation steps. Read-only \u2014 does not modify files.\\n",\n "arguments": [\n {\n "name": "project-dir",\n "required": false,\n "description": "Path to the project directory to audit. Defaults to current directory.",\n "schema": {\n "type": "string"\n }\n }\n ],\n "options": [\n {\n "name": "adapter",\n "aliases": [\n "a"\n ],\n "description": "SDK adapter to use for the audit agent.",\n "schema": {\n "type": "string",\n "enum": [\n "claude",\n "mock"\n ],\n "default": "claude"\n }\n },\n {\n "name": "focus",\n "description": "Limit audit to a specific layer. Defaults to all layers.",\n "schema": {\n "type": "string",\n "enum": [\n "all",\n "dsl",\n "runtime",\n "cli-contract",\n "architecture"\n ],\n "default": "all"\n }\n },\n {\n "name": "dry-run",\n "aliases": [\n "n"\n ],\n "description": "Output the prompt context without calling the LLM.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "fail-on",\n "description": "Minimum finding severity that causes a non-zero exit.",\n "schema": {\n "type": "string",\n "enum": [\n "warning",\n "error",\n "critical"\n ],\n "default": "error"\n }\n },\n {\n "name": "model",\n "description": "Model name override for the selected adapter.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Write the result to a file instead of stdout.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n },\n {\n "name": "report-format",\n "description": "Output format for the audit report.",\n "schema": {\n "type": "string",\n "enum": [\n "json",\n "text",\n "yaml"\n ],\n "default": "text"\n }\n },\n {\n "name": "log-file",\n "aliases": [\n "l"\n ],\n "description": "Write agent progress log to this file.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Audit completed with no findings above threshold.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/AuditImplementationResult"\n }\n }\n },\n "1": {\n "description": "Audit failed (agent error, unexpected failure).",\n "stderr": {\n "format": "text"\n }\n },\n "3": {\n "description": "Input validation failed (e.g. project directory not found).",\n "stderr": {\n "format": "text"\n }\n },\n "10": {\n "description": "Audit completed with findings above --fail-on threshold.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/AuditImplementationResult"\n }\n }\n },\n "12": {\n "description": "Adapter initialization error.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": [\n "network"\n ],\n "sideEffectNote": "Network calls to LLM provider when adapter is not mock. Filesystem write only when --output is specified.",\n "safeDryRunOption": "dry-run",\n "expectedDurationMs": 180000,\n "retryableExitCodes": [\n 1,\n 12\n ]\n }\n },\n "agents": {\n "summary": "Output the full resolved DSL as structured data.",\n "description": "Outputs the complete resolved DSL (agents, tasks, workflows,\\nhandoff_types, etc.) embedded in this CLI binary.\\n\\nUseful for debugging, external tooling integration, and DSL\\ninspection. Unlike `list`, which shows tabular summaries,\\nthis command outputs the full DSL structure.\\n",\n "options": [\n {\n "name": "format",\n "aliases": [\n "F"\n ],\n "description": "Output format.",\n "schema": {\n "type": "string",\n "enum": [\n "yaml",\n "json"\n ],\n "default": "yaml"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "DSL output successfully.",\n "stdout": {\n "format": "text"\n }\n },\n "1": {\n "description": "Failed to load embedded DSL.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n },\n "doctor": {\n "summary": "Verify configuration, generated files, and SDK connectivity.",\n "description": "Runs a series of diagnostic checks to verify that the project\\nis correctly configured for agent-runtime execution.\\n\\nChecks: config existence, DSL existence, generated manifest freshness,\\nadapter configuration, API key environment variables, plugin entrypoint.\\n",\n "exits": {\n "0": {\n "description": "All checks passed.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/DoctorResult"\n }\n }\n },\n "1": {\n "description": "One or more checks failed.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/DoctorResult"\n }\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n },\n "navigation-index": {\n "summary": "Build artifact navigation index from resolved DSL.",\n "description": "Resolves the embedded DSL (merged with project overlay if configured),\\napplies artifact binding, and builds a navigation index showing\\nartifact-to-tool-to-agent mappings.\\n\\nThe output is a JSON/YAML structure suitable for IDE integration,\\nrouting rules, and artifact coverage analysis.\\n",\n "options": [\n {\n "name": "format",\n "aliases": [\n "F"\n ],\n "description": "Output format.",\n "schema": {\n "type": "string",\n "enum": [\n "json",\n "yaml"\n ],\n "default": "json"\n }\n },\n {\n "name": "artifact",\n "description": "Filter output to a single artifact by ID.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Write output to a file instead of stdout.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Navigation index built successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/NavigationIndexResult"\n }\n }\n },\n "1": {\n "description": "Failed to build navigation index.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n }\n }\n }\n },\n "components": {\n "schemas": {\n "InitResult": {\n "type": "object",\n "required": [\n "files_created"\n ],\n "properties": {\n "files_created": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of files created by init."\n }\n }\n },\n "GenerateResult": {\n "type": "object",\n "required": [\n "files_generated",\n "dsl_hash",\n "generation_input_hash"\n ],\n "properties": {\n "files_generated": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of generated file paths."\n },\n "dsl_hash": {\n "type": "string",\n "description": "SHA-256 hash of the resolved DSL (canonical stringify)."\n },\n "generation_input_hash": {\n "type": "string",\n "description": "SHA-256 hash of all generation inputs."\n },\n "cleaned": {\n "type": "boolean",\n "description": "Whether --clean was used."\n },\n "check_mode": {\n "type": "boolean",\n "description": "Whether --check was used."\n },\n "has_differences": {\n "type": "boolean",\n "description": "In --check mode, whether differences were found."\n }\n }\n },\n "ValidationError": {\n "type": "object",\n "required": [\n "errors"\n ],\n "properties": {\n "errors": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "code",\n "message"\n ],\n "properties": {\n "code": {\n "type": "string"\n },\n "message": {\n "type": "string"\n },\n "path": {\n "type": "string",\n "description": "JSON path to the invalid element."\n }\n }\n }\n }\n }\n },\n "WorkflowResult": {\n "type": "object",\n "required": [\n "workflow_id",\n "status",\n "steps",\n "total_elapsed_ms"\n ],\n "properties": {\n "workflow_id": {\n "type": "string"\n },\n "status": {\n "type": "string",\n "enum": [\n "completed",\n "escalated",\n "gate_rejected",\n "error"\n ]\n },\n "steps": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/StepResult"\n }\n },\n "total_elapsed_ms": {\n "type": "integer",\n "minimum": 0\n },\n "escalation_reason": {\n "type": "string"\n },\n "error_message": {\n "type": "string"\n }\n }\n },\n "StepResult": {\n "type": "object",\n "required": [\n "step_index",\n "retries_used",\n "elapsed_ms",\n "outcome"\n ],\n "properties": {\n "step_index": {\n "type": "integer",\n "minimum": 0\n },\n "task_id": {\n "type": "string"\n },\n "gate_kind": {\n "type": "string"\n },\n "outcome": {\n "type": "object",\n "required": [\n "status"\n ],\n "properties": {\n "status": {\n "type": "string",\n "enum": [\n "success",\n "validation_error",\n "escalation",\n "error",\n "gate_approved",\n "gate_rejected",\n "skipped"\n ]\n }\n }\n },\n "retries_used": {\n "type": "integer",\n "minimum": 0\n },\n "elapsed_ms": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "ListResult": {\n "type": "object",\n "required": [\n "resource",\n "items"\n ],\n "properties": {\n "resource": {\n "type": "string",\n "enum": [\n "workflows",\n "tasks",\n "agents"\n ]\n },\n "items": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "id",\n "description"\n ],\n "properties": {\n "id": {\n "type": "string"\n },\n "description": {\n "type": "string"\n }\n }\n }\n }\n }\n },\n "ShowPromptResult": {\n "type": "object",\n "required": [\n "task_id",\n "agent_id",\n "prompt"\n ],\n "properties": {\n "task_id": {\n "type": "string",\n "description": "The task ID used to build the prompt."\n },\n "agent_id": {\n "type": "string",\n "description": "The target agent ID for this task."\n },\n "prompt": {\n "type": "string",\n "description": "The full generated prompt text."\n },\n "handoff_schema": {\n "type": "string",\n "description": "The handoff schema ID for the task result."\n },\n "plugins_applied": {\n "type": "boolean",\n "description": "Whether plugin prompt enhancers were applied."\n }\n }\n },\n "DoctorResult": {\n "type": "object",\n "required": [\n "checks",\n "all_passed"\n ],\n "properties": {\n "checks": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/DoctorCheck"\n }\n },\n "all_passed": {\n "type": "boolean"\n }\n }\n },\n "ImplementResult": {\n "type": "object",\n "required": [\n "files_created",\n "files_modified",\n "summary"\n ],\n "properties": {\n "files_created": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of new files created."\n },\n "files_modified": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of existing files modified."\n },\n "summary": {\n "type": "string",\n "description": "Human-readable summary of what was implemented."\n },\n "commands_added": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "name",\n "type"\n ],\n "properties": {\n "name": {\n "type": "string"\n },\n "type": {\n "type": "string",\n "enum": [\n "audit",\n "propose",\n "explain"\n ]\n },\n "description": {\n "type": "string"\n }\n }\n }\n },\n "next_steps": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "Recommended next steps for the developer."\n }\n }\n },\n "AuditImplementationResult": {\n "type": "object",\n "required": [\n "summary",\n "riskLevel",\n "findings"\n ],\n "properties": {\n "summary": {\n "type": "string",\n "description": "One-paragraph overall assessment."\n },\n "riskLevel": {\n "type": "string",\n "enum": [\n "low",\n "medium",\n "high",\n "critical"\n ],\n "description": "Derived from worst finding severity."\n },\n "findings": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/AgentFinding"\n }\n },\n "recommendedActions": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/AgentRecommendedAction"\n }\n },\n "metadata": {\n "type": "object",\n "properties": {\n "tool": {\n "type": "string"\n },\n "command": {\n "type": "string"\n },\n "version": {\n "type": "string"\n },\n "generatedAt": {\n "type": "string"\n },\n "adapter": {\n "type": "string"\n },\n "model": {\n "type": "string"\n }\n }\n }\n }\n },\n "DoctorCheck": {\n "type": "object",\n "required": [\n "name",\n "status"\n ],\n "properties": {\n "name": {\n "type": "string",\n "description": "Check name (e.g. config_exists, dsl_exists, manifest_fresh)."\n },\n "status": {\n "type": "string",\n "enum": [\n "pass",\n "fail",\n "warn"\n ]\n },\n "message": {\n "type": "string",\n "description": "Human-readable detail."\n }\n }\n },\n "NavigationIndexResult": {\n "type": "object",\n "required": [\n "version",\n "generated_at",\n "system",\n "artifacts"\n ],\n "properties": {\n "version": {\n "type": "string"\n },\n "generated_at": {\n "type": "string"\n },\n "system": {\n "type": "object",\n "required": [\n "id",\n "name"\n ],\n "properties": {\n "id": {\n "type": "string"\n },\n "name": {\n "type": "string"\n }\n }\n },\n "artifacts": {\n "type": "object",\n "additionalProperties": true\n }\n }\n },\n "AgentFinding": {\n "type": "object",\n "required": [\n "severity",\n "category",\n "message"\n ],\n "properties": {\n "id": {\n "type": "string",\n "description": "Unique finding identifier (e.g. F-001)."\n },\n "severity": {\n "type": "string",\n "enum": [\n "info",\n "warning",\n "error",\n "critical"\n ]\n },\n "category": {\n "type": "string",\n "description": "Domain vocabulary category (e.g. cli-contract-options, runtime-adapter)."\n },\n "target": {\n "type": "string",\n "description": "File path or resource the finding applies to."\n },\n "location": {\n "type": "string",\n "description": "Line range or specific location within the target."\n },\n "message": {\n "type": "string",\n "description": "Human-readable description of the finding."\n },\n "recommendation": {\n "type": "string",\n "description": "Concrete remediation step."\n },\n "confidence": {\n "type": "number",\n "minimum": 0,\n "maximum": 1,\n "description": "Confidence score (0\u20131) for the finding."\n },\n "evidence": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/AgentEvidence"\n }\n },\n "details": {\n "type": "object",\n "description": "Additional structured details specific to the finding category."\n }\n }\n },\n "AgentRecommendedAction": {\n "type": "object",\n "required": [\n "kind",\n "title"\n ],\n "properties": {\n "kind": {\n "type": "string",\n "enum": [\n "run_command",\n "edit_file",\n "review",\n "confirm",\n "block",\n "ignore"\n ]\n },\n "title": {\n "type": "string",\n "description": "Short human-readable title for the action."\n },\n "command": {\n "type": "string",\n "description": "Shell command to run (when kind is run_command)."\n },\n "target": {\n "type": "string",\n "description": "File path to edit (when kind is edit_file)."\n },\n "rationale": {\n "type": "string",\n "description": "Explanation of why this action is recommended."\n }\n }\n },\n "AgentEvidence": {\n "type": "object",\n "required": [\n "type",\n "content"\n ],\n "properties": {\n "type": {\n "type": "string",\n "description": "Evidence type (e.g. code_snippet, file_excerpt, lint_output)."\n },\n "content": {\n "type": "string",\n "description": "The evidence content."\n },\n "source": {\n "type": "string",\n "description": "Source file path or URL for the evidence."\n }\n }\n }\n }\n }\n}';
|
|
29
|
+
var CONTRACT_YAML = 'cli_contracts: 0.1.0\n\ninfo:\n title: agent-runtime CLI\n version: 0.36.17\n description: |\n Runtime bridge for executing agent-contracts workflows on Agent SDKs.\n Generates typed contracts, handoff validators, and guardrail hooks from DSL,\n then runs workflows through pluggable SDK adapters.\n license:\n name: MIT\n\ncommand_sets:\n agent-runtime:\n summary: CLI for agent-contracts-runtime \u2014 generate, run, and manage agent workflows.\n global_options:\n - name: config\n aliases: [c]\n description: Path to agents.conf.yaml (project runtime config).\n schema:\n type: string\n default: ./agents.conf.yaml\n file:\n mode: read\n exists: true\n media_type: application/yaml\n\n - name: verbose\n aliases: [v]\n description: Enable verbose output.\n schema:\n type: boolean\n default: false\n\n - name: quiet\n aliases: [q]\n description: Suppress non-error output.\n schema:\n type: boolean\n default: false\n\n commands:\n # -----------------------------------------------------------------------\n # init\n # -----------------------------------------------------------------------\n init:\n summary: Initialize runtime scaffolding for a project.\n description: |\n Generates the initial directory structure and configuration files\n for using agent-contracts-runtime in a project.\n Creates agents.conf.yaml and agent/src/ user code templates.\n options:\n - name: adapter\n aliases: [a]\n description: Default SDK adapter to configure.\n schema:\n type: string\n enum: [claude, openai, mock]\n default: mock\n\n - name: output\n aliases: [o]\n description: Output directory for generated scaffolding.\n schema:\n type: string\n default: "."\n\n - name: force\n aliases: [f]\n description: Overwrite existing files without prompting.\n schema:\n type: boolean\n default: false\n\n exits:\n "0":\n description: Scaffolding generated successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/InitResult"\n\n "1":\n description: Initialization failed (existing files, permission error, etc.).\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: false\n sideEffects:\n - filesystem_write\n safeDryRunOption: ""\n\n # -----------------------------------------------------------------------\n # generate\n # -----------------------------------------------------------------------\n generate:\n summary: Generate runtime contracts and hooks from DSL.\n description: |\n Reads agent-contracts.yaml, resolves the DSL, validates it,\n and generates typed contracts, handoff schemas, guardrail hooks,\n and a runtime manifest into the configured generated_dir.\n\n Each generated file includes a DO NOT EDIT header.\n options:\n - name: clean\n description: |\n Delete generated_dir before regenerating.\n Removes stale files that may remain from previous generations.\n schema:\n type: boolean\n default: false\n\n - name: check\n description: |\n Dry-run mode for CI. Does not write files.\n Compares current generated output with what would be regenerated.\n Exits with code 1 if any differences are found.\n schema:\n type: boolean\n default: false\n\n - name: templates\n aliases: [t]\n description: Custom templates directory. Overrides built-in templates.\n schema:\n type: string\n\n exits:\n "0":\n description: Generation completed successfully (or --check found no differences).\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/GenerateResult"\n\n "1":\n description: |\n Generation failed, or --check detected differences between\n current generated files and expected output.\n stderr:\n format: text\n\n "2":\n description: DSL validation error. The input DSL has structural or semantic issues.\n stderr:\n format: json\n schema:\n $ref: "#/components/schemas/ValidationError"\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects:\n - filesystem_write\n safeDryRunOption: check\n\n # -----------------------------------------------------------------------\n # run\n # -----------------------------------------------------------------------\n run:\n summary: Execute a workflow.\n description: |\n Loads generated contracts, creates an SDK adapter, registers user plugins,\n and executes the specified workflow with the given user request.\n\n The workflow runner orchestrates task delegation, retry, gate handling,\n and handoff validation mechanically.\n arguments:\n - name: workflow-id\n required: false\n description: ID of the workflow to execute. Required unless --file is used.\n schema:\n type: string\n\n - name: user-request\n required: false\n description: Natural language description of what to do. Required unless --file is used.\n schema:\n type: string\n\n options:\n - name: adapter\n aliases: [a]\n description: SDK adapter to use. Overrides config.\n schema:\n type: string\n enum: [claude, openai, mock]\n\n - name: max-retries\n aliases: [r]\n description: Override default max retries per step.\n schema:\n type: integer\n minimum: 0\n maximum: 10\n\n - name: max-follow-ups\n aliases: [f]\n description: Override default max follow-ups per step.\n schema:\n type: integer\n minimum: 0\n maximum: 10\n\n - name: dry-run\n aliases: [n]\n description: Simulate execution without calling the SDK adapter.\n schema:\n type: boolean\n default: false\n\n - name: auto-approve-gates\n description: Automatically approve all gate steps.\n schema:\n type: boolean\n default: false\n\n - name: file\n description: |\n Path to a YAML invocation file. When provided, workflow-id and\n user-request arguments are read from the file instead of CLI args.\n schema:\n type: string\n file:\n mode: read\n exists: true\n media_type: application/yaml\n\n - name: log-file\n aliases: [l]\n description: Write agent progress log to this file. Overrides config logging.progress_log.\n schema:\n type: string\n file:\n mode: write\n\n exits:\n "0":\n description: Workflow completed successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/WorkflowResult"\n\n "1":\n description: Workflow failed (escalation, error, or gate rejection).\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/WorkflowResult"\n stderr:\n format: text\n\n "3":\n description: >-\n Input validation failed (invalid arguments, unknown workflow/adapter,\n or generated files outdated).\n stderr:\n format: text\n\n "12":\n description: Adapter initialization error (missing API key, etc.).\n stderr:\n format: text\n\n x-agent:\n riskLevel: high\n requiresConfirmation: true\n idempotent: false\n sideEffects:\n - sdk_call\n - filesystem_write\n safeDryRunOption: dry-run\n expectedDurationMs: 300000\n recommendedBeforeUse:\n - Run `agent-runtime generate --check` to ensure contracts are up to date.\n - Run `agent-runtime doctor` to verify SDK configuration.\n\n # -----------------------------------------------------------------------\n # list\n # -----------------------------------------------------------------------\n list:\n summary: List available workflows, tasks, or agents.\n description: |\n Reads generated contracts and displays available resources.\n Useful for discovering what workflows, tasks, and agents\n are defined in the current project.\n arguments:\n - name: resource\n required: true\n description: Type of resource to list.\n schema:\n type: string\n enum: [workflows, tasks, agents]\n\n options:\n - name: format\n description: Output format.\n schema:\n type: string\n enum: [table, json]\n default: table\n\n exits:\n "0":\n description: Resources listed successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/ListResult"\n\n "1":\n description: Failed to load contracts.\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n # -----------------------------------------------------------------------\n # show-prompt\n # -----------------------------------------------------------------------\n show-prompt:\n summary: Display the generated prompt for a task.\n description: |\n Builds and displays the full prompt that would be sent to an SDK agent\n for a given task. Useful for inspecting, debugging, and validating\n prompt content before execution.\n\n Shows the agent role, responsibilities, constraints, task details,\n completion criteria, handoff schema fields, and output format example.\n arguments:\n - name: task-id\n required: true\n description: ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).\n schema:\n type: string\n\n options:\n - name: user-request\n aliases: [u]\n description: User request text to include in the prompt preview.\n schema:\n type: string\n default: "(preview)"\n\n - name: format\n description: Output format.\n schema:\n type: string\n enum: [markdown, raw, json]\n default: markdown\n\n - name: with-plugins\n description: Apply registered plugin prompt enhancers to the output.\n schema:\n type: boolean\n default: false\n\n exits:\n "0":\n description: Prompt displayed successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/ShowPromptResult"\n\n "1":\n description: Failed to build prompt (unknown task, missing contracts, etc.).\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n # -----------------------------------------------------------------------\n # implement\n # -----------------------------------------------------------------------\n implement:\n summary: Implement LLM-powered commands in a CLI tool.\n description: |\n Uses an agentic LLM adapter (Claude, etc.) to analyze the\n target project and implement LLM-powered commands following the\n agent-contracts + agent-contracts-runtime + cli-contracts stack.\n\n The agent reads the project structure, cli-contract.yaml, and existing\n code, then generates DSL definitions, TypeScript modules (orchestrator,\n context-builder, formatter), CLI command handlers, and updates the\n CLI contract with x-agent metadata.\n\n Requires an agentic adapter that supports tool use (file read/write).\n arguments:\n - name: description\n required: true\n description: >-\n Natural language description of the LLM feature(s) to implement.\n Examples: "Add an audit command for migration safety",\n "Add propose and explain commands for SQL optimization".\n schema:\n type: string\n\n options:\n - name: adapter\n aliases: [a]\n description: SDK adapter to use. Must be an agentic adapter (claude).\n schema:\n type: string\n enum: [claude, mock]\n default: claude\n\n - name: project-dir\n aliases: [p]\n description: Path to the target project directory.\n schema:\n type: string\n default: "."\n\n - name: dry-run\n aliases: [n]\n description: Output the prompt context without calling the LLM.\n schema:\n type: boolean\n default: false\n\n - name: model\n description: Model name override for the selected adapter.\n schema:\n type: string\n\n - name: output\n aliases: [o]\n description: Write the result to a file instead of stdout.\n schema:\n type: string\n file:\n mode: write\n\n - name: report-format\n description: Output format for the result.\n schema:\n type: string\n enum: [json, text, yaml]\n default: text\n\n - name: log-file\n aliases: [l]\n description: Write agent progress log to this file.\n schema:\n type: string\n file:\n mode: write\n\n exits:\n "0":\n description: Implementation completed successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/ImplementResult"\n\n "1":\n description: Implementation failed.\n stderr:\n format: text\n\n "3":\n description: Input validation failed (e.g. project directory not found).\n stderr:\n format: text\n\n "12":\n description: Adapter initialization error.\n stderr:\n format: text\n\n x-agent:\n riskLevel: high\n requiresConfirmation: true\n idempotent: false\n sideEffects:\n - sdk_call\n - filesystem_write\n safeDryRunOption: dry-run\n expectedDurationMs: 300000\n retryableExitCodes: [1, 12]\n recommendedBeforeUse:\n - Ensure the target project has a cli-contract.yaml or plan to create one.\n - Run in a clean git working tree so changes can be reviewed.\n\n # -----------------------------------------------------------------------\n # audit-implementation\n # -----------------------------------------------------------------------\n audit-implementation:\n summary: Audit an LLM command integration for pattern conformance.\n description: |\n Analyzes a target project\'s LLM command integration to verify it\n correctly follows the agent-contracts + agent-contracts-runtime +\n cli-contracts stack conventions.\n\n Checks all three layers:\n 1. DSL definitions (agents, tasks, workflows, handoff schemas)\n 2. Runtime integration (adapter usage, runTask/runWorkflow, registries)\n 3. CLI contract (standard options, x-agent metadata, exit codes)\n\n Produces structured findings with severity, category, and\n concrete remediation steps. Read-only \u2014 does not modify files.\n arguments:\n - name: project-dir\n required: false\n description: >-\n Path to the project directory to audit. Defaults to current directory.\n schema:\n type: string\n\n options:\n - name: adapter\n aliases: [a]\n description: SDK adapter to use for the audit agent.\n schema:\n type: string\n enum: [claude, mock]\n default: claude\n\n - name: focus\n description: >-\n Limit audit to a specific layer. Defaults to all layers.\n schema:\n type: string\n enum: [all, dsl, runtime, cli-contract, architecture]\n default: all\n\n - name: dry-run\n aliases: [n]\n description: Output the prompt context without calling the LLM.\n schema:\n type: boolean\n default: false\n\n - name: fail-on\n description: Minimum finding severity that causes a non-zero exit.\n schema:\n type: string\n enum: [warning, error, critical]\n default: error\n\n - name: model\n description: Model name override for the selected adapter.\n schema:\n type: string\n\n - name: output\n aliases: [o]\n description: Write the result to a file instead of stdout.\n schema:\n type: string\n file:\n mode: write\n\n - name: report-format\n description: Output format for the audit report.\n schema:\n type: string\n enum: [json, text, yaml]\n default: text\n\n - name: log-file\n aliases: [l]\n description: Write agent progress log to this file.\n schema:\n type: string\n file:\n mode: write\n\n exits:\n "0":\n description: Audit completed with no findings above threshold.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/AuditImplementationResult"\n\n "1":\n description: Audit failed (agent error, unexpected failure).\n stderr:\n format: text\n\n "3":\n description: Input validation failed (e.g. project directory not found).\n stderr:\n format: text\n\n "10":\n description: Audit completed with findings above --fail-on threshold.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/AuditImplementationResult"\n\n "12":\n description: Adapter initialization error.\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects:\n - network\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: dry-run\n expectedDurationMs: 180000\n retryableExitCodes: [1, 12]\n\n # -----------------------------------------------------------------------\n # agents\n # -----------------------------------------------------------------------\n agents:\n summary: Output the full resolved DSL as structured data.\n description: |\n Outputs the complete resolved DSL (agents, tasks, workflows,\n handoff_types, etc.) embedded in this CLI binary.\n\n Useful for debugging, external tooling integration, and DSL\n inspection. Unlike `list`, which shows tabular summaries,\n this command outputs the full DSL structure.\n options:\n - name: format\n aliases: [F]\n description: Output format.\n schema:\n type: string\n enum: [yaml, json]\n default: yaml\n\n exits:\n "0":\n description: DSL output successfully.\n stdout:\n format: text\n\n "1":\n description: Failed to load embedded DSL.\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n # -----------------------------------------------------------------------\n # doctor\n # -----------------------------------------------------------------------\n doctor:\n summary: Verify configuration, generated files, and SDK connectivity.\n description: |\n Runs a series of diagnostic checks to verify that the project\n is correctly configured for agent-runtime execution.\n\n Checks: config existence, DSL existence, generated manifest freshness,\n adapter configuration, API key environment variables, plugin entrypoint.\n exits:\n "0":\n description: All checks passed.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/DoctorResult"\n\n "1":\n description: One or more checks failed.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/DoctorResult"\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n # -----------------------------------------------------------------------\n # navigation-index\n # -----------------------------------------------------------------------\n navigation-index:\n summary: Build artifact navigation index from resolved DSL.\n description: |\n Resolves the embedded DSL (merged with project overlay if configured),\n applies artifact binding, and builds a navigation index showing\n artifact-to-tool-to-agent mappings.\n\n The output is a JSON/YAML structure suitable for IDE integration,\n routing rules, and artifact coverage analysis.\n options:\n - name: format\n aliases: [F]\n description: Output format.\n schema:\n type: string\n enum: [json, yaml]\n default: json\n\n - name: artifact\n description: Filter output to a single artifact by ID.\n schema:\n type: string\n\n - name: output\n aliases: [o]\n description: Write output to a file instead of stdout.\n schema:\n type: string\n file:\n mode: write\n\n exits:\n "0":\n description: Navigation index built successfully.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/NavigationIndexResult"\n\n "1":\n description: Failed to build navigation index.\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n\n# =============================================================================\n# Components\n# =============================================================================\n\ncomponents:\n schemas:\n # -------------------------------------------------------------------------\n # init\n # -------------------------------------------------------------------------\n InitResult:\n type: object\n required: [files_created]\n properties:\n files_created:\n type: array\n items:\n type: string\n description: List of files created by init.\n\n # -------------------------------------------------------------------------\n # generate\n # -------------------------------------------------------------------------\n GenerateResult:\n type: object\n required: [files_generated, dsl_hash, generation_input_hash]\n properties:\n files_generated:\n type: array\n items:\n type: string\n description: List of generated file paths.\n dsl_hash:\n type: string\n description: SHA-256 hash of the resolved DSL (canonical stringify).\n generation_input_hash:\n type: string\n description: SHA-256 hash of all generation inputs.\n cleaned:\n type: boolean\n description: Whether --clean was used.\n check_mode:\n type: boolean\n description: Whether --check was used.\n has_differences:\n type: boolean\n description: In --check mode, whether differences were found.\n\n ValidationError:\n type: object\n required: [errors]\n properties:\n errors:\n type: array\n items:\n type: object\n required: [code, message]\n properties:\n code:\n type: string\n message:\n type: string\n path:\n type: string\n description: JSON path to the invalid element.\n\n # -------------------------------------------------------------------------\n # run\n # -------------------------------------------------------------------------\n WorkflowResult:\n type: object\n required: [workflow_id, status, steps, total_elapsed_ms]\n properties:\n workflow_id:\n type: string\n status:\n type: string\n enum: [completed, escalated, gate_rejected, error]\n steps:\n type: array\n items:\n $ref: "#/components/schemas/StepResult"\n total_elapsed_ms:\n type: integer\n minimum: 0\n escalation_reason:\n type: string\n error_message:\n type: string\n\n StepResult:\n type: object\n required: [step_index, retries_used, elapsed_ms, outcome]\n properties:\n step_index:\n type: integer\n minimum: 0\n task_id:\n type: string\n gate_kind:\n type: string\n outcome:\n type: object\n required: [status]\n properties:\n status:\n type: string\n enum: [success, validation_error, escalation, error, gate_approved, gate_rejected, skipped]\n retries_used:\n type: integer\n minimum: 0\n elapsed_ms:\n type: integer\n minimum: 0\n\n # -------------------------------------------------------------------------\n # list\n # -------------------------------------------------------------------------\n ListResult:\n type: object\n required: [resource, items]\n properties:\n resource:\n type: string\n enum: [workflows, tasks, agents]\n items:\n type: array\n items:\n type: object\n required: [id, description]\n properties:\n id:\n type: string\n description:\n type: string\n\n # -------------------------------------------------------------------------\n # show-prompt\n # -------------------------------------------------------------------------\n ShowPromptResult:\n type: object\n required: [task_id, agent_id, prompt]\n properties:\n task_id:\n type: string\n description: The task ID used to build the prompt.\n agent_id:\n type: string\n description: The target agent ID for this task.\n prompt:\n type: string\n description: The full generated prompt text.\n handoff_schema:\n type: string\n description: The handoff schema ID for the task result.\n plugins_applied:\n type: boolean\n description: Whether plugin prompt enhancers were applied.\n\n # -------------------------------------------------------------------------\n # doctor\n # -------------------------------------------------------------------------\n DoctorResult:\n type: object\n required: [checks, all_passed]\n properties:\n checks:\n type: array\n items:\n $ref: "#/components/schemas/DoctorCheck"\n all_passed:\n type: boolean\n\n # -------------------------------------------------------------------------\n # implement\n # -------------------------------------------------------------------------\n ImplementResult:\n type: object\n required: [files_created, files_modified, summary]\n properties:\n files_created:\n type: array\n items:\n type: string\n description: List of new files created.\n files_modified:\n type: array\n items:\n type: string\n description: List of existing files modified.\n summary:\n type: string\n description: Human-readable summary of what was implemented.\n commands_added:\n type: array\n items:\n type: object\n required: [name, type]\n properties:\n name:\n type: string\n type:\n type: string\n enum: [audit, propose, explain]\n description:\n type: string\n next_steps:\n type: array\n items:\n type: string\n description: Recommended next steps for the developer.\n\n # -------------------------------------------------------------------------\n # audit-implementation\n # -------------------------------------------------------------------------\n AuditImplementationResult:\n type: object\n required: [summary, riskLevel, findings]\n properties:\n summary:\n type: string\n description: One-paragraph overall assessment.\n riskLevel:\n type: string\n enum: [low, medium, high, critical]\n description: Derived from worst finding severity.\n findings:\n type: array\n items:\n $ref: "#/components/schemas/AgentFinding"\n recommendedActions:\n type: array\n items:\n $ref: "#/components/schemas/AgentRecommendedAction"\n metadata:\n type: object\n properties:\n tool:\n type: string\n command:\n type: string\n version:\n type: string\n generatedAt:\n type: string\n adapter:\n type: string\n model:\n type: string\n\n DoctorCheck:\n type: object\n required: [name, status]\n properties:\n name:\n type: string\n description: Check name (e.g. config_exists, dsl_exists, manifest_fresh).\n status:\n type: string\n enum: [pass, fail, warn]\n message:\n type: string\n description: Human-readable detail.\n\n # -------------------------------------------------------------------------\n # navigation-index\n # -------------------------------------------------------------------------\n NavigationIndexResult:\n type: object\n required: [version, generated_at, system, artifacts]\n properties:\n version:\n type: string\n generated_at:\n type: string\n system:\n type: object\n required: [id, name]\n properties:\n id:\n type: string\n name:\n type: string\n artifacts:\n type: object\n additionalProperties: true\n\n # -------------------------------------------------------------------------\n # Canonical agent result schemas (AgentAuditResult sub-types)\n # -------------------------------------------------------------------------\n AgentFinding:\n type: object\n required: [severity, category, message]\n properties:\n id:\n type: string\n description: Unique finding identifier (e.g. F-001).\n severity:\n type: string\n enum: [info, warning, error, critical]\n category:\n type: string\n description: Domain vocabulary category (e.g. cli-contract-options, runtime-adapter).\n target:\n type: string\n description: File path or resource the finding applies to.\n location:\n type: string\n description: Line range or specific location within the target.\n message:\n type: string\n description: Human-readable description of the finding.\n recommendation:\n type: string\n description: Concrete remediation step.\n confidence:\n type: number\n minimum: 0\n maximum: 1\n description: Confidence score (0\u20131) for the finding.\n evidence:\n type: array\n items:\n $ref: "#/components/schemas/AgentEvidence"\n details:\n type: object\n description: Additional structured details specific to the finding category.\n\n AgentRecommendedAction:\n type: object\n required: [kind, title]\n properties:\n kind:\n type: string\n enum: [run_command, edit_file, review, confirm, block, ignore]\n title:\n type: string\n description: Short human-readable title for the action.\n command:\n type: string\n description: Shell command to run (when kind is run_command).\n target:\n type: string\n description: File path to edit (when kind is edit_file).\n rationale:\n type: string\n description: Explanation of why this action is recommended.\n\n AgentEvidence:\n type: object\n required: [type, content]\n properties:\n type:\n type: string\n description: Evidence type (e.g. code_snippet, file_excerpt, lint_output).\n content:\n type: string\n description: The evidence content.\n source:\n type: string\n description: Source file path or URL for the evidence.\n';
|
|
30
|
+
var CONTRACT_JSON_STR = '{\n "cli_contracts": "0.1.0",\n "info": {\n "title": "agent-runtime CLI",\n "version": "0.36.17",\n "description": "Runtime bridge for executing agent-contracts workflows on Agent SDKs.\\nGenerates typed contracts, handoff validators, and guardrail hooks from DSL,\\nthen runs workflows through pluggable SDK adapters.\\n",\n "license": {\n "name": "MIT"\n }\n },\n "command_sets": {\n "agent-runtime": {\n "summary": "CLI for agent-contracts-runtime \u2014 generate, run, and manage agent workflows.",\n "global_options": [\n {\n "name": "config",\n "aliases": [\n "c"\n ],\n "description": "Path to agents.conf.yaml (project runtime config).",\n "schema": {\n "type": "string",\n "default": "./agents.conf.yaml"\n },\n "file": {\n "mode": "read",\n "exists": true,\n "media_type": "application/yaml"\n }\n },\n {\n "name": "verbose",\n "aliases": [\n "v"\n ],\n "description": "Enable verbose output.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "quiet",\n "aliases": [\n "q"\n ],\n "description": "Suppress non-error output.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n }\n ],\n "commands": {\n "init": {\n "summary": "Initialize runtime scaffolding for a project.",\n "description": "Generates the initial directory structure and configuration files\\nfor using agent-contracts-runtime in a project.\\nCreates agents.conf.yaml and agent/src/ user code templates.\\n",\n "options": [\n {\n "name": "adapter",\n "aliases": [\n "a"\n ],\n "description": "Default SDK adapter to configure.",\n "schema": {\n "type": "string",\n "enum": [\n "claude",\n "openai",\n "mock"\n ],\n "default": "mock"\n }\n },\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Output directory for generated scaffolding.",\n "schema": {\n "type": "string",\n "default": "."\n }\n },\n {\n "name": "force",\n "aliases": [\n "f"\n ],\n "description": "Overwrite existing files without prompting.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Scaffolding generated successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/InitResult"\n }\n }\n },\n "1": {\n "description": "Initialization failed (existing files, permission error, etc.).",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": false,\n "sideEffects": [\n "filesystem_write"\n ],\n "safeDryRunOption": ""\n }\n },\n "generate": {\n "summary": "Generate runtime contracts and hooks from DSL.",\n "description": "Reads agent-contracts.yaml, resolves the DSL, validates it,\\nand generates typed contracts, handoff schemas, guardrail hooks,\\nand a runtime manifest into the configured generated_dir.\\n\\nEach generated file includes a DO NOT EDIT header.\\n",\n "options": [\n {\n "name": "clean",\n "description": "Delete generated_dir before regenerating.\\nRemoves stale files that may remain from previous generations.\\n",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "check",\n "description": "Dry-run mode for CI. Does not write files.\\nCompares current generated output with what would be regenerated.\\nExits with code 1 if any differences are found.\\n",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "templates",\n "aliases": [\n "t"\n ],\n "description": "Custom templates directory. Overrides built-in templates.",\n "schema": {\n "type": "string"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Generation completed successfully (or --check found no differences).",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/GenerateResult"\n }\n }\n },\n "1": {\n "description": "Generation failed, or --check detected differences between\\ncurrent generated files and expected output.\\n",\n "stderr": {\n "format": "text"\n }\n },\n "2": {\n "description": "DSL validation error. The input DSL has structural or semantic issues.",\n "stderr": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/ValidationError"\n }\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": [\n "filesystem_write"\n ],\n "safeDryRunOption": "check"\n }\n },\n "run": {\n "summary": "Execute a workflow.",\n "description": "Loads generated contracts, creates an SDK adapter, registers user plugins,\\nand executes the specified workflow with the given user request.\\n\\nThe workflow runner orchestrates task delegation, retry, gate handling,\\nand handoff validation mechanically.\\n",\n "arguments": [\n {\n "name": "workflow-id",\n "required": false,\n "description": "ID of the workflow to execute. Required unless --file is used.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "user-request",\n "required": false,\n "description": "Natural language description of what to do. Required unless --file is used.",\n "schema": {\n "type": "string"\n }\n }\n ],\n "options": [\n {\n "name": "adapter",\n "aliases": [\n "a"\n ],\n "description": "SDK adapter to use. Overrides config.",\n "schema": {\n "type": "string",\n "enum": [\n "claude",\n "openai",\n "mock"\n ]\n }\n },\n {\n "name": "max-retries",\n "aliases": [\n "r"\n ],\n "description": "Override default max retries per step.",\n "schema": {\n "type": "integer",\n "minimum": 0,\n "maximum": 10\n }\n },\n {\n "name": "max-follow-ups",\n "aliases": [\n "f"\n ],\n "description": "Override default max follow-ups per step.",\n "schema": {\n "type": "integer",\n "minimum": 0,\n "maximum": 10\n }\n },\n {\n "name": "dry-run",\n "aliases": [\n "n"\n ],\n "description": "Simulate execution without calling the SDK adapter.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "auto-approve-gates",\n "description": "Automatically approve all gate steps.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "file",\n "description": "Path to a YAML invocation file. When provided, workflow-id and\\nuser-request arguments are read from the file instead of CLI args.\\n",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true,\n "media_type": "application/yaml"\n }\n },\n {\n "name": "log-file",\n "aliases": [\n "l"\n ],\n "description": "Write agent progress log to this file. Overrides config logging.progress_log.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Workflow completed successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/WorkflowResult"\n }\n }\n },\n "1": {\n "description": "Workflow failed (escalation, error, or gate rejection).",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/WorkflowResult"\n }\n },\n "stderr": {\n "format": "text"\n }\n },\n "3": {\n "description": "Input validation failed (invalid arguments, unknown workflow/adapter, or generated files outdated).",\n "stderr": {\n "format": "text"\n }\n },\n "12": {\n "description": "Adapter initialization error (missing API key, etc.).",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "high",\n "requiresConfirmation": true,\n "idempotent": false,\n "sideEffects": [\n "sdk_call",\n "filesystem_write"\n ],\n "safeDryRunOption": "dry-run",\n "expectedDurationMs": 300000,\n "recommendedBeforeUse": [\n "Run `agent-runtime generate --check` to ensure contracts are up to date.",\n "Run `agent-runtime doctor` to verify SDK configuration."\n ]\n }\n },\n "list": {\n "summary": "List available workflows, tasks, or agents.",\n "description": "Reads generated contracts and displays available resources.\\nUseful for discovering what workflows, tasks, and agents\\nare defined in the current project.\\n",\n "arguments": [\n {\n "name": "resource",\n "required": true,\n "description": "Type of resource to list.",\n "schema": {\n "type": "string",\n "enum": [\n "workflows",\n "tasks",\n "agents"\n ]\n }\n }\n ],\n "options": [\n {\n "name": "format",\n "description": "Output format.",\n "schema": {\n "type": "string",\n "enum": [\n "table",\n "json"\n ],\n "default": "table"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Resources listed successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/ListResult"\n }\n }\n },\n "1": {\n "description": "Failed to load contracts.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n },\n "show-prompt": {\n "summary": "Display the generated prompt for a task.",\n "description": "Builds and displays the full prompt that would be sent to an SDK agent\\nfor a given task. Useful for inspecting, debugging, and validating\\nprompt content before execution.\\n\\nShows the agent role, responsibilities, constraints, task details,\\ncompletion criteria, handoff schema fields, and output format example.\\n",\n "arguments": [\n {\n "name": "task-id",\n "required": true,\n "description": "ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).",\n "schema": {\n "type": "string"\n }\n }\n ],\n "options": [\n {\n "name": "user-request",\n "aliases": [\n "u"\n ],\n "description": "User request text to include in the prompt preview.",\n "schema": {\n "type": "string",\n "default": "(preview)"\n }\n },\n {\n "name": "format",\n "description": "Output format.",\n "schema": {\n "type": "string",\n "enum": [\n "markdown",\n "raw",\n "json"\n ],\n "default": "markdown"\n }\n },\n {\n "name": "with-plugins",\n "description": "Apply registered plugin prompt enhancers to the output.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Prompt displayed successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/ShowPromptResult"\n }\n }\n },\n "1": {\n "description": "Failed to build prompt (unknown task, missing contracts, etc.).",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n },\n "implement": {\n "summary": "Implement LLM-powered commands in a CLI tool.",\n "description": "Uses an agentic LLM adapter (Claude, etc.) to analyze the\\ntarget project and implement LLM-powered commands following the\\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\\n\\nThe agent reads the project structure, cli-contract.yaml, and existing\\ncode, then generates DSL definitions, TypeScript modules (orchestrator,\\ncontext-builder, formatter), CLI command handlers, and updates the\\nCLI contract with x-agent metadata.\\n\\nRequires an agentic adapter that supports tool use (file read/write).\\n",\n "arguments": [\n {\n "name": "description",\n "required": true,\n "description": "Natural language description of the LLM feature(s) to implement. Examples: \\"Add an audit command for migration safety\\", \\"Add propose and explain commands for SQL optimization\\".",\n "schema": {\n "type": "string"\n }\n }\n ],\n "options": [\n {\n "name": "adapter",\n "aliases": [\n "a"\n ],\n "description": "SDK adapter to use. Must be an agentic adapter (claude).",\n "schema": {\n "type": "string",\n "enum": [\n "claude",\n "mock"\n ],\n "default": "claude"\n }\n },\n {\n "name": "project-dir",\n "aliases": [\n "p"\n ],\n "description": "Path to the target project directory.",\n "schema": {\n "type": "string",\n "default": "."\n }\n },\n {\n "name": "dry-run",\n "aliases": [\n "n"\n ],\n "description": "Output the prompt context without calling the LLM.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "model",\n "description": "Model name override for the selected adapter.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Write the result to a file instead of stdout.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n },\n {\n "name": "report-format",\n "description": "Output format for the result.",\n "schema": {\n "type": "string",\n "enum": [\n "json",\n "text",\n "yaml"\n ],\n "default": "text"\n }\n },\n {\n "name": "log-file",\n "aliases": [\n "l"\n ],\n "description": "Write agent progress log to this file.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Implementation completed successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/ImplementResult"\n }\n }\n },\n "1": {\n "description": "Implementation failed.",\n "stderr": {\n "format": "text"\n }\n },\n "3": {\n "description": "Input validation failed (e.g. project directory not found).",\n "stderr": {\n "format": "text"\n }\n },\n "12": {\n "description": "Adapter initialization error.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "high",\n "requiresConfirmation": true,\n "idempotent": false,\n "sideEffects": [\n "sdk_call",\n "filesystem_write"\n ],\n "safeDryRunOption": "dry-run",\n "expectedDurationMs": 300000,\n "retryableExitCodes": [\n 1,\n 12\n ],\n "recommendedBeforeUse": [\n "Ensure the target project has a cli-contract.yaml or plan to create one.",\n "Run in a clean git working tree so changes can be reviewed."\n ]\n }\n },\n "audit-implementation": {\n "summary": "Audit an LLM command integration for pattern conformance.",\n "description": "Analyzes a target project\'s LLM command integration to verify it\\ncorrectly follows the agent-contracts + agent-contracts-runtime +\\ncli-contracts stack conventions.\\n\\nChecks all three layers:\\n1. DSL definitions (agents, tasks, workflows, handoff schemas)\\n2. Runtime integration (adapter usage, runTask/runWorkflow, registries)\\n3. CLI contract (standard options, x-agent metadata, exit codes)\\n\\nProduces structured findings with severity, category, and\\nconcrete remediation steps. Read-only \u2014 does not modify files.\\n",\n "arguments": [\n {\n "name": "project-dir",\n "required": false,\n "description": "Path to the project directory to audit. Defaults to current directory.",\n "schema": {\n "type": "string"\n }\n }\n ],\n "options": [\n {\n "name": "adapter",\n "aliases": [\n "a"\n ],\n "description": "SDK adapter to use for the audit agent.",\n "schema": {\n "type": "string",\n "enum": [\n "claude",\n "mock"\n ],\n "default": "claude"\n }\n },\n {\n "name": "focus",\n "description": "Limit audit to a specific layer. Defaults to all layers.",\n "schema": {\n "type": "string",\n "enum": [\n "all",\n "dsl",\n "runtime",\n "cli-contract",\n "architecture"\n ],\n "default": "all"\n }\n },\n {\n "name": "dry-run",\n "aliases": [\n "n"\n ],\n "description": "Output the prompt context without calling the LLM.",\n "schema": {\n "type": "boolean",\n "default": false\n }\n },\n {\n "name": "fail-on",\n "description": "Minimum finding severity that causes a non-zero exit.",\n "schema": {\n "type": "string",\n "enum": [\n "warning",\n "error",\n "critical"\n ],\n "default": "error"\n }\n },\n {\n "name": "model",\n "description": "Model name override for the selected adapter.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Write the result to a file instead of stdout.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n },\n {\n "name": "report-format",\n "description": "Output format for the audit report.",\n "schema": {\n "type": "string",\n "enum": [\n "json",\n "text",\n "yaml"\n ],\n "default": "text"\n }\n },\n {\n "name": "log-file",\n "aliases": [\n "l"\n ],\n "description": "Write agent progress log to this file.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Audit completed with no findings above threshold.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/AuditImplementationResult"\n }\n }\n },\n "1": {\n "description": "Audit failed (agent error, unexpected failure).",\n "stderr": {\n "format": "text"\n }\n },\n "3": {\n "description": "Input validation failed (e.g. project directory not found).",\n "stderr": {\n "format": "text"\n }\n },\n "10": {\n "description": "Audit completed with findings above --fail-on threshold.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/AuditImplementationResult"\n }\n }\n },\n "12": {\n "description": "Adapter initialization error.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": [\n "network"\n ],\n "sideEffectNote": "Network calls to LLM provider when adapter is not mock. Filesystem write only when --output is specified.",\n "safeDryRunOption": "dry-run",\n "expectedDurationMs": 180000,\n "retryableExitCodes": [\n 1,\n 12\n ]\n }\n },\n "agents": {\n "summary": "Output the full resolved DSL as structured data.",\n "description": "Outputs the complete resolved DSL (agents, tasks, workflows,\\nhandoff_types, etc.) embedded in this CLI binary.\\n\\nUseful for debugging, external tooling integration, and DSL\\ninspection. Unlike `list`, which shows tabular summaries,\\nthis command outputs the full DSL structure.\\n",\n "options": [\n {\n "name": "format",\n "aliases": [\n "F"\n ],\n "description": "Output format.",\n "schema": {\n "type": "string",\n "enum": [\n "yaml",\n "json"\n ],\n "default": "yaml"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "DSL output successfully.",\n "stdout": {\n "format": "text"\n }\n },\n "1": {\n "description": "Failed to load embedded DSL.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n },\n "doctor": {\n "summary": "Verify configuration, generated files, and SDK connectivity.",\n "description": "Runs a series of diagnostic checks to verify that the project\\nis correctly configured for agent-runtime execution.\\n\\nChecks: config existence, DSL existence, generated manifest freshness,\\nadapter configuration, API key environment variables, plugin entrypoint.\\n",\n "exits": {\n "0": {\n "description": "All checks passed.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/DoctorResult"\n }\n }\n },\n "1": {\n "description": "One or more checks failed.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/DoctorResult"\n }\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n },\n "navigation-index": {\n "summary": "Build artifact navigation index from resolved DSL.",\n "description": "Resolves the embedded DSL (merged with project overlay if configured),\\napplies artifact binding, and builds a navigation index showing\\nartifact-to-tool-to-agent mappings.\\n\\nThe output is a JSON/YAML structure suitable for IDE integration,\\nrouting rules, and artifact coverage analysis.\\n",\n "options": [\n {\n "name": "format",\n "aliases": [\n "F"\n ],\n "description": "Output format.",\n "schema": {\n "type": "string",\n "enum": [\n "json",\n "yaml"\n ],\n "default": "json"\n }\n },\n {\n "name": "artifact",\n "description": "Filter output to a single artifact by ID.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Write output to a file instead of stdout.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "write"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Navigation index built successfully.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/NavigationIndexResult"\n }\n }\n },\n "1": {\n "description": "Failed to build navigation index.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n }\n }\n }\n },\n "components": {\n "schemas": {\n "InitResult": {\n "type": "object",\n "required": [\n "files_created"\n ],\n "properties": {\n "files_created": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of files created by init."\n }\n }\n },\n "GenerateResult": {\n "type": "object",\n "required": [\n "files_generated",\n "dsl_hash",\n "generation_input_hash"\n ],\n "properties": {\n "files_generated": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of generated file paths."\n },\n "dsl_hash": {\n "type": "string",\n "description": "SHA-256 hash of the resolved DSL (canonical stringify)."\n },\n "generation_input_hash": {\n "type": "string",\n "description": "SHA-256 hash of all generation inputs."\n },\n "cleaned": {\n "type": "boolean",\n "description": "Whether --clean was used."\n },\n "check_mode": {\n "type": "boolean",\n "description": "Whether --check was used."\n },\n "has_differences": {\n "type": "boolean",\n "description": "In --check mode, whether differences were found."\n }\n }\n },\n "ValidationError": {\n "type": "object",\n "required": [\n "errors"\n ],\n "properties": {\n "errors": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "code",\n "message"\n ],\n "properties": {\n "code": {\n "type": "string"\n },\n "message": {\n "type": "string"\n },\n "path": {\n "type": "string",\n "description": "JSON path to the invalid element."\n }\n }\n }\n }\n }\n },\n "WorkflowResult": {\n "type": "object",\n "required": [\n "workflow_id",\n "status",\n "steps",\n "total_elapsed_ms"\n ],\n "properties": {\n "workflow_id": {\n "type": "string"\n },\n "status": {\n "type": "string",\n "enum": [\n "completed",\n "escalated",\n "gate_rejected",\n "error"\n ]\n },\n "steps": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/StepResult"\n }\n },\n "total_elapsed_ms": {\n "type": "integer",\n "minimum": 0\n },\n "escalation_reason": {\n "type": "string"\n },\n "error_message": {\n "type": "string"\n }\n }\n },\n "StepResult": {\n "type": "object",\n "required": [\n "step_index",\n "retries_used",\n "elapsed_ms",\n "outcome"\n ],\n "properties": {\n "step_index": {\n "type": "integer",\n "minimum": 0\n },\n "task_id": {\n "type": "string"\n },\n "gate_kind": {\n "type": "string"\n },\n "outcome": {\n "type": "object",\n "required": [\n "status"\n ],\n "properties": {\n "status": {\n "type": "string",\n "enum": [\n "success",\n "validation_error",\n "escalation",\n "error",\n "gate_approved",\n "gate_rejected",\n "skipped"\n ]\n }\n }\n },\n "retries_used": {\n "type": "integer",\n "minimum": 0\n },\n "elapsed_ms": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "ListResult": {\n "type": "object",\n "required": [\n "resource",\n "items"\n ],\n "properties": {\n "resource": {\n "type": "string",\n "enum": [\n "workflows",\n "tasks",\n "agents"\n ]\n },\n "items": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "id",\n "description"\n ],\n "properties": {\n "id": {\n "type": "string"\n },\n "description": {\n "type": "string"\n }\n }\n }\n }\n }\n },\n "ShowPromptResult": {\n "type": "object",\n "required": [\n "task_id",\n "agent_id",\n "prompt"\n ],\n "properties": {\n "task_id": {\n "type": "string",\n "description": "The task ID used to build the prompt."\n },\n "agent_id": {\n "type": "string",\n "description": "The target agent ID for this task."\n },\n "prompt": {\n "type": "string",\n "description": "The full generated prompt text."\n },\n "handoff_schema": {\n "type": "string",\n "description": "The handoff schema ID for the task result."\n },\n "plugins_applied": {\n "type": "boolean",\n "description": "Whether plugin prompt enhancers were applied."\n }\n }\n },\n "DoctorResult": {\n "type": "object",\n "required": [\n "checks",\n "all_passed"\n ],\n "properties": {\n "checks": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/DoctorCheck"\n }\n },\n "all_passed": {\n "type": "boolean"\n }\n }\n },\n "ImplementResult": {\n "type": "object",\n "required": [\n "files_created",\n "files_modified",\n "summary"\n ],\n "properties": {\n "files_created": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of new files created."\n },\n "files_modified": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of existing files modified."\n },\n "summary": {\n "type": "string",\n "description": "Human-readable summary of what was implemented."\n },\n "commands_added": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "name",\n "type"\n ],\n "properties": {\n "name": {\n "type": "string"\n },\n "type": {\n "type": "string",\n "enum": [\n "audit",\n "propose",\n "explain"\n ]\n },\n "description": {\n "type": "string"\n }\n }\n }\n },\n "next_steps": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "Recommended next steps for the developer."\n }\n }\n },\n "AuditImplementationResult": {\n "type": "object",\n "required": [\n "summary",\n "riskLevel",\n "findings"\n ],\n "properties": {\n "summary": {\n "type": "string",\n "description": "One-paragraph overall assessment."\n },\n "riskLevel": {\n "type": "string",\n "enum": [\n "low",\n "medium",\n "high",\n "critical"\n ],\n "description": "Derived from worst finding severity."\n },\n "findings": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/AgentFinding"\n }\n },\n "recommendedActions": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/AgentRecommendedAction"\n }\n },\n "metadata": {\n "type": "object",\n "properties": {\n "tool": {\n "type": "string"\n },\n "command": {\n "type": "string"\n },\n "version": {\n "type": "string"\n },\n "generatedAt": {\n "type": "string"\n },\n "adapter": {\n "type": "string"\n },\n "model": {\n "type": "string"\n }\n }\n }\n }\n },\n "DoctorCheck": {\n "type": "object",\n "required": [\n "name",\n "status"\n ],\n "properties": {\n "name": {\n "type": "string",\n "description": "Check name (e.g. config_exists, dsl_exists, manifest_fresh)."\n },\n "status": {\n "type": "string",\n "enum": [\n "pass",\n "fail",\n "warn"\n ]\n },\n "message": {\n "type": "string",\n "description": "Human-readable detail."\n }\n }\n },\n "NavigationIndexResult": {\n "type": "object",\n "required": [\n "version",\n "generated_at",\n "system",\n "artifacts"\n ],\n "properties": {\n "version": {\n "type": "string"\n },\n "generated_at": {\n "type": "string"\n },\n "system": {\n "type": "object",\n "required": [\n "id",\n "name"\n ],\n "properties": {\n "id": {\n "type": "string"\n },\n "name": {\n "type": "string"\n }\n }\n },\n "artifacts": {\n "type": "object",\n "additionalProperties": true\n }\n }\n },\n "AgentFinding": {\n "type": "object",\n "required": [\n "severity",\n "category",\n "message"\n ],\n "properties": {\n "id": {\n "type": "string",\n "description": "Unique finding identifier (e.g. F-001)."\n },\n "severity": {\n "type": "string",\n "enum": [\n "info",\n "warning",\n "error",\n "critical"\n ]\n },\n "category": {\n "type": "string",\n "description": "Domain vocabulary category (e.g. cli-contract-options, runtime-adapter)."\n },\n "target": {\n "type": "string",\n "description": "File path or resource the finding applies to."\n },\n "location": {\n "type": "string",\n "description": "Line range or specific location within the target."\n },\n "message": {\n "type": "string",\n "description": "Human-readable description of the finding."\n },\n "recommendation": {\n "type": "string",\n "description": "Concrete remediation step."\n },\n "confidence": {\n "type": "number",\n "minimum": 0,\n "maximum": 1,\n "description": "Confidence score (0\u20131) for the finding."\n },\n "evidence": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/AgentEvidence"\n }\n },\n "details": {\n "type": "object",\n "description": "Additional structured details specific to the finding category."\n }\n }\n },\n "AgentRecommendedAction": {\n "type": "object",\n "required": [\n "kind",\n "title"\n ],\n "properties": {\n "kind": {\n "type": "string",\n "enum": [\n "run_command",\n "edit_file",\n "review",\n "confirm",\n "block",\n "ignore"\n ]\n },\n "title": {\n "type": "string",\n "description": "Short human-readable title for the action."\n },\n "command": {\n "type": "string",\n "description": "Shell command to run (when kind is run_command)."\n },\n "target": {\n "type": "string",\n "description": "File path to edit (when kind is edit_file)."\n },\n "rationale": {\n "type": "string",\n "description": "Explanation of why this action is recommended."\n }\n }\n },\n "AgentEvidence": {\n "type": "object",\n "required": [\n "type",\n "content"\n ],\n "properties": {\n "type": {\n "type": "string",\n "description": "Evidence type (e.g. code_snippet, file_excerpt, lint_output)."\n },\n "content": {\n "type": "string",\n "description": "The evidence content."\n },\n "source": {\n "type": "string",\n "description": "Source file path or URL for the evidence."\n }\n }\n }\n }\n }\n}';
|
|
33
31
|
|
|
34
32
|
// src/generated/cli/program.ts
|
|
35
33
|
function createProgram(handlers2, version) {
|
|
@@ -88,10 +86,11 @@ function createProgram(handlers2, version) {
|
|
|
88
86
|
program2.command("navigation-index").description("Build artifact navigation index from resolved DSL.").option("-F, --format <value>", "Output format.", "json").option("--artifact <value>", "Filter output to a single artifact by ID.").option("-o, --output <value>", "Write output to a file instead of stdout.").action(async (opts, cmd) => {
|
|
89
87
|
await handlers2.navigationIndex(opts, cmd.optsWithGlobals());
|
|
90
88
|
});
|
|
91
|
-
program2.command("extract").description("Extract contract specification for this CLI tool.").argument("[commands...]", "Command IDs to extract. Use dot notation.").option("-a, --all", "Extract all commands.", false).option("--include-meta", "Include extraction metadata.", true).option("-F, --format <format>", "Output format (yaml or json).", "yaml").action(async (commands, opts) => {
|
|
89
|
+
program2.command("extract").description("Extract contract specification for this CLI tool.").argument("[commands...]", "Command IDs to extract. Use dot notation.").option("-a, --all", "Extract all commands.", false).option("--include-meta", "Include extraction metadata.", true).option("--no-include-meta").option("-F, --format <format>", "Output format (yaml or json).", "yaml").action(async (commands, opts) => {
|
|
92
90
|
if (commands.length === 0 && !opts.all) {
|
|
93
91
|
process.stderr.write(JSON.stringify({ code: "INVALID_ARGS", message: "Specify command IDs or use --all" }) + "\n");
|
|
94
|
-
process.
|
|
92
|
+
process.exitCode = 2;
|
|
93
|
+
return;
|
|
95
94
|
}
|
|
96
95
|
const format = opts.format || "yaml";
|
|
97
96
|
const doc = JSON.parse(CONTRACT_JSON_STR);
|
|
@@ -156,7 +155,7 @@ function createProgram(handlers2, version) {
|
|
|
156
155
|
if (doc.components) filtered.components = doc.components;
|
|
157
156
|
process.stdout.write(JSON.stringify(filtered, null, 2) + "\n");
|
|
158
157
|
}
|
|
159
|
-
process.
|
|
158
|
+
process.exitCode = 0;
|
|
160
159
|
});
|
|
161
160
|
return program2;
|
|
162
161
|
}
|
|
@@ -644,12 +643,12 @@ var llmFeatureImplementer = {
|
|
|
644
643
|
'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.'
|
|
645
644
|
],
|
|
646
645
|
constraints: [
|
|
647
|
-
"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk,
|
|
646
|
+
"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk, MockAdapter from agent-contracts-runtime/adapters/mock.",
|
|
648
647
|
"NEVER call adapter.send() or adapter.sendExecution() directly. All LLM invocations must go through runWorkflow() imported from agent-contracts-runtime. NEVER use runTask() \u2014 it is a low-level internal API. runWorkflow() handles prompt building, handoff validation, retry/followUp, workflow DAG, and plugin hooks.",
|
|
649
648
|
'Dynamic-import both agent-contracts-runtime and adapter packages. The tool must work without them installed (graceful degradation). Pattern: const RUNTIME = "agent-contracts-runtime"; try { const { runWorkflow } = await import(RUNTIME); } catch { exit(11); }',
|
|
650
649
|
"LLM commands use --report-format (json|text|yaml) for output format. --format is reserved for deterministic commands. Never mix them.",
|
|
651
650
|
"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.).",
|
|
652
|
-
"Standard LLM command options (all must be present): --adapter <name> (mock|claude|openai
|
|
651
|
+
"Standard LLM command options (all must be present): --adapter <name> (mock|claude|openai, default varies), --model <name> (optional override), --show-prompt (output prompt without LLM call), --fail-on <level> (warning|error|critical, default error), --output/-o <file> (write to file instead of stdout), --report-format <fmt> (json|text|yaml, default json).",
|
|
653
652
|
"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).",
|
|
654
653
|
"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).",
|
|
655
654
|
"AgentRecommendedAction shape: kind (run_command|edit_file|review|confirm| block|ignore), title (required), command?, target?, rationale?.",
|
|
@@ -657,7 +656,7 @@ var llmFeatureImplementer = {
|
|
|
657
656
|
"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.",
|
|
658
657
|
"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}).",
|
|
659
658
|
"runWorkflow (the ONLY API consumer projects should use): Overloads: (1) runWorkflow(adapter, workflowId, options, registries?) \u2014 legacy. (2) runWorkflow(adapter, invocation, registries?) \u2014 structured (preferred). WorkflowInvocation: { workflow, handoff?, user_request?, runtime? {maxFollowUps,maxRetries,timeoutMs,readonly, dryRun}, hooks? {onStepComplete,onGate,onOptionalStep}, context? {cwd,environment,artifacts,variables} }. WorkflowResult: { workflow_id, status (completed|escalated|gate_rejected|error), steps[], total_elapsed_ms, escalation_reason?, error_message? }. NEVER use runTask() \u2014 it is a low-level internal API.",
|
|
660
|
-
"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?})
|
|
659
|
+
"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?}).",
|
|
661
660
|
'Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from "../generated/dsl/index.js". Pass these as registries to runWorkflow: { workflowRegistry, taskRegistry, agentRegistry, handoffSchemas }.',
|
|
662
661
|
"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).",
|
|
663
662
|
"x-agent fields for LLM commands in cli-contract.yaml: riskLevel (low for read-only analysis), requiresConfirmation (false for read-only), idempotent (true for analysis), sideEffects ([network]), sideEffectNote (describe network call and optional file write), safeDryRunOption (show-prompt), expectedDurationMs (120000 typical), retryableExitCodes ([1, 12])."
|
|
@@ -722,7 +721,7 @@ var agentRegistry = {
|
|
|
722
721
|
// src/builtin-agents/generated/tasks.ts
|
|
723
722
|
var implementLlmFeature = {
|
|
724
723
|
id: "implement-llm-feature",
|
|
725
|
-
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\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 "claude": {\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\n }\n case "openai": {\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\n }\n case "gemini": {\n const m = await import(`${pkg}/adapters/gemini-sdk`);\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\n }\n }\n }\n\n export async function runAgentWorkflow(\n userRequest: string, workflowId: WorkflowId, config: AgentConfig, options: AgentOptions,\n ): Promise<AgentRunResult> {\n if (options.dryRun) return { workflowId, data:null, raw:"", prompt:userRequest, dryRun:true, status:"success" };\n\n const PKG = "agent-contracts-runtime";\n let runWorkflow;\n try { ({ runWorkflow } = await import(PKG)); }\n catch { throw Object.assign(new Error("agent-contracts-runtime not installed"), { exitCode: EXIT_RUNTIME_MISSING }); }\n\n let registries;\n try {\n const dsl = await import("../generated/dsl/index.js");\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas, workflowRegistry: dsl.workflowRegistry };\n } catch { registries = {}; }\n\n const adapter = await createAdapter(PKG, config.adapter ?? "mock", config);\n const result = await runWorkflow(adapter, { workflow: workflowId, user_request: userRequest, runtime: { maxFollowUps:3, maxRetries:1 } }, registries);\n // map result to AgentRunResult\n }\n\n**src/agents/context-builder.ts**:\n\nCRITICAL: context-builder builds the USER-SIDE prompt only.\nAgent instructions (purpose, responsibilities, constraints, rules,\nevaluation criteria, anti-patterns, output format) are defined in\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\nbuildTaskPrompt / runWorkflow. NEVER hardcode these in context-builder.\n\nContext-builder SHOULD contain:\n- Domain-specific DATA: file contents, configuration, scan results\n- Project metadata: target paths, dialect, directory structure\n- Deterministic pre-analysis: lint results, schema excerpts\n- Operational context: cwd, timestamps\n- Brief task framing: "# Migration Safety Audit Request"\n\nContext-builder MUST NOT contain:\n- "## Instructions" / "## Required Patterns" sections\n- Output format specifications (handled by handoff schema)\n- Evaluation criteria or checklists\n- Anti-pattern definitions or rule sets\n- API reference material\n- Anything that duplicates DSL agent purpose/responsibilities/rules\n\n export function build{Command}Context(target, config): string {\n const sections = [];\n sections.push("# {Command} Request");\n sections.push(`## Target\\n\\n${target}`);\n // Domain data only \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 runAgentWorkflow(context, "{workflow-id}", agentConfig, agentOpts);\n if (opts.reportFormat === "json") console.log(formatResultJson(result));\n else console.log(formatResultText(result));\n process.exit(computeExitCode(result, opts));\n }\n\nWire handlers through cli-contracts\' generated program:\n\n import { createProgram, type CommandHandlers } from \'./generated/program.js\';\n\n const handlers: CommandHandlers = {\n {commandName}: async (target, opts) => {\n await command{Name}(target, opts);\n },\n // ... other handlers\n };\n\n createProgram(handlers, version).parse();\n\n### Step 7: Update cli-contract.yaml\n\nAdd each LLM command with standard options and x-agent metadata:\n\n {command-name}:\n summary: "{Command summary}"\n arguments: [...]\n options:\n - name: adapter\n schema: { type: string, enum: [mock, claude, openai, gemini] }\n - name: model\n schema: { type: string }\n - name: show-prompt\n schema: { type: boolean, default: false }\n - name: fail-on\n schema: { type: string, enum: [warning, error, critical], default: error }\n - name: output\n aliases: [o]\n schema: { type: string }\n file: { mode: write }\n - name: report-format\n schema: { type: string, enum: [json, text, yaml], default: json }\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: [network]\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: show-prompt\n expectedDurationMs: 120000\n retryableExitCodes: [1, 12]\n exits:\n \'0\': { description: "No blocking findings.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'1\': { description: "General error.", stderr: { format: text } }\n \'3\': { description: "Input validation failed.", stderr: { format: json } }\n \'10\': { description: "Blocking findings detected.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'11\': { description: "Runtime not installed.", stderr: { format: json } }\n \'12\': { description: "Adapter error.", stderr: { format: json } }\n\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\nto components/schemas if not already present.\n\n### Step 8: Update README\n\nAdd "Agent-Native Toolchain" section after mechanical features:\n- Intro: tool encapsulates domain-specific semantic reasoning\n- Deterministic checks first, then semantic audit\n- Structured findings (AgentAuditResult/AgentFinding)\n- LLM Adapter Configuration table\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\n',
|
|
724
|
+
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\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 "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 }\n }\n\n export async function runAgentWorkflow(\n userRequest: string, workflowId: WorkflowId, config: AgentConfig, options: AgentOptions,\n ): Promise<AgentRunResult> {\n if (options.dryRun) return { workflowId, data:null, raw:"", prompt:userRequest, dryRun:true, status:"success" };\n\n const PKG = "agent-contracts-runtime";\n let runWorkflow;\n try { ({ runWorkflow } = await import(PKG)); }\n catch { throw Object.assign(new Error("agent-contracts-runtime not installed"), { exitCode: EXIT_RUNTIME_MISSING }); }\n\n let registries;\n try {\n const dsl = await import("../generated/dsl/index.js");\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas, workflowRegistry: dsl.workflowRegistry };\n } catch { registries = {}; }\n\n const adapter = await createAdapter(PKG, config.adapter ?? "mock", config);\n const result = await runWorkflow(adapter, { workflow: workflowId, user_request: userRequest, runtime: { maxFollowUps:3, maxRetries:1 } }, registries);\n // map result to AgentRunResult\n }\n\n**src/agents/context-builder.ts**:\n\nCRITICAL: context-builder builds the USER-SIDE prompt only.\nAgent instructions (purpose, responsibilities, constraints, rules,\nevaluation criteria, anti-patterns, output format) are defined in\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\nbuildTaskPrompt / runWorkflow. NEVER hardcode these in context-builder.\n\nContext-builder SHOULD contain:\n- Domain-specific DATA: file contents, configuration, scan results\n- Project metadata: target paths, dialect, directory structure\n- Deterministic pre-analysis: lint results, schema excerpts\n- Operational context: cwd, timestamps\n- Brief task framing: "# Migration Safety Audit Request"\n\nContext-builder MUST NOT contain:\n- "## Instructions" / "## Required Patterns" sections\n- Output format specifications (handled by handoff schema)\n- Evaluation criteria or checklists\n- Anti-pattern definitions or rule sets\n- API reference material\n- Anything that duplicates DSL agent purpose/responsibilities/rules\n\n export function build{Command}Context(target, config): string {\n const sections = [];\n sections.push("# {Command} Request");\n sections.push(`## Target\\n\\n${target}`);\n // Domain data only \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 runAgentWorkflow(context, "{workflow-id}", agentConfig, agentOpts);\n if (opts.reportFormat === "json") console.log(formatResultJson(result));\n else console.log(formatResultText(result));\n process.exit(computeExitCode(result, opts));\n }\n\nWire handlers through cli-contracts\' generated program:\n\n import { createProgram, type CommandHandlers } from \'./generated/program.js\';\n\n const handlers: CommandHandlers = {\n {commandName}: async (target, opts) => {\n await command{Name}(target, opts);\n },\n // ... other handlers\n };\n\n createProgram(handlers, version).parse();\n\n### Step 7: Update cli-contract.yaml\n\nAdd each LLM command with standard options and x-agent metadata:\n\n {command-name}:\n summary: "{Command summary}"\n arguments: [...]\n options:\n - name: adapter\n schema: { type: string, enum: [mock, claude, openai] }\n - name: model\n schema: { type: string }\n - name: show-prompt\n schema: { type: boolean, default: false }\n - name: fail-on\n schema: { type: string, enum: [warning, error, critical], default: error }\n - name: output\n aliases: [o]\n schema: { type: string }\n file: { mode: write }\n - name: report-format\n schema: { type: string, enum: [json, text, yaml], default: json }\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: [network]\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: show-prompt\n expectedDurationMs: 120000\n retryableExitCodes: [1, 12]\n exits:\n \'0\': { description: "No blocking findings.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'1\': { description: "General error.", stderr: { format: text } }\n \'3\': { description: "Input validation failed.", stderr: { format: json } }\n \'10\': { description: "Blocking findings detected.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'11\': { description: "Runtime not installed.", stderr: { format: json } }\n \'12\': { description: "Adapter error.", stderr: { format: json } }\n\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\nto components/schemas if not already present.\n\n### Step 8: Update README\n\nAdd "Agent-Native Toolchain" section after mechanical features:\n- Intro: tool encapsulates domain-specific semantic reasoning\n- Deterministic checks first, then semantic audit\n- Structured findings (AgentAuditResult/AgentFinding)\n- LLM Adapter Configuration table\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\n',
|
|
726
725
|
target_agent: "llm-feature-implementer",
|
|
727
726
|
allowed_from_agents: [
|
|
728
727
|
"llm-feature-implementer"
|
|
@@ -1261,12 +1260,12 @@ var resolvedDsl = {
|
|
|
1261
1260
|
'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.'
|
|
1262
1261
|
],
|
|
1263
1262
|
"constraints": [
|
|
1264
|
-
"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk,
|
|
1263
|
+
"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk, MockAdapter from agent-contracts-runtime/adapters/mock.",
|
|
1265
1264
|
"NEVER call adapter.send() or adapter.sendExecution() directly. All LLM invocations must go through runWorkflow() imported from agent-contracts-runtime. NEVER use runTask() \u2014 it is a low-level internal API. runWorkflow() handles prompt building, handoff validation, retry/followUp, workflow DAG, and plugin hooks.",
|
|
1266
1265
|
'Dynamic-import both agent-contracts-runtime and adapter packages. The tool must work without them installed (graceful degradation). Pattern: const RUNTIME = "agent-contracts-runtime"; try { const { runWorkflow } = await import(RUNTIME); } catch { exit(11); }',
|
|
1267
1266
|
"LLM commands use --report-format (json|text|yaml) for output format. --format is reserved for deterministic commands. Never mix them.",
|
|
1268
1267
|
"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.).",
|
|
1269
|
-
"Standard LLM command options (all must be present): --adapter <name> (mock|claude|openai
|
|
1268
|
+
"Standard LLM command options (all must be present): --adapter <name> (mock|claude|openai, default varies), --model <name> (optional override), --show-prompt (output prompt without LLM call), --fail-on <level> (warning|error|critical, default error), --output/-o <file> (write to file instead of stdout), --report-format <fmt> (json|text|yaml, default json).",
|
|
1270
1269
|
"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).",
|
|
1271
1270
|
"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).",
|
|
1272
1271
|
"AgentRecommendedAction shape: kind (run_command|edit_file|review|confirm| block|ignore), title (required), command?, target?, rationale?.",
|
|
@@ -1274,7 +1273,7 @@ var resolvedDsl = {
|
|
|
1274
1273
|
"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.",
|
|
1275
1274
|
"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}).",
|
|
1276
1275
|
"runWorkflow (the ONLY API consumer projects should use): Overloads: (1) runWorkflow(adapter, workflowId, options, registries?) \u2014 legacy. (2) runWorkflow(adapter, invocation, registries?) \u2014 structured (preferred). WorkflowInvocation: { workflow, handoff?, user_request?, runtime? {maxFollowUps,maxRetries,timeoutMs,readonly, dryRun}, hooks? {onStepComplete,onGate,onOptionalStep}, context? {cwd,environment,artifacts,variables} }. WorkflowResult: { workflow_id, status (completed|escalated|gate_rejected|error), steps[], total_elapsed_ms, escalation_reason?, error_message? }. NEVER use runTask() \u2014 it is a low-level internal API.",
|
|
1277
|
-
"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?})
|
|
1276
|
+
"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?}).",
|
|
1278
1277
|
'Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from "../generated/dsl/index.js". Pass these as registries to runWorkflow: { workflowRegistry, taskRegistry, agentRegistry, handoffSchemas }.',
|
|
1279
1278
|
"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).",
|
|
1280
1279
|
"x-agent fields for LLM commands in cli-contract.yaml: riskLevel (low for read-only analysis), requiresConfirmation (false for read-only), idempotent (true for analysis), sideEffects ([network]), sideEffectNote (describe network call and optional file write), safeDryRunOption (show-prompt), expectedDurationMs (120000 typical), retryableExitCodes ([1, 12])."
|
|
@@ -1334,7 +1333,7 @@ var resolvedDsl = {
|
|
|
1334
1333
|
},
|
|
1335
1334
|
"tasks": {
|
|
1336
1335
|
"implement-llm-feature": {
|
|
1337
|
-
"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\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 "claude": {\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\n }\n case "openai": {\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\n }\n case "gemini": {\n const m = await import(`${pkg}/adapters/gemini-sdk`);\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\n }\n }\n }\n\n export async function runAgentWorkflow(\n userRequest: string, workflowId: WorkflowId, config: AgentConfig, options: AgentOptions,\n ): Promise<AgentRunResult> {\n if (options.dryRun) return { workflowId, data:null, raw:"", prompt:userRequest, dryRun:true, status:"success" };\n\n const PKG = "agent-contracts-runtime";\n let runWorkflow;\n try { ({ runWorkflow } = await import(PKG)); }\n catch { throw Object.assign(new Error("agent-contracts-runtime not installed"), { exitCode: EXIT_RUNTIME_MISSING }); }\n\n let registries;\n try {\n const dsl = await import("../generated/dsl/index.js");\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas, workflowRegistry: dsl.workflowRegistry };\n } catch { registries = {}; }\n\n const adapter = await createAdapter(PKG, config.adapter ?? "mock", config);\n const result = await runWorkflow(adapter, { workflow: workflowId, user_request: userRequest, runtime: { maxFollowUps:3, maxRetries:1 } }, registries);\n // map result to AgentRunResult\n }\n\n**src/agents/context-builder.ts**:\n\nCRITICAL: context-builder builds the USER-SIDE prompt only.\nAgent instructions (purpose, responsibilities, constraints, rules,\nevaluation criteria, anti-patterns, output format) are defined in\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\nbuildTaskPrompt / runWorkflow. NEVER hardcode these in context-builder.\n\nContext-builder SHOULD contain:\n- Domain-specific DATA: file contents, configuration, scan results\n- Project metadata: target paths, dialect, directory structure\n- Deterministic pre-analysis: lint results, schema excerpts\n- Operational context: cwd, timestamps\n- Brief task framing: "# Migration Safety Audit Request"\n\nContext-builder MUST NOT contain:\n- "## Instructions" / "## Required Patterns" sections\n- Output format specifications (handled by handoff schema)\n- Evaluation criteria or checklists\n- Anti-pattern definitions or rule sets\n- API reference material\n- Anything that duplicates DSL agent purpose/responsibilities/rules\n\n export function build{Command}Context(target, config): string {\n const sections = [];\n sections.push("# {Command} Request");\n sections.push(`## Target\\n\\n${target}`);\n // Domain data only \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 runAgentWorkflow(context, "{workflow-id}", agentConfig, agentOpts);\n if (opts.reportFormat === "json") console.log(formatResultJson(result));\n else console.log(formatResultText(result));\n process.exit(computeExitCode(result, opts));\n }\n\nWire handlers through cli-contracts\' generated program:\n\n import { createProgram, type CommandHandlers } from \'./generated/program.js\';\n\n const handlers: CommandHandlers = {\n {commandName}: async (target, opts) => {\n await command{Name}(target, opts);\n },\n // ... other handlers\n };\n\n createProgram(handlers, version).parse();\n\n### Step 7: Update cli-contract.yaml\n\nAdd each LLM command with standard options and x-agent metadata:\n\n {command-name}:\n summary: "{Command summary}"\n arguments: [...]\n options:\n - name: adapter\n schema: { type: string, enum: [mock, claude, openai, gemini] }\n - name: model\n schema: { type: string }\n - name: show-prompt\n schema: { type: boolean, default: false }\n - name: fail-on\n schema: { type: string, enum: [warning, error, critical], default: error }\n - name: output\n aliases: [o]\n schema: { type: string }\n file: { mode: write }\n - name: report-format\n schema: { type: string, enum: [json, text, yaml], default: json }\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: [network]\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: show-prompt\n expectedDurationMs: 120000\n retryableExitCodes: [1, 12]\n exits:\n \'0\': { description: "No blocking findings.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'1\': { description: "General error.", stderr: { format: text } }\n \'3\': { description: "Input validation failed.", stderr: { format: json } }\n \'10\': { description: "Blocking findings detected.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'11\': { description: "Runtime not installed.", stderr: { format: json } }\n \'12\': { description: "Adapter error.", stderr: { format: json } }\n\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\nto components/schemas if not already present.\n\n### Step 8: Update README\n\nAdd "Agent-Native Toolchain" section after mechanical features:\n- Intro: tool encapsulates domain-specific semantic reasoning\n- Deterministic checks first, then semantic audit\n- Structured findings (AgentAuditResult/AgentFinding)\n- LLM Adapter Configuration table\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\n',
|
|
1336
|
+
"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\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 "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 }\n }\n\n export async function runAgentWorkflow(\n userRequest: string, workflowId: WorkflowId, config: AgentConfig, options: AgentOptions,\n ): Promise<AgentRunResult> {\n if (options.dryRun) return { workflowId, data:null, raw:"", prompt:userRequest, dryRun:true, status:"success" };\n\n const PKG = "agent-contracts-runtime";\n let runWorkflow;\n try { ({ runWorkflow } = await import(PKG)); }\n catch { throw Object.assign(new Error("agent-contracts-runtime not installed"), { exitCode: EXIT_RUNTIME_MISSING }); }\n\n let registries;\n try {\n const dsl = await import("../generated/dsl/index.js");\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas, workflowRegistry: dsl.workflowRegistry };\n } catch { registries = {}; }\n\n const adapter = await createAdapter(PKG, config.adapter ?? "mock", config);\n const result = await runWorkflow(adapter, { workflow: workflowId, user_request: userRequest, runtime: { maxFollowUps:3, maxRetries:1 } }, registries);\n // map result to AgentRunResult\n }\n\n**src/agents/context-builder.ts**:\n\nCRITICAL: context-builder builds the USER-SIDE prompt only.\nAgent instructions (purpose, responsibilities, constraints, rules,\nevaluation criteria, anti-patterns, output format) are defined in\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\nbuildTaskPrompt / runWorkflow. NEVER hardcode these in context-builder.\n\nContext-builder SHOULD contain:\n- Domain-specific DATA: file contents, configuration, scan results\n- Project metadata: target paths, dialect, directory structure\n- Deterministic pre-analysis: lint results, schema excerpts\n- Operational context: cwd, timestamps\n- Brief task framing: "# Migration Safety Audit Request"\n\nContext-builder MUST NOT contain:\n- "## Instructions" / "## Required Patterns" sections\n- Output format specifications (handled by handoff schema)\n- Evaluation criteria or checklists\n- Anti-pattern definitions or rule sets\n- API reference material\n- Anything that duplicates DSL agent purpose/responsibilities/rules\n\n export function build{Command}Context(target, config): string {\n const sections = [];\n sections.push("# {Command} Request");\n sections.push(`## Target\\n\\n${target}`);\n // Domain data only \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 runAgentWorkflow(context, "{workflow-id}", agentConfig, agentOpts);\n if (opts.reportFormat === "json") console.log(formatResultJson(result));\n else console.log(formatResultText(result));\n process.exit(computeExitCode(result, opts));\n }\n\nWire handlers through cli-contracts\' generated program:\n\n import { createProgram, type CommandHandlers } from \'./generated/program.js\';\n\n const handlers: CommandHandlers = {\n {commandName}: async (target, opts) => {\n await command{Name}(target, opts);\n },\n // ... other handlers\n };\n\n createProgram(handlers, version).parse();\n\n### Step 7: Update cli-contract.yaml\n\nAdd each LLM command with standard options and x-agent metadata:\n\n {command-name}:\n summary: "{Command summary}"\n arguments: [...]\n options:\n - name: adapter\n schema: { type: string, enum: [mock, claude, openai] }\n - name: model\n schema: { type: string }\n - name: show-prompt\n schema: { type: boolean, default: false }\n - name: fail-on\n schema: { type: string, enum: [warning, error, critical], default: error }\n - name: output\n aliases: [o]\n schema: { type: string }\n file: { mode: write }\n - name: report-format\n schema: { type: string, enum: [json, text, yaml], default: json }\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: [network]\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: show-prompt\n expectedDurationMs: 120000\n retryableExitCodes: [1, 12]\n exits:\n \'0\': { description: "No blocking findings.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'1\': { description: "General error.", stderr: { format: text } }\n \'3\': { description: "Input validation failed.", stderr: { format: json } }\n \'10\': { description: "Blocking findings detected.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'11\': { description: "Runtime not installed.", stderr: { format: json } }\n \'12\': { description: "Adapter error.", stderr: { format: json } }\n\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\nto components/schemas if not already present.\n\n### Step 8: Update README\n\nAdd "Agent-Native Toolchain" section after mechanical features:\n- Intro: tool encapsulates domain-specific semantic reasoning\n- Deterministic checks first, then semantic audit\n- Structured findings (AgentAuditResult/AgentFinding)\n- LLM Adapter Configuration table\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\n',
|
|
1338
1337
|
"target_agent": "llm-feature-implementer",
|
|
1339
1338
|
"allowed_from_agents": [
|
|
1340
1339
|
"llm-feature-implementer"
|
|
@@ -2393,7 +2392,7 @@ function formatAuditResult(result) {
|
|
|
2393
2392
|
// src/cli/index.ts
|
|
2394
2393
|
import YAML2 from "yaml";
|
|
2395
2394
|
register();
|
|
2396
|
-
var VERSION = "0.36.
|
|
2395
|
+
var VERSION = "0.36.17";
|
|
2397
2396
|
async function loadGeneratedContracts(configPath) {
|
|
2398
2397
|
const config = await loadConfig(configPath);
|
|
2399
2398
|
const basePath = `${config.generatedDir}/index`;
|
|
@@ -2435,16 +2434,12 @@ async function createAdapter(adapterName, guardrailHooks, cwd, model) {
|
|
|
2435
2434
|
const { ClaudeAgentSdkAdapter } = await import("../adapters/claude-agent-sdk.js");
|
|
2436
2435
|
return new ClaudeAgentSdkAdapter({ cwd, guardrailHooks, ...model ? { model } : {} });
|
|
2437
2436
|
}
|
|
2438
|
-
case "gemini": {
|
|
2439
|
-
const { AdkSdkAdapter } = await import("../adapters/adk-sdk.js");
|
|
2440
|
-
return new AdkSdkAdapter({ guardrailHooks, ...model ? { model } : {} });
|
|
2441
|
-
}
|
|
2442
2437
|
case "openai": {
|
|
2443
2438
|
const { OpenAIAgentsSdkAdapter } = await import("../adapters/openai-agents-sdk.js");
|
|
2444
2439
|
return new OpenAIAgentsSdkAdapter({ guardrailHooks, ...model ? { model } : {} });
|
|
2445
2440
|
}
|
|
2446
2441
|
default:
|
|
2447
|
-
throw new Error(`Unknown adapter: ${adapterName}. Available: mock, claude,
|
|
2442
|
+
throw new Error(`Unknown adapter: ${adapterName}. Available: mock, claude, openai`);
|
|
2448
2443
|
}
|
|
2449
2444
|
}
|
|
2450
2445
|
function formatTable(headers, rows) {
|