diff --git a/CHANGELOG.md b/CHANGELOG.md index 6124f09579..0a2f0bafd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,9 +33,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - STATUS and READY match `kubectl get pods` wherever pods are listed: the dashboard, `devops dashboard --summary`, `devops k8s pods` and `--watch`. The Kubernetes tab's banner names the context, the Ready nodes and the unhealthy pods, or the context and the real error when it cannot connect (#686). - Namespace and text filters survive refreshes and keep the highlighted pod on screen. Logs follow a pod's default container, `c` cycles containers, a replaced log stream is closed, and `e` opens the pod's containers and recent events. The Minikube probe is gone (#686). +### Changed +- **MCP Tool `k8s_chaos` Previews by Default**: + - `experiment` is the positional argument, and a new `dry_run` parameter (default `true`) passes `--dry-run`, so the tool runs an experiment only when `dry_run` is false (#836). + ### Removed - **LightLLM Inference Backend (`devops_cli.ai`, `k8s/llm`)**: - Fully removed the unused `ghcr.io/modeltc/lightllm` inference backend, including `k8s/llm/lightllm/` manifests, `CONST_AI_BACKEND_LIGHTLLM`, `GatewayRouter.scale_lightllm()`, the `devops-cli-ai_lightllm_scale` MCP tool, and all associated CLI, configuration, and test references. The `devops ai gateway scale` command now exclusively targets the vLLM backend. +- **MCP Tools and Parameters With No Command Behind Them**: + - The `ai_architecture` tool, which called a nonexistent `devops analyze architecture`, and the parameters `repos_sync(all_repos)`, `k8s_audit(namespace)` and `k8s_chaos(action)`, which their commands never took (#836). ### Fixed - **Kubernetes Monitoring Stack Integration & Dashboard Metrics (`k8s/monitoring`)**: @@ -69,6 +75,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Tests Never Reach Port-Forwarded Services (`tests/conftest.py`)**: - The test network guard refuses loopback connects to any port the test process is not listening on, and a port refuses again once its listener closes, so a workstation's port-forwards (OTLP collector, Valkey, Ollama, ArgoCD) are never reached by the suite; one run had made 5,716 such connects. The refusal is the `ConnectionRefusedError` clients already handle (#837). - `EmbeddingsEngine` no longer skips its Valkey probe under pytest, and `test_popeye_dry_run` no longer runs the real popeye binary (#837). +- **MCP Tools Call Commands That Exist (`devops mcp`, `devops docs check`)**: + - Twelve MCP entry points called commands or options the CLI does not have and failed on every call. They now call real commands: `benchmark_embeddings` and `benchmark_suite` run `devops ai benchmark`; `scan_gitleaks`, `scan_semgrep` and `scan_checkov` run `devops scan secrets`, `sast` and `iac`; `resource://workspace/status` runs `devops repos list`; `scan_complexity` passes `--max-indent`; `resource://argo/fleet/status` no longer passes `--json` (#836). + - `devops docs check` resolves every `uv run devops` argv in the MCP server against the real command tree without running it, and reports each defect at its server line (#836). ## [0.2.24] - 2026-09-28 diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md index e6f32a4c4f..c97b6c1437 100644 --- a/docs/MCP_TOOLS.md +++ b/docs/MCP_TOOLS.md @@ -6,7 +6,6 @@ The `devops-cli` FastMCP server exposes DevOps automation and AI review capabili | Tool Name | Description | |---|---| -| [`ai_architecture`](#ai-architecture) | Analyze architectural module boundaries, dependency graphs, and cyclic imports. | | [`ai_ast_graph`](#ai-ast-graph) | Synthesize whole-repository code symbol and reference graph across polyglot languages. | | [`ai_ast_parse`](#ai-ast-parse) | Parse a polyglot source file (Python, TypeScript, JavaScript, Go, Rust, Java, C#, C, C++, HCL, shell, Markdown) into syntax symbols or execute S-expression query. | | [`ai_backend_probe`](#ai-backend-probe) | Directly probe health, latency, and registered models of an inference backend. | @@ -170,17 +169,6 @@ Pass the domain name alone, for example `k8s`. | --- -### `ai_architecture` - -Analyze architectural module boundaries, dependency graphs, and cyclic imports. - -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|---|---|---|---|---| -| `target` | `string` | No | `src` | - | -| `max_depth` | `integer` | No | `4` | - | - ### `ai_ast_graph` Synthesize whole-repository code symbol and reference graph across polyglot languages. @@ -952,11 +940,7 @@ Pass the domain name alone, for example `k8s`. Audit Kubernetes cluster security posture, RBAC policies, and CIS benchmarks. -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|---|---|---|---|---| -| `namespace` | `string` | No | `default` | - | +*No parameters required.* ### `k8s_bootstrap` @@ -976,9 +960,9 @@ Inject or validate Kubernetes chaos engineering experiments and cluster resilien | Parameter | Type | Required | Default | Description | |---|---|---|---|---| -| `action` | `string` | No | `validate` | - | | `experiment` | `string` | No | `pod-failure` | - | | `namespace` | `string` | No | `default` | - | +| `dry_run` | `boolean` | No | `True` | - | ### `k8s_create_tls_secret` @@ -1346,11 +1330,7 @@ Display uncommitted changes and branch drift across workspace repositories. Fetch and pull tracking branches across workspace repositories. -**Parameters:** - -| Parameter | Type | Required | Default | Description | -|---|---|---|---|---| -| `all_repos` | `boolean` | No | `False` | - | +*No parameters required.* ### `review_branch` diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 6fe61ba914..cb80db6979 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1034,12 +1034,10 @@ High-density product roadmap, engineering milestones, and open-source integratio - *Constraint*: A parser written for one agent's schema reads another's transcripts as steps with no source or tools and reports a passing error rate (Measured). Character counts cannot estimate thinking tokens, because most stored thinking blocks are empty. Native data carries `session.id`, `user.id`, `organization.id` and, when available, `user.email`: an `attributes` delete processor must strip identity fields before any exporter, with `OTEL_LOG_TOOL_DETAILS` and `OTEL_LOG_USER_PROMPTS` unset. Prometheus and Loki keep 2h (`k8s/monitoring/prometheus-values.yaml:11`), so the dashboard shows recent sessions, not trends; report values without thresholds. - *Measured*: Snapshot of live, growing transcripts on 2026-09-25. `python3 -B probe/t89/vibes_on_cc.py` ran vibes `TrajectoryParser` and `TelemetryCalculator` over this project's Claude Code transcripts and printed error_rate 0.0. `python3 -B probe/t89/measure.py` over the same files printed 53 of 2788 tool results flagged `is_error`, 1,338,604 recorded thinking tokens, and 1923 of 2809 thinking blocks with empty text. - *Source*: vibes `tools/conversation_synthesizer.py` -- [ ] **MCP Tools Resolve to Real Commands; Whole-Tree Import-Cycle Invariant (P0 - Critical)**: - - *Context & Rationale*: Three MCP tools shell out to commands that do not exist. `ai_architecture` runs `devops analyze architecture` (`src/devops_cli/ai/mcp/server.py:2135-2151`), and `benchmark_embeddings` and `benchmark_suite` run a top-level `devops benchmark` (`server.py:2078-2131`). `docs/MCP_TOOLS.md:9` still advertises cyclic-import analysis, and `tests/test_mcp.py:400` passes only because `_run_mcp_cmd` is mocked. The only cycle check is a hand-rolled Tarjan over four subsystems (`tests/test_architectural_invariants.py:282-347`), which runs inside the pytest step of `devops ci` (`src/devops_cli/commands/ci.py:303`). Its walker uses `ast.walk` (`:275`), so function-scope and `TYPE_CHECKING` imports count as edges. Of vibes' SGM001-SGM005, `mypy --strict` (`.github/workflows/ci.yml:57`) already covers SGM001/SGM002, and SGM003 (cycles) is the real gap. Nothing enforces AGENTS.md:84's ban on obsolete shims. `devops ci` has no dead-code step, and vulture sits in `.venv` but appears in neither `pyproject.toml` nor `uv.lock`. - - *Deliverable*: Measure before enforcing. (1) A contract test resolves every `uv run devops` argv list in `ai/mcp/server.py` against `typer.main.get_command(app)` with no subprocess mock, reusing T01's resolver once it lands. Repoint `benchmark_suite` to `devops ai benchmark --suite`, fix or delete the other two tools, and update `docs/MCP_TOOLS.md`. (2) Move the test's import resolver into `core/import_graph.py`, keep only module-level imports outside `if TYPE_CHECKING:`, widen the check to all of `src/devops_cli`, and replace the Tarjan with stdlib `graphlib.TopologicalSorter(graph).prepare()`, whose `CycleError` names a cycle. Add vibes' `from pkg import b` fixture and a deferred-import fixture. (3) Only then back `ai_architecture` with that seam, reporting import-time and function-scope cycles separately. (4) Add vulture as a dev dependency with `[tool.vulture]` `ignore_decorators` for Typer, MCP and Pydantic, and run it as an advisory `devops ci` step that never fails. Whitelist only the residue, leave unused arguments to Ruff `ARG`, and delete confirmed dead constants. Port nothing from `code_memory.py`. - - *Constraint*: A gate that counts function-scope imports starts red on a component that is not an import-time cycle. Drawing both package and submodule edges for `from pkg import b`, as vibes does, flags `ai.client` against `ai.client.unified`, which CPython imports cleanly. grimp's `is_lazy` marks only `lazy import` syntax, and an import-linter `acyclic_siblings` contract already breaks, so neither import-linter nor pylint R0401 earns a dependency. Unconfigured vulture rates almost everything at 60% and proposes deleting Typer commands and MCP tools. `grep` each residue hit before deleting it, because `getattr` and string lookups hide references. Add no caller or blast-radius column (SGM005). vibes' oracle reports zero for every symbol, and a zero reads as safe to change. Ratcheting belongs to `devops scan baseline`. - - *Measured*: `python probe/value435/mcp_argv.py`: 3 of 170 `devops` argv lists in `server.py` resolve to no command. `python probe/cycles_grimp_like.py toplevel` (module-level, non-`TYPE_CHECKING` imports): 0 non-trivial SCCs. `python probe/cycles_grimp_like.py all` (every import node): largest SCC 102 modules. `vulture src/devops_cli --min-confidence 60 | wc -l`: 1624 findings before any decorator is ignored. - - *Source*: vibes `tools/code_memory.py`, vibes `observations/systems/26-semantic-graph-ast-code-memory-and-persistent-symbol-indexing.md`, vibes `docs/ROADMAP.md`, vibes `examples/code-smell-quantifier/smell_quantifier.py`, vibes `examples/code-smell-quantifier/test_smell_quantifier.py`, vibes `examples/code-smell-quantifier/README.md` +- [x] **MCP Tools Resolve to Real Commands; Whole-Tree Import-Cycle Invariant (P0 - Critical, Issue #836)**: + - *Context & Rationale*: 12 of the 169 `uv run devops` argv lists in the MCP server called commands or options the CLI never had (`devops benchmark`, `analyze architecture`, the scan aliases, `repos sync --all` and others), so those tools failed on every call; each was broken when it was added, and the tests mocked the runner. + - *Deliverable*: Every broken argv now calls a real command, or the tool or parameter that had nothing behind it is removed (`ai_architecture`; `repos_sync(all_repos)`, `k8s_audit(namespace)`, `k8s_chaos(action)`), and `k8s_chaos` previews by default. `devops docs check` resolves every MCP argv statically against the real command tree, without running anything, and reports each defect by server line. The whole-tree import-cycle half is #848; the vulture step is dropped. + - *Constraint*: Critical fix: a P0 defect fix admitted to the current release by the owner. A bare `["devops", ...]` argv outside the MCP server (`commands/devcontainer.py:964`) is a follow-up. - [x] **Loopback Socket Guard So Tests Never Reach Port-Forwarded Services (P0 - Critical, Issue #837)**: - *Context & Rationale*: The test network guard refused external hosts but let every loopback connect through, so a workstation's kubectl port-forwards were live test dependencies: one suite run made 5,716 loopback connects (5,562 to the OTLP collector, 80 to Valkey, 29 to Ollama). - *Deliverable*: The guard refuses a loopback connect to any port the test process is not itself listening on, with the `ConnectionRefusedError` clients already handle, and a port refuses again once its listener closes. With stand-ins listening on the usual ports, a full suite run reaches none of them (5,736 refused, 21 to in-process servers). The guard stays installed after the session, `EmbeddingsEngine` no longer skips its Valkey probe under pytest, and `test_popeye_dry_run` no longer runs the real popeye binary. diff --git a/docs/agent/tasks/task-836-mcp-command-contract.md b/docs/agent/tasks/task-836-mcp-command-contract.md new file mode 100644 index 0000000000..f6927690e2 --- /dev/null +++ b/docs/agent/tasks/task-836-mcp-command-contract.md @@ -0,0 +1,48 @@ +# Task: MCP Tools and Resources Call Commands and Options That Exist (#836) + +**Issue**: [#836](https://github.com/dan-petty/devops-cli/issues/836) +**Status**: Done +**Milestone**: v0.2.24 +**Priority**: priority/p0-critical +**Scope**: scope/mcp + +## Description +`src/devops_cli/ai/mcp/server.py` built 169 `uv run devops` argv lists, and 12 of them failed on every call. None of these was a regression: each entry point was broken from the start. 22bba04 (v0.2.11) added eight of them: `scan_gitleaks`, `scan_semgrep` and `scan_checkov`, one day after 4cfe033 (v0.2.10) removed the scan aliases they call, plus `scan_complexity`, `k8s_chaos`, `k8s_audit`, `benchmark_embeddings` and `ai_architecture`. e2b146a (v0.2.5) added `resource://workspace/status`, when `devops workspace` had only `add`, `remove`, `generate`, `open` and `clean`. d9c1e63 (v0.2.15) added `resource://argo/fleet/status` with a `--json` that `argo cd apps list` did not have then either. b861fc4 (v0.2.13) added `benchmark_suite`. 4e48cd7 (v0.1.8) added the `--all` that `repos_sync` appends. A failure came back as ordinary tool text, not as an MCP error, and `tests/test_mcp.py` patched `_run_mcp_cmd` and asserted the mock's own return value, so nothing caught them. + +`devops docs check` now resolves every argv list in the server against the real command tree, without running anything: + +- `src/devops_cli/docs/command_resolver.py`: `resolve_devops_argv` walks from `main._COMMAND_SPECS` to each module app, as `main._delegate` does, and descends with `resolve_command`. It parses every node with `make_context(resilient_parsing=False)` and never calls `invoke`. A conversion error from a placeholder stops Click before its extra-argument check, so a lenient re-parse then recovers the leftovers. A known option missing its value stops Click's parser before it binds the positionals, so its leftovers are not reported as extra arguments. Parsing runs parameter callbacks, so a node is not parsed when the option parser alone, run with no callbacks, shows it was given an action option: an eager one (`--help`, `-h`, `--version`) or one whose value the command never sees (Typer's `--install-completion` and `--show-completion`). Those print, write a shell profile or exit. A group given no arguments, which prints its help, is not parsed either, and a callback that still exits ends the walk. None of these names a missing command or option, so the walk stops without a finding. A group's parser stops at its subcommand, so `scan gitleaks --help` still reports `gitleaks`. The vendored Click classes are duck-typed: a group is whatever has `resolve_command`, and an unknown option is the parse error that carries `possibilities`. The resolver reports only unknown commands, unknown options and unexpected extra arguments, and only for literal tokens. Code under `src/` can import it, so the prose, workflow and #697 checks can use it instead of writing a second walker. +- `src/devops_cli/docs/mcp_argv_collector.py`: an AST collector. It takes list literals that start with `uv run devops` and adds every token appended or extended onto the same variable, in source order, before that variable is reassigned. A literal string is kept as written, and each non-literal element or added value becomes a placeholder, so `cmd.append("--config"); cmd.append(cfg)` reads as `--config `. `DocGenerator.check_docs` runs it, so both `devops docs check` and `devops docs generate --check` report each defect at its repository path and line, `src/devops_cli/ai/mcp/server.py:`. +- `module_click_command` builds each command module's Click tree once per process, and the docs generator and the resolver share it. Without the shared build, the check cost 0.90 to 1.09 s. + +The 12 entry points: + +| Entry point | Was | Now | +|---|---|---| +| `benchmark_embeddings` | `devops benchmark embeddings --model` | `devops ai benchmark --type embedding --models --samples` | +| `benchmark_suite` | `devops benchmark --suite` | `devops ai benchmark --suite` | +| `ai_architecture` | `devops analyze architecture` | deleted, with no shim | +| `scan_gitleaks`, `scan_semgrep`, `scan_checkov` | `devops scan gitleaks`, `semgrep`, `checkov` | `devops scan secrets`, `sast`, `iac` | +| `resource://workspace/status` | `devops workspace list` | `devops repos list`, the command the `workspace_list` tool already runs | +| `repos_sync` | `--all` (the `all_repos` parameter) | parameter dropped | +| `resource://argo/fleet/status` | `--json` | dropped | +| `scan_complexity` | `--max-nesting-depth` | `--max-indent` | +| `k8s_chaos` | positional `action`, `--experiment` | `experiment` is the positional; `dry_run` (default true) passes `--dry-run` | +| `k8s_audit` | `--namespace` | parameter dropped; `devops k8s audit` takes only `--dry-run` | + +`k8s_chaos` called `action` "validate" by default. The command has no action argument, and without `--dry-run` it deletes a pod, so the tool previews by default and runs the experiment only when `dry_run` is false. + +The same defect class remains outside this issue's `server.py` scope. `_auto_deploy_k8s_stack` in `src/devops_cli/commands/devcontainer.py` runs `devops k8s deploy-stack `, but `deploy-stack` takes the stack only as `--stack`, so every call has failed with an unexpected extra argument since 491907c (v0.2.0). The collector does not see it because the list has no `uv run` prefix and its positional is a placeholder. The `list_mcp_tools` docstring in `server.py` cites `devops ai mcp export-schemas`, but the command is `devops mcp export-schemas`. That is a prose reference, which the `docs/ROADMAP.md:908` gate covers. + +Key questions, answered as the issue proposed: `ai_architecture` returns, backed by the import graph, only when something needs it. The vulture step in `docs/ROADMAP.md:1040` is dropped, and the import-cycle part of that entry remains a separate item. + +## Acceptance Criteria +- [x] `devops docs check` covers every literal argv list in the server and reports 0 unresolved commands and 0 unknown options. `test_every_mcp_server_argv_resolves` asserts at least 168 lists, all resolving, each at `src/devops_cli/ai/mcp/server.py`. The count is 168, not the issue's 169, because this change deletes `ai_architecture`'s list. Run against the unfixed server, the same check listed exactly the 12 entry points above out of 169. +- [x] The fixture argv `uv run devops analyze architecture` is reported as unresolved, naming `analyze`: `test_unresolved_fixture_argv_are_reported_with_their_source_line` gives `fixture.py:2 ai_architecture: 'devops analyze architecture ': unknown command 'analyze' under 'devops'.` +- [x] A fixture with an unknown option is reported with its source line: the same test gives `fixture.py:6 ... unknown option '--max-nesting-depth' for 'devops scan complexity'` and `fixture.py:12 ... unknown option '--all' for 'devops repos sync'`. The fixture's `--config` and its value, appended in two calls at line 35, resolve. `test_docs_check_reports_an_unresolved_mcp_argv` shows `devops docs check` exiting 1 with that line. +- [x] No test in `tests/test_mcp.py` asserts a mocked return value for a changed or removed tool. Those assertions are gone. `test_repointed_mcp_entry_points_pass_real_command_lines` asserts the argv that each changed tool and resource hands `_run_mcp_cmd`, and `test_ai_architecture_tool_is_removed` asserts that the tool, its function and its export are gone. `tests/test_argo_fleet.py` asserts the argo resource's exact argv. +- [x] `uv run devops docs check` passes with the regenerated `docs/MCP_TOOLS.md`. README.md did not change. +- [x] The docs stage grows by at most 1 s. In-process, right after every command module's tree was built, `check_mcp_server_argv` took 0.365, 0.347 and 0.392 s over three runs, with a parallel agent's gate loading the machine. End-to-end `check_docs` runs with and without the contract were within the noise of a parallel agent's gate runs, at 4.8 to 10.8 s either way. +- [x] No network access, no subprocess, no new dependency. `test_every_mcp_server_argv_resolves` and `test_resolving_parses_without_invoking_or_spawning` build the command trees first, because importing a command module may spawn (GitPython runs `git version` on import) and `devops docs check` has imported them all to generate the docs before it resolves. They then patch `subprocess.Popen` to fail around collecting and resolving, and assert that neither `_run_mcp_cmd` nor the `k8s chaos` experiment is called. Each passes when run on its own, with `-n0` and under xdist. `test_a_completion_option_never_installs_completion` asserts that `scan --install-completion bash` never reaches Typer's installer. The session fixture blocks external sockets, and `pyproject.toml` and `uv.lock` are unchanged. +- [x] The negative controls in `tests/test_docs_command_resolver.py` put a defect at each depth: root, group, leaf, the four-deep `argo cd apps list --json`, the group-as-command `ai benchmark`, and the root-level `lint`. Another control checks that a placeholder the integer option rejects still lets a stray argument be found. `scan gitleaks --help` still reports `gitleaks`, and `scan complexity --max-nesting-depth --help` still reports the option. `scan sast . --config` reports nothing. `test_an_eager_option_or_a_bare_group_resolves_silently` resolves no arguments, `--help`, `--version`, a bare `k8s`, `scan --help`, `scan sast --help`, `scan sast . -h` and `scan --show-completion bash` to `None` with nothing on stdout. A Typer upgrade that changes the walk turns these findings into `None`, and a renamed `_protected_args` raises. +- [x] `uv run devops ci` passes: all 13 checks, 197 s wall clock (3 min 17 s, pytest and coverage 3 min 14 s) while a parallel agent's gate shared the machine. diff --git a/src/devops_cli/ai/mcp/__init__.py b/src/devops_cli/ai/mcp/__init__.py index 50876a61d4..54e821e922 100644 --- a/src/devops_cli/ai/mcp/__init__.py +++ b/src/devops_cli/ai/mcp/__init__.py @@ -10,7 +10,6 @@ resolve_tool_domain, ) from devops_cli.ai.mcp.server import ( - ai_architecture, ai_ast_graph, ai_ast_parse, ai_diagram, @@ -153,7 +152,6 @@ "ResourceTemplate", "ServerCapabilities", "ToolResult", - "ai_architecture", "ai_ast_graph", "ai_ast_parse", "ai_diagram", diff --git a/src/devops_cli/ai/mcp/server.py b/src/devops_cli/ai/mcp/server.py index dabf8e2e92..ad4e9753e8 100644 --- a/src/devops_cli/ai/mcp/server.py +++ b/src/devops_cli/ai/mcp/server.py @@ -229,12 +229,12 @@ def repos_status() -> str: @mcp.tool() -def repos_sync(all_repos: bool = False) -> str: +def repos_sync() -> str: """Fetch and pull tracking branches across workspace repositories.""" - cmd = ["uv", "run", "devops", "repos", "sync"] - if all_repos: - cmd.append("--all") - return _run_mcp_cmd(cmd, timeout=DEFAULT_MCP_TOOL_SHORT_TIMEOUT_SECONDS * 2) + return _run_mcp_cmd( + ["uv", "run", "devops", "repos", "sync"], + timeout=DEFAULT_MCP_TOOL_SHORT_TIMEOUT_SECONDS * 2, + ) @mcp.tool() @@ -1156,7 +1156,7 @@ def get_workspace_resource() -> str: """Return live workspace inventory and repository statuses.""" return _run_mcp_resource( "resource://workspace/status", - ["uv", "run", "devops", "workspace", "list"], + ["uv", "run", "devops", "repos", "list"], timeout=DEFAULT_MCP_TOOL_SHORT_TIMEOUT_SECONDS, ) @@ -1238,16 +1238,7 @@ def get_gh_views_resource() -> str: def get_argo_fleet_status_resource() -> str: """Return live ArgoCD multi-cluster fleet synchronization status across all managed clusters.""" return _run_mcp_cmd( - [ - "uv", - "run", - "devops", - "argo", - "cd", - "apps", - "list", - "--json", - ], + ["uv", "run", "devops", "argo", "cd", "apps", "list"], timeout=DEFAULT_MCP_TOOL_FAST_TIMEOUT_SECONDS, ) @@ -1854,7 +1845,7 @@ def scan_gitleaks(target: str = ".") -> str: """Scan git repository or directory for hardcoded secrets, tokens, and private keys.""" _validate_mcp_arg("target", target) return _run_mcp_cmd( - ["uv", "run", "devops", "scan", "gitleaks", target], + ["uv", "run", "devops", "scan", "secrets", target], timeout=DEFAULT_MCP_TOOL_TIMEOUT_SECONDS, ) @@ -1865,7 +1856,7 @@ def scan_semgrep(target: str = ".", config: str = "auto") -> str: _validate_mcp_arg("target", target) _validate_mcp_arg("config", config) return _run_mcp_cmd( - ["uv", "run", "devops", "scan", "semgrep", target, "--config", config], + ["uv", "run", "devops", "scan", "sast", target, "--config", config], timeout=DEFAULT_MCP_TOOL_TIMEOUT_SECONDS, ) @@ -1875,7 +1866,7 @@ def scan_checkov(target: str = ".") -> str: """Scan Infrastructure-as-Code (Terraform, Helm, Kubernetes, Dockerfile) via Checkov.""" _validate_mcp_arg("target", target) return _run_mcp_cmd( - ["uv", "run", "devops", "scan", "checkov", target], + ["uv", "run", "devops", "scan", "iac", target], timeout=DEFAULT_MCP_TOOL_TIMEOUT_SECONDS, ) @@ -1898,7 +1889,7 @@ def scan_complexity( target, "--max-complexity", str(max_complexity), - "--max-nesting-depth", + "--max-indent", str(max_nesting_depth), ], timeout=DEFAULT_MCP_TOOL_SHORT_TIMEOUT_SECONDS, @@ -1928,37 +1919,24 @@ def scan_sbom(target: str = ".", format: str = "cyclonedx") -> str: @mcp.tool() def k8s_chaos( - action: str = "validate", experiment: str = "pod-failure", namespace: str = "default", + dry_run: bool = True, ) -> str: """Inject or validate Kubernetes chaos engineering experiments and cluster resilience.""" - _validate_mcp_arg("action", action) _validate_mcp_arg("experiment", experiment) _validate_mcp_arg("namespace", namespace) - return _run_mcp_cmd( - [ - "uv", - "run", - "devops", - "k8s", - "chaos", - action, - "--experiment", - experiment, - "--namespace", - namespace, - ], - timeout=DEFAULT_MCP_TOOL_TIMEOUT_SECONDS, - ) + cmd = ["uv", "run", "devops", "k8s", "chaos", experiment, "--namespace", namespace] + if dry_run: + cmd.append("--dry-run") + return _run_mcp_cmd(cmd, timeout=DEFAULT_MCP_TOOL_TIMEOUT_SECONDS) @mcp.tool() -def k8s_audit(namespace: str = "default") -> str: +def k8s_audit() -> str: """Audit Kubernetes cluster security posture, RBAC policies, and CIS benchmarks.""" - _validate_mcp_arg("namespace", namespace) return _run_mcp_cmd( - ["uv", "run", "devops", "k8s", "audit", "--namespace", namespace], + ["uv", "run", "devops", "k8s", "audit"], timeout=DEFAULT_MCP_TOOL_SHORT_TIMEOUT_SECONDS, ) @@ -2093,11 +2071,13 @@ def benchmark_embeddings( "uv", "run", "devops", + "ai", "benchmark", - "embeddings", + "--type", + "embedding", "--provider", provider, - "--model", + "--models", model, "--samples", str(samples), @@ -2120,6 +2100,7 @@ def benchmark_suite( "uv", "run", "devops", + "ai", "benchmark", "--suite", "--models", @@ -2135,26 +2116,6 @@ def benchmark_suite( return _run_mcp_cmd(cmd, timeout=DEFAULT_MCP_TOOL_TIMEOUT_SECONDS) -@mcp.tool() -def ai_architecture(target: str = "src", max_depth: int = 4) -> str: - """Analyze architectural module boundaries, dependency graphs, and cyclic imports.""" - _validate_mcp_arg("target", target) - _validate_mcp_int_bound("max_depth", max_depth, min_val=1) - return _run_mcp_cmd( - [ - "uv", - "run", - "devops", - "analyze", - "architecture", - target, - "--max-depth", - str(max_depth), - ], - timeout=DEFAULT_MCP_TOOL_SHORT_TIMEOUT_SECONDS, - ) - - @mcp.tool() def branches_list(remote: bool = True) -> str: """List git branches across repositories with tracking status and stale detection.""" diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 1a604a9601..213151ac3d 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -94,6 +94,15 @@ CONST_MCP_DOMAINS: Final[frozenset[str]] = frozenset( CONST_MCP_EAGER_DOMAINS | CONST_MCP_LAZY_DOMAINS | {"github", "secrets", "benchmarks"} ) +# The module whose tools and resources shell out to `devops`, and the argv head that marks +# such a call. `devops docs check` resolves every list that starts with it. +CONST_MCP_SERVER_MODULE = "devops_cli.ai.mcp.server" +CONST_DEVOPS_ARGV_PREFIX: Final[tuple[str, ...]] = ("uv", "run", "devops") +# The list methods that add tokens to an argv the MCP server builds up in a variable. +CONST_ARGV_EXTENDING_METHODS: Final[frozenset[str]] = frozenset({"append", "extend"}) +# Root commands whose module app takes the command's own name as its first argument: +# `devops lint` runs the `lint` subcommand of `devops_cli.commands.ci`. +CONST_CLI_ROOT_LEVEL_COMMANDS: Final[frozenset[str]] = frozenset({"format", "lint"}) CONST_SYSTEM_TEMP_DIRS: tuple[Path, ...] = (Path("/tmp"), Path("/var/tmp")) # nosec B108 CONST_FORBIDDEN_SYSTEM_DIRS: tuple[Path, ...] = ( Path("/etc"), diff --git a/src/devops_cli/docs/command_resolver.py b/src/devops_cli/docs/command_resolver.py new file mode 100644 index 0000000000..d20fcfa137 --- /dev/null +++ b/src/devops_cli/docs/command_resolver.py @@ -0,0 +1,234 @@ +"""Resolve `devops` command lines against the real command tree without running them. + +`typer.main.get_command(main.app)` cannot see past the first segment: every top-level +command is a lazy proxy that accepts any arguments (`core/cli.py`). The walk therefore +starts where `main._delegate` does, at the module app `main._COMMAND_SPECS` names, and +descends it with `resolve_command`. Each node is parsed with `make_context`, which converts +values and runs parameter callbacks but never a command's own callback. An action option +-- eager, like `--help` and `--version`, or one whose value the command never sees, like +Typer's completion options -- runs its callback as it is parsed, to print, write a shell +profile or exit. A node given one, or a group given nothing, which prints its help, is +therefore not parsed: none of them names a missing command or option. + +Typer vendors its own copy of Click, so nothing here imports a Click class: a group is +whatever has `resolve_command`, and an unknown option is the parse error that carries +`possibilities`. The resolver tests hold one defect at each depth as a negative control, so +a Typer upgrade that changes the walk fails them instead of resolving everything. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from enum import StrEnum +from functools import cache +from importlib import import_module +from typing import Any + +import typer +from pydantic import BaseModel, ConfigDict + +from devops_cli.config.constants import CONST_CLI_ROOT_LEVEL_COMMANDS +from devops_cli.lang import MESSAGES + +_ROOT = "devops" + + +class ArgvPlaceholder(BaseModel): + """An argv token computed at runtime, so it may stand for any value or option.""" + + model_config = ConfigDict(frozen=True) + + expression: str + + def __str__(self) -> str: + return f"<{self.expression}>" + + +ArgvToken = str | ArgvPlaceholder + + +class CommandReferenceDefect(StrEnum): + """The defects a command line is checked for.""" + + UNKNOWN_COMMAND = "unknown_command" + UNKNOWN_OPTION = "unknown_option" + UNEXPECTED_ARGUMENT = "unexpected_argument" + + +class CommandReferenceFinding(BaseModel): + """The token a command line's parse rejected, and the command it was given to.""" + + model_config = ConfigDict(frozen=True) + + defect: CommandReferenceDefect + command_path: str + token: str + + def describe(self) -> str: + """Name the rejected token and the command it was given to.""" + template = { + CommandReferenceDefect.UNKNOWN_COMMAND: MESSAGES.docs.argv_unknown_command, + CommandReferenceDefect.UNKNOWN_OPTION: MESSAGES.docs.argv_unknown_option, + CommandReferenceDefect.UNEXPECTED_ARGUMENT: MESSAGES.docs.argv_unexpected_argument, + }[self.defect] + return template.format(token=self.token, command_path=self.command_path) + + +def resolve_devops_argv(tokens: Sequence[ArgvToken]) -> CommandReferenceFinding | None: + """Return the first defect in the command line `devops `, or None if it parses. + + Only literal tokens are reported. A placeholder where a subcommand belongs ends the walk, + and a placeholder left over as an argument may be an option the caller computes. + """ + context, finding = _parse(_root_command(), _ROOT, _ROOT, tokens, parent=None) + subcommand = _literal_subcommand(context, tokens) if finding is None else None + return finding if subcommand is None else _walk_delegated(*subcommand) + + +def _walk_delegated(command_name: str, args: Sequence[ArgvToken]) -> CommandReferenceFinding | None: + """Walk a top-level command as `main._delegate` runs it: its module app, from the top.""" + command = _module_command(command_name) + if command is None: + return _found(CommandReferenceDefect.UNKNOWN_COMMAND, _ROOT, command_name) + if command_name in CONST_CLI_ROOT_LEVEL_COMMANDS: + return _walk(command, _ROOT, _ROOT, [command_name, *args], parent=None) + return _walk(command, command_name, f"{_ROOT} {command_name}", args, parent=None) + + +def _walk( + command: Any, name: str, path: str, tokens: Sequence[ArgvToken], parent: Any +) -> CommandReferenceFinding | None: + """Parse `tokens` on `command` and, for a group, descend into the subcommand they name.""" + context, finding = _parse(command, name, path, tokens, parent) + is_group = callable(getattr(command, "resolve_command", None)) + subcommand = _literal_subcommand(context, tokens) if finding is None and is_group else None + if subcommand is None: + return finding + child_name, child_tokens = subcommand + child = _child(command, context, child_name) + if child is None: + return _found(CommandReferenceDefect.UNKNOWN_COMMAND, path, child_name) + return _walk(child, child_name, f"{path} {child_name}", child_tokens, context) + + +def _parse( + command: Any, name: str, path: str, tokens: Sequence[ArgvToken], parent: Any +) -> tuple[Any | None, CommandReferenceFinding | None]: + """Parse `tokens` as `command`'s arguments: its context, or the defect that stopped it. + + No context means the walk stops here with nothing to report. Of the errors a strict + parse raises, one naming an option is final: an unknown option is the defect, and a + known option missing its value stopped the parser before it bound the positionals, so + its leftovers are not extra arguments. Click converts values before it looks for extra + arguments, so a value that fails conversion -- usually a placeholder -- hides them, and + a lenient parse recovers the leftovers instead. Click's parser consumes the list it is + given, so each parse gets its own. An exit is a fallback for any other callback that + ends the command. + """ + args = [str(token) for token in tokens] + if not args or _gives_action_option(command, name, args, parent): + return None, None + try: + strict = command.make_context(name, list(args), parent=parent, resilient_parsing=False) + return strict, None + except typer.Exit, SystemExit: + return None, None + except typer.TyperException as error: + if hasattr(error, "option_name"): + return None, _unknown_option(error, path) + context = command.make_context(name, args, parent=parent, resilient_parsing=True) + return context, _unexpected_argument(context, path, tokens) + + +def _gives_action_option(command: Any, name: str, args: list[str], parent: Any) -> bool: + """Whether `args` hands `command` one of its own action options, without parsing them. + + An action option is eager, or keeps its value from the command, so it exists for its + callback. Only the option parser runs, on a context parsed from no arguments, so no + callback sees these tokens. A group's parser stops at its subcommand, so + `scan gitleaks --help` gives `--help` to `gitleaks`, not to `scan`, and the missing + `gitleaks` is still found. + """ + probe = command.make_context(name, [], parent=parent, resilient_parsing=True) + _, _, given = command.make_parser(probe).parse_args(list(args)) + return any(parameter.is_eager or not parameter.expose_value for parameter in given) + + +def _unknown_option(error: Exception, path: str) -> CommandReferenceFinding | None: + """The unknown option a parse rejected, duck-typed on vendored Click's `NoSuchOption`. + + `BadOptionUsage` carries `option_name` too, for a known option missing its value; only + `NoSuchOption` carries `possibilities`. + """ + if not hasattr(error, "possibilities"): + return None + option = str(getattr(error, "option_name", "")) + return _found(CommandReferenceDefect.UNKNOWN_OPTION, path, option) + + +def _unexpected_argument( + context: Any, path: str, tokens: Sequence[ArgvToken] +) -> CommandReferenceFinding | None: + """Report the literal arguments a command that takes no extra arguments left over.""" + literals = {token for token in tokens if isinstance(token, str)} + stray = [argument for argument in context.args if argument in literals] + if context.allow_extra_args or not stray: + return None + return _found(CommandReferenceDefect.UNEXPECTED_ARGUMENT, path, " ".join(stray)) + + +def _literal_subcommand( + context: Any | None, tokens: Sequence[ArgvToken] +) -> tuple[str, Sequence[ArgvToken]] | None: + """The literal subcommand name a group's parse left over, and the tokens after it.""" + if context is None: + return None + # Vendored Click keeps the subcommand name in `_protected_args`, with no public + # accessor. A group parses no positionals of its own, so what it leaves is a suffix of + # its tokens. If Typer renames the attribute, the walk fails here, loudly. + leftover = len(context._protected_args) + len(context.args) + tail = tokens[len(tokens) - leftover :] + head = tail[0] if tail else None + if head is None or isinstance(head, ArgvPlaceholder): + return None + return head, tail[1:] + + +def _child(group: Any, context: Any, name: str) -> Any | None: + """The subcommand `name` of `group`, or None when the group has no such command.""" + try: + _, child, _ = group.resolve_command(context, [name]) + except typer.TyperException: + return None + return child + + +def _found(defect: CommandReferenceDefect, path: str, token: str) -> CommandReferenceFinding: + return CommandReferenceFinding(defect=defect, command_path=path, token=token) + + +@cache +def _root_command() -> Any: + """The `devops` group itself, whose own options precede the command name.""" + from devops_cli.main import app + + return typer.main.get_command(app) + + +def _module_command(command_name: str) -> Any | None: + """The command `main._delegate` hands a top-level command's arguments to, if any.""" + from devops_cli.main import _COMMAND_SPECS + + spec = _COMMAND_SPECS.get(command_name) + return None if spec is None else module_click_command(spec[0]) + + +@cache +def module_click_command(module_path: str) -> Any | None: + """The command Typer builds from a command module's `app`, built once per process. + + A build evaluates every parameter annotation in the module, most of a second across all + of them, and documentation generation and the resolver share each build. + """ + app = getattr(import_module(module_path), "app", None) + return None if app is None else typer.main.get_command(app) diff --git a/src/devops_cli/docs/generator.py b/src/devops_cli/docs/generator.py index 2889e8a6c7..6263cd8d49 100644 --- a/src/devops_cli/docs/generator.py +++ b/src/devops_cli/docs/generator.py @@ -5,12 +5,10 @@ import asyncio import concurrent.futures import re -from importlib import import_module from pathlib import Path from typing import Any import click -import typer from pydantic import BaseModel, Field from devops_cli.config.constants import ( @@ -18,6 +16,7 @@ CONST_STANDARD_HTML_TAGS, ) from devops_cli.config.env import EnvVarSpec, get_all_env_var_specs +from devops_cli.docs.command_resolver import module_click_command from devops_cli.output import write_text_file from devops_cli.telemetry import trace_span @@ -329,11 +328,9 @@ def _introspect_single_group( if not module_path.startswith("devops_cli.commands."): return None try: - module = import_module(module_path) - app_obj = getattr(module, "app", None) - if app_obj is None: + click_cmd = module_click_command(module_path) + if click_cmd is None: return None - click_cmd = typer.main.get_command(app_obj) return self._introspect_leaf_or_group(click_cmd, name, module_path, summary) except Exception as exc: return CommandGroupDoc( @@ -1038,9 +1035,11 @@ def write_all_docs(self, output_dir: Path, sync_readme_table: bool = True) -> li def check_docs( self, output_dir: Path, check_readme_table: bool = True ) -> tuple[bool, list[str]]: - """Verify if on-disk docs match current generated docs.""" + """Verify on-disk docs match the generated docs and every MCP argv resolves.""" + from devops_cli.docs.mcp_argv_collector import check_mcp_server_argv + docs = self.generate_all_docs(output_dir) - errors: list[str] = [] + errors: list[str] = check_mcp_server_argv() for rel_path, expected_content in docs.items(): target_path = output_dir / rel_path diff --git a/src/devops_cli/docs/mcp_argv_collector.py b/src/devops_cli/docs/mcp_argv_collector.py new file mode 100644 index 0000000000..663424d39c --- /dev/null +++ b/src/devops_cli/docs/mcp_argv_collector.py @@ -0,0 +1,190 @@ +"""Collect the `devops` command lines the MCP server builds and resolve them statically. + +The MCP tools and resources shell out through `_run_mcp_cmd`, and a command that does not +exist comes back as ordinary tool text, not as an error. Nothing ran these lists against +the CLI, so this module reads them from the server's source and hands each one to +`resolve_devops_argv`; no tool and no command runs. +""" + +from __future__ import annotations + +import ast +import inspect +import sys +from collections.abc import Iterable, Iterator, Sequence +from importlib import import_module +from pathlib import Path + +from pydantic import BaseModel, ConfigDict + +from devops_cli.config.constants import ( + CONST_ARGV_EXTENDING_METHODS, + CONST_DEVOPS_ARGV_PREFIX, + CONST_MCP_SERVER_MODULE, +) +from devops_cli.core.repo import find_repo_root +from devops_cli.docs.command_resolver import ArgvPlaceholder, ArgvToken, resolve_devops_argv +from devops_cli.lang import MESSAGES + +_SCOPE_NODES = (ast.FunctionDef, ast.AsyncFunctionDef) +_MODULE_SCOPE = "" + + +class DevopsArgvReference(BaseModel): + """One `uv run devops` argv list in source, as the tokens that follow `devops`.""" + + model_config = ConfigDict(frozen=True) + + path: str + line: int + owner: str + tokens: tuple[ArgvToken, ...] + + @property + def command_line(self) -> str: + """The tokens after `devops`, placeholders shown as ``.""" + return " ".join(str(token) for token in self.tokens) + + +def collect_devops_argv_references(source: str, path: str) -> list[DevopsArgvReference]: + """Collect every list literal in `source` that starts with `uv run devops`. + + A list assigned to a variable also gains every token later appended or extended onto + that variable in the same function, in source order, up to the next list assigned to + it. A literal string is kept as written and any other element or added value becomes a + placeholder. Branches are not followed, so appends that exclude each other read as one + command line. + """ + tree = ast.parse(source, filename=path) + scopes = [tree, *(node for node in ast.walk(tree) if isinstance(node, _SCOPE_NODES))] + references = [ref for scope in scopes for ref in _scope_references(scope, path)] + return sorted(references, key=lambda reference: reference.line) + + +def collect_mcp_server_argv_references() -> list[DevopsArgvReference]: + """Collect the `uv run devops` argv lists of the FastMCP server's tools and resources. + + Each is located by its path from the repository root, `src/` included, so an editor or + a CI annotation can open it. + """ + module = import_module(CONST_MCP_SERVER_MODULE) + source_file = Path(inspect.getsourcefile(module) or "").resolve() + path = source_file.relative_to(find_repo_root(source_file)).as_posix() + return collect_devops_argv_references(inspect.getsource(module), path) + + +def describe_unresolved_references(references: Iterable[DevopsArgvReference]) -> list[str]: + """One line per reference that does not resolve, at its `path:line`.""" + return [ + MESSAGES.docs.argv_unresolved.format( + location=f"{reference.path}:{reference.line}", + owner=reference.owner, + command_line=reference.command_line, + problem=finding.describe(), + ) + for reference in references + if (finding := resolve_devops_argv(reference.tokens)) is not None + ] + + +def check_mcp_server_argv() -> list[str]: + """Describe every MCP server argv list that names a missing command or option.""" + return describe_unresolved_references(collect_mcp_server_argv_references()) + + +def _scope_references(scope: ast.AST, path: str) -> Iterator[DevopsArgvReference]: + """The argv lists written directly in one module or function body.""" + nodes = list(_own_nodes(scope)) + bindings = [binding for node in nodes if (binding := _argv_binding(node)) is not None] + calls = [node for node in nodes if isinstance(node, ast.Call) and _extended_name(node)] + owner = getattr(scope, "name", _MODULE_SCOPE) + for node in nodes: + if isinstance(node, ast.List) and _is_devops_argv(node): + listed = [_token(element) for element in node.elts[len(CONST_DEVOPS_ARGV_PREFIX) :]] + added = _added_tokens(node, bindings, calls) + yield DevopsArgvReference( + path=path, line=node.lineno, owner=owner, tokens=(*listed, *added) + ) + + +def _own_nodes(scope: ast.AST) -> Iterator[ast.AST]: + """The nodes of a scope, without descending into the functions defined in it.""" + for child in ast.iter_child_nodes(scope): + yield child + if not isinstance(child, _SCOPE_NODES): + yield from _own_nodes(child) + + +def _is_devops_argv(node: ast.List) -> bool: + head = node.elts[: len(CONST_DEVOPS_ARGV_PREFIX)] + literals = (element.value for element in head if isinstance(element, ast.Constant)) + return tuple(literals) == CONST_DEVOPS_ARGV_PREFIX + + +def _argv_binding(node: ast.AST) -> tuple[str, ast.List] | None: + """The variable name and argv list of an assignment such as `cmd = ["uv", ...]`.""" + if not isinstance(node, ast.Assign | ast.AnnAssign): + return None + target = node.targets[0] if isinstance(node, ast.Assign) else node.target + value = node.value + if isinstance(target, ast.Name) and isinstance(value, ast.List) and _is_devops_argv(value): + return target.id, value + return None + + +def _extended_name(call: ast.Call) -> str | None: + """The variable a call such as `cmd.append(...)` or `cmd.extend(...)` adds tokens to.""" + method = call.func + if not isinstance(method, ast.Attribute) or method.attr not in CONST_ARGV_EXTENDING_METHODS: + return None + return method.value.id if isinstance(method.value, ast.Name) else None + + +def _added_tokens( + argv: ast.List, bindings: Sequence[tuple[str, ast.List]], calls: Sequence[ast.Call] +) -> list[ArgvToken]: + """The tokens added to `argv`'s variable before the variable is reassigned.""" + name = next((bound for bound, value in bindings if value is argv), None) + if name is None: + return [] + start = _position(argv) + end = min( + ( + _position(value) + for bound, value in bindings + if bound == name and _position(value) > start + ), + default=(sys.maxsize, 0), + ) + return [ + token + for call in calls + if _extended_name(call) == name and start < _position(call) < end + for token in _call_tokens(call) + ] + + +def _call_tokens(call: ast.Call) -> list[ArgvToken]: + """The tokens `.append(value)` or `.extend(values)` adds, a placeholder per runtime value. + + An extend of a list or tuple literal adds its elements; any other extend adds tokens + that are not known until it runs, which one placeholder stands for. + """ + if len(call.args) != 1: + return [] + added = call.args[0] + if not isinstance(call.func, ast.Attribute) or call.func.attr != "extend": + return [_token(added)] + if isinstance(added, ast.List | ast.Tuple): + return [_token(element) for element in added.elts] + return [ArgvPlaceholder(expression=ast.unparse(added))] + + +def _token(element: ast.expr) -> ArgvToken: + if isinstance(element, ast.Constant) and isinstance(element.value, str): + return element.value + return ArgvPlaceholder(expression=ast.unparse(element)) + + +def _position(node: ast.expr) -> tuple[int, int]: + return node.lineno, node.col_offset diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 5dcde83f2f..e075b0f525 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -308,6 +308,10 @@ class DocsMessages: check_failed: str = ( "Documentation check failed. Run 'devops docs generate' to refresh documentation." ) + argv_unresolved: str = "{location} {owner}: 'devops {command_line}': {problem}." + argv_unknown_command: str = "unknown command '{token}' under '{command_path}'" + argv_unknown_option: str = "unknown option '{token}' for '{command_path}'" + argv_unexpected_argument: str = "unexpected extra argument '{token}' for '{command_path}'" synced_readme: str = "✓ Synchronized Command Matrix table in {path}" unsupported_format: str = ( "Unsupported documentation format: {format}. Supported: markdown, json" diff --git a/src/devops_cli/main.py b/src/devops_cli/main.py index 16d7a6c36b..9de9d08957 100644 --- a/src/devops_cli/main.py +++ b/src/devops_cli/main.py @@ -11,6 +11,7 @@ import typer from devops_cli import __version__ +from devops_cli.config.constants import CONST_CLI_ROOT_LEVEL_COMMANDS from devops_cli.core.cli import new_typer from devops_cli.dry_run import dry_run_requested_by_environment, is_dry_run, set_dry_run from devops_cli.lang import HELP @@ -83,9 +84,10 @@ def _delegate(module_path: str, command_name: str, args: list[str]) -> None: module_app = module.app command = typer.main.get_command(module_app) - effective_args = [command_name, *args] if command_name in ("format", "lint") else list(args) + is_root_level = command_name in CONST_CLI_ROOT_LEVEL_COMMANDS + effective_args = [command_name, *args] if is_root_level else list(args) - prog = "devops" if command_name in ("format", "lint") else f"devops {command_name}" + prog = "devops" if is_root_level else f"devops {command_name}" # Fast dispatch for help queries to avoid importing telemetry/OTLP network exporters if any(a in ("-h", "--help") for a in args): diff --git a/tests/test_argo_fleet.py b/tests/test_argo_fleet.py index 26ea993f27..48008c182a 100644 --- a/tests/test_argo_fleet.py +++ b/tests/test_argo_fleet.py @@ -276,14 +276,10 @@ def test_mcp_argo_fleet_status_resource() -> None: """Verify FastMCP resource get_argo_fleet_status_resource queries read-only apps list.""" from devops_cli.ai.mcp.server import get_argo_fleet_status_resource - with patch("devops_cli.ai.mcp.server._run_mcp_cmd", return_value='{"items": []}') as mock_cmd: - out = get_argo_fleet_status_resource() - assert "items" in out - mock_cmd.assert_called_once() - cmd = mock_cmd.call_args[0][0] - assert "cd" in cmd - assert "apps" in cmd - assert "list" in cmd + with patch("devops_cli.ai.mcp.server._run_mcp_cmd", return_value="argocd Synced") as mock_cmd: + get_argo_fleet_status_resource() + + assert mock_cmd.call_args.args[0] == ["uv", "run", "devops", "argo", "cd", "apps", "list"] def test_execute_cluster_sync_live() -> None: diff --git a/tests/test_docs_command_resolver.py b/tests/test_docs_command_resolver.py new file mode 100644 index 0000000000..a10f3d656f --- /dev/null +++ b/tests/test_docs_command_resolver.py @@ -0,0 +1,214 @@ +"""Tests for resolving `devops` command lines against the real Typer command tree.""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest + +from devops_cli.docs.command_resolver import ( + ArgvPlaceholder, + ArgvToken, + CommandReferenceDefect, + CommandReferenceFinding, + module_click_command, + resolve_devops_argv, +) +from devops_cli.main import _COMMAND_SPECS + + +def _finding(defect: CommandReferenceDefect, path: str, token: str) -> CommandReferenceFinding: + return CommandReferenceFinding(defect=defect, command_path=path, token=token) + + +TARGET = ArgvPlaceholder(expression="target") +NUMBER = ArgvPlaceholder(expression="str(max_complexity)") + + +# The negative controls below fail if a Typer upgrade changes how the walk descends: each +# defect sits at a different depth, so a walk that stops early, or a parse that stops +# raising, turns a finding into None. +@pytest.mark.parametrize( + ("tokens", "expected"), + [ + ( + ["analyze", "architecture", TARGET], + _finding(CommandReferenceDefect.UNKNOWN_COMMAND, "devops", "analyze"), + ), + ( + ["scan", "gitleaks", TARGET], + _finding(CommandReferenceDefect.UNKNOWN_COMMAND, "devops scan", "gitleaks"), + ), + ( + ["scan", "complexity", TARGET, "--max-nesting-depth", NUMBER], + _finding( + CommandReferenceDefect.UNKNOWN_OPTION, + "devops scan complexity", + "--max-nesting-depth", + ), + ), + ( + ["argo", "cd", "apps", "list", "--json"], + _finding(CommandReferenceDefect.UNKNOWN_OPTION, "devops argo cd apps list", "--json"), + ), + ( + ["k8s", "audit", "stray"], + _finding(CommandReferenceDefect.UNEXPECTED_ARGUMENT, "devops k8s audit", "stray"), + ), + ( + ["benchmark", "--suite"], + _finding(CommandReferenceDefect.UNKNOWN_COMMAND, "devops", "benchmark"), + ), + ( + ["ai", "benchmark", "--suite", "--experiment", "x"], + _finding(CommandReferenceDefect.UNKNOWN_OPTION, "devops ai benchmark", "--experiment"), + ), + ( + ["lint", "--nope"], + _finding(CommandReferenceDefect.UNKNOWN_OPTION, "devops lint", "--nope"), + ), + ( + ["scan", "gitleaks", "--help"], + _finding(CommandReferenceDefect.UNKNOWN_COMMAND, "devops scan", "gitleaks"), + ), + ( + ["scan", "complexity", "--max-nesting-depth", "--help"], + _finding( + CommandReferenceDefect.UNKNOWN_OPTION, + "devops scan complexity", + "--max-nesting-depth", + ), + ), + ], +) +def test_a_defective_command_line_is_named_where_it_breaks( + tokens: list[ArgvToken], expected: CommandReferenceFinding +) -> None: + """Verify an unknown command, unknown option or extra argument is reported at its depth.""" + assert resolve_devops_argv(tokens) == expected + + +@pytest.mark.parametrize( + "tokens", + [ + ["argo", "cd", "apps", "list"], + ["scan", "complexity", TARGET, "--max-complexity", NUMBER, "--max-indent", NUMBER], + ["ai", "benchmark", "--suite", "--models", TARGET, "--dry-run"], + ["ai", "benchmark", "--type", "embedding", "--samples", NUMBER], + ["repos", "sync"], + ["ci"], + ["lint"], + ["--dry-run", "repos", "list"], + ["k8s", "chaos", TARGET, "--namespace", TARGET, "--dry-run"], + ], +) +def test_a_real_command_line_resolves(tokens: list[ArgvToken]) -> None: + """Verify command lines the CLI accepts, at every depth, report nothing.""" + assert resolve_devops_argv(tokens) is None + + +def test_a_placeholder_that_fails_conversion_does_not_hide_an_extra_argument() -> None: + """Verify a placeholder an integer option rejects still lets the leftovers be checked. + + Click converts option values before it looks for extra arguments, so a strict parse + stops at the placeholder; the lenient parse still finds the stray literal. + """ + tokens: list[ArgvToken] = ["scan", "complexity", TARGET, "--max-complexity", NUMBER, "stray"] + + assert resolve_devops_argv(tokens) == _finding( + CommandReferenceDefect.UNEXPECTED_ARGUMENT, "devops scan complexity", "stray" + ) + + +@pytest.mark.parametrize( + "tokens", + [ + ["ai", ArgvPlaceholder(expression="subcommand")], + [ArgvPlaceholder(expression="group"), "list"], + ["config", "output", ArgvPlaceholder(expression="flag")], + ], +) +def test_a_placeholder_is_never_reported(tokens: list[ArgvToken]) -> None: + """Verify a runtime value where a command or an extra argument sits is inconclusive. + + A placeholder can stand for anything, `--json` included, so only literal tokens are + reported. + """ + assert resolve_devops_argv(tokens) is None + + +def test_an_option_missing_its_value_is_not_an_extra_argument() -> None: + """Verify a known option left without its value does not blame an earlier literal. + + Click's parser stops at the option, before it binds the positionals, so what that parse + leaves over is not a set of extra arguments. + """ + assert resolve_devops_argv(["scan", "sast", ".", "--config"]) is None + + +@pytest.mark.parametrize( + "tokens", + [ + [], + ["--help"], + ["--version"], + ["k8s"], + ["scan", "--help"], + ["scan", "sast", "--help"], + ["scan", "sast", ".", "-h"], + ["scan", "--show-completion", "bash"], + ], +) +def test_an_eager_option_or_a_bare_group_resolves_silently( + tokens: list[ArgvToken], capsys: pytest.CaptureFixture[str] +) -> None: + """Verify `--help`, `--version`, a completion option or a bare group prints nothing. + + An eager option's callback prints and exits as the option is parsed, and a group given + nothing prints its help. None of them names a missing command or option, so the walk + stops there instead of parsing them. + """ + finding = resolve_devops_argv(tokens) + + assert (finding, capsys.readouterr().out) == (None, "") + + +def test_a_completion_option_never_installs_completion() -> None: + """Verify `--install-completion` resolves without writing a completion script or profile.""" + with patch("typer.completion.install", side_effect=AssertionError("installed")) as install: + finding = resolve_devops_argv(["scan", "--install-completion", "bash"]) + + assert (finding, install.called) == (None, False) + + +def test_resolving_parses_without_invoking_or_spawning() -> None: + """Verify a destructive command line resolves without its callback or a subprocess. + + Importing a command module may spawn (GitPython runs `git version` on import), and + `devops docs check` imports every module to generate the docs anyway, so the module is + built before the guard and only the resolving runs inside it. + """ + module_click_command(_COMMAND_SPECS["k8s"][0]) + with ( + patch("devops_cli.k8s.chaos.execute_chaos_experiment") as experiment, + patch("subprocess.Popen", side_effect=AssertionError("no subprocess")) as popen, + ): + finding = resolve_devops_argv(["k8s", "chaos", "pod-kill", "--namespace", "default"]) + + assert (finding, experiment.called, popen.called) == (None, False, False) + + +def test_a_finding_describes_itself() -> None: + """Verify each defect reads as the token and the command it was given to.""" + assert [ + _finding(defect, "devops scan", "x").describe() for defect in CommandReferenceDefect + ] == [ + "unknown command 'x' under 'devops scan'", + "unknown option 'x' for 'devops scan'", + "unexpected extra argument 'x' for 'devops scan'", + ] + + +def test_a_placeholder_renders_as_its_expression() -> None: + """Verify a placeholder token reads as the source expression it replaced.""" + assert str(ArgvPlaceholder(expression="str(limit)")) == "" diff --git a/tests/test_docs_mcp_argv_collector.py b/tests/test_docs_mcp_argv_collector.py new file mode 100644 index 0000000000..7df6b9e328 --- /dev/null +++ b/tests/test_docs_mcp_argv_collector.py @@ -0,0 +1,175 @@ +"""Tests for collecting the MCP server's `devops` argv lists and resolving them statically.""" + +from __future__ import annotations + +from pathlib import Path +from unittest.mock import patch + +from typer.testing import CliRunner + +from devops_cli.commands.docs import app as docs_app +from devops_cli.docs.command_resolver import ArgvPlaceholder, module_click_command +from devops_cli.docs.generator import DocGenerator +from devops_cli.docs.mcp_argv_collector import ( + DevopsArgvReference, + collect_devops_argv_references, + collect_mcp_server_argv_references, + describe_unresolved_references, +) +from devops_cli.main import _COMMAND_SPECS + +FIXTURE_SOURCE = """\ +def ai_architecture(target: str = "src") -> str: + return _run(["uv", "run", "devops", "analyze", "architecture", target]) + + +def scan_complexity(target: str = "src", depth: int = 5) -> str: + cmd = ["uv", "run", "devops", "scan", "complexity", target] + cmd.extend(["--max-nesting-depth", str(depth)]) + return _run(cmd) + + +def repos_sync(all_repos: bool = False, branch: str = "") -> str: + cmd = ["uv", "run", "devops", "repos", "sync"] + if all_repos: + cmd.append("--all") + if branch: + cmd.append(branch) + cmd.extend(extra_flags) + cmd.append("list") + return _run(cmd) + + +def two_commands() -> str: + cmd = ["uv", "run", "devops", "repos", "sync"] + cmd.append("--no-pull") + cmd = ["uv", "run", "devops", "repos", "sync"] + cmd.append("--dry-run") + return _run(cmd) + + +def not_devops() -> str: + return _run(["uv", "run", "pytest", "-q"]) + + +def scan_sast(config: str) -> str: + cmd = ["uv", "run", "devops", "scan", "sast", "."] + cmd.append("--config") + cmd.append(config) + return _run(cmd) +""" + +FIXTURE_REFERENCES = collect_devops_argv_references(FIXTURE_SOURCE, "fixture.py") + + +def _reference(line: int, owner: str, *tokens: str | ArgvPlaceholder) -> DevopsArgvReference: + return DevopsArgvReference(path="fixture.py", line=line, owner=owner, tokens=tokens) + + +def test_argv_lists_and_everything_added_to_them_are_collected() -> None: + """Verify each `uv run devops` list keeps its literals, a placeholder per runtime value, + and every token appended or extended onto the variable it is assigned to, in order. + + A non-literal append or extend becomes a placeholder like a non-literal element, so an + option and its value appended in two calls stay together. + """ + assert FIXTURE_REFERENCES == [ + _reference( + 2, "ai_architecture", "analyze", "architecture", ArgvPlaceholder(expression="target") + ), + _reference( + 6, + "scan_complexity", + "scan", + "complexity", + ArgvPlaceholder(expression="target"), + "--max-nesting-depth", + ArgvPlaceholder(expression="str(depth)"), + ), + _reference( + 12, + "repos_sync", + "repos", + "sync", + "--all", + ArgvPlaceholder(expression="branch"), + ArgvPlaceholder(expression="extra_flags"), + "list", + ), + _reference(23, "two_commands", "repos", "sync", "--no-pull"), + _reference(25, "two_commands", "repos", "sync", "--dry-run"), + _reference( + 35, + "scan_sast", + "scan", + "sast", + ".", + "--config", + ArgvPlaceholder(expression="config"), + ), + ] + + +def test_unresolved_fixture_argv_are_reported_with_their_source_line() -> None: + """Verify an unknown command names `analyze` and an unknown option names its line. + + The option and value appended in two calls, at line 35, resolve. + """ + assert describe_unresolved_references(FIXTURE_REFERENCES) == [ + "fixture.py:2 ai_architecture: 'devops analyze architecture ': " + "unknown command 'analyze' under 'devops'.", + "fixture.py:6 scan_complexity: " + "'devops scan complexity --max-nesting-depth ': " + "unknown option '--max-nesting-depth' for 'devops scan complexity'.", + "fixture.py:12 repos_sync: 'devops repos sync --all list': " + "unknown option '--all' for 'devops repos sync'.", + ] + + +def test_every_mcp_server_argv_resolves() -> None: + """Verify every literal argv list in the MCP server names a real command and options. + + The lists are resolved, not run: neither the MCP runner nor a subprocess is reached. + 168 is every list once `ai_architecture`, the 169th, was deleted. Importing a command + module may spawn (GitPython runs `git version` on import), and `devops docs check` has + imported every module to generate the docs before it resolves, so each module's command + tree is built before the guard and only collecting and resolving run inside it. + """ + for module_path, _ in _COMMAND_SPECS.values(): + module_click_command(module_path) + with ( + patch("devops_cli.ai.mcp.server._run_mcp_cmd") as mcp_runner, + patch("subprocess.Popen", side_effect=AssertionError("no subprocess")) as popen, + ): + references = collect_mcp_server_argv_references() + unresolved = describe_unresolved_references(references) + + assert ( + len(references) >= 168, + {reference.path for reference in references}, + unresolved, + mcp_runner.called, + popen.called, + ) == (True, {"src/devops_cli/ai/mcp/server.py"}, [], False, False) + + +def test_docs_check_reports_an_unresolved_mcp_argv(tmp_path: Path) -> None: + """Verify `devops docs check` fails on an MCP argv that names no real command.""" + with ( + patch.object(DocGenerator, "generate_all_docs", return_value={}), + patch( + "devops_cli.docs.mcp_argv_collector.collect_mcp_server_argv_references", + return_value=FIXTURE_REFERENCES[:1], + ), + ): + ok, errors = DocGenerator().check_docs(tmp_path, check_readme_table=False) + result = CliRunner().invoke( + docs_app, ["check", "--no-check-readme", "--output-dir", str(tmp_path)] + ) + + assert (ok, errors, result.exit_code, "fixture.py:2" in result.output) == ( + False, + describe_unresolved_references(FIXTURE_REFERENCES[:1]), + 1, + True, + ) diff --git a/tests/test_fastmcp_contracts.py b/tests/test_fastmcp_contracts.py index c247e890ad..b1f2be4d87 100644 --- a/tests/test_fastmcp_contracts.py +++ b/tests/test_fastmcp_contracts.py @@ -99,7 +99,6 @@ def test_fastmcp_tools_registration() -> None: "ai_repomap", "ai_diagram", "ai_test_gen", - "ai_architecture", "ai_harness_status", "ai_subagent_offload", "ai_chaos_model", diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 6ed952850d..f7f78341b1 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -276,7 +276,6 @@ def test_mcp_tool_delegations(self) -> None: release_status, repos_list, repos_status, - repos_sync, scan_uv_audit, security_intel_network, security_intel_package, @@ -303,7 +302,6 @@ def test_mcp_tool_delegations(self) -> None: ): assert repos_list() == "mock_output" assert repos_status() == "mock_output" - assert repos_sync(all_repos=True) == "mock_output" assert ssh_status() == "mock_output" assert ssh_audit() == "mock_output" assert k8s_pods(namespace="default") == "mock_output" @@ -348,14 +346,10 @@ def test_mcp_tool_delegations(self) -> None: def test_expanded_mcp_tools_and_prompts_execution() -> None: """Verify execution of newly added security, k8s, vault, benchmark, and git governance MCP tools.""" from devops_cli.ai.mcp.server import ( - ai_architecture, ai_harness_status, ai_subagent_offload, - benchmark_embeddings, branches_list, code_review_prompt, - k8s_audit, - k8s_chaos, k8s_diff_helm, k8s_lint, k8s_validate, @@ -363,11 +357,7 @@ def test_expanded_mcp_tools_and_prompts_execution() -> None: pr_list, pr_monitor, scan_aibom, - scan_checkov, - scan_complexity, - scan_gitleaks, scan_sbom, - scan_semgrep, scan_trivy, security_audit_prompt, vault_set, @@ -377,16 +367,10 @@ def test_expanded_mcp_tools_and_prompts_execution() -> None: with patch("devops_cli.ai.mcp.server._run_mcp_cmd", return_value="mock_output"): # Security scanners assert scan_trivy(".") == "mock_output" - assert scan_gitleaks(".") == "mock_output" - assert scan_semgrep(".") == "mock_output" - assert scan_checkov(".") == "mock_output" - assert scan_complexity("src") == "mock_output" assert scan_aibom(".") == "mock_output" assert scan_sbom(".") == "mock_output" # Kubernetes operations - assert k8s_chaos("validate", "pod-failure") == "mock_output" - assert k8s_audit("default") == "mock_output" assert k8s_lint(".") == "mock_output" assert k8s_validate(".") == "mock_output" assert k8s_diff_helm("argocd", "argo/argo-cd") == "mock_output" @@ -395,9 +379,7 @@ def test_expanded_mcp_tools_and_prompts_execution() -> None: assert vault_set("secret/data/app", ["FOO=bar"]) == "mock_output" assert vault_sync("secret/data/app") == "mock_output" - # AI & Benchmark - assert benchmark_embeddings(provider="ollama", model="bge-m3") == "mock_output" - assert ai_architecture(target="src") == "mock_output" + # AI assert ai_harness_status() == "mock_output" assert ai_subagent_offload(repo="src", symbol="Foo") == "mock_output" with pytest.raises(ValidationError, match="Cannot specify both 'symbol' and 'pattern'"): @@ -420,6 +402,101 @@ def test_expanded_mcp_tools_and_prompts_execution() -> None: assert "src" in sec_p +def test_repointed_mcp_entry_points_pass_real_command_lines() -> None: + """Verify the tools and resources that called missing commands or options now pass the + argv of the real command, with only options it declares.""" + from devops_cli.ai.mcp.server import ( + benchmark_embeddings, + benchmark_suite, + get_argo_fleet_status_resource, + get_workspace_resource, + k8s_audit, + k8s_chaos, + repos_sync, + scan_checkov, + scan_complexity, + scan_gitleaks, + scan_semgrep, + ) + + calls = { + "repos_sync": repos_sync, + "scan_gitleaks": lambda: scan_gitleaks("."), + "scan_semgrep": lambda: scan_semgrep("."), + "scan_checkov": lambda: scan_checkov("."), + "scan_complexity": lambda: scan_complexity("src"), + "k8s_chaos": k8s_chaos, + "k8s_chaos_live": lambda: k8s_chaos("pod-kill", "llm", dry_run=False), + "k8s_audit": k8s_audit, + "benchmark_embeddings": lambda: benchmark_embeddings(provider="ollama", model="bge-m3"), + "benchmark_suite": lambda: benchmark_suite(models="m1,m2", dataset="feedback.jsonl"), + "resource://workspace/status": get_workspace_resource, + "resource://argo/fleet/status": get_argo_fleet_status_resource, + } + with patch("devops_cli.ai.mcp.server._run_mcp_cmd", return_value="output") as runner: + argv = {name: (call(), runner.call_args.args[0][3:])[1] for name, call in calls.items()} + + assert argv == { + "repos_sync": ["repos", "sync"], + "scan_gitleaks": ["scan", "secrets", "."], + "scan_semgrep": ["scan", "sast", ".", "--config", "auto"], + "scan_checkov": ["scan", "iac", "."], + "scan_complexity": [ + "scan", + "complexity", + "src", + "--max-complexity", + "10", + "--max-indent", + "5", + ], + "k8s_chaos": ["k8s", "chaos", "pod-failure", "--namespace", "default", "--dry-run"], + "k8s_chaos_live": ["k8s", "chaos", "pod-kill", "--namespace", "llm"], + "k8s_audit": ["k8s", "audit"], + "benchmark_embeddings": [ + "ai", + "benchmark", + "--type", + "embedding", + "--provider", + "ollama", + "--models", + "bge-m3", + "--samples", + "10", + ], + "benchmark_suite": [ + "ai", + "benchmark", + "--suite", + "--models", + "m1,m2", + "--provider", + "ollama", + "--dataset", + "feedback.jsonl", + "--dry-run", + ], + "resource://workspace/status": ["repos", "list"], + "resource://argo/fleet/status": ["argo", "cd", "apps", "list"], + } + + +def test_ai_architecture_tool_is_removed() -> None: + """Verify the tool that ran the never-existing `devops analyze architecture` is gone, + with no shim left behind.""" + import devops_cli.ai.mcp as mcp_package + from devops_cli.ai.mcp import server + + tool_names = {tool.name for tool in asyncio.run(mcp._list_tools())} + + assert ( + "ai_architecture" in tool_names, + hasattr(server, "ai_architecture"), + "ai_architecture" in mcp_package.__all__, + ) == (False, False, False) + + def test_mcp_helpers_and_error_branches() -> None: """Verify _run_mcp_cmd timeout, error exit code, _validate_mcp_arg, and review tool calls.""" # 1. _validate_mcp_arg @@ -472,7 +549,6 @@ def test_mcp_integer_bounds_validation() -> None: """Verify integer bounds validation rejecting non-positive or negative values.""" from devops_cli.ai.mcp.server import ( _validate_mcp_int_bound, - ai_architecture, pr_checks, pr_list, pr_monitor, @@ -517,9 +593,6 @@ def test_mcp_integer_bounds_validation() -> None: with pytest.raises(ValidationError, match="limit"): pr_list(limit=0) - with pytest.raises(ValidationError, match="max_depth"): - ai_architecture(target="src", max_depth=0) - class TestValkeyMcpTools: """Tests for Valkey FastMCP tools and system resource.""" diff --git a/tests/test_pydantic_ai_mcp.py b/tests/test_pydantic_ai_mcp.py index 437fb1566a..b54b23900b 100644 --- a/tests/test_pydantic_ai_mcp.py +++ b/tests/test_pydantic_ai_mcp.py @@ -72,7 +72,7 @@ async def test_create_devops_mcp_toolset() -> None: # Eager domains are offered without a round trip. assert "review_path" in tool_names assert "config_show" in tool_names - assert "ai_architecture" in tool_names + assert "ai_repomap" in tool_names # Gated domains appear once hydrated, and are absent before. gated = {