Skip to content

Commit 35f6176

Browse files
feat: cognitive & cyclomatic complexity metrics (#130)
* feat: add codegraph path for A→B symbol pathfinding Add `codegraph path <from> <to>` — BFS shortest-path search on the call graph. Given two symbol names, finds the shortest call chain with hop count, intermediate nodes, edge kinds, and alternate path count. Supports --reverse, --max-depth, --kinds, --from-file/--to-file, -T, -j, -k flags. Exposed as symbol_path MCP tool. Impact: 4 functions changed, 3 affected * docs: add Titan Paradigm use case, update docs with roles/co-change/path - Create docs/use-cases/titan-paradigm.md — maps Johannes R.'s multi-agent codebase cleanup architecture (RECON, GAUNTLET, GLOBAL SYNC, STATE MACHINE) to codegraph commands, roadmap items, and post-LLM-integration recommendations - Update roadmap/BACKLOG.md: mark #4 (node classification), #9 (git change coupling), #1 (dead code), #2 (shortest path), #12 (execution flow) as DONE; add 6 new Titan Paradigm-inspired items (#21-#26): composite audit, batch querying, triage priority queue, change validation predicates, graph snapshots, MCP orchestration tools - Update README.md: add roles + co-change to features table, differentiators, commands section, agent template, common flags, comparison table; update MCP tool count 18 → 19 - Update docs/recommended-practices.md: update MCP tool count and tool list, add roles/co-change/path to CLAUDE.md template and developer workflow, add "Understand architectural roles" and "Surface hidden coupling" sections, add co-change step to setup checklist - Add full examples with real output for roles, co-change, and path to docs/examples/CLI.md and docs/examples/MCP.md - Update GitHub repo description with new capabilities * docs: restore Architecture Refactoring phase, fix references - Restore Phase 3 (Architectural Refactoring) to ROADMAP - Renumber phases 4-8 and all cross-references - Fix MCP tool count per Greptile review * fix: correct MCP tool counts and backlog ID collisions Address Greptile review comments on #121: - Update MCP tool counts from 18/19 to 21 (22 in multi-repo mode) across README, recommended-practices, dogfood skill, titan-paradigm - Add missing execution_flow and list_entry_points to tool enumeration - Renumber new backlog items 21-26 → 27-32 to avoid collision with existing items 21-22 * feat: add token savings benchmark (codegraph vs raw navigation) Adds a benchmark suite that measures how much codegraph reduces token usage when AI agents navigate the Next.js codebase (~4k TS files). - scripts/token-benchmark-issues.js: 5 real Next.js PRs as test cases - scripts/token-benchmark.js: runner using Claude Agent SDK (baseline vs codegraph MCP), with --perf flag for build/query benchmarks - scripts/update-token-report.js: JSON → markdown report generator - docs/benchmarks/: methodology docs and placeholder report Impact: 21 functions changed, 7 affected * feat: extend benchmarks with incremental builds and expanded query coverage benchmark.js now measures no-op rebuilds, 1-file rebuilds, and query latency (fn-deps, fn-impact, path, roles) alongside full builds. update-benchmark-report.js renders new Incremental Rebuilds and Query Latency sections in BUILD-BENCHMARKS.md and adds incremental/query rows to the README performance table. All new fields are additive for backward compatibility. Impact: 5 functions changed, 2 affected * ci: include version in automated benchmark commits and PRs Extract version from benchmark result JSON and include it in branch names, commit messages, PR titles, and PR bodies across all 4 benchmark jobs (build, embedding, query, incremental). * fix: update remaining 19-tool references to 21-tool in README * docs: remove "viral" from titan paradigm LinkedIn reference * fix: use endLine for scope-aware caller selection in nested functions Nested/closure functions (e.g. nodeId inside exportMermaid) were incorrectly classified as [dead] because the caller selection loop picked the last definition where line <= call.line, creating self-call edges that got filtered out. Now uses endLine to find the innermost enclosing scope, so calls within an outer function correctly attribute the outer function as caller rather than the nested function itself. Fixes false-positive [dead] for nodeId in branch-compare.js, export.js, and queries.js. Impact: 1 functions changed, 17 affected * feat: add cognitive & cyclomatic complexity metrics Compute per-function complexity during build via single-traversal DFS of tree-sitter ASTs: cognitive (SonarSource), cyclomatic (McCabe), and max nesting depth. Stores results in new function_complexity table (migration v8) and surfaces them in stats, context, explain, and a dedicated `complexity` CLI command + MCP tool. Adds manifesto config section with warn thresholds (cognitive: 15, cyclomatic: 10, maxNesting: 4) seeding the future rule engine. Phase 1 supports JS/TS/TSX; unsupported languages are skipped gracefully. Impact: 18 functions changed, 32 affected --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
1 parent 2d79f18 commit 35f6176

11 files changed

Lines changed: 1238 additions & 0 deletions

File tree

src/builder.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,17 +496,27 @@ export async function buildGraph(rootDir, opts = {}) {
496496
const deleteMetricsForFile = db.prepare(
497497
'DELETE FROM node_metrics WHERE node_id IN (SELECT id FROM nodes WHERE file = ?)',
498498
);
499+
let deleteComplexityForFile;
500+
try {
501+
deleteComplexityForFile = db.prepare(
502+
'DELETE FROM function_complexity WHERE node_id IN (SELECT id FROM nodes WHERE file = ?)',
503+
);
504+
} catch {
505+
deleteComplexityForFile = null;
506+
}
499507
for (const relPath of removed) {
500508
deleteEmbeddingsForFile?.run(relPath);
501509
deleteEdgesForFile.run({ f: relPath });
502510
deleteMetricsForFile.run(relPath);
511+
deleteComplexityForFile?.run(relPath);
503512
deleteNodesForFile.run(relPath);
504513
}
505514
for (const item of parseChanges) {
506515
const relPath = item.relPath || normalizePath(path.relative(rootDir, item.file));
507516
deleteEmbeddingsForFile?.run(relPath);
508517
deleteEdgesForFile.run({ f: relPath });
509518
deleteMetricsForFile.run(relPath);
519+
deleteComplexityForFile?.run(relPath);
510520
deleteNodesForFile.run(relPath);
511521
}
512522

@@ -996,6 +1006,14 @@ export async function buildGraph(rootDir, opts = {}) {
9961006
debug(`Role classification failed: ${err.message}`);
9971007
}
9981008

1009+
// Compute per-function complexity metrics (cognitive, cyclomatic, nesting)
1010+
try {
1011+
const { buildComplexityMetrics } = await import('./complexity.js');
1012+
await buildComplexityMetrics(db, allSymbols, rootDir, engineOpts);
1013+
} catch (err) {
1014+
debug(`Complexity analysis failed: ${err.message}`);
1015+
}
1016+
9991017
const nodeCount = db.prepare('SELECT COUNT(*) as c FROM nodes').get().c;
10001018
info(`Graph built: ${nodeCount} nodes, ${edgeCount} edges`);
10011019
info(`Stored in ${dbPath}`);

src/cli.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,55 @@ program
712712
});
713713
});
714714

