diff --git a/changelog.d/854.md b/changelog.d/854.md new file mode 100644 index 0000000000..3292a17a20 --- /dev/null +++ b/changelog.d/854.md @@ -0,0 +1,3 @@ +### Fixed + +- Make `devops docs generate` and `devops docs check` fail closed when a command module, FastMCP tool listing, or exception module fails to import, and render group-callback options, MCP array item types and enum values, all project config file candidates and `Settings` sections in `docs/CONFIGURATION.md`, and all `DevOpsCLIError` subclasses with their constructor error and exit codes in `docs/ERRORS.md` (#854). diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 9530aad374..20684326a0 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -632,6 +632,19 @@ devops workspace clean [OPTIONS] Install and manage DevOps tool binaries. +```bash +devops install-tools [OPTIONS] COMMAND [ARGS]... +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--tool`, `-t` | `string` | - | Install a specific tool. | +| `--target-dir`, `-d` | `path` | `~/.local/bin` | Target directory path for operation. | +| `--only-missing` | `boolean` | - | Only install tools that are not linked at their locked version. | +| `--check` | `boolean` | - | Install nothing: report each tool not linked at its locked version, and exit 1 if any. | + ### `devops install-tools status` **Show each tool's locked version and where its command is installed, without a request.** @@ -2532,6 +2545,22 @@ devops config audit-keys [OPTIONS] Run tests, linting, formatting, and type-checks. +```bash +devops ci [OPTIONS] COMMAND [ARGS]... +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--fix` / `--no-fix` | `boolean` | `True` | Auto-fix lint/format before reporting status. | +| `--check` | `boolean` | - | Run in check-only mode without automatically applying formatting or lint fixes. | +| `--cache` / `--no-cache` | `boolean` | `True` | Reuse a cached verdict when the codebase is unchanged. Results are recorded either way. | +| `--force`, `-f` | `boolean` | - | Bypass CI execution cache and force re-execution of all quality gates. | +| `--only` | `string` | - | Run only the specified check names (comma-separated or repeated). | +| `--skip` | `string` | - | Skip the specified check names (comma-separated or repeated). | +| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | + ### `devops ci test` **Run the test suite, or only the tests covering the given source files.** @@ -2877,6 +2906,17 @@ devops uv run Security scanner suite: Trivy, Gitleaks, Semgrep, Checkov, Kubeconform. +```bash +devops scan [OPTIONS] COMMAND [ARGS]... +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | +| `--json` | `boolean` | - | Output findings or metrics as JSON. | + ### `devops scan trivy` **Run Aqua Trivy vulnerability, secret, and misconfiguration scan.** @@ -3120,6 +3160,16 @@ devops scan sarif [OPTIONS] Configure, test, chat, analyze, and review codebases (Ollama, Claude, Copilot). +```bash +devops ai [OPTIONS] COMMAND [ARGS]... +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--explain`, `-e` | `boolean` | - | Explain AI agent workflows, FastMCP tools, RAG terminology, and metrics. | + ### `devops ai config` **Show or update AI provider configuration.** @@ -5290,6 +5340,16 @@ devops ai research analogies [OPTIONS] AI-powered multi-persona code review and security audits. +```bash +devops review [OPTIONS] COMMAND [ARGS]... +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--explain`, `-e` | `boolean` | - | Explain code review personas, severity levels, and terminology. | + ### `devops review path` **Review source files directly (no git required).** diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index c7a4480abf..7d65781012 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -5,7 +5,7 @@ This document is automatically generated from `Settings` (`src/devops_cli/config DevOps CLI supports hierarchical configuration resolution through: 1. **CLI Flags & Arguments** (highest precedence) 2. **Environment Variables** (`DEVOPS_CLI_*`) -3. **Local Project Configuration** (the file `DEVOPS_CLI_CONFIG` names, else the nearest `config.yaml`, `.devops/config.yaml` or `.devops.yaml` from the working directory up to its repository root) +3. **Local Project Configuration** (the file `DEVOPS_CLI_CONFIG` names, else the nearest `config.yaml`, `.devcontainer/config.yaml`, `.devops/config.yaml`, `.devops.yaml` or `.devcontainer/.devops.yaml` from the working directory up to its repository root) 4. **Global User Configuration** (`~/.config/devops-cli/config.yaml`) 5. **System Defaults** @@ -13,6 +13,14 @@ A `devops review` command reads a tree it does not own. Started in a repository --- +## GitHub Configuration (`github`) + +GitHub authentication, default owner, and repository settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `default_org` | `Union` | - | `DEVOPS_CLI_GITHUB_DEFAULT_ORG` | - | + ## SSH Configuration (`ssh`) SSH key generation, rotation, signing, and GitHub registration settings. @@ -39,9 +47,82 @@ Multi-root VS Code workspace file management and data tier settings. |---|---|---|---|---| | `file` | `Path` | `.code-workspace` | `DEVOPS_CLI_WORKSPACE_FILE` | - | +## Grafana Configuration (`grafana`) + +Grafana endpoint, authentication, and service addressing settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `url` | `Union` | - | `DEVOPS_CLI_GRAFANA_URL` | - | + +## Prometheus Configuration (`prometheus`) + +Prometheus query endpoint, authentication, and service addressing settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `url` | `Union` | - | `DEVOPS_CLI_PROMETHEUS_URL` | - | + +## Argo CD Configuration (`argocd`) + +Argo CD server endpoint, authentication, TLS, and service addressing settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `url` | `Union` | - | `DEVOPS_CLI_ARGOCD_URL` | - | + +## Qdrant Vector Store (`qdrant`) + +The vector store that RAG searches query and indexing writes to. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `url` | `Union` | `http://localhost:6333` | `DEVOPS_CLI_QDRANT_URL` | - | +| `collection_prefix` | `str` | `devops` | `DEVOPS_CLI_QDRANT_COLLECTION_PREFIX` | - | +| `api_key` | `Union` | - | `DEVOPS_CLI_QDRANT_API_KEY` | - | +| `timeout` | `float` | `300.0` | `DEVOPS_CLI_QDRANT_TIMEOUT` | Seconds each Qdrant request waits per attempt: RAG searches, and indexing's upserts and deletes, which share the client | + +## Valkey Configuration (`valkey`) + +Valkey caching endpoint, authentication, TLS, and service addressing settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `host` | `str` | `localhost:6379` | `DEVOPS_CLI_VALKEY_HOST` | - | +| `port` | `int` | `6379` | `DEVOPS_CLI_VALKEY_PORT` | - | +| `url` | `Union` | - | - | - | +| `password` | `Union` | - | `DEVOPS_CLI_VALKEY_PASSWORD` | - | +| `db` | `int` | `0` | `DEVOPS_CLI_VALKEY_DB` | - | +| `timeout` | `float` | `2.0` | `DEVOPS_CLI_VALKEY_TIMEOUT` | - | +| `threat_intel_ttl` | `int` | `86400` | - | - | + +## Shared Run Index (`runs`) + +PostgreSQL connection settings for the shared AI run index. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `index_url` | `Union` | - | `DEVOPS_CLI_RUNS_INDEX_URL` | - | + +## Tempo Configuration (`tempo`) + +Grafana Tempo distributed tracing query endpoint and service addressing settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `url` | `Union` | `http://localhost:3200` | - | - | + +## Pyroscope Configuration (`pyroscope`) + +Grafana Pyroscope continuous profiling endpoint and service addressing settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `url` | `Union` | `http://localhost:4040` | - | - | + ## Telemetry & Metrics (`telemetry`) -OpenTelemetry distributed tracing and Prometheus metric export settings. +OpenTelemetry export and Logfire settings. | Option | Type | Default | Environment Variable | Description | |---|---|---|---|---| @@ -53,7 +134,7 @@ OpenTelemetry distributed tracing and Prometheus metric export settings. ## Kubernetes Configuration (`k8s`) -Kubernetes cluster connection, Minikube, Helm, and Kustomize settings. +Kubernetes context, ingress domain, and service addressing settings. | Option | Type | Default | Environment Variable | Description | |---|---|---|---|---| @@ -62,6 +143,27 @@ Kubernetes cluster connection, Minikube, Helm, and Kustomize settings. | `addressing` | `Union` | - | - | Default addressing mode for cluster services: nodeport, proxy, or fqdn. | | `github_account` | `Union` | - | `DEVOPS_CLI_K8S_GITHUB_ACCOUNT` | Login of the machine account whose gh token `devops k8s push-secrets` writes to the cluster as GH_TOKEN; `--github-account` overrides it | +## Cloudflare Configuration (`cloudflare`) + +Cloudflare API token and zone settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `domain` | `Union` | - | `DEVOPS_CLI_CLOUDFLARE_DOMAIN` | Root or zone domain name managed in Cloudflare (e.g. example.com) | +| `tunnel` | `Union` | - | `DEVOPS_CLI_CLOUDFLARE_TUNNEL` | Cloudflare tunnel name or identifier (e.g. homelab) | +| `account_id` | `Union` | - | `DEVOPS_CLI_CLOUDFLARE_ACCOUNT_ID` | Cloudflare Account ID | +| `zone_id` | `Union` | - | `DEVOPS_CLI_CLOUDFLARE_ZONE_ID` | Cloudflare Zone ID | +| `public_ip_bypass` | `Union` | - | - | Homelab public IP address or CIDR block permitted to bypass Cloudflare Access authentication | +| `access` | `CloudflareAccessConfig` | `enabled=False allowed_emails=[] idp='google' bypass_ips=[] public_ip_bypass=None` | - | Cloudflare Zero Trust Access application and policy configuration | + +## Sandbox Configuration (`sandbox`) + +Isolated container sandbox runtime, resource limits, and network policy settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `exclude_home_dir` | `bool` | `True` | - | Exclude user home directory entirely from sandbox access (/home/**/* and ~/**/*) | + ## AI & LLM Configuration (`ai`) AI code review, multi-agent pipelines, RAG semantic search, and embeddings. @@ -96,16 +198,13 @@ AI code review, multi-agent pipelines, RAG semantic search, and embeddings. | `durable` | `AIDurableConfig` | `engine='sqlite' store_path=PosixPath('.data/durable_runs.db') task_queue='devops-cli-tasks' workflow_id_prefix='devops-run-'` | - | - | | `task_name` | `Union` | - | - | - | -## Qdrant Vector Store (`qdrant`) +## Open WebUI Configuration (`open_webui`) -The vector store that RAG searches query and indexing writes to. +Open WebUI endpoint, authentication, and service addressing settings. | Option | Type | Default | Environment Variable | Description | |---|---|---|---|---| -| `url` | `Union` | `http://localhost:6333` | `DEVOPS_CLI_QDRANT_URL` | - | -| `collection_prefix` | `str` | `devops` | `DEVOPS_CLI_QDRANT_COLLECTION_PREFIX` | - | -| `api_key` | `Union` | - | `DEVOPS_CLI_QDRANT_API_KEY` | - | -| `timeout` | `float` | `300.0` | `DEVOPS_CLI_QDRANT_TIMEOUT` | Seconds each Qdrant request waits per attempt: RAG searches, and indexing's upserts and deletes, which share the client | +| `url` | `Union` | - | - | - | ## Data Storage Tier (`data`) @@ -126,3 +225,30 @@ Local artifact caches, review findings, session histories, and log paths. | `tls_dir` | `Path` | `.data/tls` | `DEVOPS_CLI_DATA_TLS_DIR` | - | | `audit_log_path` | `Path` | `.data/logs/audit.jsonl` | `DEVOPS_CLI_DATA_AUDIT_LOG_PATH` | - | | `feedback_dataset_path` | `Path` | `.data/feedback_dataset.jsonl` | `DEVOPS_CLI_DATA_FEEDBACK_DATASET_PATH` | - | + +## Service Configuration (`service`) + +In-cluster webhook receiver and background job runner settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `repos` | `list` | `[]` | `DEVOPS_CLI_SERVICE_REPOS` | - | +| `machine_account` | `Union` | - | `DEVOPS_CLI_SERVICE_MACHINE_ACCOUNT` | - | +| `poll_interval_seconds` | `int` | `300` | `DEVOPS_CLI_SERVICE_POLL_INTERVAL_SECONDS` | - | +| `drain_timeout_seconds` | `int` | `120` | `DEVOPS_CLI_SERVICE_DRAIN_TIMEOUT_SECONDS` | - | + +## Tavily Search Configuration (`tavily`) + +Tavily web search API authentication settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `api_key` | `Union` | - | `DEVOPS_CLI_TAVILY_API_KEY` | - | + +## Top-Level Settings + +Top-level workstation and environment settings. + +| Option | Type | Default | Environment Variable | Description | +|---|---|---|---|---| +| `domain` | `Union` | - | - | Default domain name for the environment or workstation | diff --git a/docs/ERRORS.md b/docs/ERRORS.md index f0b04d0eec..c50da6d871 100644 --- a/docs/ERRORS.md +++ b/docs/ERRORS.md @@ -19,6 +19,8 @@ and domain categorization for all exceptions inheriting from `DevOpsCLIError`. An error code may be shared by a base class and its subclasses; the exception column names the class each row describes. One code never maps to two exit statuses. +The Exit Code column is the exception's `exit_code` attribute. Only `devops cloudflare`, `devops valkey` and `devops sandbox` exit with it today; other commands exit 1 when one of these exceptions escapes. + | Exception | Error Code | Exit Code | Domain | Description | |---|---|---|---|---| | `AIClientError` | `LLM_INFERENCE_ERROR` | `10` | Devops_cli.ai.client.models | Raised when an AI provider request fails with a user-actionable message. | @@ -32,7 +34,7 @@ names the class each row describes. One code never maps to two exit statuses. | `CallDeferred` | `CALL_DEFERRED` | `18` | Ai | Raised by a tool when execution is deferred to an external worker or async system. | | `CapabilityDegradationError` | `CAPABILITY_DEGRADATION` | `1` | Ai | Raised when a fallback or failover model breaches minimum capability tier requirements. | | `ChaosExecutionError` | `CHAOS_EXECUTION_ERROR` | `1` | K8s | Raised when chaos engineering injection or validation fails. | -| `ChecksumMismatchError` | `ChecksumMismatchError` | `1` | Tools | Raised when downloaded tool archive SHA-256 does not match expected checksum. | +| `ChecksumMismatchError` | `CHECKSUM_MISMATCH` | `1` | Tools | Raised when downloaded tool archive SHA-256 does not match expected checksum. | | `CloudflareAPIError` | `CLOUDFLARE_API_ERROR` | `1` | Cloudflare | Raised when a Cloudflare API call returns an error response. | | `CloudflareAuthError` | `CLOUDFLARE_AUTH_ERROR` | `1` | Cloudflare | Raised when Cloudflare authentication or token verification fails. | | `CloudflareError` | `CLOUDFLARE_ERROR` | `1` | Cloudflare | Base exception for Cloudflare domain errors. | @@ -80,6 +82,7 @@ names the class each row describes. One code never maps to two exit statuses. | `LibraryIngestionError` | `LIBRARY_INGESTION_ERROR` | `1` | Ai | Base exception for package introspection and library ingestion errors. | | `LibraryNotFoundError` | `LIBRARY_NOT_FOUND_ERROR` | `1` | Ai | Raised when target package cannot be imported or found in the environment. | | `LogfireConfigurationError` | `LOGFIRE_CONFIG_ERROR` | `1` | Telemetry | Raised when Logfire configuration fails or credentials cannot be retrieved. | +| `MemoryOperationConflictError` | `HARNESS_EXECUTION_ERROR` | `1` | Devops_cli.ai.harness.memory | Raised when an optimistic concurrency conflict or duplicate operation occurs in memory store. | | `MemoryProfilerError` | `PROFILER_ERROR` | `1` | Devops_cli.telemetry.memory_profiler | Domain exception raised when memory profiling target resolution or execution fails. | | `ModelAPIError` | `MODEL_API_ERROR` | `22` | Ai | Raised when a model provider API request fails. | | `ModelBundleError` | `MODEL_BUNDLE_ERROR` | `1` | Ai | Raised when an AI model bundle cannot be located, resolved, or loaded. | @@ -110,7 +113,7 @@ names the class each row describes. One code never maps to two exit statuses. | `SandboxNotFoundError` | `SANDBOX_NOT_FOUND_ERROR` | `1` | Sandbox | Raised when requested sandbox instance or container cannot be found. | | `SandboxPortAllocationError` | `SANDBOX_PORT_ALLOCATION_ERROR` | `1` | Sandbox | Raised when host port allocation encounters collisions or range exhaustion. | | `SandboxValidationError` | `SANDBOX_VALIDATION_ERROR` | `1` | Sandbox | Raised when sandbox configuration or directory mount paths violate security boundaries. | -| `SecretExposureError` | `SecretExposureError` | `1` | Security | Raised when an unmasked credential or private key is detected in uncommitted diffs. | +| `SecretExposureError` | `SECRET_EXPOSURE_DETECTED` | `4` | Security | Raised when an unmasked credential or private key is detected in uncommitted diffs. | | `SecurityError` | `SECURITY_ERROR` | `1` | Security | Base exception for all security, policy, and egress violations. | | `ServiceAddressError` | `K8S_ERROR` | `1` | Devops_cli.k8s.service_proxy | Raised when a cluster service address cannot be resolved. | | `ServiceNotReachableError` | `DEVOPS_CLI_ERROR` | `1` | Devops_cli.k8s.node_port | A service cannot be reached from outside the cluster. | @@ -121,7 +124,7 @@ names the class each row describes. One code never maps to two exit statuses. | `SuspendedResponseExpired` | `SUSPENDED_RESPONSE_EXPIRED` | `28` | Ai | Raised when resuming a suspended response whose server-side job is no longer available. | | `TelemetryError` | `TELEMETRY_ERROR` | `1` | Telemetry | Base exception for telemetry, tracing, and metric collection errors. | | `TemplateRenderError` | `VALIDATION_ERROR` | `1` | Devops_cli.core.templating | Raised when a template cannot be rendered into valid output. | -| `ToolDownloadError` | `ToolDownloadError` | `1` | Tools | Raised when an external tool download fails or is rejected. | +| `ToolDownloadError` | `TOOL_DOWNLOAD_ERROR` | `1` | Tools | Raised when an external tool download fails or is rejected. | | `ToolExecutionError` | `TOOL_EXECUTION_ERROR` | `1` | Tools | Base exception for external developer tool and binary execution failures. | | `ToolFailed` | `TOOL_FAILED` | `16` | Ai | Raised when a tool encounters an unrecoverable runtime failure without requesting model retry. | | `TraceValidationError` | `VALIDATION_ERROR` | `1` | Devops_cli.telemetry.context | Raised when trace metadata or flags fail validation. | diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md index 4dea6f8e4a..d5d39501cd 100644 --- a/docs/MCP_TOOLS.md +++ b/docs/MCP_TOOLS.md @@ -493,7 +493,7 @@ Run devops-cli complete quality gate or an individual check in check-only mode w | Parameter | Type | Required | Default | Description | |---|---|---|---|---| -| `check` | `string` | No | `all` | - | +| `check` | `string (all, test, lint, format, typecheck, audit, security, actionlint, docs, uv-check, lockfile, outdated, devcontainer)` | No | `all` | - | ### `config_audit_keys` @@ -525,14 +525,14 @@ Execute command inside an isolated Docker container sandbox. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| -| `command` | `array` | Yes | - | - | +| `command` | `array[string]` | Yes | - | - | | `image` | `string` | No | `python:3.14-slim` | - | | `workspace` | `string` | No | `.` | - | | `memory` | `string` | No | `2g` | - | | `network` | `string` | No | `isolated` | - | | `network_mode` | `string` | No | - | - | -| `public_whitelist` | `array` | No | - | - | -| `local_whitelist` | `array` | No | - | - | +| `public_whitelist` | `array[string]` | No | - | - | +| `local_whitelist` | `array[string]` | No | - | - | | `read_only` | `boolean` | No | `False` | - | ### `docker_sign` @@ -547,7 +547,7 @@ Sign a container image using Sigstore Cosign (keyless or keyed). | `key` | `string` | No | - | - | | `keyless` | `boolean` | No | `True` | - | | `oidc_token` | `string` | No | - | - | -| `annotations` | `array` | No | - | - | +| `annotations` | `array[string]` | No | - | - | | `upload` | `boolean` | No | `True` | - | | `dry_run` | `boolean` | No | `False` | - | @@ -771,7 +771,7 @@ remain and fails with exit status 1. Reconcile adds no card. |---|---|---|---|---| | `project_number` | `integer` | No | - | - | | `repo` | `string` | No | - | - | -| `mode` | `string` | No | `plan` | - | +| `mode` | `string (dry-run, plan, write)` | No | `plan` | - | ### `gh_project_status` @@ -1358,7 +1358,7 @@ and returns the requests a run makes. A person or the service runs |---|---|---|---|---| | `repo` | `string` | No | - | - | | `ref` | `string` | No | - | - | -| `mode` | `string` | No | `plan` | - | +| `mode` | `string (dry-run, plan)` | No | `plan` | - | ### `roadmap_intake` @@ -1377,12 +1377,12 @@ the tool reads no file of the caller's choosing. |---|---|---|---|---| | `repo` | `string` | No | - | - | | `ref` | `string` | No | - | - | -| `issues` | `array` | No | - | - | +| `issues` | `array[integer]` | No | - | - | | `title` | `string` | No | - | - | | `body` | `string` | No | - | - | | `source` | `string` | No | - | - | -| `borrow_reason` | `string` | No | - | - | -| `mode` | `string` | No | `plan` | - | +| `borrow_reason` | `string (split, follow-up)` | No | - | - | +| `mode` | `string (dry-run, plan, confirm)` | No | `plan` | - | ### `roadmap_migrate` @@ -1398,7 +1398,7 @@ person reviews the plan and runs `devops roadmap migrate --confirm`. |---|---|---|---|---| | `repo` | `string` | No | - | - | | `ref` | `string` | No | - | - | -| `mode` | `string` | No | `plan` | - | +| `mode` | `string (dry-run, plan)` | No | `plan` | - | ### `roadmap_refine` @@ -1431,7 +1431,7 @@ requests a run makes; `mode="write"` writes the file. |---|---|---|---|---| | `repo` | `string` | No | - | - | | `ref` | `string` | No | - | - | -| `mode` | `string` | No | `plan` | - | +| `mode` | `string (dry-run, plan, write)` | No | `plan` | - | ### `roadmap_reprioritize` @@ -1448,7 +1448,7 @@ run makes; `mode="confirm"` makes the changes. |---|---|---|---|---| | `repo` | `string` | No | - | - | | `ref` | `string` | No | - | - | -| `mode` | `string` | No | `plan` | - | +| `mode` | `string (dry-run, plan, confirm)` | No | `plan` | - | ### `roadmap_run` @@ -1470,16 +1470,16 @@ Deploy an isolated workload container sandbox with security containment and port |---|---|---|---|---| | `image` | `string` | No | `python:3.14-slim` | - | | `name` | `string` | No | - | - | -| `ports` | `array` | No | - | - | +| `ports` | `array[integer]` | No | - | - | | `workspace` | `string` | No | `.` | - | | `memory` | `string` | No | `2g` | - | | `cpus` | `number` | No | `2.0` | - | | `network` | `string` | No | `isolated` | - | | `network_mode` | `string` | No | - | - | -| `public_whitelist` | `array` | No | - | - | -| `local_whitelist` | `array` | No | - | - | +| `public_whitelist` | `array[string]` | No | - | - | +| `local_whitelist` | `array[string]` | No | - | - | | `read_only` | `boolean` | No | `True` | - | -| `command` | `array` | No | - | - | +| `command` | `array[string]` | No | - | - | ### `sandbox_exec` @@ -1490,7 +1490,7 @@ Execute a command inside an active sandbox container. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `instance_id` | `string` | Yes | - | - | -| `command` | `array` | Yes | - | - | +| `command` | `array[string]` | Yes | - | - | | `workdir` | `string` | No | - | - | ### `sandbox_network_policy` @@ -1508,8 +1508,8 @@ in the sandbox_namespace, public_whitelist and local_whitelist modes. | `network_mode` | `string` | No | `isolated` | - | | `name` | `string` | No | `app-sandbox` | - | | `namespace` | `string` | No | `sandbox` | - | -| `public_whitelist` | `array` | No | - | - | -| `local_whitelist` | `array` | No | - | - | +| `public_whitelist` | `array[string]` | No | - | - | +| `local_whitelist` | `array[string]` | No | - | - | | `allow_collector` | `boolean` | No | `False` | - | ### `sandbox_status` @@ -1867,7 +1867,7 @@ Store secret key-value pairs in HashiCorp Vault KV-v2 engine. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `path` | `string` | Yes | - | - | -| `key_values` | `array` | Yes | - | - | +| `key_values` | `array[string]` | Yes | - | - | ### `vault_status` @@ -1888,7 +1888,7 @@ Synchronize secrets from HashiCorp Vault into the local OS Keyring. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `path` | `string` | Yes | - | - | -| `keys` | `array` | No | - | - | +| `keys` | `array[string]` | No | - | - | ### `workspace_list` diff --git a/docs/agent/tasks/task-854-reference-docs-fail-closed.md b/docs/agent/tasks/task-854-reference-docs-fail-closed.md new file mode 100644 index 0000000000..fbc290ea6e --- /dev/null +++ b/docs/agent/tasks/task-854-reference-docs-fail-closed.md @@ -0,0 +1,15 @@ +# Task #854: Reference Docs Fail Closed and Describe the Real Surface + +**Issue**: [#854](https://github.com/dan-petty/devops-cli/issues/854) +**Status**: Done +**Scope**: `src/devops_cli/docs/generator.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/config/settings.py`, `docs/`, `tests/test_docs.py` +**Feasibility**: Verified against `src/devops_cli/docs/generator.py` (`_introspect_single_group`, `_fetch_mcp_tools`, `_extract_mcp_prop_type`, `generate_configuration_docs`, `generate_error_catalog_docs`), `src/devops_cli/config/settings.py` (`Settings.model_fields` and `_find_project_config_path`), and `config.example.yaml`. + +## Checklist +- [x] Remove catch-and-continue fallbacks in `DocGenerator._introspect_single_group`, `DocGenerator._fetch_mcp_tools`, and `DocGenerator._import_all_exception_modules` so introspection or import failures raise `RuntimeError` naming the module and stating that a missing optional dependency now fails the docs stage, by design. +- [x] Preserve group-callback options and usage on `CommandGroupDoc` and render them in `docs/commands/.md` and `docs/CLI_REFERENCE.md` (`devops ci` lists `--check`, `--only`, and `--skip`; `devops review` lists `--explain`). +- [x] Render MCP array item types (`array[]`) and enum values (` (, , ...)`) in `_extract_mcp_prop_type` and `docs/MCP_TOOLS.md`. +- [x] Move project configuration file candidates to `CONST_PROJECT_CONFIG_CANDIDATES` in `src/devops_cli/config/constants.py`, use it in `_find_project_config_path` and `DocGenerator.generate_configuration_docs`, and iterate over `Settings.model_fields` in `generate_configuration_docs`. +- [x] Import all `devops_cli.exceptions.*` and domain exception modules in `DocGenerator.generate_error_catalog_docs`, instantiate each `DevOpsCLIError` subclass with its required constructor arguments so `ChecksumMismatchError`, `SecretExposureError`, `ToolDownloadError`, and `MemoryOperationConflictError` render their real error and exit codes, and add `CONST_EXIT_USAGE` and `CONST_EXIT_CANCELLED` to `src/devops_cli/config/constants.py`. +- [x] Add unit tests in `tests/test_docs.py` covering fail-closed group and MCP introspection, group-callback options, MCP array/enum parameter types, `CONFIGURATION.md` and `ERRORS.md` accuracy, and walking `config.example.yaml` against `Settings`. +- [x] Regenerate all reference documentation via `uv run devops docs generate --sync-readme` and verify `uv run devops docs check`. diff --git a/docs/commands/ai.md b/docs/commands/ai.md index 12db81e7d3..33323d78f8 100644 --- a/docs/commands/ai.md +++ b/docs/commands/ai.md @@ -2,6 +2,16 @@ Configure, test, chat, analyze, and review codebases (Ollama, Claude, Copilot). +```bash +devops ai [OPTIONS] COMMAND [ARGS]... +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--explain`, `-e` | `boolean` | - | Explain AI agent workflows, FastMCP tools, RAG terminology, and metrics. | + ## Commands ## `devops ai config` diff --git a/docs/commands/ci.md b/docs/commands/ci.md index cddb28b1cc..0b93704cf0 100644 --- a/docs/commands/ci.md +++ b/docs/commands/ci.md @@ -2,6 +2,22 @@ Run tests, linting, formatting, and type-checks. +```bash +devops ci [OPTIONS] COMMAND [ARGS]... +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--fix` / `--no-fix` | `boolean` | `True` | Auto-fix lint/format before reporting status. | +| `--check` | `boolean` | - | Run in check-only mode without automatically applying formatting or lint fixes. | +| `--cache` / `--no-cache` | `boolean` | `True` | Reuse a cached verdict when the codebase is unchanged. Results are recorded either way. | +| `--force`, `-f` | `boolean` | - | Bypass CI execution cache and force re-execution of all quality gates. | +| `--only` | `string` | - | Run only the specified check names (comma-separated or repeated). | +| `--skip` | `string` | - | Skip the specified check names (comma-separated or repeated). | +| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | + ## Commands ## `devops ci test` diff --git a/docs/commands/install-tools.md b/docs/commands/install-tools.md index d541c6f620..3f3be7a146 100644 --- a/docs/commands/install-tools.md +++ b/docs/commands/install-tools.md @@ -2,6 +2,19 @@ Install and manage DevOps tool binaries. +```bash +devops install-tools [OPTIONS] COMMAND [ARGS]... +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--tool`, `-t` | `string` | - | Install a specific tool. | +| `--target-dir`, `-d` | `path` | `~/.local/bin` | Target directory path for operation. | +| `--only-missing` | `boolean` | - | Only install tools that are not linked at their locked version. | +| `--check` | `boolean` | - | Install nothing: report each tool not linked at its locked version, and exit 1 if any. | + ## Commands ## `devops install-tools status` diff --git a/docs/commands/review.md b/docs/commands/review.md index 004f980de5..79d32c1793 100644 --- a/docs/commands/review.md +++ b/docs/commands/review.md @@ -2,6 +2,16 @@ AI-powered multi-persona code review and security audits. +```bash +devops review [OPTIONS] COMMAND [ARGS]... +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--explain`, `-e` | `boolean` | - | Explain code review personas, severity levels, and terminology. | + ## Commands ## `devops review path` diff --git a/docs/commands/scan.md b/docs/commands/scan.md index 61fb7eb39f..1177ac8fbd 100644 --- a/docs/commands/scan.md +++ b/docs/commands/scan.md @@ -2,6 +2,17 @@ Security scanner suite: Trivy, Gitleaks, Semgrep, Checkov, Kubeconform. +```bash +devops scan [OPTIONS] COMMAND [ARGS]... +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | +| `--json` | `boolean` | - | Output findings or metrics as JSON. | + ## Commands ## `devops scan trivy` diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index ab9821a714..4c0d4bc83d 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -24,6 +24,117 @@ # secret (`require_persistent_keyring`). CONST_KEYRING_UNLOCK_PROBE_KEY = "keyring-unlock-probe" CONST_PROJECT_CONFIG_FILENAME = "config.yaml" +CONST_PROJECT_CONFIG_CANDIDATES: Final[tuple[str, ...]] = ( + CONST_PROJECT_CONFIG_FILENAME, + f".devcontainer/{CONST_PROJECT_CONFIG_FILENAME}", + f".devops/{CONST_PROJECT_CONFIG_FILENAME}", + ".devops.yaml", + ".devcontainer/.devops.yaml", +) +CONST_SETTINGS_SECTION_METADATA: Final[dict[str, tuple[str, str]]] = { + "github": ( + "GitHub Configuration (`github`)", + "GitHub authentication, default owner, and repository settings.", + ), + "ssh": ( + "SSH Configuration (`ssh`)", + "SSH key generation, rotation, signing, and GitHub registration settings.", + ), + "repos": ( + "Repositories Configuration (`repos`)", + "Multi-repository workspace discovery, cloning, and sync settings.", + ), + "workspace": ( + "Workspace Configuration (`workspace`)", + "Multi-root VS Code workspace file management and data tier settings.", + ), + "grafana": ( + "Grafana Configuration (`grafana`)", + "Grafana endpoint, authentication, and service addressing settings.", + ), + "prometheus": ( + "Prometheus Configuration (`prometheus`)", + "Prometheus query endpoint, authentication, and service addressing settings.", + ), + "argocd": ( + "Argo CD Configuration (`argocd`)", + "Argo CD server endpoint, authentication, TLS, and service addressing settings.", + ), + "qdrant": ( + "Qdrant Vector Store (`qdrant`)", + "The vector store that RAG searches query and indexing writes to.", + ), + "valkey": ( + "Valkey Configuration (`valkey`)", + "Valkey caching endpoint, authentication, TLS, and service addressing settings.", + ), + "runs": ( + "Shared Run Index (`runs`)", + "PostgreSQL connection settings for the shared AI run index.", + ), + "tempo": ( + "Tempo Configuration (`tempo`)", + "Grafana Tempo distributed tracing query endpoint and service addressing settings.", + ), + "pyroscope": ( + "Pyroscope Configuration (`pyroscope`)", + "Grafana Pyroscope continuous profiling endpoint and service addressing settings.", + ), + "telemetry": ( + "Telemetry & Metrics (`telemetry`)", + "OpenTelemetry export and Logfire settings.", + ), + "k8s": ( + "Kubernetes Configuration (`k8s`)", + "Kubernetes context, ingress domain, and service addressing settings.", + ), + "cloudflare": ( + "Cloudflare Configuration (`cloudflare`)", + "Cloudflare API token and zone settings.", + ), + "sandbox": ( + "Sandbox Configuration (`sandbox`)", + "Isolated container sandbox runtime, resource limits, and network policy settings.", + ), + "ai": ( + "AI & LLM Configuration (`ai`)", + "AI code review, multi-agent pipelines, RAG semantic search, and embeddings.", + ), + "open_webui": ( + "Open WebUI Configuration (`open_webui`)", + "Open WebUI endpoint, authentication, and service addressing settings.", + ), + "data": ( + "Data Storage Tier (`data`)", + "Local artifact caches, review findings, session histories, and log paths.", + ), + "service": ( + "Service Configuration (`service`)", + "In-cluster webhook receiver and background job runner settings.", + ), + "tavily": ( + "Tavily Search Configuration (`tavily`)", + "Tavily web search API authentication settings.", + ), +} +CONST_DOMAIN_EXCEPTION_MODULES: Final[tuple[str, ...]] = ( + "devops_cli.ai.agents.spend", + "devops_cli.ai.agents.testing", + "devops_cli.ai.client.models", + "devops_cli.ai.gateway_tune", + "devops_cli.ai.harness.memory", + "devops_cli.ai.pool_load", + "devops_cli.ai.rag.embeddings", + "devops_cli.ai.rag.qdrant", + "devops_cli.ai.run_store", + "devops_cli.core.templating", + "devops_cli.http.client", + "devops_cli.k8s.node_port", + "devops_cli.k8s.service_proxy", + "devops_cli.review.state", + "devops_cli.telemetry.context", + "devops_cli.telemetry.memory_profiler", +) CONST_PROJECT_CONFIG_ENV = "DEVOPS_CLI_CONFIG" # absolute path overrides CWD lookup # A configuration file is only eligible for caching once it has been still for this # long. The kernel stamps files from a coarse clock, so a file rewritten moments after @@ -1056,9 +1167,11 @@ CONST_EXIT_SUCCESS: int = 0 CONST_EXIT_FAILURE: int = 1 +CONST_EXIT_USAGE: int = 2 CONST_EXIT_ERROR_INFERENCE: int = 10 # The status the subprocess runners report when the program is not on PATH, as POSIX shells do. CONST_EXIT_COMMAND_NOT_FOUND: int = 127 +CONST_EXIT_CANCELLED: int = 130 CONST_MSG_KEYRING_UNAVAILABLE = "OS Keyring service is unavailable; run in headless CI mode" CONST_MSG_BRANCH_INVALID = "Branch name is invalid" diff --git a/src/devops_cli/config/settings.py b/src/devops_cli/config/settings.py index 239b5e8075..c3f028c8ee 100644 --- a/src/devops_cli/config/settings.py +++ b/src/devops_cli/config/settings.py @@ -30,10 +30,10 @@ CONST_KEYRING_SERVICE as KEYRING_SERVICE, ) from devops_cli.config.constants import ( - CONST_PROJECT_CONFIG_ENV as PROJECT_CONFIG_ENV, + CONST_PROJECT_CONFIG_CANDIDATES as PROJECT_CONFIG_CANDIDATES, ) from devops_cli.config.constants import ( - CONST_PROJECT_CONFIG_FILENAME as PROJECT_CONFIG_FILENAME, + CONST_PROJECT_CONFIG_ENV as PROJECT_CONFIG_ENV, ) from devops_cli.config.defaults import ( DEFAULT_AI_CONTEXT_WINDOW, @@ -1101,16 +1101,9 @@ def _find_project_config_path(base_dir: Path | None = None) -> Path | None: if reads_untrusted_trees(): return None - candidate_names = ( - PROJECT_CONFIG_FILENAME, - f".devcontainer/{PROJECT_CONFIG_FILENAME}", - f".devops/{PROJECT_CONFIG_FILENAME}", - ".devops.yaml", - ".devcontainer/.devops.yaml", - ) start_dir = (base_dir or Path.cwd()).resolve() for d in (start_dir, *start_dir.parents): - candidate = _match_dir_candidate(d, candidate_names) + candidate = _match_dir_candidate(d, PROJECT_CONFIG_CANDIDATES) if candidate is not None: return candidate if (d / ".git").exists() or (d / ".devcontainer").exists(): diff --git a/src/devops_cli/docs/generator.py b/src/devops_cli/docs/generator.py index dcf769aacc..0ba7ab45ac 100644 --- a/src/devops_cli/docs/generator.py +++ b/src/devops_cli/docs/generator.py @@ -16,7 +16,10 @@ CONST_DOC_CREDENTIAL_NAME_WORD_PAIRS, CONST_DOC_CREDENTIAL_NAME_WORDS, CONST_DOC_CREDENTIAL_NAMING_WORD, + CONST_DOMAIN_EXCEPTION_MODULES, CONST_MARKDOWN_HEADING_LEVEL, + CONST_PROJECT_CONFIG_CANDIDATES, + CONST_SETTINGS_SECTION_METADATA, CONST_STANDARD_HTML_TAGS, ) from devops_cli.config.defaults import DEFAULT_OTEL_ENDPOINT @@ -120,6 +123,8 @@ class CommandGroupDoc(BaseModel): module_path: str summary: str description: str + usage: str = "" + params: list[ParamDoc] = Field(default_factory=list) commands: list[CommandDoc] = Field(default_factory=list) @@ -131,16 +136,27 @@ class MCPToolDoc(BaseModel): parameters: list[dict[str, Any]] = Field(default_factory=list) -def _extract_mcp_prop_type(prop_data: dict[str, Any]) -> str: - """Extract human-readable schema type from an MCP property schema, supporting anyOf/oneOf.""" - direct_type = prop_data.get("type") - if direct_type: - return str(direct_type) +def _select_non_null_mcp_variant(prop_data: dict[str, Any]) -> dict[str, Any]: + """Return the first non-null variant dict when a schema property uses anyOf/oneOf.""" variants = prop_data.get("anyOf") or prop_data.get("oneOf") or [] for sub in variants: - if isinstance(sub, dict) and sub.get("type") and sub.get("type") != "null": - return str(sub["type"]) - return "string" + if isinstance(sub, dict) and sub.get("type") != "null": + return sub + return prop_data + + +def _extract_mcp_prop_type(prop_data: dict[str, Any]) -> str: + """Extract human-readable schema type from an MCP property schema, including items and enums.""" + variant = _select_non_null_mcp_variant(prop_data) if not prop_data.get("type") else prop_data + base_type = str(variant.get("type") or "string") + items = variant.get("items") + if base_type == "array" and isinstance(items, dict): + return f"array[{_extract_mcp_prop_type(items)}]" + enum_values = variant.get("enum") + if isinstance(enum_values, list) and enum_values: + joined = ", ".join(str(v) for v in enum_values) + return f"{base_type} ({joined})" + return base_type def _parse_mcp_input_schema_parameters(input_schema: Any) -> list[dict[str, Any]]: @@ -364,6 +380,8 @@ def _introspect_leaf_or_group( module_path=module_path, summary=summary or doc.summary, description=doc.description or summary, + usage=doc.usage if doc.is_group else "", + params=doc.params if doc.is_group else [], commands=commands_list, ) @@ -379,13 +397,10 @@ def _introspect_single_group( return None return self._introspect_leaf_or_group(click_cmd, name, module_path, summary) except Exception as exc: - return CommandGroupDoc( - name=name, - module_path=module_path, - summary=summary, - description=f"Error introspecting module: {exc}", - commands=[], - ) + raise RuntimeError( + f"Failed to introspect command group '{name}' ({module_path}): {exc}. " + "A missing optional dependency now fails the docs stage, by design." + ) from exc def introspect_all_groups(self) -> list[CommandGroupDoc]: """Introspect all command groups declared in main._COMMAND_SPECS.""" @@ -429,8 +444,11 @@ async def _get_tools() -> list[MCPToolDoc]: finally: pool.shutdown(wait=False, cancel_futures=True) return asyncio.run(_get_tools()) - except Exception: - return [] + except Exception as exc: + raise RuntimeError( + f"Failed to introspect FastMCP tools (devops_cli.ai.mcp.server): {exc}. " + "A missing optional dependency now fails the docs stage, by design." + ) from exc def introspect_mcp_tools(self) -> list[MCPToolDoc]: """Collect all registered FastMCP tools.""" @@ -439,6 +457,54 @@ def introspect_mcp_tools(self) -> list[MCPToolDoc]: span.set_attributes({"tool_count": len(tools)}) return tools + @staticmethod + def _append_params_tables(params: list[ParamDoc], lines: list[str]) -> None: + """Append Arguments and Options markdown tables for a parameter list.""" + args = [p for p in params if p.kind == "argument"] + opts = [p for p in params if p.kind in ("option", "flag")] + + if args: + lines.extend( + [ + "**Arguments:**", + "", + "| Argument | Type | Required | Description |", + "|---|---|---|---|", + *( + f"| {f'`{a.flags[0]}`' if a.flags else f'`{a.name}`'} | " + f"`{a.type_name}` | {'Yes' if a.required else 'No'} | " + f"{a.description or '-'} |" + for a in args + ), + "", + ] + ) + + if opts: + lines.extend( + [ + "**Options:**", + "", + "| Option / Flag | Type | Default | Description |", + "|---|---|---|---|", + *( + f"| {_option_flags_cell(o)} | `{o.type_name}` | " + f"{f'`{o.default}`' if o.default is not None else '-'} | " + f"{o.description or '-'}{f' *(Env: `{o.envvar}`)*' if o.envvar else ''} |" + for o in opts + ), + "", + ] + ) + + def _append_group_callback_section(self, group: CommandGroupDoc, lines: list[str]) -> None: + """Append group-level usage and callback parameter tables when the group has options.""" + if not group.params: + return + if group.usage: + lines.extend(["```bash", group.usage, "```", ""]) + self._append_params_tables(group.params, lines) + def render_cli_reference_markdown(self, groups: list[CommandGroupDoc]) -> str: """Render complete CLI Reference documentation in Markdown format.""" lines: list[str] = [ @@ -454,29 +520,22 @@ def render_cli_reference_markdown(self, groups: list[CommandGroupDoc]) -> str: for group in groups: anchor = group.name.replace("_", "-") lines.append(f"- [`devops {group.name}`](#devops-{anchor}) — {group.summary}") - lines.append("") - lines.append("---") - lines.append("") + lines.extend(["", "---", ""]) for group in groups: - lines.append(f"## devops {group.name}") - lines.append("") - lines.append(f"{group.summary}") - lines.append("") + lines.extend([f"## devops {group.name}", "", f"{group.summary}", ""]) if group.description and group.description != group.summary: - lines.append(f"{group.description}") - lines.append("") + lines.extend([f"{group.description}", ""]) + self._append_group_callback_section(group, lines) if not group.commands: - lines.append("*No subcommands available.*") - lines.append("") + lines.extend(["*No subcommands available.*", ""]) continue for cmd in group.commands: self._render_command_markdown(cmd, lines, level=3) - lines.append("---") - lines.append("") + lines.extend(["---", ""]) return "\n".join(lines) @@ -488,52 +547,17 @@ def _render_command_markdown( ) -> None: """Render a single command or recursive subcommands into Markdown lines.""" heading = "#" * level - lines.append(f"{heading} `{cmd.full_path}`") - lines.append("") + lines.extend([f"{heading} `{cmd.full_path}`", ""]) if cmd.summary: - lines.append(f"**{cmd.summary}**") - lines.append("") + lines.extend([f"**{cmd.summary}**", ""]) if cmd.description and cmd.description != cmd.summary: - lines.append(f"{cmd.description}") - lines.append("") - - lines.append("```bash") - lines.append(cmd.usage) - lines.append("```") - lines.append("") + lines.extend([f"{cmd.description}", ""]) - args = [p for p in cmd.params if p.kind == "argument"] - opts = [p for p in cmd.params if p.kind in ("option", "flag")] + lines.extend(["```bash", cmd.usage, "```", ""]) + self._append_params_tables(cmd.params, lines) - if args: - lines.append("**Arguments:**") - lines.append("") - lines.append("| Argument | Type | Required | Description |") - lines.append("|---|---|---|---|") - for arg in args: - flag_str = f"`{arg.flags[0]}`" if arg.flags else f"`{arg.name}`" - req_str = "Yes" if arg.required else "No" - lines.append( - f"| {flag_str} | `{arg.type_name}` | {req_str} | {arg.description or '-'} |" - ) - lines.append("") - - if opts: - lines.append("**Options:**") - lines.append("") - lines.append("| Option / Flag | Type | Default | Description |") - lines.append("|---|---|---|---|") - for opt in opts: - flags_str = _option_flags_cell(opt) - default_str = f"`{opt.default}`" if opt.default is not None else "-" - env_str = f" *(Env: `{opt.envvar}`)*" if opt.envvar else "" - desc = f"{opt.description or '-'}{env_str}" - lines.append(f"| {flags_str} | `{opt.type_name}` | {default_str} | {desc} |") - lines.append("") - - if cmd.subcommands: - for sub in cmd.subcommands: - self._render_command_markdown(sub, lines, level=level + 1) + for sub in cmd.subcommands: + self._render_command_markdown(sub, lines, level=level + 1) def render_command_group_markdown(self, group: CommandGroupDoc) -> str: """Render documentation for a single command group.""" @@ -542,13 +566,12 @@ def render_command_group_markdown(self, group: CommandGroupDoc) -> str: "", f"{group.summary}", "", - "## Commands", - "", ] + self._append_group_callback_section(group, lines) + lines.extend(["## Commands", ""]) for cmd in group.commands: self._render_command_markdown(cmd, lines, level=2) - lines.append("---") - lines.append("") + lines.extend(["---", ""]) return "\n".join(lines) def render_env_vars_markdown(self, env_specs: list[EnvVarSpec]) -> str: @@ -740,11 +763,36 @@ def check_readme(self, readme_path: Path | None = None) -> tuple[bool, str | Non return False, f"Could not find Command Matrix table or markers in {target}" + def _format_settings_field_row( + self, + field_name: str, + field_info: Any, + def_val: Any, + opt_key: str, + option_to_env: dict[str, str], + ) -> str: + """Render a single configuration field row for CONFIGURATION.md.""" + env_var = option_to_env.get(opt_key, "-") + env_str = f"`{env_var}`" if env_var != "-" else "-" + type_ann = field_info.annotation + type_str = getattr(type_ann, "__name__", str(type_ann)).replace("pathlib.", "") + if "Optional[" in type_str: + type_str = type_str.replace("Optional[", "").rstrip("]") + def_str = f"`{def_val}`" if def_val is not None else "-" + if isinstance(def_val, Path): + def_str = f"`{_format_param_default_str(def_val, self.root_dir)}`" + desc = field_info.description or "-" + return f"| `{field_name}` | `{type_str}` | {def_str} | {env_str} | {desc} |" + def generate_configuration_docs(self) -> str: """Programmatically generate Markdown configuration reference from Settings schema.""" from devops_cli.config.env import OPTION_TO_ENV_VAR from devops_cli.config.settings import Settings + candidates_str = ( + ", ".join(f"`{c}`" for c in CONST_PROJECT_CONFIG_CANDIDATES[:-1]) + + f" or `{CONST_PROJECT_CONFIG_CANDIDATES[-1]}`" + ) lines: list[str] = [ "# DevOps CLI Configuration Reference", "", @@ -754,8 +802,7 @@ def generate_configuration_docs(self) -> str: "1. **CLI Flags & Arguments** (highest precedence)", "2. **Environment Variables** (`DEVOPS_CLI_*`)", "3. **Local Project Configuration** (the file `DEVOPS_CLI_CONFIG` names, else the " - "nearest `config.yaml`, `.devops/config.yaml` or `.devops.yaml` from the working " - "directory up to its repository root)", + f"nearest {candidates_str} from the working directory up to its repository root)", "4. **Global User Configuration** (`~/.config/devops-cli/config.yaml`)", "5. **System Defaults**", "", @@ -779,115 +826,117 @@ def generate_configuration_docs(self) -> str: "", ] - sections = [ - ( - "SSH Configuration (`ssh`)", - "ssh", - "SSH key generation, rotation, signing, and GitHub registration settings.", - ), - ( - "Repositories Configuration (`repos`)", - "repos", - "Multi-repository workspace discovery, cloning, and sync settings.", - ), - ( - "Workspace Configuration (`workspace`)", - "workspace", - "Multi-root VS Code workspace file management and data tier settings.", - ), - ( - "Telemetry & Metrics (`telemetry`)", - "telemetry", - "OpenTelemetry distributed tracing and Prometheus metric export settings.", - ), - ( - "Kubernetes Configuration (`k8s`)", - "k8s", - "Kubernetes cluster connection, Minikube, Helm, and Kustomize settings.", - ), - ( - "Security Scanner Configuration (`security`)", - "security", - "Security scanning engines, vulnerability audits, and policy enforcement.", - ), - ( - "AI & LLM Configuration (`ai`)", - "ai", - "AI code review, multi-agent pipelines, RAG semantic search, and embeddings.", - ), - ( - "Qdrant Vector Store (`qdrant`)", - "qdrant", - "The vector store that RAG searches query and indexing writes to.", - ), - ( - "Data Storage Tier (`data`)", - "data", - "Local artifact caches, review findings, session histories, and log paths.", - ), - ( - "OIDC & Authentication (`oidc`)", - "oidc", - "OpenID Connect authentication and identity token settings.", - ), - ] - settings = Settings() - for title, section_key, description in sections: - section_model = getattr(settings, section_key, None) - if section_model is None: + scalar_rows: list[str] = [] + for section_key, top_info in Settings.model_fields.items(): + section_val = getattr(settings, section_key, None) + if not isinstance(section_val, BaseModel): + scalar_rows.append( + self._format_settings_field_row( + section_key, top_info, section_val, section_key, OPTION_TO_ENV_VAR + ) + ) continue - lines.append(f"## {title}") - lines.append("") - lines.append(description) - lines.append("") - lines.append("| Option | Type | Default | Environment Variable | Description |") - lines.append("|---|---|---|---|---|") - - for field_name, field_info in section_model.__class__.model_fields.items(): - opt_key = f"{section_key}.{field_name}" - env_var = OPTION_TO_ENV_VAR.get(opt_key, "-") - env_str = f"`{env_var}`" if env_var != "-" else "-" - type_ann = field_info.annotation - type_str = getattr(type_ann, "__name__", str(type_ann)).replace("pathlib.", "") - if "Optional[" in type_str: - type_str = type_str.replace("Optional[", "").rstrip("]") - def_val = getattr(section_model, field_name, None) - def_str = f"`{def_val}`" if def_val is not None else "-" - if isinstance(def_val, Path): - def_str = f"`{_format_param_default_str(def_val, self.root_dir)}`" - desc = field_info.description or "-" - lines.append(f"| `{field_name}` | `{type_str}` | {def_str} | {env_str} | {desc} |") + title, description = CONST_SETTINGS_SECTION_METADATA.get( + section_key, + ( + f"{section_key.replace('_', ' ').title()} Configuration (`{section_key}`)", + top_info.description or f"{section_key} configuration settings.", + ), + ) + lines.extend( + [ + f"## {title}", + "", + description, + "", + "| Option | Type | Default | Environment Variable | Description |", + "|---|---|---|---|---|", + *( + self._format_settings_field_row( + field_name, + field_info, + getattr(section_val, field_name, None), + f"{section_key}.{field_name}", + OPTION_TO_ENV_VAR, + ) + for field_name, field_info in section_val.__class__.model_fields.items() + ), + "", + ] + ) - lines.append("") + if scalar_rows: + lines.extend( + [ + "## Top-Level Settings", + "", + "Top-level workstation and environment settings.", + "", + "| Option | Type | Default | Environment Variable | Description |", + "|---|---|---|---|---|", + *scalar_rows, + "", + ] + ) return "\n".join(lines) - def generate_error_catalog_docs(self) -> str: - """Programmatically generate Exit Code and Error Taxonomy catalog from DevOpsCLIError hierarchy.""" + @staticmethod + def _import_all_exception_modules() -> None: + """Import every module defining DevOpsCLIError subclasses, failing closed on error.""" import importlib + import pkgutil - from devops_cli.exceptions.base import DevOpsCLIError + import devops_cli.exceptions - exception_modules = [ - ("AI & LLM Subsystem", "devops_cli.exceptions.ai"), - ("Configuration Subsystem", "devops_cli.exceptions.config"), - ("Git Operations Subsystem", "devops_cli.exceptions.git"), - ("Kubernetes Subsystem", "devops_cli.exceptions.k8s"), - ("Network & Egress Subsystem", "devops_cli.exceptions.network"), - ("Security & Scanner Subsystem", "devops_cli.exceptions.security"), - ("SSH Key Management", "devops_cli.exceptions.ssh"), - ("Tool Execution Subsystem", "devops_cli.exceptions.tools"), - ("Input Validation Subsystem", "devops_cli.exceptions.validation"), - ("Core & MCP Subsystem", "devops_cli.exceptions.base"), + module_names = [ + *( + mod_name + for _, mod_name, _ in pkgutil.iter_modules( + devops_cli.exceptions.__path__, prefix="devops_cli.exceptions." + ) + ), + *CONST_DOMAIN_EXCEPTION_MODULES, ] - - for _, mod_name in exception_modules: + for mod_name in module_names: try: importlib.import_module(mod_name) - except Exception: - pass + except Exception as exc: + raise RuntimeError( + f"Failed to import exception module '{mod_name}': {exc}. " + "A missing optional dependency now fails the docs stage, by design." + ) from exc + + @staticmethod + def _instantiate_error_for_catalog(err_cls: type[Exception]) -> tuple[str, int]: + """Instantiate a DevOpsCLIError subclass with dummy required arguments to read its codes.""" + import inspect + + params = list(inspect.signature(err_cls).parameters.values()) + pos_args = [ + "error" + for p in params + if p.default is inspect.Parameter.empty + and p.kind + in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) + ] + kw_args = { + p.name: "error" + for p in params + if p.default is inspect.Parameter.empty and p.kind == inspect.Parameter.KEYWORD_ONLY + } + inst = err_cls(*pos_args, **kw_args) + return str(getattr(inst, "error_code", err_cls.__name__)), int( + getattr(inst, "exit_code", 1) + ) + + def generate_error_catalog_docs(self) -> str: + """Programmatically generate Exit Code and Error Taxonomy catalog from DevOpsCLIError hierarchy.""" + from devops_cli.exceptions.base import DevOpsCLIError + + self._import_all_exception_modules() lines: list[str] = [ "# DevOps CLI Exit Code & Error Catalog", @@ -911,30 +960,26 @@ def generate_error_catalog_docs(self) -> str: "An error code may be shared by a base class and its subclasses; the exception column", "names the class each row describes. One code never maps to two exit statuses.", "", + "The Exit Code column is the exception's `exit_code` attribute. Only `devops cloudflare`, " + "`devops valkey` and `devops sandbox` exit with it today; other commands exit 1 when one " + "of these exceptions escapes.", + "", "| Exception | Error Code | Exit Code | Domain | Description |", "|---|---|---|---|---|", ] - def get_all_subclasses(cls: type[DevOpsCLIError]) -> list[type[DevOpsCLIError]]: - subclasses: list[type[DevOpsCLIError]] = [] + def get_all_subclasses(cls: type[DevOpsCLIError]) -> set[type[DevOpsCLIError]]: + subclasses: set[type[DevOpsCLIError]] = set() for sub in cls.__subclasses__(): - subclasses.append(sub) - subclasses.extend(get_all_subclasses(sub)) + subclasses.add(sub) + subclasses.update(get_all_subclasses(sub)) return subclasses all_errs = sorted(get_all_subclasses(DevOpsCLIError), key=lambda c: c.__name__) for err_cls in all_errs: doc = (err_cls.__doc__ or "").strip().split("\n")[0] - # Instantiate dummy to get default error_code and exit_code if possible - try: - inst = err_cls("error message") - err_code = getattr(inst, "error_code", err_cls.__name__) - exit_code = getattr(inst, "exit_code", 1) - except Exception: - err_code = getattr(err_cls, "DEFAULT_ERROR_CODE", err_cls.__name__) - exit_code = getattr(err_cls, "DEFAULT_EXIT_CODE", 1) - + err_code, exit_code = self._instantiate_error_for_catalog(err_cls) domain = ( err_cls.__module__.replace("devops_cli.exceptions.", "") .replace("devops_cli.exceptions", "core") diff --git a/tests/fixtures/swallowed_failures_ceilings.json b/tests/fixtures/swallowed_failures_ceilings.json index 65f2a78093..5d977a8cb2 100644 --- a/tests/fixtures/swallowed_failures_ceilings.json +++ b/tests/fixtures/swallowed_failures_ceilings.json @@ -108,7 +108,6 @@ "src/devops_cli/crypto/tls_certificates.py": 1, "src/devops_cli/docker/engine.py": 5, "src/devops_cli/docker/sandbox.py": 2, - "src/devops_cli/docs/generator.py": 5, "src/devops_cli/git/operations.py": 8, "src/devops_cli/git/worktree.py": 4, "src/devops_cli/github/client.py": 3, diff --git a/tests/test_docs.py b/tests/test_docs.py index 43c2d64505..4d4b97b722 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -605,7 +605,7 @@ def test_doc_generator_knowledge_base_index(generator: DocGenerator) -> None: def test_parse_mcp_input_schema_parameters_with_anyof_array() -> None: - """Verify that optional array parameters using anyOf resolve to 'array' rather than falling back.""" + """Verify that MCP schema parameter parsing preserves array item types and enum values (#854).""" from devops_cli.docs.generator import _parse_mcp_input_schema_parameters schema = { @@ -620,13 +620,200 @@ def test_parse_mcp_input_schema_parameters_with_anyof_array() -> None: "default": None, "description": "Optional secret keys", }, + "mode": { + "type": "string", + "enum": ["dry-run", "plan", "write"], + "default": "plan", + "description": "Execution mode", + }, }, "required": ["path"], } params = _parse_mcp_input_schema_parameters(schema) - assert len(params) == 2 by_name = {p["name"]: p for p in params} - assert by_name["path"]["type"] == "string" - assert by_name["path"]["required"] is True - assert by_name["keys"]["type"] == "array" - assert by_name["keys"]["required"] is False + assert ( + len(params), + by_name["path"]["type"], + by_name["path"]["required"], + by_name["keys"]["type"], + by_name["keys"]["required"], + by_name["mode"]["type"], + ) == (3, "string", True, "array[string]", False, "string (dry-run, plan, write)") + + +def test_generate_all_docs_raises_on_group_import_failure( + generator: DocGenerator, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A forced import failure makes generate_all_docs raise and names the module (#854).""" + import devops_cli.docs.generator as gen_mod + + def _failing_loader(module_path: str) -> object: + raise ImportError(f"No module named 'missing_optional_dep' while loading {module_path}") + + monkeypatch.setattr(gen_mod, "module_click_command", _failing_loader) + with pytest.raises(RuntimeError) as exc_info: + generator.generate_all_docs(tmp_path) + msg = str(exc_info.value) + assert ( + "devops_cli.commands." in msg, + "missing optional dependency now fails the docs stage, by design" in msg, + ) == (True, True) + + +def test_introspect_mcp_tools_raises_on_listing_failure( + generator: DocGenerator, monkeypatch: pytest.MonkeyPatch +) -> None: + """A forced MCP listing failure makes MCP doc generation raise (#854).""" + import builtins + + real_import = builtins.__import__ + + def _failing_import( + name: str, + globals: dict[str, object] | None = None, + locals: dict[str, object] | None = None, + fromlist: tuple[str, ...] = (), + level: int = 0, + ) -> object: + if name == "devops_cli.ai.mcp.server": + raise ImportError("FastMCP dependency missing") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr(builtins, "__import__", _failing_import) + with pytest.raises(RuntimeError) as exc_info: + generator.introspect_mcp_tools() + assert "missing optional dependency now fails the docs stage, by design" in str(exc_info.value) + + +def test_group_callback_options_rendered_for_ci_and_review(generator: DocGenerator) -> None: + """Group-callback options on devops ci (--check, --only, --skip) and devops review (--explain) + are rendered in command group pages (#854).""" + pages = Path(__file__).resolve().parents[1] / "docs" / "commands" + ci_md = (pages / "ci.md").read_text(encoding="utf-8") + review_md = (pages / "review.md").read_text(encoding="utf-8") + ci_header_section = ci_md.split("## Commands", 1)[0] + review_header_section = review_md.split("## Commands", 1)[0] + assert ( + "| `--check` |" in ci_header_section, + "| `--only` |" in ci_header_section, + "| `--skip` |" in ci_header_section, + "| `--explain`, `-e` |" in review_header_section, + ) == (True, True, True, True) + + +def test_configuration_and_error_catalog_docs_describe_real_surface( + generator: DocGenerator, +) -> None: + """CONFIGURATION.md lists all project config candidates and Settings fields; ERRORS.md lists + all DevOpsCLIError subclasses with their real error_code and exit_code (#854).""" + from devops_cli.config.constants import ( + CONST_EXIT_CANCELLED, + CONST_EXIT_USAGE, + CONST_PROJECT_CONFIG_CANDIDATES, + ) + from devops_cli.config.settings import Settings + + config_md = generator.generate_configuration_docs() + errors_md = generator.generate_error_catalog_docs() + + assert ( + CONST_EXIT_USAGE, + CONST_EXIT_CANCELLED, + all(f"`{candidate}`" in config_md for candidate in CONST_PROJECT_CONFIG_CANDIDATES), + "Kubernetes context, ingress domain, and service addressing settings." in config_md, + "OpenTelemetry export and Logfire settings." in config_md, + all( + f"(`{field}`)" in config_md or f"| `{field}` |" in config_md + for field in Settings.model_fields + ), + "| `MemoryOperationConflictError` | `HARNESS_EXECUTION_ERROR` | `1` |" in errors_md, + "| `ChecksumMismatchError` | `CHECKSUM_MISMATCH` | `1` |" in errors_md, + "| `SecretExposureError` | `SECRET_EXPOSURE_DETECTED` | `4` |" in errors_md, + "| `ToolDownloadError` | `TOOL_DOWNLOAD_ERROR` | `1` |" in errors_md, + "Only `devops cloudflare`, `devops valkey` and `devops sandbox` exit with it today" + in errors_md, + ) == (2, 130, True, True, True, True, True, True, True, True, True) + + +def _unwrap_settings_model(annotation: object) -> type | None: + import types + from typing import get_args, get_origin + + from pydantic import BaseModel + + if isinstance(annotation, type) and issubclass(annotation, BaseModel): + return annotation + origin = get_origin(annotation) + if origin is types.UnionType or str(origin).endswith("Union"): + for arg in get_args(annotation): + resolved = _unwrap_settings_model(arg) + if resolved is not None: + return resolved + return None + + +def _field_names_and_aliases(field_name: str, info: object) -> list[str]: + from pydantic import AliasChoices + + keys = [field_name] + alias = getattr(info, "alias", None) + if isinstance(alias, str): + keys.append(alias) + val_alias = getattr(info, "validation_alias", None) + if isinstance(val_alias, str): + keys.append(val_alias) + elif isinstance(val_alias, AliasChoices): + keys.extend(c for c in val_alias.choices if isinstance(c, str)) + return keys + + +def _model_field_lookup(model_cls: type) -> dict[str, object]: + return { + key: info + for field_name, info in model_cls.model_fields.items() + for key in _field_names_and_aliases(field_name, info) + } + + +def _collect_unknown_settings_key_paths( + payload: dict[str, object], model_cls: type, prefix: str = "" +) -> list[str]: + lookup = _model_field_lookup(model_cls) + unknown: list[str] = [] + for key, val in payload.items(): + path = f"{prefix}.{key}" if prefix else key + info = lookup.get(key) + if info is None: + unknown.append(path) + continue + sub_model = _unwrap_settings_model(getattr(info, "annotation", None)) + if isinstance(val, dict) and sub_model is not None: + unknown.extend(_collect_unknown_settings_key_paths(val, sub_model, path)) + return unknown + + +def test_config_example_yaml_maps_to_settings_fields_and_validates() -> None: + """Every key path in config.example.yaml maps to a Settings field and validates; an unknown + key in a copy fails the check and names the key path (#854).""" + import copy + + import yaml + + from devops_cli.config.settings import Settings + + example_path = Path(__file__).resolve().parents[1] / "config.example.yaml" + raw = yaml.safe_load(example_path.read_text(encoding="utf-8")) + assert isinstance(raw, dict) + + unknown = _collect_unknown_settings_key_paths(raw, Settings) + validated = Settings.model_validate(raw) + + mutated = copy.deepcopy(raw) + mutated["ai"]["nonexistent_setting_key"] = True + unknown_mutated = _collect_unknown_settings_key_paths(mutated, Settings) + + assert ( + unknown, + isinstance(validated, Settings), + unknown_mutated, + ) == ([], True, ["ai.nonexistent_setting_key"])