-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.ts
More file actions
1205 lines (1034 loc) · 41.3 KB
/
Copy pathcli.ts
File metadata and controls
1205 lines (1034 loc) · 41.3 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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
process.on("SIGINT", () => {
process.exit(0);
});
process.on("uncaughtException", (err) => {
process.stderr.write(`Fatal: ${err.stack ?? err.message}\n`);
process.exit(1);
});
import fs from "fs";
import path from "path";
import { execSync } from "child_process";
import { createRequire } from "module";
import { Command } from "commander";
const require = createRequire(import.meta.url);
const pkg = require("../package.json") as { version: string };
import { parseCodebase } from "./parser/index.js";
import { buildGraph } from "./graph/index.js";
import { analyzeGraph } from "./analyzer/index.js";
import { startMcpServer } from "./mcp/index.js";
import { setIndexedHead, setRoot } from "./server/graph-store.js";
import { exportGraph, importGraph } from "./persistence/index.js";
import {
computeOverview,
computeFileContext,
computeHotspots,
computeSearch,
computeChanges,
computeDependents,
computeModuleStructure,
computeForces,
computeDeadExports,
computeGroups,
computeSymbolContext,
computeProcesses,
computeClusters,
impactAnalysis,
renameSymbol,
} from "./core/index.js";
import {
installRepoFiles,
installGlobalSkill,
resolveInitPlan,
ALL_AGENT_IDS,
} from "./install/index.js";
import { promptSelection } from "./install/prompt.js";
import { runCheck, exitCodeFor } from "./rules/check.js";
import { formatResult, formatSummaryLine } from "./rules/format.js";
import { ConfigError } from "./config/index.js";
import type { CodebaseGraph, OutputFormat } from "./types/index.js";
const INDEX_DIR_NAME = ".code-visualizer";
// ── Helpers ─────────────────────────────────────────────────
function getIndexDir(targetPath: string): string {
return path.join(path.resolve(targetPath), INDEX_DIR_NAME);
}
function getHeadHash(targetPath: string): string {
try {
return execSync("git rev-parse HEAD", {
cwd: path.resolve(targetPath),
encoding: "utf-8",
timeout: 5000,
stdio: ["ignore", "pipe", "ignore"],
}).trim();
} catch {
return "unknown";
}
}
function progress(msg: string): void {
process.stderr.write(`${msg}\n`);
}
function output(data: string): void {
process.stdout.write(`${data}\n`);
}
function outputJson(data: unknown): void {
process.stdout.write(`${JSON.stringify(data, null, 2)}\n`);
}
/** Load (or parse+cache) the codebase graph for a target path. */
function loadGraph(targetPath: string, force = false): { graph: CodebaseGraph; headHash: string } {
const resolved = path.resolve(targetPath);
if (!fs.existsSync(resolved)) {
process.stderr.write(`Error: Path does not exist: ${targetPath}\n`);
process.exit(1);
}
setRoot(resolved);
const indexDir = getIndexDir(targetPath);
const headHash = getHeadHash(targetPath);
if (!force && headHash !== "unknown") {
const cached = importGraph(indexDir);
if (cached?.headHash === headHash) {
progress(`Using cached index (HEAD: ${headHash.slice(0, 7)})`);
setIndexedHead(cached.headHash);
return { graph: cached.graph, headHash };
}
}
progress(`Parsing ${targetPath}...`);
const files = parseCodebase(targetPath);
progress(`Parsed ${files.length} files`);
if (files.length === 0) {
process.stderr.write(`Error: No TypeScript files found at ${targetPath}\n`);
process.exit(1);
}
const built = buildGraph(files);
progress(
`Built graph: ${built.nodes.filter((n) => n.type === "file").length} files, ` +
`${built.nodes.filter((n) => n.type === "function").length} functions, ` +
`${built.edges.length} dependencies`,
);
const graph = analyzeGraph(built, files);
progress(
`Analysis complete: ${graph.stats.circularDeps.length} circular deps, ` +
`${graph.forceAnalysis.tensionFiles.length} tension files`,
);
setIndexedHead(headHash);
exportGraph(graph, indexDir, headHash);
progress(`Index saved to ${indexDir}`);
return { graph, headHash };
}
// ── CLI Program ─────────────────────────────────────────────
interface CliCommandOptions {
json?: boolean;
force?: boolean;
}
interface HotspotOptions extends CliCommandOptions {
metric?: string;
limit?: string;
}
interface SearchOptions extends CliCommandOptions {
limit?: string;
}
interface ChangesOptions extends CliCommandOptions {
scope?: string;
}
interface DependentsOptions extends CliCommandOptions {
depth?: string;
}
interface ForcesOptions extends CliCommandOptions {
cohesion?: string;
tension?: string;
escape?: string;
}
interface DeadExportsOptions extends CliCommandOptions {
module?: string;
limit?: string;
}
interface ProcessesOptions extends CliCommandOptions {
entry?: string;
limit?: string;
}
interface ClustersOptions extends CliCommandOptions {
minFiles?: string;
}
interface RenameOptions extends CliCommandOptions {
dryRun?: boolean;
}
interface McpOptions {
index?: boolean;
force?: boolean;
status?: boolean;
clean?: boolean;
}
interface InitOptions {
agents?: string;
all?: boolean;
skill?: boolean;
yes?: boolean;
json?: boolean;
}
const program = new Command();
program
.name("codebase-intelligence")
.description("Analyze TypeScript codebases — architecture, dependencies, metrics.")
.version(pkg.version);
// Commander auto-generates the command list; only the extras it can't express
// (MCP mode, a starter hint) are appended after it. A second, hand-maintained
// command list would drift out of sync — keep commander as the single source.
program.addHelpText(
"after",
"\nMCP mode:\n" +
" codebase-intelligence <path> Start MCP stdio server\n\n" +
"Try: codebase-intelligence overview ./src",
);
// ── Subcommand: overview ────────────────────────────────────
program
.command("overview")
.description("High-level codebase snapshot: files, functions, modules, dependencies")
.argument("<path>", "Path to TypeScript codebase")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, options: CliCommandOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const result = computeOverview(graph);
if (options.json) {
outputJson(result);
return;
}
output(`Codebase Overview`);
output(`─────────────────`);
output(`Files: ${result.totalFiles}`);
output(`Functions: ${result.totalFunctions}`);
output(`Dependencies: ${result.totalDependencies}`);
output(`Avg LOC: ${result.metrics.avgLOC}`);
output(`Max Depth: ${result.metrics.maxDepth}`);
output(`Circular: ${result.metrics.circularDeps}`);
output(``);
output(`Modules`);
output(`${"Path".padEnd(40)} ${"Files".padStart(6)} ${"LOC".padStart(8)} ${"Coupling".padStart(10)} ${"Cohesion".padStart(10)}`);
output(`${"─".repeat(40)} ${"─".repeat(6)} ${"─".repeat(8)} ${"─".repeat(10)} ${"─".repeat(10)}`);
for (const m of result.modules) {
output(
`${m.path.padEnd(40)} ${String(m.files).padStart(6)} ${String(m.loc).padStart(8)} ${m.avgCoupling.padStart(10)} ${m.cohesion.toFixed(2).padStart(10)}`,
);
}
output(``);
output(`Top Depended Files`);
for (const f of result.topDependedFiles) {
output(` ${f}`);
}
});
// ── Subcommand: hotspots ────────────────────────────────────
program
.command("hotspots")
.description("Rank files by metric (coupling, pagerank, churn, complexity, blast_radius, ...)")
.argument("<path>", "Path to TypeScript codebase")
.option("--metric <metric>", "Metric to rank by (default: coupling)")
.option("--limit <n>", "Number of results (default: 10)")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, options: HotspotOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const metric = options.metric ?? "coupling";
const limit = options.limit ? parseInt(options.limit, 10) : 10;
if (isNaN(limit) || limit < 1) {
process.stderr.write("Error: --limit must be a positive integer\n");
process.exit(2);
}
const result = computeHotspots(graph, metric, limit);
if (options.json) {
outputJson(result);
return;
}
if (!options.metric) {
progress(`Showing coupling (default). Use --metric to change.`);
}
output(`Hotspots: ${result.metric}`);
output(`──────────${"─".repeat(result.metric.length)}`);
output(`${"Path".padEnd(50)} ${"Score".padStart(10)} Reason`);
output(`${"─".repeat(50)} ${"─".repeat(10)} ${"─".repeat(30)}`);
for (const h of result.hotspots) {
output(`${h.path.padEnd(50)} ${h.score.toFixed(2).padStart(10)} ${h.reason}`);
}
output(``);
output(result.summary);
});
// ── Subcommand: file ────────────────────────────────────────
program
.command("file")
.description("Detailed file context: exports, imports, dependents, metrics")
.argument("<path>", "Path to TypeScript codebase")
.argument("<file>", "File to inspect (relative to codebase root)")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, filePath: string, options: CliCommandOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const result = computeFileContext(graph, filePath);
if ("error" in result) {
process.stderr.write(`Error: ${result.error}\n`);
if (result.suggestions.length > 0) {
process.stderr.write(`\nDid you mean:\n`);
for (const s of result.suggestions) {
process.stderr.write(` ${s}\n`);
}
}
process.exit(1);
}
if (options.json) {
outputJson(result);
return;
}
output(`File: ${result.path}`);
output("─".repeat(6 + result.path.length));
output(`LOC: ${result.loc}`);
output(``);
if (result.exports.length > 0) {
output(`Exports (${result.exports.length})`);
for (const e of result.exports) {
output(` ${e.type.padEnd(12)} ${e.name} (${e.loc} LOC)`);
}
output(``);
}
if (result.imports.length > 0) {
output(`Imports (${result.imports.length})`);
for (const i of result.imports) {
const typeTag = i.isTypeOnly ? " [type]" : "";
output(` ${i.from} → {${i.symbols.join(", ")}}${typeTag}`);
}
output(``);
}
if (result.dependents.length > 0) {
output(`Dependents (${result.dependents.length})`);
for (const d of result.dependents) {
const typeTag = d.isTypeOnly ? " [type]" : "";
output(` ${d.path} → {${d.symbols.join(", ")}}${typeTag}`);
}
output(``);
}
output(`Metrics`);
output(` PageRank: ${result.metrics.pageRank}`);
output(` Betweenness: ${result.metrics.betweenness}`);
output(` Fan-in: ${result.metrics.fanIn}`);
output(` Fan-out: ${result.metrics.fanOut}`);
output(` Coupling: ${result.metrics.coupling}`);
output(` Tension: ${result.metrics.tension}`);
output(` Bridge: ${result.metrics.isBridge ? "yes" : "no"}`);
output(` Churn: ${result.metrics.churn}`);
output(` Complexity: ${result.metrics.cyclomaticComplexity}`);
output(` Blast radius: ${result.metrics.blastRadius}`);
output(` Has tests: ${result.metrics.hasTests ? `yes (${result.metrics.testFile})` : "no"}`);
if (result.metrics.deadExports.length > 0) {
output(` Dead exports: ${result.metrics.deadExports.join(", ")}`);
}
});
// ── Subcommand: search ──────────────────────────────────────
program
.command("search")
.description("Keyword search across files and symbols (BM25)")
.argument("<path>", "Path to TypeScript codebase")
.argument("<query>", "Search query")
.option("--limit <n>", "Number of results (default: 20)")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, query: string, options: SearchOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const limit = options.limit ? parseInt(options.limit, 10) : 20;
if (isNaN(limit) || limit < 1) {
process.stderr.write("Error: --limit must be a positive integer\n");
process.exit(2);
}
const result = computeSearch(graph, query, limit);
if (options.json) {
outputJson(result);
return;
}
if (result.results.length === 0) {
output(`No results for "${query}"`);
if (result.suggestions && result.suggestions.length > 0) {
output(`\nDid you mean: ${result.suggestions.join(", ")}?`);
}
return;
}
output(`Search: "${query}" (${result.results.length} results)`);
output("─".repeat(40));
for (const r of result.results) {
output(`${r.file} (score: ${r.score.toFixed(2)})`);
for (const s of r.symbols) {
output(` ${s.type.padEnd(12)} ${s.name} (${s.loc} LOC, relevance: ${s.relevance.toFixed(2)})`);
}
}
});
// ── Subcommand: changes ─────────────────────────────────────
program
.command("changes")
.description("Analyze git changes: affected files, symbols, risk metrics")
.argument("<path>", "Path to TypeScript codebase")
.option("--scope <scope>", "Diff scope: staged, unstaged, or all (default: all)")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, options: ChangesOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const result = computeChanges(graph, options.scope);
if ("error" in result) {
process.stderr.write(`Error: ${result.error}\n`);
process.exit(1);
}
if (options.json) {
outputJson(result);
return;
}
output(`Changes (${result.scope})`);
output("─".repeat(20));
if (result.changedFiles.length === 0) {
output(`No changes detected.`);
return;
}
output(`Changed files (${result.changedFiles.length}):`);
for (const f of result.changedFiles) {
output(` ${f}`);
}
if (result.changedSymbols.length > 0) {
output(``);
output(`Changed symbols:`);
for (const cs of result.changedSymbols) {
output(` ${cs.file}: ${cs.symbols.join(", ")}`);
}
}
if (result.affectedFiles.length > 0) {
output(``);
output(`Affected files (${result.affectedFiles.length}):`);
for (const f of result.affectedFiles) {
output(` ${f}`);
}
}
if (result.fileRiskMetrics.length > 0) {
output(``);
output(`Risk Metrics`);
output(`${"File".padEnd(50)} ${"Blast".padStart(8)} ${"Cmplx".padStart(8)} ${"Churn".padStart(8)}`);
output(`${"─".repeat(50)} ${"─".repeat(8)} ${"─".repeat(8)} ${"─".repeat(8)}`);
for (const m of result.fileRiskMetrics) {
output(
`${m.file.padEnd(50)} ${String(m.blastRadius).padStart(8)} ${m.complexity.toFixed(1).padStart(8)} ${String(m.churn).padStart(8)}`,
);
}
}
});
// ── Subcommand: dependents ──────────────────────────────────
program
.command("dependents")
.description("File-level blast radius: direct + transitive dependents")
.argument("<path>", "Path to TypeScript codebase")
.argument("<file>", "File to inspect (relative to codebase root)")
.option("--depth <n>", "Max traversal depth (default: 2)")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, filePath: string, options: DependentsOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const depth = options.depth ? parseInt(options.depth, 10) : undefined;
if (depth !== undefined && (isNaN(depth) || depth < 1)) {
process.stderr.write("Error: --depth must be a positive integer\n");
process.exit(2);
}
const result = computeDependents(graph, filePath, depth);
if ("error" in result) {
process.stderr.write(`Error: ${result.error}\n`);
process.exit(1);
}
if (options.json) {
outputJson(result);
return;
}
output(`Dependents: ${result.file}`);
output("─".repeat(13 + result.file.length));
output(`Risk level: ${result.riskLevel}`);
output(`Total affected: ${result.totalAffected}`);
output(``);
if (result.directDependents.length > 0) {
output(`Direct dependents (${result.directDependents.length}):`);
for (const d of result.directDependents) {
output(` ${d.path} → {${d.symbols.join(", ")}}`);
}
output(``);
}
if (result.transitiveDependents.length > 0) {
output(`Transitive dependents (${result.transitiveDependents.length}):`);
for (const t of result.transitiveDependents) {
output(` ${t.path} (depth ${t.depth}, via ${t.throughPath.join(" → ")})`);
}
}
});
// ── Subcommand: modules ────────────────────────────────────
program
.command("modules")
.description("Module architecture: cohesion, cross-module deps, circular deps")
.argument("<path>", "Path to TypeScript codebase")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, options: CliCommandOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const result = computeModuleStructure(graph);
if (options.json) {
outputJson(result);
return;
}
output(`Module Structure`);
output(`────────────────`);
output(`${"Path".padEnd(30)} ${"Files".padStart(6)} ${"LOC".padStart(8)} ${"Cohesion".padStart(10)} ${"EscVel".padStart(8)}`);
output(`${"─".repeat(30)} ${"─".repeat(6)} ${"─".repeat(8)} ${"─".repeat(10)} ${"─".repeat(8)}`);
for (const m of result.modules) {
output(
`${m.path.padEnd(30)} ${String(m.files).padStart(6)} ${String(m.loc).padStart(8)} ${m.cohesion.toFixed(2).padStart(10)} ${m.escapeVelocity.toFixed(2).padStart(8)}`,
);
}
if (result.crossModuleDeps.length > 0) {
output(``);
output(`Cross-Module Dependencies (${result.crossModuleDeps.length}):`);
for (const d of result.crossModuleDeps.slice(0, 20)) {
output(` ${d.from} → ${d.to} (weight: ${d.weight})`);
}
}
if (result.circularDeps.length > 0) {
output(``);
output(`Circular Dependencies (${result.circularDeps.length}):`);
for (const c of result.circularDeps) {
output(` [${c.severity}] ${c.cycle.map((p) => p.join(" → ")).join("; ")}`);
}
}
});
// ── Subcommand: forces ─────────────────────────────────────
program
.command("forces")
.description("Architectural force analysis: tension, bridges, extraction candidates")
.argument("<path>", "Path to TypeScript codebase")
.option("--cohesion <n>", "Min cohesion threshold (default: 0.6)")
.option("--tension <n>", "Min tension threshold (default: 0.3)")
.option("--escape <n>", "Min escape velocity threshold (default: 0.5)")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, options: ForcesOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const cohesion = options.cohesion ? parseFloat(options.cohesion) : undefined;
const tension = options.tension ? parseFloat(options.tension) : undefined;
const escape = options.escape ? parseFloat(options.escape) : undefined;
const result = computeForces(graph, cohesion, tension, escape);
if (options.json) {
outputJson(result);
return;
}
output(`Force Analysis`);
output(`──────────────`);
output(result.summary);
output(``);
output(`Module Cohesion:`);
for (const m of result.moduleCohesion) {
output(` ${m.path.padEnd(30)} ${m.verdict.padEnd(14)} cohesion: ${m.cohesion.toFixed(2)}`);
}
if (result.tensionFiles.length > 0) {
output(``);
output(`Tension Files (${result.tensionFiles.length}):`);
for (const t of result.tensionFiles) {
output(` ${t.file} (tension: ${t.tension.toFixed(2)})`);
for (const p of t.pulledBy) {
output(` ← ${p.module} (strength: ${p.strength.toFixed(2)}, symbols: ${p.symbols.join(", ")})`);
}
}
}
if (result.bridgeFiles.length > 0) {
output(``);
output(`Bridge Files (${result.bridgeFiles.length}):`);
for (const b of result.bridgeFiles) {
output(` ${b.file} (betweenness: ${b.betweenness.toFixed(3)}, role: ${b.role})`);
}
}
if (result.extractionCandidates.length > 0) {
output(``);
output(`Extraction Candidates (${result.extractionCandidates.length}):`);
for (const e of result.extractionCandidates) {
output(` ${e.target} (escape velocity: ${e.escapeVelocity.toFixed(2)})`);
output(` ${e.recommendation}`);
}
}
if (result.shallowModules.length > 0) {
output(``);
output(`Shallow Modules (${result.shallowModules.length}):`);
for (const m of result.shallowModules) {
output(` ${m.module} (${m.exports} exports, cohesion: ${m.cohesion.toFixed(2)})`);
output(` ${m.evidence}`);
}
}
if (result.deepModules.length > 0) {
output(``);
output(`Deep Modules (${result.deepModules.length}):`);
for (const m of result.deepModules) {
output(` ${m.module} (${m.exports} exports, depended by: ${m.dependedByModules})`);
output(` ${m.evidence}`);
}
}
if (result.seamCandidates.length > 0) {
output(``);
output(`Seam Candidates (${result.seamCandidates.length}):`);
for (const seam of result.seamCandidates) {
output(` ${seam.target} [${seam.scope}] (dependents: ${seam.dependentModules}, fan-in: ${seam.fanIn})`);
output(` ${seam.evidence}`);
}
}
if (result.localityRisks.length > 0) {
output(``);
output(`Locality Risks (${result.localityRisks.length}):`);
for (const risk of result.localityRisks) {
output(` ${risk.file} [${risk.kind}] (blast radius: ${risk.blastRadius}, tension: ${risk.tension.toFixed(2)})`);
output(` ${risk.evidence}`);
}
}
});
// ── Subcommand: dead-exports ───────────────────────────────
program
.command("dead-exports")
.description("Find unused exports across the codebase")
.argument("<path>", "Path to TypeScript codebase")
.option("--module <module>", "Filter by module path")
.option("--limit <n>", "Max results (default: 20)")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, options: DeadExportsOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const limit = options.limit ? parseInt(options.limit, 10) : undefined;
if (limit !== undefined && (isNaN(limit) || limit < 1)) {
process.stderr.write("Error: --limit must be a positive integer\n");
process.exit(2);
}
const result = computeDeadExports(graph, options.module, limit);
if (options.json) {
outputJson(result);
return;
}
output(`Dead Exports`);
output(`────────────`);
output(result.summary);
if (result.files.length > 0) {
output(``);
for (const f of result.files) {
output(`${f.path} (${f.deadExports.length}/${f.totalExports} unused):`);
for (const e of f.deadExports) {
output(` - ${e}`);
}
}
}
});
// ── Subcommand: groups ─────────────────────────────────────
program
.command("groups")
.description("Top-level directory groups with aggregate metrics")
.argument("<path>", "Path to TypeScript codebase")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, options: CliCommandOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const result = computeGroups(graph);
if (options.json) {
outputJson(result);
return;
}
output(`Groups`);
output(`──────`);
output(`${"#".padStart(3)} ${"Name".padEnd(20)} ${"Files".padStart(6)} ${"LOC".padStart(8)} ${"Importance".padStart(12)} ${"Coupling".padStart(10)}`);
output(`${"─".repeat(3)} ${"─".repeat(20)} ${"─".repeat(6)} ${"─".repeat(8)} ${"─".repeat(12)} ${"─".repeat(10)}`);
for (const g of result.groups) {
output(
`${String(g.rank).padStart(3)} ${g.name.padEnd(20)} ${String(g.files).padStart(6)} ${String(g.loc).padStart(8)} ${g.importance.padStart(12)} ${String(g.coupling.total).padStart(10)}`,
);
}
});
// ── Subcommand: symbol ─────────────────────────────────────
program
.command("symbol")
.description("Function/class context: callers, callees, metrics")
.argument("<path>", "Path to TypeScript codebase")
.argument("<name>", "Symbol name (e.g., 'AuthService', 'getUserById')")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, symbolName: string, options: CliCommandOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const result = computeSymbolContext(graph, symbolName);
if ("error" in result) {
process.stderr.write(`Error: ${result.error}\n`);
process.exit(1);
}
if (options.json) {
outputJson(result);
return;
}
output(`Symbol: ${result.name}`);
output("─".repeat(8 + result.name.length));
output(`File: ${result.file}`);
output(`Type: ${result.type}`);
output(`LOC: ${result.loc}`);
output(`Default: ${result.isDefault ? "yes" : "no"}`);
output(`Complexity: ${result.complexity}`);
output(`Fan-in: ${result.fanIn}`);
output(`Fan-out: ${result.fanOut}`);
output(`PageRank: ${result.pageRank}`);
output(`Betweenness:${result.betweenness}`);
if (result.callers.length > 0) {
output(``);
output(`Callers (${result.callers.length}):`);
for (const c of result.callers) {
output(` ${c.symbol} (${c.file}) [${c.confidence}]`);
}
}
if (result.callees.length > 0) {
output(``);
output(`Callees (${result.callees.length}):`);
for (const c of result.callees) {
output(` ${c.symbol} (${c.file}) [${c.confidence}]`);
}
}
});
// ── Subcommand: impact ─────────────────────────────────────
program
.command("impact")
.description("Symbol-level blast radius with depth-grouped impact levels")
.argument("<path>", "Path to TypeScript codebase")
.argument("<symbol>", "Symbol name (e.g., 'getUserById')")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, symbol: string, options: CliCommandOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const result = impactAnalysis(graph, symbol);
if (result.notFound) {
process.stderr.write(`Error: Symbol not found: ${symbol}\n`);
process.exit(1);
}
if (options.json) {
outputJson(result);
return;
}
output(`Impact Analysis: ${symbol}`);
output("─".repeat(18 + symbol.length));
output(`Total affected: ${result.totalAffected}`);
if (result.levels.length > 0) {
output(``);
for (const level of result.levels) {
output(`Depth ${level.depth} — ${level.risk} (${level.affected.length}):`);
for (const a of level.affected) {
output(` ${a.symbol} (${a.file}) [${a.confidence}]`);
}
}
}
});
// ── Subcommand: rename ─────────────────────────────────────
program
.command("rename")
.description("Find all references for rename planning (read-only)")
.argument("<path>", "Path to TypeScript codebase")
.argument("<oldName>", "Current symbol name")
.argument("<newName>", "New symbol name")
.option("--no-dry-run", "Actually perform the rename (default: dry run)")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, oldName: string, newName: string, options: RenameOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const dryRun = options.dryRun !== false;
const result = renameSymbol(graph, oldName, newName, dryRun);
if (options.json) {
outputJson(result);
return;
}
output(`Rename: ${oldName} → ${newName}${dryRun ? " (dry run)" : ""}`);
output("─".repeat(40));
if (result.references.length === 0) {
output(`No references found for "${oldName}"`);
return;
}
output(`References (${result.references.length}):`);
for (const ref of result.references) {
output(` ${ref.file} [${ref.confidence}] ${ref.symbol}`);
}
});
// ── Subcommand: processes ──────────────────────────────────
program
.command("processes")
.description("Entry point execution flows through the call graph")
.argument("<path>", "Path to TypeScript codebase")
.option("--entry <name>", "Filter by entry point name")
.option("--limit <n>", "Max processes to return")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, options: ProcessesOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const limit = options.limit ? parseInt(options.limit, 10) : undefined;
if (limit !== undefined && (isNaN(limit) || limit < 1)) {
process.stderr.write("Error: --limit must be a positive integer\n");
process.exit(2);
}
const result = computeProcesses(graph, options.entry, limit);
if (options.json) {
outputJson(result);
return;
}
output(`Processes (${result.processes.length} of ${result.totalProcesses})`);
output("─".repeat(30));
if (result.processes.length === 0) {
output(`No processes found.`);
return;
}
for (const p of result.processes) {
output(``);
output(`${p.name} (depth: ${p.depth}, modules: ${p.modulesTouched.join(", ")})`);
output(` Entry: ${p.entryPoint.file}::${p.entryPoint.symbol}`);
for (const s of p.steps) {
output(` ${String(s.step).padStart(3)}. ${s.file}::${s.symbol}`);
}
}
});
// ── Subcommand: clusters ───────────────────────────────────
program
.command("clusters")
.description("Community-detected file clusters (Louvain algorithm)")
.argument("<path>", "Path to TypeScript codebase")
.option("--min-files <n>", "Min files per cluster (default: 0)")
.option("--json", "Output as JSON")
.option("--force", "Re-index even if HEAD unchanged")
.action((targetPath: string, options: ClustersOptions) => {
const { graph } = loadGraph(targetPath, options.force);
const minFiles = options.minFiles ? parseInt(options.minFiles, 10) : undefined;
if (minFiles !== undefined && (isNaN(minFiles) || minFiles < 1)) {
process.stderr.write("Error: --min-files must be a positive integer\n");
process.exit(2);
}
const result = computeClusters(graph, minFiles);
if (options.json) {
outputJson(result);
return;
}
output(`Clusters (${result.clusters.length} of ${result.totalClusters})`);
output("─".repeat(30));
for (const c of result.clusters) {
output(``);
output(`${c.name} (${c.fileCount} files, cohesion: ${c.cohesion.toFixed(2)})`);
for (const f of c.files) {
output(` ${f}`);
}
}
});
// ── Subcommand: init ───────────────────────────────────────
program
.command("init")
.description("Set up AI agents to use codebase-intelligence: write per-agent instruction files (+ optional skill)")
.argument("[path]", "Repo root (default: current directory)", ".")
.option("--agents <list>", `Comma-separated agents, non-interactive. Available: ${ALL_AGENT_IDS.join(", ")}`)
.option("--all", "Target every agent (non-interactive)")
.option("--skill", "Also install the global Claude skill (opt-in)")
.option("-y, --yes", "Accept defaults without prompting")
.option("--json", "Output as JSON (implies non-interactive)")
.action(async (targetPath: string, options: InitOptions) => {
const resolved = path.resolve(targetPath);
if (!fs.existsSync(resolved)) {
process.stderr.write(`Error: Path does not exist: ${targetPath}\n`);
process.exit(1);
}
const isTty = process.stdin.isTTY && process.stdout.isTTY;
const plan = resolveInitPlan(options, isTty);
if (plan.invalidAgents.length > 0) {
process.stderr.write(
`Error: Unknown agents: ${plan.invalidAgents.join(", ")}. Available: ${ALL_AGENT_IDS.join(", ")}\n`,
);
process.exit(2);
}
let agents = plan.agents;
let installSkill = plan.installSkill;
if (plan.mode === "interactive") {
const selection = await promptSelection(agents, installSkill);
if (!selection) {
output("Cancelled — nothing written.");
return;
}
agents = selection.agents;
installSkill = selection.skill;
}
if (agents.length === 0 && !installSkill) {
output("Nothing selected — nothing to do.");
return;
}
const repoResults = installRepoFiles(resolved, { agents });
const skillResult = installSkill ? installGlobalSkill() : undefined;
if (options.json) {
outputJson({ repoFiles: repoResults, skill: skillResult ?? null });
return;
}