715+
program
716+
.command('complexity [target]')
717+
.description('Show per-function complexity metrics (cognitive, cyclomatic, nesting depth)')
718+
.option('-d, --db <path>', 'Path to graph.db')
719+
.option('-n, --limit <number>', 'Max results', '20')
720+
.option('--sort <metric>', 'Sort by: cognitive | cyclomatic | nesting', 'cognitive')
721+
.option('--above-threshold', 'Only functions exceeding warn thresholds')
722+
.option('-f, --file <path>', 'Scope to file (partial match)')
723+
.option('-k, --kind <kind>', 'Filter by symbol kind')
724+
.option('-T, --no-tests', 'Exclude test/spec files from results')
725+
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
726+
.option('-j, --json', 'Output as JSON')
727+
.action(async (target, opts) => {
728+
if (opts.kind && !ALL_SYMBOL_KINDS.includes(opts.kind)) {
729+
console.error(`Invalid kind "${opts.kind}". Valid: ${ALL_SYMBOL_KINDS.join(', ')}`);
730+
process.exit(1);
731+
}
732+
const { complexity } = await import('./complexity.js');
733+
complexity(opts.db, {
734+
target,
735+
limit: parseInt(opts.limit, 10),
736+
sort: opts.sort,
737+
aboveThreshold: opts.aboveThreshold,
738+
file: opts.file,
739+
kind: opts.kind,
740+
noTests: resolveNoTests(opts),
741+
json: opts.json,
742+
});
743+
});
744+
745+
program
746+
.command('branch-compare <base> <target>')
747+
.description('Compare code structure between two branches/refs')
748+
.option('--depth <n>', 'Max transitive caller depth', '3')
749+
.option('-T, --no-tests', 'Exclude test/spec files')
750+
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
751+
.option('-j, --json', 'Output as JSON')
752+
.option('-f, --format <format>', 'Output format: text, mermaid, json', 'text')
753+
.action(async (base, target, opts) => {
754+
const { branchCompare } = await import('./branch-compare.js');
755+
await branchCompare(base, target, {
756+
engine: program.opts().engine,
757+
depth: parseInt(opts.depth, 10),
758+
noTests: resolveNoTests(opts),
759+
json: opts.json,
760+
format: opts.format,
761+
});
762+
});
763+
715764
program
716765
.command('watch [dir]')
717766
.description('Watch project for file changes and incrementally update the graph')

0 commit comments

Comments
 (0)