Skip to content

Metric expansion: cognitive complexity and Svelte template scoping #6

Closed

Description

@ElbertePlinio

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 switch where 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 pickgauge src-tauri, zero in complexity-gate itself. Strong signal, but it needs a #[tauri::command] exemption to avoid firing on every IPC boundary, and a type AppError = String in another crate is invisible to single-file analysis.
  • Rust discarded error identity (map_err(|_| ...)) — e.g. pickgauge/src-tauri/src/local_provider.rs:532 repeats "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 plain any at 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

Acceptance

Open decisions

Children

Status: Done
Outcome: all children shipped; the metric registry is deferred to #39.

Activity

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

    @ElbertePlinio
    MemberAuthor

    Progress update — corpus survey done, scope extended.

    Issue body updated with the scan table, per-family findings, and the extended PR plan.

    Two notes:

    • The expression-nesting gap is no longer parked — the sweep produced the evidence it was waiting on, so it ships as ternary_depth in Readability metrics: bool_ops + widget_depth #9.
    • One lane claim did not survive checking: nested closures are excluded from the parent function but are measured independently by 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

  3. ElbertePlinio commented on Aug 31, 2026

    @ElbertePlinio
    MemberAuthor

    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_depth per decision point instead of += 1 — a one-line change offered as a cheap substitute for cognitive complexity. It does not work.

    Function Cyclomatic Weighted depth
    the env validator (flat guards) 54 118 3
    the field summarizer (flat switch) 30 58 1

    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:

    • the field summarizer — a switch scores +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-match case.
    • the env validator — 54 sequential if guards 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.

    #7 currently claims both should pass on default limits. Corrected: only the field summarizer and the Rust match cases 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-generated app_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 at pickgauge-playwright-sidecar.mjs:265 and picklab/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 Dart build methods measured: median 5, p90 8, p95 10, max 11.

    limit failures share
    >6 37 23%
    >7 23 14%
    >8 13 8%

    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 a child: / children: / body: argument position. Decide before implementing.

    Net effect on the plan

    Prototype lives in a disposable worktree (measure/nesting-weighted), unmerged and uncommitted; raw data under the session scratchpad.

  4. ElbertePlinio commented on Aug 31, 2026

    @ElbertePlinio
    MemberAuthor

    PR #10 opened for #9 (bool_ops + widget_depth): #10

    Updated PR plan:

    The registry planned in #7 turned out not to be a prerequisite: bool_ops has the same shape as the existing four metrics, and widget_depth is 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:

    • Dart ?? chains were reported as undercounting; they do not (a ?? b ?? c ?? d ?? e scores 4).
    • config.default.json reformatting is serde_json::to_string_pretty output, matching what init emits.

    The lint-vs-complexity boundary is now recorded in docs/spec.md as a non-goal, so the rejected families from the mining survey do not need re-litigating.

  5. ElbertePlinio commented on Sep 30, 2026

    @ElbertePlinio
    MemberAuthor

    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:

    • a 16-arm TS switch and a 19-arm Rust match both pass on default limits
    • a five-clause && in an otherwise trivial function fails bool_ops 4 > 3
    • a branch-free Flutter build nested nine widgets deep fails widget_depth 9 > 7
    • a Svelte file with deep nesting inside {#each} reports p.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.

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