-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcli.js
More file actions
609 lines (566 loc) · 22.5 KB
/
cli.js
File metadata and controls
609 lines (566 loc) · 22.5 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
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import { Command } from 'commander';
import { buildGraph } from './builder.js';
import { loadConfig } from './config.js';
import { findCycles, formatCycles } from './cycles.js';
import { openReadonlyOrFail } from './db.js';
import {
buildEmbeddings,
DEFAULT_MODEL,
EMBEDDING_STRATEGIES,
MODELS,
search,
} from './embedder.js';
import { exportDOT, exportJSON, exportMermaid } from './export.js';
import { setVerbose } from './logger.js';
import {
ALL_SYMBOL_KINDS,
context,
diffImpact,
explain,
fileDeps,
fnDeps,
fnImpact,
impactAnalysis,
moduleMap,
queryName,
roles,
stats,
VALID_ROLES,
where,
} from './queries.js';
import {
listRepos,
pruneRegistry,
REGISTRY_PATH,
registerRepo,
unregisterRepo,
} from './registry.js';
import { watchProject } from './watcher.js';
const __cliDir = path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/i, '$1'));
const pkg = JSON.parse(fs.readFileSync(path.join(__cliDir, '..', 'package.json'), 'utf-8'));
const config = loadConfig(process.cwd());
const program = new Command();
program
.name('codegraph')
.description('Local code dependency graph tool')
.version(pkg.version)
.option('-v, --verbose', 'Enable verbose/debug output')
.option('--engine <engine>', 'Parser engine: native, wasm, or auto (default: auto)', 'auto')
.hook('preAction', (thisCommand) => {
const opts = thisCommand.opts();
if (opts.verbose) setVerbose(true);
});
/**
* Resolve the effective noTests value: CLI flag > config > false.
* Commander sets opts.tests to false when --no-tests is passed.
* When --include-tests is passed, always return false (include tests).
* Otherwise, fall back to config.query.excludeTests.
*/
function resolveNoTests(opts) {
if (opts.includeTests) return false;
if (opts.tests === false) return true;
return config.query?.excludeTests || false;
}
program
.command('build [dir]')
.description('Parse repo and build graph in .codegraph/graph.db')
.option('--no-incremental', 'Force full rebuild (ignore file hashes)')
.action(async (dir, opts) => {
const root = path.resolve(dir || '.');
const engine = program.opts().engine;
await buildGraph(root, { incremental: opts.incremental, engine });
});
program
.command('query <name>')
.description('Find a function/class, show callers and callees')
.option('-d, --db <path>', 'Path to graph.db')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((name, opts) => {
queryName(name, opts.db, { noTests: resolveNoTests(opts), json: opts.json });
});
program
.command('impact <file>')
.description('Show what depends on this file (transitive)')
.option('-d, --db <path>', 'Path to graph.db')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((file, opts) => {
impactAnalysis(file, opts.db, { noTests: resolveNoTests(opts), json: opts.json });
});
program
.command('map')
.description('High-level module overview with most-connected nodes')
.option('-d, --db <path>', 'Path to graph.db')
.option('-n, --limit <number>', 'Number of top nodes', '20')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((opts) => {
moduleMap(opts.db, parseInt(opts.limit, 10), {
noTests: resolveNoTests(opts),
json: opts.json,
});
});
program
.command('stats')
.description('Show graph health overview: nodes, edges, languages, cycles, hotspots, embeddings')
.option('-d, --db <path>', 'Path to graph.db')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((opts) => {
stats(opts.db, { noTests: resolveNoTests(opts), json: opts.json });
});
program
.command('deps <file>')
.description('Show what this file imports and what imports it')
.option('-d, --db <path>', 'Path to graph.db')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((file, opts) => {
fileDeps(file, opts.db, { noTests: resolveNoTests(opts), json: opts.json });
});
program
.command('fn <name>')
.description('Function-level dependencies: callers, callees, and transitive call chain')
.option('-d, --db <path>', 'Path to graph.db')
.option('--depth <n>', 'Transitive caller depth', '3')
.option('-f, --file <path>', 'Scope search to functions in this file (partial match)')
.option('-k, --kind <kind>', 'Filter to a specific symbol kind')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((name, opts) => {
if (opts.kind && !ALL_SYMBOL_KINDS.includes(opts.kind)) {
console.error(`Invalid kind "${opts.kind}". Valid: ${ALL_SYMBOL_KINDS.join(', ')}`);
process.exit(1);
}
fnDeps(name, opts.db, {
depth: parseInt(opts.depth, 10),
file: opts.file,
kind: opts.kind,
noTests: resolveNoTests(opts),
json: opts.json,
});
});
program
.command('fn-impact <name>')
.description('Function-level impact: what functions break if this one changes')
.option('-d, --db <path>', 'Path to graph.db')
.option('--depth <n>', 'Max transitive depth', '5')
.option('-f, --file <path>', 'Scope search to functions in this file (partial match)')
.option('-k, --kind <kind>', 'Filter to a specific symbol kind')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((name, opts) => {
if (opts.kind && !ALL_SYMBOL_KINDS.includes(opts.kind)) {
console.error(`Invalid kind "${opts.kind}". Valid: ${ALL_SYMBOL_KINDS.join(', ')}`);
process.exit(1);
}
fnImpact(name, opts.db, {
depth: parseInt(opts.depth, 10),
file: opts.file,
kind: opts.kind,
noTests: resolveNoTests(opts),
json: opts.json,
});
});
program
.command('context <name>')
.description('Full context for a function: source, deps, callers, tests, signature')
.option('-d, --db <path>', 'Path to graph.db')
.option('--depth <n>', 'Include callee source up to N levels deep', '0')
.option('-f, --file <path>', 'Scope search to functions in this file (partial match)')
.option('-k, --kind <kind>', 'Filter to a specific symbol kind')
.option('--no-source', 'Metadata only (skip source extraction)')
.option('--with-test-source', 'Include test source code')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((name, opts) => {
if (opts.kind && !ALL_SYMBOL_KINDS.includes(opts.kind)) {
console.error(`Invalid kind "${opts.kind}". Valid: ${ALL_SYMBOL_KINDS.join(', ')}`);
process.exit(1);
}
context(name, opts.db, {
depth: parseInt(opts.depth, 10),
file: opts.file,
kind: opts.kind,
noSource: !opts.source,
noTests: resolveNoTests(opts),
includeTests: opts.withTestSource,
json: opts.json,
});
});
program
.command('explain <target>')
.description('Structural summary of a file or function (no LLM needed)')
.option('-d, --db <path>', 'Path to graph.db')
.option('--depth <n>', 'Recursively explain dependencies up to N levels deep', '0')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((target, opts) => {
explain(target, opts.db, {
depth: parseInt(opts.depth, 10),
noTests: resolveNoTests(opts),
json: opts.json,
});
});
program
.command('where [name]')
.description('Find where a symbol is defined and used (minimal, fast lookup)')
.option('-d, --db <path>', 'Path to graph.db')
.option('-f, --file <path>', 'File overview: list symbols, imports, exports')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((name, opts) => {
if (!name && !opts.file) {
console.error('Provide a symbol name or use --file <path>');
process.exit(1);
}
const target = opts.file || name;
where(target, opts.db, { file: !!opts.file, noTests: resolveNoTests(opts), json: opts.json });
});
program
.command('diff-impact [ref]')
.description('Show impact of git changes (unstaged, staged, or vs a ref)')
.option('-d, --db <path>', 'Path to graph.db')
.option('--staged', 'Analyze staged changes instead of unstaged')
.option('--depth <n>', 'Max transitive caller depth', '3')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.option('-f, --format <format>', 'Output format: text, mermaid, json', 'text')
.action((ref, opts) => {
diffImpact(opts.db, {
ref,
staged: opts.staged,
depth: parseInt(opts.depth, 10),
noTests: resolveNoTests(opts),
json: opts.json,
format: opts.format,
});
});
// ─── New commands ────────────────────────────────────────────────────────
program
.command('export')
.description('Export dependency graph as DOT (Graphviz), Mermaid, or JSON')
.option('-d, --db <path>', 'Path to graph.db')
.option('-f, --format <format>', 'Output format: dot, mermaid, json', 'dot')
.option('--functions', 'Function-level graph instead of file-level')
.option('-T, --no-tests', 'Exclude test/spec files')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('--min-confidence <score>', 'Minimum edge confidence threshold (default: 0.5)', '0.5')
.option('-o, --output <file>', 'Write to file instead of stdout')
.action((opts) => {
const db = openReadonlyOrFail(opts.db);
const exportOpts = {
fileLevel: !opts.functions,
noTests: resolveNoTests(opts),
minConfidence: parseFloat(opts.minConfidence),
};
let output;
switch (opts.format) {
case 'mermaid':
output = exportMermaid(db, exportOpts);
break;
case 'json':
output = JSON.stringify(exportJSON(db, exportOpts), null, 2);
break;
default:
output = exportDOT(db, exportOpts);
break;
}
db.close();
if (opts.output) {
fs.writeFileSync(opts.output, output, 'utf-8');
console.log(`Exported ${opts.format} to ${opts.output}`);
} else {
console.log(output);
}
});
program
.command('cycles')
.description('Detect circular dependencies in the codebase')
.option('-d, --db <path>', 'Path to graph.db')
.option('--functions', 'Function-level cycle detection')
.option('-T, --no-tests', 'Exclude test/spec files')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((opts) => {
const db = openReadonlyOrFail(opts.db);
const cycles = findCycles(db, { fileLevel: !opts.functions, noTests: resolveNoTests(opts) });
db.close();
if (opts.json) {
console.log(JSON.stringify({ cycles, count: cycles.length }, null, 2));
} else {
console.log(formatCycles(cycles));
}
});
program
.command('mcp')
.description('Start MCP (Model Context Protocol) server for AI assistant integration')
.option('-d, --db <path>', 'Path to graph.db')
.option('--multi-repo', 'Enable access to all registered repositories')
.option('--repos <names>', 'Comma-separated list of allowed repo names (restricts access)')
.action(async (opts) => {
const { startMCPServer } = await import('./mcp.js');
const mcpOpts = {};
mcpOpts.multiRepo = opts.multiRepo || !!opts.repos;
if (opts.repos) {
mcpOpts.allowedRepos = opts.repos.split(',').map((s) => s.trim());
}
await startMCPServer(opts.db, mcpOpts);
});
// ─── Registry commands ──────────────────────────────────────────────────
const registry = program.command('registry').description('Manage the multi-repo project registry');
registry
.command('list')
.description('List all registered repositories')
.option('-j, --json', 'Output as JSON')
.action((opts) => {
pruneRegistry();
const repos = listRepos();
if (opts.json) {
console.log(JSON.stringify(repos, null, 2));
} else if (repos.length === 0) {
console.log(`No repositories registered.\nRegistry: ${REGISTRY_PATH}`);
} else {
console.log(`Registered repositories (${REGISTRY_PATH}):\n`);
for (const r of repos) {
const dbExists = fs.existsSync(r.dbPath);
const status = dbExists ? '' : ' [DB missing]';
console.log(` ${r.name}${status}`);
console.log(` Path: ${r.path}`);
console.log(` DB: ${r.dbPath}`);
console.log();
}
}
});
registry
.command('add <dir>')
.description('Register a project directory')
.option('-n, --name <name>', 'Custom name (defaults to directory basename)')
.action((dir, opts) => {
const absDir = path.resolve(dir);
const { name, entry } = registerRepo(absDir, opts.name);
console.log(`Registered "${name}" → ${entry.path}`);
});
registry
.command('remove <name>')
.description('Unregister a repository by name')
.action((name) => {
const removed = unregisterRepo(name);
if (removed) {
console.log(`Removed "${name}" from registry.`);
} else {
console.error(`Repository "${name}" not found in registry.`);
process.exit(1);
}
});
registry
.command('prune')
.description('Remove stale registry entries (missing directories or idle beyond TTL)')
.option('--ttl <days>', 'Days of inactivity before pruning (default: 30)', '30')
.option('--exclude <names>', 'Comma-separated repo names to preserve from pruning')
.action((opts) => {
const excludeNames = opts.exclude
? opts.exclude
.split(',')
.map((s) => s.trim())
.filter((s) => s.length > 0)
: [];
const pruned = pruneRegistry(undefined, parseInt(opts.ttl, 10), excludeNames);
if (pruned.length === 0) {
console.log('No stale entries found.');
} else {
for (const entry of pruned) {
const tag = entry.reason === 'expired' ? 'expired' : 'missing';
console.log(`Pruned "${entry.name}" (${entry.path}) [${tag}]`);
}
console.log(`\nRemoved ${pruned.length} stale ${pruned.length === 1 ? 'entry' : 'entries'}.`);
}
});
// ─── Embedding commands ─────────────────────────────────────────────────
program
.command('models')
.description('List available embedding models')
.action(() => {
const defaultModel = config.embeddings?.model || DEFAULT_MODEL;
console.log('\nAvailable embedding models:\n');
for (const [key, cfg] of Object.entries(MODELS)) {
const def = key === defaultModel ? ' (default)' : '';
const ctx = cfg.contextWindow ? `${cfg.contextWindow} ctx` : '';
console.log(
` ${key.padEnd(12)} ${String(cfg.dim).padStart(4)}d ${ctx.padEnd(9)} ${cfg.desc}${def}`,
);
}
console.log('\nUsage: codegraph embed --model <name> --strategy <structured|source>');
console.log(' codegraph search "query" --model <name>\n');
});
program
.command('embed [dir]')
.description(
'Build semantic embeddings for all functions/methods/classes (requires prior `build`)',
)
.option(
'-m, --model <name>',
'Embedding model (default from config or minilm). Run `codegraph models` for details',
)
.option(
'-s, --strategy <name>',
`Embedding strategy: ${EMBEDDING_STRATEGIES.join(', ')}. "structured" uses graph context (callers/callees), "source" embeds raw code`,
'structured',
)
.action(async (dir, opts) => {
if (!EMBEDDING_STRATEGIES.includes(opts.strategy)) {
console.error(
`Unknown strategy: ${opts.strategy}. Available: ${EMBEDDING_STRATEGIES.join(', ')}`,
);
process.exit(1);
}
const root = path.resolve(dir || '.');
const model = opts.model || config.embeddings?.model || DEFAULT_MODEL;
await buildEmbeddings(root, model, undefined, { strategy: opts.strategy });
});
program
.command('search <query>')
.description('Semantic search: find functions by natural language description')
.option('-d, --db <path>', 'Path to graph.db')
.option('-m, --model <name>', 'Override embedding model (auto-detects from DB)')
.option('-n, --limit <number>', 'Max results', '15')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('--min-score <score>', 'Minimum similarity threshold', '0.2')
.option('-k, --kind <kind>', 'Filter by kind: function, method, class')
.option('--file <pattern>', 'Filter by file path pattern')
.option('--rrf-k <number>', 'RRF k parameter for multi-query ranking', '60')
.option('-j, --json', 'Output as JSON')
.action(async (query, opts) => {
await search(query, opts.db, {
limit: parseInt(opts.limit, 10),
noTests: resolveNoTests(opts),
minScore: parseFloat(opts.minScore),
model: opts.model,
kind: opts.kind,
filePattern: opts.file,
rrfK: parseInt(opts.rrfK, 10),
json: opts.json,
});
});
program
.command('structure [dir]')
.description(
'Show project directory structure with hierarchy, cohesion scores, and per-file metrics',
)
.option('-d, --db <path>', 'Path to graph.db')
.option('--depth <n>', 'Max directory depth')
.option('--sort <metric>', 'Sort by: cohesion | fan-in | fan-out | density | files', 'files')
.option('-T, --no-tests', 'Exclude test/spec files')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action(async (dir, opts) => {
const { structureData, formatStructure } = await import('./structure.js');
const data = structureData(opts.db, {
directory: dir,
depth: opts.depth ? parseInt(opts.depth, 10) : undefined,
sort: opts.sort,
noTests: resolveNoTests(opts),
});
if (opts.json) {
console.log(JSON.stringify(data, null, 2));
} else {
console.log(formatStructure(data));
}
});
program
.command('hotspots')
.description(
'Find structural hotspots: files or directories with extreme fan-in, fan-out, or symbol density',
)
.option('-d, --db <path>', 'Path to graph.db')
.option('-n, --limit <number>', 'Number of results', '10')
.option('--metric <metric>', 'fan-in | fan-out | density | coupling', 'fan-in')
.option('--level <level>', 'file | directory', 'file')
.option('-T, --no-tests', 'Exclude test/spec files from results')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action(async (opts) => {
const { hotspotsData, formatHotspots } = await import('./structure.js');
const data = hotspotsData(opts.db, {
metric: opts.metric,
level: opts.level,
limit: parseInt(opts.limit, 10),
noTests: resolveNoTests(opts),
});
if (opts.json) {
console.log(JSON.stringify(data, null, 2));
} else {
console.log(formatHotspots(data));
}
});
program
.command('roles')
.description('Show node role classification: entry, core, utility, adapter, dead, leaf')
.option('-d, --db <path>', 'Path to graph.db')
.option('--role <role>', `Filter by role (${VALID_ROLES.join(', ')})`)
.option('-f, --file <path>', 'Scope to a specific file (partial match)')
.option('-T, --no-tests', 'Exclude test/spec files')
.option('--include-tests', 'Include test/spec files (overrides excludeTests config)')
.option('-j, --json', 'Output as JSON')
.action((opts) => {
if (opts.role && !VALID_ROLES.includes(opts.role)) {
console.error(`Invalid role "${opts.role}". Valid roles: ${VALID_ROLES.join(', ')}`);
process.exit(1);
}
roles(opts.db, {
role: opts.role,
file: opts.file,
noTests: resolveNoTests(opts),
json: opts.json,
});
});
program
.command('watch [dir]')
.description('Watch project for file changes and incrementally update the graph')
.action(async (dir) => {
const root = path.resolve(dir || '.');
const engine = program.opts().engine;
await watchProject(root, { engine });
});
program
.command('info')
.description('Show codegraph engine info and diagnostics')
.action(async () => {
const { isNativeAvailable, loadNative } = await import('./native.js');
const { getActiveEngine } = await import('./parser.js');
const engine = program.opts().engine;
const { name: activeName, version: activeVersion } = getActiveEngine({ engine });
const nativeAvailable = isNativeAvailable();
console.log('\nCodegraph Diagnostics');
console.log('====================');
console.log(` Version : ${program.version()}`);
console.log(` Node.js : ${process.version}`);
console.log(` Platform : ${process.platform}-${process.arch}`);
console.log(` Native engine : ${nativeAvailable ? 'available' : 'unavailable'}`);
if (nativeAvailable) {
const native = loadNative();
const nativeVersion =
typeof native.engineVersion === 'function' ? native.engineVersion() : 'unknown';
console.log(` Native version: ${nativeVersion}`);
}
console.log(` Engine flag : --engine ${engine}`);
console.log(` Active engine : ${activeName}${activeVersion ? ` (v${activeVersion})` : ''}`);
console.log();
});
program.parse();