From 3a268980e4a5fc81e354874a91b32a932d1a6dda Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 3 Oct 2026 14:32:06 +0000 Subject: [PATCH] feat(cli): enforce the complexity cap with ruff C901 and an inline baseline that only shrinks (#586) --- .pre-commit-config.yaml | 4 +- AGENTS.md | 2 +- CONTRIBUTING.md | 2 +- changelog.d/586.md | 22 + docs/ROUTINE_TASKS.md | 2 +- docs/SDLC.md | 2 +- ...86-cyclomatic-complexity-debt-reduction.md | 135 +++- pyproject.toml | 13 +- src/devops_cli/ai/__init__.py | 2 +- src/devops_cli/ai/agents/__init__.py | 2 +- src/devops_cli/ai/agents/agent.py | 8 +- src/devops_cli/ai/analyze/outlines.py | 4 +- src/devops_cli/ai/analyze/scanner.py | 2 +- .../ai/benchmark/document_chunker.py | 2 +- .../ai/benchmark/embedding_runner.py | 2 +- src/devops_cli/ai/client/ollama.py | 2 +- src/devops_cli/ai/context_budget.py | 2 +- src/devops_cli/ai/ext_langchain.py | 2 +- src/devops_cli/ai/gateway_bench.py | 6 +- src/devops_cli/ai/gateway_tune.py | 2 +- src/devops_cli/ai/harness/agents.py | 2 +- src/devops_cli/ai/harness/compaction.py | 4 +- src/devops_cli/ai/harness/docs.py | 2 +- src/devops_cli/ai/harness/filesystem.py | 2 +- src/devops_cli/ai/harness/memory.py | 2 +- src/devops_cli/ai/harness/planning.py | 2 +- src/devops_cli/ai/harness/shell.py | 2 +- src/devops_cli/ai/harness/skills.py | 2 +- src/devops_cli/ai/harness/workflow.py | 6 +- src/devops_cli/ai/mcp/server.py | 6 +- src/devops_cli/ai/output/__init__.py | 2 +- src/devops_cli/ai/rag/indexer.py | 2 +- .../ai/review/common_hallucinations.py | 2 +- src/devops_cli/ai/review/pipeline.py | 2 +- src/devops_cli/ai/review/runner.py | 2 +- src/devops_cli/ai/review/verification.py | 2 +- src/devops_cli/ai/review_schema.py | 2 +- src/devops_cli/commands/ai.py | 2 +- src/devops_cli/commands/analyze.py | 4 +- src/devops_cli/commands/config.py | 4 +- src/devops_cli/commands/devcontainer.py | 6 +- src/devops_cli/commands/docs.py | 2 +- src/devops_cli/commands/gh.py | 2 +- .../commands/k8s/cluster_context.py | 2 +- src/devops_cli/commands/test_cmd.py | 4 +- src/devops_cli/config/constants.py | 58 ++ src/devops_cli/config/defaults.py | 3 + src/devops_cli/core/process.py | 2 +- src/devops_cli/core/serialization.py | 2 +- src/devops_cli/core/validation.py | 2 +- src/devops_cli/k8s/logql.py | 2 +- src/devops_cli/output/console.py | 2 +- src/devops_cli/security/aibom.py | 2 +- .../security/reference_extractor.py | 20 +- .../security/structural_invariants.py | 102 ++- tests/test_ai_gateway_tune.py | 2 +- tests/test_architectural_invariants.py | 601 +++++++++++++++++- tests/test_exceptions.py | 4 +- tests/test_sandbox_metrics.py | 2 +- tests/test_sandbox_probe.py | 2 +- tests/test_structural_invariant_hook.py | 48 +- 61 files changed, 956 insertions(+), 186 deletions(-) create mode 100644 changelog.d/586.md diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4209a6222c..9fb1b20f46 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -47,8 +47,8 @@ repos: # Pure-stdlib AST walk over the staged files: no devops_cli import, because loading # the package costs about five seconds before a single file is read, and a # commit-time gate has to cost less than the commit. Blocks on nesting depth, which - # the tree currently satisfies; complexity is reported without blocking, since 240 - # functions breach that cap today and nothing enforces it. + # the tree currently satisfies. Complexity is not checked here: it is Ruff's C901, + # run by the ruff-check hook above. - id: structural-invariants name: AST structural invariants (nesting depth) entry: uv run python3 -m devops_cli.security.structural_invariants diff --git a/AGENTS.md b/AGENTS.md index 2ed31dab0d..9ab98baa42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ This document provides foundational context, architectural principles, and opera - **High Reliability & Quality First**: Build robust, resilient workstation automation and developer tooling with defensive error handling, bounded timeouts, and zero tolerance for flaky tests. - **Poetic Conciseness, Expressive Integration & Zero Boilerplate**: - The codebase must read as an expressive, poetically concise integration of tools, libraries, docs, AI, and automation rather than a sprawl of procedural loops or boilerplate. - - **Strict Complexity & Nesting Caps**: Strictly enforce cyclomatic complexity $\le 10$ and maximum nesting depth $\le 5$ (< 6 indentation levels) project-wide across all functions, closures, and blocks. Continuous compliance is validated by `devops scan complexity` and automated architectural invariant gates ([`tests/test_architectural_invariants.py`](tests/test_architectural_invariants.py)). + - **Strict Complexity & Nesting Caps**: Cyclomatic complexity $\le 10$ is Ruff `C901` (standard McCabe), run by `uv run devops ci` and the pre-commit `ruff-check` hook. Functions over the cap when it was turned on carry `# noqa: C901`. RUF100 removes a marker once its function is fixed, and `test_c901_suppressions_stay_under_the_ceiling` ([`tests/test_architectural_invariants.py`](tests/test_architectural_invariants.py)) keeps the count from growing. A function over the cap is decomposed, never suppressed: `test_the_complexity_cap_has_no_escape` rejects every other committed way past it, including Ruff's own `# ruff: ignore[C901]` and `# ruff: disable[C901]` comments and ignore files that hide a source. Nesting depth $\le 5$ (< 6 indentation levels) is enforced by the `structural-invariants` pre-commit hook and `test_no_excessive_nesting_in_src`. `devops scan complexity` reports a different, in-house count and does not gate. - **Structural Tuple Equality Consolidation in Test Suites (Mitigating Assertion Sprawl)**: - Under Python AST semantics, every `assert expr` statement compiles to `if not (expr): raise AssertionError`, adding $+1$ to McCabe cyclomatic complexity $M$. - When asserting multiple object attributes or properties in test suites, developers and AI agents **MUST CONSOLIDATE LINEAR ASSERTIONS INTO STRUCTURAL TUPLE EQUALITY CHECKS** (`assert (actual_a, actual_b, actual_c) == (expected_a, expected_b, expected_c)`) or collection predicates (`assert all(...)`). This prevents purely linear test code from breaching the $M \le 10$ complexity cap while fully preserving Pytest element-level diff diagnostics. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a1c94ab713..fa2a0b444c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,7 +10,7 @@ DevOps CLI follows an uncompromising quality-first, test-driven engineering cult - **Test-First Implementation (TDD)**: All features, fixes, and refactorings **must** have tests written first. Tests serve as the executable documentation of public interfaces, edge cases, and architectural boundaries. - **Strict Complexity & Nesting Caps**: - - Cyclomatic complexity $\le 10$ across all functions and closures (`tests/test_architectural_invariants.py`). + - Cyclomatic complexity $\le 10$ is Ruff `C901` (standard McCabe), run by `uv run devops ci` and the pre-commit `ruff-check` hook. Functions over the cap when it was turned on carry `# noqa: C901`, and `tests/test_architectural_invariants.py` keeps their count from growing; `devops scan complexity` reports a different, in-house count and does not gate. - Maximum nesting depth $\le 5$ (< 6 indentation levels) project-wide. - Decompose multi-step procedures into dedicated single-responsibility helpers and pure predicates. - **Strongly Typed Domain Exceptions**: diff --git a/changelog.d/586.md b/changelog.d/586.md new file mode 100644 index 0000000000..cb9001673f --- /dev/null +++ b/changelog.d/586.md @@ -0,0 +1,22 @@ +### Added +- **Ruff Enforces the Complexity Cap of 10 (`pyproject.toml`, `uv run devops ci`, the `ruff-check` pre-commit hook)**: + - `pyproject.toml` selects `C901` and sets `[tool.ruff.lint.mccabe] max-complexity = 10`, so a function over the cap (standard McCabe) fails `ruff check` in `devops ci`, in the `ruff-check` pre-commit hook and in GitHub CI. `AGENTS.md` called the cap strictly enforced, but nothing checked it: `C901` was not selected, and the `structural-invariants` hook only printed a note (#586). + - The 66 functions over the cap when it was turned on, 65 in `src/` and 1 in `tests/`, carry a `# noqa: C901` marker. `ruff check --select C901 --add-noqa` wrote the markers in one run, and no function was decomposed in this change. `RUF100` reports a marker once its function is back under the cap, and the default `devops ci --fix` removes it. `PGH004` bans the blanket `noqa` that would hide `C901` without naming it (#586). + - With `RUF100` selected, nine `noqa` codes that did nothing are gone. Five name rules the project does not select: `S310` three times in `ai/gateway_bench.py`, `S603` in `ai/gateway_tune.py` and `S102` in `tests/test_ai_gateway_tune.py`. Four sit where Ruff raises nothing: `F401` twice in `tests/test_exceptions.py`, and `N802` in `tests/test_sandbox_metrics.py` and `tests/test_sandbox_probe.py`. The `# nosec` comments that Bandit reads stay, and the reason "the script under test" stays as a plain comment (#586). + - `test_c901_suppressions_stay_under_the_ceiling` counts the `C901` markers in `src/` and `tests/`, in every spelling Ruff honours, including a form feed or a no-break space where a space would go. It fails when the count exceeds `DEFAULT_C901_SUPPRESSION_CEILING` (66), names the files that carry markers, and says to decompose the function rather than raise the ceiling. A change that removes markers lowers the ceiling in the same change (#586). + - `test_the_complexity_cap_has_no_escape` fails when `[tool.ruff]` or `[tool.ruff.lint]` holds a key outside its allowlist. The allowlists keep out Ruff's deprecated top-level `per-file-ignores` and `extend-ignore`, as well as `include`, `extend`, `extend-exclude` and `lint.exclude` (#586). + - The same test fails when `exclude` is not `["repos"]`, when `C901`, `RUF100` or `PGH004` is not enforced or a per-file ignore waives it, or when `max-complexity` is not 10. A rule counts as enforced only when `select` names it by its own code, because Ruff reads `C9` as `C90`, so `C90` selected with `C9` ignored turns `C901` off (#586). + - It also fails when a file under `src/` or `tests/` has a file-level exemption, when a `ruff.toml`, `.ruff.toml` or `pyproject.toml` sits under those directories, or when a `ruff.toml` or `.ruff.toml` sits beside `pyproject.toml` (#586). + - It fails when a file under `src/` or `tests/` carries one of Ruff's own suppression comments naming `C901`: a `# ruff: ignore[C901]`, a `# ruff: disable[C901]` that holds until its `enable` or the end of the file, or a `# ruff: file-ignore[C901]`. One such comment hides any number of functions and leaves no marker to count, so these comments are banned rather than counted (#586). + - It fails when an `.ignore` or `.gitignore` sits under `src/` or `tests/`, when an `.ignore` sits beside `pyproject.toml`, or when the project's `.gitignore` matches a source file there. Ruff skips the files an ignore file lists. Ignore files outside the checkout differ per machine and never reach GitHub CI's clean checkout. No test runs a Ruff process (#586). + +### Changed +- **The `structural-invariants` Hook Checks Nesting Only (`.pre-commit-config.yaml`, `devops_cli.security.structural_invariants`)**: + - The hook no longer counts complexity or prints its "Not blocking" complexity note, because complexity is now Ruff's `C901`. `breaches` and `check_structural_invariants` return only the nesting breaches and take no `max_complexity`, `measure` returns a function's nesting depth, and `MAX_COMPLEXITY` is gone. Nesting is measured as before: the old and new measures agree on all 14,749 functions in `src/` and `tests/` (#586). + - `measure` walks a function with its own stack instead of recursing, so a long expression such as a 3,000-term sum is measured instead of stopping the hook with a `RecursionError` traceback. The released hook already failed that way at 3,000 terms. A parser stack overflow is reported as a file the hook could not parse (#586). + - Two tests are removed. `test_complexity_is_reported_without_blocking` started a hook subprocess, and `test_filesystem_get_tools_complexity` guarded a function that `C901` now covers (#586). + +### Fixed +- **The Docs Name What Enforces the Complexity Cap (`AGENTS.md`, `CONTRIBUTING.md`, `docs/SDLC.md`, `docs/ROUTINE_TASKS.md`)**: + - These four files said `devops scan complexity` and the architectural invariant tests enforced the cap of 10. They now say that Ruff `C901` enforces it through `uv run devops ci` and the pre-commit hook, and that a test keeps the number of functions carrying markers from growing. `AGENTS.md` adds that a function over the cap is decomposed, never suppressed, and that `test_the_complexity_cap_has_no_escape` rejects Ruff's own `ruff:` suppression comments and ignore files that hide a source (#586). + - They also say that the `structural-invariants` hook and `test_no_excessive_nesting_in_src` enforce nesting, and that `devops scan complexity` reports a different, in-house count and does not gate (#586). diff --git a/docs/ROUTINE_TASKS.md b/docs/ROUTINE_TASKS.md index ef1810a1b7..b53c7e129b 100644 --- a/docs/ROUTINE_TASKS.md +++ b/docs/ROUTINE_TASKS.md @@ -52,7 +52,7 @@ The following matrix categorizes all project routine tasks by operational layer, | **Security & Audits** | Dependency Security Audit | Weekly / Pre-Release | `uv run devops ci audit` (`uv audit`) | Scans installed packages for known vulnerabilities | 0 known vulnerabilities | | **Security & Audits** | Static Security Scan (SAST) | Weekly / Pre-Release | `uv run devops ci security` (`bandit`) | Static security scan for code vulnerabilities | 0 high/medium issues identified | | **Security & Audits** | Kubernetes Manifest Scans | Per Manifest Change | `devops scan [kubelinter\|popeye\|pluto\|trivy]` | Validates manifests against K8s security best practices | Zero deprecated APIs or misconfigurations | -| **Security & Audits** | Codebase Deduplication & Invariant Audit | Weekly / Pre-PR | `devops scan complexity` && `pytest tests/test_architectural_invariants.py` | Enforces complexity <= 10, nesting <= 5, and shared helper adoption | Zero invariant violations | +| **Security & Audits** | Codebase Deduplication & Invariant Audit | Weekly / Pre-PR | `uv run ruff check .` && `pytest tests/test_architectural_invariants.py` | Ruff `C901` enforces complexity <= 10; the tests enforce nesting <= 5, the `C901` marker ceiling and shared helper adoption | Zero invariant violations | | **Observability & Diagnostics** | Command Output, Logs, Metrics & Trace Audit | Continuous / On Execution | `devops telemetry status` / `devops telemetry logfire-status` | Comprehensive review of command outputs, application logs (`.data/logs/`), metrics, and tracing spans for latency, misconfigurations, and warnings | Nominal latencies, zero unhandled errors/warnings | | **Workspace & Sync** | DevContainer Lifecycle Hooks | Daily / On Start | `devops devcontainer run-lifecycle --post-start` | Cross-platform container initialization tasks | All lifecycle tasks complete successfully | | **Workspace & Sync** | Multi-Repo Synchronization | Daily / On Demand | `devops repos sync` / `devops repos status` | Pulls upstream changes across all managed repos | All repositories up to date | diff --git a/docs/SDLC.md b/docs/SDLC.md index 74aa5ec08a..b196cb6eb2 100644 --- a/docs/SDLC.md +++ b/docs/SDLC.md @@ -126,7 +126,7 @@ graph TD 1. **Cyclomatic Complexity $\le 10$ & Nesting Depth $\le 5$**: - Every function, method, and code block must maintain cyclomatic complexity $\le 10$ and nesting depth $\le 5$ (< 6 indentation levels). - Decompose multi-step branching into pure predicate helpers, table-driven dispatch dictionaries, or functional pipelines (`functools`, `itertools`, `pathlib`). - - Validated continuously by `devops scan complexity` and `tests/test_architectural_invariants.py`. + - Complexity is Ruff `C901` (standard McCabe), run by `uv run devops ci` and the pre-commit `ruff-check` hook; functions over the cap when it was turned on carry `# noqa: C901`, and `tests/test_architectural_invariants.py` keeps their count from growing. Nesting is enforced by the `structural-invariants` pre-commit hook and `test_no_excessive_nesting_in_src`. `devops scan complexity` reports a different, in-house count and does not gate. 2. **Standardized Domain Exception Taxonomy**: - Raising bare Python built-ins (`ValueError`, `RuntimeError`, `TypeError`, `Exception`) in domain logic is strictly prohibited. - All domain errors must inherit from `DevOpsCLIError` under `src/devops_cli/exceptions/`, supplying an exit code, machine-readable code (`CONST_ERROR_CODE_*`), and contextual details. diff --git a/docs/agent/tasks/task-586-cyclomatic-complexity-debt-reduction.md b/docs/agent/tasks/task-586-cyclomatic-complexity-debt-reduction.md index 18023c68b1..86dbebea2e 100644 --- a/docs/agent/tasks/task-586-cyclomatic-complexity-debt-reduction.md +++ b/docs/agent/tasks/task-586-cyclomatic-complexity-debt-reduction.md @@ -1,20 +1,127 @@ -# Task 586: Cyclomatic Complexity Debt Reduction +# Task: Ruff Enforces the Complexity Cap of 10 (#586) **Issue**: [#586](https://github.com/dan-petty/devops-cli/issues/586) -**Status**: Backlog -**Milestone**: `v0.2.24` -**Priority**: `priority/p1-high` -**Scope**: `type/feature`, `scope/cli`, `priority/p1-high` +**Status**: Done +**Milestone**: v0.2.25 +**Priority**: priority/p1-high +**Scope**: scope/cli ---- +## Description +`AGENTS.md:14` said cyclomatic complexity ≤ 10 was strictly enforced project-wide, validated by `devops scan complexity` and the architectural invariant tests. Nothing enforced it. `pyproject.toml` did not select `C901`, `devops ci` had no complexity step, `devops scan complexity` exits 0 on a breach, and the `structural-invariants` hook only printed complexity breaches as a note. -## 1. Description & Objectives +Owner decision D1 makes Ruff's `C901` (standard McCabe) the enforced definition. It comes with an inline baseline, `RUF100` to remove a marker once its function is fixed, `PGH004` against blanket `noqa`, a ceiling on `C901` markers that may only go down, and a meta-test that pins `max-complexity` and forbids `C901` in per-file ignores. It uses no radon, no lizard and no new dependency. No function is decomposed here. -AGENTS.md states complexity $\le 10$ as a project-wide invariant validated continuously. It is not: 240 functions in `src/` breach it and no gate checks it. The invariant is aspirational, and stating it as enforced is worse than stating it as a target, because reviewers and agents trust it. +A review of the first version found committed ways past the cap that the tests missed. Ruff 0.16's own `# ruff: ignore[C901]`, `# ruff: disable[C901]` and `# ruff: file-ignore[C901]` comments hide functions without a marker. A marker or file-level exemption with a form feed or a no-break space in place of a space went uncounted. `.ignore` and `.gitignore` files drop a source from Ruff's walk. `C90` selected with `C9` ignored turns `C901` off. The rewritten nesting walk also hit Python's recursion limit on long expressions. All five are fixed here, each with tests. -#### Key Deliverables: -- Context & Rationale*: AGENTS.md states complexity $\le 10$ as a project-wide invariant validated continuously. It is not: 240 functions in `src/` breach it and no gate checks it. The invariant is aspirational, and stating it as enforced is worse than stating it as a target, because reviewers and agents trust it. -- Deliverable*: either bring the 240 down and turn on `C901`, or record a ratcheted baseline so new breaches fail while existing ones are worked off. Until one of those exists, the claim in AGENTS.md should be softened to match what is actually checked. -- Unit and integration test coverage with structural tuple equality assertions. -- Maintain cyclomatic complexity $M \le 10$ and nesting depth $\le 5$. -- 100% passing across Gated CI validation suite (`uv run devops ci`). +## Key Changes +- **`pyproject.toml`**: `select` adds `C901`, `PGH004` and `RUF100`, and `[tool.ruff.lint.mccabe] max-complexity = 10`. +- **Baseline**: the three steps ran in order. `uv run ruff check --select C901 --add-noqa .` ran once and added 66 directives, none of them merged into an existing comment. Then `uv run ruff check --fix --fixable RUF100 .`, without `--select RUF100`, fixed the 9 stale codes. The `# nosec` comments stay, and `tests/test_ai_gateway_tune.py:338` keeps "the script under test" as a plain comment. +- **`src/devops_cli/config/constants.py`**: `CONST_COMPLEXITY_LINT_RULES` (`C901`, `PGH004`, `RUF100`) sits beside `CONST_TEST_ASSERTION_LINT_RULES`. Next to it are: + - the key allowlists `CONST_RUFF_TOP_LEVEL_KEYS`, `CONST_RUFF_LINT_KEYS` and `CONST_RUFF_MCCABE_KEYS`, plus `CONST_RUFF_PER_FILE_IGNORE_KEYS`; + - `CONST_RUFF_EXCLUDE`, `CONST_COMPLEXITY_CAP_ROOTS`, `CONST_RUFF_SOURCE_SUFFIXES` and `CONST_RUFF_CONFIG_FILE_NAMES`; + - `CONST_RUFF_IGNORE_FILE_NAMES` (`.gitignore`, `.ignore`); + - the three regexes, `CONST_RUFF_FILE_EXEMPTION`, `CONST_C901_SUPPRESSION` and `CONST_RUFF_C901_SUPPRESSION_COMMENT`. Each one takes any whitespace except a newline (`[^\S\n]`) where Ruff does. The last one matches a `ruff:` comment with any verb whose brackets name `C901`. +- **`src/devops_cli/config/defaults.py`**: `DEFAULT_C901_SUPPRESSION_CEILING = 66` sits next to `DEFAULT_MAX_COMPLEXITY`. +- **`tests/test_architectural_invariants.py`**: + - `_complexity_cap_escapes(pyproject, project)` returns every escape it finds. `_lint_escapes` counts a cap rule as enforced only when `select` names it by its own code. `_tree_escapes` checks four things: file-level exemptions and Ruff's own `C901` suppression comments, through `_source_escapes`; nested and outranking Ruff configs; and ignore files, through `_ignore_file_escapes`. That helper matches covered sources against the root `.gitignore` with `pathspec`, a declared dependency, so no `git` process runs. + - `_c901_suppressions` and `_c901_suppressions_over` count `C901` markers with a regex over the file text. + - The new tests are `test_every_complexity_cap_escape_is_reported` (38 cases), `test_the_complexity_cap_has_no_escape`, `test_c901_suppressions_stay_under_the_ceiling`, `test_suppressions_over_the_ceiling_name_their_files` and `test_every_marker_spelling_ruff_honours_is_counted` (4 cases). + - `test_filesystem_get_tools_complexity` is removed, because `C901` covers it. +- **`src/devops_cli/security/structural_invariants.py`**: the hook checks nesting only. The complexity accumulation in `_measure`, `MAX_COMPLEXITY`, the `max_complexity` parameters, `over_complex` and the note are gone. `measure` returns the nesting depth from an explicit stack, not recursion. `breaches` and `check_structural_invariants` return the breach list, and `breaches` reports a parser `RecursionError` as a file it could not parse. +- **`tests/test_structural_invariant_hook.py`**: `test_complexity_is_reported_without_blocking` is removed. `test_a_long_expression_is_measured_rather_than_overflowing` and `test_a_parser_overflow_is_reported_rather_than_raised` are added, and both run in-process. +- **`pyproject.toml` comment**: says the meta-test bans every other way past the cap, and that each of the three rules must be named by its own code. +- **`.pre-commit-config.yaml`**: the hook comment's complexity clause now says that complexity is Ruff's `C901`, run by the `ruff-check` hook. The import claim is left for #773. +- **Docs**: `AGENTS.md:14`, `CONTRIBUTING.md:13`, `docs/SDLC.md:129` and `docs/ROUTINE_TASKS.md:55` name the real enforcers. `AGENTS.md:14` also says that a function over the cap is decomposed, never suppressed, and that the meta-test rejects Ruff's own `ruff:` comments and ignore files: + - `C901`, through `uv run devops ci` and the pre-commit ruff hook; + - the marker ceiling test; + - for nesting, the `structural-invariants` hook and `test_no_excessive_nesting_in_src`. + + They also say that `devops scan complexity` reports a different, in-house count and does not gate. +- **`docs/ROADMAP.md`**: not edited. #739 made it a generated view. The PR description names "Metric Provenance: radon's Cyclomatic Complexity Behind One Adapter" as superseded by D1. + +## Measurements +These were taken on 321ecda (`origin/release/v0.2.25`) with ruff 0.16.8. The issue's figures are from ef21785, and the counts have moved since then. +- `C901` breaches, measured with `ruff check --no-cache --isolated --select C901 --config 'lint.mccabe.max-complexity = 10' --statistics --exit-zero src tests`: 66 (the issue had 76). With the markers in place, the same command needs `--ignore-noqa` and still prints 66. 65 are in 42 `src` files and 1 is in `tests`: `test_no_circular_imports_in_decoupled_subsystems` in `tests/test_architectural_invariants.py`. +- The in-house counter, `run_complexity_scan(src/devops_cli, max_complexity=10)`: 215 functions over 10 (the issue had 235). +- `ruff check --select RUF100 .`, which replaces the configured `select`, reports 34 unused codes before the baseline (the issue had 31). With the project's `select` plus `RUF100`, it reports exactly the 9 listed below. +- `PGH004` (blanket `noqa`): 0 hits. +- The release tip moves until this ships. If it moves before merge, the orchestrator re-runs the baseline on the new tip at ship time: `--add-noqa` once, then `--fix --fixable RUF100`. `DEFAULT_C901_SUPPRESSION_CEILING` and the counts in this file are then set to the new tip's numbers. The local `origin/release/v0.2.25` was still 321ecda at the last check. + +## Acceptance Criteria +- [x] `uv run devops ci --check --no-cache` passes on the PR head, with every check reported as passing. Plain `uv run ruff check .`, the command GitHub CI runs (`.github/workflows/ci.yml:51`), prints `All checks passed!`. +- [x] The baseline removed no `noqa` code the project needs. `git diff -U0 321ecda -- src tests | grep -c '^-.*# noqa'` prints 9, and they are the issue's lines: + - `ai/gateway_bench.py:69`, `:97` and `:100` (`S310`); + - `ai/gateway_tune.py:432` (`S603`); + - `tests/test_ai_gateway_tune.py:338` (`S102`); + - `tests/test_exceptions.py:172-173` (`F401`); + - `tests/test_sandbox_metrics.py:231`, which was `:229` at ef21785, and `tests/test_sandbox_probe.py:133` (`N802`). +- [x] The meta-test passes on the real `pyproject.toml`. Before the config change it reported `C901`, `PGH004` and `RUF100` as not enforced and `max-complexity: None, not 10`. `test_every_complexity_cap_escape_is_reported` has 38 cases, built from in-memory config dicts and `tmp_path` files: 2 complying controls and 36 escapes, one per case. The helper reports each escape alone. The first 24 escapes failed against a stub helper. The 12 added in review fail against the helpers as they were before the review, and Ruff 0.16.8 hides a complexity-13 function behind each comment spelling they use. The escapes are: + - top-level `per-file-ignores` covering `C901`; + - top-level `extend-ignore = ["C901"]`; + - `include`, `extend`, `extend-exclude` and `lint.exclude`; + - an `exclude` other than `["repos"]`; + - `C901` unselected, `C901` ignored, and `C901` selected as `C90` with `C9` ignored. The control `C9` ignored under an exact `C901` reports nothing, and Ruff agrees; + - `RUF100` in `extend-ignore`, and `PGH004` unselected; + - `max-complexity` raised, `max-complexity` missing, and an extra `mccabe` key; + - `per-file-ignores` with `C9`, `extend-per-file-ignores` with `ALL`, and `per-file-ignores` with `PGH`; + - a file-level `ruff` exemption with and without codes, and a file-level `flake8` exemption. Each also appears with a form feed or a no-break space after the `#`; + - Ruff's own comments naming `C901`: a trailing `ignore[C901]`, a `disable[C901]`/`enable[C901]` pair, an unpaired and unspaced `disable[E501,C901]`, a `file-ignore[C901]`, and a `disable[ C901 ]` with em spaces; + - an `.ignore` under `src`, a `.gitignore` under `tests`, an `.ignore` beside `pyproject.toml`, and a root `.gitignore` that lists a source. In that last case, the `__pycache__/` and `*.py[cod]` lines in the same file report nothing; + - a nested `ruff.toml`, `.ruff.toml` or `pyproject.toml`; + - a `ruff.toml` beside `pyproject.toml`. + + No test runs the ruff binary. +- [x] The ceiling test passes, and three numbers are equal at 66: + - `DEFAULT_C901_SUPPRESSION_CEILING`; + - `_c901_suppressions` over `src` and `tests`: 65 + 1, in 43 files; + - `uv run ruff check --select C901 --ignore-noqa --statistics --exit-zero .`, which prints `66 C901 complex-structure`. + + `test_every_marker_spelling_ruff_honours_is_counted` counts 1 for each of four markers: a form feed or a no-break space after the `#`, an em space after the colon, and an ASCII `noqa : E501 C901`. The regex as it was before the review counted 0 for the first three. Ruff hides the function behind all four. + + With the ceiling still at 0 after the baseline, the test failed with `66 more C901 marker(s) than DEFAULT_C901_SUPPRESSION_CEILING allows, among these files: [...]. Decompose the function the new marker sits on until Ruff no longer reports it; do not raise the ceiling.` +- [x] `test_suppressions_over_the_ceiling_name_their_files` writes, at run time, both forms `--add-noqa` produces: the plain `C901` marker on `def f(x):` and the merged `C901, N802` marker on `def do_GET(x):`. The helper counts 2 for `src/over.py`, reports an excess of 1 naming `src/over.py` at ceiling 1, and reports nothing at ceiling 2. It failed against a stub helper. +- [x] The probe sequence, with `p=src/devops_cli/_c901_probe.py`, gave the expected result at each step. The probe is deleted. + + ```text + $ uv run ruff check $p -> C901 `f` is too complex (11 > 10), exit 1 + $ uv run pre-commit run ruff-check --files $p -> ruff check....Failed (C901 `f` is too complex (11 > 10)), exit 1 + $ sed -i '1s/$/ # noqa: C901/' $p && sed -i '/x == 10/,+1d' $p + $ uv run ruff check $p -> RUF100 [*] Unused `noqa` directive (unused: `C901`), exit 1 + $ uv run ruff check --fix $p; grep -c noqa $p -> Found 1 error (1 fixed, 0 remaining). / 0 + $ rm $p + ``` + +- [x] `rg -n -i complexity src/devops_cli/security/structural_invariants.py` returns nothing, and the six tests in `tests/test_structural_invariant_hook.py` pass. The old and new nesting measures agree on all 14,749 functions in `src` and `tests`. +- [x] The hook survives long expressions. With a `def f()` returning a sum of N ones, the hook as first rewritten raised `RecursionError` (exit 1) at 600 and 900 terms, where the 321ecda hook exited 0. Now it exits 0 at 450, 600, 900 and 3000 terms; the 321ecda hook also failed at 3000. `ast.parse` itself overflows near 200,000 terms, and `breaches` reports that as `could not parse`. +- [x] `rg -n C901 AGENTS.md CONTRIBUTING.md docs/SDLC.md docs/ROUTINE_TASKS.md` shows `AGENTS.md:14`, `CONTRIBUTING.md:13`, `docs/SDLC.md:129` and `docs/ROUTINE_TASKS.md:55`. `rg -n 'nothing enforces it|240 functions' .pre-commit-config.yaml src tests` returns nothing. `git diff` changes only `AGENTS.md:14` in that file and leaves `.github/pull_request_template.md` unchanged. +- [x] `uv run ruff check .` wall time, over 7 runs each: + - with `--no-cache`: median 1.27 s before and 1.08 s after; + - cached: median 1.14 s before and 0.94 s after. + + Both changes are under 1 s and within run-to-run noise. +- [x] Test durations, from a JUnit report covering setup, call and teardown: + - The 47 new test items take 0.467 s together, with the file cache warm. The breakdown: + - `test_the_complexity_cap_has_no_escape`: 0.129 s. Reading the 921 sources takes about 55 ms of that, and matching them against `.gitignore` about 27 ms. + - `test_c901_suppressions_stay_under_the_ceiling`: 0.092 s. + - `test_suppressions_over_the_ceiling_name_their_files`: 0.005 s. + - The 38 escape cases: 0.174 s together, at most 0.006 s each. + - The 4 marker-spelling cases: 0.018 s together. + - `test_a_long_expression_is_measured_rather_than_overflowing`: 0.045 s. + - `test_a_parser_overflow_is_reported_rather_than_raised`: 0.004 s. + - Before the review fixes, the test step ran as `pytest -n auto --maxprocesses=8 --durations=0 --cov=src`. Before this change: 8021 passed in 144.23 s, with a `--durations` sum of 662.70 s. After it: 8047 passed in 138.62 s, with a sum of 578.79 s. + - After the review fixes, `uv run devops ci --check --no-cache` passed all 13 checks. Its test step took 2 m 34 s, with mypy at 31 s and docs at 17 s. It prints no test count; `pytest --collect-only` collects 8074 tests. + - The earlier difference is negative. The removed `test_complexity_is_reported_without_blocking` took 5.06 s, one hook subprocess, and `test_filesystem_get_tools_complexity` took 0.02 s. `test_structural_invariant_hook.py` went from 31.47 s to 26.73 s. The rest of the 83.9 s drop in the sum is load varying between runs. + +## Trade-offs +- `devops scan complexity` keeps the in-house count (215 over 10 in `src`, against 65 for `C901`) until #773 aligns it with McCabe. It reports only and does not gate. +- The ceiling test uses `≤`, so it does not force the ceiling down when a marker goes. A PR that removes markers lowers the ceiling itself, and a raised ceiling or a new marker shows up in review as a changed line. +- The meta-test goes beyond D1's list. Besides the checks added in review (the bullets below), it does two more things: + - A per-file ignore that covers `RUF100` or `PGH004` also counts as an escape. Without `PGH004`, a blanket `noqa` would hide `C901` with no marker to count. + - A `ruff.toml` or `.ruff.toml` beside `pyproject.toml` is reported, because Ruff prefers it to `pyproject.toml`. + + `per-file-ignores` stays allowed for every other rule. #420 adds any new Ruff key to the allowlists in its own PR. +- The counting regex reads raw text, not comment tokens, so a string literal that looks like a marker overcounts, which fails safe. The new tests build every marker, exemption and comment text at run time, so their own source does not match. +- Ruff's own `ruff:` comments naming `C901` are banned, not counted. One `disable` covers any number of functions, so it cannot be counted one per function the way a marker is. The pattern accepts any verb (`ignore`, `disable`, `enable`, `file-ignore`) and any case. It therefore also reports spellings Ruff does not honour, such as `# RUFF: DISABLE[C901]`, which fails safe. A rule name like `[complex-structure]`, or a prefix like `[C9]` or `[ALL]`, does not hide `C901` in Ruff 0.16.8, so the pattern does not look for them. `PGH004` cannot be suppressed by a line or range comment at all: Ruff reports `RUF100` on the comment and still reports `PGH004`. `RUF104` (unmatched range comment) is not selected; the ban already covers every range comment that names `C901`. +- A cap rule counts as enforced only when `select` names it by its own code. That is stricter than Ruff: `select = ["C90"]` alone does enforce `C901`, but the test reports it. Matching Ruff's prefix redirects instead would mean copying a table Ruff can change. +- Ignore files that are not committed are out of the meta-test's reach: `.git/info/exclude`, a global gitignore, and ignore files above the project. They differ per machine and never reach the clean checkout GitHub CI lints. The root `.gitignore` is matched with `pathspec`, not with `git check-ignore`, so the tests start no process. Where `pathspec` and Ruff's `ignore` crate disagree on an edge case, the check can miss a file. +- The nesting walk uses an explicit stack, so it has no depth limit of its own. Only `ast.parse` limits how deep an input can go. diff --git a/pyproject.toml b/pyproject.toml index 90f6a54e7f..355a0197de 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -90,9 +90,20 @@ exclude = ["repos"] # lazily re-exporting packages all define — suppresses it for the entire module. # Selected individually rather than as the whole RUF family, which is a separate # roadmap item with its own triage. -select = ["E", "F", "I", "N", "W", "UP", "B017", "RUF022", "RUF043", "RUF068"] +# C901 is the complexity cap of 10 (standard McCabe, #586). The functions over it when it was +# turned on carry a C901 noqa marker; RUF100 reports a marker once its function is back under +# the cap, PGH004 bans the blanket noqa that would hide C901, and +# `test_c901_suppressions_stay_under_the_ceiling` keeps the markers from growing in number. +# `test_the_complexity_cap_has_no_escape` bans every other way past the cap, and counts the +# three as enforced only when named by their own codes here: Ruff reads `C9` as `C90`. +select = [ + "E", "F", "I", "N", "W", "UP", "B017", "C901", "PGH004", "RUF022", "RUF043", "RUF068", "RUF100", +] ignore = ["E501", "N818"] +[tool.ruff.lint.mccabe] +max-complexity = 10 + [tool.mypy] python_version = "3.14" strict = true diff --git a/src/devops_cli/ai/__init__.py b/src/devops_cli/ai/__init__.py index 4abd3b82f8..b9348392fe 100644 --- a/src/devops_cli/ai/__init__.py +++ b/src/devops_cli/ai/__init__.py @@ -5,7 +5,7 @@ from typing import Any -def __getattr__(name: str) -> Any: +def __getattr__(name: str) -> Any: # noqa: C901 try: import importlib diff --git a/src/devops_cli/ai/agents/__init__.py b/src/devops_cli/ai/agents/__init__.py index 44bf3525d3..b1c925cde2 100644 --- a/src/devops_cli/ai/agents/__init__.py +++ b/src/devops_cli/ai/agents/__init__.py @@ -290,7 +290,7 @@ ) -def __getattr__(name: str) -> Any: +def __getattr__(name: str) -> Any: # noqa: C901 if name in { "BaseDurabilityCapability", "LocalDurabilityCapability", diff --git a/src/devops_cli/ai/agents/agent.py b/src/devops_cli/ai/agents/agent.py index 66807df04f..158a262481 100644 --- a/src/devops_cli/ai/agents/agent.py +++ b/src/devops_cli/ai/agents/agent.py @@ -223,7 +223,7 @@ def from_spec( tools=tools, ) - def __init__( + def __init__( # noqa: C901 self, model: str | Any | None = None, system_prompt: str | None = None, @@ -606,7 +606,7 @@ def render_tool_interface( include_type_defs=include_type_defs, ) - def _build_system_prompt_with_tools( + def _build_system_prompt_with_tools( # noqa: C901 self, ctx: RunContext[Any] | None = None, *, skip_memory_summary: bool = False ) -> str: base_prompt: str = str(self.system_prompt) @@ -676,7 +676,7 @@ def _build_system_prompt_with_tools( return "\n\n".join(prompt_parts) - def _dispatch_tool_calls( + def _dispatch_tool_calls( # noqa: C901 self, tool_calls_info: list[Any], tool_calls: list[ToolCall], @@ -797,7 +797,7 @@ def _dispatch_tool_calls( messages.append(ChatMessage(role="user", content=extra_content)) return executed_any, already_called, deferred_requests - def run( + def run( # noqa: C901 self, user_prompt: str, *, diff --git a/src/devops_cli/ai/analyze/outlines.py b/src/devops_cli/ai/analyze/outlines.py index 039c2fff4d..27d2ade0bf 100644 --- a/src/devops_cli/ai/analyze/outlines.py +++ b/src/devops_cli/ai/analyze/outlines.py @@ -327,7 +327,7 @@ def _generate_ai_pseudocode( return None -def _generate_pseudocode( +def _generate_pseudocode( # noqa: C901 rel_path: str, content: str, lang: str, @@ -386,7 +386,7 @@ def _extract_semantic_outline_meta(rel_path: str, repo_root: Path | None) -> dic return None -def analyze_single_file( +def analyze_single_file( # noqa: C901 rel_path: str, content: str, size_bytes: int, diff --git a/src/devops_cli/ai/analyze/scanner.py b/src/devops_cli/ai/analyze/scanner.py index 714bce74e0..328a83590f 100644 --- a/src/devops_cli/ai/analyze/scanner.py +++ b/src/devops_cli/ai/analyze/scanner.py @@ -303,7 +303,7 @@ def _extract_file_dependencies(content: str, lang: str) -> list[str]: return deps[:12] -def _extract_file_purpose(rel_path: str, content: str, lang: str, symbols: list[str]) -> str: +def _extract_file_purpose(rel_path: str, content: str, lang: str, symbols: list[str]) -> str: # noqa: C901 """Infer an accurate, human-meaningful primary purpose description for a file.""" filename = Path(rel_path).name.lower() stem = Path(rel_path).stem diff --git a/src/devops_cli/ai/benchmark/document_chunker.py b/src/devops_cli/ai/benchmark/document_chunker.py index 9e798e5247..296c6796d6 100644 --- a/src/devops_cli/ai/benchmark/document_chunker.py +++ b/src/devops_cli/ai/benchmark/document_chunker.py @@ -434,7 +434,7 @@ def _collect_chunks_from_path( return chunks -def load_test_document_corpus( +def load_test_document_corpus( # noqa: C901 document_path: Path | None = None, repo_root: Path | None = None, chunk_size_words: int = 100, diff --git a/src/devops_cli/ai/benchmark/embedding_runner.py b/src/devops_cli/ai/benchmark/embedding_runner.py index 33c9d01873..fc75a25ba2 100644 --- a/src/devops_cli/ai/benchmark/embedding_runner.py +++ b/src/devops_cli/ai/benchmark/embedding_runner.py @@ -311,7 +311,7 @@ def evaluate_model( endpoint = self.servers[0] if self.servers else "default" return self.evaluate_model_on_server(model_name, endpoint, pairs, corpus) - def evaluate_model_on_server( + def evaluate_model_on_server( # noqa: C901 self, model_name: str, server_url: str, diff --git a/src/devops_cli/ai/client/ollama.py b/src/devops_cli/ai/client/ollama.py index 8eac33c446..2240450d9a 100644 --- a/src/devops_cli/ai/client/ollama.py +++ b/src/devops_cli/ai/client/ollama.py @@ -269,7 +269,7 @@ def _ollama_messages( raise self._connection_error(last_exc or RuntimeError("All Ollama servers unreachable")) - def _ollama_request( + def _ollama_request( # noqa: C901 self, base: str, system: str, messages: list[ChatMessage], think: bool ) -> LLMResponse: start_time = time.monotonic() diff --git a/src/devops_cli/ai/context_budget.py b/src/devops_cli/ai/context_budget.py index e48361c14a..c13023911d 100644 --- a/src/devops_cli/ai/context_budget.py +++ b/src/devops_cli/ai/context_budget.py @@ -129,7 +129,7 @@ def validate_and_budget_prompt( return text, False -def budget_diff_chunks( +def budget_diff_chunks( # noqa: C901 diff_text: str, max_tokens: int = DEFAULT_DIFF_CHUNK_BUDGET, model: str = "gpt-4o", diff --git a/src/devops_cli/ai/ext_langchain.py b/src/devops_cli/ai/ext_langchain.py index cd9bbdbb9f..e3725bf7e8 100644 --- a/src/devops_cli/ai/ext_langchain.py +++ b/src/devops_cli/ai/ext_langchain.py @@ -21,7 +21,7 @@ def _validate_langchain_kwargs(kwargs: dict[str, Any]) -> str | None: return None -def tool_from_langchain( +def tool_from_langchain( # noqa: C901 langchain_tool: Any, *, name: str | None = None, diff --git a/src/devops_cli/ai/gateway_bench.py b/src/devops_cli/ai/gateway_bench.py index 8449e990fc..8e51eeb655 100644 --- a/src/devops_cli/ai/gateway_bench.py +++ b/src/devops_cli/ai/gateway_bench.py @@ -66,7 +66,7 @@ def _validate_http_url(url: str) -> None: def _get_text(url: str, timeout: float) -> tuple[int, str]: try: _validate_http_url(url) - with urllib.request.urlopen(url, timeout=timeout) as response: # noqa: S310 # nosec B310 + with urllib.request.urlopen(url, timeout=timeout) as response: # nosec B310 return response.status, response.read().decode("utf-8", "replace") except urllib.error.HTTPError as exc: return exc.code, "" @@ -94,10 +94,10 @@ def engine_info(api_base: str, get: Get = _get_text, timeout: float = 10.0) -> d def _post_json(url: str, body: dict[str, Any], timeout: float) -> dict[str, Any]: # The URL is a backend api_base from the gateway's own configuration, always http(s). _validate_http_url(url) - request = urllib.request.Request( # noqa: S310 + request = urllib.request.Request( url, json.dumps(body).encode(), {"Content-Type": "application/json"} ) - with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 # nosec B310 + with urllib.request.urlopen(request, timeout=timeout) as response: # nosec B310 result: dict[str, Any] = json.load(response) return result diff --git a/src/devops_cli/ai/gateway_tune.py b/src/devops_cli/ai/gateway_tune.py index 9d6dbf5121..a9e2714817 100644 --- a/src/devops_cli/ai/gateway_tune.py +++ b/src/devops_cli/ai/gateway_tune.py @@ -429,7 +429,7 @@ def _kubectl( cmd = ["kubectl", *(["--context", context] if context else []), *args] for attempt in range(1, _KUBECTL_ATTEMPTS + 1): try: - proc = subprocess.run( # noqa: S603 # nosec B603 - fixed kubectl argv, no shell + proc = subprocess.run( # nosec B603 - fixed kubectl argv, no shell cmd, input=input_data, capture_output=True, diff --git a/src/devops_cli/ai/harness/agents.py b/src/devops_cli/ai/harness/agents.py index 3215b3c5c4..4638a7016b 100644 --- a/src/devops_cli/ai/harness/agents.py +++ b/src/devops_cli/ai/harness/agents.py @@ -374,7 +374,7 @@ def __init__( guidance=guidance, ) - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: + def get_tools(self) -> list[AgentTool | Callable[..., Any]]: # noqa: C901 def navigate(url: str, timeout_ms: int | None = None) -> str: """Navigate to a URL and return title, URL, and visible page text.""" from urllib.parse import urlparse diff --git a/src/devops_cli/ai/harness/compaction.py b/src/devops_cli/ai/harness/compaction.py index 0a101a02ab..c62667765d 100644 --- a/src/devops_cli/ai/harness/compaction.py +++ b/src/devops_cli/ai/harness/compaction.py @@ -305,7 +305,7 @@ def __init__( serializer=serializer, ) - def reduce_output( + def reduce_output( # noqa: C901 self, tool_name: str, output: Any, tool_call_id: str = "" ) -> tuple[Any, bool]: """Measure tool return size and apply winning reduction band.""" @@ -660,7 +660,7 @@ class SummarizingCompaction(BaseCapability): receipts: bool = False transcript_handle_provider: Any | None = None - def compact_messages(self, messages: list[Any]) -> list[Any]: + def compact_messages(self, messages: list[Any]) -> list[Any]: # noqa: C901 """Compress the middle turns into a concise summary block.""" if len(messages) <= self.keep_tail + 2: return list(messages) diff --git a/src/devops_cli/ai/harness/docs.py b/src/devops_cli/ai/harness/docs.py index 039500e328..7f783a172d 100644 --- a/src/devops_cli/ai/harness/docs.py +++ b/src/devops_cli/ai/harness/docs.py @@ -105,7 +105,7 @@ def _read_local_doc(self, local_file: Path) -> str | None: logger.debug("Error reading local doc %s: %s", local_file, e) return None - def read_doc(self, topic: str) -> str: + def read_doc(self, topic: str) -> str: # noqa: C901 """Resolve and read a Pydantic AI documentation topic (local checkout first, then remote).""" import re diff --git a/src/devops_cli/ai/harness/filesystem.py b/src/devops_cli/ai/harness/filesystem.py index 3aed6a29cb..c0bed39237 100644 --- a/src/devops_cli/ai/harness/filesystem.py +++ b/src/devops_cli/ai/harness/filesystem.py @@ -251,7 +251,7 @@ def _find_files(self, pattern: str, path: str = ".") -> str: return "\n".join(matches) or f"No files matching pattern '{pattern}' found." - def _search_files(self, query: str, path: str = ".", include_glob: str | None = None) -> str: + def _search_files(self, query: str, path: str = ".", include_glob: str | None = None) -> str: # noqa: C901 """Regex or text search across file contents.""" safe_p = self._resolve_safe_path(path) if not safe_p.is_dir(): diff --git a/src/devops_cli/ai/harness/memory.py b/src/devops_cli/ai/harness/memory.py index 4c4f5edfe2..0f77689aad 100644 --- a/src/devops_cli/ai/harness/memory.py +++ b/src/devops_cli/ai/harness/memory.py @@ -626,7 +626,7 @@ def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> lis raise return additions - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: + def get_tools(self) -> list[AgentTool | Callable[..., Any]]: # noqa: C901 prefix = f"{self.tool_prefix}_" if self.tool_prefix else "" store = self.store diff --git a/src/devops_cli/ai/harness/planning.py b/src/devops_cli/ai/harness/planning.py index b1fd460eb1..1c8e725dce 100644 --- a/src/devops_cli/ai/harness/planning.py +++ b/src/devops_cli/ai/harness/planning.py @@ -437,7 +437,7 @@ def _render_node(pid: str | None, indent: int = 0) -> None: _render_node(None) return "\n".join(lines) - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: + def get_tools(self) -> list[AgentTool | Callable[..., Any]]: # noqa: C901 all_tools: list[AgentTool | Callable[..., Any]] = [] def write_plan(items: list[dict[str, Any] | PlanItem | str]) -> str: diff --git a/src/devops_cli/ai/harness/shell.py b/src/devops_cli/ai/harness/shell.py index 2e611dc8fc..2b39f5f8a5 100644 --- a/src/devops_cli/ai/harness/shell.py +++ b/src/devops_cli/ai/harness/shell.py @@ -368,7 +368,7 @@ def _terminate_process_group(self, proc: subprocess.Popen[str]) -> None: self.stop_grace_seconds, ) - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: + def get_tools(self) -> list[AgentTool | Callable[..., Any]]: # noqa: C901 bg_commands: dict[str, _BackgroundCommand] = {} def run_command(command: str, timeout_seconds: float | None = None) -> str: diff --git a/src/devops_cli/ai/harness/skills.py b/src/devops_cli/ai/harness/skills.py index b6b04d97ed..8ac1e9ad92 100644 --- a/src/devops_cli/ai/harness/skills.py +++ b/src/devops_cli/ai/harness/skills.py @@ -119,7 +119,7 @@ class Skills(BaseCapability): skills: dict[str, ParsedSkill] = Field(default_factory=dict) loaded_skills: set[str] = Field(default_factory=set) - def __init__( + def __init__( # noqa: C901 self, directories: str | Path | Sequence[str | Path], *, diff --git a/src/devops_cli/ai/harness/workflow.py b/src/devops_cli/ai/harness/workflow.py index 208408e413..a1254ed541 100644 --- a/src/devops_cli/ai/harness/workflow.py +++ b/src/devops_cli/ai/harness/workflow.py @@ -211,7 +211,7 @@ def __init__( call_counts=defaultdict(int), ) - def load_disk_agents(self) -> list[SubAgent]: + def load_disk_agents(self) -> list[SubAgent]: # noqa: C901 """Auto-load markdown agent definitions from conventional or configured folders.""" if self.agent_folders is None: return [] @@ -259,11 +259,11 @@ def _resolve_delegate_model(self, target: SubAgent, model: str | None) -> str: return target.models[0] return next(iter(self.models.keys())) - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: + def get_tools(self) -> list[AgentTool | Callable[..., Any]]: # noqa: C901 all_sub_agents = self.get_all_agents() agent_map = {sa.name: sa for sa in all_sub_agents} - def delegate_task( + def delegate_task( # noqa: C901 ctx: NativeRunContext[Any] = None, # type: ignore[assignment] agent_name: str = "", task: str = "", diff --git a/src/devops_cli/ai/mcp/server.py b/src/devops_cli/ai/mcp/server.py index 71a71ee588..7ce9b555d5 100644 --- a/src/devops_cli/ai/mcp/server.py +++ b/src/devops_cli/ai/mcp/server.py @@ -511,7 +511,7 @@ def docker_stats() -> str: @mcp.tool() -def docker_sign( +def docker_sign( # noqa: C901 image: str, key: str | None = None, keyless: bool = True, @@ -549,7 +549,7 @@ def docker_sign( @mcp.tool() -def docker_verify( +def docker_verify( # noqa: C901 image: str, key: str | None = None, certificate_identity: str | None = None, @@ -1362,7 +1362,7 @@ def docker_sandbox( @mcp.tool() -def sandbox_deploy( +def sandbox_deploy( # noqa: C901 image: str = "python:3.14-slim", name: str | None = None, ports: list[int] | None = None, diff --git a/src/devops_cli/ai/output/__init__.py b/src/devops_cli/ai/output/__init__.py index d14a77f726..214cf8dcb5 100644 --- a/src/devops_cli/ai/output/__init__.py +++ b/src/devops_cli/ai/output/__init__.py @@ -94,7 +94,7 @@ def unwrap_output_spec(spec: Any) -> tuple[Any, ...]: return (spec,) -def extract_output_json_schema(spec: Any) -> dict[str, Any] | None: +def extract_output_json_schema(spec: Any) -> dict[str, Any] | None: # noqa: C901 """Extract standard JSON schema dictionary from any OutputSpec or BaseModel. Inspects NativeOutput, ToolOutput, PromptedOutput, StructuredDict, TextOutput, and bare Pydantic models. diff --git a/src/devops_cli/ai/rag/indexer.py b/src/devops_cli/ai/rag/indexer.py index b27240dc78..c9125aec87 100644 --- a/src/devops_cli/ai/rag/indexer.py +++ b/src/devops_cli/ai/rag/indexer.py @@ -80,7 +80,7 @@ def _load_gitignore_spec(root: Path) -> Any: return None -def _is_indexable_file(p: Path, root: Path, *, gitignore_spec: Any = None) -> bool: +def _is_indexable_file(p: Path, root: Path, *, gitignore_spec: Any = None) -> bool: # noqa: C901 """Determine if a path is an indexable code/doc file under root.""" if not p.is_file() or p.is_symlink(): return False diff --git a/src/devops_cli/ai/review/common_hallucinations.py b/src/devops_cli/ai/review/common_hallucinations.py index 9eaa18572a..4fca1cc71e 100644 --- a/src/devops_cli/ai/review/common_hallucinations.py +++ b/src/devops_cli/ai/review/common_hallucinations.py @@ -761,7 +761,7 @@ def verify_ground_truth_hallucination( return verifier(finding, entry, file_path) if verifier else False -def calculate_hallucination_similarity( +def calculate_hallucination_similarity( # noqa: C901 finding: Finding, entry: CommonHallucinationEntry, file_path: Path | None = None ) -> HallucinationMatch: """Calculate similarity between a finding and a known common hallucination. diff --git a/src/devops_cli/ai/review/pipeline.py b/src/devops_cli/ai/review/pipeline.py index dc093ff959..3766ff02d3 100644 --- a/src/devops_cli/ai/review/pipeline.py +++ b/src/devops_cli/ai/review/pipeline.py @@ -2829,7 +2829,7 @@ def _safe_review_file_payload( prefix=False, ) - def execute_multi_persona_review( + def execute_multi_persona_review( # noqa: C901 self, file_payloads: list[FileReviewPayload], diff_text_by_file: dict[str, str], diff --git a/src/devops_cli/ai/review/runner.py b/src/devops_cli/ai/review/runner.py index 22ea86efd9..6796ee902b 100644 --- a/src/devops_cli/ai/review/runner.py +++ b/src/devops_cli/ai/review/runner.py @@ -1275,7 +1275,7 @@ def _calculate_parallel_review_workers( return min(num_tasks, capacity, DEFAULT_REVIEW_MAX_CONCURRENCY) -def _run_persona_loop( +def _run_persona_loop( # noqa: C901 pages: list[str], title: str, build_prompt: Callable[[str, str], str], diff --git a/src/devops_cli/ai/review/verification.py b/src/devops_cli/ai/review/verification.py index 5f4a778cf1..84aa6bce3e 100644 --- a/src/devops_cli/ai/review/verification.py +++ b/src/devops_cli/ai/review/verification.py @@ -542,7 +542,7 @@ def _check_candidate_paths(base_dir: Path, rel_path: Path) -> Path | None: return None -def _resolve_target_file(loc_file: str, repo_root: Path | None) -> Path | None: +def _resolve_target_file(loc_file: str, repo_root: Path | None) -> Path | None: # noqa: C901 """Resolve finding location file path against repo_root or current working directory.""" if not loc_file: return None diff --git a/src/devops_cli/ai/review_schema.py b/src/devops_cli/ai/review_schema.py index e359f3cca3..337c88727c 100644 --- a/src/devops_cli/ai/review_schema.py +++ b/src/devops_cli/ai/review_schema.py @@ -1107,7 +1107,7 @@ def _first_set(base: Finding, other: Finding, names: Sequence[str]) -> dict[str, return {name: getattr(base, name) or getattr(other, name) for name in names} -def _merge_two_findings[F: Finding](base: F, other: F) -> F: +def _merge_two_findings[F: Finding](base: F, other: F) -> F: # noqa: C901 """Merge duplicate finding `other` into `base`, taking highest severity and confidence.""" base_sev = base.severity.upper().strip() other_sev = other.severity.upper().strip() diff --git a/src/devops_cli/commands/ai.py b/src/devops_cli/commands/ai.py index d4952be1c6..a77921142e 100644 --- a/src/devops_cli/commands/ai.py +++ b/src/devops_cli/commands/ai.py @@ -962,7 +962,7 @@ def _stream_interactive_chat_turn( @app.command() -def chat( +def chat( # noqa: C901 persona: Annotated[ str, typer.Option( diff --git a/src/devops_cli/commands/analyze.py b/src/devops_cli/commands/analyze.py index 75615f7ae7..3e25dfeb6b 100644 --- a/src/devops_cli/commands/analyze.py +++ b/src/devops_cli/commands/analyze.py @@ -251,7 +251,7 @@ def analyze_main( @app.command(name="path") -def analyze_path( +def analyze_path( # noqa: C901 target: Annotated[Path, typer.Argument(help=HELP.analyze.target)] = DEFAULT_CURRENT_PATH, pattern: Annotated[ str, @@ -446,7 +446,7 @@ def analyze_branch( @app.command(name="pr") -def analyze_pr( +def analyze_pr( # noqa: C901 pr_number: Annotated[int, typer.Argument(help=HELP.analyze.pr_number)], enhanced: Annotated[ bool, diff --git a/src/devops_cli/commands/config.py b/src/devops_cli/commands/config.py index 635cd656df..436822dfca 100755 --- a/src/devops_cli/commands/config.py +++ b/src/devops_cli/commands/config.py @@ -209,7 +209,7 @@ def set_value( @app.command() -def init() -> None: +def init() -> None: # noqa: C901 """Interactive first-time setup wizard.""" settings = load_settings() print_info("[bold]devops-cli setup wizard[/bold]\n", prefix=False) @@ -359,7 +359,7 @@ def _resolve_env_spec_value(spec: EnvVarSpec, settings: Settings) -> tuple[objec @app.command("output") @app.command("env") @app.command("env-vars") -def output_env_vars( +def output_env_vars( # noqa: C901 export: Annotated[ bool, typer.Option( diff --git a/src/devops_cli/commands/devcontainer.py b/src/devops_cli/commands/devcontainer.py index 5106df325d..7ee0e47bd8 100755 --- a/src/devops_cli/commands/devcontainer.py +++ b/src/devops_cli/commands/devcontainer.py @@ -217,7 +217,7 @@ def update( # ============================================================================= -def _validate_manifest_content(data: object, base_dir: Path) -> list[str]: +def _validate_manifest_content(data: object, base_dir: Path) -> list[str]: # noqa: C901 """Validate parsed DevContainer manifest dictionary structure and referenced paths.""" errors: list[str] = [] if not isinstance(data, dict): @@ -787,7 +787,7 @@ def _install_keyring_packages(*, dry_run: bool = False) -> list[str]: return [f"Installed {', '.join(CONST_KEYRING_PACKAGES)} for the container's keyring"] -def _run_post_create_lifecycle( +def _run_post_create_lifecycle( # noqa: C901 workspace_dir: Path, *, dry_run: bool = False, @@ -1046,7 +1046,7 @@ def _spawn_background_k8s_bootstrap( return f"Warning: Failed to spawn background Minikube bootstrap: {exc}" -def _run_post_start_lifecycle(workspace_dir: Path, *, dry_run: bool = False) -> list[str]: +def _run_post_start_lifecycle(workspace_dir: Path, *, dry_run: bool = False) -> list[str]: # noqa: C901 """Execute DevContainer post-start lifecycle tasks in pure Python.""" actions: list[str] = [] diff --git a/src/devops_cli/commands/docs.py b/src/devops_cli/commands/docs.py index 01f2ba98b9..e15713175c 100644 --- a/src/devops_cli/commands/docs.py +++ b/src/devops_cli/commands/docs.py @@ -51,7 +51,7 @@ def _get_default_docs_dir() -> Path: @app.command(name="generate") -def generate( +def generate( # noqa: C901 output_dir: Annotated[ Path | None, typer.Option( diff --git a/src/devops_cli/commands/gh.py b/src/devops_cli/commands/gh.py index 80d4e22095..9a68cdab84 100644 --- a/src/devops_cli/commands/gh.py +++ b/src/devops_cli/commands/gh.py @@ -1070,7 +1070,7 @@ def issues_status_cmd( @issues_app.command("edit", help=HELP.gh.issues_edit) -def edit_issue_cmd( +def edit_issue_cmd( # noqa: C901 number: Annotated[int, typer.Argument(help="Issue number to edit.")], title: Annotated[ str | None, diff --git a/src/devops_cli/commands/k8s/cluster_context.py b/src/devops_cli/commands/k8s/cluster_context.py index e4164188e3..016dc2c17d 100644 --- a/src/devops_cli/commands/k8s/cluster_context.py +++ b/src/devops_cli/commands/k8s/cluster_context.py @@ -286,7 +286,7 @@ def _render_logql_results(result: Any, output_format: str) -> None: print(f"{ns_pod}{escaped_line}{trace_badge}") -def _execute_legacy_kubectl_logs( +def _execute_legacy_kubectl_logs( # noqa: C901 pod: str, container: str | None, namespace: str | None, diff --git a/src/devops_cli/commands/test_cmd.py b/src/devops_cli/commands/test_cmd.py index 827325b3b1..1c90a9d281 100644 --- a/src/devops_cli/commands/test_cmd.py +++ b/src/devops_cli/commands/test_cmd.py @@ -38,7 +38,7 @@ app = new_typer(help=HELP.test.app, no_args_is_help=False) -def find_changed_test_files(repo_root: Path, base_ref: str = "main") -> list[Path]: +def find_changed_test_files(repo_root: Path, base_ref: str = "main") -> list[Path]: # noqa: C901 """Find test files corresponding to modified source files via git diff.""" clean_ref = base_ref.strip() if clean_ref.startswith("-") or not re.match(r"^[a-zA-Z0-9_\-./~^]+$", clean_ref): @@ -102,7 +102,7 @@ def find_changed_test_files(repo_root: Path, base_ref: str = "main") -> list[Pat @app.command("run") -def run_test_cmd( +def run_test_cmd( # noqa: C901 target: Annotated[ Path | None, typer.Argument(help="Target test file or test directory."), diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index d348710410..a0a798ae4f 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -2984,6 +2984,64 @@ # neither escaped nor declared raw. Both defects read as correct tests, so they belong in # the lint selection rather than in a reviewer's memory. CONST_TEST_ASSERTION_LINT_RULES: Final[frozenset[str]] = frozenset({"B017", "RUF043"}) +# The Ruff rules that hold the complexity cap of 10 (#586): C901 is the cap (standard McCabe), +# RUF100 reports a C901 marker left on a function back under the cap, and PGH004 bans the +# blanket noqa that would silence C901 without naming it. +CONST_COMPLEXITY_LINT_RULES: Final[frozenset[str]] = frozenset({"C901", "PGH004", "RUF100"}) +# The keys `[tool.ruff]`, `[tool.ruff.lint]` and `[tool.ruff.lint.mccabe]` may hold (#586). Any +# other key can take a file out of the cap: Ruff 0.16 still honours the deprecated top-level +# `per-file-ignores` and `extend-ignore`, `include` and `extend` change which files or which +# settings apply, and `lint.exclude` drops files from linting. A key Ruff adds later stays out +# until a reviewed change admits it. +CONST_RUFF_TOP_LEVEL_KEYS: Final[frozenset[str]] = frozenset( + {"target-version", "line-length", "exclude", "lint"} +) +CONST_RUFF_PER_FILE_IGNORE_KEYS: Final[tuple[str, ...]] = ( + "per-file-ignores", + "extend-per-file-ignores", +) +CONST_RUFF_LINT_KEYS: Final[frozenset[str]] = frozenset( + { + "select", + "extend-select", + "ignore", + "extend-ignore", + "mccabe", + *CONST_RUFF_PER_FILE_IGNORE_KEYS, + } +) +CONST_RUFF_MCCABE_KEYS: Final[frozenset[str]] = frozenset({"max-complexity"}) +# `[tool.ruff] exclude` replaces Ruff's default exclusions, so any other value can drop a source. +CONST_RUFF_EXCLUDE: Final[tuple[str, ...]] = ("repos",) +# Where the cap holds, the suffixes Ruff lints there by default, and the config file names Ruff +# reads in any directory; one under a covered root outranks pyproject.toml for the files below it. +CONST_COMPLEXITY_CAP_ROOTS: Final[tuple[str, ...]] = ("src", "tests") +CONST_RUFF_SOURCE_SUFFIXES: Final[frozenset[str]] = frozenset({".py", ".pyi", ".ipynb"}) +CONST_RUFF_CONFIG_FILE_NAMES: Final[frozenset[str]] = frozenset( + {"pyproject.toml", "ruff.toml", ".ruff.toml"} +) +# The ignore files Ruff's file walk honours by default (`respect-gitignore`). One under a covered +# root, or a `.ignore` beside pyproject.toml, drops the files it lists from every rule. +CONST_RUFF_IGNORE_FILE_NAMES: Final[frozenset[str]] = frozenset( + {CONST_GITIGNORE_FILENAME, ".ignore"} +) +# The suppression comments below are matched on the raw text, not on comment tokens, so a string +# literal that looks like one overcounts, which fails safe. Ruff reads any whitespace but a +# newline as a separator inside them, form feed and no-break space included, hence `[^\S\n]`. +# A file-level exemption, Ruff's or the flake8 spelling Ruff honours, with or without codes. +CONST_RUFF_FILE_EXEMPTION: Final[re.Pattern[str]] = re.compile( + r"#[^\S\n]*(?:ruff|flake8)[^\S\n]*:[^\S\n]*noqa\b", re.IGNORECASE +) +# One line-level noqa comment naming C901 among any codes: the marker the ceiling counts. +CONST_C901_SUPPRESSION: Final[re.Pattern[str]] = re.compile( + r"#[^\S\n]*noqa[^\S\n]*:(?:[A-Z0-9,]|[^\S\n])*?\bC901\b", re.IGNORECASE +) +# Ruff's own bracketed suppression comment naming C901, whatever its verb: a line `ignore`, a +# `disable` that holds until its `enable` or the end of the file, or a `file-ignore`. One such +# comment can hide any number of functions without a marker to count, so each is an escape. +CONST_RUFF_C901_SUPPRESSION_COMMENT: Final[re.Pattern[str]] = re.compile( + r"#[^\S\n]*ruff[^\S\n]*:[^\S\n]*[\w-]+[^\S\n]*\[[^\]\n]*\bC901\b", re.IGNORECASE +) # Who adjudicated a recorded finding when nothing says. The feedback exporter defaulted to # "human", which routed every finding the verifier never reached into the human diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index b09ca2f20d..7b88309d6e 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -689,6 +689,9 @@ DEFAULT_DEPENDENCY_MIN_SEVERITY: str = "HIGH" DEFAULT_SBOM_FORMAT: str = "cyclonedx" DEFAULT_MAX_COMPLEXITY: int = 10 +# The C901 markers src/ and tests/ may carry: the functions over the cap when Ruff began +# enforcing it (#586). It only goes down; a function over the cap is decomposed instead. +DEFAULT_C901_SUPPRESSION_CEILING: int = 66 DEFAULT_MAX_NESTING_DEPTH: int = 5 DEFAULT_QUANTIZATION_BITS: int = 16 diff --git a/src/devops_cli/core/process.py b/src/devops_cli/core/process.py index dd36569fbe..b933419403 100644 --- a/src/devops_cli/core/process.py +++ b/src/devops_cli/core/process.py @@ -342,7 +342,7 @@ def run_subprocess( return proc -async def run_subprocess_async( +async def run_subprocess_async( # noqa: C901 cmd: list[str], *, cwd: Path | None = None, diff --git a/src/devops_cli/core/serialization.py b/src/devops_cli/core/serialization.py index 8a86330a0d..cf45818eab 100644 --- a/src/devops_cli/core/serialization.py +++ b/src/devops_cli/core/serialization.py @@ -20,7 +20,7 @@ def strip_json_comments(text: str) -> str: return _JSONC_STRING_OR_COMMENT.sub(lambda match: match.group(1) or "", text) -def extract_json_block(text: str, *, default: Any = _JSON_UNSET) -> Any: +def extract_json_block(text: str, *, default: Any = _JSON_UNSET) -> Any: # noqa: C901 """Extract and deserialize JSON from raw text, markdown code blocks, or conversational LLM output. Args: diff --git a/src/devops_cli/core/validation.py b/src/devops_cli/core/validation.py index cd735ec854..84ef96983b 100644 --- a/src/devops_cli/core/validation.py +++ b/src/devops_cli/core/validation.py @@ -353,7 +353,7 @@ def validate_configured_service_url( validate_url(url, purpose=purpose, allow_private=allow_private or _is_loopback_host(host)) -def validate_path( +def validate_path( # noqa: C901 path: Path | str, *, must_exist: bool = True, diff --git a/src/devops_cli/k8s/logql.py b/src/devops_cli/k8s/logql.py index 99ba4777e1..c775c350a4 100644 --- a/src/devops_cli/k8s/logql.py +++ b/src/devops_cli/k8s/logql.py @@ -284,7 +284,7 @@ def _parse_duration_to_seconds(duration_str: str) -> int: return 3600 -def execute_kubectl_logql( +def execute_kubectl_logql( # noqa: C901 query: LogQLQuery, namespace: str = DEFAULT_K8S_NAMESPACE, limit: int = DEFAULT_LOG_QUERY_LIMIT, diff --git a/src/devops_cli/output/console.py b/src/devops_cli/output/console.py index c9f482a20c..c081c8939a 100644 --- a/src/devops_cli/output/console.py +++ b/src/devops_cli/output/console.py @@ -150,7 +150,7 @@ def write_stderr(text: str, *, flush: bool = True) -> None: write_stream(text, stream="stderr", flush=flush) -def print( +def print( # noqa: C901 content: Any = "", *, level: MessageLevel = "raw", diff --git a/src/devops_cli/security/aibom.py b/src/devops_cli/security/aibom.py index bac07cc31c..4384705aab 100644 --- a/src/devops_cli/security/aibom.py +++ b/src/devops_cli/security/aibom.py @@ -123,7 +123,7 @@ def estimate_hardware_requirements( ) -def detect_trust_remote_code(target_dir: Path) -> bool: +def detect_trust_remote_code(target_dir: Path) -> bool: # noqa: C901 """Detect whether a model directory contains or triggers trust_remote_code execution.""" if not target_dir.exists(): return False diff --git a/src/devops_cli/security/reference_extractor.py b/src/devops_cli/security/reference_extractor.py index 5d09379663..6bc80c4980 100644 --- a/src/devops_cli/security/reference_extractor.py +++ b/src/devops_cli/security/reference_extractor.py @@ -197,7 +197,7 @@ def _is_unspecified_ip_host(target: str) -> bool: @functools.lru_cache(maxsize=4096) -def is_example_or_invalid_network_target(target: str) -> bool: +def is_example_or_invalid_network_target(target: str) -> bool: # noqa: C901 """Check if any network target (URL, IP, domain, phone) is a documented example or invalid reference.""" clean = target.strip().rstrip(".,;)>]\"'") if not clean: @@ -281,7 +281,7 @@ def is_local_or_reserved_domain(target: str) -> bool: @functools.lru_cache(maxsize=16) -def _get_workspace_filenames(root_dir_str: str = "") -> tuple[set[str], tuple[str, ...]]: +def _get_workspace_filenames(root_dir_str: str = "") -> tuple[set[str], tuple[str, ...]]: # noqa: C901 """Recursively discover all file names and relative paths across the workspace respecting .gitignore.""" root = Path(root_dir_str) if root_dir_str else Path.cwd() if not root.exists() or not root.is_dir(): @@ -528,7 +528,7 @@ def _is_known_python_module(name: str) -> bool: @functools.lru_cache(maxsize=4096) -def is_file_reference(target: str, source_file: str = "") -> bool: +def is_file_reference(target: str, source_file: str = "") -> bool: # noqa: C901 """Check if target string represents an existing file on disk, known extension, or search match. """ @@ -593,7 +593,7 @@ def is_file_reference(target: str, source_file: str = "") -> bool: @functools.lru_cache(maxsize=4096) -def is_code_or_config_reference(target: str, source_file: str = "") -> bool: +def is_code_or_config_reference(target: str, source_file: str = "") -> bool: # noqa: C901 """Differentiate code identifiers, method chains, and config keys from network hosts.""" clean = target.strip().rstrip(".,;)>]\"'") @@ -692,7 +692,7 @@ def is_code_or_config_reference(target: str, source_file: str = "") -> bool: @functools.lru_cache(maxsize=4096) -def is_network_domain(target: str, source_file: str = "") -> bool: +def is_network_domain(target: str, source_file: str = "") -> bool: # noqa: C901 """Validate whether target string is a legitimate public network domain using standard library parsers and the Public Suffix List (PSL). """ @@ -775,7 +775,7 @@ def _parse_python_token_string(tok_string: str) -> str | None: return clean_str if clean_str else None -def _extract_python_literals_and_comments(source: str) -> list[tuple[str, int]]: +def _extract_python_literals_and_comments(source: str) -> list[tuple[str, int]]: # noqa: C901 """Extract string constants and comments from Python source code with line numbers.""" literals: list[tuple[str, int]] = [] source = textwrap.dedent(source) @@ -1010,7 +1010,7 @@ def is_package_repository_asset(url: str, host: str = "") -> bool: return False -def _extract_url_reference( +def _extract_url_reference( # noqa: C901 clean_token: str, source_file: str, line_idx: int, @@ -1112,7 +1112,7 @@ def _extract_ip_reference( return None -def _extract_domain_reference( +def _extract_domain_reference( # noqa: C901 clean_token: str, text_segment: str, source_file: str, @@ -1297,7 +1297,7 @@ def deduplicate_network_references(refs: list[NetworkReference]) -> list[Network return sort_network_references(deduped) -def extract_network_references( +def extract_network_references( # noqa: C901 content: str, source_file: str = "", include_local: bool = True, @@ -1404,7 +1404,7 @@ def _extract_pip_dependencies(content_lines: list[str], file_name: str) -> list[ return deps -def _extract_pyproject_dependencies( +def _extract_pyproject_dependencies( # noqa: C901 content: str, content_lines: list[str], file_name: str ) -> list[DependencySpec]: """Parse dependencies from pyproject.toml format.""" diff --git a/src/devops_cli/security/structural_invariants.py b/src/devops_cli/security/structural_invariants.py index 9a12653ca7..22bc4bbd24 100644 --- a/src/devops_cli/security/structural_invariants.py +++ b/src/devops_cli/security/structural_invariants.py @@ -1,4 +1,4 @@ -"""AST-based structural invariants sentinel and verification module.""" +"""AST-based nesting-depth sentinel for the structural-invariants pre-commit hook.""" from __future__ import annotations @@ -7,12 +7,11 @@ from collections.abc import Sequence from pathlib import Path -from devops_cli.config.defaults import DEFAULT_MAX_COMPLEXITY, DEFAULT_MAX_NESTING_DEPTH +from devops_cli.config.defaults import DEFAULT_MAX_NESTING_DEPTH MAX_NESTING_DEPTH: int = DEFAULT_MAX_NESTING_DEPTH -MAX_COMPLEXITY: int = DEFAULT_MAX_COMPLEXITY -_DEPTH_AND_BRANCH = ( +_NESTING = ( ast.If, ast.While, ast.For, @@ -21,85 +20,64 @@ ast.With, ast.AsyncWith, ast.Assert, + ast.Match, ) +_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef) -def _measure(node: ast.AST, depth: int, state: dict[str, int]) -> None: - """Accumulate complexity and deepest nesting for one function.""" - state["depth"] = max(state["depth"], depth) +def measure(node: ast.AST) -> int: + """Return one function's deepest nesting. - if isinstance(node, _DEPTH_AND_BRANCH): - state["complexity"] += 1 - depth += 1 - elif isinstance(node, ast.BoolOp): - state["complexity"] += len(node.values) - 1 - elif isinstance(node, ast.IfExp): - state["complexity"] += 1 - elif isinstance(node, ast.Match): - state["complexity"] += len(node.cases) - depth += 1 - - for child in ast.iter_child_nodes(node): + An explicit stack, not recursion: `1 + 1 + ... + 1` parses into one node per term, so a + long expression that `ast.parse` accepts would exceed Python's recursion limit (#586). + """ + deepest = 0 + pending: list[tuple[ast.AST, int]] = [(node, 0)] + while pending: + current, depth = pending.pop() + deepest = max(deepest, depth) + inner = depth + isinstance(current, _NESTING) # A nested function carries its own budget, as the scanner treats it. - if not isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): - _measure(child, depth, state) - - -def measure(node: ast.AST) -> tuple[int, int]: - """Return one function's cyclomatic complexity and deepest nesting.""" - state = {"complexity": 1, "depth": 0} - for child in ast.iter_child_nodes(node): - if not isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): - _measure(child, 0, state) - return state["complexity"], state["depth"] + pending.extend( + (child, inner) + for child in ast.iter_child_nodes(current) + if not isinstance(child, _FUNCTIONS) + ) + return deepest -def breaches( - path: Path, - max_depth: int = DEFAULT_MAX_NESTING_DEPTH, - max_complexity: int = DEFAULT_MAX_COMPLEXITY, -) -> tuple[list[str], int]: - """Report nesting breaches, and count complexity breaches separately.""" +def breaches(path: Path, max_depth: int = DEFAULT_MAX_NESTING_DEPTH) -> list[str]: + """Report every function in one file nested deeper than the cap.""" try: tree = ast.parse(path.read_text(encoding="utf-8")) - except (OSError, SyntaxError) as exc: - return [f"{path}: could not parse ({exc})"], 0 + except (OSError, SyntaxError, RecursionError) as exc: + # The parser itself overflows the stack on a long enough expression. + return [f"{path}: could not parse ({exc})"] - found: list[str] = [] - over_complex = 0 - for node in ast.walk(tree): - if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): - continue - complexity, depth = measure(node) - if depth > max_depth: - found.append(f"{path}:{node.lineno}: {node.name} nesting {depth} > {max_depth}") - over_complex += int(complexity > max_complexity) - return found, over_complex + return [ + f"{path}:{node.lineno}: {node.name} nesting {depth} > {max_depth}" + for node in ast.walk(tree) + if isinstance(node, _FUNCTIONS) and (depth := measure(node)) > max_depth + ] def check_structural_invariants( paths: Sequence[Path | str], max_depth: int = DEFAULT_MAX_NESTING_DEPTH, - max_complexity: int = DEFAULT_MAX_COMPLEXITY, -) -> tuple[list[str], int]: - """Audit paths for structural invariant violations, returning breaches and complexity count.""" +) -> list[str]: + """Audit paths for nesting breaches.""" found: list[str] = [] - over_complex = 0 for name in paths: path = Path(name) if path.suffix == ".py" and path.is_file(): - file_found, file_complex = breaches( - path, max_depth=max_depth, max_complexity=max_complexity - ) - found.extend(file_found) - over_complex += file_complex - return found, over_complex + found.extend(breaches(path, max_depth=max_depth)) + return found def main(argv: list[str] | None = None) -> int: """Check Python files passed via argv, reporting every breach before failing.""" args = sys.argv[1:] if argv is None else argv - found, over_complex = check_structural_invariants(args) + found = check_structural_invariants(args) for line in found: print(line, file=sys.stderr) @@ -109,12 +87,6 @@ def main(argv: list[str] | None = None) -> int: f"{DEFAULT_MAX_NESTING_DEPTH}; decompose the block into a helper.", file=sys.stderr, ) - if over_complex: - print( - f"note: {over_complex} changed function(s) exceed complexity " - f"{DEFAULT_MAX_COMPLEXITY}. Not blocking -- see the roadmap entry on the existing debt.", - file=sys.stderr, - ) return 1 if found else 0 diff --git a/tests/test_ai_gateway_tune.py b/tests/test_ai_gateway_tune.py index 38446e2a06..d6cb28991a 100644 --- a/tests/test_ai_gateway_tune.py +++ b/tests/test_ai_gateway_tune.py @@ -335,7 +335,7 @@ def test_bench_script_is_the_bench_module_plus_a_call_with_the_spec(self) -> Non printed: list[str] = [] namespace["print"] = printed.append - exec(compile(script, "", "exec"), namespace) # noqa: S102 - the script under test + exec(compile(script, "", "exec"), namespace) # the script under test assert json.loads(printed[-1]) == [] diff --git a/tests/test_architectural_invariants.py b/tests/test_architectural_invariants.py index ba043bf719..5f374bb40a 100644 --- a/tests/test_architectural_invariants.py +++ b/tests/test_architectural_invariants.py @@ -4,13 +4,33 @@ import ast import tomllib -from collections.abc import Sequence +from collections.abc import Iterable, Mapping, Sequence from pathlib import Path +from typing import Any + +import pathspec +import pytest from devops_cli.config.constants import ( CONST_BLIND_EXCEPTION_TYPES, + CONST_C901_SUPPRESSION, + CONST_COMPLEXITY_CAP_ROOTS, + CONST_COMPLEXITY_LINT_RULES, + CONST_GITIGNORE_FILENAME, + CONST_GITIGNORE_PATTERN_STYLE, + CONST_RUFF_C901_SUPPRESSION_COMMENT, + CONST_RUFF_CONFIG_FILE_NAMES, + CONST_RUFF_EXCLUDE, + CONST_RUFF_FILE_EXEMPTION, + CONST_RUFF_IGNORE_FILE_NAMES, + CONST_RUFF_LINT_KEYS, + CONST_RUFF_MCCABE_KEYS, + CONST_RUFF_PER_FILE_IGNORE_KEYS, + CONST_RUFF_SOURCE_SUFFIXES, + CONST_RUFF_TOP_LEVEL_KEYS, CONST_TEST_ASSERTION_LINT_RULES, ) +from devops_cli.config.defaults import DEFAULT_C901_SUPPRESSION_CEILING, DEFAULT_MAX_COMPLEXITY from devops_cli.exceptions.base import DevOpsCLIError @@ -157,16 +177,6 @@ def test_no_excessive_nesting_in_src() -> None: ) -def test_filesystem_get_tools_complexity() -> None: - """Ensure FileSystem.get_tools maintains cyclomatic complexity <= 10.""" - from devops_cli.security.complexity import run_complexity_scan - - mod = Path("src/devops_cli/ai/harness/filesystem.py") - findings = run_complexity_scan(mod, max_complexity=10, max_nesting_depth=5) - tools_findings = [f for f in findings if "get_tools" in f.title] - assert not tools_findings, f"FileSystem.get_tools exceeded complexity limit: {tools_findings}" - - def test_no_bare_generic_exceptions_in_refactored_modules() -> None: """Ensure refactored domain modules do not raise bare ValueError, RuntimeError, or TypeError.""" import ast @@ -304,7 +314,7 @@ def _record_import_edges( _resolve_import_from_edge(sub, mod, pkg_parts, module_files, graph) -def test_no_circular_imports_in_decoupled_subsystems() -> None: +def test_no_circular_imports_in_decoupled_subsystems() -> None: # noqa: C901 """Ensure decoupled subsystems (k8s commands, output, ai.review, config) have zero circular imports.""" from collections import defaultdict @@ -558,6 +568,573 @@ def test_a_broad_ignore_defeats_a_broad_select() -> None: ) == (False, True) +def _unlisted_keys(table: str, keys: Iterable[str], allowed: frozenset[str]) -> list[str]: + """Name each key of one table that its allowlist does not admit.""" + return [f"[{table}] {key}: outside the allowlist" for key in sorted(set(keys) - allowed)] + + +def _names_rule(rule: str, code: str) -> bool: + """Report whether one selector names a rule, by Ruff's prefix matching.""" + return code == "ALL" or rule.startswith(code) + + +def _lint_escapes(lint: Mapping[str, Any]) -> list[str]: + """Report an unenforced cap rule, a per-file waiver of one, or a moved complexity limit. + + A cap rule counts as enforced only when `select` names it by its own code. Ruff redirects + some prefixes before it weighs them (`C9` reads as `C90`), so `C90` selected with `C9` + ignored turns C901 off while `_ruff_enforces`, ranking by length, calls it on. Only the same + code can tie an exact code, and `_ruff_enforces` gives that tie to ignore, as Ruff does. + """ + select = [*lint.get("select", []), *lint.get("extend-select", [])] + ignore = [*lint.get("ignore", []), *lint.get("extend-ignore", [])] + rules = sorted(CONST_COMPLEXITY_LINT_RULES) + unenforced = [ + f"{rule}: not enforced" + for rule in rules + if rule not in select or not _ruff_enforces(rule, select, ignore) + ] + waived = [ + f"[tool.ruff.lint.{table}] {pattern}: waives {rule}" + for table in CONST_RUFF_PER_FILE_IGNORE_KEYS + for pattern, codes in lint.get(table, {}).items() + for rule in rules + if any(_names_rule(rule, code) for code in codes) + ] + mccabe = lint.get("mccabe", {}) + cap = mccabe.get("max-complexity") + raised = f"[tool.ruff.lint.mccabe] max-complexity: {cap}, not {DEFAULT_MAX_COMPLEXITY}" + return [ + *_unlisted_keys("tool.ruff.lint", lint, CONST_RUFF_LINT_KEYS), + *unenforced, + *waived, + *_unlisted_keys("tool.ruff.lint.mccabe", mccabe, CONST_RUFF_MCCABE_KEYS), + *([] if cap == DEFAULT_MAX_COMPLEXITY else [raised]), + ] + + +def _covered_files(project: Path) -> list[Path]: + """List every file under the roots the complexity cap covers.""" + return sorted( + path + for root in CONST_COMPLEXITY_CAP_ROOTS + for path in (project / root).rglob("*") + if path.is_file() + ) + + +_SOURCE_ESCAPES = ( + (CONST_RUFF_FILE_EXEMPTION, "file-level noqa"), + (CONST_RUFF_C901_SUPPRESSION_COMMENT, "a ruff suppression comment naming C901"), +) + + +def _source_escapes(project: Path, sources: Iterable[Path]) -> list[str]: + """Report each source that exempts itself, or hides C901 behind a comment no marker counts.""" + texts = { + path.relative_to(project).as_posix(): path.read_text(encoding="utf-8") for path in sources + } + return [ + f"{name}: {escape}" + for name, text in texts.items() + for pattern, escape in _SOURCE_ESCAPES + if pattern.search(text) + ] + + +def _ignore_file_escapes( + project: Path, covered: Sequence[Path], sources: Sequence[Path] +) -> list[str]: + """Report an ignore file that drops a covered source from Ruff's walk of the project. + + The root `.gitignore` is the project's own and stays, so only a source it matches is an + escape; an ignore file under a covered root, or a root `.ignore`, is one by being there. + """ + gitignore = project / CONST_GITIGNORE_FILENAME + lines = gitignore.read_text(encoding="utf-8").splitlines() if gitignore.is_file() else [] + listed = pathspec.PathSpec.from_lines(CONST_GITIGNORE_PATTERN_STYLE, lines) + nested = [ + f"{path.relative_to(project).as_posix()}: an ignore file under a covered root" + for path in covered + if path.name in CONST_RUFF_IGNORE_FILE_NAMES + ] + beside = [ + f"{name}: an ignore file beside pyproject.toml" + for name in sorted(CONST_RUFF_IGNORE_FILE_NAMES - {CONST_GITIGNORE_FILENAME}) + if (project / name).exists() + ] + names = [path.relative_to(project).as_posix() for path in sources] + matched = [ + f"{name}: matched by {CONST_GITIGNORE_FILENAME}" + for name in names + if listed.match_file(name) + ] + return [*nested, *beside, *matched] + + +def _tree_escapes(project: Path) -> list[str]: + """Report a source that suppresses C901 without a marker, or a file that hides one from Ruff.""" + covered = _covered_files(project) + sources = [path for path in covered if path.suffix in CONST_RUFF_SOURCE_SUFFIXES] + nested = [ + f"{path.relative_to(project).as_posix()}: a Ruff config under a covered root" + for path in covered + if path.name in CONST_RUFF_CONFIG_FILE_NAMES + ] + outranking = [ + f"{name}: outranks pyproject.toml" + for name in sorted(CONST_RUFF_CONFIG_FILE_NAMES - {"pyproject.toml"}) + if (project / name).exists() + ] + return [ + *_source_escapes(project, sources), + *nested, + *outranking, + *_ignore_file_escapes(project, covered, sources), + ] + + +def _complexity_cap_escapes(pyproject: Mapping[str, Any], project: Path) -> list[str]: + """Report every way a committed file lets a function past the C901 cap without a marker. + + Keys are checked against allowlists rather than a list of known escapes, so a setting + Ruff adds later is reported until a reviewed change admits it. `per-file-ignores` stays + allowed for other rules; an entry covering C901, RUF100 or PGH004 is an escape. Ignore + files outside the checkout (`.git/info/exclude`, a global gitignore, one above the + project) differ per machine and never reach the clean checkout GitHub CI lints. + """ + ruff = pyproject.get("tool", {}).get("ruff", {}) + exclude, expected = ruff.get("exclude"), [*CONST_RUFF_EXCLUDE] + widened = f"[tool.ruff] exclude: {exclude}, not {expected}" + return [ + *_unlisted_keys("tool.ruff", ruff, CONST_RUFF_TOP_LEVEL_KEYS), + *([] if exclude == expected else [widened]), + *_lint_escapes(ruff.get("lint", {})), + *_tree_escapes(project), + ] + + +def _c901_suppressions(project: Path) -> dict[str, int]: + """Count the noqa comments naming C901 in each covered file, keyed by its project path. + + A regex over the text, not `tokenize`: tokenizing the tree took 1.2-8.0 s (#586). + """ + counts = { + path.relative_to(project).as_posix(): len( + CONST_C901_SUPPRESSION.findall(path.read_text(encoding="utf-8")) + ) + for path in _covered_files(project) + if path.suffix in CONST_RUFF_SOURCE_SUFFIXES + } + return {name: count for name, count in counts.items() if count} + + +def _c901_suppressions_over(project: Path, ceiling: int) -> tuple[int, list[str]]: + """Return how far the C901 suppressions exceed a ceiling, and the files that carry them.""" + counts = _c901_suppressions(project) + excess = sum(counts.values()) - ceiling + return (excess, sorted(counts)) if excess > 0 else (0, []) + + +_DROP = object() +# Built here so this file's own text holds no file-level exemption, no C901 marker and no +# Ruff suppression comment naming C901. Ruff honours each spelling below (checked on 0.16.8). +_RUFF_FILE_NOQA = "# " + "ruff" + ": noqa" +_FLAKE8_FILE_NOQA = "# " + "flake8" + ": noqa" +_C901_MARKER = "# " + "noqa: " + "C901" +_RUFF_COMMENT = "# " + "ruff" + ": " +_FORM_FEED, _NO_BREAK_SPACE, _EM_SPACE = "\x0c", "\xa0", "\u2003" + + +def _complying_pyproject() -> dict[str, Any]: + """Build, as a fresh dict, a pyproject.toml the complexity cap's meta-test accepts.""" + lint = { + "select": ["E", *sorted(CONST_COMPLEXITY_LINT_RULES)], + "ignore": ["E501"], + "mccabe": {"max-complexity": DEFAULT_MAX_COMPLEXITY}, + } + ruff = {"target-version": "py314", "line-length": 100, "exclude": [*CONST_RUFF_EXCLUDE]} + return {"tool": {"ruff": {**ruff, "lint": lint}}} + + +def _edit(table: dict[str, Any], path: Sequence[str], value: object) -> None: + """Set, or with `_DROP` delete, the key a path names inside nested tables.""" + *parents, key = path + for name in parents: + table = table[name] + if value is _DROP: + del table[key] + else: + table[key] = value + + +_COMPLEXITY_CAP_ESCAPES = [ + pytest.param((), None, {}, [], id="complying"), + pytest.param( + ("per-file-ignores",), + {"pkg/*": ["C901"]}, + {}, + ["[tool.ruff] per-file-ignores: outside the allowlist"], + id="top-level-per-file-ignores", + ), + pytest.param( + ("extend-ignore",), + ["C901"], + {}, + ["[tool.ruff] extend-ignore: outside the allowlist"], + id="top-level-extend-ignore", + ), + pytest.param( + ("include",), + ["src/devops_cli/cli.py"], + {}, + ["[tool.ruff] include: outside the allowlist"], + id="include", + ), + pytest.param( + ("extend",), + "../ruff.toml", + {}, + ["[tool.ruff] extend: outside the allowlist"], + id="extend", + ), + pytest.param( + ("extend-exclude",), + ["src"], + {}, + ["[tool.ruff] extend-exclude: outside the allowlist"], + id="extend-exclude", + ), + pytest.param( + ("lint", "exclude"), + ["src/**"], + {}, + ["[tool.ruff.lint] exclude: outside the allowlist"], + id="lint-exclude", + ), + pytest.param( + ("exclude",), + ["repos", "src"], + {}, + ["[tool.ruff] exclude: ['repos', 'src'], not ['repos']"], + id="exclude", + ), + pytest.param( + ("lint", "select"), + ["E", "PGH004", "RUF100"], + {}, + ["C901: not enforced"], + id="c901-unselected", + ), + pytest.param( + ("lint", "ignore"), + ["E501", "C901"], + {}, + ["C901: not enforced"], + id="c901-ignored", + ), + pytest.param( + ("lint", "extend-ignore"), + ["RUF100"], + {}, + ["RUF100: not enforced"], + id="ruf100-extend-ignored", + ), + pytest.param( + ("lint", "select"), + ["E", "C901", "RUF100"], + {}, + ["PGH004: not enforced"], + id="pgh004-unselected", + ), + pytest.param( + ("lint",), + { + "select": ["E", "C90", "PGH004", "RUF100"], + "ignore": ["E501", "C9"], + "mccabe": {"max-complexity": DEFAULT_MAX_COMPLEXITY}, + }, + {}, + ["C901: not enforced"], + id="c901-selected-as-c90-and-ignored-as-c9", + ), + pytest.param( + ("lint", "ignore"), + ["E501", "C9"], + {}, + [], + id="c9-ignored-under-an-exact-c901", + ), + pytest.param( + ("lint", "mccabe", "max-complexity"), + 11, + {}, + ["[tool.ruff.lint.mccabe] max-complexity: 11, not 10"], + id="max-complexity-raised", + ), + pytest.param( + ("lint", "mccabe", "max-complexity"), + _DROP, + {}, + ["[tool.ruff.lint.mccabe] max-complexity: None, not 10"], + id="max-complexity-missing", + ), + pytest.param( + ("lint", "mccabe", "ignore-names"), + ["main"], + {}, + ["[tool.ruff.lint.mccabe] ignore-names: outside the allowlist"], + id="mccabe-extra-key", + ), + pytest.param( + ("lint", "per-file-ignores"), + {"tests/*": ["C9"]}, + {}, + ["[tool.ruff.lint.per-file-ignores] tests/*: waives C901"], + id="per-file-ignores", + ), + pytest.param( + ("lint", "extend-per-file-ignores"), + {"src/*": ["ALL"]}, + {}, + [ + "[tool.ruff.lint.extend-per-file-ignores] src/*: waives C901", + "[tool.ruff.lint.extend-per-file-ignores] src/*: waives PGH004", + "[tool.ruff.lint.extend-per-file-ignores] src/*: waives RUF100", + ], + id="extend-per-file-ignores", + ), + pytest.param( + ("lint", "per-file-ignores"), + {"src/*": ["PGH"]}, + {}, + ["[tool.ruff.lint.per-file-ignores] src/*: waives PGH004"], + id="per-file-ignores-blanket-noqa", + ), + pytest.param( + (), + None, + {"src/pkg/mod.py": f"{_RUFF_FILE_NOQA}\n"}, + ["src/pkg/mod.py: file-level noqa"], + id="ruff-file-noqa", + ), + pytest.param( + (), + None, + {"src/mod.py": f"{_RUFF_FILE_NOQA}: C901\n"}, + ["src/mod.py: file-level noqa"], + id="ruff-file-noqa-naming-c901", + ), + pytest.param( + (), + None, + {"tests/test_mod.py": f"{_FLAKE8_FILE_NOQA}\n"}, + ["tests/test_mod.py: file-level noqa"], + id="flake8-file-noqa", + ), + pytest.param( + (), + None, + {"src/mod.py": f"#{_FORM_FEED}{_RUFF_FILE_NOQA[2:]}: C901\n"}, + ["src/mod.py: file-level noqa"], + id="ruff-file-noqa-after-a-form-feed", + ), + pytest.param( + (), + None, + {"tests/test_mod.py": f"#{_NO_BREAK_SPACE}{_FLAKE8_FILE_NOQA[2:]}\n"}, + ["tests/test_mod.py: file-level noqa"], + id="flake8-file-noqa-after-a-no-break-space", + ), + pytest.param( + (), + None, + {"src/mod.py": f"def f(x): {_RUFF_COMMENT}ignore[C901]\n return x\n"}, + ["src/mod.py: a ruff suppression comment naming C901"], + id="ruff-ignore-naming-c901", + ), + pytest.param( + (), + None, + { + "src/pkg/mod.py": f"{_RUFF_COMMENT}disable[C901]\n" + "def f(x):\n return x\n" + f"{_RUFF_COMMENT}enable[C901]\n" + }, + ["src/pkg/mod.py: a ruff suppression comment naming C901"], + id="ruff-disable-enable-pair", + ), + pytest.param( + (), + None, + {"tests/test_mod.py": "#" + "ruff:" + "disable[E501,C901]\ndef f(x):\n return x\n"}, + ["tests/test_mod.py: a ruff suppression comment naming C901"], + id="ruff-disable-unpaired-unspaced", + ), + pytest.param( + (), + None, + {"src/mod.py": f"{_RUFF_COMMENT}file-ignore[C901]\n"}, + ["src/mod.py: a ruff suppression comment naming C901"], + id="ruff-file-ignore", + ), + pytest.param( + (), + None, + {"src/mod.py": f"#{_EM_SPACE}{_RUFF_COMMENT[2:]}{_EM_SPACE}disable[ C901 ]\n"}, + ["src/mod.py: a ruff suppression comment naming C901"], + id="ruff-disable-after-em-spaces", + ), + pytest.param( + (), + None, + {"src/pkg/.ignore": "mod.py\n", "src/pkg/mod.py": ""}, + ["src/pkg/.ignore: an ignore file under a covered root"], + id="nested-ignore-file", + ), + pytest.param( + (), + None, + {"tests/.gitignore": "test_mod.py\n", "tests/test_mod.py": ""}, + ["tests/.gitignore: an ignore file under a covered root"], + id="nested-gitignore", + ), + pytest.param( + (), + None, + {".ignore": "src/mod.py\n", "src/mod.py": ""}, + [".ignore: an ignore file beside pyproject.toml"], + id="project-ignore-file", + ), + pytest.param( + (), + None, + { + ".gitignore": "__pycache__/\n*.py[cod]\nsrc/pkg/hidden.py\n", + "src/pkg/hidden.py": "", + "src/pkg/kept.py": "", + "src/pkg/__pycache__/kept.cpython-314.pyc": "", + }, + ["src/pkg/hidden.py: matched by .gitignore"], + id="project-gitignore-listing-a-source", + ), + pytest.param( + (), + None, + {"src/pkg/ruff.toml": ""}, + ["src/pkg/ruff.toml: a Ruff config under a covered root"], + id="nested-ruff-toml", + ), + pytest.param( + (), + None, + {"tests/.ruff.toml": ""}, + ["tests/.ruff.toml: a Ruff config under a covered root"], + id="nested-dot-ruff-toml", + ), + pytest.param( + (), + None, + {"src/pkg/pyproject.toml": ""}, + ["src/pkg/pyproject.toml: a Ruff config under a covered root"], + id="nested-pyproject-toml", + ), + pytest.param( + (), + None, + {"ruff.toml": ""}, + ["ruff.toml: outranks pyproject.toml"], + id="project-ruff-toml", + ), +] + + +@pytest.mark.parametrize(("path", "value", "files", "expected"), _COMPLEXITY_CAP_ESCAPES) +def test_every_complexity_cap_escape_is_reported( + tmp_path: Path, + path: Sequence[str], + value: object, + files: Mapping[str, str], + expected: list[str], +) -> None: + """Each way past the cap, in the configuration or in the tree, is reported by itself. + + Ruff 0.16 still honours the deprecated top-level `per-file-ignores` and `extend-ignore`, + and `include`, `extend` and `lint.exclude` change which files or which settings apply, + so the helper allows known keys rather than forbidding known escapes. + """ + pyproject = _complying_pyproject() + if path: + _edit(pyproject["tool"]["ruff"], path, value) + for name, text in files.items(): + (tmp_path / name).parent.mkdir(parents=True, exist_ok=True) + (tmp_path / name).write_text(text, encoding="utf-8") + + assert _complexity_cap_escapes(pyproject, tmp_path) == expected + + +def test_the_complexity_cap_has_no_escape() -> None: + """Ruff's C901 is the cap of 10 (#586), and only a counted marker takes a function past it. + + `_ruff_enforces` alone reads `select` and `ignore`; a raised `max-complexity`, a + per-file waiver, a nested config, a file-level exemption, one of Ruff's own bracketed + suppression comments or an ignore file would each pass it. + """ + repo_root = Path(__file__).resolve().parents[1] + pyproject = tomllib.loads((repo_root / "pyproject.toml").read_text(encoding="utf-8")) + assert _complexity_cap_escapes(pyproject, repo_root) == [] + + +def test_c901_suppressions_stay_under_the_ceiling() -> None: + """The functions over the cap when Ruff began enforcing it may only become fewer. + + Each carries a C901 marker that RUF100 reports once the function is back under the cap. + A new marker takes the count past `DEFAULT_C901_SUPPRESSION_CEILING` and fails here. + """ + repo_root = Path(__file__).resolve().parents[1] + excess, files = _c901_suppressions_over(repo_root, DEFAULT_C901_SUPPRESSION_CEILING) + assert (excess, files) == (0, []), ( + f"{excess} more C901 marker(s) than DEFAULT_C901_SUPPRESSION_CEILING allows, " + f"among these files: {files}. Decompose the function the new marker sits on until " + "Ruff no longer reports it; do not raise the ceiling." + ) + + +def test_suppressions_over_the_ceiling_name_their_files(tmp_path: Path) -> None: + """Both forms `--add-noqa` writes count, once per comment, and the excess names its file.""" + (tmp_path / "src").mkdir() + (tmp_path / "tests").mkdir() + (tmp_path / "src" / "over.py").write_text( + f"def f(x): {_C901_MARKER}\n return x\n\n\n" + f"def do_GET(x): {_C901_MARKER}, N802\n return x\n", + encoding="utf-8", + ) + (tmp_path / "tests" / "test_clean.py").write_text("def g(x):\n return x\n", "utf-8") + + assert ( + _c901_suppressions(tmp_path), + _c901_suppressions_over(tmp_path, 1), + _c901_suppressions_over(tmp_path, 2), + ) == ({"src/over.py": 2}, (1, ["src/over.py"]), (0, [])) + + +@pytest.mark.parametrize( + "marker", + [ + pytest.param(f"#{_FORM_FEED}{_C901_MARKER[2:]}", id="form-feed-after-the-hash"), + pytest.param(f"#{_NO_BREAK_SPACE}{_C901_MARKER[2:]}", id="no-break-space-after-the-hash"), + pytest.param(_C901_MARKER.replace(": ", f":{_EM_SPACE}"), id="em-space-after-the-colon"), + pytest.param(_C901_MARKER.replace(": ", " : E501 "), id="spaced-colon-unseparated-codes"), + ], +) +def test_every_marker_spelling_ruff_honours_is_counted(tmp_path: Path, marker: str) -> None: + """Ruff reads any whitespace but a newline inside a noqa comment, so each spelling counts.""" + (tmp_path / "src").mkdir() + (tmp_path / "src" / "mod.py").write_text(f"def f(x): {marker}\n return x\n", "utf-8") + + assert _c901_suppressions(tmp_path) == {"src/mod.py": 1} + + def test_manifests_by_stack_files_exist() -> None: """Every Kubernetes manifest declared in _MANIFESTS_BY_STACK must exist on disk.""" from devops_cli.commands.k8s.stack_lifecycle import _MANIFESTS_BY_STACK diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 739ccd8c46..f512ffe766 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -169,8 +169,8 @@ def test_one_error_code_maps_to_one_exit_status() -> None: `EmbeddingsError` reused `LLM_INFERENCE_ERROR` while exiting 1 rather than 10, so the generated catalog listed the same code against both. """ - import devops_cli.ai.client.models # noqa: F401 - import devops_cli.ai.rag.embeddings # noqa: F401 + import devops_cli.ai.client.models + import devops_cli.ai.rag.embeddings import devops_cli.exceptions.ai # noqa: F401 def descendants(cls: type[DevOpsCLIError]) -> list[type[DevOpsCLIError]]: diff --git a/tests/test_sandbox_metrics.py b/tests/test_sandbox_metrics.py index 0f9a7a2405..d3baf3db77 100644 --- a/tests/test_sandbox_metrics.py +++ b/tests/test_sandbox_metrics.py @@ -228,7 +228,7 @@ def test_parse_prometheus_exposition() -> None: class _MockPrometheusHandler(BaseHTTPRequestHandler): - def do_GET(self) -> None: # noqa: N802 + def do_GET(self) -> None: if self.path == "/metrics": self.send_response(200) self.send_header("Content-Type", "text/plain; version=0.0.4; charset=utf-8") diff --git a/tests/test_sandbox_probe.py b/tests/test_sandbox_probe.py index 79cb792d8f..f3319746f9 100644 --- a/tests/test_sandbox_probe.py +++ b/tests/test_sandbox_probe.py @@ -130,7 +130,7 @@ def test_probe_tcp_timeout() -> None: class _MockHTTPHandler(BaseHTTPRequestHandler): - def do_GET(self) -> None: # noqa: N802 + def do_GET(self) -> None: if self.path in ("/healthz", "/health", "/ready"): self.send_response(200) self.send_header("Content-Type", "application/json") diff --git a/tests/test_structural_invariant_hook.py b/tests/test_structural_invariant_hook.py index e875768b41..2f860f6b20 100644 --- a/tests/test_structural_invariant_hook.py +++ b/tests/test_structural_invariant_hook.py @@ -2,10 +2,15 @@ from __future__ import annotations +import ast import subprocess import sys from pathlib import Path +import pytest + +from devops_cli.security.structural_invariants import breaches, measure + def _run(*paths: Path) -> subprocess.CompletedProcess[str]: """Invoke the structural invariants sentinel exactly as pre-commit does.""" @@ -42,20 +47,6 @@ def test_shallow_nesting_passes(tmp_path: Path) -> None: assert _run(module).returncode == 0 -def test_complexity_is_reported_without_blocking(tmp_path: Path) -> None: - """240 functions in `src/` breach the complexity cap and nothing enforces it. - - Failing here would block work on any of those files rather than hold a line the - codebase is already on, so the breach is reported and the commit proceeds. - """ - module = tmp_path / "complex.py" - body = "def f(x):\n" + "".join(f" if x == {i}:\n return {i}\n" for i in range(14)) - module.write_text(body + " return None\n", encoding="utf-8") - - result = _run(module) - assert (result.returncode, "complexity" in result.stderr) == (0, True) - - def test_the_metric_matches_the_projects_own_scanner() -> None: """A hook stricter than the scanner rejects code the project accepts. @@ -79,3 +70,32 @@ def test_an_unparseable_file_is_reported_rather_than_skipped(tmp_path: Path) -> module = tmp_path / "broken.py" module.write_text("def f(:\n", encoding="utf-8") assert _run(module).returncode == 1 + + +def test_a_long_expression_is_measured_rather_than_overflowing(tmp_path: Path) -> None: + """`1 + 1 + ... + 1` parses one node deeper per term. + + A recursive walk spending two frames per node raised RecursionError from 600 terms on, a + traceback where the hook before it passed; the walk now keeps its own stack (#586). + """ + module = tmp_path / "long.py" + expression = " + ".join(["1"] * 3000) + module.write_text(f"def f(x):\n if x:\n return {expression}\n", encoding="utf-8") + function = ast.parse(module.read_text(encoding="utf-8")).body[0] + + assert (measure(function), breaches(module)) == (1, []) + + +def test_a_parser_overflow_is_reported_rather_than_raised( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """`ast.parse` raises RecursionError on an expression too deep for its own stack.""" + + def overflow(source: str) -> ast.Module: + raise RecursionError("Stack overflow during compilation") + + module = tmp_path / "deep.py" + module.write_text("x = 1\n", encoding="utf-8") + monkeypatch.setattr(ast, "parse", overflow) + + assert breaches(module) == [f"{module}: could not parse (Stack overflow during compilation)"]