Repository navigation
Description
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
switchwith 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/catchchain 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_decisionequivalents. - 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_nodeincrates/core/src/language.rs. Do not extend it — cyclomatic and cognitive deliberately count different things. - New field on
FunctionMetrics; extendScoreandmeasure_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 inadd_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.jsongains acognitivevalue, including the negative casesAGENTS.mdrequires (operator inside a string literal, unbracedelse <loop>,_ whenguard). - Output format, JSON shape (
Violation.metric), and exit codes are unchanged.
Checklist
- PR 1:
docs/spec.md— cognitive complexity section, algorithm pinned per language (docs(spec): pin the cognitive complexity algorithm per language #27) - PR 2: metric registry (deferred: no second language-specific metric yet, see feat: add cognitive complexity and make cyclomatic a backstop #28)
- PR 2: cognitive traversal +
FunctionMetricsfield (feat: add cognitive complexity and make cyclomatic a backstop #28) - PR 2: config schema, validator, per-language overrides, default limit (feat: add cognitive complexity and make cyclomatic a backstop #28)
- PR 2: golden fixtures for every language incl. negative cases (feat: add cognitive complexity and make cyclomatic a backstop #28)
-
Verify the env validator and the field summarizer pass on defaults. Amended: neither passes, and both failures are real- env validator: cognitive 61 (54 sequential guards), already corrected in the comment above
- field summarizer: cognitive 40. The prediction of low single digits assumed trivial
switcharms; its arms hold about 16 conditional expressions, several of them nested ternaries, and Sonar's algorithm scores it the same way. A real refactor, not a metric artifact (measured in feat: add cognitive complexity and make cyclomatic a backstop #28)
- Verify Rust
matchcases no longer need per-repo overrides (feat: add cognitive complexity and make cyclomatic a backstop #28) - PR/review (docs(spec): pin the cognitive complexity algorithm per language #27 spec, feat: add cognitive complexity and make cyclomatic a backstop #28 implementation; rebased on fix(svelte): score templates per top-level block and snippet #25, reviewed, CI green)
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
ElbertePlinio commentedon Aug 31, 2026
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:
switchscores +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-matchoverrides, which remains the strongest argument for this issue.ifguards 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:
match-heavy code no longer needs per-repocomplexityoverridesthe env validator passes— flat repetition is a real refactor, not a metric artifactAlso: 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_opsneeds no registry, andwidget_depthis the only language-specific metric planned — consider building it as a Dart-specific field and extracting a registry when a second one appears.docs(spec): pin the cognitive complexity algorithm per language
feat: add cognitive complexity as the default complexity gate