Repository navigation
Description
Expand the metric set beyond the v1 four (complexity, depth, lines, params), driven by evidence from a real scan rather than by a metrics checklist.
Why
A widely-shared "AI slop" checklist proposes ten metrics (cyclomatic < 22, cognitive < 22, Halstead Difficulty < 80, LOC/file < 500, 100% coverage, CRAP < 25, 0 surviving mutants, 0 dead code, 0 redundant code, 0 any/unknown). Most of it is rejected — see "Rejected" below. Two changes survived, and the case for both comes from scanning a private SvelteKit + TS app with complexity-gate 0.1.1.
Evidence: private SvelteKit app scan
complexity-gate check --format json src → 3647 functions checked, 44 violations across 28 files.
| Metric | Violations |
|---|---|
| complexity | 31 |
| lines | 8 |
| depth | 4 |
| params | 1 |
Two patterns dominate:
1. Flat, readable code fails the cyclomatic limit.
- a server env validator — complexity 54. A sequential list of
if (!config.x) errors.push(...)guards. The 55th check is no harder to read than the 5th. - a profile-field summarizer — complexity 30. A
switchwhere every arm is independent and self-contained.
Neither is slop; both fail today. Cognitive complexity scores nesting and continuity breaks rather than branch count, so both would drop near zero. This is also the pattern behind the per-repo complexity overrides Rust consumers currently need for large match expressions.
2. Svelte templates are measured as one pseudo-function.
12 of 44 violations are <template>. Its largest route page scores complexity 137 — a 2675-line template with 94 {#if}/{#each}/{#await} blocks collapsed into a single number. A limit of 15 against a whole-file metric can only ever say "this template is big", which is not incrementally actionable.
Corpus survey (2026-08-31)
complexity-gate 0.1.1 scanned across 20 repos in ~/Projects/Personal and ~/Projects/Pickforge:
| repo | functions | violations | breakdown |
|---|---|---|---|
| pickforge | 10184 | 134 | complexity 55, lines 59, params 14, depth 6 |
| pickarena | 5376 | 116 | complexity 67, lines 45, params 2, depth 2 |
| private SvelteKit app | 4053 | 50 | complexity 36, lines 9, depth 4, params 1 |
| picklab | 3139 | 48 | complexity 23, lines 20, depth 5 |
| private Flutter app | 4667 | 20 | lines 13, complexity 5, depth 2 |
| private TS repo | 1135 | 20 | complexity 12, lines 8 |
| pickforge-platform | 2688 | 19 | lines 6, complexity 10, params 2, depth 1 |
| pickscribe | 1143 | 17 | lines 7, complexity 7, depth 3 |
| pickgauge | 2158 | 11 | complexity 7, lines 2, params 2 |
(complexity-gate's own 29 violations are almost entirely deliberate test fixtures.)
Three investigation lanes then mined the corpus for problems the four metrics miss: TS/Svelte and Dart/Flutter (GPT-5.6 Sol, high), Rust (Grok 4.6, high). Findings split into two families.
Adopted — readability, tracked in #9: widget_depth (Dart build methods; the existing depth counts control flow, so a branch-free build can nest eight visual layers and stay green — 156 wrapper edges in the Dart corpus), bool_ops (max logical operators per expression — 32 TS lines carry 3+), and ternary_depth. All three are syntax-only, single-file, and fit the existing per-function model.
This supersedes the earlier decision to park expression nesting for lack of evidence; the sweep supplied it.
Rejected — lint/policy rules. Real problems, wrong tool:
- Rust stringly-typed errors (
Result<_, String>+map_err(|e| e.to_string())) — 100+ hits each in pickforge and pickgaugesrc-tauri, zero in complexity-gate itself. Strong signal, but it needs a#[tauri::command]exemption to avoid firing on every IPC boundary, and atype AppError = Stringin another crate is invisible to single-file analysis. - Rust discarded error identity (
map_err(|_| ...)) — e.g.pickgauge/src-tauri/src/local_provider.rs:532repeats"codex_threads_query_failed"six times in one method. - TS/Svelte escape hatches — 52 nodes of
any/as unknown as(28 double assertions). A separate count found plainanyat essentially zero across the repos (0/0/11/0/0); eslint already holds that line, leaving too narrow a signal to justify the mechanism.
These are lint rules requiring per-language allowlists and cross-file resolution, and adopting them starts reimplementing clippy and eslint — a non-goal in docs/spec.md. Record the boundary in the spec so it is not re-litigated: complexity-gate measures how hard code is to read, not whether it follows a policy.
Corrected during review: a lane reported that measure_node returns early on nested closures, leaving callback bodies unmeasured. It excludes them from the parent, but collect_functions (crates/core/src/language.rs:296) walks the whole tree and measures every closure independently, and the parent's lines still spans them. No gap.
Rejected from the checklist
| Metric | Reason |
|---|---|
| Halstead Difficulty | Near-collinear with LOC + cyclomatic; "difficulty 83" gives no refactor direction, breaking the hook feedback loop. Sol priced it at 1000–2000 lines incl. per-language operator/operand tables and a fractional-metric representation (all metrics are usize today). |
| CRAP score | Composite of cyclomatic² and coverage — both gated directly elsewhere. |
| 100% test coverage | Perverse for an agent gate: optimizing it yields execution-only, assertion-free tests. Also needs per-language test runners, violating the no-external-tooling constraint. |
| 0 surviving mutants | Equivalent mutants make 0 unachievable; runtime is minutes to hours against a per-edit hook. |
| 0 dead code / 0 redundant code | Whole-program analysis. tsc, cargo, and oxlint do it better; docs/spec.md leaves repo-level linting to CI. |
0 unknown types |
Backwards — unknown is the safe alternative to any; banning it pushes code toward any and as unknown as T. |
The checklist's thresholds are also looser than current defaults (cyclomatic < 22 vs. complexity: 15) and specify no depth, function-length, or parameter limits at all.
PR plan
- PR 1 — spec: cognitive complexity algorithm, pinned per language
- Depends on: none
- Touches:
docs/spec.md - Validation: review only, no code
- Link: docs(spec): pin the cognitive complexity algorithm per language #27
- PR 2 — metric registry + cognitive complexity implementation and fixtures
- Depends on: PR 1
- Touches:
crates/core/src/language.rs,config.rs,scan.rs,config.default.json,tests/fixtures/** - Validation:
cargo test --workspace --locked --all-targets,cargo clippy --workspace --all-targets -- -D warnings,cargo llvm-cov,cargo run -- check crates - Link: feat: add cognitive complexity and make cyclomatic a backstop #28 (registry deferred until a second language-specific metric exists)
- PR 3 — Svelte template scoping
- Depends on: none (parallel with PR 1/2, but touches
language.rs— serialize the merge) - Touches:
crates/core/src/language.rs,docs/spec.md,tests/fixtures/svelte/** - Validation: as above, plus re-scan the private SvelteKit app
- Link: fix(svelte): score templates per top-level block and snippet #25
- Depends on: none (parallel with PR 1/2, but touches
- PR 4 — readability metrics
bool_ops+(Readability metrics: bool_ops + widget_depth #9;ternary_depthternary_depthcut after calibration)- Depends on: PR 2 (metric registry)
- Touches:
crates/core/src/language.rs,docs/spec.md,tests/fixtures/** - Validation: as above, plus before/after corpus scan
- Link: feat: add bool_ops and widget_depth readability metrics #10
- PR 5 —
widget_depthfor Dart (Readability metrics: bool_ops + widget_depth #9)- Depends on: PR 4
- Touches:
crates/core/src/language.rs,docs/spec.md,tests/fixtures/dart/** - Validation: as above, plus calibration against a private Flutter app / 3d_portfolio
- Link: feat: add bool_ops and widget_depth readability metrics #10 (shipped with PR 4)
- PR 6 — spec: record the lint-vs-complexity boundary as a non-goal
- Depends on: none
- Touches:
docs/spec.md - Validation: review only
- Link: feat: add bool_ops and widget_depth readability metrics #10 (
docs/spec.mdNon-goals)
Acceptance
- Cognitive complexity is specified, implemented, and fixtured for every supported language including Svelte templates (docs(spec): pin the cognitive complexity algorithm per language #27, feat: add cognitive complexity and make cyclomatic a backstop #28; all 8 fixture sets carry
cognitive) -
The env validator and the field summarizer pass on default limitsAmended: both fail for real reasons (cognitive 61 from 54 sequential guards, cognitive 40 from nested ternaries), see Per-language metric registry + cognitive complexity #7 and feat: add cognitive complexity and make cyclomatic a backstop #28. Flat dispatch itself passes: a 16-armswitchis clean on defaults. - Rust
match-heavy code no longer needs per-repocomplexityoverrides (feat: add cognitive complexity and make cyclomatic a backstop #28; a 19-armmatchpasses on defaults) - Svelte template violations are attributable to a block/snippet, not a whole file (fix(svelte): score templates per top-level block and snippet #25)
-
Adding a per-language metric no longer requires editing a hard-coded metric arrayDeferred to Extract a metric registry when a second language-specific metric lands #39: onlywidget_depthis language-specific, so the registry waits for a second user (Readability metrics: bool_ops + widget_depth #9, feat: add cognitive complexity and make cyclomatic a backstop #28) - A deeply nested Flutter
buildwith no control flow is flagged (feat: add bool_ops and widget_depth readability metrics #10;widget_depthdefault 7, recalibrated in feat: add bool_ops and widget_depth readability metrics #10) - A five-clause boolean condition is flagged regardless of its function's total complexity (feat: add bool_ops and widget_depth readability metrics #10;
bool_opsdefault 3) -
docs/spec.mdstates the lint-vs-complexity boundary as an explicit non-goal (feat: add bool_ops and widget_depth readability metrics #10)
Open decisions
RolloutDecided:cognitive15 is the default gate andcomplexityis off by default (null), with the change called out indocs/releases/UNRELEASED.md(feat: add cognitive complexity and make cyclomatic a backstop #28).Decided:depthdepthkeeps its current meaning.
Children
- Metric registry + cognitive complexity: Per-language metric registry + cognitive complexity #7
- Svelte templates score as one pseudo-function: Svelte templates are scored as one whole-file pseudo-function #8
- Readability metrics (widget_depth, bool_ops, ternary_depth): Readability metrics: bool_ops + widget_depth #9
Status: Done
Outcome: all children shipped; the metric registry is deferred to #39.
Activity
ElbertePlinio commentedon Aug 31, 2026
Progress update — corpus survey done, scope extended.
~/Projects/Personaland~/Projects/PickforgeIssue body updated with the scan table, per-family findings, and the extended PR plan.
Two notes:
ternary_depthin Readability metrics: bool_ops + widget_depth #9.collect_functions. No gap.Children: #7 (registry + cognitive), #8 (Svelte scoping), #9 (readability metrics)
Status: Planned
Next: write the cognitive-complexity spec section in #7
ElbertePlinio commentedon Aug 31, 2026
Measurement results — prototype binary over 17,414 functions (after ignore rules) across 10 source trees. Cyclomatic output validated against the shipped tool: 17,414/17,414 exact matches, 0 mismatches.
Nesting-weighted complexity: rejected
Proposal was
score += 1 + current_depthper decision point instead of+= 1— a one-line change offered as a cheap substitute for cognitive complexity. It does not work.Corpus distribution: median 1, p90 5, p95 9, p99 25, max 457. The env validator lands 5th highest of 17,414. Passing it requires a limit of ≥118, at which only 4 functions in the entire corpus fail — and
picklab/packages/core/src/redact.ts:153 redactCookiePairs, a genuinely nested parser, scores exactly 118 and passes too. No threshold separates flat-and-readable from nested-and-hard. Weighting by depth just amplifies branch count.Full cognitive complexity (#7) therefore stands as the only candidate for that problem — but see the correction below.
Correction to the #7 acceptance criteria
The two motivating functions are not equivalent, and cognitive complexity only fixes one:
switchscores +1 for the entire switch under cognitive complexity regardless of arm count, so 30 → low single digits. Genuine false positive, genuinely fixed. Same mechanism that fixes the Rust big-matchcase.ifguards each still score +1 under cognitive complexity. It ends up ~54 and still fails. On reflection that is probably correct: 54 distinct validations crammed into one sub-100-line function is a table or a loop waiting to happen, and the refactor is real work rather than a metric artifact.#7currently claims both should pass on default limits. Corrected: only the field summarizer and the Rustmatchcases should. Flat dispatch is the false positive; flat repetition is not.Metric calibration
Counts exclude generated files (
*.g.dart,*.freezed.dart,node_modules, etc.) — an early pass was dominated by Drift-generatedapp_database.g.dart, which the shipped ignore rules already skip.bool_ops— adopt, limit 3. 59 functions exceed 3 operators in one expression; 39 of those are not caught by any existing metric. Max observed 9 (pickforge/src/components/chat/Composer.tsx:190), then 8 atpickgauge-playwright-sidecar.mjs:265andpicklab/packages/core/src/redact.ts:95. Real, new, and cheap.ternary_depth— cut. Only 12 functions exceed depth 2, and just 4 are not already caught. That does not justify a metric, a config key, and fixtures across 8 languages. The worst case (pickforge/src/screens/Settings.tsx:971, depth 6) is already flagged today. Dropping to limit 1 would flag 85, but that starts failing ordinary two-branch ternaries.widget_depth— adopt, limit 8 (not 7). 163 Dartbuildmethods measured: median 5, p90 8, p95 10, max 11.8 keeps it to the genuine outliers. Worst offenders: two screens in a private Flutter app at 11; seven more at 10 across that app and 3d_portfolio.
Proxy caveat: of 2,475 constructor-like nodes counted, roughly 22% are non-widget value constructors —
EdgeInsets(111),Theme.of(174),BorderRadius(52),BoxDecoration(47),InputDecoration(32),Border(23). Most are leaves and rarely sit on the maximum-depth path, but the rule should either carry an exclusion list or require the node to occupy achild:/children:/body:argument position. Decide before implementing.Net effect on the plan
ternary_depth: cut from Readability metrics: bool_ops + widget_depth #9.bool_ops: confirmed, limit 3.widget_depth: confirmed, limit 8, proxy needs narrowing.Prototype lives in a disposable worktree (
measure/nesting-weighted), unmerged and uncommitted; raw data under the session scratchpad.ElbertePlinio commentedon Aug 31, 2026
PR #10 opened for #9 (
bool_ops+widget_depth): #10Updated PR plan:
bool_ops+widget_depth(Readability metrics: bool_ops + widget_depth #9), including the spec's lint-vs-complexity non-goalThe registry planned in #7 turned out not to be a prerequisite:
bool_opshas the same shape as the existing four metrics, andwidget_depthis the only language-specific one so far. #7 should reconsider whether the registry is worth building before a second language-specific metric exists.Three reviewed HEADs. Two findings were dismissed with evidence rather than fixed, and both dismissals are pinned by fixtures now:
??chains were reported as undercounting; they do not (a ?? b ?? c ?? d ?? escores 4).config.default.jsonreformatting isserde_json::to_string_prettyoutput, matching whatinitemits.The lint-vs-complexity boundary is now recorded in
docs/spec.mdas a non-goal, so the rejected families from the mining survey do not need re-litigating.ElbertePlinio commentedon Sep 30, 2026
Closing after checking the acceptance list against main at 99a0826. No code change was needed; the work shipped in #10, #25, #27, and #28.
The release binary built from that revision was run over one sample per criterion:
switchand a 19-arm Rustmatchboth pass on default limits&&in an otherwise trivial function failsbool_ops 4 > 3buildnested nine widgets deep failswidget_depth 9 > 7{#each}reportsp.svelte:10 {#each}, not a line-1<template>Two criteria were amended rather than met, both recorded in the body. The env validator and field summarizer still fail, for real reasons measured in #28. The metric registry is deferred to #39 until a second language-specific metric exists.