Skip to content

feat: add cognitive complexity analysis with GazeCRAP-CC (#270) - #294

Merged
jflowers merged 13 commits into
unbound-force:mainfrom
jflowers:opsx/cognitive-complexity
Oct 2, 2026
Merged

jflowers merged 13 commits into
unbound-force:mainfrom
jflowers:opsx/cognitive-complexity

Conversation

@jflowers

Copy link
Copy Markdown
Collaborator

Summary

  • Ports the SonarSource cognitive complexity algorithm to Go AST analysis (internal/cognitive).
  • Adds GazeCRAP-CC, a variant mirroring the CRAP formula but using cognitive complexity: CC^2 * (1 - coverage)^3 + CC, reported alongside existing CRAP (not replacing it).
  • Adds a --max-cognitive-complexity=<N> gate flag to gaze crap — exits non-zero when any function exceeds the threshold.
  • Emits cognitive_complexity and gaze_crap_cc per function in JSON output.
  • Extends the external analyzer protocol with an optional cognitive_complexity method (graceful degradation when a language analyzer does not implement it).

Closes #270.

How to Test

go test -race -count=1 -short ./...
go run ./cmd/gaze crap ./... --max-cognitive-complexity=15

How to Demo

go run ./cmd/gaze crap ./... --format=json | jq '.scores[] | select(.cognitive_complexity != null) | {function, cognitive_complexity, gaze_crap_cc}'

Key Files Changed

  • internal/cognitive/ — new Sonar cognitive complexity analyzer + 22 unit tests
  • internal/crap/crap.go — CognitiveFormula, Score.CognitiveComplexity + Score.GazeCRAPCC
  • internal/crap/analyze.go / provider.go — provider wiring + CognitiveComplexityProvider
  • internal/provider/goprovider/cognitive.go — Go provider
  • internal/adapter/cognitive.go — external analyzer adapter
  • internal/protocol/types.go — cognitive_complexity method constant + types
  • cmd/gaze/main.go — --max-cognitive-complexity flag + gate evaluation

This PR was generated by /uf.finale (AI-assisted).

@jflowers
jflowers force-pushed the opsx/cognitive-complexity branch from 2ed40f2 to cce6005 Compare October 1, 2026 14:48
@jflowers jflowers self-assigned this Oct 1, 2026
@jflowers
jflowers force-pushed the opsx/cognitive-complexity branch from 3af0370 to 8631033 Compare October 1, 2026 21:48
…ce#270)

- Add SonarSource cognitive complexity analyzer (internal/cognitive)
- Add CognitiveComplexityProvider interface with Go implementation
- Add GazeCRAP-CC variant (CC^2*(1-cov)^3 + CC) reported alongside CRAP
- Add --max-cognitive-complexity gate flag to gaze crap
- Add optional cognitive_complexity method to external analyzer protocol
- Emit cognitive_complexity and gaze_crap_cc in JSON output

Assisted-by: deepseek-v4-pro

Generated with AI assistance (deepseek-v4-pro)
@jflowers
jflowers force-pushed the opsx/cognitive-complexity branch from 8631033 to 83febf9 Compare October 1, 2026 23:26

@jflowers jflowers left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: Could not post as REQUEST_CHANGES due to self-review restriction (PR authored by current user). Posted as COMMENT instead. Original verdict: REQUEST_CHANGES.

Review Summary

6 findings (0 CRITICAL, 2 HIGH, 4 MEDIUM). Verdict: REQUEST CHANGES.

HIGH (blocks merge):

  1. Summary.CognitiveComplexityExceeded is dead code (internal/crap/analyze.go:418) — initialized but never incremented; buildSummary doesn't receive the threshold.
  2. JSON Schema (internal/report/schema.go) not updated with cognitive_complexity/gaze_crap_cc, violating crap-scoring/spec.md:77-84.

MEDIUM:
3. --max-cognitive-complexity is only on gaze crap, not gaze analyze (design goal #3 names both).
4. printCISummary (cmd/gaze/main.go:885) omits the cognitive complexity gate — it takes maxCrapload, maxGazeCrapload but not maxCognitiveComplexity, so the CI summary won't report the gate.
5. Protocol Capabilities (internal/protocol/types.go:147) lacks a CognitiveComplexity bool; every other optional method (discover, test_mapping, classify_signals, streaming, doc_coverage) declares one for handshake negotiation.
6. Logical operator counting deviates from the Sonar spec (see inline comment on cognitive_test.go).

Local go build and go test -race -count=1 -short ./... pass; MegaLinter passes; CI unit/e2e tests still running.

This review was generated by /uf.review-pr (AI-assisted).

Comment thread internal/crap/analyze.go Resolved
Comment thread internal/crap/crap.go Resolved
}
}

