-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
1130 lines (1079 loc) · 49.9 KB
/
Copy pathindex.ts
File metadata and controls
1130 lines (1079 loc) · 49.9 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
/**
* `codehub` CLI entrypoint.
*
* Every subcommand is loaded lazily via `await import(...)` so that
* `codehub --help` (and `codehub <command> --help`) stays fast: no native storage engine
* native binding, no pipeline, no MCP SDK unless we are actually going to
* run that subcommand.
*/
import { readFileSync } from "node:fs";
import { cpus } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
// Silence the one-shot node:sqlite ExperimentalWarning before any subcommand
// lazily loads the storage layer. This module is dependency-free (no native
// binding), so importing it eagerly does not regress `--help` startup cost.
import { installSqliteRuntimeGuard } from "@opencodehub/storage/sqlite-runtime";
import { Command } from "commander";
installSqliteRuntimeGuard();
// Read the CLI's own version from its package.json. The bin entry is always
// emitted at <pkg-root>/dist/index.js in every layout (the tsup collapse keeps
// `index` at the dist root), so package.json is exactly one level up. This
// single `..` is layout-stable precisely because index.js never moves; the
// asset resolvers that DID move use the walk-up probe in ./asset-resolver.ts.
const pkgJsonPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
const pkgVersion = JSON.parse(readFileSync(pkgJsonPath, "utf8")).version as string;
// `OCH_NATIVE_PARSER` was removed in 0.4.0 with the WASM-only parser
// migration. If a stale shell or .envrc still sets it, emit a one-shot
// advisory and clear it so it doesn't leak into spawned worker processes
// (some of which may still inspect `process.env`).
if (process.env["OCH_NATIVE_PARSER"] !== undefined) {
process.stderr.write(
"[codehub] OCH_NATIVE_PARSER was removed in 0.4.0; WASM is the only parser runtime. Unset to silence this warning.\n",
);
delete process.env["OCH_NATIVE_PARSER"];
}
const program = new Command()
.name("codehub")
.version(pkgVersion)
.description("OpenCodeHub — code-graph indexer and MCP server for coding agents");
program
.command("analyze [path]")
.description("Index a repository at [path] (default: current directory)")
.option("--force", "Ignore registry cache and re-run the pipeline")
.option("--embeddings", "Embed symbols and populate the embeddings table in store.sqlite")
.option("--embeddings-int8", "Use the int8 embedder variant (~23 MB) instead of fp32")
.option(
"--granularity <csv>",
"Hierarchical embedding tiers to emit, comma-separated. Values: symbol, file, community. Default: symbol. Example: --granularity symbol,file,community",
)
.option(
"--embeddings-workers <n|auto>",
'Parallel ONNX embedder workers (each ~300 MB RSS on fp32). "auto" = os.cpus().length - 1, min 1. Default: "auto" when --embeddings is on (was 1 until 2026-04-27; single-threaded ONNX inference on a 100k-node repo took ~45 min, so CLI now opts into parallel by default). Pass --embeddings-workers 1 for the legacy in-process path.',
)
.option(
"--embeddings-batch-size <n>",
"Chunks per embedBatch() call. Default 32. Set to 1 to restore the legacy one-node-per-call pattern.",
)
.option("--offline", "Assert no network access during analyze")
.option("--verbose", "Emit per-phase pipeline progress")
.option("--skip-agents-md", "Do not write the AGENTS.md / CLAUDE.md stanza")
.option(
"--sbom",
"Emit .codehub/sbom.cyclonedx.json + .codehub/sbom.spdx.json from Dependency nodes. Default ON — use --no-sbom to suppress.",
)
.option("--no-sbom", "Suppress SBOM emission. Equivalent to omitting `sbom: true`.")
.option(
"--coverage",
"Force the coverage overlay phase on and warn when no report is found. Default AUTO — `codehub analyze` auto-detects lcov/cobertura/jacoco/coverage.py reports and silently skips when none exist.",
)
.option("--no-coverage", "Force the coverage overlay phase off even when a report is present.")
.option(
"--scan",
"Run Priority-1 scanners after analyze, write .codehub/scan.sarif, and ingest findings into the graph. Default ON — use --no-scan to suppress.",
)
.option(
"--no-scan",
"Skip the post-analyze scan step. The graph pipeline runs unchanged; `codehub verdict` / `list_findings` work against the last SARIF on disk.",
)
.option(
"--summaries",
"Opt into the summarize phase (structured Bedrock summaries per callable). Default OFF — `codehub analyze` is fast, local, deterministic by default. Also enabled by CODEHUB_BEDROCK_SUMMARIES=1.",
)
.option(
"--no-summaries",
"Explicitly disable the summarize phase (equivalent to CODEHUB_BEDROCK_DISABLED=1). Only meaningful when combined with CODEHUB_BEDROCK_SUMMARIES=1.",
)
.option(
"--max-summaries <n|auto>",
'Cap on Bedrock summarize calls per run. "auto" (default) scales the cap to 10% of the SCIP-confirmed callable count (max 500).',
"auto",
)
.option(
"--summary-model <id>",
"Override the Bedrock model id used by the summarize phase (defaults to DEFAULT_MODEL_ID).",
)
.option(
"--skills",
"After analyze, emit one SKILL.md per Community (symbolCount >= 5) under .codehub/skills/",
)
.option(
"--strict-detectors",
"Drop heuristic-only matches from the route / ORM detectors — emit edges only when the receiver's module origin was confirmed (DET-O-001)",
)
.option(
"--allow-build-scripts <list>",
"Comma-separated opt-ins that enable build-script-driven indexers. Current value: `proleap` (JVM COBOL deep-parse). Unset → regex hot path only.",
)
.action(async (path: string | undefined, opts: Record<string, unknown>) => {
const mod = await import("./commands/analyze.js");
// Pass the raw flag straight through to `runAnalyze`. The env
// kill-switch (`CODEHUB_BEDROCK_DISABLED=1`) and the env opt-in
// (`CODEHUB_BEDROCK_SUMMARIES=1`) are re-checked inside `runAnalyze`
// via `resolveSummariesEnabled` so tests that call `runAnalyze`
// directly honor the same truth table. Summaries are OFF by default
// — the fast, local, deterministic analyze path. Pass `--summaries`
// or set `CODEHUB_BEDROCK_SUMMARIES=1` to opt in.
let summaries: boolean | undefined;
if (opts["summaries"] === true) summaries = true;
else if (opts["summaries"] === false) summaries = false;
else summaries = undefined;
// --max-summaries accepts either a positive integer or the literal
// string "auto". Unknown strings fall back to "auto" so the CLI never
// refuses a run over flag syntax.
const rawMax = opts["maxSummaries"];
let maxSummariesPerRun: number | "auto";
if (rawMax === "auto" || rawMax === undefined) {
maxSummariesPerRun = "auto";
} else if (typeof rawMax === "number" && Number.isFinite(rawMax)) {
maxSummariesPerRun = Math.max(0, Math.floor(rawMax));
} else if (typeof rawMax === "string") {
const parsed = Number.parseInt(rawMax, 10);
maxSummariesPerRun = Number.isFinite(parsed) ? Math.max(0, parsed) : "auto";
} else {
maxSummariesPerRun = "auto";
}
const granularity = parseGranularityCsv(opts["granularity"]);
const allowBuildScripts = parseAllowBuildScripts(opts["allowBuildScripts"]);
// When --embeddings is on and the user didn't pick a worker count, default
// to "auto" — single-threaded ONNX inference on 100k+ nodes takes ~45 min
// vs ~6–8 min with all cores busy. Power users can still pass
// `--embeddings-workers 1` for the legacy path.
const workersRaw =
opts["embeddings"] === true && opts["embeddingsWorkers"] === undefined
? "auto"
: opts["embeddingsWorkers"];
const embeddingsWorkers = parseWorkerCount(workersRaw);
const embeddingsBatchSize = parsePositiveInt(opts["embeddingsBatchSize"]);
const analyzeSummary = await mod.runAnalyze(path ?? process.cwd(), {
force: opts["force"] === true,
embeddings: opts["embeddings"] === true,
embeddingsVariant: opts["embeddingsInt8"] === true ? "int8" : "fp32",
...(granularity !== undefined ? { embeddingsGranularity: granularity } : {}),
...(embeddingsWorkers !== undefined ? { embeddingsWorkers } : {}),
...(embeddingsBatchSize !== undefined ? { embeddingsBatchSize } : {}),
offline: opts["offline"] === true,
verbose: opts["verbose"] === true,
skipAgentsMd: opts["skipAgentsMd"] === true,
// `sbom`, `coverage`, `scan` are three-state (true / false / auto).
// commander encodes `--no-sbom` as `opts.sbom === false`, `--sbom` as
// `true`, and omitted as `undefined`. Forward all three verbatim —
// `runAnalyze` reads the resolvers (resolveSbomEnabled / resolveScan-
// Enabled / resolveCoverageEnabled) to pick the effective value.
...(opts["sbom"] === false ? { sbom: false as const } : {}),
...(opts["sbom"] === true ? { sbom: true as const } : {}),
...(opts["coverage"] === false ? { coverage: false as const } : {}),
...(opts["coverage"] === true ? { coverage: true as const } : {}),
...(opts["scan"] === false ? { scan: false as const } : {}),
...(opts["scan"] === true ? { scan: true as const } : {}),
...(summaries !== undefined ? { summaries } : {}),
maxSummariesPerRun,
...(typeof opts["summaryModel"] === "string" ? { summaryModel: opts["summaryModel"] } : {}),
skills: opts["skills"] === true,
strictDetectors: opts["strictDetectors"] === true,
...(allowBuildScripts !== undefined ? { allowBuildScripts } : {}),
});
// Advisory exit code 3: analyze built a graph but extracted zero code
// symbols (likely a broken parser). Distinct from the generic failure
// exit 1 so CI can detect a silent-skeleton run without parsing logs.
if (analyzeSummary.zeroSymbolGuard === true) process.exitCode = 3;
});
program
.command("index [paths...]")
.description(
"Register an existing .codehub/ folder into the registry (no re-analysis). " +
"With no [paths], registers the current directory.",
)
.option("--force", "Stamp a minimal meta.json stub when .codehub/meta.json is missing")
.option("--allow-non-git", "Allow registering folders that are not git repositories")
.action(async (paths: string[] | undefined, opts: Record<string, boolean | undefined>) => {
const mod = await import("./commands/index-repo.js");
await mod.runIndexRepo(paths ?? [], {
force: opts["force"] === true,
allowNonGit: opts["allowNonGit"] === true,
});
});
program
.command("init [path]")
.description(
"Bootstrap a repo for OpenCodeHub — copies the Claude Code plugin assets into .claude/ (project-scope), writes .mcp.json, appends .codehub/ to .gitignore, seeds opencodehub.policy.yaml",
)
.option("--force", "Overwrite conflicting files under .claude/")
.option("--skip-mcp", "Skip writing .mcp.json")
.option("--skip-policy", "Skip seeding opencodehub.policy.yaml")
.action(async (path: string | undefined, opts: Record<string, boolean | undefined>) => {
const mod = await import("./commands/init.js");
const result = await mod.runInit({
...(path !== undefined ? { repo: path } : {}),
force: opts["force"] === true,
skipMcp: opts["skipMcp"] === true,
skipPolicy: opts["skipPolicy"] === true,
});
// One-line recap so the user knows what changed.
const bits: string[] = [`${result.filesCopied} file(s) into .claude/`];
if (result.mcpResult) bits.push(`.mcp.json (${result.mcpResult.action})`);
if (result.gitignoreUpdated) bits.push(".gitignore updated");
if (result.policySeeded) bits.push("opencodehub.policy.yaml seeded");
console.warn(`codehub init: ${bits.join(" · ")}`);
console.warn("Next: run 'codehub analyze' to build the graph, then restart Claude Code.");
});
program
.command("setup")
.description(
"Write MCP config entries for supported editors, download embedder weights, or install SCIP adapter binaries",
)
.option(
"--editors <list>",
"Comma-separated editor ids (claude-code,cursor,codex,windsurf,opencode). Default: all",
)
.option("--force", "Overwrite an existing codehub entry without prompting; re-download weights")
.option("--undo", "Restore the most recent .bak next to each config")
.option("--embeddings", "Download gte-modernbert-base ONNX weights (SHA256-pinned)")
.option("--int8", "Use the int8 weight variant (~150 MB) instead of fp32 (~596 MB)")
.option("--model-dir <path>", "Override the target directory for embedder weights")
.option("--plugin", "Install the Claude Code plugin to ~/.claude/plugins/opencodehub/")
.option(
"--scip <tool>",
"Install an external SCIP adapter binary (clang|ruby|dotnet|kotlin) or 'all'. SHA256-pinned; dotnet requires .NET SDK 8+ on PATH",
)
.option(
"--cobol-proleap",
"Build the uwol/cobol-parser library from source (git clone + mvn install) and compile the bridge wrapper. Requires git, mvn, JDK 17+ on PATH. Installs under ~/.codehub/vendor/proleap/",
)
.action(async (opts: Record<string, string | boolean | undefined>) => {
const mod = await import("./commands/setup.js");
if (opts["plugin"] === true) {
await mod.runSetupPlugin({});
return;
}
if (opts["cobolProleap"] === true) {
await mod.runSetupCobolProleap({
force: opts["force"] === true,
});
return;
}
if (typeof opts["scip"] === "string") {
const tool = mod.parseScipFlag(opts["scip"]);
await mod.runSetupScip({
tool,
force: opts["force"] === true,
});
return;
}
if (opts["embeddings"] === true) {
const modelDir = typeof opts["modelDir"] === "string" ? opts["modelDir"] : undefined;
await mod.runSetupEmbeddings({
variant: opts["int8"] === true ? "int8" : "fp32",
...(modelDir !== undefined ? { modelDir } : {}),
force: opts["force"] === true,
});
return;
}
const editors = typeof opts["editors"] === "string" ? parseEditors(opts["editors"]) : undefined;
await mod.runSetup({
...(editors !== undefined ? { editors } : {}),
force: opts["force"] === true,
undo: opts["undo"] === true,
});
});
program
.command("mcp")
.description("Launch the codehub stdio MCP server")
.action(async () => {
const mod = await import("./commands/mcp.js");
await mod.runMcp();
});
program
.command("list")
.description("List all repos indexed on this machine")
.action(async () => {
const mod = await import("./commands/list.js");
await mod.runList();
});
program
.command("status [path]")
.description("Show index metadata for [path] (default: current directory)")
.action(async (path: string | undefined) => {
const mod = await import("./commands/status.js");
await mod.runStatus(path ?? process.cwd());
});
program
.command("clean [path]")
.description("Delete the index at [path]. --all deletes every registered index.")
.option("--all", "Delete every registered index")
.action(async (path: string | undefined, opts: Record<string, boolean>) => {
const mod = await import("./commands/clean.js");
await mod.runClean(path ?? process.cwd(), { all: opts["all"] === true });
});
program
.command("pack [path]")
.description("Produce a single-file LLM-ready snapshot of the repo via repomix (AST-compressed).")
.option("--style <style>", "Output style: xml|markdown|json|plain", "xml")
.option("--no-compress", "Disable tree-sitter AST compression (keeps full source)")
.option("--remove-comments", "Strip comments from the packed output")
.option("--out <path>", "Custom output path (default: <repo>/.codehub/pack/repo.<ext>)")
.action(async (path: string | undefined, opts: Record<string, unknown>) => {
const mod = await import("./commands/pack.js");
const style = opts["style"] as "xml" | "markdown" | "json" | "plain" | undefined;
const result = await mod.runPack(path ?? process.cwd(), {
...(style !== undefined ? { style } : {}),
compress: opts["compress"] !== false,
removeComments: opts["removeComments"] === true,
...(typeof opts["out"] === "string" ? { outputPath: opts["out"] as string } : {}),
});
console.warn(
`codehub pack: wrote ${result.bytes} bytes to ${result.outputPath} in ${result.durationMs}ms`,
);
});
program
.command("code-pack [path]")
.description(
"Produce the deterministic 8-item code-pack BOM (manifest + skeleton + file-tree + deps + " +
"ast-chunks + xrefs + findings + licenses) plus a readme at " +
"<repo>/.codehub/packs/<packHash>/. Default engine is the new @opencodehub/pack BOM; " +
"--engine repomix opts into the legacy single-file snapshot (drop deferred to M7).",
)
.option("--budget <n>", "AST-chunker token budget (default 100000)", (v) =>
Number.parseInt(v, 10),
)
.option(
"--tokenizer <id>",
'Tokenizer pin "<vendor>:<name>@<pin>" (default openai:o200k_base@tiktoken-0.8.0)',
)
.option(
"--out-dir <dir>",
"Override the .codehub/packs/<packHash>/ default output directory (the directory still " +
"contains the manifest + BOM bodies; supplying this flag lets you put the artifacts " +
"under a non-standard path, e.g. /tmp/my-pack)",
)
.option(
"--engine <engine>",
"Engine: pack (default — 8-item BOM via @opencodehub/pack) or repomix (legacy single-file)",
"pack",
)
.action(async (path: string | undefined, opts: Record<string, unknown>) => {
const mod = await import("./commands/code-pack.js");
const rawEngine = typeof opts["engine"] === "string" ? opts["engine"] : "pack";
const engine: "pack" | "repomix" =
rawEngine === "repomix" ? "repomix" : rawEngine === "pack" ? "pack" : "pack";
if (rawEngine !== engine && rawEngine !== "pack") {
throw new Error(`Unknown --engine value: "${rawEngine}". Expected one of: pack, repomix`);
}
const budget =
typeof opts["budget"] === "number" && Number.isFinite(opts["budget"])
? opts["budget"]
: undefined;
const result = await mod.runCodePack({
...(path !== undefined ? { repo: path } : {}),
...(budget !== undefined ? { budget } : {}),
...(typeof opts["tokenizer"] === "string" ? { tokenizer: opts["tokenizer"] } : {}),
...(typeof opts["outDir"] === "string" ? { outDir: opts["outDir"] } : {}),
engine,
});
if (result.engine === "pack") {
console.warn(
`codehub code-pack: wrote ${result.bomItemCount} BOM items to ${result.outDir} ` +
`(packHash=${result.packHash.slice(0, 12)})`,
);
} else {
console.warn(
`codehub code-pack: wrote repomix snapshot to ${result.repomixOutputPath ?? result.outDir} ` +
`(packHash=${result.packHash.slice(0, 12)})`,
);
}
});
program
.command("query <text>")
.description("Direct hybrid search against a repo's graph")
.option("--limit <n>", "Max results", (v) => Number.parseInt(v, 10), 10)
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--json", "Emit JSON on stdout")
.option("--content", "Attach full symbol source to each hit (capped at 2000 chars)")
.option(
"--context <text>",
"What you are working on — prefixed to the query text to steer ranking",
)
.option("--goal <text>", "What you want to find — prefixed alongside --context to steer ranking")
.option("--max-symbols <n>", "Max symbols in process-grouped output (default 50)", (v) =>
Number.parseInt(v, 10),
)
.option("--bm25-only", "Skip the embedder probe and run BM25 search only")
.option("--rerank-top-k <n>", "RRF top-k passed to hybrid fusion (default 50)", (v) =>
Number.parseInt(v, 10),
)
.option(
"--zoom",
"Enable coarse-to-fine retrieval (file tier → symbol tier). Requires an embedder and a hierarchical index (see `analyze --granularity symbol,file,community`).",
)
.option("--fanout <n>", "Files to shortlist at the coarse step when --zoom is on", (v) =>
Number.parseInt(v, 10),
)
.option(
"--granularity <tier>",
"Restrict ANN to one hierarchical tier: symbol (default), file, or community",
)
.option(
"--force-backend-mismatch",
"Bypass the embedder fingerprint check. Lets a query run when the persisted embedder model_id differs from the current one. Vectors may be stale.",
)
.action(async (text: string, opts: Record<string, unknown>) => {
const mod = await import("./commands/query.js");
const granularity = parseQueryGranularity(opts["granularity"]);
await mod.runQuery(text, {
limit: typeof opts["limit"] === "number" ? opts["limit"] : 10,
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
json: opts["json"] === true,
content: opts["content"] === true,
...(typeof opts["context"] === "string" ? { context: opts["context"] } : {}),
...(typeof opts["goal"] === "string" ? { goal: opts["goal"] } : {}),
...(typeof opts["maxSymbols"] === "number" ? { maxSymbols: opts["maxSymbols"] } : {}),
bm25Only: opts["bm25Only"] === true,
...(typeof opts["rerankTopK"] === "number" ? { rerankTopK: opts["rerankTopK"] } : {}),
zoom: opts["zoom"] === true,
...(typeof opts["fanout"] === "number" ? { fanout: opts["fanout"] } : {}),
...(granularity !== undefined ? { granularity } : {}),
forceBackendMismatch: opts["forceBackendMismatch"] === true,
});
});
program
.command("context <symbol>")
.description("360° view of a symbol (callers, callees, flows)")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--json", "Emit JSON on stdout")
.option(
"--target-uid <id>",
"Exact node id from a prior result; bypasses name-based disambiguation",
)
.option("--file-path <hint>", "File path (or suffix) to disambiguate same-named symbols")
.option("--kind <kind>", "Kind filter (Function, Method, Class, Interface, …)")
.action(async (symbol: string, opts: Record<string, unknown>) => {
const mod = await import("./commands/context.js");
await mod.runContext(symbol, {
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
json: opts["json"] === true,
...(typeof opts["targetUid"] === "string" ? { targetUid: opts["targetUid"] } : {}),
...(typeof opts["filePath"] === "string" ? { filePath: opts["filePath"] } : {}),
...(typeof opts["kind"] === "string" ? { kind: opts["kind"] } : {}),
});
});
program
.command("impact <symbol>")
.description("Blast-radius analysis for a symbol")
.option("--depth <n>", "Max traversal depth", (v) => Number.parseInt(v, 10), 3)
.option("--direction <dir>", "up | down | both", "both")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--json", "Emit JSON on stdout")
.option(
"--target-uid <id>",
"Exact node id from a prior result; bypasses name-based disambiguation",
)
.option("--file-path <hint>", "File path (or suffix) to disambiguate same-named symbols")
.option("--kind <kind>", "Kind filter (Function, Method, Class, Interface, …)")
.action(async (symbol: string, opts: Record<string, unknown>) => {
const mod = await import("./commands/impact.js");
const directionRaw = typeof opts["direction"] === "string" ? opts["direction"] : "both";
const direction: "up" | "down" | "both" =
directionRaw === "up" || directionRaw === "down" ? directionRaw : "both";
await mod.runImpact(symbol, {
depth: typeof opts["depth"] === "number" ? opts["depth"] : 3,
direction,
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
json: opts["json"] === true,
...(typeof opts["targetUid"] === "string" ? { targetUid: opts["targetUid"] } : {}),
...(typeof opts["filePath"] === "string" ? { filePath: opts["filePath"] } : {}),
...(typeof opts["kind"] === "string" ? { kind: opts["kind"] } : {}),
});
});
program
.command("detect-changes")
.description(
"Map an uncommitted or committed diff onto affected graph symbols + processes. Useful in CI without launching the MCP server.",
)
.option(
"--scope <scope>",
"unstaged | staged | all | compare (default: all = working tree + index)",
"all",
)
.option(
"--compare-ref <ref>",
"Git ref to compare against (required when --scope=compare, e.g. origin/main)",
)
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--json", "Emit JSON on stdout")
.option("--strict", "Exit 1 on MEDIUM+ risk (default: exit 1 only on HIGH / CRITICAL)")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/detect-changes.js");
const rawScope = typeof opts["scope"] === "string" ? opts["scope"] : "all";
const scope: "unstaged" | "staged" | "all" | "compare" =
rawScope === "unstaged" || rawScope === "staged" || rawScope === "compare" ? rawScope : "all";
if (rawScope !== scope && rawScope !== "all") {
throw new Error(
`Unknown --scope value: "${rawScope}". Expected one of: unstaged, staged, all, compare`,
);
}
await mod.runDetectChangesCmd({
scope,
...(typeof opts["compareRef"] === "string" ? { compareRef: opts["compareRef"] } : {}),
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
json: opts["json"] === true,
strict: opts["strict"] === true,
});
});
program
.command("verdict")
.description("5-tier PR verdict (auto_merge|single_review|dual_review|expert_review|block)")
.option("--base <ref>", "Base git ref", "main")
.option("--head <ref>", "Head git ref", "HEAD")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--json", "Emit JSON on stdout instead of the default text summary")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/verdict.js");
await mod.runVerdict({
base: typeof opts["base"] === "string" ? opts["base"] : "main",
head: typeof opts["head"] === "string" ? opts["head"] : "HEAD",
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
json: opts["json"] === true,
});
});
program
.command("change-pack")
.description(
"Diff-scoped change-pack: impacted subgraph + verdict + affected tests + cost estimate (CLI sibling of the change_pack MCP tool)",
)
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--base <ref>", "Base git ref (default: main)")
.option("--head <ref>", "Head git ref (default: HEAD)")
.option("--depth <n>", "Upstream traversal depth (default: 4)", (v) => Number.parseInt(v, 10))
.option("--min-confidence <f>", "Traversal confidence floor 0-1 (default: 0.7)", (v) =>
Number.parseFloat(v),
)
.option("--budget <n>", "Context budget in heuristic tokens (default: 100000)", (v) =>
Number.parseInt(v, 10),
)
.option("--include-tests-in-subgraph", "Retain test nodes in the impacted subgraph")
.option("--json", "Emit JSON on stdout")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/change-pack.js");
await mod.runChangePackCmd({
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
...(typeof opts["base"] === "string" ? { base: opts["base"] } : {}),
...(typeof opts["head"] === "string" ? { head: opts["head"] } : {}),
...(typeof opts["depth"] === "number" ? { depth: opts["depth"] } : {}),
...(typeof opts["minConfidence"] === "number"
? { minConfidence: opts["minConfidence"] }
: {}),
...(typeof opts["budget"] === "number" ? { budget: opts["budget"] } : {}),
...(opts["includeTestsInSubgraph"] === true ? { includeTestsInSubgraph: true } : {}),
json: opts["json"] === true,
});
});
// `codehub group ...` — cross-repo groups. We register placeholder
// subcommands so `commander` routes the invocation correctly, and load the
// real handler lazily on .action(). This keeps `codehub --help` snappy.
{
const group = program.command("group").description("Manage named cross-repo groups");
group
.command("create <name> <repos...>")
.description("Create a group from registered repo names")
.option("--description <text>", "Short human-readable description")
.action(async (name: string, repos: string[], opts: Record<string, unknown>) => {
const mod = await import("./commands/group.js");
await mod.runGroupCreate(name, repos, {
...(typeof opts["description"] === "string" ? { description: opts["description"] } : {}),
});
});
group
.command("list")
.description("List all groups")
.action(async () => {
const mod = await import("./commands/group.js");
await mod.runGroupList();
});
group
.command("delete <name>")
.description("Delete a group")
.action(async (name: string) => {
const mod = await import("./commands/group.js");
await mod.runGroupDelete(name);
});
group
.command("status <name>")
.description("Per-repo index freshness within a group")
.action(async (name: string) => {
const mod = await import("./commands/group.js");
await mod.runGroupStatus(name);
});
group
.command("query <name> <text>")
.description("BM25 over every repo in the group, fused with RRF")
.option("--limit <n>", "Max results (default 20)", (v) => Number.parseInt(v, 10), 20)
.option("--json", "Emit JSON on stdout")
.action(async (name: string, text: string, opts: Record<string, unknown>) => {
const mod = await import("./commands/group.js");
await mod.runGroupQuery(name, text, {
limit: typeof opts["limit"] === "number" ? opts["limit"] : 20,
json: opts["json"] === true,
});
});
group
.command("sync <name>")
.description(
"Extract cross-repo HTTP / gRPC / topic contracts and write ~/.codehub/groups/<name>/contracts.json",
)
.option("--json", "Emit the written registry on stdout")
.action(async (name: string, opts: Record<string, unknown>) => {
const mod = await import("./commands/group.js");
await mod.runGroupSyncCmd(name, {
json: opts["json"] === true,
});
});
}
program
.command("ingest-sarif <sarifFile>")
.description("Ingest a SARIF 2.1.0 log into the graph as Finding nodes + FOUND_IN edges")
.option("--repo <name>", "Registered repo name (default: current directory)")
.action(async (sarifFile: string, opts: Record<string, unknown>) => {
const mod = await import("./commands/ingest-sarif.js");
await mod.runIngestSarif(sarifFile, {
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
});
});
program
.command("scan [path]")
.description("Run Priority-1 scanners and ingest findings into the graph")
.option("--scanners <list>", "Comma-separated scanner ids (overrides profile gating)")
.option("--with <list>", "Additional scanner ids to include (comma-separated)")
.option("--output <file>", "SARIF output path (default: <repo>/.codehub/scan.sarif)")
.option("--severity <list>", "Severity levels that fail the run (default: HIGH,CRITICAL)")
.option("--repo <name>", "Registered repo name (default: [path] or current directory)")
.option("--concurrency <n>", "Max parallel scanners", (v) => Number.parseInt(v, 10))
.option("--timeout <ms>", "Per-scanner timeout in ms", (v) => Number.parseInt(v, 10))
.action(async (path: string | undefined, opts: Record<string, unknown>) => {
const mod = await import("./commands/scan.js");
const scanners = typeof opts["scanners"] === "string" ? splitList(opts["scanners"]) : undefined;
const withScanners = typeof opts["with"] === "string" ? splitList(opts["with"]) : undefined;
const severity = typeof opts["severity"] === "string" ? splitList(opts["severity"]) : undefined;
const summary = await mod.runScan(path ?? process.cwd(), {
...(scanners !== undefined ? { scanners } : {}),
...(withScanners !== undefined ? { withScanners } : {}),
...(severity !== undefined ? { severity } : {}),
...(typeof opts["output"] === "string" ? { output: opts["output"] } : {}),
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
...(typeof opts["concurrency"] === "number" ? { concurrency: opts["concurrency"] } : {}),
...(typeof opts["timeout"] === "number" ? { timeoutMs: opts["timeout"] } : {}),
});
if (summary.exitCode !== 0) {
process.exitCode = summary.exitCode;
}
});
program
.command("doctor")
.description(
"Probe the local environment (node/pnpm/native bindings/vendored grammars/scip indexers/scanners/registry) and print actionable hints",
)
.option(
"--skip-native",
"Skip checks that require native bindings (no longer any; retained for compat)",
)
.option(
"--strict",
"Treat a missing SCIP indexer as a failure (exit 2), not a warning — for release/CI gates",
)
.option(
"--repoRoot <path>",
"Override the workspace root used as a fallback for native-binding resolution",
)
.action(async (opts: Record<string, string | boolean | undefined>) => {
const mod = await import("./commands/doctor.js");
await mod.runDoctor({
skipNative: opts["skipNative"] === true,
strict: opts["strict"] === true,
...(typeof opts["repoRoot"] === "string" && opts["repoRoot"].length > 0
? { repoRoot: opts["repoRoot"] }
: {}),
});
});
program
.command("bench")
.description(
"Run the acceptance gate suite (scripts/acceptance.sh) and render a pass/fail dashboard",
)
.option("--acceptance <path>", "Override the path to scripts/acceptance.sh")
.option("--silent", "Suppress the listr2 progress renderer (useful in CI)")
.action(async (opts: Record<string, string | boolean | undefined>) => {
const mod = await import("./commands/bench.js");
await mod.runBench({
...(typeof opts["acceptance"] === "string" ? { acceptanceScript: opts["acceptance"] } : {}),
silent: opts["silent"] === true,
});
});
program
.command("wiki")
.description(
"Emit a Markdown wiki under --output (deterministic by default; --llm for LLM prose)",
)
.requiredOption("--output <dir>", "Target directory for rendered pages")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--json", "Emit a JSON summary on stdout")
.option("--offline", "Assert no network access (incompatible with --llm)")
.option("--llm", "Route top-ranked modules through @opencodehub/summarizer for narrative prose")
.option(
"--max-llm-calls <n>",
"Cap on Bedrock summarizer calls when --llm is set. 0 (default) runs in dry-run mode",
(v) => Number.parseInt(v, 10),
0,
)
.option("--llm-model <id>", "Override the Bedrock model id passed to the summarizer")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/wiki.js");
const output = typeof opts["output"] === "string" ? opts["output"] : "";
if (output.length === 0) {
throw new Error("--output <dir> is required");
}
const maxLlmCallsRaw = opts["maxLlmCalls"];
const maxLlmCalls =
typeof maxLlmCallsRaw === "number" && Number.isFinite(maxLlmCallsRaw)
? Math.max(0, Math.floor(maxLlmCallsRaw))
: 0;
await mod.runWiki({
output,
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
json: opts["json"] === true,
offline: opts["offline"] === true,
llm: opts["llm"] === true,
maxLlmCalls,
...(typeof opts["llmModel"] === "string" ? { llmModel: opts["llmModel"] } : {}),
});
});
program
.command("ci-init")
.description("Emit opinionated CI workflow files for GitHub Actions and/or GitLab CI")
.option("--platform <p>", "Target platform: github | gitlab | both (default: auto-detect)")
.option("--main-branch <b>", "Name of the main branch", "main")
.option("--repo <path>", "Repo root (default: current directory)")
.option("--force", "Overwrite existing workflow files")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/ci-init.js");
const rawPlatform = typeof opts["platform"] === "string" ? opts["platform"] : undefined;
const platform: "github" | "gitlab" | "both" | undefined =
rawPlatform === "github" || rawPlatform === "gitlab" || rawPlatform === "both"
? rawPlatform
: undefined;
if (rawPlatform !== undefined && platform === undefined) {
throw new Error(
`Unknown --platform value: ${rawPlatform}. Expected one of: github, gitlab, both.`,
);
}
await mod.runCiInit({
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
...(platform !== undefined ? { platform } : {}),
...(typeof opts["mainBranch"] === "string" ? { mainBranch: opts["mainBranch"] } : {}),
force: opts["force"] === true,
});
});
program
.command("augment <pattern>")
.description(
"Fast-path BM25 enrichment for editor PreToolUse hooks — writes a compact context block to stderr",
)
.option("--limit <n>", "Max hits to enrich (default 5)", (v) => Number.parseInt(v, 10), 5)
.action(async (pattern: string, opts: Record<string, unknown>) => {
const mod = await import("./commands/augment.js");
await mod.runAugment(pattern, {
limit: typeof opts["limit"] === "number" ? opts["limit"] : 5,
});
});
program
.command("sql <query>")
.description(
"Run a read-only SQL query against the temporal store (cochanges + symbol_summaries); the node/edge graph is queried via the typed tools or Cypher",
)
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--timeout <ms>", "Per-query timeout in ms", (v) => Number.parseInt(v, 10), 5_000)
.option("--json", "Emit JSON on stdout")
.action(async (query: string, opts: Record<string, unknown>) => {
const mod = await import("./commands/sql.js");
await mod.runSql(query, {
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
timeoutMs: typeof opts["timeout"] === "number" ? opts["timeout"] : 5_000,
json: opts["json"] === true,
});
});
// --- read-only graph capabilities (CLI siblings of the MCP tools) ----------
// Each reuses the same underlying logic as its MCP tool (a shared
// `@opencodehub/analysis` fn or an IGraphStore/ITemporalStore reader),
// following the `verdict` CLI↔MCP shared-function pattern.
program
.command("findings")
.description("List SARIF Finding nodes (sibling of the MCP list_findings tool)")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--severity <level>", "Restrict to one SARIF severity: error | warning | note | none")
.option("--scanner <id>", "Restrict to a single scanner id (e.g. 'semgrep')")
.option("--rule-id <id>", "Restrict to a single rule id")
.option("--file-path <hint>", "Substring filter on the finding's file path")
.option("--limit <n>", "Maximum findings to return", (v) => Number.parseInt(v, 10), 500)
.option("--json", "Emit JSON on stdout")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/findings.js");
const sev = opts["severity"];
await mod.runFindings({
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
...(sev === "error" || sev === "warning" || sev === "note" || sev === "none"
? { severity: sev }
: {}),
...(typeof opts["scanner"] === "string" ? { scanner: opts["scanner"] } : {}),
...(typeof opts["ruleId"] === "string" ? { ruleId: opts["ruleId"] } : {}),
...(typeof opts["filePath"] === "string" ? { filePath: opts["filePath"] } : {}),
...(typeof opts["limit"] === "number" ? { limit: opts["limit"] } : {}),
json: opts["json"] === true,
});
});
program
.command("dead-code")
.description("List dead and unreachable-export symbols (sibling of MCP list_dead_code)")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--file-path-pattern <hint>", "Substring filter on each symbol's file path")
.option("--include-unreachable-exports", "Also include exported-but-unreferenced symbols")
.option("--limit <n>", "Maximum symbols to return", (v) => Number.parseInt(v, 10), 100)
.option("--json", "Emit JSON on stdout")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/dead-code.js");
await mod.runDeadCode({
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
...(typeof opts["filePathPattern"] === "string"
? { filePathPattern: opts["filePathPattern"] }
: {}),
includeUnreachableExports: opts["includeUnreachableExports"] === true,
...(typeof opts["limit"] === "number" ? { limit: opts["limit"] } : {}),
json: opts["json"] === true,
});
});
program
.command("license-audit")
.description("Classify Dependency nodes by license risk tier (sibling of MCP license_audit)")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--json", "Emit JSON on stdout")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/license-audit.js");
await mod.runLicenseAudit({
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
json: opts["json"] === true,
});
});
program
.command("project-profile")
.description("Show the detected project profile (sibling of MCP project_profile)")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--json", "Emit JSON on stdout")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/project-profile.js");
await mod.runProjectProfile({
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
json: opts["json"] === true,
});
});
program
.command("risk-trends")
.description("Per-community risk trend + 30-day projection (sibling of MCP risk_trends)")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--json", "Emit JSON on stdout")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/risk-trends.js");
await mod.runRiskTrends({
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
...(typeof opts["home"] === "string" ? { home: opts["home"] } : {}),
json: opts["json"] === true,
});
});
program
.command("owners <target>")
.description("List ranked OWNED_BY contributors for a node (sibling of MCP owners)")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--limit <n>", "Maximum contributors to return", (v) => Number.parseInt(v, 10), 20)
.option("--json", "Emit JSON on stdout")
.action(async (target: string, opts: Record<string, unknown>) => {
const mod = await import("./commands/owners.js");
await mod.runOwners(target, {
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
...(typeof opts["limit"] === "number" ? { limit: opts["limit"] } : {}),
json: opts["json"] === true,
});
});
program
.command("route-map")
.description("Map HTTP routes to handlers and consumers (sibling of MCP route_map)")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--route <hint>", "Substring match against Route.url (e.g. '/api/users')")
.option("--method <verb>", "Exact match against Route.method (e.g. 'GET')")
.option("--json", "Emit JSON on stdout")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/route-map.js");
await mod.runRouteMap({
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
...(typeof opts["route"] === "string" ? { route: opts["route"] } : {}),
...(typeof opts["method"] === "string" ? { method: opts["method"] } : {}),
json: opts["json"] === true,
});
});
program
.command("api-impact")
.description("Score the blast radius of changing a Route's contract (sibling of MCP api_impact)")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--route <hint>", "Substring match against Route.url")
.option("--file <hint>", "Substring match against Route.filePath")
.option("--json", "Emit JSON on stdout")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/api-impact.js");
await mod.runApiImpact({
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
...(typeof opts["route"] === "string" ? { route: opts["route"] } : {}),
...(typeof opts["file"] === "string" ? { file: opts["file"] } : {}),
json: opts["json"] === true,
});
});
program
.command("dependencies")
.description("List external dependencies (sibling of MCP dependencies)")
.option("--repo <name>", "Registered repo name (default: current directory)")
.option("--ecosystem <id>", "Restrict to one ecosystem: npm | pypi | go | cargo | maven | nuget")
.option("--file-path <hint>", "Substring filter on the manifest/lockfile path")
.option("--limit <n>", "Maximum dependencies to return", (v) => Number.parseInt(v, 10), 500)
.option("--json", "Emit JSON on stdout")
.action(async (opts: Record<string, unknown>) => {
const mod = await import("./commands/dependencies.js");
const eco = opts["ecosystem"];
await mod.runDependencies({
...(typeof opts["repo"] === "string" ? { repo: opts["repo"] } : {}),
...(eco === "npm" ||
eco === "pypi" ||
eco === "go" ||
eco === "cargo" ||
eco === "maven" ||
eco === "nuget"
? { ecosystem: eco }
: {}),
...(typeof opts["filePath"] === "string" ? { filePath: opts["filePath"] } : {}),
...(typeof opts["limit"] === "number" ? { limit: opts["limit"] } : {}),