agent-contracts-runtime 0.33.1 → 0.33.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli-contract.yaml +38 -0
- package/dist/agent-runtime.bundle.mjs +1001 -242
- package/dist/agent-runtime.bundle.mjs.map +4 -4
- package/dist/{chunk-TR4RR7M3.js → chunk-XM22OOCZ.js} +8 -1
- package/dist/chunk-XM22OOCZ.js.map +1 -0
- package/dist/{chunk-GVJYNAEQ.js → chunk-YTPEKBSI.js} +240 -2
- package/dist/chunk-YTPEKBSI.js.map +1 -0
- package/dist/cli/index.js +900 -26
- package/dist/cli/index.js.map +1 -1
- package/dist/generator/index.js +1 -1
- package/dist/index.d.ts +73 -1
- package/dist/index.js +9 -1
- package/docs/cli-reference.md +48 -0
- package/package.json +1 -1
- package/templates/contracts-index.ts.hbs +1 -0
- package/dist/chunk-GVJYNAEQ.js.map +0 -1
- package/dist/chunk-TR4RR7M3.js.map +0 -1
package/dist/cli/index.js
CHANGED
|
@@ -4,13 +4,13 @@ import {
|
|
|
4
4
|
loadPlugins,
|
|
5
5
|
pluginRegistry,
|
|
6
6
|
runWorkflow
|
|
7
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-YTPEKBSI.js";
|
|
8
8
|
import "../chunk-AWBHN3LI.js";
|
|
9
9
|
import {
|
|
10
10
|
checkFreshness,
|
|
11
11
|
generate,
|
|
12
12
|
loadConfig
|
|
13
|
-
} from "../chunk-
|
|
13
|
+
} from "../chunk-XM22OOCZ.js";
|
|
14
14
|
|
|
15
15
|
// src/cli/index.ts
|
|
16
16
|
import { existsSync as existsSync5, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
@@ -21,8 +21,8 @@ import { register } from "tsx/esm/api";
|
|
|
21
21
|
import { Command } from "commander";
|
|
22
22
|
|
|
23
23
|
// src/generated/cli/contract.ts
|
|
24
|
-
var CONTRACT_YAML = 'cli_contracts: 0.1.0\n\ninfo:\n title: agent-runtime CLI\n version: 0.1.0\n description: |\n Runtime bridge for executing agent-contracts workflows on Agent SDKs.\n Generates typed contracts, handoff validators, and guardrail hooks from DSL,\n then runs workflows through pluggable SDK adapters.\n license:\n name: MIT\n\ncommand_sets:\n agent-runtime:\n summary: CLI for agent-contracts-runtime \u2014 generate, run, and manage agent workflows.\n global_options:\n - name: config\n aliases: [c]\n description: Path to agent-runtime.config.yaml.\n schema:\n type: string\n default: ./agent-runtime.config.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 agent-runtime.config.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: [cursor, 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: [cursor, 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 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, Cursor, 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, cursor).\n schema:\n type: string\n enum: [claude, cursor, 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 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, cursor, 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 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 # doctor\n # -----------------------------------------------------------------------\n doctor:\n summary: Verify configuration, generated files, and SDK connectivity.\n description: |\n Runs a series of diagnostic checks to verify that the project\n is correctly configured for agent-runtime execution.\n\n Checks: config existence, DSL existence, generated manifest freshness,\n adapter configuration, API key environment variables, plugin entrypoint.\n exits:\n "0":\n description: All checks passed.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/DoctorResult"\n\n "1":\n description: One or more checks failed.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/DoctorResult"\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n\n# =============================================================================\n# Components\n# =============================================================================\n\ncomponents:\n schemas:\n # -------------------------------------------------------------------------\n # init\n # -------------------------------------------------------------------------\n InitResult:\n type: object\n required: [files_created]\n properties:\n files_created:\n type: array\n items:\n type: string\n description: List of files created by init.\n\n # -------------------------------------------------------------------------\n # generate\n # -------------------------------------------------------------------------\n GenerateResult:\n type: object\n required: [files_generated, dsl_hash, generation_input_hash]\n properties:\n files_generated:\n type: array\n items:\n type: string\n description: List of generated file paths.\n dsl_hash:\n type: string\n description: SHA-256 hash of the resolved DSL (canonical stringify).\n generation_input_hash:\n type: string\n description: SHA-256 hash of all generation inputs.\n cleaned:\n type: boolean\n description: Whether --clean was used.\n check_mode:\n type: boolean\n description: Whether --check was used.\n has_differences:\n type: boolean\n description: In --check mode, whether differences were found.\n\n ValidationError:\n type: object\n required: [errors]\n properties:\n errors:\n type: array\n items:\n type: object\n required: [code, message]\n properties:\n code:\n type: string\n message:\n type: string\n path:\n type: string\n description: JSON path to the invalid element.\n\n # -------------------------------------------------------------------------\n # run\n # -------------------------------------------------------------------------\n WorkflowResult:\n type: object\n required: [workflow_id, status, steps, total_elapsed_ms]\n properties:\n workflow_id:\n type: string\n status:\n type: string\n enum: [completed, escalated, gate_rejected, error]\n steps:\n type: array\n items:\n $ref: "#/components/schemas/StepResult"\n total_elapsed_ms:\n type: integer\n minimum: 0\n escalation_reason:\n type: string\n error_message:\n type: string\n\n StepResult:\n type: object\n required: [step_index, retries_used, elapsed_ms, outcome]\n properties:\n step_index:\n type: integer\n minimum: 0\n task_id:\n type: string\n gate_kind:\n type: string\n outcome:\n type: object\n required: [status]\n properties:\n status:\n type: string\n enum: [success, validation_error, escalation, error, gate_approved, gate_rejected, skipped]\n retries_used:\n type: integer\n minimum: 0\n elapsed_ms:\n type: integer\n minimum: 0\n\n # -------------------------------------------------------------------------\n # list\n # -------------------------------------------------------------------------\n ListResult:\n type: object\n required: [resource, items]\n properties:\n resource:\n type: string\n enum: [workflows, tasks, agents]\n items:\n type: array\n items:\n type: object\n required: [id, description]\n properties:\n id:\n type: string\n description:\n type: string\n\n # -------------------------------------------------------------------------\n # show-prompt\n # -------------------------------------------------------------------------\n ShowPromptResult:\n type: object\n required: [task_id, agent_id, prompt]\n properties:\n task_id:\n type: string\n description: The task ID used to build the prompt.\n agent_id:\n type: string\n description: The target agent ID for this task.\n prompt:\n type: string\n description: The full generated prompt text.\n handoff_schema:\n type: string\n description: The handoff schema ID for the task result.\n plugins_applied:\n type: boolean\n description: Whether plugin prompt enhancers were applied.\n\n # -------------------------------------------------------------------------\n # doctor\n # -------------------------------------------------------------------------\n DoctorResult:\n type: object\n required: [checks, all_passed]\n properties:\n checks:\n type: array\n items:\n $ref: "#/components/schemas/DoctorCheck"\n all_passed:\n type: boolean\n\n # -------------------------------------------------------------------------\n # implement\n # -------------------------------------------------------------------------\n ImplementResult:\n type: object\n required: [files_created, files_modified, summary]\n properties:\n files_created:\n type: array\n items:\n type: string\n description: List of new files created.\n files_modified:\n type: array\n items:\n type: string\n description: List of existing files modified.\n summary:\n type: string\n description: Human-readable summary of what was implemented.\n commands_added:\n type: array\n items:\n type: object\n required: [name, type]\n properties:\n name:\n type: string\n type:\n type: string\n enum: [audit, propose, explain]\n description:\n type: string\n next_steps:\n type: array\n items:\n type: string\n description: Recommended next steps for the developer.\n\n # -------------------------------------------------------------------------\n # audit-implementation\n # -------------------------------------------------------------------------\n AuditImplementationResult:\n type: object\n required: [summary, riskLevel, findings]\n properties:\n summary:\n type: string\n description: One-paragraph overall assessment.\n riskLevel:\n type: string\n enum: [low, medium, high, critical]\n description: Derived from worst finding severity.\n findings:\n type: array\n items:\n $ref: "#/components/schemas/AgentFinding"\n recommendedActions:\n type: array\n items:\n $ref: "#/components/schemas/AgentRecommendedAction"\n metadata:\n type: object\n properties:\n tool:\n type: string\n command:\n type: string\n version:\n type: string\n generatedAt:\n type: string\n adapter:\n type: string\n model:\n type: string\n\n DoctorCheck:\n type: object\n required: [name, status]\n properties:\n name:\n type: string\n description: Check name (e.g. config_exists, dsl_exists, manifest_fresh).\n status:\n type: string\n enum: [pass, fail, warn]\n message:\n type: string\n description: Human-readable detail.\n\n # -------------------------------------------------------------------------\n # Canonical agent result schemas (AgentAuditResult sub-types)\n # -------------------------------------------------------------------------\n AgentFinding:\n type: object\n required: [severity, category, message]\n properties:\n id:\n type: string\n description: Unique finding identifier (e.g. F-001).\n severity:\n type: string\n enum: [info, warning, error, critical]\n category:\n type: string\n description: Domain vocabulary category (e.g. cli-contract-options, runtime-adapter).\n target:\n type: string\n description: File path or resource the finding applies to.\n location:\n type: string\n description: Line range or specific location within the target.\n message:\n type: string\n description: Human-readable description of the finding.\n recommendation:\n type: string\n description: Concrete remediation step.\n confidence:\n type: number\n minimum: 0\n maximum: 1\n description: Confidence score (0\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';
|
|
25
|
-
var CONTRACT_JSON_STR = '{\n "cli_contracts": "0.1.0",\n "info": {\n "title": "agent-runtime CLI",\n "version": "0.1.0",\n "description": "Runtime bridge for executing agent-contracts workflows on Agent SDKs.\\nGenerates typed contracts, handoff validators, and guardrail hooks from DSL,\\nthen runs workflows through pluggable SDK adapters.\\n",\n "license": {\n "name": "MIT"\n }\n },\n "command_sets": {\n "agent-runtime": {\n "summary": "CLI for agent-contracts-runtime \u2014 generate, run, and manage agent workflows.",\n "global_options": [\n {\n "name": "config",\n "aliases": [\n "c"\n ],\n "description": "Path to agent-runtime.config.yaml.",\n "schema": {\n "type": "string",\n "default": "./agent-runtime.config.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 agent-runtime.config.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 "cursor",\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 "cursor",\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 "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, Cursor, 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, cursor).",\n "schema": {\n "type": "string",\n "enum": [\n "claude",\n "cursor",\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 "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 "cursor",\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 "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 "doctor": {\n "summary": "Verify configuration, generated files, and SDK connectivity.",\n "description": "Runs a series of diagnostic checks to verify that the project\\nis correctly configured for agent-runtime execution.\\n\\nChecks: config existence, DSL existence, generated manifest freshness,\\nadapter configuration, API key environment variables, plugin entrypoint.\\n",\n "exits": {\n "0": {\n "description": "All checks passed.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/DoctorResult"\n }\n }\n },\n "1": {\n "description": "One or more checks failed.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/DoctorResult"\n }\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n }\n }\n }\n },\n "components": {\n "schemas": {\n "InitResult": {\n "type": "object",\n "required": [\n "files_created"\n ],\n "properties": {\n "files_created": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of files created by init."\n }\n }\n },\n "GenerateResult": {\n "type": "object",\n "required": [\n "files_generated",\n "dsl_hash",\n "generation_input_hash"\n ],\n "properties": {\n "files_generated": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of generated file paths."\n },\n "dsl_hash": {\n "type": "string",\n "description": "SHA-256 hash of the resolved DSL (canonical stringify)."\n },\n "generation_input_hash": {\n "type": "string",\n "description": "SHA-256 hash of all generation inputs."\n },\n "cleaned": {\n "type": "boolean",\n "description": "Whether --clean was used."\n },\n "check_mode": {\n "type": "boolean",\n "description": "Whether --check was used."\n },\n "has_differences": {\n "type": "boolean",\n "description": "In --check mode, whether differences were found."\n }\n }\n },\n "ValidationError": {\n "type": "object",\n "required": [\n "errors"\n ],\n "properties": {\n "errors": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "code",\n "message"\n ],\n "properties": {\n "code": {\n "type": "string"\n },\n "message": {\n "type": "string"\n },\n "path": {\n "type": "string",\n "description": "JSON path to the invalid element."\n }\n }\n }\n }\n }\n },\n "WorkflowResult": {\n "type": "object",\n "required": [\n "workflow_id",\n "status",\n "steps",\n "total_elapsed_ms"\n ],\n "properties": {\n "workflow_id": {\n "type": "string"\n },\n "status": {\n "type": "string",\n "enum": [\n "completed",\n "escalated",\n "gate_rejected",\n "error"\n ]\n },\n "steps": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/StepResult"\n }\n },\n "total_elapsed_ms": {\n "type": "integer",\n "minimum": 0\n },\n "escalation_reason": {\n "type": "string"\n },\n "error_message": {\n "type": "string"\n }\n }\n },\n "StepResult": {\n "type": "object",\n "required": [\n "step_index",\n "retries_used",\n "elapsed_ms",\n "outcome"\n ],\n "properties": {\n "step_index": {\n "type": "integer",\n "minimum": 0\n },\n "task_id": {\n "type": "string"\n },\n "gate_kind": {\n "type": "string"\n },\n "outcome": {\n "type": "object",\n "required": [\n "status"\n ],\n "properties": {\n "status": {\n "type": "string",\n "enum": [\n "success",\n "validation_error",\n "escalation",\n "error",\n "gate_approved",\n "gate_rejected",\n "skipped"\n ]\n }\n }\n },\n "retries_used": {\n "type": "integer",\n "minimum": 0\n },\n "elapsed_ms": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "ListResult": {\n "type": "object",\n "required": [\n "resource",\n "items"\n ],\n "properties": {\n "resource": {\n "type": "string",\n "enum": [\n "workflows",\n "tasks",\n "agents"\n ]\n },\n "items": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "id",\n "description"\n ],\n "properties": {\n "id": {\n "type": "string"\n },\n "description": {\n "type": "string"\n }\n }\n }\n }\n }\n },\n "ShowPromptResult": {\n "type": "object",\n "required": [\n "task_id",\n "agent_id",\n "prompt"\n ],\n "properties": {\n "task_id": {\n "type": "string",\n "description": "The task ID used to build the prompt."\n },\n "agent_id": {\n "type": "string",\n "description": "The target agent ID for this task."\n },\n "prompt": {\n "type": "string",\n "description": "The full generated prompt text."\n },\n "handoff_schema": {\n "type": "string",\n "description": "The handoff schema ID for the task result."\n },\n "plugins_applied": {\n "type": "boolean",\n "description": "Whether plugin prompt enhancers were applied."\n }\n }\n },\n "DoctorResult": {\n "type": "object",\n "required": [\n "checks",\n "all_passed"\n ],\n "properties": {\n "checks": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/DoctorCheck"\n }\n },\n "all_passed": {\n "type": "boolean"\n }\n }\n },\n "ImplementResult": {\n "type": "object",\n "required": [\n "files_created",\n "files_modified",\n "summary"\n ],\n "properties": {\n "files_created": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of new files created."\n },\n "files_modified": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of existing files modified."\n },\n "summary": {\n "type": "string",\n "description": "Human-readable summary of what was implemented."\n },\n "commands_added": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "name",\n "type"\n ],\n "properties": {\n "name": {\n "type": "string"\n },\n "type": {\n "type": "string",\n "enum": [\n "audit",\n "propose",\n "explain"\n ]\n },\n "description": {\n "type": "string"\n }\n }\n }\n },\n "next_steps": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "Recommended next steps for the developer."\n }\n }\n },\n "AuditImplementationResult": {\n "type": "object",\n "required": [\n "summary",\n "riskLevel",\n "findings"\n ],\n "properties": {\n "summary": {\n "type": "string",\n "description": "One-paragraph overall assessment."\n },\n "riskLevel": {\n "type": "string",\n "enum": [\n "low",\n "medium",\n "high",\n "critical"\n ],\n "description": "Derived from worst finding severity."\n },\n "findings": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/AgentFinding"\n }\n },\n "recommendedActions": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/AgentRecommendedAction"\n }\n },\n "metadata": {\n "type": "object",\n "properties": {\n "tool": {\n "type": "string"\n },\n "command": {\n "type": "string"\n },\n "version": {\n "type": "string"\n },\n "generatedAt": {\n "type": "string"\n },\n "adapter": {\n "type": "string"\n },\n "model": {\n "type": "string"\n }\n }\n }\n }\n },\n "DoctorCheck": {\n "type": "object",\n "required": [\n "name",\n "status"\n ],\n "properties": {\n "name": {\n "type": "string",\n "description": "Check name (e.g. config_exists, dsl_exists, manifest_fresh)."\n },\n "status": {\n "type": "string",\n "enum": [\n "pass",\n "fail",\n "warn"\n ]\n },\n "message": {\n "type": "string",\n "description": "Human-readable detail."\n }\n }\n },\n "AgentFinding": {\n "type": "object",\n "required": [\n "severity",\n "category",\n "message"\n ],\n "properties": {\n "id": {\n "type": "string",\n "description": "Unique finding identifier (e.g. F-001)."\n },\n "severity": {\n "type": "string",\n "enum": [\n "info",\n "warning",\n "error",\n "critical"\n ]\n },\n "category": {\n "type": "string",\n "description": "Domain vocabulary category (e.g. cli-contract-options, runtime-adapter)."\n },\n "target": {\n "type": "string",\n "description": "File path or resource the finding applies to."\n },\n "location": {\n "type": "string",\n "description": "Line range or specific location within the target."\n },\n "message": {\n "type": "string",\n "description": "Human-readable description of the finding."\n },\n "recommendation": {\n "type": "string",\n "description": "Concrete remediation step."\n },\n "confidence": {\n "type": "number",\n "minimum": 0,\n "maximum": 1,\n "description": "Confidence score (0\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}';
|
|
24
|
+
var CONTRACT_YAML = 'cli_contracts: 0.1.0\n\ninfo:\n title: agent-runtime CLI\n version: 0.1.0\n description: |\n Runtime bridge for executing agent-contracts workflows on Agent SDKs.\n Generates typed contracts, handoff validators, and guardrail hooks from DSL,\n then runs workflows through pluggable SDK adapters.\n license:\n name: MIT\n\ncommand_sets:\n agent-runtime:\n summary: CLI for agent-contracts-runtime \u2014 generate, run, and manage agent workflows.\n global_options:\n - name: config\n aliases: [c]\n description: Path to agent-runtime.config.yaml.\n schema:\n type: string\n default: ./agent-runtime.config.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 agent-runtime.config.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: [cursor, 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: [cursor, 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 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, Cursor, 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, cursor).\n schema:\n type: string\n enum: [claude, cursor, 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 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, cursor, 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 exits:\n "0":\n description: Audit completed with no findings above threshold.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/AuditImplementationResult"\n\n "1":\n description: Audit failed (agent error, unexpected failure).\n stderr:\n format: text\n\n "3":\n description: Input validation failed (e.g. project directory not found).\n stderr:\n format: text\n\n "10":\n description: Audit completed with findings above --fail-on threshold.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/AuditImplementationResult"\n\n "12":\n description: Adapter initialization error.\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects:\n - network\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: dry-run\n expectedDurationMs: 180000\n retryableExitCodes: [1, 12]\n\n # -----------------------------------------------------------------------\n # agents\n # -----------------------------------------------------------------------\n agents:\n summary: Output the full resolved DSL as structured data.\n description: |\n Outputs the complete resolved DSL (agents, tasks, workflows,\n handoff_types, etc.) embedded in this CLI binary.\n\n Useful for debugging, external tooling integration, and DSL\n inspection. Unlike `list`, which shows tabular summaries,\n this command outputs the full DSL structure.\n options:\n - name: format\n aliases: [F]\n description: Output format.\n schema:\n type: string\n enum: [yaml, json]\n default: yaml\n\n exits:\n "0":\n description: DSL output successfully.\n stdout:\n format: text\n\n "1":\n description: Failed to load embedded DSL.\n stderr:\n format: text\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n # -----------------------------------------------------------------------\n # doctor\n # -----------------------------------------------------------------------\n doctor:\n summary: Verify configuration, generated files, and SDK connectivity.\n description: |\n Runs a series of diagnostic checks to verify that the project\n is correctly configured for agent-runtime execution.\n\n Checks: config existence, DSL existence, generated manifest freshness,\n adapter configuration, API key environment variables, plugin entrypoint.\n exits:\n "0":\n description: All checks passed.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/DoctorResult"\n\n "1":\n description: One or more checks failed.\n stdout:\n format: json\n schema:\n $ref: "#/components/schemas/DoctorResult"\n\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: []\n\n\n# =============================================================================\n# Components\n# =============================================================================\n\ncomponents:\n schemas:\n # -------------------------------------------------------------------------\n # init\n # -------------------------------------------------------------------------\n InitResult:\n type: object\n required: [files_created]\n properties:\n files_created:\n type: array\n items:\n type: string\n description: List of files created by init.\n\n # -------------------------------------------------------------------------\n # generate\n # -------------------------------------------------------------------------\n GenerateResult:\n type: object\n required: [files_generated, dsl_hash, generation_input_hash]\n properties:\n files_generated:\n type: array\n items:\n type: string\n description: List of generated file paths.\n dsl_hash:\n type: string\n description: SHA-256 hash of the resolved DSL (canonical stringify).\n generation_input_hash:\n type: string\n description: SHA-256 hash of all generation inputs.\n cleaned:\n type: boolean\n description: Whether --clean was used.\n check_mode:\n type: boolean\n description: Whether --check was used.\n has_differences:\n type: boolean\n description: In --check mode, whether differences were found.\n\n ValidationError:\n type: object\n required: [errors]\n properties:\n errors:\n type: array\n items:\n type: object\n required: [code, message]\n properties:\n code:\n type: string\n message:\n type: string\n path:\n type: string\n description: JSON path to the invalid element.\n\n # -------------------------------------------------------------------------\n # run\n # -------------------------------------------------------------------------\n WorkflowResult:\n type: object\n required: [workflow_id, status, steps, total_elapsed_ms]\n properties:\n workflow_id:\n type: string\n status:\n type: string\n enum: [completed, escalated, gate_rejected, error]\n steps:\n type: array\n items:\n $ref: "#/components/schemas/StepResult"\n total_elapsed_ms:\n type: integer\n minimum: 0\n escalation_reason:\n type: string\n error_message:\n type: string\n\n StepResult:\n type: object\n required: [step_index, retries_used, elapsed_ms, outcome]\n properties:\n step_index:\n type: integer\n minimum: 0\n task_id:\n type: string\n gate_kind:\n type: string\n outcome:\n type: object\n required: [status]\n properties:\n status:\n type: string\n enum: [success, validation_error, escalation, error, gate_approved, gate_rejected, skipped]\n retries_used:\n type: integer\n minimum: 0\n elapsed_ms:\n type: integer\n minimum: 0\n\n # -------------------------------------------------------------------------\n # list\n # -------------------------------------------------------------------------\n ListResult:\n type: object\n required: [resource, items]\n properties:\n resource:\n type: string\n enum: [workflows, tasks, agents]\n items:\n type: array\n items:\n type: object\n required: [id, description]\n properties:\n id:\n type: string\n description:\n type: string\n\n # -------------------------------------------------------------------------\n # show-prompt\n # -------------------------------------------------------------------------\n ShowPromptResult:\n type: object\n required: [task_id, agent_id, prompt]\n properties:\n task_id:\n type: string\n description: The task ID used to build the prompt.\n agent_id:\n type: string\n description: The target agent ID for this task.\n prompt:\n type: string\n description: The full generated prompt text.\n handoff_schema:\n type: string\n description: The handoff schema ID for the task result.\n plugins_applied:\n type: boolean\n description: Whether plugin prompt enhancers were applied.\n\n # -------------------------------------------------------------------------\n # doctor\n # -------------------------------------------------------------------------\n DoctorResult:\n type: object\n required: [checks, all_passed]\n properties:\n checks:\n type: array\n items:\n $ref: "#/components/schemas/DoctorCheck"\n all_passed:\n type: boolean\n\n # -------------------------------------------------------------------------\n # implement\n # -------------------------------------------------------------------------\n ImplementResult:\n type: object\n required: [files_created, files_modified, summary]\n properties:\n files_created:\n type: array\n items:\n type: string\n description: List of new files created.\n files_modified:\n type: array\n items:\n type: string\n description: List of existing files modified.\n summary:\n type: string\n description: Human-readable summary of what was implemented.\n commands_added:\n type: array\n items:\n type: object\n required: [name, type]\n properties:\n name:\n type: string\n type:\n type: string\n enum: [audit, propose, explain]\n description:\n type: string\n next_steps:\n type: array\n items:\n type: string\n description: Recommended next steps for the developer.\n\n # -------------------------------------------------------------------------\n # audit-implementation\n # -------------------------------------------------------------------------\n AuditImplementationResult:\n type: object\n required: [summary, riskLevel, findings]\n properties:\n summary:\n type: string\n description: One-paragraph overall assessment.\n riskLevel:\n type: string\n enum: [low, medium, high, critical]\n description: Derived from worst finding severity.\n findings:\n type: array\n items:\n $ref: "#/components/schemas/AgentFinding"\n recommendedActions:\n type: array\n items:\n $ref: "#/components/schemas/AgentRecommendedAction"\n metadata:\n type: object\n properties:\n tool:\n type: string\n command:\n type: string\n version:\n type: string\n generatedAt:\n type: string\n adapter:\n type: string\n model:\n type: string\n\n DoctorCheck:\n type: object\n required: [name, status]\n properties:\n name:\n type: string\n description: Check name (e.g. config_exists, dsl_exists, manifest_fresh).\n status:\n type: string\n enum: [pass, fail, warn]\n message:\n type: string\n description: Human-readable detail.\n\n # -------------------------------------------------------------------------\n # Canonical agent result schemas (AgentAuditResult sub-types)\n # -------------------------------------------------------------------------\n AgentFinding:\n type: object\n required: [severity, category, message]\n properties:\n id:\n type: string\n description: Unique finding identifier (e.g. F-001).\n severity:\n type: string\n enum: [info, warning, error, critical]\n category:\n type: string\n description: Domain vocabulary category (e.g. cli-contract-options, runtime-adapter).\n target:\n type: string\n description: File path or resource the finding applies to.\n location:\n type: string\n description: Line range or specific location within the target.\n message:\n type: string\n description: Human-readable description of the finding.\n recommendation:\n type: string\n description: Concrete remediation step.\n confidence:\n type: number\n minimum: 0\n maximum: 1\n description: Confidence score (0\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';
|
|
25
|
+
var CONTRACT_JSON_STR = '{\n "cli_contracts": "0.1.0",\n "info": {\n "title": "agent-runtime CLI",\n "version": "0.1.0",\n "description": "Runtime bridge for executing agent-contracts workflows on Agent SDKs.\\nGenerates typed contracts, handoff validators, and guardrail hooks from DSL,\\nthen runs workflows through pluggable SDK adapters.\\n",\n "license": {\n "name": "MIT"\n }\n },\n "command_sets": {\n "agent-runtime": {\n "summary": "CLI for agent-contracts-runtime \u2014 generate, run, and manage agent workflows.",\n "global_options": [\n {\n "name": "config",\n "aliases": [\n "c"\n ],\n "description": "Path to agent-runtime.config.yaml.",\n "schema": {\n "type": "string",\n "default": "./agent-runtime.config.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 agent-runtime.config.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 "cursor",\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 "cursor",\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 "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, Cursor, 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, cursor).",\n "schema": {\n "type": "string",\n "enum": [\n "claude",\n "cursor",\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 "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 "cursor",\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 "exits": {\n "0": {\n "description": "Audit completed with no findings above threshold.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/AuditImplementationResult"\n }\n }\n },\n "1": {\n "description": "Audit failed (agent error, unexpected failure).",\n "stderr": {\n "format": "text"\n }\n },\n "3": {\n "description": "Input validation failed (e.g. project directory not found).",\n "stderr": {\n "format": "text"\n }\n },\n "10": {\n "description": "Audit completed with findings above --fail-on threshold.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/AuditImplementationResult"\n }\n }\n },\n "12": {\n "description": "Adapter initialization error.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": [\n "network"\n ],\n "sideEffectNote": "Network calls to LLM provider when adapter is not mock. Filesystem write only when --output is specified.",\n "safeDryRunOption": "dry-run",\n "expectedDurationMs": 180000,\n "retryableExitCodes": [\n 1,\n 12\n ]\n }\n },\n "agents": {\n "summary": "Output the full resolved DSL as structured data.",\n "description": "Outputs the complete resolved DSL (agents, tasks, workflows,\\nhandoff_types, etc.) embedded in this CLI binary.\\n\\nUseful for debugging, external tooling integration, and DSL\\ninspection. Unlike `list`, which shows tabular summaries,\\nthis command outputs the full DSL structure.\\n",\n "options": [\n {\n "name": "format",\n "aliases": [\n "F"\n ],\n "description": "Output format.",\n "schema": {\n "type": "string",\n "enum": [\n "yaml",\n "json"\n ],\n "default": "yaml"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "DSL output successfully.",\n "stdout": {\n "format": "text"\n }\n },\n "1": {\n "description": "Failed to load embedded DSL.",\n "stderr": {\n "format": "text"\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n },\n "doctor": {\n "summary": "Verify configuration, generated files, and SDK connectivity.",\n "description": "Runs a series of diagnostic checks to verify that the project\\nis correctly configured for agent-runtime execution.\\n\\nChecks: config existence, DSL existence, generated manifest freshness,\\nadapter configuration, API key environment variables, plugin entrypoint.\\n",\n "exits": {\n "0": {\n "description": "All checks passed.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/DoctorResult"\n }\n }\n },\n "1": {\n "description": "One or more checks failed.",\n "stdout": {\n "format": "json",\n "schema": {\n "$ref": "#/components/schemas/DoctorResult"\n }\n }\n }\n },\n "x-agent": {\n "riskLevel": "low",\n "requiresConfirmation": false,\n "idempotent": true,\n "sideEffects": []\n }\n }\n }\n }\n },\n "components": {\n "schemas": {\n "InitResult": {\n "type": "object",\n "required": [\n "files_created"\n ],\n "properties": {\n "files_created": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of files created by init."\n }\n }\n },\n "GenerateResult": {\n "type": "object",\n "required": [\n "files_generated",\n "dsl_hash",\n "generation_input_hash"\n ],\n "properties": {\n "files_generated": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of generated file paths."\n },\n "dsl_hash": {\n "type": "string",\n "description": "SHA-256 hash of the resolved DSL (canonical stringify)."\n },\n "generation_input_hash": {\n "type": "string",\n "description": "SHA-256 hash of all generation inputs."\n },\n "cleaned": {\n "type": "boolean",\n "description": "Whether --clean was used."\n },\n "check_mode": {\n "type": "boolean",\n "description": "Whether --check was used."\n },\n "has_differences": {\n "type": "boolean",\n "description": "In --check mode, whether differences were found."\n }\n }\n },\n "ValidationError": {\n "type": "object",\n "required": [\n "errors"\n ],\n "properties": {\n "errors": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "code",\n "message"\n ],\n "properties": {\n "code": {\n "type": "string"\n },\n "message": {\n "type": "string"\n },\n "path": {\n "type": "string",\n "description": "JSON path to the invalid element."\n }\n }\n }\n }\n }\n },\n "WorkflowResult": {\n "type": "object",\n "required": [\n "workflow_id",\n "status",\n "steps",\n "total_elapsed_ms"\n ],\n "properties": {\n "workflow_id": {\n "type": "string"\n },\n "status": {\n "type": "string",\n "enum": [\n "completed",\n "escalated",\n "gate_rejected",\n "error"\n ]\n },\n "steps": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/StepResult"\n }\n },\n "total_elapsed_ms": {\n "type": "integer",\n "minimum": 0\n },\n "escalation_reason": {\n "type": "string"\n },\n "error_message": {\n "type": "string"\n }\n }\n },\n "StepResult": {\n "type": "object",\n "required": [\n "step_index",\n "retries_used",\n "elapsed_ms",\n "outcome"\n ],\n "properties": {\n "step_index": {\n "type": "integer",\n "minimum": 0\n },\n "task_id": {\n "type": "string"\n },\n "gate_kind": {\n "type": "string"\n },\n "outcome": {\n "type": "object",\n "required": [\n "status"\n ],\n "properties": {\n "status": {\n "type": "string",\n "enum": [\n "success",\n "validation_error",\n "escalation",\n "error",\n "gate_approved",\n "gate_rejected",\n "skipped"\n ]\n }\n }\n },\n "retries_used": {\n "type": "integer",\n "minimum": 0\n },\n "elapsed_ms": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "ListResult": {\n "type": "object",\n "required": [\n "resource",\n "items"\n ],\n "properties": {\n "resource": {\n "type": "string",\n "enum": [\n "workflows",\n "tasks",\n "agents"\n ]\n },\n "items": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "id",\n "description"\n ],\n "properties": {\n "id": {\n "type": "string"\n },\n "description": {\n "type": "string"\n }\n }\n }\n }\n }\n },\n "ShowPromptResult": {\n "type": "object",\n "required": [\n "task_id",\n "agent_id",\n "prompt"\n ],\n "properties": {\n "task_id": {\n "type": "string",\n "description": "The task ID used to build the prompt."\n },\n "agent_id": {\n "type": "string",\n "description": "The target agent ID for this task."\n },\n "prompt": {\n "type": "string",\n "description": "The full generated prompt text."\n },\n "handoff_schema": {\n "type": "string",\n "description": "The handoff schema ID for the task result."\n },\n "plugins_applied": {\n "type": "boolean",\n "description": "Whether plugin prompt enhancers were applied."\n }\n }\n },\n "DoctorResult": {\n "type": "object",\n "required": [\n "checks",\n "all_passed"\n ],\n "properties": {\n "checks": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/DoctorCheck"\n }\n },\n "all_passed": {\n "type": "boolean"\n }\n }\n },\n "ImplementResult": {\n "type": "object",\n "required": [\n "files_created",\n "files_modified",\n "summary"\n ],\n "properties": {\n "files_created": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of new files created."\n },\n "files_modified": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "List of existing files modified."\n },\n "summary": {\n "type": "string",\n "description": "Human-readable summary of what was implemented."\n },\n "commands_added": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "name",\n "type"\n ],\n "properties": {\n "name": {\n "type": "string"\n },\n "type": {\n "type": "string",\n "enum": [\n "audit",\n "propose",\n "explain"\n ]\n },\n "description": {\n "type": "string"\n }\n }\n }\n },\n "next_steps": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "Recommended next steps for the developer."\n }\n }\n },\n "AuditImplementationResult": {\n "type": "object",\n "required": [\n "summary",\n "riskLevel",\n "findings"\n ],\n "properties": {\n "summary": {\n "type": "string",\n "description": "One-paragraph overall assessment."\n },\n "riskLevel": {\n "type": "string",\n "enum": [\n "low",\n "medium",\n "high",\n "critical"\n ],\n "description": "Derived from worst finding severity."\n },\n "findings": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/AgentFinding"\n }\n },\n "recommendedActions": {\n "type": "array",\n "items": {\n "$ref": "#/components/schemas/AgentRecommendedAction"\n }\n },\n "metadata": {\n "type": "object",\n "properties": {\n "tool": {\n "type": "string"\n },\n "command": {\n "type": "string"\n },\n "version": {\n "type": "string"\n },\n "generatedAt": {\n "type": "string"\n },\n "adapter": {\n "type": "string"\n },\n "model": {\n "type": "string"\n }\n }\n }\n }\n },\n "DoctorCheck": {\n "type": "object",\n "required": [\n "name",\n "status"\n ],\n "properties": {\n "name": {\n "type": "string",\n "description": "Check name (e.g. config_exists, dsl_exists, manifest_fresh)."\n },\n "status": {\n "type": "string",\n "enum": [\n "pass",\n "fail",\n "warn"\n ]\n },\n "message": {\n "type": "string",\n "description": "Human-readable detail."\n }\n }\n },\n "AgentFinding": {\n "type": "object",\n "required": [\n "severity",\n "category",\n "message"\n ],\n "properties": {\n "id": {\n "type": "string",\n "description": "Unique finding identifier (e.g. F-001)."\n },\n "severity": {\n "type": "string",\n "enum": [\n "info",\n "warning",\n "error",\n "critical"\n ]\n },\n "category": {\n "type": "string",\n "description": "Domain vocabulary category (e.g. cli-contract-options, runtime-adapter)."\n },\n "target": {\n "type": "string",\n "description": "File path or resource the finding applies to."\n },\n "location": {\n "type": "string",\n "description": "Line range or specific location within the target."\n },\n "message": {\n "type": "string",\n "description": "Human-readable description of the finding."\n },\n "recommendation": {\n "type": "string",\n "description": "Concrete remediation step."\n },\n "confidence": {\n "type": "number",\n "minimum": 0,\n "maximum": 1,\n "description": "Confidence score (0\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}';
|
|
26
26
|
|
|
27
27
|
// src/generated/cli/program.ts
|
|
28
28
|
function createProgram(handlers2, version) {
|
|
@@ -72,6 +72,9 @@ function createProgram(handlers2, version) {
|
|
|
72
72
|
}
|
|
73
73
|
await handlers2.auditImplementation(projectDir, opts, cmd.optsWithGlobals());
|
|
74
74
|
});
|
|
75
|
+
program2.command("agents").description("Output the full resolved DSL as structured data.").option("-F, --format <value>", "Output format.", "yaml").action(async (opts, cmd) => {
|
|
76
|
+
await handlers2.agents(opts, cmd.optsWithGlobals());
|
|
77
|
+
});
|
|
75
78
|
program2.command("doctor").description("Verify configuration, generated files, and SDK connectivity.").action(async (opts, cmd) => {
|
|
76
79
|
await handlers2.doctor({}, cmd.optsWithGlobals());
|
|
77
80
|
});
|
|
@@ -92,7 +95,7 @@ function createProgram(handlers2, version) {
|
|
|
92
95
|
type: "cli-contracts/extract",
|
|
93
96
|
extractedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
94
97
|
specVersion: doc.cli_contracts ?? "0.1.0",
|
|
95
|
-
commands: ["agent-runtime.init", "agent-runtime.generate", "agent-runtime.run", "agent-runtime.list", "agent-runtime.show-prompt", "agent-runtime.implement", "agent-runtime.audit-implementation", "agent-runtime.doctor"]
|
|
98
|
+
commands: ["agent-runtime.init", "agent-runtime.generate", "agent-runtime.run", "agent-runtime.list", "agent-runtime.show-prompt", "agent-runtime.implement", "agent-runtime.audit-implementation", "agent-runtime.agents", "agent-runtime.doctor"]
|
|
96
99
|
};
|
|
97
100
|
}
|
|
98
101
|
Object.assign(out, doc);
|
|
@@ -109,7 +112,7 @@ function createProgram(handlers2, version) {
|
|
|
109
112
|
yamlLines.push("extractedAt: " + (/* @__PURE__ */ new Date()).toISOString());
|
|
110
113
|
yamlLines.push("spec_version: " + (doc.cli_contracts ?? "0.1.0"));
|
|
111
114
|
yamlLines.push("commands:");
|
|
112
|
-
for (const id of ["agent-runtime.init", "agent-runtime.generate", "agent-runtime.run", "agent-runtime.list", "agent-runtime.show-prompt", "agent-runtime.implement", "agent-runtime.audit-implementation", "agent-runtime.doctor"]) {
|
|
115
|
+
for (const id of ["agent-runtime.init", "agent-runtime.generate", "agent-runtime.run", "agent-runtime.list", "agent-runtime.show-prompt", "agent-runtime.implement", "agent-runtime.audit-implementation", "agent-runtime.agents", "agent-runtime.doctor"]) {
|
|
113
116
|
yamlLines.push(" - " + id);
|
|
114
117
|
}
|
|
115
118
|
}
|
|
@@ -490,7 +493,7 @@ import { fileURLToPath } from "url";
|
|
|
490
493
|
var implementationAuditor = {
|
|
491
494
|
id: "implementation-auditor",
|
|
492
495
|
role_name: "Implementation Auditor",
|
|
493
|
-
purpose: "Audits an existing LLM command integration to verify it correctly\nfollows the agent-contracts + agent-contracts-runtime + cli-contracts\nstack conventions. Detects architectural violations, missing patterns,\nincorrect API usage, and deviations from the canonical\nintegrate-llm-commands pattern.\n\nThis agent is read-only \u2014 it analyzes code but does not modify it.\nIt produces structured findings (AgentAuditResult) that identify\nexactly what is wrong and how to fix it.\n\n## What This Agent Checks\n\n### Layer 1: agent-contracts DSL\n- DSL entry has version:1 and system block with id/name\n- Agents defined with all required fields (role_name, purpose, mode,\n can_read_artifacts, can_write_artifacts, responsibilities, constraints)\n- Tasks have target_agent, workflow, result_handoff, completion_criteria\n- Handoff type schemas conform to AgentAuditResult base shape\n- Workflows define steps with correct task/agent cross-references\n- Guardrails and guardrail_policies are defined\n- agent-runtime.config.yaml exists with dsl and generated_dir\n\n### Layer 2: agent-contracts-runtime Integration\n- orchestrator.ts uses
|
|
496
|
+
purpose: "Audits an existing LLM command integration to verify it correctly\nfollows the agent-contracts + agent-contracts-runtime + cli-contracts\nstack conventions. Detects architectural violations, missing patterns,\nincorrect API usage, and deviations from the canonical\nintegrate-llm-commands pattern.\n\nThis agent is read-only \u2014 it analyzes code but does not modify it.\nIt produces structured findings (AgentAuditResult) that identify\nexactly what is wrong and how to fix it.\n\n## What This Agent Checks\n\n### Layer 1: agent-contracts DSL\n- DSL entry has version:1 and system block with id/name\n- Agents defined with all required fields (role_name, purpose, mode,\n can_read_artifacts, can_write_artifacts, responsibilities, constraints)\n- Tasks have target_agent, workflow, result_handoff, completion_criteria\n- Handoff type schemas conform to AgentAuditResult base shape\n- Workflows define steps with correct task/agent cross-references\n- Guardrails and guardrail_policies are defined\n- agent-runtime.config.yaml exists with dsl and generated_dir\n\n### Layer 2: agent-contracts-runtime Integration\n- orchestrator.ts uses runWorkflow(), NOT runTask() or adapter.send()\n- runTask() is a low-level internal API \u2014 consumer projects must\n use runWorkflow() which handles workflow DAG, plugin hooks, gates\n- Adapters imported from agent-contracts-runtime/adapters/*, not custom\n- Dynamic import pattern for graceful degradation (exit 11/12)\n- Generated registries imported from src/generated/dsl/index.js\n- Registries (including workflowRegistry) passed to runWorkflow\n- Plugin hooks not bypassed\n- No hand-rolled prompt building (use buildTaskPrompt or let runWorkflow do it)\n\n### Layer 3: cli-contracts Compliance\n- cli-contract.yaml has LLM commands with all standard options:\n --adapter, --model, --dry-run, --fail-on, --output, --report-format\n- x-agent metadata present (riskLevel, safeDryRunOption, expectedDurationMs)\n- Exit codes follow convention (0, 1, 3, 10, 11, 12)\n- components/schemas includes AgentAuditResult and related types\n- --report-format used (not --format) for LLM commands\n\n### Architecture & Patterns\n- src/agents/ module structure (orchestrator, context-builder, formatter, types)\n- Context builder caps input at 16KB\n- Formatter implements computeExitCode with correct threshold logic\n- --dry-run returns prompt without LLM call\n- No direct LLM API calls anywhere in the codebase\n\n### Semantic Design Coherence\n- Context-builder must contain only domain DATA (file contents,\n config, scan results) \u2014 never agent INSTRUCTIONS (evaluation\n criteria, rules, anti-patterns, output format specifications).\n These belong in the DSL agent definition and are injected by\n buildTaskPrompt / runWorkflow. Hardcoding instructions in\n context-builder defeats the purpose of using DSL.\n- Agent mode must match purpose: read-only agents must not have\n write-oriented purposes, read-write agents must propagate cwd\n to their adapter so file tools operate in the project directory.\n- CLI must use cli-contracts' generated CommandHandlers interface\n and createProgram() \u2014 not manually wired Commander commands.\n",
|
|
494
497
|
mode: "read-only",
|
|
495
498
|
dispatch_only: false,
|
|
496
499
|
can_read_artifacts: [],
|
|
@@ -507,8 +510,8 @@ var implementationAuditor = {
|
|
|
507
510
|
"Validate task definitions: target_agent matches a defined agent, workflow matches a defined workflow, result_handoff matches a defined handoff type, completion_criteria are specific and testable.",
|
|
508
511
|
"Verify handoff type schemas conform to AgentAuditResult shape when applicable (summary, riskLevel, findings[], recommendedActions[], metadata). Check $ref usage and SSoT comments for inlined schemas.",
|
|
509
512
|
"Check that guardrails and guardrail_policies are defined, and that output-schema-conformance is included.",
|
|
510
|
-
"Scan src/agents/orchestrator.ts for: (1) imports from agent-contracts-runtime (not custom SDK wrappers), (2) usage of
|
|
511
|
-
"Verify no file in the project calls adapter.send(), adapter.followUp(),
|
|
513
|
+
"Scan src/agents/orchestrator.ts for: (1) imports from agent-contracts-runtime (not custom SDK wrappers), (2) usage of runWorkflow() \u2014 NOT runTask() which is a low-level internal API that bypasses workflow orchestration, plugin hooks, and gate steps, (3) dynamic import pattern with exit code 11 for missing runtime and exit code 12 for adapter errors, (4) generated registries (including workflowRegistry) imported and passed to runWorkflow.",
|
|
514
|
+
"Verify no file in the project calls adapter.send(), adapter.followUp(), adapter.sendExecution(), or runTask() directly \u2014 all LLM invocations must go through runWorkflow().",
|
|
512
515
|
"Check that src/generated/dsl/ exists and contains the expected files (agents.ts, tasks.ts, workflows.ts, handoffs.ts, index.ts). Verify the .manifest.json exists and is not stale.",
|
|
513
516
|
"Verify adapter creation uses the correct constructors: CursorSdkAdapter.create() (async static), ClaudeAgentSdkAdapter constructor, OpenAIAgentsSdkAdapter constructor, etc.",
|
|
514
517
|
"Check cli-contract.yaml for each LLM command: all six standard options present (--adapter, --model, --dry-run, --fail-on, --output, --report-format). Verify --report-format is used (not --format).",
|
|
@@ -544,7 +547,7 @@ var implementationAuditor = {
|
|
|
544
547
|
},
|
|
545
548
|
{
|
|
546
549
|
"id": "R-AUDIT-003",
|
|
547
|
-
"description": "Critical findings must be surfaced for: (1) direct adapter.send() calls bypassing
|
|
550
|
+
"description": "Critical findings must be surfaced for: (1) direct adapter.send() calls bypassing runWorkflow, (2) runTask() used instead of runWorkflow() \u2014 runTask is a low-level internal API that bypasses workflow orchestration, (3) custom adapter classes not from agent-contracts-runtime, (4) missing generated registries in runWorkflow calls.",
|
|
548
551
|
"severity": "mandatory"
|
|
549
552
|
},
|
|
550
553
|
{
|
|
@@ -554,7 +557,12 @@ var implementationAuditor = {
|
|
|
554
557
|
},
|
|
555
558
|
{
|
|
556
559
|
"id": "R-AUDIT-005",
|
|
557
|
-
"description": "Context-builder must be audited for SSoT violations. Any hardcoded agent instructions (evaluation criteria, rules, anti-patterns, output format specs) in context-builder is a critical finding \u2014 these belong in the DSL agent definition and are injected by buildTaskPrompt /
|
|
560
|
+
"description": "Context-builder must be audited for SSoT violations. Any hardcoded agent instructions (evaluation criteria, rules, anti-patterns, output format specs) in context-builder is a critical finding \u2014 these belong in the DSL agent definition and are injected by buildTaskPrompt / runWorkflow. Context-builder may only contain domain-specific data (file contents, configuration, scan results, project metadata).",
|
|
561
|
+
"severity": "mandatory"
|
|
562
|
+
},
|
|
563
|
+
{
|
|
564
|
+
"id": "R-AUDIT-007",
|
|
565
|
+
"description": "runTask() usage in consumer projects is a CRITICAL finding. Consumer projects integrating with cli-contracts must use runWorkflow() exclusively. runTask() is a low-level internal API that bypasses workflow DAG orchestration, workflow-level plugin hooks (beforeWorkflow/afterWorkflow), gate steps, and step dependencies. Any occurrence of runTask import or call in orchestrator, command handler, or CLI entry point code must be reported as severity: critical.",
|
|
558
566
|
"severity": "mandatory"
|
|
559
567
|
},
|
|
560
568
|
{
|
|
@@ -598,17 +606,17 @@ var llmFeatureImplementer = {
|
|
|
598
606
|
"Define guardrails (output-schema-conformance, domain-specific safety) and guardrail_policies grouping them with severity and action.",
|
|
599
607
|
"Create agent-runtime.config.yaml: dsl points to main DSL file, generated_dir points to src/generated/dsl.",
|
|
600
608
|
"Implement src/agents/types.ts: TaskId union type, AgentConfig interface (adapter, model, temperature), AgentOptions interface (dryRun, failOn), AgentRunResult interface (taskId, data, raw, prompt, dryRun, status, errorMessage, followUpsUsed, retriesUsed).",
|
|
601
|
-
"Implement src/agents/orchestrator.ts: createAdapter() with dynamic imports from agent-contracts-runtime/adapters/*,
|
|
609
|
+
"Implement src/agents/orchestrator.ts: createAdapter() with dynamic imports from agent-contracts-runtime/adapters/*, runAgentWorkflow() that imports runWorkflow from agent-contracts-runtime, loads generated registries (including workflowRegistry) from src/generated/dsl/index.js, and calls runWorkflow with registries. NEVER use runTask \u2014 it is a low-level internal API that bypasses workflow orchestration.",
|
|
602
610
|
"Implement src/agents/context-builder.ts: build{Command}Context() functions that transform CLI inputs into structured markdown prompts. Cap context at 16KB. Structure: # Request, ## Configuration, ## Target, ## Instructions.",
|
|
603
611
|
"Implement src/agents/formatter.ts: computeExitCode() mapping findings to exit codes via --fail-on threshold, formatResultText() with severity icons, formatResultJson() for structured output.",
|
|
604
|
-
"Create src/commands/{command}.ts handlers: load config, call context builder, call
|
|
612
|
+
"Create src/commands/{command}.ts handlers: load config, call context builder, call runAgentWorkflow, format output, compute exit code.",
|
|
605
613
|
"Update cli-contract.yaml: add command definitions with standard LLM options (--adapter, --model, --dry-run, --fail-on, --output, --report-format), exit codes (0, 1, 3, 10, 11, 12), x-agent metadata, and register AgentAuditResult/AgentFinding/AgentRecommendedAction in components/schemas.",
|
|
606
614
|
'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.'
|
|
607
615
|
],
|
|
608
616
|
constraints: [
|
|
609
617
|
"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, CursorSdkAdapter from agent-contracts-runtime/adapters/cursor-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk, GeminiSdkAdapter from agent-contracts-runtime/adapters/gemini-sdk, MockAdapter from agent-contracts-runtime/adapters/mock.",
|
|
610
|
-
"NEVER call adapter.send() or adapter.sendExecution() directly. All LLM invocations must go through
|
|
611
|
-
'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 {
|
|
618
|
+
"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.",
|
|
619
|
+
'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); }',
|
|
612
620
|
"LLM commands use --report-format (json|text|yaml) for output format. --format is reserved for deterministic commands. Never mix them.",
|
|
613
621
|
"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.).",
|
|
614
622
|
"Standard LLM command options (all must be present): --adapter <name> (mock|cursor|claude|openai|gemini, default varies), --model <name> (optional override), --dry-run (output prompt without LLM call), --fail-on <level> (warning|error|critical, default error), --output/-o <file> (write to file instead of stdout), --report-format <fmt> (json|text|yaml, default json).",
|
|
@@ -618,10 +626,9 @@ var llmFeatureImplementer = {
|
|
|
618
626
|
"Main DSL entry must have version:1 and a system block with id and name. Without these, the generator produces numbered files instead of named ones.",
|
|
619
627
|
"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.",
|
|
620
628
|
"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}).",
|
|
621
|
-
"
|
|
622
|
-
"runWorkflow overloads: (1) runWorkflow(adapter, workflowId, options, registries?) \u2014 legacy. (2) runWorkflow(adapter, invocation, registries?) \u2014 structured. WorkflowInvocation: { workflow, handoff?, user_request?, runtime? {maxFollowUps,maxRetries,timeoutMs,readonly,dryRun}, hooks? {onStepComplete,onGate,onOptionalStep}, context? {cwd,environment,artifacts,variables} }. WorkflowResult: { workflow_id, status (completed|escalated|gate_rejected|error), steps[], total_elapsed_ms, escalation_reason?, error_message? }.",
|
|
629
|
+
"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.",
|
|
623
630
|
"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), CursorSdkAdapter.create({apiKey, model?, cwd?, guardrailHooks?}) \u2014 async static, ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?}), GeminiSdkAdapter({apiKey?, model?, systemInstruction?, temperature?, maxOutputTokens?, guardrailHooks?}).",
|
|
624
|
-
'Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from "../generated/dsl/index.js". Pass these as
|
|
631
|
+
'Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from "../generated/dsl/index.js". Pass these as registries to runWorkflow: { workflowRegistry, taskRegistry, agentRegistry, handoffSchemas }.',
|
|
625
632
|
"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).",
|
|
626
633
|
"x-agent fields for LLM commands in cli-contract.yaml: riskLevel (low for read-only analysis), requiresConfirmation (false for read-only), idempotent (true for analysis), sideEffects ([network]), sideEffectNote (describe network call and optional file write), safeDryRunOption (dry-run), expectedDurationMs (120000 typical), retryableExitCodes ([1, 12])."
|
|
627
634
|
],
|
|
@@ -633,7 +640,7 @@ var llmFeatureImplementer = {
|
|
|
633
640
|
},
|
|
634
641
|
{
|
|
635
642
|
"id": "R-IMPL-002",
|
|
636
|
-
"description": "All LLM invocations must use
|
|
643
|
+
"description": "All LLM invocations must use runWorkflow() from agent-contracts-runtime. NEVER use runTask() \u2014 it is a low-level internal API that bypasses workflow orchestration. Never call adapter.send(), adapter.followUp(), or adapter.sendExecution() directly. The runtime handles prompt building, schema validation, retry, followUp, workflow DAG, and plugin hooks.",
|
|
637
644
|
"severity": "mandatory"
|
|
638
645
|
},
|
|
639
646
|
{
|
|
@@ -658,7 +665,7 @@ var llmFeatureImplementer = {
|
|
|
658
665
|
},
|
|
659
666
|
{
|
|
660
667
|
"id": "R-IMPL-007",
|
|
661
|
-
"description": "Generated DSL contracts must be imported from src/generated/dsl/index.js and passed as registries to
|
|
668
|
+
"description": "Generated DSL contracts must be imported from src/generated/dsl/index.js and passed as registries to runWorkflow. Never hard-code agent definitions, task definitions, or handoff schemas in application code.",
|
|
662
669
|
"severity": "mandatory"
|
|
663
670
|
}
|
|
664
671
|
],
|
|
@@ -685,7 +692,7 @@ var agentRegistry = {
|
|
|
685
692
|
// src/builtin-agents/generated/tasks.ts
|
|
686
693
|
var implementLlmFeature = {
|
|
687
694
|
id: "implement-llm-feature",
|
|
688
|
-
description: 'Implement LLM-powered commands in a target CLI tool using the\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\n\n## Implementation Procedure\n\n### Step 1: Project Analysis\n\nRead these files from the target project:\n- cli-contract.yaml \u2014 existing commands, components/schemas, x-agent usage\n- package.json \u2014 dependencies, scripts, bin entries, type:"module" check\n- tsconfig.json \u2014 module resolution, paths, outDir\n- src/ directory structure \u2014 understand existing command handler pattern\n\nDetermine:\n- Which LLM commands to add (audit / propose / explain)\n- What domain-specific context each command needs\n- What structured output schema each command returns\n- Whether the project already has agent-contracts integration\n\n### Step 2: Install Dependencies\n\nAdd to package.json devDependencies:\n- agent-contracts: ^0.32.0\n- agent-contracts-runtime: ^0.31.0\n- zod: ^4.0.0\n\nAdd optional peerDependencies for SDK packages:\n- @anthropic-ai/claude-agent-sdk: >=0.2.0\n- @openai/agents: >=0.10.0\n- @google/genai: >=2.0.0\n- @cursor/sdk (no version constraint)\n\n### Step 3: Create DSL Definitions\n\nCreate directory structure:\n\n dsl/\n \u251C\u2500\u2500 {project}-dsl.yaml\n \u251C\u2500\u2500 agent-runtime.config.yaml\n \u251C\u2500\u2500 agents/\n \u2502 \u2514\u2500\u2500 {agent-name}.yaml\n \u251C\u2500\u2500 tasks.yaml\n \u2514\u2500\u2500 handoff-types.yaml\n\n**Main DSL entry** (`dsl/{project}-dsl.yaml`):\n\n version: 1\n system:\n id: {project}\n name: "{Project} Agent System"\n default_workflow_order:\n - {workflow-ids}\n agents: { $ref: "./agents/" }\n tasks: { $ref: "./tasks.yaml" }\n handoff_types: { $ref: "./handoff-types.yaml" }\n guardrails:\n output-schema-conformance:\n description: ...\n scope: { agents: [...], tasks: [...] }\n rationale: ...\n guardrail_policies:\n {domain}-safety-policy:\n rules:\n - guardrail: output-schema-conformance\n severity: critical\n action: block\n workflow:\n {workflow-id}:\n description: ...\n trigger: cli-command\n entry_conditions: [...]\n steps:\n - type: delegate\n task: {task-id}\n from_agent: {agent-id}\n\n**Agent definition** (`dsl/agents/{agent-name}.yaml`):\n\n {agent-name}:\n role_name: "{Role Name}"\n purpose: >-\n Domain-specific purpose describing what the agent knows\n and what it can do that static rules cannot.\n mode: read-only\n can_read_artifacts: []\n can_write_artifacts: []\n can_invoke_agents: []\n can_execute_tools: []\n can_return_handoffs: [{result-handoff-ids}]\n responsibilities: [...]\n constraints: [...]\n rules:\n - id: "R-{PREFIX}-001"\n description: ...\n severity: mandatory\n escalation_criteria:\n - condition: ...\n action: stop_and_report\n\n**Tasks** (`dsl/tasks.yaml`):\n\n {task-id}:\n description: ...\n target_agent: {agent-name}\n allowed_from_agents: [{agent-name}]\n workflow: {workflow-id}\n input_artifacts: []\n invocation_handoff: {request-handoff}\n result_handoff: {result-handoff}\n responsibilities: [...]\n completion_criteria: [...]\n\n**Handoff types** (`dsl/handoff-types.yaml`):\nUse AgentAuditResult shape as the base for result types:\n\n {result-handoff}:\n version: 1\n description: ...\n schema:\n type: object\n required: [summary, riskLevel, findings]\n properties:\n summary: { type: string }\n riskLevel:\n type: string\n enum: [low, medium, high, critical]\n findings:\n type: array\n items:\n type: object\n required: [severity, category, message]\n properties:\n id: { type: string }\n severity:\n type: string\n enum: [info, warning, error, critical]\n category: { type: string }\n target: { type: string }\n location: { type: string }\n message: { type: string }\n recommendation: { type: string }\n confidence: { type: number, minimum: 0, maximum: 1 }\n recommendedActions:\n type: array\n items:\n type: object\n required: [kind, title]\n properties:\n kind:\n type: string\n enum: [run_command, edit_file, review, confirm, block, ignore]\n title: { type: string }\n command: { type: string }\n target: { type: string }\n rationale: { type: string }\n metadata:\n type: object\n properties:\n tool: { type: string }\n command: { type: string }\n version: { type: string }\n generatedAt: { type: string }\n adapter: { type: string }\n model: { type: string }\n\nDomain-specific result types add properties alongside the base fields.\n\n**Runtime config** (`dsl/agent-runtime.config.yaml`):\n\n dsl: ./{project}-dsl.yaml\n generated_dir: ../src/generated/dsl\n\n### Step 4: Generate TypeScript Contracts\n\nAdd to package.json scripts:\n\n "dsl:generate": "agent-runtime generate --config dsl/agent-runtime.config.yaml"\n\nRun: npm run dsl:generate\n\nThis produces src/generated/dsl/ containing:\n- agents.ts (AgentContract interface + agentRegistry)\n- tasks.ts (TaskContract interface + taskRegistry)\n- workflows.ts (WorkflowContract + workflowRegistry)\n- handoffs.ts (Zod schemas + handoffSchemas + factory functions)\n- index.ts (barrel re-exports)\n\n### Step 5: Implement src/agents/ Module\n\n**src/agents/types.ts**:\n\n import type { {ResultType} } from "../generated/dsl/handoffs.js";\n\n export type TaskId = "{task-1}" | "{task-2}" | ...;\n\n export interface AgentConfig {\n adapter?: string;\n model?: string;\n temperature?: number;\n }\n\n export interface AgentOptions {\n dryRun?: boolean;\n failOn?: "warning" | "error" | "critical";\n }\n\n export interface AgentRunResult {\n taskId: TaskId;\n data: {ResultType} | null;\n raw: string;\n prompt: string;\n dryRun: boolean;\n status: "success" | "error" | "escalation" | "validation_error";\n errorMessage?: string;\n followUpsUsed: number;\n retriesUsed: number;\n }\n\n**src/agents/orchestrator.ts**:\n\n export const EXIT_RUNTIME_MISSING = 11;\n export const EXIT_ADAPTER_ERROR = 12;\n\n async function createAdapter(pkg: string, name: string, config: AgentConfig) {\n switch (name) {\n case "mock": {\n const m = await import(`${pkg}/adapters/mock`);\n return new m.MockAdapter();\n }\n case "cursor": {\n const m = await import(`${pkg}/adapters/cursor-sdk`);\n return m.CursorSdkAdapter.create({ apiKey: process.env.CURSOR_API_KEY, model: config.model });\n }\n case "claude": {\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\n }\n case "openai": {\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\n }\n case "gemini": {\n const m = await import(`${pkg}/adapters/gemini-sdk`);\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\n }\n }\n }\n\n export async function runAgentTask(\n userRequest: string, taskId: TaskId, config: AgentConfig, options: AgentOptions,\n ): Promise<AgentRunResult> {\n if (options.dryRun) return { taskId, data:null, raw:"", prompt:userRequest, dryRun:true, status:"success", followUpsUsed:0, retriesUsed:0 };\n\n const PKG = "agent-contracts-runtime";\n let runTask;\n try { ({ runTask } = await import(PKG)); }\n catch { throw Object.assign(new Error("agent-contracts-runtime not installed"), { exitCode: EXIT_RUNTIME_MISSING }); }\n\n let registries;\n try {\n const dsl = await import("../generated/dsl/index.js");\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas };\n } catch { registries = { agentRegistry:{}, taskRegistry:{}, handoffSchemas:{} }; }\n\n const adapter = await createAdapter(PKG, config.adapter ?? "mock", config);\n const result = await runTask(adapter, taskId, { user_request: userRequest }, { maxFollowUps:3, maxRetries:1, ...registries });\n // map result.outcome to AgentRunResult\n }\n\n**src/agents/context-builder.ts**:\n\nCRITICAL: context-builder builds the USER-SIDE prompt only.\nAgent instructions (purpose, responsibilities, constraints, rules,\nevaluation criteria, anti-patterns, output format) are defined in\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\nbuildTaskPrompt / runTask. NEVER hardcode these in context-builder.\n\nContext-builder SHOULD contain:\n- Domain-specific DATA: file contents, configuration, scan results\n- Project metadata: target paths, dialect, directory structure\n- Deterministic pre-analysis: lint results, schema excerpts\n- Operational context: cwd, timestamps\n- Brief task framing: "# Migration Safety Audit Request"\n\nContext-builder MUST NOT contain:\n- "## Instructions" / "## Required Patterns" sections\n- Output format specifications (handled by handoff schema)\n- Evaluation criteria or checklists\n- Anti-pattern definitions or rule sets\n- API reference material\n- Anything that duplicates DSL agent purpose/responsibilities/rules\n\n export function build{Command}Context(target, config): string {\n const sections = [];\n sections.push("# {Command} Request");\n sections.push(`## Target\\n\\n${target}`);\n // Domain data only \u2014 no instructions here.\n // Agent instructions come from DSL via buildTaskPrompt.\n // Cap total context at 16KB\n return sections.join("\\n\\n");\n }\n\n**src/agents/formatter.ts**:\n\n export function computeExitCode(result, options): number {\n if (result.dryRun) return 0;\n if (result.status !== "success") return 1;\n const order = ["info","warning","error","critical"];\n const threshold = order.indexOf(options.failOn ?? "error");\n return result.data.findings.some(f => order.indexOf(f.severity) >= threshold) ? 10 : 0;\n }\n\n export function formatResultText(result): string { /* severity icons, structured output */ }\n export function formatResultJson(result): string { return JSON.stringify(result.data, null, 2); }\n\n### Step 6: Create CLI Command Handlers\n\nFor each LLM command, create src/commands/{command}.ts:\n\n export async function command{Name}(target, opts) {\n const cwd = process.cwd();\n const context = build{Name}Context(target, config);\n const agentConfig = { adapter: opts.adapter, model: opts.model, cwd };\n const result = await runAgentTask(context, "{task-id}", agentConfig, agentOpts);\n if (opts.reportFormat === "json") console.log(formatResultJson(result));\n else console.log(formatResultText(result));\n process.exit(computeExitCode(result, opts));\n }\n\nWire handlers through cli-contracts\' generated program:\n\n import { createProgram, type CommandHandlers } from \'./generated/program.js\';\n\n const handlers: CommandHandlers = {\n {commandName}: async (target, opts) => {\n await command{Name}(target, opts);\n },\n // ... other handlers\n };\n\n createProgram(handlers, version).parse();\n\n### Step 7: Update cli-contract.yaml\n\nAdd each LLM command with standard options and x-agent metadata:\n\n {command-name}:\n summary: "{Command summary}"\n arguments: [...]\n options:\n - name: adapter\n schema: { type: string, enum: [mock, cursor, claude, openai, gemini] }\n - name: model\n schema: { type: string }\n - name: dry-run\n schema: { type: boolean, default: false }\n - name: fail-on\n schema: { type: string, enum: [warning, error, critical], default: error }\n - name: output\n aliases: [o]\n schema: { type: string }\n file: { mode: write }\n - name: report-format\n schema: { type: string, enum: [json, text, yaml], default: json }\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: [network]\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: dry-run\n expectedDurationMs: 120000\n retryableExitCodes: [1, 12]\n exits:\n \'0\': { description: "No blocking findings.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'1\': { description: "General error.", stderr: { format: text } }\n \'3\': { description: "Input validation failed.", stderr: { format: json } }\n \'10\': { description: "Blocking findings detected.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'11\': { description: "Runtime not installed.", stderr: { format: json } }\n \'12\': { description: "Adapter error.", stderr: { format: json } }\n\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\nto components/schemas if not already present.\n\n### Step 8: Update README\n\nAdd "Agent-Native Toolchain" section after mechanical features:\n- Intro: tool encapsulates domain-specific semantic reasoning\n- Deterministic checks first, then semantic audit\n- Structured findings (AgentAuditResult/AgentFinding)\n- LLM Adapter Configuration table\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\n',
|
|
695
|
+
description: 'Implement LLM-powered commands in a target CLI tool using the\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\n\n## Implementation Procedure\n\n### Step 1: Project Analysis\n\nRead these files from the target project:\n- cli-contract.yaml \u2014 existing commands, components/schemas, x-agent usage\n- package.json \u2014 dependencies, scripts, bin entries, type:"module" check\n- tsconfig.json \u2014 module resolution, paths, outDir\n- src/ directory structure \u2014 understand existing command handler pattern\n\nDetermine:\n- Which LLM commands to add (audit / propose / explain)\n- What domain-specific context each command needs\n- What structured output schema each command returns\n- Whether the project already has agent-contracts integration\n\n### Step 2: Install Dependencies\n\nAdd to package.json devDependencies:\n- agent-contracts: ^0.32.0\n- agent-contracts-runtime: ^0.31.0\n- zod: ^4.0.0\n\nAdd optional peerDependencies for SDK packages:\n- @anthropic-ai/claude-agent-sdk: >=0.2.0\n- @openai/agents: >=0.10.0\n- @google/genai: >=2.0.0\n- @cursor/sdk (no version constraint)\n\n### Step 3: Create DSL Definitions\n\nCreate directory structure:\n\n dsl/\n \u251C\u2500\u2500 {project}-dsl.yaml\n \u251C\u2500\u2500 agent-runtime.config.yaml\n \u251C\u2500\u2500 agents/\n \u2502 \u2514\u2500\u2500 {agent-name}.yaml\n \u251C\u2500\u2500 tasks.yaml\n \u2514\u2500\u2500 handoff-types.yaml\n\n**Main DSL entry** (`dsl/{project}-dsl.yaml`):\n\n version: 1\n system:\n id: {project}\n name: "{Project} Agent System"\n default_workflow_order:\n - {workflow-ids}\n agents: { $ref: "./agents/" }\n tasks: { $ref: "./tasks.yaml" }\n handoff_types: { $ref: "./handoff-types.yaml" }\n guardrails:\n output-schema-conformance:\n description: ...\n scope: { agents: [...], tasks: [...] }\n rationale: ...\n guardrail_policies:\n {domain}-safety-policy:\n rules:\n - guardrail: output-schema-conformance\n severity: critical\n action: block\n workflow:\n {workflow-id}:\n description: ...\n trigger: cli-command\n entry_conditions: [...]\n steps:\n - type: delegate\n task: {task-id}\n from_agent: {agent-id}\n\n**Agent definition** (`dsl/agents/{agent-name}.yaml`):\n\n {agent-name}:\n role_name: "{Role Name}"\n purpose: >-\n Domain-specific purpose describing what the agent knows\n and what it can do that static rules cannot.\n mode: read-only\n can_read_artifacts: []\n can_write_artifacts: []\n can_invoke_agents: []\n can_execute_tools: []\n can_return_handoffs: [{result-handoff-ids}]\n responsibilities: [...]\n constraints: [...]\n rules:\n - id: "R-{PREFIX}-001"\n description: ...\n severity: mandatory\n escalation_criteria:\n - condition: ...\n action: stop_and_report\n\n**Tasks** (`dsl/tasks.yaml`):\n\n {task-id}:\n description: ...\n target_agent: {agent-name}\n allowed_from_agents: [{agent-name}]\n workflow: {workflow-id}\n input_artifacts: []\n invocation_handoff: {request-handoff}\n result_handoff: {result-handoff}\n responsibilities: [...]\n completion_criteria: [...]\n\n**Handoff types** (`dsl/handoff-types.yaml`):\nUse AgentAuditResult shape as the base for result types:\n\n {result-handoff}:\n version: 1\n description: ...\n schema:\n type: object\n required: [summary, riskLevel, findings]\n properties:\n summary: { type: string }\n riskLevel:\n type: string\n enum: [low, medium, high, critical]\n findings:\n type: array\n items:\n type: object\n required: [severity, category, message]\n properties:\n id: { type: string }\n severity:\n type: string\n enum: [info, warning, error, critical]\n category: { type: string }\n target: { type: string }\n location: { type: string }\n message: { type: string }\n recommendation: { type: string }\n confidence: { type: number, minimum: 0, maximum: 1 }\n recommendedActions:\n type: array\n items:\n type: object\n required: [kind, title]\n properties:\n kind:\n type: string\n enum: [run_command, edit_file, review, confirm, block, ignore]\n title: { type: string }\n command: { type: string }\n target: { type: string }\n rationale: { type: string }\n metadata:\n type: object\n properties:\n tool: { type: string }\n command: { type: string }\n version: { type: string }\n generatedAt: { type: string }\n adapter: { type: string }\n model: { type: string }\n\nDomain-specific result types add properties alongside the base fields.\n\n**Runtime config** (`dsl/agent-runtime.config.yaml`):\n\n dsl: ./{project}-dsl.yaml\n generated_dir: ../src/generated/dsl\n\n### Step 4: Generate TypeScript Contracts\n\nAdd to package.json scripts:\n\n "dsl:generate": "agent-runtime generate --config dsl/agent-runtime.config.yaml"\n\nRun: npm run dsl:generate\n\nThis produces src/generated/dsl/ containing:\n- agents.ts (AgentContract interface + agentRegistry)\n- tasks.ts (TaskContract interface + taskRegistry)\n- workflows.ts (WorkflowContract + workflowRegistry)\n- handoffs.ts (Zod schemas + handoffSchemas + factory functions)\n- index.ts (barrel re-exports)\n\n### Step 5: Implement src/agents/ Module\n\n**src/agents/types.ts**:\n\n import type { {ResultType} } from "../generated/dsl/handoffs.js";\n\n export type TaskId = "{task-1}" | "{task-2}" | ...;\n\n export interface AgentConfig {\n adapter?: string;\n model?: string;\n temperature?: number;\n }\n\n export interface AgentOptions {\n dryRun?: boolean;\n failOn?: "warning" | "error" | "critical";\n }\n\n export interface AgentRunResult {\n taskId: TaskId;\n data: {ResultType} | null;\n raw: string;\n prompt: string;\n dryRun: boolean;\n status: "success" | "error" | "escalation" | "validation_error";\n errorMessage?: string;\n followUpsUsed: number;\n retriesUsed: number;\n }\n\n**src/agents/orchestrator.ts**:\n\n export const EXIT_RUNTIME_MISSING = 11;\n export const EXIT_ADAPTER_ERROR = 12;\n\n async function createAdapter(pkg: string, name: string, config: AgentConfig) {\n switch (name) {\n case "mock": {\n const m = await import(`${pkg}/adapters/mock`);\n return new m.MockAdapter();\n }\n case "cursor": {\n const m = await import(`${pkg}/adapters/cursor-sdk`);\n return m.CursorSdkAdapter.create({ apiKey: process.env.CURSOR_API_KEY, model: config.model });\n }\n case "claude": {\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\n }\n case "openai": {\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\n }\n case "gemini": {\n const m = await import(`${pkg}/adapters/gemini-sdk`);\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\n }\n }\n }\n\n export async function 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, cursor, claude, openai, gemini] }\n - name: model\n schema: { type: string }\n - name: dry-run\n schema: { type: boolean, default: false }\n - name: fail-on\n schema: { type: string, enum: [warning, error, critical], default: error }\n - name: output\n aliases: [o]\n schema: { type: string }\n file: { mode: write }\n - name: report-format\n schema: { type: string, enum: [json, text, yaml], default: json }\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: [network]\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: dry-run\n expectedDurationMs: 120000\n retryableExitCodes: [1, 12]\n exits:\n \'0\': { description: "No blocking findings.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'1\': { description: "General error.", stderr: { format: text } }\n \'3\': { description: "Input validation failed.", stderr: { format: json } }\n \'10\': { description: "Blocking findings detected.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'11\': { description: "Runtime not installed.", stderr: { format: json } }\n \'12\': { description: "Adapter error.", stderr: { format: json } }\n\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\nto components/schemas if not already present.\n\n### Step 8: Update README\n\nAdd "Agent-Native Toolchain" section after mechanical features:\n- Intro: tool encapsulates domain-specific semantic reasoning\n- Deterministic checks first, then semantic audit\n- Structured findings (AgentAuditResult/AgentFinding)\n- LLM Adapter Configuration table\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\n',
|
|
689
696
|
target_agent: "llm-feature-implementer",
|
|
690
697
|
allowed_from_agents: [
|
|
691
698
|
"llm-feature-implementer"
|
|
@@ -707,7 +714,7 @@ var implementLlmFeature = {
|
|
|
707
714
|
"dsl/ directory contains valid DSL definitions that pass agent-runtime generate",
|
|
708
715
|
"agent-runtime.config.yaml points to the DSL with correct generated_dir",
|
|
709
716
|
"src/generated/dsl/ contains generated contracts (agentRegistry, taskRegistry, handoffSchemas, workflowRegistry)",
|
|
710
|
-
"src/agents/orchestrator.ts uses
|
|
717
|
+
"src/agents/orchestrator.ts uses runWorkflow from agent-contracts-runtime (never runTask directly, no direct adapter.send calls)",
|
|
711
718
|
"src/agents/orchestrator.ts dynamic-imports the runtime and adapters with correct exit codes (11, 12)",
|
|
712
719
|
"src/agents/context-builder.ts contains only domain data (file contents, config, scan results) \u2014 no hardcoded agent instructions, evaluation criteria, or output format specs",
|
|
713
720
|
"src/agents/context-builder.ts caps input at 16KB",
|
|
@@ -749,7 +756,7 @@ var auditDsl = {
|
|
|
749
756
|
};
|
|
750
757
|
var auditRuntime = {
|
|
751
758
|
id: "audit-runtime",
|
|
752
|
-
description: "Audit the runtime integration layer of an LLM command integration.\n\nScan src/agents/orchestrator.ts (or equivalent runtime module):\n\nCRITICAL violations (category: runtime-orchestrator):\n- adapter.send() or adapter.sendExecution() called directly\n- adapter.followUp() called directly\n- Custom adapter class defined (not imported from runtime)\n-
|
|
759
|
+
description: "Audit the runtime integration layer of an LLM command integration.\n\nScan src/agents/orchestrator.ts (or equivalent runtime module):\n\nCRITICAL violations (category: runtime-orchestrator):\n- adapter.send() or adapter.sendExecution() called directly\n- adapter.followUp() called directly\n- Custom adapter class defined (not imported from runtime)\n- runWorkflow not imported from agent-contracts-runtime\n- runTask used instead of runWorkflow \u2014 consumer projects must\n use runWorkflow() which orchestrates through the DSL workflow\n DAG, activates workflow-level plugin hooks (beforeWorkflow/\n afterWorkflow), handles gate steps and step dependencies.\n runTask() is a low-level internal API; calling it directly\n bypasses workflow orchestration entirely\n\nERROR violations (category: runtime-registry):\n- Generated registries not imported from src/generated/dsl/\n- Registries not passed to runWorkflow options\n- Hard-coded agent/task definitions instead of registry lookup\n\nERROR violations (category: runtime-adapter):\n- Adapter packages imported statically (not dynamic import)\n- Missing exit code 11 when runtime import fails\n- Missing exit code 12 when adapter creation fails\n- CursorSdkAdapter created with constructor (must use static .create())\n\nERROR violations (category: runtime-handler):\n- Project has cli-contracts generated code (src/generated/program.ts\n or src/generated/cli/program.ts exporting CommandHandlers and\n createProgram) but CLI entry point manually creates Commander\n commands instead of using createProgram(handlers, version)\n- LLM command handlers are not wired through the generated\n CommandHandlers interface \u2014 handler signatures drift from the\n cli-contract.yaml definition without type errors\n- CLI entry point calls runTask directly instead of going through\n the command handler \u2192 context-builder \u2192 orchestrator chain\n\nWARNING violations (category: runtime-plugin):\n- Plugin hooks explicitly bypassed or ignored\n\nCategory vocabulary: runtime-orchestrator, runtime-registry,\nruntime-adapter, runtime-handler, runtime-plugin.\n\nOutput a partial audit-result with findings only from the runtime layer.\n",
|
|
753
760
|
target_agent: "implementation-auditor",
|
|
754
761
|
allowed_from_agents: [
|
|
755
762
|
"implementation-auditor"
|
|
@@ -760,12 +767,14 @@ var auditRuntime = {
|
|
|
760
767
|
input_artifacts: [],
|
|
761
768
|
responsibilities: [
|
|
762
769
|
"Scan orchestrator code for direct adapter usage",
|
|
770
|
+
"Verify runWorkflow is used (not runTask) for LLM command execution",
|
|
763
771
|
"Verify registry imports and passing",
|
|
764
772
|
"Check adapter creation patterns and exit codes",
|
|
765
773
|
"Verify cli-contracts handler wiring (CommandHandlers + createProgram used in CLI entry point)"
|
|
766
774
|
],
|
|
767
775
|
completion_criteria: [
|
|
768
776
|
"All orchestrator files scanned for adapter.send / adapter.followUp",
|
|
777
|
+
"No runTask usage found (runWorkflow must be used instead)",
|
|
769
778
|
"Registry usage verified",
|
|
770
779
|
"Exit code 11/12 patterns checked",
|
|
771
780
|
"cli-contracts handler integration verified (CommandHandlers interface used, createProgram called)"
|
|
@@ -817,7 +826,7 @@ The context-builder's role is to assemble domain-specific DATA (file
|
|
|
817
826
|
contents, configuration, scan results, schema context) into the user
|
|
818
827
|
prompt. Agent INSTRUCTIONS (how to evaluate, what rules to apply,
|
|
819
828
|
what patterns to look for, output format) belong in the DSL agent
|
|
820
|
-
definition
|
|
829
|
+
definition and are injected by buildTaskPrompt / runWorkflow.
|
|
821
830
|
|
|
822
831
|
Detect any of the following in context-builder source code:
|
|
823
832
|
- Sections titled "## Instructions", "## Required Patterns",
|
|
@@ -859,6 +868,12 @@ ERROR: adapter cwd propagation (category: architecture-adapter-cwd):
|
|
|
859
868
|
- Agentic adapters (claude, cursor) instantiated without cwd \u2014
|
|
860
869
|
their file tools will operate in an undefined directory
|
|
861
870
|
|
|
871
|
+
CRITICAL: runTask usage (category: architecture-handler):
|
|
872
|
+
- runTask() imported or called anywhere in the consumer project \u2014
|
|
873
|
+
consumer projects must use runWorkflow() exclusively; runTask()
|
|
874
|
+
is a low-level internal API that bypasses workflow DAG
|
|
875
|
+
orchestration, workflow-level plugin hooks, and gate steps
|
|
876
|
+
|
|
862
877
|
ERROR: cli-contracts handler wiring (category: architecture-handler):
|
|
863
878
|
- Project has cli-contracts generated code (src/generated/program.ts
|
|
864
879
|
or src/generated/cli/program.ts with CommandHandlers) but CLI
|
|
@@ -964,7 +979,7 @@ var AuditResultSchema = z.object({
|
|
|
964
979
|
location: z.string().optional(),
|
|
965
980
|
message: z.string(),
|
|
966
981
|
recommendation: z.string().optional(),
|
|
967
|
-
confidence: z.number().optional()
|
|
982
|
+
confidence: z.number().min(0).max(1).optional()
|
|
968
983
|
})),
|
|
969
984
|
recommendedActions: z.array(z.object({
|
|
970
985
|
kind: z.enum(["run_command", "edit_file", "review", "confirm", "block", "ignore"]),
|
|
@@ -1085,6 +1100,852 @@ var workflowRegistry = {
|
|
|
1085
1100
|
"audit-implementation": auditImplementation
|
|
1086
1101
|
};
|
|
1087
1102
|
|
|
1103
|
+
// src/builtin-agents/generated/dsl-data.ts
|
|
1104
|
+
var resolvedDsl = {
|
|
1105
|
+
"version": 1,
|
|
1106
|
+
"system": {
|
|
1107
|
+
"id": "agent-runtime-builtin",
|
|
1108
|
+
"name": "agent-runtime Built-in Agents",
|
|
1109
|
+
"default_workflow_order": [
|
|
1110
|
+
"implement-llm-feature",
|
|
1111
|
+
"audit-implementation"
|
|
1112
|
+
]
|
|
1113
|
+
},
|
|
1114
|
+
"agents": {
|
|
1115
|
+
"implementation-auditor": {
|
|
1116
|
+
"role_name": "Implementation Auditor",
|
|
1117
|
+
"purpose": "Audits an existing LLM command integration to verify it correctly\nfollows the agent-contracts + agent-contracts-runtime + cli-contracts\nstack conventions. Detects architectural violations, missing patterns,\nincorrect API usage, and deviations from the canonical\nintegrate-llm-commands pattern.\n\nThis agent is read-only \u2014 it analyzes code but does not modify it.\nIt produces structured findings (AgentAuditResult) that identify\nexactly what is wrong and how to fix it.\n\n## What This Agent Checks\n\n### Layer 1: agent-contracts DSL\n- DSL entry has version:1 and system block with id/name\n- Agents defined with all required fields (role_name, purpose, mode,\n can_read_artifacts, can_write_artifacts, responsibilities, constraints)\n- Tasks have target_agent, workflow, result_handoff, completion_criteria\n- Handoff type schemas conform to AgentAuditResult base shape\n- Workflows define steps with correct task/agent cross-references\n- Guardrails and guardrail_policies are defined\n- agent-runtime.config.yaml exists with dsl and generated_dir\n\n### Layer 2: agent-contracts-runtime Integration\n- orchestrator.ts uses runWorkflow(), NOT runTask() or adapter.send()\n- runTask() is a low-level internal API \u2014 consumer projects must\n use runWorkflow() which handles workflow DAG, plugin hooks, gates\n- Adapters imported from agent-contracts-runtime/adapters/*, not custom\n- Dynamic import pattern for graceful degradation (exit 11/12)\n- Generated registries imported from src/generated/dsl/index.js\n- Registries (including workflowRegistry) passed to runWorkflow\n- Plugin hooks not bypassed\n- No hand-rolled prompt building (use buildTaskPrompt or let runWorkflow do it)\n\n### Layer 3: cli-contracts Compliance\n- cli-contract.yaml has LLM commands with all standard options:\n --adapter, --model, --dry-run, --fail-on, --output, --report-format\n- x-agent metadata present (riskLevel, safeDryRunOption, expectedDurationMs)\n- Exit codes follow convention (0, 1, 3, 10, 11, 12)\n- components/schemas includes AgentAuditResult and related types\n- --report-format used (not --format) for LLM commands\n\n### Architecture & Patterns\n- src/agents/ module structure (orchestrator, context-builder, formatter, types)\n- Context builder caps input at 16KB\n- Formatter implements computeExitCode with correct threshold logic\n- --dry-run returns prompt without LLM call\n- No direct LLM API calls anywhere in the codebase\n\n### Semantic Design Coherence\n- Context-builder must contain only domain DATA (file contents,\n config, scan results) \u2014 never agent INSTRUCTIONS (evaluation\n criteria, rules, anti-patterns, output format specifications).\n These belong in the DSL agent definition and are injected by\n buildTaskPrompt / runWorkflow. Hardcoding instructions in\n context-builder defeats the purpose of using DSL.\n- Agent mode must match purpose: read-only agents must not have\n write-oriented purposes, read-write agents must propagate cwd\n to their adapter so file tools operate in the project directory.\n- CLI must use cli-contracts' generated CommandHandlers interface\n and createProgram() \u2014 not manually wired Commander commands.\n",
|
|
1118
|
+
"mode": "read-only",
|
|
1119
|
+
"can_read_artifacts": [],
|
|
1120
|
+
"can_write_artifacts": [],
|
|
1121
|
+
"can_invoke_agents": [],
|
|
1122
|
+
"can_execute_tools": [],
|
|
1123
|
+
"can_return_handoffs": [
|
|
1124
|
+
"audit-result"
|
|
1125
|
+
],
|
|
1126
|
+
"responsibilities": [
|
|
1127
|
+
"Verify the DSL directory structure exists: dsl/{project}-dsl.yaml, dsl/agents/*.yaml, dsl/tasks.yaml, dsl/handoff-types.yaml, dsl/agent-runtime.config.yaml.",
|
|
1128
|
+
"Check that the main DSL entry has version:1, a system block with id and name, and uses $ref for agents/tasks/handoff_types.",
|
|
1129
|
+
"Validate agent definitions have all required fields: role_name, purpose, mode, can_read_artifacts:[], can_write_artifacts:[], responsibilities, constraints. Check that rules use R-PREFIX-NNN format and severity is mandatory|recommended|optional.",
|
|
1130
|
+
"Validate task definitions: target_agent matches a defined agent, workflow matches a defined workflow, result_handoff matches a defined handoff type, completion_criteria are specific and testable.",
|
|
1131
|
+
"Verify handoff type schemas conform to AgentAuditResult shape when applicable (summary, riskLevel, findings[], recommendedActions[], metadata). Check $ref usage and SSoT comments for inlined schemas.",
|
|
1132
|
+
"Check that guardrails and guardrail_policies are defined, and that output-schema-conformance is included.",
|
|
1133
|
+
"Scan src/agents/orchestrator.ts for: (1) imports from agent-contracts-runtime (not custom SDK wrappers), (2) usage of runWorkflow() \u2014 NOT runTask() which is a low-level internal API that bypasses workflow orchestration, plugin hooks, and gate steps, (3) dynamic import pattern with exit code 11 for missing runtime and exit code 12 for adapter errors, (4) generated registries (including workflowRegistry) imported and passed to runWorkflow.",
|
|
1134
|
+
"Verify no file in the project calls adapter.send(), adapter.followUp(), adapter.sendExecution(), or runTask() directly \u2014 all LLM invocations must go through runWorkflow().",
|
|
1135
|
+
"Check that src/generated/dsl/ exists and contains the expected files (agents.ts, tasks.ts, workflows.ts, handoffs.ts, index.ts). Verify the .manifest.json exists and is not stale.",
|
|
1136
|
+
"Verify adapter creation uses the correct constructors: CursorSdkAdapter.create() (async static), ClaudeAgentSdkAdapter constructor, OpenAIAgentsSdkAdapter constructor, etc.",
|
|
1137
|
+
"Check cli-contract.yaml for each LLM command: all six standard options present (--adapter, --model, --dry-run, --fail-on, --output, --report-format). Verify --report-format is used (not --format).",
|
|
1138
|
+
'Verify x-agent metadata on each LLM command: riskLevel, safeDryRunOption (must be "dry-run"), expectedDurationMs. Flag high-risk commands without requiresConfirmation.',
|
|
1139
|
+
"Check exit code definitions: 0 (success), 1 (error), 3 (validation), 10 (findings), 11 (runtime missing), 12 (adapter error).",
|
|
1140
|
+
"Verify components/schemas includes AgentAuditResult, AgentFinding, AgentRecommendedAction, and AgentEvidence definitions.",
|
|
1141
|
+
"Verify src/agents/ directory structure: types.ts (TaskId, AgentConfig, AgentOptions, AgentRunResult), orchestrator.ts (createAdapter, runAgentTask with dynamic imports), context-builder.ts (build*Context functions with 16KB cap), formatter.ts (computeExitCode, formatResultText, formatResultJson).",
|
|
1142
|
+
"Check that --dry-run mode returns the constructed prompt without making any LLM API call.",
|
|
1143
|
+
"Scan for direct LLM API imports (@anthropic-ai/sdk, openai, @google/genai, @cursor/sdk) used outside of adapter files \u2014 application code must not import these directly.",
|
|
1144
|
+
'Audit context-builder for SSoT violations: scan for hardcoded agent instructions (sections titled "## Instructions", "## Required Patterns", "## Output Format", evaluation criteria, checklists, anti-pattern definitions, API references, or output schema descriptions). These belong in the DSL agent definition and are injected by buildTaskPrompt. Context-builder should contain only domain-specific data (file contents, configuration, scan results, project metadata).',
|
|
1145
|
+
"Check agent mode-purpose coherence: for each agent in the DSL, verify that mode: read-only agents do not have purposes or responsibilities describing file writing/editing/creation, and that mode: read-write agents propagate cwd through AgentConfig to the adapter so file tools operate in the correct directory.",
|
|
1146
|
+
"Verify cwd propagation: command handlers must set cwd in AgentConfig (e.g. process.cwd() or resolve(projectDir)), createAdapter must pass cwd to adapter constructors/factories, and AgentConfig type must include a cwd field.",
|
|
1147
|
+
"Verify cli-contracts handler wiring: if the project uses cli-contracts (has src/generated/program.ts or src/generated/cli/program.ts exporting CommandHandlers and createProgram), the CLI entry point must use createProgram(handlers, version) with a handlers object implementing the CommandHandlers interface \u2014 not manually created Commander commands."
|
|
1148
|
+
],
|
|
1149
|
+
"constraints": [
|
|
1150
|
+
"This agent is read-only. It must not create, modify, or delete any files. Output is a structured audit report only.",
|
|
1151
|
+
"Findings must include specific file paths, line references where possible, and concrete remediation steps.",
|
|
1152
|
+
"Severity classification: critical = breaks the integration pattern (direct API calls, missing runtime usage), error = missing required element (no x-agent, missing standard option), warning = deviation from best practice (context not capped, missing guardrail), info = improvement suggestion.",
|
|
1153
|
+
"Category vocabulary: dsl-structure, dsl-agent, dsl-task, dsl-handoff, dsl-workflow, dsl-guardrail, runtime-adapter, runtime-orchestrator, runtime-registry, runtime-handler, runtime-plugin, cli-contract-options, cli-contract-xagent, cli-contract-exits, cli-contract-schema, architecture-modules, architecture-dry-run, architecture-context-builder, architecture-agent-coherence, architecture-adapter-cwd, architecture-handler, architecture-formatter.",
|
|
1154
|
+
"Every finding with severity warning or above must include a recommendation field with a concrete fix.",
|
|
1155
|
+
"The confidence field should reflect how certain the finding is: 1.0 for pattern matches (e.g., adapter.send() found in code), 0.8+ for structural checks (e.g., missing file), 0.5-0.8 for heuristic assessments (e.g., context might exceed 16KB)."
|
|
1156
|
+
],
|
|
1157
|
+
"rules": [
|
|
1158
|
+
{
|
|
1159
|
+
"id": "R-AUDIT-001",
|
|
1160
|
+
"description": "Every finding must specify target (file path) and category (from the defined category vocabulary). Findings without a target are not actionable.",
|
|
1161
|
+
"severity": "mandatory"
|
|
1162
|
+
},
|
|
1163
|
+
{
|
|
1164
|
+
"id": "R-AUDIT-002",
|
|
1165
|
+
"description": "The audit must check all four layers (DSL, runtime, CLI contract, architecture). Skipping a layer or returning partial results is not acceptable.",
|
|
1166
|
+
"severity": "mandatory"
|
|
1167
|
+
},
|
|
1168
|
+
{
|
|
1169
|
+
"id": "R-AUDIT-003",
|
|
1170
|
+
"description": "Critical findings must be surfaced for: (1) direct adapter.send() calls bypassing runWorkflow, (2) runTask() used instead of runWorkflow() \u2014 runTask is a low-level internal API that bypasses workflow orchestration, (3) custom adapter classes not from agent-contracts-runtime, (4) missing generated registries in runWorkflow calls.",
|
|
1171
|
+
"severity": "mandatory"
|
|
1172
|
+
},
|
|
1173
|
+
{
|
|
1174
|
+
"id": "R-AUDIT-004",
|
|
1175
|
+
"description": "The riskLevel in the audit result must be derived from the most severe finding: any critical \u2192 critical, any error \u2192 high, any warning \u2192 medium, info only \u2192 low.",
|
|
1176
|
+
"severity": "mandatory"
|
|
1177
|
+
},
|
|
1178
|
+
{
|
|
1179
|
+
"id": "R-AUDIT-005",
|
|
1180
|
+
"description": "Context-builder must be audited for SSoT violations. Any hardcoded agent instructions (evaluation criteria, rules, anti-patterns, output format specs) in context-builder is a critical finding \u2014 these belong in the DSL agent definition and are injected by buildTaskPrompt / runWorkflow. Context-builder may only contain domain-specific data (file contents, configuration, scan results, project metadata).",
|
|
1181
|
+
"severity": "mandatory"
|
|
1182
|
+
},
|
|
1183
|
+
{
|
|
1184
|
+
"id": "R-AUDIT-007",
|
|
1185
|
+
"description": "runTask() usage in consumer projects is a CRITICAL finding. Consumer projects integrating with cli-contracts must use runWorkflow() exclusively. runTask() is a low-level internal API that bypasses workflow DAG orchestration, workflow-level plugin hooks (beforeWorkflow/afterWorkflow), gate steps, and step dependencies. Any occurrence of runTask import or call in orchestrator, command handler, or CLI entry point code must be reported as severity: critical.",
|
|
1186
|
+
"severity": "mandatory"
|
|
1187
|
+
},
|
|
1188
|
+
{
|
|
1189
|
+
"id": "R-AUDIT-006",
|
|
1190
|
+
"description": "Agent mode-purpose coherence must be verified. A read-only agent whose purpose describes file writing is a critical finding because the adapter's tool set (Read/Glob/Grep only) makes the stated purpose impossible to fulfil.",
|
|
1191
|
+
"severity": "mandatory"
|
|
1192
|
+
}
|
|
1193
|
+
],
|
|
1194
|
+
"escalation_criteria": [
|
|
1195
|
+
{
|
|
1196
|
+
"condition": "Target project has no LLM command integration to audit",
|
|
1197
|
+
"action": "stop_and_report"
|
|
1198
|
+
},
|
|
1199
|
+
{
|
|
1200
|
+
"condition": "Target project uses a completely different integration pattern (not agent-contracts stack)",
|
|
1201
|
+
"action": "stop_and_report"
|
|
1202
|
+
}
|
|
1203
|
+
]
|
|
1204
|
+
},
|
|
1205
|
+
"llm-feature-implementer": {
|
|
1206
|
+
"role_name": "LLM Feature Implementer",
|
|
1207
|
+
"purpose": 'Expert implementation agent for the agent-contracts toolchain.\nAdds LLM-powered commands (audit, propose, explain, etc.) to CLI tools\nusing the three-layer stack:\n\n1. **agent-contracts** \u2014 DSL package. Defines agents, tasks, workflows,\n handoff types, guardrails, and guardrail policies in YAML. The\n `resolve()` function handles `$ref`, `extends`, and merge operators.\n Installed as a devDependency. CLI: `agent-contracts audit`.\n\n2. **agent-contracts-runtime** \u2014 Runtime bridge. Generates typed\n TypeScript contracts from DSL via Handlebars templates, then\n executes workflows through pluggable SDK adapters. Provides\n `runTask()`, `runWorkflow()`, `createRuntime()`, plugin system,\n and guardrail hooks. CLI: `agent-runtime generate|run|list|doctor`.\n\n3. **cli-contracts** \u2014 CLI contract package. Defines command-line\n interfaces in YAML (`cli-contract.yaml`): command sets, arguments,\n options, exit codes, stdout/stderr schemas, `x-agent` metadata,\n and `effects`. Generates typed Commander programs, Zod validators,\n and markdown docs. CLI: `cli-contracts init|generate|validate`.\n\nThe canonical integration pattern ("integrate-llm-commands") produces:\n- DSL definitions under `dsl/` (agents, tasks, workflows, handoff-types)\n- Pre-generated TypeScript contracts under `src/generated/dsl/`\n- Runtime integration module under `src/agents/` (orchestrator,\n context-builder, formatter, types)\n- CLI command handlers under `src/commands/`\n- Updated `cli-contract.yaml` with new commands and `x-agent` metadata\n',
|
|
1208
|
+
"mode": "read-write",
|
|
1209
|
+
"can_read_artifacts": [],
|
|
1210
|
+
"can_write_artifacts": [],
|
|
1211
|
+
"can_invoke_agents": [],
|
|
1212
|
+
"can_execute_tools": [],
|
|
1213
|
+
"can_return_handoffs": [
|
|
1214
|
+
"implementation-result"
|
|
1215
|
+
],
|
|
1216
|
+
"responsibilities": [
|
|
1217
|
+
"Read and analyze the target project's cli-contract.yaml, package.json, tsconfig.json, and existing source code to understand the CLI structure, existing commands, component schemas, and TypeScript configuration.",
|
|
1218
|
+
"Identify which LLM commands to add based on the user's description. Canonical command types: audit (semantic review), propose (structured proposal generation), explain (human-readable explanation of machine output).",
|
|
1219
|
+
"Create the DSL directory structure: dsl/{project}-dsl.yaml (main entry with version:1, system block, $ref to sub-files), dsl/agents/{name}.yaml, dsl/tasks.yaml, dsl/handoff-types.yaml, dsl/agent-runtime.config.yaml.",
|
|
1220
|
+
"Define agents with: role_name, purpose (domain expertise), mode (read-only for analysis agents), can_read_artifacts:[], can_write_artifacts:[], can_return_handoffs, responsibilities, constraints, rules (R-PREFIX-NNN format), escalation_criteria.",
|
|
1221
|
+
"Define tasks with: description, target_agent, allowed_from_agents, workflow (must match a workflow ID), invocation_handoff, result_handoff, responsibilities, completion_criteria.",
|
|
1222
|
+
"Define handoff types with: version:1, description, schema (JSON Schema). Result types should conform to AgentAuditResult shape (summary, riskLevel, findings[], recommendedActions[], metadata). Use $ref to cli-contract.yaml components/schemas as SSoT when possible; inline with SSoT comment as fallback.",
|
|
1223
|
+
"Define workflows with trigger, entry_conditions, and steps (delegate or gate). Each delegate step references a task and from_agent. Gate steps pause for user approval.",
|
|
1224
|
+
"Define guardrails (output-schema-conformance, domain-specific safety) and guardrail_policies grouping them with severity and action.",
|
|
1225
|
+
"Create agent-runtime.config.yaml: dsl points to main DSL file, generated_dir points to src/generated/dsl.",
|
|
1226
|
+
"Implement src/agents/types.ts: TaskId union type, AgentConfig interface (adapter, model, temperature), AgentOptions interface (dryRun, failOn), AgentRunResult interface (taskId, data, raw, prompt, dryRun, status, errorMessage, followUpsUsed, retriesUsed).",
|
|
1227
|
+
"Implement src/agents/orchestrator.ts: createAdapter() with dynamic imports from agent-contracts-runtime/adapters/*, runAgentWorkflow() that imports runWorkflow from agent-contracts-runtime, loads generated registries (including workflowRegistry) from src/generated/dsl/index.js, and calls runWorkflow with registries. NEVER use runTask \u2014 it is a low-level internal API that bypasses workflow orchestration.",
|
|
1228
|
+
"Implement src/agents/context-builder.ts: build{Command}Context() functions that transform CLI inputs into structured markdown prompts. Cap context at 16KB. Structure: # Request, ## Configuration, ## Target, ## Instructions.",
|
|
1229
|
+
"Implement src/agents/formatter.ts: computeExitCode() mapping findings to exit codes via --fail-on threshold, formatResultText() with severity icons, formatResultJson() for structured output.",
|
|
1230
|
+
"Create src/commands/{command}.ts handlers: load config, call context builder, call runAgentWorkflow, format output, compute exit code.",
|
|
1231
|
+
"Update cli-contract.yaml: add command definitions with standard LLM options (--adapter, --model, --dry-run, --fail-on, --output, --report-format), exit codes (0, 1, 3, 10, 11, 12), x-agent metadata, and register AgentAuditResult/AgentFinding/AgentRecommendedAction in components/schemas.",
|
|
1232
|
+
'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.'
|
|
1233
|
+
],
|
|
1234
|
+
"constraints": [
|
|
1235
|
+
"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, CursorSdkAdapter from agent-contracts-runtime/adapters/cursor-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk, GeminiSdkAdapter from agent-contracts-runtime/adapters/gemini-sdk, MockAdapter from agent-contracts-runtime/adapters/mock.",
|
|
1236
|
+
"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.",
|
|
1237
|
+
'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); }',
|
|
1238
|
+
"LLM commands use --report-format (json|text|yaml) for output format. --format is reserved for deterministic commands. Never mix them.",
|
|
1239
|
+
"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.).",
|
|
1240
|
+
"Standard LLM command options (all must be present): --adapter <name> (mock|cursor|claude|openai|gemini, default varies), --model <name> (optional override), --dry-run (output prompt without LLM call), --fail-on <level> (warning|error|critical, default error), --output/-o <file> (write to file instead of stdout), --report-format <fmt> (json|text|yaml, default json).",
|
|
1241
|
+
"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).",
|
|
1242
|
+
"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).",
|
|
1243
|
+
"AgentRecommendedAction shape: kind (run_command|edit_file|review|confirm| block|ignore), title (required), command?, target?, rationale?.",
|
|
1244
|
+
"Main DSL entry must have version:1 and a system block with id and name. Without these, the generator produces numbered files instead of named ones.",
|
|
1245
|
+
"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.",
|
|
1246
|
+
"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}).",
|
|
1247
|
+
"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.",
|
|
1248
|
+
"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), CursorSdkAdapter.create({apiKey, model?, cwd?, guardrailHooks?}) \u2014 async static, ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?}), GeminiSdkAdapter({apiKey?, model?, systemInstruction?, temperature?, maxOutputTokens?, guardrailHooks?}).",
|
|
1249
|
+
'Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from "../generated/dsl/index.js". Pass these as registries to runWorkflow: { workflowRegistry, taskRegistry, agentRegistry, handoffSchemas }.',
|
|
1250
|
+
"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).",
|
|
1251
|
+
"x-agent fields for LLM commands in cli-contract.yaml: riskLevel (low for read-only analysis), requiresConfirmation (false for read-only), idempotent (true for analysis), sideEffects ([network]), sideEffectNote (describe network call and optional file write), safeDryRunOption (dry-run), expectedDurationMs (120000 typical), retryableExitCodes ([1, 12])."
|
|
1252
|
+
],
|
|
1253
|
+
"rules": [
|
|
1254
|
+
{
|
|
1255
|
+
"id": "R-IMPL-001",
|
|
1256
|
+
"description": "Import SDK adapters exclusively from agent-contracts-runtime/adapters/*. Never create adapter classes, wrapper functions, or API client code.",
|
|
1257
|
+
"severity": "mandatory"
|
|
1258
|
+
},
|
|
1259
|
+
{
|
|
1260
|
+
"id": "R-IMPL-002",
|
|
1261
|
+
"description": "All LLM invocations must use runWorkflow() from agent-contracts-runtime. NEVER use runTask() \u2014 it is a low-level internal API that bypasses workflow orchestration. Never call adapter.send(), adapter.followUp(), or adapter.sendExecution() directly. The runtime handles prompt building, schema validation, retry, followUp, workflow DAG, and plugin hooks.",
|
|
1262
|
+
"severity": "mandatory"
|
|
1263
|
+
},
|
|
1264
|
+
{
|
|
1265
|
+
"id": "R-IMPL-003",
|
|
1266
|
+
"description": "Every LLM command in cli-contract.yaml must have x-agent metadata with at minimum: riskLevel, safeDryRunOption, expectedDurationMs.",
|
|
1267
|
+
"severity": "mandatory"
|
|
1268
|
+
},
|
|
1269
|
+
{
|
|
1270
|
+
"id": "R-IMPL-004",
|
|
1271
|
+
"description": "Handoff type schemas must use $ref to cli-contract.yaml components/schemas as SSoT. If $ref resolution fails at generate time, inline the schema and add a YAML comment noting the SSoT path.",
|
|
1272
|
+
"severity": "mandatory"
|
|
1273
|
+
},
|
|
1274
|
+
{
|
|
1275
|
+
"id": "R-IMPL-005",
|
|
1276
|
+
"description": "Context builder must cap prompt input at 16KB. Filter large contexts (schema dumps, lint output, etc.) to relevant portions before inclusion.",
|
|
1277
|
+
"severity": "recommended"
|
|
1278
|
+
},
|
|
1279
|
+
{
|
|
1280
|
+
"id": "R-IMPL-006",
|
|
1281
|
+
"description": 'The orchestrator must dynamic-import agent-contracts-runtime as a single string variable (const PKG = "agent-contracts-runtime") to enable graceful degradation. Exit with code 11 when the import fails, code 12 when the adapter fails to initialize.',
|
|
1282
|
+
"severity": "mandatory"
|
|
1283
|
+
},
|
|
1284
|
+
{
|
|
1285
|
+
"id": "R-IMPL-007",
|
|
1286
|
+
"description": "Generated DSL contracts must be imported from src/generated/dsl/index.js and passed as registries to runWorkflow. Never hard-code agent definitions, task definitions, or handoff schemas in application code.",
|
|
1287
|
+
"severity": "mandatory"
|
|
1288
|
+
}
|
|
1289
|
+
],
|
|
1290
|
+
"escalation_criteria": [
|
|
1291
|
+
{
|
|
1292
|
+
"condition": "Target project has no cli-contract.yaml and user did not request creating one",
|
|
1293
|
+
"action": "stop_and_report"
|
|
1294
|
+
},
|
|
1295
|
+
{
|
|
1296
|
+
"condition": "Target project is not a TypeScript / Node.js stack",
|
|
1297
|
+
"action": "stop_and_report"
|
|
1298
|
+
},
|
|
1299
|
+
{
|
|
1300
|
+
"condition": "Target project already has src/agents/ with a different integration pattern",
|
|
1301
|
+
"action": "stop_and_report"
|
|
1302
|
+
}
|
|
1303
|
+
]
|
|
1304
|
+
}
|
|
1305
|
+
},
|
|
1306
|
+
"tasks": {
|
|
1307
|
+
"implement-llm-feature": {
|
|
1308
|
+
"description": 'Implement LLM-powered commands in a target CLI tool using the\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\n\n## Implementation Procedure\n\n### Step 1: Project Analysis\n\nRead these files from the target project:\n- cli-contract.yaml \u2014 existing commands, components/schemas, x-agent usage\n- package.json \u2014 dependencies, scripts, bin entries, type:"module" check\n- tsconfig.json \u2014 module resolution, paths, outDir\n- src/ directory structure \u2014 understand existing command handler pattern\n\nDetermine:\n- Which LLM commands to add (audit / propose / explain)\n- What domain-specific context each command needs\n- What structured output schema each command returns\n- Whether the project already has agent-contracts integration\n\n### Step 2: Install Dependencies\n\nAdd to package.json devDependencies:\n- agent-contracts: ^0.32.0\n- agent-contracts-runtime: ^0.31.0\n- zod: ^4.0.0\n\nAdd optional peerDependencies for SDK packages:\n- @anthropic-ai/claude-agent-sdk: >=0.2.0\n- @openai/agents: >=0.10.0\n- @google/genai: >=2.0.0\n- @cursor/sdk (no version constraint)\n\n### Step 3: Create DSL Definitions\n\nCreate directory structure:\n\n dsl/\n \u251C\u2500\u2500 {project}-dsl.yaml\n \u251C\u2500\u2500 agent-runtime.config.yaml\n \u251C\u2500\u2500 agents/\n \u2502 \u2514\u2500\u2500 {agent-name}.yaml\n \u251C\u2500\u2500 tasks.yaml\n \u2514\u2500\u2500 handoff-types.yaml\n\n**Main DSL entry** (`dsl/{project}-dsl.yaml`):\n\n version: 1\n system:\n id: {project}\n name: "{Project} Agent System"\n default_workflow_order:\n - {workflow-ids}\n agents: { $ref: "./agents/" }\n tasks: { $ref: "./tasks.yaml" }\n handoff_types: { $ref: "./handoff-types.yaml" }\n guardrails:\n output-schema-conformance:\n description: ...\n scope: { agents: [...], tasks: [...] }\n rationale: ...\n guardrail_policies:\n {domain}-safety-policy:\n rules:\n - guardrail: output-schema-conformance\n severity: critical\n action: block\n workflow:\n {workflow-id}:\n description: ...\n trigger: cli-command\n entry_conditions: [...]\n steps:\n - type: delegate\n task: {task-id}\n from_agent: {agent-id}\n\n**Agent definition** (`dsl/agents/{agent-name}.yaml`):\n\n {agent-name}:\n role_name: "{Role Name}"\n purpose: >-\n Domain-specific purpose describing what the agent knows\n and what it can do that static rules cannot.\n mode: read-only\n can_read_artifacts: []\n can_write_artifacts: []\n can_invoke_agents: []\n can_execute_tools: []\n can_return_handoffs: [{result-handoff-ids}]\n responsibilities: [...]\n constraints: [...]\n rules:\n - id: "R-{PREFIX}-001"\n description: ...\n severity: mandatory\n escalation_criteria:\n - condition: ...\n action: stop_and_report\n\n**Tasks** (`dsl/tasks.yaml`):\n\n {task-id}:\n description: ...\n target_agent: {agent-name}\n allowed_from_agents: [{agent-name}]\n workflow: {workflow-id}\n input_artifacts: []\n invocation_handoff: {request-handoff}\n result_handoff: {result-handoff}\n responsibilities: [...]\n completion_criteria: [...]\n\n**Handoff types** (`dsl/handoff-types.yaml`):\nUse AgentAuditResult shape as the base for result types:\n\n {result-handoff}:\n version: 1\n description: ...\n schema:\n type: object\n required: [summary, riskLevel, findings]\n properties:\n summary: { type: string }\n riskLevel:\n type: string\n enum: [low, medium, high, critical]\n findings:\n type: array\n items:\n type: object\n required: [severity, category, message]\n properties:\n id: { type: string }\n severity:\n type: string\n enum: [info, warning, error, critical]\n category: { type: string }\n target: { type: string }\n location: { type: string }\n message: { type: string }\n recommendation: { type: string }\n confidence: { type: number, minimum: 0, maximum: 1 }\n recommendedActions:\n type: array\n items:\n type: object\n required: [kind, title]\n properties:\n kind:\n type: string\n enum: [run_command, edit_file, review, confirm, block, ignore]\n title: { type: string }\n command: { type: string }\n target: { type: string }\n rationale: { type: string }\n metadata:\n type: object\n properties:\n tool: { type: string }\n command: { type: string }\n version: { type: string }\n generatedAt: { type: string }\n adapter: { type: string }\n model: { type: string }\n\nDomain-specific result types add properties alongside the base fields.\n\n**Runtime config** (`dsl/agent-runtime.config.yaml`):\n\n dsl: ./{project}-dsl.yaml\n generated_dir: ../src/generated/dsl\n\n### Step 4: Generate TypeScript Contracts\n\nAdd to package.json scripts:\n\n "dsl:generate": "agent-runtime generate --config dsl/agent-runtime.config.yaml"\n\nRun: npm run dsl:generate\n\nThis produces src/generated/dsl/ containing:\n- agents.ts (AgentContract interface + agentRegistry)\n- tasks.ts (TaskContract interface + taskRegistry)\n- workflows.ts (WorkflowContract + workflowRegistry)\n- handoffs.ts (Zod schemas + handoffSchemas + factory functions)\n- index.ts (barrel re-exports)\n\n### Step 5: Implement src/agents/ Module\n\n**src/agents/types.ts**:\n\n import type { {ResultType} } from "../generated/dsl/handoffs.js";\n\n export type TaskId = "{task-1}" | "{task-2}" | ...;\n\n export interface AgentConfig {\n adapter?: string;\n model?: string;\n temperature?: number;\n }\n\n export interface AgentOptions {\n dryRun?: boolean;\n failOn?: "warning" | "error" | "critical";\n }\n\n export interface AgentRunResult {\n taskId: TaskId;\n data: {ResultType} | null;\n raw: string;\n prompt: string;\n dryRun: boolean;\n status: "success" | "error" | "escalation" | "validation_error";\n errorMessage?: string;\n followUpsUsed: number;\n retriesUsed: number;\n }\n\n**src/agents/orchestrator.ts**:\n\n export const EXIT_RUNTIME_MISSING = 11;\n export const EXIT_ADAPTER_ERROR = 12;\n\n async function createAdapter(pkg: string, name: string, config: AgentConfig) {\n switch (name) {\n case "mock": {\n const m = await import(`${pkg}/adapters/mock`);\n return new m.MockAdapter();\n }\n case "cursor": {\n const m = await import(`${pkg}/adapters/cursor-sdk`);\n return m.CursorSdkAdapter.create({ apiKey: process.env.CURSOR_API_KEY, model: config.model });\n }\n case "claude": {\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\n }\n case "openai": {\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\n }\n case "gemini": {\n const m = await import(`${pkg}/adapters/gemini-sdk`);\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\n }\n }\n }\n\n export async function 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, cursor, claude, openai, gemini] }\n - name: model\n schema: { type: string }\n - name: dry-run\n schema: { type: boolean, default: false }\n - name: fail-on\n schema: { type: string, enum: [warning, error, critical], default: error }\n - name: output\n aliases: [o]\n schema: { type: string }\n file: { mode: write }\n - name: report-format\n schema: { type: string, enum: [json, text, yaml], default: json }\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: [network]\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: dry-run\n expectedDurationMs: 120000\n retryableExitCodes: [1, 12]\n exits:\n \'0\': { description: "No blocking findings.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'1\': { description: "General error.", stderr: { format: text } }\n \'3\': { description: "Input validation failed.", stderr: { format: json } }\n \'10\': { description: "Blocking findings detected.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'11\': { description: "Runtime not installed.", stderr: { format: json } }\n \'12\': { description: "Adapter error.", stderr: { format: json } }\n\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\nto components/schemas if not already present.\n\n### Step 8: Update README\n\nAdd "Agent-Native Toolchain" section after mechanical features:\n- Intro: tool encapsulates domain-specific semantic reasoning\n- Deterministic checks first, then semantic audit\n- Structured findings (AgentAuditResult/AgentFinding)\n- LLM Adapter Configuration table\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\n',
|
|
1309
|
+
"target_agent": "llm-feature-implementer",
|
|
1310
|
+
"allowed_from_agents": [
|
|
1311
|
+
"llm-feature-implementer"
|
|
1312
|
+
],
|
|
1313
|
+
"workflow": "implement-llm-feature",
|
|
1314
|
+
"input_artifacts": [],
|
|
1315
|
+
"invocation_handoff": "implement-request",
|
|
1316
|
+
"result_handoff": "implementation-result",
|
|
1317
|
+
"responsibilities": [
|
|
1318
|
+
"Analyze the target project and determine the right LLM commands to add",
|
|
1319
|
+
"Create all DSL definition files with correct cross-references",
|
|
1320
|
+
"Generate TypeScript contracts via agent-runtime generate",
|
|
1321
|
+
"Implement the complete src/agents/ module following the exact patterns",
|
|
1322
|
+
"Create CLI command handlers integrating with the project's existing CLI structure",
|
|
1323
|
+
"Update cli-contract.yaml with proper x-agent metadata and component schemas",
|
|
1324
|
+
"Ensure the implementation compiles and --dry-run mode works"
|
|
1325
|
+
],
|
|
1326
|
+
"completion_criteria": [
|
|
1327
|
+
"dsl/ directory contains valid DSL definitions that pass agent-runtime generate",
|
|
1328
|
+
"agent-runtime.config.yaml points to the DSL with correct generated_dir",
|
|
1329
|
+
"src/generated/dsl/ contains generated contracts (agentRegistry, taskRegistry, handoffSchemas, workflowRegistry)",
|
|
1330
|
+
"src/agents/orchestrator.ts uses runWorkflow from agent-contracts-runtime (never runTask directly, no direct adapter.send calls)",
|
|
1331
|
+
"src/agents/orchestrator.ts dynamic-imports the runtime and adapters with correct exit codes (11, 12)",
|
|
1332
|
+
"src/agents/context-builder.ts contains only domain data (file contents, config, scan results) \u2014 no hardcoded agent instructions, evaluation criteria, or output format specs",
|
|
1333
|
+
"src/agents/context-builder.ts caps input at 16KB",
|
|
1334
|
+
"src/agents/formatter.ts implements computeExitCode with the standard exit code mapping",
|
|
1335
|
+
"src/commands/ has a handler for each new LLM command, passing cwd to AgentConfig",
|
|
1336
|
+
"CLI entry point uses cli-contracts' createProgram(handlers, version) with CommandHandlers interface",
|
|
1337
|
+
"cli-contract.yaml has all new commands with --adapter, --model, --dry-run, --fail-on, --output, --report-format options",
|
|
1338
|
+
"cli-contract.yaml has x-agent metadata on each new command (riskLevel, safeDryRunOption, expectedDurationMs)",
|
|
1339
|
+
"components/schemas includes AgentAuditResult and related schemas",
|
|
1340
|
+
"All generated TypeScript compiles without type errors",
|
|
1341
|
+
"--dry-run returns the constructed prompt without calling the LLM"
|
|
1342
|
+
]
|
|
1343
|
+
},
|
|
1344
|
+
"audit-dsl": {
|
|
1345
|
+
"description": "Audit the DSL layer of an LLM command integration.\n\nVerify these files exist and are well-formed:\n- dsl/{project}-dsl.yaml \u2014 must have version:1, system:{id,name},\n agents/tasks/handoff_types via $ref\n- dsl/agents/*.yaml \u2014 each agent has role_name, purpose, mode,\n can_read_artifacts:[], can_write_artifacts:[], responsibilities,\n constraints, rules with R-PREFIX-NNN\n- dsl/tasks.yaml \u2014 target_agent, workflow, result_handoff all\n cross-reference valid IDs\n- dsl/handoff-types.yaml \u2014 version:1, schema with JSON Schema,\n result types follow AgentAuditResult shape\n- dsl/agent-runtime.config.yaml \u2014 dsl and generated_dir fields\n\nSeverity classification:\n- critical: missing version:1 or system block (generator will fail)\n- critical: task references non-existent agent or workflow\n- critical: agent mode contradicts its purpose (see below)\n- error: agent missing constraints or rules\n- error: handoff schema not following AgentAuditResult shape\n- warning: missing guardrails or guardrail_policies\n- warning: agent has no escalation_criteria\n\nCRITICAL: agent mode-purpose coherence (category: dsl-agent):\n- Agent with mode: read-only has purpose or responsibilities\n that describe file writing, editing, creation, or code\n generation \u2014 the agent's adapter tools won't include Write/Edit\n so the stated purpose is impossible to fulfil\n- Agent with mode: read-write has purpose that is purely\n analytical (audit, review, explain) with no file output \u2014\n unnecessarily broad permissions\n\nCategory vocabulary: dsl-structure, dsl-agent, dsl-task,\ndsl-handoff, dsl-workflow, dsl-guardrail.\n\nOutput a partial audit-result with findings only from the DSL layer.\n",
|
|
1346
|
+
"target_agent": "implementation-auditor",
|
|
1347
|
+
"allowed_from_agents": [
|
|
1348
|
+
"implementation-auditor"
|
|
1349
|
+
],
|
|
1350
|
+
"workflow": "audit-implementation",
|
|
1351
|
+
"input_artifacts": [],
|
|
1352
|
+
"invocation_handoff": "audit-request",
|
|
1353
|
+
"result_handoff": "audit-result",
|
|
1354
|
+
"responsibilities": [
|
|
1355
|
+
"Check all DSL files for structural correctness",
|
|
1356
|
+
"Validate cross-references (agent\u2194task\u2194workflow\u2194handoff)",
|
|
1357
|
+
"Verify guardrails and guardrail_policies",
|
|
1358
|
+
"Check agent mode-purpose coherence (read-only agents must not have write-oriented purposes; read-write agents must justify their write permissions in their purpose)"
|
|
1359
|
+
],
|
|
1360
|
+
"completion_criteria": [
|
|
1361
|
+
"Every dsl/* file checked for required fields",
|
|
1362
|
+
"Cross-references validated",
|
|
1363
|
+
"Agent mode is consistent with stated purpose and responsibilities",
|
|
1364
|
+
"Findings use dsl-* category vocabulary"
|
|
1365
|
+
]
|
|
1366
|
+
},
|
|
1367
|
+
"audit-runtime": {
|
|
1368
|
+
"description": "Audit the runtime integration layer of an LLM command integration.\n\nScan src/agents/orchestrator.ts (or equivalent runtime module):\n\nCRITICAL violations (category: runtime-orchestrator):\n- adapter.send() or adapter.sendExecution() called directly\n- adapter.followUp() called directly\n- Custom adapter class defined (not imported from runtime)\n- runWorkflow not imported from agent-contracts-runtime\n- runTask used instead of runWorkflow \u2014 consumer projects must\n use runWorkflow() which orchestrates through the DSL workflow\n DAG, activates workflow-level plugin hooks (beforeWorkflow/\n afterWorkflow), handles gate steps and step dependencies.\n runTask() is a low-level internal API; calling it directly\n bypasses workflow orchestration entirely\n\nERROR violations (category: runtime-registry):\n- Generated registries not imported from src/generated/dsl/\n- Registries not passed to runWorkflow options\n- Hard-coded agent/task definitions instead of registry lookup\n\nERROR violations (category: runtime-adapter):\n- Adapter packages imported statically (not dynamic import)\n- Missing exit code 11 when runtime import fails\n- Missing exit code 12 when adapter creation fails\n- CursorSdkAdapter created with constructor (must use static .create())\n\nERROR violations (category: runtime-handler):\n- Project has cli-contracts generated code (src/generated/program.ts\n or src/generated/cli/program.ts exporting CommandHandlers and\n createProgram) but CLI entry point manually creates Commander\n commands instead of using createProgram(handlers, version)\n- LLM command handlers are not wired through the generated\n CommandHandlers interface \u2014 handler signatures drift from the\n cli-contract.yaml definition without type errors\n- CLI entry point calls runTask directly instead of going through\n the command handler \u2192 context-builder \u2192 orchestrator chain\n\nWARNING violations (category: runtime-plugin):\n- Plugin hooks explicitly bypassed or ignored\n\nCategory vocabulary: runtime-orchestrator, runtime-registry,\nruntime-adapter, runtime-handler, runtime-plugin.\n\nOutput a partial audit-result with findings only from the runtime layer.\n",
|
|
1369
|
+
"target_agent": "implementation-auditor",
|
|
1370
|
+
"allowed_from_agents": [
|
|
1371
|
+
"implementation-auditor"
|
|
1372
|
+
],
|
|
1373
|
+
"workflow": "audit-implementation",
|
|
1374
|
+
"input_artifacts": [],
|
|
1375
|
+
"invocation_handoff": "audit-request",
|
|
1376
|
+
"result_handoff": "audit-result",
|
|
1377
|
+
"responsibilities": [
|
|
1378
|
+
"Scan orchestrator code for direct adapter usage",
|
|
1379
|
+
"Verify runWorkflow is used (not runTask) for LLM command execution",
|
|
1380
|
+
"Verify registry imports and passing",
|
|
1381
|
+
"Check adapter creation patterns and exit codes",
|
|
1382
|
+
"Verify cli-contracts handler wiring (CommandHandlers + createProgram used in CLI entry point)"
|
|
1383
|
+
],
|
|
1384
|
+
"completion_criteria": [
|
|
1385
|
+
"All orchestrator files scanned for adapter.send / adapter.followUp",
|
|
1386
|
+
"No runTask usage found (runWorkflow must be used instead)",
|
|
1387
|
+
"Registry usage verified",
|
|
1388
|
+
"Exit code 11/12 patterns checked",
|
|
1389
|
+
"cli-contracts handler integration verified (CommandHandlers interface used, createProgram called)"
|
|
1390
|
+
]
|
|
1391
|
+
},
|
|
1392
|
+
"audit-cli-contract": {
|
|
1393
|
+
"description": "Audit the CLI contract layer of an LLM command integration.\n\nParse cli-contract.yaml and check each LLM command:\n\nERROR: missing standard options (category: cli-contract-options):\n- --adapter, --model, --dry-run, --fail-on, --output, --report-format\n- Using --format instead of --report-format for LLM commands\n\nERROR: missing x-agent metadata (category: cli-contract-xagent):\n- No x-agent block on LLM command\n- Missing riskLevel, safeDryRunOption, or expectedDurationMs\n- Using snake_case instead of camelCase for x-agent fields\n\nERROR: wrong exit codes (category: cli-contract-exits):\n- Missing exit 0/1/3/10/11/12 definitions\n- Exit 10 not defined for finding-based commands\n\nWARNING: missing schemas (category: cli-contract-schema):\n- AgentAuditResult not in components/schemas\n- AgentFinding, AgentRecommendedAction, AgentEvidence not defined\n\nCategory vocabulary: cli-contract-options, cli-contract-xagent,\ncli-contract-exits, cli-contract-schema.\n\nOutput a partial audit-result with findings only from the CLI contract layer.\n",
|
|
1394
|
+
"target_agent": "implementation-auditor",
|
|
1395
|
+
"allowed_from_agents": [
|
|
1396
|
+
"implementation-auditor"
|
|
1397
|
+
],
|
|
1398
|
+
"workflow": "audit-implementation",
|
|
1399
|
+
"input_artifacts": [],
|
|
1400
|
+
"invocation_handoff": "audit-request",
|
|
1401
|
+
"result_handoff": "audit-result",
|
|
1402
|
+
"responsibilities": [
|
|
1403
|
+
"Check each LLM command for standard options",
|
|
1404
|
+
"Verify x-agent metadata fields and casing",
|
|
1405
|
+
"Validate exit code definitions",
|
|
1406
|
+
"Check components/schemas for canonical types"
|
|
1407
|
+
],
|
|
1408
|
+
"completion_criteria": [
|
|
1409
|
+
"Every LLM command checked for all 6 standard options",
|
|
1410
|
+
"x-agent metadata validated on every LLM command",
|
|
1411
|
+
"Exit codes verified against convention",
|
|
1412
|
+
"Schema completeness checked"
|
|
1413
|
+
]
|
|
1414
|
+
},
|
|
1415
|
+
"audit-architecture": {
|
|
1416
|
+
"description": `Audit the architecture and module structure of an LLM command integration.
|
|
1417
|
+
|
|
1418
|
+
Verify module structure (category: architecture-modules):
|
|
1419
|
+
- src/agents/types.ts exists with TaskId, AgentConfig, AgentOptions, AgentRunResult
|
|
1420
|
+
- src/agents/orchestrator.ts exists
|
|
1421
|
+
- src/agents/context-builder.ts exists
|
|
1422
|
+
- src/agents/formatter.ts exists with computeExitCode
|
|
1423
|
+
|
|
1424
|
+
Verify behavior (category: architecture-dry-run):
|
|
1425
|
+
- --dry-run path returns the constructed prompt without calling the adapter
|
|
1426
|
+
- buildTaskPrompt is used (not a placeholder string)
|
|
1427
|
+
|
|
1428
|
+
CRITICAL: context-builder SSoT violations (category: architecture-context-builder):
|
|
1429
|
+
|
|
1430
|
+
The context-builder's role is to assemble domain-specific DATA (file
|
|
1431
|
+
contents, configuration, scan results, schema context) into the user
|
|
1432
|
+
prompt. Agent INSTRUCTIONS (how to evaluate, what rules to apply,
|
|
1433
|
+
what patterns to look for, output format) belong in the DSL agent
|
|
1434
|
+
definition and are injected by buildTaskPrompt / runWorkflow.
|
|
1435
|
+
|
|
1436
|
+
Detect any of the following in context-builder source code:
|
|
1437
|
+
- Sections titled "## Instructions", "## Required Patterns",
|
|
1438
|
+
"## Audit Instructions", "## Output Format", or similar
|
|
1439
|
+
behavioral directive headings \u2014 these are agent instructions
|
|
1440
|
+
that belong in DSL (agent purpose, responsibilities, constraints,
|
|
1441
|
+
rules) and must not be hardcoded in context-builder
|
|
1442
|
+
- Output format specifications (field lists, JSON/YAML schema
|
|
1443
|
+
descriptions, example output structures) \u2014 buildTaskPrompt
|
|
1444
|
+
already generates "Required Output Format" from the handoff
|
|
1445
|
+
Zod schema; duplicating this in context-builder causes conflicts
|
|
1446
|
+
- Domain-specific evaluation criteria, checklists, anti-pattern
|
|
1447
|
+
definitions, rule sets, or API reference material \u2014 these
|
|
1448
|
+
belong in the DSL agent definition's purpose field
|
|
1449
|
+
- Any string that duplicates or paraphrases content already
|
|
1450
|
+
present in the DSL agent's purpose, responsibilities,
|
|
1451
|
+
constraints, or rules fields
|
|
1452
|
+
|
|
1453
|
+
What IS allowed in context-builder:
|
|
1454
|
+
- File contents read from disk (migration SQL, schema, config)
|
|
1455
|
+
- Project metadata (dialect, directories, file lists)
|
|
1456
|
+
- Deterministic pre-analysis results (lint violations, scan output)
|
|
1457
|
+
- Operational context (target path, cwd, timestamp)
|
|
1458
|
+
- Brief task framing ("# Migration Safety Audit Request")
|
|
1459
|
+
|
|
1460
|
+
ERROR: mode-purpose coherence (category: architecture-agent-coherence):
|
|
1461
|
+
- DSL agent with mode: read-only has purpose or responsibilities
|
|
1462
|
+
that describe file writing, editing, creation, or modification
|
|
1463
|
+
- DSL agent with mode: read-write but no cwd propagated to adapter
|
|
1464
|
+
\u2014 the agent's file tools won't operate in the project directory
|
|
1465
|
+
- Command handler doesn't pass cwd to AgentConfig when using an
|
|
1466
|
+
agentic adapter (claude, cursor)
|
|
1467
|
+
|
|
1468
|
+
ERROR: adapter cwd propagation (category: architecture-adapter-cwd):
|
|
1469
|
+
- AgentConfig type has no cwd field
|
|
1470
|
+
- Command handlers don't set config.cwd = process.cwd() or
|
|
1471
|
+
resolve(projectDir)
|
|
1472
|
+
- createAdapter doesn't pass cwd to adapter constructor/factory
|
|
1473
|
+
- Agentic adapters (claude, cursor) instantiated without cwd \u2014
|
|
1474
|
+
their file tools will operate in an undefined directory
|
|
1475
|
+
|
|
1476
|
+
CRITICAL: runTask usage (category: architecture-handler):
|
|
1477
|
+
- runTask() imported or called anywhere in the consumer project \u2014
|
|
1478
|
+
consumer projects must use runWorkflow() exclusively; runTask()
|
|
1479
|
+
is a low-level internal API that bypasses workflow DAG
|
|
1480
|
+
orchestration, workflow-level plugin hooks, and gate steps
|
|
1481
|
+
|
|
1482
|
+
ERROR: cli-contracts handler wiring (category: architecture-handler):
|
|
1483
|
+
- Project has cli-contracts generated code (src/generated/program.ts
|
|
1484
|
+
or src/generated/cli/program.ts with CommandHandlers) but CLI
|
|
1485
|
+
entry point manually creates Commander commands instead of
|
|
1486
|
+
calling createProgram(handlers, version)
|
|
1487
|
+
- Command handlers bypass the generated CommandHandlers interface
|
|
1488
|
+
|
|
1489
|
+
Scan for direct SDK imports (category: architecture-modules):
|
|
1490
|
+
- @anthropic-ai/sdk or @anthropic-ai/claude-agent-sdk imported
|
|
1491
|
+
outside src/agents/orchestrator.ts or adapter files
|
|
1492
|
+
- openai or @openai/agents imported outside adapters
|
|
1493
|
+
- @google/genai imported outside adapters
|
|
1494
|
+
- @cursor/sdk imported outside adapters
|
|
1495
|
+
|
|
1496
|
+
Category vocabulary: architecture-modules, architecture-dry-run,
|
|
1497
|
+
architecture-context-builder, architecture-agent-coherence,
|
|
1498
|
+
architecture-adapter-cwd, architecture-handler,
|
|
1499
|
+
architecture-formatter.
|
|
1500
|
+
|
|
1501
|
+
Output a partial audit-result with findings only from the architecture layer.
|
|
1502
|
+
`,
|
|
1503
|
+
"target_agent": "implementation-auditor",
|
|
1504
|
+
"allowed_from_agents": [
|
|
1505
|
+
"implementation-auditor"
|
|
1506
|
+
],
|
|
1507
|
+
"workflow": "audit-implementation",
|
|
1508
|
+
"input_artifacts": [],
|
|
1509
|
+
"invocation_handoff": "audit-request",
|
|
1510
|
+
"result_handoff": "audit-result",
|
|
1511
|
+
"responsibilities": [
|
|
1512
|
+
"Verify module structure",
|
|
1513
|
+
"Check dry-run behavior",
|
|
1514
|
+
"Audit context-builder for SSoT violations (hardcoded instructions, output format specs, domain rules that belong in DSL)",
|
|
1515
|
+
"Check mode-purpose coherence across DSL definitions and runtime code",
|
|
1516
|
+
"Verify cwd propagation from command handler through adapter config",
|
|
1517
|
+
"Verify cli-contracts handler wiring (CommandHandlers + createProgram)",
|
|
1518
|
+
"Scan for direct SDK imports"
|
|
1519
|
+
],
|
|
1520
|
+
"completion_criteria": [
|
|
1521
|
+
"Module structure verified",
|
|
1522
|
+
"Dry-run behavior confirmed",
|
|
1523
|
+
"Context-builder contains only domain data, not agent instructions",
|
|
1524
|
+
"Agent mode is consistent with purpose and tool usage",
|
|
1525
|
+
"cwd is propagated to agentic adapters",
|
|
1526
|
+
"cli-contracts handler integration verified",
|
|
1527
|
+
"No direct SDK imports outside adapter files"
|
|
1528
|
+
]
|
|
1529
|
+
},
|
|
1530
|
+
"audit-merge": {
|
|
1531
|
+
"description": 'Merge the partial audit results from the four parallel layer audits\n(DSL, runtime, CLI contract, architecture) into a single unified\naudit-result.\n\nThe prior_context contains the JSON output from each completed\naudit step. Parse each one, combine all findings into a single\narray, deduplicate by (target + message), assign sequential IDs\n(F-001, F-002, ...), derive the overall riskLevel from the worst\nfinding severity, and produce prioritized recommendedActions.\n\nMerging rules:\n- Collect all findings from all layer results\n- Sort: critical first, then error, warning, info\n- Assign sequential IDs: F-001, F-002, ...\n- Deduplicate: if two findings have the same target and message, keep one\n- Derive riskLevel: any critical \u2192 critical, any error \u2192 high,\n any warning \u2192 medium, info only \u2192 low\n- Merge recommendedActions from all layers, deduplicate by title\n- Set metadata: { tool: "agent-runtime", command: "audit-implementation" }\n',
|
|
1532
|
+
"target_agent": "implementation-auditor",
|
|
1533
|
+
"allowed_from_agents": [
|
|
1534
|
+
"implementation-auditor"
|
|
1535
|
+
],
|
|
1536
|
+
"workflow": "audit-implementation",
|
|
1537
|
+
"input_artifacts": [],
|
|
1538
|
+
"invocation_handoff": "audit-request",
|
|
1539
|
+
"result_handoff": "audit-result",
|
|
1540
|
+
"responsibilities": [
|
|
1541
|
+
"Parse prior_context JSON from each layer audit step",
|
|
1542
|
+
"Merge and deduplicate findings",
|
|
1543
|
+
"Derive overall riskLevel",
|
|
1544
|
+
"Produce a single coherent summary paragraph"
|
|
1545
|
+
],
|
|
1546
|
+
"completion_criteria": [
|
|
1547
|
+
"All findings from all layers included",
|
|
1548
|
+
"No duplicate findings",
|
|
1549
|
+
"riskLevel correctly derived from worst finding",
|
|
1550
|
+
"Summary paragraph covers all audited layers"
|
|
1551
|
+
]
|
|
1552
|
+
}
|
|
1553
|
+
},
|
|
1554
|
+
"handoff_types": {
|
|
1555
|
+
"implement-request": {
|
|
1556
|
+
"version": 1,
|
|
1557
|
+
"description": "Request to implement LLM-powered features in a CLI tool",
|
|
1558
|
+
"schema": {
|
|
1559
|
+
"type": "object",
|
|
1560
|
+
"required": [
|
|
1561
|
+
"description",
|
|
1562
|
+
"project_dir"
|
|
1563
|
+
],
|
|
1564
|
+
"properties": {
|
|
1565
|
+
"description": {
|
|
1566
|
+
"type": "string",
|
|
1567
|
+
"description": "Description of the LLM feature(s) to implement"
|
|
1568
|
+
},
|
|
1569
|
+
"project_dir": {
|
|
1570
|
+
"type": "string",
|
|
1571
|
+
"description": "Absolute path to the target project directory"
|
|
1572
|
+
},
|
|
1573
|
+
"reference_doc": {
|
|
1574
|
+
"type": "string",
|
|
1575
|
+
"description": "Content of the integrate-llm-commands reference documentation"
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
},
|
|
1580
|
+
"audit-request": {
|
|
1581
|
+
"version": 1,
|
|
1582
|
+
"description": "Request to audit an LLM command integration",
|
|
1583
|
+
"schema": {
|
|
1584
|
+
"type": "object",
|
|
1585
|
+
"required": [
|
|
1586
|
+
"project_dir"
|
|
1587
|
+
],
|
|
1588
|
+
"properties": {
|
|
1589
|
+
"project_dir": {
|
|
1590
|
+
"type": "string",
|
|
1591
|
+
"description": "Absolute path to the target project directory"
|
|
1592
|
+
},
|
|
1593
|
+
"focus": {
|
|
1594
|
+
"type": "string",
|
|
1595
|
+
"description": "Optional focus area (dsl, runtime, cli-contract, architecture, or all). Defaults to all.",
|
|
1596
|
+
"enum": [
|
|
1597
|
+
"all",
|
|
1598
|
+
"dsl",
|
|
1599
|
+
"runtime",
|
|
1600
|
+
"cli-contract",
|
|
1601
|
+
"architecture"
|
|
1602
|
+
]
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
},
|
|
1607
|
+
"audit-result": {
|
|
1608
|
+
"version": 1,
|
|
1609
|
+
"description": "Structured audit result following AgentAuditResult shape. Conforms to cli-contracts reference schema.",
|
|
1610
|
+
"schema": {
|
|
1611
|
+
"type": "object",
|
|
1612
|
+
"required": [
|
|
1613
|
+
"summary",
|
|
1614
|
+
"riskLevel",
|
|
1615
|
+
"findings"
|
|
1616
|
+
],
|
|
1617
|
+
"properties": {
|
|
1618
|
+
"summary": {
|
|
1619
|
+
"type": "string",
|
|
1620
|
+
"description": "One-paragraph overall assessment"
|
|
1621
|
+
},
|
|
1622
|
+
"riskLevel": {
|
|
1623
|
+
"type": "string",
|
|
1624
|
+
"enum": [
|
|
1625
|
+
"low",
|
|
1626
|
+
"medium",
|
|
1627
|
+
"high",
|
|
1628
|
+
"critical"
|
|
1629
|
+
],
|
|
1630
|
+
"description": "Derived from worst finding: any critical \u2192 critical, any error \u2192 high, any warning \u2192 medium, info only \u2192 low"
|
|
1631
|
+
},
|
|
1632
|
+
"findings": {
|
|
1633
|
+
"type": "array",
|
|
1634
|
+
"items": {
|
|
1635
|
+
"type": "object",
|
|
1636
|
+
"required": [
|
|
1637
|
+
"severity",
|
|
1638
|
+
"category",
|
|
1639
|
+
"message"
|
|
1640
|
+
],
|
|
1641
|
+
"properties": {
|
|
1642
|
+
"id": {
|
|
1643
|
+
"type": "string",
|
|
1644
|
+
"description": "Unique finding identifier (e.g. AUDIT-001)"
|
|
1645
|
+
},
|
|
1646
|
+
"severity": {
|
|
1647
|
+
"type": "string",
|
|
1648
|
+
"enum": [
|
|
1649
|
+
"info",
|
|
1650
|
+
"warning",
|
|
1651
|
+
"error",
|
|
1652
|
+
"critical"
|
|
1653
|
+
]
|
|
1654
|
+
},
|
|
1655
|
+
"category": {
|
|
1656
|
+
"type": "string",
|
|
1657
|
+
"description": "One of: dsl-structure, dsl-agent, dsl-task, dsl-handoff, dsl-workflow, dsl-guardrail, runtime-adapter, runtime-orchestrator, runtime-registry, runtime-handler, runtime-plugin, cli-contract-options, cli-contract-xagent, cli-contract-exits, cli-contract-schema, architecture-modules, architecture-dry-run, architecture-context-builder, architecture-agent-coherence, architecture-adapter-cwd, architecture-handler, architecture-formatter"
|
|
1658
|
+
},
|
|
1659
|
+
"target": {
|
|
1660
|
+
"type": "string",
|
|
1661
|
+
"description": "File path where the issue was found"
|
|
1662
|
+
},
|
|
1663
|
+
"location": {
|
|
1664
|
+
"type": "string",
|
|
1665
|
+
"description": "Line number or section within the file"
|
|
1666
|
+
},
|
|
1667
|
+
"message": {
|
|
1668
|
+
"type": "string",
|
|
1669
|
+
"description": "Concise description of the issue"
|
|
1670
|
+
},
|
|
1671
|
+
"recommendation": {
|
|
1672
|
+
"type": "string",
|
|
1673
|
+
"description": "Concrete fix or remediation step"
|
|
1674
|
+
},
|
|
1675
|
+
"confidence": {
|
|
1676
|
+
"type": "number",
|
|
1677
|
+
"minimum": 0,
|
|
1678
|
+
"maximum": 1,
|
|
1679
|
+
"description": "1.0 for pattern match, 0.8+ for structural check, 0.5-0.8 for heuristic assessment"
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
},
|
|
1684
|
+
"recommendedActions": {
|
|
1685
|
+
"type": "array",
|
|
1686
|
+
"items": {
|
|
1687
|
+
"type": "object",
|
|
1688
|
+
"required": [
|
|
1689
|
+
"kind",
|
|
1690
|
+
"title"
|
|
1691
|
+
],
|
|
1692
|
+
"properties": {
|
|
1693
|
+
"kind": {
|
|
1694
|
+
"type": "string",
|
|
1695
|
+
"enum": [
|
|
1696
|
+
"run_command",
|
|
1697
|
+
"edit_file",
|
|
1698
|
+
"review",
|
|
1699
|
+
"confirm",
|
|
1700
|
+
"block",
|
|
1701
|
+
"ignore"
|
|
1702
|
+
]
|
|
1703
|
+
},
|
|
1704
|
+
"title": {
|
|
1705
|
+
"type": "string"
|
|
1706
|
+
},
|
|
1707
|
+
"command": {
|
|
1708
|
+
"type": "string",
|
|
1709
|
+
"description": "CLI command to run (for run_command kind)"
|
|
1710
|
+
},
|
|
1711
|
+
"target": {
|
|
1712
|
+
"type": "string",
|
|
1713
|
+
"description": "Target file or resource"
|
|
1714
|
+
},
|
|
1715
|
+
"rationale": {
|
|
1716
|
+
"type": "string"
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
},
|
|
1721
|
+
"metadata": {
|
|
1722
|
+
"type": "object",
|
|
1723
|
+
"properties": {
|
|
1724
|
+
"tool": {
|
|
1725
|
+
"type": "string"
|
|
1726
|
+
},
|
|
1727
|
+
"command": {
|
|
1728
|
+
"type": "string"
|
|
1729
|
+
},
|
|
1730
|
+
"version": {
|
|
1731
|
+
"type": "string"
|
|
1732
|
+
},
|
|
1733
|
+
"generatedAt": {
|
|
1734
|
+
"type": "string"
|
|
1735
|
+
},
|
|
1736
|
+
"adapter": {
|
|
1737
|
+
"type": "string"
|
|
1738
|
+
},
|
|
1739
|
+
"model": {
|
|
1740
|
+
"type": "string"
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
},
|
|
1747
|
+
"implementation-result": {
|
|
1748
|
+
"version": 1,
|
|
1749
|
+
"description": "Result of the LLM feature implementation",
|
|
1750
|
+
"schema": {
|
|
1751
|
+
"type": "object",
|
|
1752
|
+
"required": [
|
|
1753
|
+
"files_created",
|
|
1754
|
+
"files_modified",
|
|
1755
|
+
"summary"
|
|
1756
|
+
],
|
|
1757
|
+
"properties": {
|
|
1758
|
+
"files_created": {
|
|
1759
|
+
"type": "array",
|
|
1760
|
+
"items": {
|
|
1761
|
+
"type": "string"
|
|
1762
|
+
},
|
|
1763
|
+
"description": "List of newly created files"
|
|
1764
|
+
},
|
|
1765
|
+
"files_modified": {
|
|
1766
|
+
"type": "array",
|
|
1767
|
+
"items": {
|
|
1768
|
+
"type": "string"
|
|
1769
|
+
},
|
|
1770
|
+
"description": "List of modified existing files"
|
|
1771
|
+
},
|
|
1772
|
+
"summary": {
|
|
1773
|
+
"type": "string",
|
|
1774
|
+
"description": "Human-readable summary of the implementation"
|
|
1775
|
+
},
|
|
1776
|
+
"commands_added": {
|
|
1777
|
+
"type": "array",
|
|
1778
|
+
"items": {
|
|
1779
|
+
"type": "object",
|
|
1780
|
+
"required": [
|
|
1781
|
+
"name",
|
|
1782
|
+
"type"
|
|
1783
|
+
],
|
|
1784
|
+
"properties": {
|
|
1785
|
+
"name": {
|
|
1786
|
+
"type": "string",
|
|
1787
|
+
"description": "Command name"
|
|
1788
|
+
},
|
|
1789
|
+
"type": {
|
|
1790
|
+
"type": "string",
|
|
1791
|
+
"enum": [
|
|
1792
|
+
"audit",
|
|
1793
|
+
"propose",
|
|
1794
|
+
"explain"
|
|
1795
|
+
],
|
|
1796
|
+
"description": "Command type"
|
|
1797
|
+
},
|
|
1798
|
+
"description": {
|
|
1799
|
+
"type": "string",
|
|
1800
|
+
"description": "Command description"
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
},
|
|
1805
|
+
"next_steps": {
|
|
1806
|
+
"type": "array",
|
|
1807
|
+
"items": {
|
|
1808
|
+
"type": "string"
|
|
1809
|
+
},
|
|
1810
|
+
"description": "Recommended next steps for the developer"
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
},
|
|
1816
|
+
"guardrails": {
|
|
1817
|
+
"output-schema-conformance": {
|
|
1818
|
+
"description": "Ensure all agent outputs conform to their respective handoff schemas. Validation is performed at runtime via Zod.",
|
|
1819
|
+
"scope": {
|
|
1820
|
+
"agents": [
|
|
1821
|
+
"llm-feature-implementer",
|
|
1822
|
+
"implementation-auditor"
|
|
1823
|
+
],
|
|
1824
|
+
"tasks": [
|
|
1825
|
+
"implement-llm-feature",
|
|
1826
|
+
"audit-dsl",
|
|
1827
|
+
"audit-runtime",
|
|
1828
|
+
"audit-cli-contract",
|
|
1829
|
+
"audit-architecture",
|
|
1830
|
+
"audit-merge"
|
|
1831
|
+
]
|
|
1832
|
+
},
|
|
1833
|
+
"rationale": "Structured output conformance is critical for CLI parsing and downstream tooling integration."
|
|
1834
|
+
},
|
|
1835
|
+
"no-direct-api-call": {
|
|
1836
|
+
"description": "The implementer agent must not generate code that calls LLM APIs directly. All LLM invocations must go through agent-contracts-runtime runWorkflow().",
|
|
1837
|
+
"scope": {
|
|
1838
|
+
"agents": [
|
|
1839
|
+
"llm-feature-implementer"
|
|
1840
|
+
]
|
|
1841
|
+
},
|
|
1842
|
+
"rationale": "Preserves SDK adapter abstraction, enabling adapter swap, plugin hooks, and guardrail enforcement."
|
|
1843
|
+
},
|
|
1844
|
+
"audit-read-only": {
|
|
1845
|
+
"description": "The auditor agent must not create, modify, or delete any files. It operates in read-only mode and produces findings only.",
|
|
1846
|
+
"scope": {
|
|
1847
|
+
"agents": [
|
|
1848
|
+
"implementation-auditor"
|
|
1849
|
+
]
|
|
1850
|
+
},
|
|
1851
|
+
"rationale": "Audit results must be reviewed by the developer before changes are applied. The auditor observes; the developer decides."
|
|
1852
|
+
}
|
|
1853
|
+
},
|
|
1854
|
+
"guardrail_policies": {
|
|
1855
|
+
"implement-safety-policy": {
|
|
1856
|
+
"description": "Guardrail policy for the LLM feature implementation agent",
|
|
1857
|
+
"rules": [
|
|
1858
|
+
{
|
|
1859
|
+
"guardrail": "output-schema-conformance",
|
|
1860
|
+
"severity": "critical",
|
|
1861
|
+
"action": "block"
|
|
1862
|
+
},
|
|
1863
|
+
{
|
|
1864
|
+
"guardrail": "no-direct-api-call",
|
|
1865
|
+
"severity": "critical",
|
|
1866
|
+
"action": "block"
|
|
1867
|
+
}
|
|
1868
|
+
]
|
|
1869
|
+
},
|
|
1870
|
+
"audit-safety-policy": {
|
|
1871
|
+
"description": "Guardrail policy for the implementation auditor agent",
|
|
1872
|
+
"rules": [
|
|
1873
|
+
{
|
|
1874
|
+
"guardrail": "output-schema-conformance",
|
|
1875
|
+
"severity": "critical",
|
|
1876
|
+
"action": "block"
|
|
1877
|
+
},
|
|
1878
|
+
{
|
|
1879
|
+
"guardrail": "audit-read-only",
|
|
1880
|
+
"severity": "critical",
|
|
1881
|
+
"action": "block"
|
|
1882
|
+
}
|
|
1883
|
+
]
|
|
1884
|
+
}
|
|
1885
|
+
},
|
|
1886
|
+
"workflow": {
|
|
1887
|
+
"implement-llm-feature": {
|
|
1888
|
+
"description": "Implement LLM-powered commands in a CLI tool",
|
|
1889
|
+
"trigger": "cli-command",
|
|
1890
|
+
"entry_conditions": [
|
|
1891
|
+
"Target project is a TypeScript / Node.js project",
|
|
1892
|
+
"cli-contract.yaml exists or is being created"
|
|
1893
|
+
],
|
|
1894
|
+
"steps": [
|
|
1895
|
+
{
|
|
1896
|
+
"type": "delegate",
|
|
1897
|
+
"task": "implement-llm-feature",
|
|
1898
|
+
"from_agent": "llm-feature-implementer"
|
|
1899
|
+
}
|
|
1900
|
+
]
|
|
1901
|
+
},
|
|
1902
|
+
"audit-implementation": {
|
|
1903
|
+
"description": "Audit an LLM command integration for pattern conformance",
|
|
1904
|
+
"trigger": "cli-command",
|
|
1905
|
+
"entry_conditions": [
|
|
1906
|
+
"Target project has LLM command integration to audit"
|
|
1907
|
+
],
|
|
1908
|
+
"steps": [
|
|
1909
|
+
{
|
|
1910
|
+
"type": "delegate",
|
|
1911
|
+
"task": "audit-dsl",
|
|
1912
|
+
"from_agent": "implementation-auditor",
|
|
1913
|
+
"depends_on": []
|
|
1914
|
+
},
|
|
1915
|
+
{
|
|
1916
|
+
"type": "delegate",
|
|
1917
|
+
"task": "audit-runtime",
|
|
1918
|
+
"from_agent": "implementation-auditor",
|
|
1919
|
+
"depends_on": []
|
|
1920
|
+
},
|
|
1921
|
+
{
|
|
1922
|
+
"type": "delegate",
|
|
1923
|
+
"task": "audit-cli-contract",
|
|
1924
|
+
"from_agent": "implementation-auditor",
|
|
1925
|
+
"depends_on": []
|
|
1926
|
+
},
|
|
1927
|
+
{
|
|
1928
|
+
"type": "delegate",
|
|
1929
|
+
"task": "audit-architecture",
|
|
1930
|
+
"from_agent": "implementation-auditor",
|
|
1931
|
+
"depends_on": []
|
|
1932
|
+
},
|
|
1933
|
+
{
|
|
1934
|
+
"type": "delegate",
|
|
1935
|
+
"task": "audit-merge",
|
|
1936
|
+
"from_agent": "implementation-auditor",
|
|
1937
|
+
"depends_on": [
|
|
1938
|
+
"audit-dsl",
|
|
1939
|
+
"audit-runtime",
|
|
1940
|
+
"audit-cli-contract",
|
|
1941
|
+
"audit-architecture"
|
|
1942
|
+
]
|
|
1943
|
+
}
|
|
1944
|
+
]
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
};
|
|
1948
|
+
|
|
1088
1949
|
// src/lib/implement.ts
|
|
1089
1950
|
function getLocale() {
|
|
1090
1951
|
return process.env.LANG?.split(".")[0] ?? process.env.LC_ALL?.split(".")[0] ?? process.env.LANGUAGE?.split(":")[0] ?? "en_US";
|
|
@@ -1496,7 +2357,7 @@ function formatAuditResult(result) {
|
|
|
1496
2357
|
// src/cli/index.ts
|
|
1497
2358
|
import YAML3 from "yaml";
|
|
1498
2359
|
register();
|
|
1499
|
-
var VERSION = "0.
|
|
2360
|
+
var VERSION = "0.33.3";
|
|
1500
2361
|
async function loadGeneratedContracts(configPath) {
|
|
1501
2362
|
const config = await loadConfig(configPath);
|
|
1502
2363
|
const basePath = `${config.generatedDir}/index`;
|
|
@@ -1942,6 +2803,19 @@ var handlers = {
|
|
|
1942
2803
|
process.exit(result.exitCode);
|
|
1943
2804
|
}
|
|
1944
2805
|
},
|
|
2806
|
+
async agents(options, _globalOpts) {
|
|
2807
|
+
const format = options.format ?? "yaml";
|
|
2808
|
+
try {
|
|
2809
|
+
if (format === "json") {
|
|
2810
|
+
console.log(JSON.stringify(resolvedDsl, null, 2));
|
|
2811
|
+
} else {
|
|
2812
|
+
console.log(YAML3.stringify(resolvedDsl, { lineWidth: 120 }));
|
|
2813
|
+
}
|
|
2814
|
+
} catch (err) {
|
|
2815
|
+
console.error(`Failed to output DSL: ${err.message}`);
|
|
2816
|
+
process.exit(1);
|
|
2817
|
+
}
|
|
2818
|
+
},
|
|
1945
2819
|
async doctor(globalOpts) {
|
|
1946
2820
|
const configPath = globalOpts.config ?? "./agent-runtime.config.yaml";
|
|
1947
2821
|
const result = await runDoctor(configPath);
|