Skip to content

feat(index): Sonar cognitive complexity column and recipes#173

Merged
SutuSebastian merged 9 commits into
mainfrom
feat/cognitive-complexity
Jun 5, 2026
Merged

feat(index): Sonar cognitive complexity column and recipes#173
SutuSebastian merged 9 commits into
mainfrom
feat/cognitive-complexity

Conversation

@SutuSebastian

@SutuSebastian SutuSebastian commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Add symbols.cognitive_complexity (SonarSource rules) in the same oxc walk as cyclomatic McCabe — SCHEMA_VERSION 38.
  • Cover top-level functions, named arrow/const, and class methods (method bodies wired via markArrowSymbol on FunctionExpression).
  • New bundled recipe high-cognitive-complexity (min_score default 15).
  • Extend high-complexity-untested SELECT with cognitive_complexity (cyclomatic >= 10 filter unchanged).
  • Plan deleted per Rule 3; roadmap item removed.

Grill decisions (locked)

  • Q1: full function-shaped coverage including class methods
  • Q2: min_score default 15 (Sonar-aligned)
  • Q3: v1 SELECT-only extend on high-complexity-untested

Test plan

  • bun test src/extractors/complexity.test.ts src/parser.test.ts
  • bun run test:golden
  • bun run typecheck
  • bun src/index.ts query --recipe high-cognitive-complexity --json on minimal fixture

Summary by CodeRabbit

  • New Features

    • Introduced cognitive complexity metric (SonarSource-based) to identify nesting-heavy control flow, complementing cyclomatic complexity for more nuanced code quality assessment.
    • Added "high-cognitive-complexity" recipe to flag functions exceeding complexity threshold (default: 15), with configurable tuning via --params min_score.
  • Documentation

    • Updated glossary and guides with cognitive complexity definitions, applicability, and integration with existing recipes.

Add symbols.cognitive_complexity in the same oxc walk as cyclomatic,
including class methods. Ship high-cognitive-complexity (min_score 15)
and extend high-complexity-untested SELECT. Schema v38; plan deleted.
@changeset-bot

changeset-bot Bot commented Jun 5, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 720aaa5

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@stainless-code/codemap Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Jun 5, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 20a6e4a8-b7c8-4ce9-8242-b9474957867c

📥 Commits

Reviewing files that changed from the base of the PR and between 0aa9948 and 720aaa5.

📒 Files selected for processing (19)
  • .agents/rules/agents-tier-system.md
  • .agents/rules/tracer-bullets.md
  • .agents/skills/harden-pr/SKILL.md
  • .changeset/cognitive-complexity.md
  • .cursor/skills/harden-pr
  • docs/architecture.md
  • docs/glossary.md
  • fixtures/golden/minimal/files-hashes.json
  • fixtures/golden/minimal/high-cognitive-complexity.json
  • fixtures/golden/minimal/high-complexity-untested.json
  • fixtures/minimal/README.md
  • src/db.test.ts
  • src/db.ts
  • src/extractors/complexity.test.ts
  • src/extractors/complexity.ts
  • src/extractors/types.ts
  • templates/agent-content/rule/00-full.md
  • templates/recipes/high-cognitive-complexity.md
  • templates/recipes/high-complexity-untested.md
✅ Files skipped from review due to trivial changes (11)
  • .cursor/skills/harden-pr
  • .agents/rules/tracer-bullets.md
  • fixtures/golden/minimal/high-complexity-untested.json
  • fixtures/golden/minimal/files-hashes.json
  • fixtures/minimal/README.md
  • templates/recipes/high-cognitive-complexity.md
  • docs/architecture.md
  • .agents/rules/agents-tier-system.md
  • .changeset/cognitive-complexity.md
  • templates/agent-content/rule/00-full.md
  • docs/glossary.md
🚧 Files skipped from review as they are similar to previous changes (4)
  • fixtures/golden/minimal/high-cognitive-complexity.json
  • src/extractors/types.ts
  • src/extractors/complexity.ts
  • src/db.ts

📝 Walkthrough

Walkthrough

This PR integrates SonarSource cognitive-complexity measurement into the codebase and introduces a new development hardening workflow. The cognitive-complexity feature extends the existing cyclomatic-complexity analysis to detect nesting-heavy control flow, while the harden-pr skill automates PR validation before opening.