func TestMixedLogicalThreeOperators(t *testing.T) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Logical operator counting deviates from the Sonar spec. TestMixedLogicalThreeOperators expects a && b || c && d = 3, but the Sonar cognitive-complexity spec counts sequences of identical operators (one && sequence + one || sequence + one && sequence = 2 increments). The implementation increments on each operator change from its parent, yielding 3, which diverges from the stated Sonar-compatibility goal. Other Sonar-compatible tools report 2 for this expression.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declined with evidence. The implementation matches the SonarSource cognitive complexity specification, and the claimed value of 2 for a && b || c && d is incorrect.

  • SonarSource's Cognitive Complexity whitepaper, Appendix B, gives if (a && b && c || d || e && f) as +3 for logical operators — one increment per sequence of like operators, i.e. three sequences (&&, ||, &&).
  • G. Ann Campbell (SonarSource) confirms the same rule directly: a || b && c || d = 3, whereas a && b && c && d = 1.
  • The implementation's walkExpr increments on each operator change (parentLogOp != e.Op), which for a && b || c && d produces 3 (a && run, then a || run, then a && run). This matches the cognitive-complexity npm reference.

The review's own arithmetic ("one && + one || + one && = 2 increments") is internally contradictory — three operator-change runs cannot sum to two increments. No code change; TestMixedLogicalThreeOperators is correct as written.

Extract the cognitive-complexity lookup inlined into Analyze into a
helper (applyCognitiveComplexity), lowering Analyze's cyclomatic
complexity below the GazeCRAP threshold so the CI gate
(--max-gaze-crapload=6) passes.

Assisted-by: deepseek-v4-pro
Signed-off-by: Jay Flowers <[email protected]>
Pass the cognitive complexity threshold into buildSummary and increment
CognitiveComplexityExceeded when a function's score exceeds it, instead
of leaving the aggregate permanently zero.

Addresses PR unbound-force#294 review feedback from @jflowers (finding #1).

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
Declare cognitive_complexity and gaze_crap_cc on Score and
cognitive_complexity_total/cognitive_complexity_exceeded on Summary so
JSON output validates against the schema.

Addresses PR unbound-force#294 review feedback from @jflowers (finding #2).

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
Wire the Go cognitive complexity provider in the crap Go path, add the
--max-cognitive-complexity flag to gaze analyze with exit-code gating,
and surface the cognitive gate in printCISummary.

Addresses PR unbound-force#294 review feedback from @jflowers (findings unbound-force#3 and unbound-force#4).

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
Add the CognitiveComplexity bool to protocol.Capabilities, expose it on
adapter.Providers, and wire the external cognitive complexity provider
so external analyzers can supply cognitive complexity scores.

Addresses PR unbound-force#294 review feedback from @jflowers (finding unbound-force#5).

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
Address review-council REQUEST CHANGES findings on the cognitive
complexity feedback fixes:

- Summary.CognitiveComplexityTotal/Exceeded now *int (nil = unavailable)
- checkCIThresholds reads the summary field (single source of truth);
  fails with "unavailable" when the gate is set but CC was not computed
- printCISummary reports "unavailable" when CC was not computed
- goprovider wraps cognitive.AnalyzeFile (removes duplicated loop)
- protocol: 11 methods / 6 optional, version 1.2.0, docs/protocol.md
- spec scopes "computed and reported" to crap/report; analyze is gate-only
- drop dead max-cognitive-complexity term from self-check thresholdSet
- add tests for gate boundaries, unavailable signal, and analyze gate

Addresses PR unbound-force#294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
Address review-council round-2 REQUEST CHANGES findings:

- Fix multi-package enumeration: cognitive provider now passes the
  original ./... wildcard through to packages.Load instead of collapsing
  it via the gocyclo-oriented ResolvePatterns (gate under-enforced root pkg)
- Scope spec "computed and reported" to gaze crap only (analyze gate-only);
  remove over-claimed gaze report
- runAnalyze gate: error on empty cognitive result instead of silent PASS
- CognitiveFormula delegates to Formula (DRY)
- Fix arithmetically wrong spec example values (110.0 / 8.125 / 3.0)
- Add tests: CognitiveFormula, applyCognitiveComplexity, buildCognitiveLookup,
  convertCognitiveComplexity; fix import grouping

