-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathllms-full.txt
More file actions
731 lines (604 loc) · 33.7 KB
/
Copy pathllms-full.txt
File metadata and controls
731 lines (604 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# Codebase Intelligence — Full Documentation
> TypeScript codebase analysis engine — dependency graphs, architectural metrics, MCP + CLI interfaces.
---
# Architecture
## Pipeline
```
CLI (commander)
|
v
Parser (TS Compiler API)
| extracts: files, exports, imports, LOC, cyclomatic/cognitive complexity, churn, test mapping
v
Graph Builder (graphology)
| creates: nodes (file + function), edges (imports with symbols/weights)
| detects: circular dependencies (iterative DFS)
v
Analyzer
| computes: PageRank, betweenness, coupling, tension, cohesion
| computes: churn, cyclomatic/cognitive complexity, blast radius, dead exports, test coverage
| produces: ForceAnalysis (tension files, bridges, extraction candidates)
v
Core (shared computation)
| result builders used by MCP, CLI, and operation descriptors
|\
| \-> Operation Registry
| typed descriptors, input schemas, CLI/MCP adapters, result wrappers, text formatters
v
MCP (stdio) + CLI
| MCP: 29 tools, 2 prompts, 3 resources for LLM agents
| CLI: 35 public commands with formatted + JSON output for humans/CI
```
## Module Map
```
src/
types/index.ts <- ALL interfaces (single source of truth)
parser/index.ts <- Parse orchestration + imports/exports/call sites + git churn/test detection
parser/type-facts.ts <- Type signatures, parameters, consumed/produced shape facts
parser/symbols.ts <- Symbol inventory + symbol cyclomatic/cognitive complexity
graph/index.ts <- graphology graph + symbol/type graph + circular dep detection
analyzer/index.ts <- All metric computation
graph-loader/index.ts <- Shared parse/build/analyze/cache pipeline + progress events
core/index.ts <- Shared result computation (MCP + CLI)
operations/index.ts <- Analysis operation descriptors + typed input schemas
operations/formatters.ts <- Result-object text formatters for CLI commands
parser/duplication.ts <- Function-body clone token extraction
duplication/index.ts <- Duplicate family detection + trace evidence
map/index.ts <- Focused codebase maps + token-bounded context packs
drift/ <- Content drift findings, profiles, tokens, and stable evidence
boundaries/ <- Architecture zones, allow/forbid edge rules, and violation evidence
highways/index.ts <- Repeated route convergence + bypass/cowpath/synthesis evidence
health/ <- Health score, maintainability, CRAP, coverage lookup, and risk scoring
ci/ <- PR-friendly quality gate over check, changes, health, baselines, history, and workspace scope
doctor/ <- Read-only setup auditor for local, CI, MCP, and coding-agent workflows
ownership/ <- CODEOWNERS/git/package/directory ownership and bus-factor signals
recommendations/ <- Architecture recommendations with effort, evidence, and context commands
lsp/ <- Advisory diagnostics/hover facts and minimal stdio LSP server
workspaces/ <- Workspace detection, changed-scope summaries, and cross-package cycle evidence
watch/ <- Watch readiness snapshots and debounce-aware change reporting
migration/ <- Dry-run-first config migration into codebase-intelligence.json
hooks/ <- Dry-run-first local hook install/uninstall for the same CI gate
history/ <- Local finding-history fingerprints under .codebase-intelligence/
explain/ <- Rule explanations and action hints
mcp/index.ts <- 29 MCP tools for LLM integration
mcp/hints.ts <- Operation-keyed next-step hints for MCP tool responses
impact/index.ts <- Symbol-level impact analysis + rename planning
search/index.ts <- BM25 search engine
process/index.ts <- Entry point detection + call chain tracing
community/index.ts <- Louvain clustering
persistence/index.ts <- Graph export/import to .codebase-intelligence/
persistence/index-dir.ts <- Canonical cache path + legacy .code-visualizer/ migration
persistence/cache-key.ts <- Cache signature from HEAD, worktree content, CLI version, parser settings
server/graph-store.ts <- Global graph state (shared by CLI + MCP)
cli.ts <- Entry point, CLI commands + MCP fallback
```
## Data Flow
```
loadCodebaseGraph(rootDir)
-> cached CodebaseGraph when cache key matches
-> otherwise emits progress events through parse/build/analyze/cache
parseCodebase(rootDir)
-> ParsedFile[] (with churn, cyclomatic/cognitive complexity, test mapping, symbol type facts, duplicate token facts)
buildGraph(parsedFiles)
-> BuiltGraph { graph: Graph, nodes: GraphNode[], edges: GraphEdge[] }
analyzeGraph(builtGraph, parsedFiles)
-> CodebaseGraph {
nodes, edges, symbolNodes, callEdges, symbolMetrics,
fileMetrics, moduleMetrics, forceAnalysis, stats,
groups, processes, clusters
}
runOperation(operation, codebaseGraph, input, context)
-> { ok: true, data } | { ok: false, error, data? }
```
## Key Design Decisions
- **graphology**: In-memory graph with O(1) neighbor lookup. PageRank and betweenness computed via graphology-metrics.
- **Operation registry foundation**: Analysis operations have typed descriptors in `src/operations/` with operation names, CLI command names, MCP tool names, input schemas, discriminated run results, and result-object text formatters. MCP tool registration and CLI command execution consume those descriptors; CLI JSON remains raw result data plus cache facts.
- **Shared graph-load pipeline**: CLI commands and MCP stdio startup both use `src/graph-loader/` for path checks, legacy cache migration, cache reuse, parse/build/analyze, optional persistence, and stderr progress events.
- **Architecture boundaries**: `boundaries` / `check_boundaries` evaluates graph import edges against preset or custom zones and directed allow/forbid rules. `no-boundary-violations` reuses the same analyzer for CI gating.
- **Batch git churn**: Single `git log --all --name-only` call, parsed for all files. Avoids O(n) subprocess spawning.
- **Dead export detection**: Cross-references parsed exports against edge symbol lists. May miss `import *` or re-exports.
- **Graceful degradation**: Non-git dirs get churn=0, no-test codebases get coverage=false. Never crashes.
- **Auto-caching**: CLI commands always cache the graph index to `.codebase-intelligence/`. MCP mode requires `--index` to persist. Legacy `.code-visualizer/` is migrated when canonical cache is absent.
- **Cache JSON facts**: Analysis commands with `--json` and `init --json` include top-level `cache`: `cacheDir`, `legacyCacheDir`, `migrated`, `gitignoreUpdated`, `warnings[]`.
---
# Data Model
All types defined in `src/types/index.ts`.
## Parser Output
```typescript
ParsedFile {
path: string // Absolute filesystem path
relativePath: string // Relative to root (used as graph node ID)
loc: number // Lines of code
exports: ParsedExport[] // Named exports
symbols?: ParsedSymbol[] // Exported/local symbols with type facts
imports: ParsedImport[] // Relative imports (external skipped)
churn: number // Git commit count (0 if non-git)
isTestFile: boolean // Matches *.test.ts / *.spec.ts / __tests__/
testFile?: string // Path to matching test file (for source files)
}
ParsedExport {
name: string // Export name ("default" for default exports)
type: "function" | "class" | "variable" | "type" | "interface" | "enum"
loc: number // Lines of code for this export
isDefault: boolean
complexity: number // Cyclomatic complexity (branch count, min 1)
cognitiveComplexity?: number // Nesting-aware cognitive complexity
typeFacts?: SymbolTypeFacts
}
ParsedSymbol extends ParsedExport {
isExported: boolean
}
SymbolTypeFacts {
signature: string
parameters: Array<{ name: string, type: string, optional: boolean, rest: boolean }>
returnType?: string
typeParameters: Array<{ name: string, constraint?: string, default?: string }>
consumes: string[]
produces: string[]
confidence: "resolved" | "syntax"
}
ParsedImport {
from: string // Raw import path
resolvedFrom: string // Resolved relative path (after .js->.ts mapping)
symbols: string[] // Imported names (["default"] for default import)
isTypeOnly: boolean // import type { X }
}
```
## Graph Structure
```typescript
GraphNode {
id: string // = relativePath for files, parentFile+name for functions
type: "file" | "function"
path: string // Display path
label: string // File basename or function name
loc: number
module: string // Top-level directory
parentFile?: string // For function nodes: which file owns this
}
GraphEdge {
source: string // Importer file ID
target: string // Imported file ID
symbols: string[] // What's imported
isTypeOnly: boolean // Type-only import
weight: number // Edge weight (default 1)
}
```
## Computed Metrics
```typescript
FileMetrics {
pageRank: number
betweenness: number
fanIn: number
fanOut: number
coupling: number // fanOut / (max(fanIn, 1) + fanOut)
tension: number // Entropy of multi-module pulls
isBridge: boolean // betweenness > 0.1
churn: number // Git commit count
hasTests: boolean // Test file exists
testFile: string // Path to test file
cyclomaticComplexity: number // Avg complexity of exports
cognitiveComplexity?: number // Avg nesting-aware complexity of symbols
blastRadius: number // Transitive dependent count
deadExports: string[] // Unused export names
totalExports: number // Named export count used as dead-export denominator
isPackageEntrypoint: boolean // package.json exports/main/types/bin point here
packageEntrypointReason: string // package.json field/path evidence
isTestFile: boolean // Whether this file is a test
}
ModuleMetrics {
path: string
files: number
loc: number
exports: number
internalDeps: number
externalDeps: number
cohesion: number // internalDeps / totalDeps
escapeVelocity: number // Extraction readiness
dependsOn: string[]
dependedBy: string[]
}
```
Graph stats include `analysisMode` (`full-program` or `ast-only`), `callGraphPrecision` (`type-resolved` or `syntax-only`), and `fullProgramFileLimit`. In `ast-only` mode, file/import/export/dependency metrics remain available while type-resolved call graph detail is reduced.
## Codebase Map Result
`map --json`, MCP `get_codebase_map`, `get_scope_graph`, and `get_context_pack`
return deterministic graph/context data with stable IDs.
```typescript
CodebaseMapResult {
overview: { focus?: string; scope?: string; depth: number; contextBudget: number; totalNodes: number; totalEdges: number; totalEvidence: number }
focus?: CodebaseMapNode
nodes: CodebaseMapNode[]
edges: CodebaseMapEdge[]
evidence: CodebaseMapEvidence[]
contextPack: CodebaseContextPack
summary: string
}
CodebaseMapNode {
id: string
kind: "file" | "symbol" | "test" | "scope"
label: string
file?: string
symbol?: string
score: number
evidenceIds: string[]
}
CodebaseMapEdge {
id: string
kind: "calls" | "contains" | "imports" | "tests"
from: string
to: string
label: string
weight: number
evidenceIds: string[]
}
CodebaseContextPack {
tokenBudget: number
tokenEstimate: number
rankedFiles: Array<{ path: string; rank: number; reason: string; tokenEstimate: number; evidenceIds: string[] }>
rankedSymbols: Array<{ file: string; symbol: string; rank: number; reason: string; tokenEstimate: number; evidenceIds: string[] }>
tests: Array<{ path: string; covers: string; rank: number; reason: string; tokenEstimate: number; evidenceIds: string[] }>
evidenceIds: string[]
nextCommands: string[]
}
```
## 2.5.0 Workflow Result Envelopes
```typescript
FindingAction {
kind: "remove-comment" | "inspect-boundary" | "inspect-file" | "inspect-symbol" | "run-check" | "review-finding" | "create-baseline"
auto_fixable: boolean
range?: { start: number; end: number }
command?: string
reason?: string
}
CiResult {
verdict: "pass" | "fail"
exitCode: 0 | 1
base: string
newOnly: boolean
gates: Array<{ name: string; verdict: "pass" | "warn" | "fail"; summary: string }>
check: CheckResult
health: HealthResult
changes: ChangesResult
workspaces?: WorkspacesResult
baseline: { path?: string; ignoredFindings: number }
}
DoctorResult {
status: "pass" | "warn" | "fail"
profile: "local" | "ci" | "agent" | "mcp"
agent: "codex" | "claude" | "cursor" | "generic"
checks: Array<{ id: string; level: "pass" | "warn" | "fail"; title: string; evidence: string[]; fix?: string; docs?: string }>
}
OwnershipResult { groupBy: "owner" | "package" | "directory"; files: Array<{ file: string; owner: string; hasTests: boolean; coverageGap: boolean }>; groups: Array<{ key: string; coverageGaps: number; riskScore: number }>; hotspots: Array<object> }
ArchitectureRecommendationsResult { recommendations: Array<{ id: string; effort: "small" | "medium" | "large"; affectedFiles: string[]; evidence: string[]; contextPack: object }> }
LspSnapshot { diagnostics: Array<object>; hovers: Array<object>; summary: string }
WorkspacesResult { base: string; changedOnly: boolean; workspaces: Array<{ name: string; path: string; files: number; changed: boolean; cycles: string[][]; evidence: string[] }>; crossPackageCycles: string[][]; summary: string }
```
---
# Metrics Reference
## Per-File Metrics
| Metric | Range | Description |
|--------|-------|-------------|
| pageRank | 0-1 | Importance in dependency graph |
| betweenness | 0-1 | Bridge frequency between shortest paths |
| fanIn | 0-N | Files that import this file |
| fanOut | 0-N | Files this file imports |
| coupling | 0-1 | fanOut / (max(fanIn, 1) + fanOut) |
| tension | 0-1 | Multi-module pull evenness. >0.3 = tension |
| isBridge | bool | betweenness > 0.1 |
| churn | 0-N | Git commits touching this file |
| cyclomaticComplexity | 1-N | Avg complexity of exports |
| cognitiveComplexity | 0-N | Avg nesting-aware complexity of symbols |
| blastRadius | 0-N | Transitive dependents affected by change |
| deadExports | list | Export names not consumed by any import |
| totalExports | count | Named exports used as dead-export denominator |
| isPackageEntrypoint | bool | True when package.json exports/main/types/bin point at file |
| packageEntrypointReason | string | package.json entry evidence for public API confidence |
| hasTests | bool | Matching test file exists |
## Module Metrics
| Metric | Description |
|--------|-------------|
| cohesion | internalDeps / totalDeps. 1=fully internal |
| escapeVelocity | Extraction readiness. High = few internal deps, many consumers |
| verdict | LEAF / COHESIVE / MODERATE / JUNK_DRAWER |
## Force Analysis
| Signal | Threshold | Meaning |
|--------|-----------|---------|
| Tension file | tension > 0.3 | Pulled by 2+ modules equally. Split candidate |
| Bridge file | betweenness > 0.05 | Removing disconnects graph. Critical path |
| Junk drawer | cohesion < 0.4 | Mostly external deps. Needs restructuring |
| Extraction candidate | escapeVelocity >= 0.5 | 0 internal deps, many consumers. Extract to package |
## Risk Trifecta
The most dangerous files have: high churn + high coupling + low coverage.
---
# MCP Tools Reference
29 tools available via MCP stdio.
## 1. codebase_overview
High-level summary. Input: `{ depth?: number }`. Returns: totalFiles, totalFunctions, modules, topDependedFiles, metrics, and analysis mode/call graph precision.
## 2. file_context
Detailed file context. Input: `{ filePath: string }`. Returns: exports, imports, dependents, all FileMetrics.
## 3. get_dependents
File-level blast radius. Input: `{ filePath: string, depth?: number }`. Returns: direct + transitive dependents, riskLevel.
## 4. find_hotspots
Rank files by metric. Input: `{ metric: string, limit?: number }`. Metrics: coupling, pagerank, fan_in, fan_out, betweenness, tension, escape_velocity, churn, complexity, cognitive_complexity, blast_radius, coverage, risk.
## 5. get_module_structure
Module architecture. Input: `{ depth?: number }`. Returns: modules with metrics, cross-module deps, circular deps.
## 6. analyze_forces
Architectural force analysis. Input: `{ cohesionThreshold?, tensionThreshold?, escapeThreshold? }`. Returns: cohesion verdicts, tension files, bridge files, extraction candidates.
## 7. find_dead_exports
Unused exports. Input: `{ module?: string, limit?: number }`. Returns: files with dead exports plus confidence. Package public entrypoints from `exports`, `main`, `types`, and `bin` are low confidence because external consumers may use them.
## 8. find_opportunities
Rank code quality and refactoring opportunities. Input: `{ limit?: number }`. Returns: ranked opportunities with priority, confidence, evidence, and suggested commands.
## 9. find_duplicates
Duplicate function families. Input: `{ mode?: "strict" | "mild" | "weak", minTokens?: number, skipLocal?: boolean, trace?: string }`. Returns: family IDs, members, token counts, similarity thresholds, and optional trace evidence.
## 10. get_groups
Top-level directory groups. Input: `{}`. Returns: groups with rank, files, loc, importance, coupling.
## 11. symbol_context
Function/class/method context. Input: `{ name: string }`. Returns: callers, callees, metrics, additive typeFacts when known.
## 12. search
Keyword/search shape facts (BM25). Input: `{ query: string, limit?: number }`. Returns: ranked files + symbols with additive typeFacts when known.
## 13. detect_changes
Git diff analysis. Input: `{ scope?: "staged" | "unstaged" | "all" }`. Returns: changed files, affected files, risk metrics.
## 14. impact_analysis
Symbol-level blast radius. Input: `{ symbol: string }`. Returns: depth-grouped impact levels.
## 15. rename_symbol
Reference finder for rename planning. Input: `{ oldName: string, newName: string, dryRun?: boolean }`. Returns: references with confidence.
## 16. get_processes
Entry point execution flows. Input: `{ entryPoint?: string, limit?: number }`. Returns: processes with steps and depth.
## 17. get_codebase_map
Focused codebase graph. Input: `{ focus?: string, scope?: string, depth?: number, format?: "json" | "markdown" | "dot" | "graphml", contextBudget?: number }`. Returns: overview, focus node, nodes, edges, evidence, contextPack, summary.
## 18. get_scope_graph
File/scope/test topology from the same map result. Input: same as `get_codebase_map`. Returns: overview, focus node, file/test/scope nodes, imports/tests edges, evidence, summary.
## 19. get_context_pack
Token-bounded context pack from the same map result. Input: same as `get_codebase_map`. Returns: tokenBudget, tokenEstimate, rankedFiles, rankedSymbols, tests, evidenceIds, nextCommands.
## 20. detect_content_drift
Content drift. Input: `{ focus?: string, scope?: string, minScore?: number }`. Returns: report-only findings with stable IDs, kind, score, severity, declaredIntent, actualBehavior, evidence, recommendation, actions, and baseline status.
## 21. get_health_score
Health score. Input: `{ minScore?: number, score?: boolean }`. Returns: score, minScore, verdict, components, coverage source/counts, per-file maintainabilityIndex, crapScore, riskScore, hotspots, actions, and summary.
## 22. check_boundaries
Architecture boundaries. Input: `{ preset?: "bulletproof" | "layered" | "hexagonal" | "feature-sliced", list?: boolean }`. Returns: preset, zones, rules, summary, verdict, and stable violations with kind, source/target files, zones, symbols, evidence, and advisory actions.
## 23. analyze_highways
Repeated route convergence. Input: `{ operation?: string, shape?: string, minRoutes?: number, propose?: boolean, trace?: string }`. Returns: bypass/cowpath/synthesis opportunities with route chains, evidence, blast radius, proposed canonical node, optional synthesis proposal, and context pack.
## 24. get_clusters
Community-detected file clusters. Input: `{ minFiles?: number }`. Returns: clusters with cohesion.
## 25. get_ownership
Ownership and bus-factor grouping. Input: `{ groupBy?: "owner" | "package" | "directory", effort?: number }`. Returns: groups with files, owners, churn, risk, busFactor, and evidence.
## 26. get_architecture_recommendations
Rank extraction, seam, tension, and locality recommendations. Input: `{}`. Returns: stable recommendation IDs, effort, score, affected files, evidence, and contextPack commands.
## 27. get_lsp_snapshot
Advisory editor facts from the same graph as batch analysis. Input: `{}`. Returns: diagnostics and hover facts for dead exports, circular deps, complexity, and risk.
## 28. get_workspaces
Workspace/package scopes. Input: `{ base?: string, changedOnly?: boolean }`. Returns: workspaces with name, path, files, changed, cycles, evidence, crossPackageCycles, and summary.
## 29. check
Rules-engine gate. Input: `{}`. Returns: pass/warn/fail verdict, findings, suppression ledger, config path, and summary counts. Findings always include ruleId, severity, file, line, column, message, and fingerprint; cleanup findings may also include kind, confidence, and evidence. Suppressions include directive, active/stale status, file, line, targetLine, ruleIds, and suppressed count.
## Tool Selection Guide
| Question | Tool |
|----------|------|
| What does this codebase look like? | codebase_overview |
| Tell me about file X | file_context |
| What breaks if I change file X? | get_dependents |
| What breaks if I change function X? | impact_analysis |
| What are the riskiest files? | find_hotspots (risk) |
| Which files need tests? | find_hotspots (coverage) |
| What is the PR quality score? | get_health_score |
| Which imports violate architecture boundaries? | check_boundaries |
| What should I improve first? | find_opportunities |
| Find refactoring opportunities | find_opportunities |
| Where is logic duplicated? | find_duplicates |
| What can I safely delete? | find_dead_exports |
| How are modules organized? | get_module_structure |
| What's architecturally wrong? | analyze_forces |
| Who calls this function? | symbol_context |
| Find files related to X | search |
| What changed? | detect_changes |
| Find all references to X | rename_symbol |
| How does data flow? | get_processes |
| What context should I give an LLM for this task? | get_context_pack |
| Show a focused codebase graph | get_codebase_map |
| Which file names lie about behavior? | detect_content_drift |
| Which routes bypass canonical dataflow? | analyze_highways |
| What files naturally belong together? | get_clusters |
| Who owns this risky scope? | get_ownership |
| What architecture cleanup should happen next? | get_architecture_recommendations |
| What editor diagnostics match batch analysis? | get_lsp_snapshot |
| Which workspaces changed in this PR? | get_workspaces |
| What rule violations exist? | check |
---
# CLI Reference
35 public commands — 29 MCP-backed analysis tools plus `ci`, `doctor`, `watch`, `migrate-config`, `hooks`, `history`, `explain`, `check`, and `init`.
## Commands
### overview
```bash
codebase-intelligence overview <path> [--json] [--force]
```
High-level codebase snapshot: files, functions, modules, dependencies.
### hotspots
```bash
codebase-intelligence hotspots <path> [--metric <metric>] [--limit <n>] [--json] [--force]
```
Rank files by metric. Default: coupling. Available: coupling, pagerank, fan_in, fan_out, betweenness, tension, churn, complexity, cognitive_complexity, blast_radius, coverage, risk, escape_velocity.
### file
```bash
codebase-intelligence file <path> <file> [--json] [--force]
```
Detailed file context: exports, imports, dependents, all metrics.
### search
```bash
codebase-intelligence search <path> <query> [--limit <n>] [--json] [--force]
```
BM25 keyword search across files, symbols, and type/shape facts.
### changes
```bash
codebase-intelligence changes <path> [--scope <scope>] [--json] [--force]
```
Git diff analysis with risk metrics. Scope: staged, unstaged, all (default).
### dependents
```bash
codebase-intelligence dependents <path> <file> [--depth <n>] [--json] [--force]
```
File-level blast radius: direct + transitive dependents, risk level.
### modules
```bash
codebase-intelligence modules <path> [--json] [--force]
```
Module architecture: cohesion, cross-module deps, circular deps.
### forces
```bash
codebase-intelligence forces <path> [--cohesion <n>] [--tension <n>] [--escape <n>] [--json] [--force]
```
Architectural force analysis: tension files, bridges, extraction candidates.
### dead-exports
```bash
codebase-intelligence dead-exports <path> [--module <m>] [--limit <n>] [--json] [--force]
```
Find unused exports across the codebase.
### opportunities
```bash
codebase-intelligence opportunities <path> [--limit <n>] [--json] [--force]
```
Rank code quality and refactoring opportunities with evidence, confidence, and suggested commands.
### duplicates
```bash
codebase-intelligence duplicates <path> [--mode <mode>] [--min-tokens <n>] [--skip-local] [--trace <id>] [--json] [--force]
```
Detect strict, renamed, and near-miss duplicate function families.
### groups
```bash
codebase-intelligence groups <path> [--json] [--force]
```
Top-level directory groups with aggregate metrics.
### symbol
```bash
codebase-intelligence symbol <path> <name> [--json] [--force]
```
Function/class context: callers, callees, metrics.
### impact
```bash
codebase-intelligence impact <path> <symbol> [--json] [--force]
```
Symbol-level blast radius with depth-grouped impact levels.
### rename
```bash
codebase-intelligence rename <path> <oldName> <newName> [--no-dry-run] [--json] [--force]
```
Find all references for rename planning (read-only by default).
### processes
```bash
codebase-intelligence processes <path> [--entry <name>] [--limit <n>] [--json] [--force]
```
Entry point execution flows through the call graph.
### map
```bash
codebase-intelligence map <path> [--focus <symbolOrFile>] [--scope <scope>] [--depth <n>] [--format <format>] [--context-budget <n>] [--json] [--force]
```
Focused codebase graph plus token-bounded context pack. Formats: markdown, json, dot, graphml.
### drift
```bash
codebase-intelligence drift <path> [--focus <fileOrSymbol>] [--scope <scope>] [--min-score <n>] [--json] [--force]
```
Report-only content drift findings. Returns stable `drift-*` IDs, drift kind, score/severity, declaredIntent, actualBehavior, evidence, recommendation, advisory actions, and baseline status.
### health
```bash
codebase-intelligence health <path> [--score] [--min-score <n>] [--json] [--force]
```
CI-gateable health score. Returns score/verdict, components, root-local Istanbul or static-test coverage source, per-file maintainabilityIndex, crapScore, riskScore, hotspots, evidence, and actions. Exits 1 when score is below `--min-score`.
### boundaries
```bash
codebase-intelligence boundaries <path> [--config <path>] [--preset <preset>] [--list] [--json] [--force]
```
Evaluate architecture boundary zones and import rules. Presets: bulletproof, layered, hexagonal, feature-sliced. Top-level `boundaries.zones[]` config defines named areas; `boundaries.rules[]` config defines directed `from -> allow/forbid` imports. Returns stable violations for forbidden edges, disallowed edges, and risky re-export chains. Exits 1 when violations exist.
### highways
```bash
codebase-intelligence highways <path> [--operation <verb>] [--shape <name>] [--min-routes <n>] [--propose] [--trace <id>] [--json] [--force]
```
Find repeated routes that should converge on one canonical operation path. Returns bypass/cowpath findings with route chains, canonical node, evidence, blast radius, recommendation, and context pack. With `--propose`, no-canonical route groups can return `synthesis` findings with proposed name, file, signature, skeleton, reroute plan, and cycle-safety check.
### clusters
```bash
codebase-intelligence clusters <path> [--min-files <n>] [--json] [--force]
```
Community-detected file clusters (Louvain algorithm).
### owners
```bash
codebase-intelligence owners <path> [--group-by owner|package|directory] [--effort <n>] [--json] [--force]
```
Ownership, package, or directory grouping with bus-factor and risk evidence.
### architecture
```bash
codebase-intelligence architecture <path> [--json] [--force]
```
Rank graph-backed extraction, seam, tension, and locality recommendations.
### workspaces
```bash
codebase-intelligence workspaces <path> [--base <ref>] [--changed] [--json] [--force]
```
Detect package/workspace scopes, changed workspaces, and cross-package cycle evidence.
### lsp
```bash
codebase-intelligence lsp <path> [--diagnostics] [--json] [--force]
```
Start the advisory LSP server, or print diagnostics/hover facts with `--diagnostics`.
### watch
```bash
codebase-intelligence watch <path> [--once] [--debounce <ms>] [--json] [--force]
```
Keep analysis warm while editing; use `--once` for CI-safe readiness snapshots.
### ci
```bash
codebase-intelligence ci <path> [--base <ref>] [--new-only] [--all] [--fail-on error|warn|never] [--min-score <n>] [--max-new <n>] [--baseline <path>] [--format <fmt>] [--output <path>] [--comment markdown] [--summary] [--production] [--changed-since <ref>] [--diff-file <path>] [--changed-workspaces] [--history] [--json] [--force]
```
One PR-friendly quality gate around `check`, `changes`, health, baselines, local history, and optional changed-workspace summaries. Exit codes: 0 pass, 1 gate failed, 2 config/usage error, 3 analyzer error. Formats: text, json, sarif, markdown, annotations, pr-comment-github, pr-comment-gitlab, badge, codeclimate, compact.
### doctor
```bash
codebase-intelligence doctor [path] [--profile local|ci|agent|mcp] [--agent codex|claude|cursor|generic] [--json]
```
Read-only setup auditor for runtime, package manager, config schema, graph build, cache path, CLI help, MCP registry, CI workflow, and agent instructions.
### explain
```bash
codebase-intelligence explain <rule> [--json]
```
Explain a rule and safe next actions.
### migrate-config
```bash
codebase-intelligence migrate-config <path> [--source <name>] [--write] [--json]
```
Dry-run-first config migration into `codebase-intelligence.json`.
### hooks
```bash
codebase-intelligence hooks install [path] [--apply] [--command <cmd>] [--json]
codebase-intelligence hooks uninstall [path] [--apply] [--json]
```
Plan or install local hooks that run the same CI gate. Default is dry-run.
### history
```bash
codebase-intelligence history [path] [--json]
```
Read local finding-history fingerprints and counts from `.codebase-intelligence/history.json`.
### init
```bash
codebase-intelligence init [path] [--agents <list>] [--all] [--skill] [--gitignore] [--yes] [--json]
```
Set up AI agents to use codebase-intelligence. Writes an idempotent, marked
instruction block ("query CI before grep/read") into each selected agent's repo file —
`AGENTS.md`, `CLAUDE.md`, `.cursor/rules/codebase-intelligence.mdc`,
`.github/copilot-instructions.md`, `GEMINI.md`, `CONVENTIONS.md`. Opt-in: on a TTY it
shows an interactive picker (`AGENTS.md` + `CLAUDE.md` preselected); non-interactively
(or `--yes`/`--json`) it defaults to those two. `--agents` selects explicitly, `--all`
targets every agent, `--skill` also installs the portable skill to
`~/.claude/skills/codebase-intelligence/SKILL.md` (never installed otherwise). Only
content between the `codebase-intelligence:start`/`:end` markers is ever touched.
### check
```bash
codebase-intelligence check <path> [--config <path>] [--format <fmt>] [--fail-on <severity>] [--gate <mode>] [--base <ref>] [--changed-since <ref>] [--diff-file <path>] [--production] [--quiet] [--summary] [--json] [--force]
```
Rules-engine gate for CI. Formats: text, json, sarif, markdown, annotations, pr-comment-github, pr-comment-gitlab, badge, codeclimate, compact. Fail-on: error, warn, never.
Gate modes: all, new-only. Returns pass/warn/fail verdict, findings with advisory `actions[]`, suppression ledger, and summary counts. Built-in rules include no-comments, no-boundary-violations, no-circular-deps, no-dead-exports, no-stale-suppressions, and opt-in no-dead-files, no-unused-types, no-unused-members, no-unused-deps, no-secrets. Dependency findings are scoped to the nearest package/workspace manifest and include unused, unlisted, type-only, test-only, and runtime-from-devDependencies drift. Reports active/stale `ci-ignore-*` and `@expected-unused` suppressions; `@public` protects exported cleanup declarations while `@internal` remains checkable.
## Global Behavior
- **Auto-caching**: First run parses and saves index to `.codebase-intelligence/`. Subsequent runs use cache only when HEAD, dirty/untracked file contents under the analyzed path, CLI version, and parser cache settings match. Legacy `.code-visualizer/` is migrated when canonical cache is absent.
- **Cache JSON facts**: Analysis commands with `--json` and `init --json` include top-level `cache`: `cacheDir`, `legacyCacheDir`, `migrated`, `gitignoreUpdated`, `warnings[]`.
- **Default scanner excludes**: `.git`, `node_modules`, `.codebase-intelligence`, legacy `.code-visualizer`, `.next`, `dist`, `coverage`, `.turbo`, `.cache`, `.worktrees`, and `.claude/worktrees`.
- **Monorepo imports**: Root tsconfig path aliases and local package.json package names resolve to source files before graph construction.
- **Large repo mode**: Above 1500 TypeScript files, use AST-only extraction to avoid TypeScript program OOM. Override with `CBI_FULL_PROGRAM_FILE_LIMIT`.
- **Real-repo verification**: `pnpm verify:cli-real` runs the default matrix. `pnpm verify:cli-real:heavy` sets `CBI_REAL_PROFILE=heavy` and verifies large `/home/ubuntu` repos with minimum file/dependency thresholds.
- **Progress**: All progress messages go to stderr. Results go to stdout.
- **JSON mode**: `--json` outputs stable JSON schema to stdout.
- **Exit codes**: 0 = success, 1 = runtime error, 2 = bad args/usage.
- **MCP mode**: `codebase-intelligence <path>` (no subcommand) starts MCP stdio server.
- **MCP operation errors**: Invalid operation inputs return `isError: true` with JSON text `{ "error": "..." }` using the same descriptor validation messages as CLI bad-argument exits.