Changes

Cognitive Complexity Feature

Layer / File(s) Summary
Database schema, type contracts, and persistence
src/db.ts, src/extractors/types.ts
Schema version 38 adds cognitive_complexity INTEGER column to symbols table; SymbolRow interface exports optional cognitive_complexity?: number | null; insertSymbols() persists cognitive values; ComplexityTracker interface declares cognitive operations.
Cognitive complexity extraction and branching logic
src/extractors/complexity.ts
Tracker maintains per-frame cognitive state and persists cognitive_complexity on popTop(); extraction logic applies structural (+1 + nesting) and flat (+1) cognitive increments during branching entry/exit, logical operators, and switch cases, in parallel with cyclomatic tracking.
Class method tracking and comprehensive test suite
src/extractors/symbols.ts, src/extractors/complexity.test.ts, src/db.test.ts
Symbol extraction passes complexity context into class member processing; methods marked via markArrowSymbol() for aligned cognitive metrics. Tests validate cognitive extraction across nested/flat branching, arrow functions, class methods, and confirm non-function symbols retain null cognitive complexity. Persistence and schema-rebuild tests added.
High-cognitive-complexity recipe and golden fixtures
templates/recipes/high-cognitive-complexity.md, .sql, fixtures/golden/minimal/*, fixtures/golden/scenarios.json
New recipe template with configurable min_score (default 15) and review-cognitive-complexity action; parameterized SQL query filters by threshold and orders by descending cognitive complexity. Golden fixtures define expected metrics; high-complexity-untested recipe and SQL extended to include cognitive column; scenario config added.
Glossary, architecture, and documentation updates
docs/glossary.md, docs/architecture.md, docs/plans/*, .changeset/cognitive-complexity.md, templates/agent-content/rule/00-full.md
Glossary entries for both complexity and new cognitive_complexity with scope and recipe references; architecture docs expanded with function-shaped symbol scope; references migrated to glossary anchors; roadmap backlog item removed; agent template updated with cognitive trigger pattern; changeset entry added.

Development Workflow Tooling

Layer / File(s) Summary
Harden-pr skill definition and constraints
.agents/skills/harden-pr/SKILL.md, .cursor/skills/harden-pr
New skill defines /harden-pr loop: parallel reviewer subagents, deduplication, in-bounds fix application, check re-run, pass-cap handling, and single final commit. Specifies production-readiness criteria, intent-anchor contract, in/out-of-bounds rules, adaptive reviewer roster, and loop control flow. Symlink created for Cursor IDE integration.
Vertical-slice hardening and PR pre-opening rules
.agents/rules/tracer-bullets.md, .agents/rules/agents-tier-system.md
Tracer-bullets rules updated to require explicit "Lite-harden the slice" step after initial slice commit/validation before expanding outward; full harden-pr mode run on origin/main...HEAD required before opening PR.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • stainless-code/codemap#70: Both PRs modify the same complexity pipeline (src/db.ts schema/insertSymbols() and templates/recipes/high-complexity-untested.*) — this PR extends with cognitive-complexity measurement building on cyclomatic-complexity groundwork.

Suggested labels

enhancement, documentation

Poem

🐰 A twist in the metrics, a nesting so deep,
Cognitive complexity now measured and steep,
While harden-pr watches each PR take flight,
The tower of checks makes the code shiny bright!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding SonarSource cognitive complexity support (column and recipes) to the symbols table, which is the primary focus of the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/cognitive-complexity

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Else-if alternates no longer inherit consequent cognitive nesting;
golden pins labyrinth cognitive_complexity at 27 on minimal fixture.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/db.ts (1)

65-65: ⚡ Quick win

Add an index for the new cognitive_complexity query path.

Line 65 introduces a new filter/sort column used by recipes; without an index, SQLite must scan/sort symbols for each run.

💡 Suggested patch
@@
     CREATE INDEX IF NOT EXISTS idx_symbols_file ON symbols(file_path);
+    CREATE INDEX IF NOT EXISTS idx_symbols_cognitive ON symbols(cognitive_complexity, complexity, file_path, name)
+      WHERE cognitive_complexity IS NOT NULL;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/db.ts` at line 65, Add a SQLite index for the new cognitive_complexity
column on the symbols table so queries that filter or sort by
cognitive_complexity don't cause full table scans; update the DB migration or
schema code that defines the symbols table (look for the CREATE TABLE or
migration function that mentions cognitive_complexity and the symbols table) to
create an index (e.g., CREATE INDEX IF NOT EXISTS
idx_symbols_cognitive_complexity ON symbols(cognitive_complexity)) and ensure
the migration runs in existing deployments.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/extractors/types.ts`:
- Around line 77-78: The new public methods enterCognitiveNest() and
exitCognitiveNest() on ComplexityTracker are missing documentation; add concise
JSDoc comments immediately above each exported signature explaining their
purpose and nesting semantics (e.g., enterCognitiveNest begins a nested
cognitive complexity scope, increments the nest depth or stack, and
exitCognitiveNest closes that scope and decrements the depth, including behavior
when called without a matching enter), mention any side-effects (state mutated,
not reentrant) and expected usage example or pairing requirement (enter must be
paired with exit). Ensure the comments are placed with the exported API (the
ComplexityTracker methods) so they satisfy the public-API documentation
guideline.

---

Nitpick comments:
In `@src/db.ts`:
- Line 65: Add a SQLite index for the new cognitive_complexity column on the
symbols table so queries that filter or sort by cognitive_complexity don't cause
full table scans; update the DB migration or schema code that defines the
symbols table (look for the CREATE TABLE or migration function that mentions
cognitive_complexity and the symbols table) to create an index (e.g., CREATE
INDEX IF NOT EXISTS idx_symbols_cognitive_complexity ON
symbols(cognitive_complexity)) and ensure the migration runs in existing
deployments.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ffd31472-25e8-4597-b239-6743aeceaf43

📥 Commits

Reviewing files that changed from the base of the PR and between cf7df2f and 0aa9948.

📒 Files selected for processing (21)
  • .changeset/cognitive-complexity.md
  • docs/architecture.md
  • docs/glossary.md
  • docs/plans/ast-hash-duplication.md
  • docs/plans/cognitive-complexity.md
  • docs/plans/graph-estimated-crap.md
  • docs/roadmap.md
  • fixtures/golden/minimal/high-cognitive-complexity.json
  • fixtures/golden/minimal/high-complexity-untested.json
  • fixtures/golden/scenarios.json
  • src/db.ts
  • src/extractors/complexity.test.ts
  • src/extractors/complexity.ts
  • src/extractors/symbols.ts
  • src/extractors/types.ts
  • src/parser.test.ts
  • templates/agent-content/rule/00-full.md
  • templates/recipes/high-cognitive-complexity.md
  • templates/recipes/high-cognitive-complexity.sql
  • templates/recipes/high-complexity-untested.md
  • templates/recipes/high-complexity-untested.sql
💤 Files with no reviewable changes (2)
  • docs/plans/cognitive-complexity.md
  • docs/roadmap.md

Comment thread src/extractors/types.ts
Codifies the review-until-clean loop as a Tier-3 skill with lite (per tracer
bullet) and full (pre-PR) modes, and wires lite harden into tracer-bullets cadence.
Minor changeset for SCHEMA 38 rebuild, agent rule column ref, arrow/bind
test coverage, and doc/comment hygiene from harden-pr review.
README content_hash drifted when fixtures/minimal/README.md listed
high-cognitive-complexity; golden now matches indexer line_count.
Skill invocation now authorizes the end commit and forbids asking about
commits, babysit, or the next pass until the loop finishes.
insertSymbols SELECT test mirrors visibility pattern; v27 rebuild asserts
symbols.cognitive_complexity via pragma_table_info.
Defines pristine/maximum production readiness as the north star reviewers
optimize for, with an explicit checklist and production-bar status in reports.
…acker

Mirror enterNest/exitNest one-liners; addresses CodeRabbit PR #173 thread.
@SutuSebastian SutuSebastian merged commit d4982c4 into main Jun 5, 2026
10 of 11 checks passed
@SutuSebastian SutuSebastian deleted the feat/cognitive-complexity branch June 5, 2026 16:20
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.

1 participant