Addresses PR unbound-force#294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
Address review-council round-3 REQUEST CHANGES findings:

- Fix method name mismatch: cognitive provider now emits gocyclo-compatible
  receiver-qualified names ((*T).M / (T).M), so methods join correctly and
  are no longer silently dropped from cognitive/gaze_crap_cc output
- Traverse switch/select case bodies (case clauses were never walked,
  under-counting control flow inside cases)
- Detect method self-recursion via SelectorExpr (s.M())
- Correct spec else-if-chain scenario (else increments, value 4)
- Make runAnalyze cognitive provider injectable for testing FAIL branches
- Wrap packages.Load error with %w
- Extend fake analyzer with cognitive_complexity capability + handler,
  bump protocol_version to 1.2.0
- Document --max-cognitive-complexity + GazeCRAP-CC in README
- Correct tasks.md/design.md bookkeeping (defer text-report column, un-check 6.5)
- Add tests: function-name format, case-body traversal, provider integration,
  runAnalyze gate FAIL branches, JSON omitempty, schema validation

Addresses PR unbound-force#294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
Address review-council round-4 REQUEST CHANGES findings:

- runAnalyze gate now evaluates before the empty-results early return, so
  --max-cognitive-complexity can no longer silently pass on zero functions
- Provider integration test asserts exact cognitive complexity values
  (new cognitive fixture with hand-computed NestedIf=3)
- External-analyzer cognitive path tested end-to-end: capability present
  yields provider + values (add/multiply/divide); --no-cognitive-complexity
  yields nil provider (graceful degradation)
- External-analyzer crap test asserts cognitive_complexity/gaze_crap_cc

Addresses PR unbound-force#294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
Correct task 6.2 (ExternalCognitiveComplexityProvider, not
FetchCognitiveComplexity) and design D6 (*int → int threshold pattern).

Addresses PR unbound-force#294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
The external-analyzer cognitive round-trip test (TestSession_CognitiveComplexityCapability
+ TestCrapWithExternalAnalyzer cognitive assertions) was added in commit 45ef3d4.

Addresses PR unbound-force#294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
@jflowers

jflowers commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in 630447e: gaze analyze now accepts --max-cognitive-complexity=<N> (0 = no limit). When the flag is set, runAnalyze computes cognitive complexity over the matched packages, exits 1 when any function exceeds the threshold, and prints a PASS summary to stderr otherwise. The gate evaluates before the empty-results early return, so it cannot silently pass when nothing was measured. Tests: TestRunAnalyze_CognitiveComplexity{Pass,Exceeded,NoFunctions,ProviderError}.

@jflowers

jflowers commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in 630447e: printCISummary now receives maxCognitiveComplexity and emits a CognitiveComplexity line (N function(s) exceed N (PASS/FAIL) or unavailable) alongside the CRAPload and GazeCRAPload gates, satisfying Constitution Principle III (actionable output). Tests: TestPrintCISummary_CognitiveComplexity{Pass,Fail,Unavailable}.

@jflowers

jflowers commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in 156f195: added Capabilities.CognitiveComplexity bool to the protocol, added Providers.CognitiveComplexity to the adapter session (constructed when the analyzer advertises the capability), and wired it into wireExternalProviders. Protocol version bumped to 1.2.0 and docs/protocol.md documents the optional cognitive_complexity method with graceful degradation. Tests: TestSession_CognitiveComplexityCapability{,_Disabled}, TestConvertCognitiveComplexity{,_Empty}, TestCrapWithExternalAnalyzer cognitive assertions.

@jflowers
jflowers merged commit 323edaa into unbound-force:main Oct 2, 2026
5 checks passed
jflowers added a commit that referenced this pull request Oct 2, 2026
Pass the cognitive complexity threshold into buildSummary and increment
CognitiveComplexityExceeded when a function's score exceeds it, instead
of leaving the aggregate permanently zero.

Addresses PR #294 review feedback from @jflowers (finding #1).

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
jflowers added a commit that referenced this pull request Oct 2, 2026
Declare cognitive_complexity and gaze_crap_cc on Score and
cognitive_complexity_total/cognitive_complexity_exceeded on Summary so
JSON output validates against the schema.

Addresses PR #294 review feedback from @jflowers (finding #2).

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
jflowers added a commit that referenced this pull request Oct 2, 2026
Wire the Go cognitive complexity provider in the crap Go path, add the
--max-cognitive-complexity flag to gaze analyze with exit-code gating,
and surface the cognitive gate in printCISummary.

Addresses PR #294 review feedback from @jflowers (findings #3 and #4).

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
jflowers added a commit that referenced this pull request Oct 2, 2026
Add the CognitiveComplexity bool to protocol.Capabilities, expose it on
adapter.Providers, and wire the external cognitive complexity provider
so external analyzers can supply cognitive complexity scores.

Addresses PR #294 review feedback from @jflowers (finding #5).

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
jflowers added a commit that referenced this pull request Oct 2, 2026
Address review-council REQUEST CHANGES findings on the cognitive
complexity feedback fixes:

- Summary.CognitiveComplexityTotal/Exceeded now *int (nil = unavailable)
- checkCIThresholds reads the summary field (single source of truth);
  fails with "unavailable" when the gate is set but CC was not computed
- printCISummary reports "unavailable" when CC was not computed
- goprovider wraps cognitive.AnalyzeFile (removes duplicated loop)
- protocol: 11 methods / 6 optional, version 1.2.0, docs/protocol.md
- spec scopes "computed and reported" to crap/report; analyze is gate-only
- drop dead max-cognitive-complexity term from self-check thresholdSet
- add tests for gate boundaries, unavailable signal, and analyze gate

Addresses PR #294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
jflowers added a commit that referenced this pull request Oct 2, 2026
Address review-council round-2 REQUEST CHANGES findings:

- Fix multi-package enumeration: cognitive provider now passes the
  original ./... wildcard through to packages.Load instead of collapsing
  it via the gocyclo-oriented ResolvePatterns (gate under-enforced root pkg)
- Scope spec "computed and reported" to gaze crap only (analyze gate-only);
  remove over-claimed gaze report
- runAnalyze gate: error on empty cognitive result instead of silent PASS
- CognitiveFormula delegates to Formula (DRY)
- Fix arithmetically wrong spec example values (110.0 / 8.125 / 3.0)
- Add tests: CognitiveFormula, applyCognitiveComplexity, buildCognitiveLookup,
  convertCognitiveComplexity; fix import grouping

Addresses PR #294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
jflowers added a commit that referenced this pull request Oct 2, 2026
Address review-council round-3 REQUEST CHANGES findings:

- Fix method name mismatch: cognitive provider now emits gocyclo-compatible
  receiver-qualified names ((*T).M / (T).M), so methods join correctly and
  are no longer silently dropped from cognitive/gaze_crap_cc output
- Traverse switch/select case bodies (case clauses were never walked,
  under-counting control flow inside cases)
- Detect method self-recursion via SelectorExpr (s.M())
- Correct spec else-if-chain scenario (else increments, value 4)
- Make runAnalyze cognitive provider injectable for testing FAIL branches
- Wrap packages.Load error with %w
- Extend fake analyzer with cognitive_complexity capability + handler,
  bump protocol_version to 1.2.0
- Document --max-cognitive-complexity + GazeCRAP-CC in README
- Correct tasks.md/design.md bookkeeping (defer text-report column, un-check 6.5)
- Add tests: function-name format, case-body traversal, provider integration,
  runAnalyze gate FAIL branches, JSON omitempty, schema validation

Addresses PR #294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
jflowers added a commit that referenced this pull request Oct 2, 2026
Address review-council round-4 REQUEST CHANGES findings:

- runAnalyze gate now evaluates before the empty-results early return, so
  --max-cognitive-complexity can no longer silently pass on zero functions
- Provider integration test asserts exact cognitive complexity values
  (new cognitive fixture with hand-computed NestedIf=3)
- External-analyzer cognitive path tested end-to-end: capability present
  yields provider + values (add/multiply/divide); --no-cognitive-complexity
  yields nil provider (graceful degradation)
- External-analyzer crap test asserts cognitive_complexity/gaze_crap_cc

Addresses PR #294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
jflowers added a commit that referenced this pull request Oct 2, 2026
Correct task 6.2 (ExternalCognitiveComplexityProvider, not
FetchCognitiveComplexity) and design D6 (*int → int threshold pattern).

Addresses PR #294 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: deepseek-v4-pro
@jflowers
jflowers deleted the opsx/cognitive-complexity branch November 15, 2026 21:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cognitive complexity per function in Gaze + GazeCRAP-CC variant (Group 6)

1 participant