Skip to content

Per-language metric registry + cognitive complexity #7

Closed

Description

@ElbertePlinio

Parent: #6

Add cognitive complexity as a per-function metric, and introduce the metric registry it needs.

Why

Cyclomatic complexity counts branches; it cannot tell a 30-arm dispatch from a 5-level nest. Two real cases from the private SvelteKit app scan (details in #6):

  • a server env validator — complexity 54, a flat sequence of guard clauses.
  • a profile-field summarizer — complexity 30, a switch with independent arms.

Both are readable and both fail today. Cognitive complexity penalizes nesting and continuity breaks instead, and would score both near zero. Same reason Rust consumers need per-repo complexity overrides for large match expressions. Already listed as a v2 candidate in docs/spec.md.

Spec first

AGENTS.md makes docs/spec.md the contract, and cognitive complexity is underspecified by name alone — without one pinned algorithm the golden fixtures become arbitrary. PR 1 is spec-only and carries all the judgment:

  • Which nodes increment, which nest, and by how much.
  • else / elif / catch chain handling.
  • Sequences of like logical operators (one increment per sequence, not per operator).
  • Recursion.
  • One explicit rule table per language: js_decision, dart_decision, rust_decision, python_decision, go_decision equivalents.
  • Svelte template rules, defined independently — they cannot inherit the TS rules.

Metric registry

Limits is a fixed struct of four usize fields and add_violations walks a hard-coded array, so there is no way to add a metric that exists for only some languages. Building the registry alongside cognitive complexity is cheaper than retrofitting it, and it unblocks later per-language checks (explicit any / as assertions for TS, unwrap() for Rust, bare except: for Python, ignored errors for Go, ! assertions for Dart). Those are follow-ups, not scope here.

Implementation notes

  • Add a separate traversal beside measure_node in crates/core/src/language.rs. Do not extend it — cyclomatic and cognitive deliberately count different things.
  • New field on FunctionMetrics; extend Score and measure_function.
  • crates/core/src/config.rs: Limits, LimitOverrides, validate_keys, validate_language_keys, Config::limits_for. The strict validator must admit the new key.
  • crates/core/src/scan.rs: emit in add_violations.
  • config.default.json: limits.cognitive (default 15, pending the rollout decision in Metric expansion: cognitive complexity and Svelte template scoping #6).
  • Every tests/fixtures/<language>/expected.json gains a cognitive value, including the negative cases AGENTS.md requires (operator inside a string literal, unbraced else <loop>, _ when guard).
  • Output format, JSON shape (Violation.metric), and exit codes are unchanged.

Checklist

Validation

cargo test --workspace --locked --all-targets
cargo clippy --workspace --all-targets -- -D warnings
cargo llvm-cov
cargo run -- check crates
complexity-gate check --format json <private-svelte-app>/src   # before/after comparison

Risks

  • Determinism is the main one: one algorithm, pinned in the spec, committed in fixtures. No per-language improvisation during implementation.
  • Hook latency: linear in AST size, computed in a second walk. Measure before merge.
  • Diff size is large. If it grows further during implementation, split the registry into its own PR.

Status: Done
Outcome: cognitive is the default gate at 15; complexity is measured but off by default (null).

Activity

  1. added
    enhancement
    on Aug 31, 2026
  2. ElbertePlinio commented on Aug 31, 2026

    @ElbertePlinio
    MemberAuthor

    Acceptance criteria corrected after measurement (full data in the #6 comment).

    This issue claimed both motivating functions should pass on default limits once cognitive complexity lands. Only one will:

    • the field summarizer (cyclomatic 30) — a switch scores +1 for the whole switch under cognitive complexity regardless of arm count, so it drops to low single digits. Genuine false positive, genuinely fixed. Same mechanism that retires the Rust big-match overrides, which remains the strongest argument for this issue.
    • the env validator (cyclomatic 54) — 54 sequential if guards each still increment under cognitive complexity, so it lands near 54 and still fails. That is probably the right answer: 54 distinct validations in one sub-100-line function is a table or a loop waiting to happen.

    Revised acceptance:

    • The field summarizer passes on default limits
    • Rust match-heavy code no longer needs per-repo complexity overrides
    • the env validator passes — flat repetition is a real refactor, not a metric artifact

    Also: a cheap substitute for this issue (nesting-weighted complexity, score += 1 + depth) was prototyped and rejected — it scores the env validator 5th-highest of 17,414 functions and no threshold separates flat from nested. Full cognitive complexity is the only remaining candidate. Details in #6.

    Scope note: the metric registry in this issue is no longer a prerequisite for #9. bool_ops needs no registry, and widget_depth is the only language-specific metric planned — consider building it as a Dart-specific field and extracting a registry when a second one appears.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions