-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·1222 lines (1090 loc) · 38.6 KB
/
Copy pathcli.js
File metadata and controls
executable file
·1222 lines (1090 loc) · 38.6 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
import { readFileSync, realpathSync } from "node:fs";
import { join } from "node:path";
import { performance } from "node:perf_hooks";
import { fileURLToPath } from "node:url";
import readline from "node:readline/promises";
import { parseArgv } from "./lib/args.js";
/** @typedef {import('./lib/args.js').ParsedArgs} ParsedArgs */
/** @typedef {import('./lib/args.js').FlagValue} FlagValue */
/**
* The parsed-args shape as consumed by the command handlers. Identical to
* {@link ParsedArgs} except flag values are read positionally and forwarded
* into typed option bags; they are FlagValue at runtime but are typed `any`
* here so the existing dynamic forwarding type-checks without runtime changes.
* @typedef {Object} CliArgs
* @property {string | undefined} command
* @property {string[]} positionals
* @property {Record<string, any>} flags
*/
/** @typedef {import('./lib/pass-local.js').PassData} PassData */
/** @typedef {import('./lib/pass-pr.js').PassPrData} PassPrData */
/** @typedef {import('./lib/review.js').ReviewData} ReviewData */
/** @typedef {import('./lib/eval.js').EvalOptions} EvalOptions */
import { formatDoctorReport, getDoctorReport } from "./lib/doctor.js";
import { inspectRepo } from "./lib/repo.js";
import { generateStructure } from "./lib/structure.js";
import { inspectDependency } from "./lib/deps.js";
import {
discoverRepositories,
formatCatalogSummary,
formatDiscoverSummary,
formatIndexSummary,
formatSearchResults,
indexRepositories,
listCatalog,
searchCatalog,
} from "./lib/catalog.js";
import { formatInitSummary, initProject } from "./lib/init.js";
import { formatInstallSummary, installOtito } from "./lib/install.js";
import { getToolMatrix } from "./lib/matrix.js";
import { startMcpServer } from "./lib/mcp.js";
import { formatContextPackTerminal, generateContextPack } from "./lib/context-engine.js";
import { formatImpactMermaid, formatImpactTerminal, generateImpact } from "./lib/impact.js";
import { formatAxMarkdown, generateAxScore } from "./lib/ax.js";
import { formatConvergenceMarkdown, generateConvergence } from "./lib/converge.js";
import { evaluateLocal, formatPassMarkdown, formatPassTerminal } from "./lib/pass-local.js";
import { evaluatePR, formatPassPrMarkdown, formatPassPrTerminal } from "./lib/pass-pr.js";
import { formatReviewMermaid, formatReviewTerminal, generateReview } from "./lib/review.js";
import { createRenderer } from "./lib/render/fancy.js";
import { generatePrReview } from "./lib/pr-review.js";
import { formatReportMermaid, formatReportTerminal, generateReport } from "./lib/report.js";
import { formatWorkspaceMermaid, generateWorkspaceReport } from "./lib/workspace.js";
import { generateHarness } from "./lib/harness.js";
import { runEval, runHarnessExecutionEval, runRetrievalEval } from "./lib/eval.js";
import { formatDataAccessMermaid, generateDataAccessReport } from "./lib/data-access.js";
import { getAgentTools } from "./lib/agent-tools.js";
import { formatCodeMapMermaid, formatCodeMapMarkdown, generateCodeMap } from "./lib/code-map.js";
import { printHelp, printText, printJson, writeArtifact } from "./lib/output.js";
import { CONFIG_KEYS, getConfigPath, listConfigSources, loadConfig, writeConfig } from "./lib/config.js";
import { appendEvent, clearTelemetryLog, noteResult, redactError, shareEvent, takePendingSignals, telemetryStatus } from "./lib/telemetry.js";
import { generateDashboard } from "./lib/dashboard.js";
const packageVersion = String(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
const versionFlags = new Set(["--version", "-v"]);
/** @type {Record<string, ((parsed: CliArgs) => void | Promise<void>) | undefined>} */
const commandHandlers = {
doctor: handleDoctor,
repo: handleRepo,
discover: handleDiscover,
index: handleIndex,
catalog: handleCatalog,
search: handleSearch,
context: handleContext,
impact: handleImpact,
ax: handleAx,
converge: handleConverge,
dashboard: handleDashboard,
telemetry: handleTelemetry,
pass: handlePass,
"pass-pr": handlePassPr,
gate: handleGate,
review: handleReview,
install: handleInstall,
i: handleInstall,
map: handleMap,
structure: handleStructure,
deps: handleDeps,
init: handleInit,
matrix: handleMatrix,
mcp: handleMcp,
pr: handlePr,
report: handleReport,
workspace: handleWorkspace,
harness: handleHarness,
eval: handleEval,
"data-access": handleDataAccess,
"agent-tools": handleAgentTools,
config: handleConfig,
help: handleHelp,
};
async function main(argv = process.argv.slice(2)) {
if (argv.length === 1 && versionFlags.has(argv[0])) {
printText(packageVersion);
process.exitCode = 0;
return;
}
const parsed = parseArgv(argv);
const command = parsed.command ?? "help";
const handler = commandHandlers[command];
// Load persisted config and inject defaults into flags. CLI flags always win —
// only inject when the user hasn't already supplied the flag.
if (command !== "config") {
const cfg = loadConfig();
if (cfg.emoji !== undefined && parsed.flags.emoji === undefined && parsed.flags.no_emoji === undefined) {
parsed.flags[cfg.emoji ? "emoji" : "no_emoji"] = true;
}
if (cfg.color !== undefined && parsed.flags.color === undefined && parsed.flags.no_color === undefined) {
parsed.flags[cfg.color ? "color" : "no_color"] = true;
}
if (cfg.theme !== undefined && cfg.theme !== "default" && parsed.flags.theme === undefined) {
parsed.flags.theme = cfg.theme;
}
if (cfg.policy !== undefined && parsed.flags.policy === undefined) {
parsed.flags.policy = cfg.policy;
}
if (cfg.governance !== undefined && parsed.flags.governance === undefined) {
parsed.flags.governance = cfg.governance;
}
}
if (!handler || parsed.flags.help) {
handleHelp(parsed);
process.exitCode = handler ? 0 : 1;
return;
}
// Opt-in usage telemetry: the long-lived `mcp` server records a single
// start-only event here (per-tool events come from mcp.js), every other
// command records once in the finally below. `argsShape` is keys only —
// never flag values — so no paths or queries reach the log.
const argsShape = { positionals: parsed.positionals.length, flags: Object.keys(parsed.flags).sort() };
if (command === "mcp") {
const record = appendEvent({ surface: "cli", cmd: "mcp", argsShape, outcome: "ok", durationMs: null, repoRoot: process.cwd() });
void shareEvent(record);
}
const startedAt = performance.now();
/** @type {unknown} */
let caughtError = null;
try {
await handler(parsed);
} catch (error) {
caughtError = error;
const message = error instanceof Error ? error.message : String(error);
if (parsed.flags.json) {
printJson({ ok: false, error: message });
} else {
console.error(`otito: ${message}`);
}
process.exitCode = 1;
} finally {
if (command !== "mcp") {
const outcome = caughtError ? "error" : process.exitCode ? "fail" : "ok";
const record = appendEvent({
surface: "cli",
cmd: command,
argsShape,
outcome,
error: caughtError ? redactError(caughtError) : null,
durationMs: performance.now() - startedAt,
signals: takePendingSignals(),
repoRoot: process.cwd(),
});
await shareEvent(record);
}
}
}
/** @param {CliArgs} parsed */
async function handleDoctor(parsed) {
const report = getDoctorReport();
if (parsed.flags.json) {
printJson(report);
return;
}
printText(formatDoctorReport(report, { emoji: emojiPreference(parsed), color: colorPreference(parsed), theme: themePreference(parsed) }));
}
/**
* @param {CliArgs} parsed
* @returns {boolean | undefined}
*/
function emojiPreference(parsed) {
if (parsed.flags.no_emoji) return false;
if (parsed.flags.emoji) return true;
return undefined;
}
/**
* @param {CliArgs} parsed
* @returns {boolean | undefined}
*/
function colorPreference(parsed) {
if (parsed.flags.no_color) return false;
if (parsed.flags.color) return true;
return undefined;
}
/**
* @param {CliArgs} parsed
* @returns {string | undefined}
*/
function themePreference(parsed) {
const t = parsed.flags.theme;
return typeof t === "string" ? t : undefined;
}
/** @param {CliArgs} parsed */
async function handleRepo(parsed) {
const repoPath = parsed.positionals[0] ?? ".";
const result = inspectRepo(repoPath);
if (parsed.flags.json) {
printJson(result);
return;
}
printText(formatRepoSummary(result));
}
/** @param {CliArgs} parsed */
async function handleDiscover(parsed) {
const roots = parsed.positionals.length ? parsed.positionals : ["."];
const result = discoverRepositories(roots, {
depth: parsed.flags.depth,
limit: parsed.flags.limit,
});
if (parsed.flags.json) {
printJson(result);
return;
}
printText(formatDiscoverSummary(result));
}
/** @param {CliArgs} parsed */
async function handleIndex(parsed) {
const repoPaths = parsed.positionals.length ? parsed.positionals : ["."];
const result = indexRepositories(repoPaths, {
catalog: parsed.flags.catalog,
discover: parsed.flags.discover,
depth: parsed.flags.depth,
limit: parsed.flags.limit,
});
if (parsed.flags.json) {
printJson(result);
if (!result.ok) {
process.exitCode = 1;
}
return;
}
printText(formatIndexSummary(result));
if (!result.ok) {
process.exitCode = 1;
}
}
/** @param {CliArgs} parsed */
async function handleCatalog(parsed) {
const result = listCatalog({
catalog: parsed.flags.catalog,
});
if (parsed.flags.json) {
printJson(result);
return;
}
printText(formatCatalogSummary(result));
}
/** @param {CliArgs} parsed */
async function handleSearch(parsed) {
const query = parsed.positionals.join(" ").trim();
const result = searchCatalog(query, {
catalog: parsed.flags.catalog,
limit: parsed.flags.limit,
offline: parsed.flags.offline,
});
if (parsed.flags.json) {
printJson(result);
return;
}
printText(formatSearchResults(result));
}
/** @param {CliArgs} parsed */
async function handleContext(parsed) {
const query = parsed.positionals.join(" ").trim();
const result = generateContextPack(query, {
path: parsed.flags.path,
limit: parsed.flags.limit,
});
if (parsed.flags.json) {
printJson(result.data);
return;
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, result.markdown);
printText(`Context pack written: ${artifact.path}`);
return;
}
printText(
formatContextPackTerminal(result.data, (/** @type {object} */ opts) =>
createRenderer({ ...opts, emoji: emojiPreference(parsed), color: colorPreference(parsed), theme: themePreference(parsed) }),
),
);
}
/** @param {CliArgs} parsed */
async function handleImpact(parsed) {
let repoPath;
let query;
if (parsed.flags.path) {
repoPath = parsed.flags.path;
query = parsed.positionals.join(" ").trim();
} else {
repoPath = parsed.positionals[0] ?? ".";
query = parsed.positionals.slice(1).join(" ").trim();
}
if (!query) {
throw new Error('impact requires a change request, e.g. `otito impact . "add Stripe refunds"`');
}
const result = generateImpact(query, {
path: repoPath,
top: parsed.flags.top,
diffBase: parsed.flags.diff_base,
});
noteResult(result.data);
if (parsed.flags.json) {
printJson(result.data);
return;
}
if (parsed.flags.mermaid) {
return writeMermaid(parsed, formatImpactMermaid(result.data), "Impact diagram");
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, result.markdown);
printText(`Change impact written: ${artifact.path}`);
return;
}
printText(
formatImpactTerminal(result.data, (/** @type {object} */ opts) =>
createRenderer({ ...opts, emoji: emojiPreference(parsed), color: colorPreference(parsed), theme: themePreference(parsed) }),
),
);
}
/** @param {CliArgs} parsed */
async function handleAx(parsed) {
// Mirror `impact` arg parsing: `ax "<task>" --path .` or `ax <repo> "<task>"`.
let repoPath;
let query;
if (parsed.flags.path) {
repoPath = parsed.flags.path;
query = parsed.positionals.join(" ").trim();
} else {
repoPath = parsed.positionals[0] ?? ".";
query = parsed.positionals.slice(1).join(" ").trim();
}
if (!query) {
throw new Error('ax requires a change request, e.g. `otito ax "add a new MCP tool" --path .`');
}
const data = generateAxScore(query, { path: repoPath, top: parsed.flags.top });
noteResult(data);
if (parsed.flags.json) {
printJson(data);
return;
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, formatAxMarkdown(data));
printText(`AX score written: ${artifact.path}`);
return;
}
printText(formatAxMarkdown(data));
}
/** @param {CliArgs} parsed */
async function handleConverge(parsed) {
// Mirror `impact` arg parsing: `converge "<task>" --path . --base <ref>` or
// `converge <repo> "<task>" --base <ref>`.
let repoPath;
let query;
if (parsed.flags.path) {
repoPath = parsed.flags.path;
query = parsed.positionals.join(" ").trim();
} else if (parsed.positionals.length >= 2) {
// `converge <repo> "<task>"` form.
repoPath = parsed.positionals[0];
query = parsed.positionals.slice(1).join(" ").trim();
} else {
// `converge "<task>"` form — repo defaults to cwd.
repoPath = ".";
query = parsed.positionals.join(" ").trim();
}
if (!query) {
throw new Error('converge requires a task, e.g. `otito converge "add Stripe refunds" --base origin/main`');
}
const data = generateConvergence(query, {
path: repoPath,
base: parsed.flags.base ?? parsed.flags.diff_base,
top: parsed.flags.top,
staged: parsed.flags.staged,
});
noteResult(data);
if (parsed.flags.json) {
printJson(data);
return;
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, formatConvergenceMarkdown(data));
printText(`Convergence report written: ${artifact.path}`);
return;
}
printText(formatConvergenceMarkdown(data));
}
/** @param {CliArgs} parsed */
async function handlePass(parsed) {
const repoPath = parsed.positionals[0] ?? ".";
// evaluateLocal returns a loosely-typed record; it is a PassData at runtime.
const data = /** @type {PassData} */ (
evaluateLocal(repoPath, {
base: parsed.flags.base,
policy: parsed.flags.policy,
governance: parsed.flags.governance,
request: parsed.flags.request,
minConvergence: parsed.flags.min_convergence,
receipt: parsed.flags.receipt,
staged: parsed.flags.staged,
})
);
noteResult(data);
if (parsed.flags.json) {
printJson(data);
if (data.verdict === "FAIL") process.exitCode = 1;
return;
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, formatPassMarkdown(data));
printText(`Pass report written: ${artifact.path}`);
if (data.verdict === "FAIL") process.exitCode = 1;
return;
}
printText(
formatPassTerminal(data, (/** @type {object} */ opts) =>
createRenderer({ ...opts, emoji: emojiPreference(parsed), color: colorPreference(parsed), theme: themePreference(parsed) }),
),
);
if (data.verdict === "FAIL") process.exitCode = 1;
}
/** @param {CliArgs} parsed */
async function handlePassPr(parsed) {
const selector = parsed.positionals[0] ?? "";
// evaluatePR returns a loosely-typed record; it is a PassPrData at runtime.
const data = /** @type {PassPrData} */ (
await evaluatePR(parsed.flags.path ?? ".", selector, {
policy: parsed.flags.policy,
governance: parsed.flags.governance,
request: parsed.flags.request,
minConvergence: parsed.flags.min_convergence,
receipt: parsed.flags.receipt,
})
);
noteResult(data);
if (parsed.flags.json) {
printJson(data);
if (data.verdict === "FAIL") process.exitCode = 1;
return;
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, formatPassPrMarkdown(data));
printText(`PR pass report written: ${artifact.path}`);
if (data.verdict === "FAIL") process.exitCode = 1;
return;
}
printText(
formatPassPrTerminal(data, (/** @type {object} */ opts) =>
createRenderer({ ...opts, emoji: emojiPreference(parsed), color: colorPreference(parsed), theme: themePreference(parsed) }),
),
);
if (data.verdict === "FAIL") process.exitCode = 1;
}
// `gate` is the canonical v2 merge-gate command. It maps to `pass` for the
// local gate (no --pr) and to `pass-pr` for the GitHub gate (--pr <selector>),
// mirroring the review_gate MCP tool's local-vs-PR dispatch. `pass` and
// `pass-pr` remain available as legacy aliases.
/** @param {CliArgs} parsed */
async function handleGate(parsed) {
const selector = parsed.flags.pr;
if (selector && selector !== true) {
// pass-pr reads the selector from positionals[0] and the repo from --path.
return handlePassPr({
...parsed,
positionals: [selector],
});
}
return handlePass(parsed);
}
/** @param {CliArgs} parsed */
async function handleReview(parsed) {
const repoPath = parsed.positionals[0] ?? ".";
const trailingRequest = parsed.positionals.slice(1).join(" ").trim();
const { data } = await generateReview(repoPath, {
request: parsed.flags.request ?? (trailingRequest || undefined),
base: parsed.flags.base,
head: parsed.flags.head,
prSelector: parsed.flags.pr,
policy: parsed.flags.policy,
governance: parsed.flags.governance,
minConvergence: parsed.flags.min_convergence,
receipt: parsed.flags.receipt,
impactTop: parsed.flags.top,
});
noteResult(data);
if (parsed.flags.json) {
printJson(data);
if (data.verdict === "FAIL") process.exitCode = 1;
return;
}
if (parsed.flags.mermaid) {
writeMermaid(parsed, formatReviewMermaid(/** @type {ReviewData} */ (data)), "Review diagram");
if (data.verdict === "FAIL") process.exitCode = 1;
return;
}
printText(
formatReviewTerminal(/** @type {ReviewData} */ (data), (/** @type {object} */ opts) =>
createRenderer({ ...opts, emoji: emojiPreference(parsed), color: colorPreference(parsed), theme: themePreference(parsed) }),
),
);
if (data.verdict === "FAIL") process.exitCode = 1;
}
/** @param {CliArgs} parsed */
async function handleInstall(parsed) {
const result = installOtito({
global: parsed.flags.global,
link: parsed.flags.link,
});
if (parsed.flags.json) {
printJson(result);
if (result.applied === false) {
process.exitCode = 1;
}
return;
}
printText(formatInstallSummary(result));
if (result.applied === false) {
process.exitCode = 1;
}
}
/** @param {CliArgs} parsed */
async function handleMap(parsed) {
const repoPath = parsed.positionals[0] ?? ".";
const result = generateCodeMap(repoPath, {
maxSymbols: parsed.flags.max_symbols,
});
if (parsed.flags.json) {
printJson(result);
return;
}
if (parsed.flags.mermaid) {
return writeMermaid(parsed, formatCodeMapMermaid(result), "Code map diagram");
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, formatCodeMapMarkdown(result));
printText(`Code map written: ${artifact.path}`);
return;
}
printText(formatCodeMapMarkdown(result));
}
/** @param {CliArgs} parsed */
async function handleStructure(parsed) {
const repoPath = parsed.positionals[0] ?? ".";
// generateStructure returns an opaque `object`; describe the fields used here.
const result = /** @type {{ ok: boolean, error?: string, command?: string, installHint?: string, outputPath?: string }} */ (
generateStructure(repoPath, {
out: parsed.flags.out,
pattern: parsed.flags.pattern,
exclude: parsed.flags.exclude,
})
);
if (parsed.flags.json) {
printJson(result);
if (!result.ok) {
process.exitCode = 1;
}
return;
}
if (!result.ok) {
const details = [`Structure generation skipped: ${result.error}`, result.command ? `Command: ${result.command}` : undefined, result.installHint].filter(
Boolean,
);
printText(details.join("\n"));
process.exitCode = 1;
return;
}
printText(`Structure generated: ${result.outputPath}`);
}
/** @param {CliArgs} parsed */
async function handleDeps(parsed) {
const packageName = parsed.positionals[0];
if (!packageName) {
throw new Error("deps requires a package name, for example: otito deps zod --query parse");
}
// inspectDependency is declared to return an opaque `object`; describe the
// ok-vs-error fields the CLI reads off it.
const result =
/** @type {{ ok: boolean, packageName: string, sourcePath?: string, query?: string, matches?: { file: string, line: number, text: string }[], error?: string, installHint?: string }} */ (
inspectDependency(packageName, {
query: parsed.flags.query,
limit: Number(parsed.flags.limit ?? 25),
})
);
if (parsed.flags.json) {
printJson(result);
if (!result.ok) {
process.exitCode = 1;
}
return;
}
if (!result.ok) {
printText(`Dependency lookup failed: ${result.error}\n${result.installHint}`);
process.exitCode = 1;
return;
}
const lines = [`# Dependency Source: ${result.packageName}`, "", `Path: ${result.sourcePath}`];
if (result.matches?.length) {
lines.push("", `Matches for "${result.query}":`);
for (const match of result.matches) {
lines.push(`- ${match.file}:${match.line}: ${match.text}`);
}
} else if (result.query) {
lines.push("", `No matches found for "${result.query}".`);
}
printText(lines.join("\n"));
}
/** @param {CliArgs} parsed */
async function handleMatrix(parsed) {
const matrix = getToolMatrix();
if (parsed.flags.json) {
printJson(matrix);
return;
}
const rows = [
"| Tool | Role | Pilot Use | Notes |",
"|---|---|---|---|",
...matrix.tools.map((tool) => `| ${tool.name} | ${tool.role} | ${tool.pilotUse} | ${tool.notes} |`),
];
printText(["# Tool Evaluation Matrix", "", ...rows].join("\n"));
}
/** @param {CliArgs} parsed */
async function handleInit(parsed) {
const targetPath = parsed.positionals[0] ?? ".";
// Resolve scaffold options from flags first. --no-gates / --no-precommit turn
// the new behaviors off; --hooks-path opts into the git core.hooksPath write.
let gates = !parsed.flags.no_gates;
let precommit = !parsed.flags.no_precommit;
let hooksPath = Boolean(parsed.flags.hooks_path);
// Prompting lives only here, and only for a human at a TTY. MCP, agents, CI,
// and --json/--yes callers run fully non-interactively off the flags above, so
// init never blocks an unattended caller.
const interactive = Boolean(process.stdin.isTTY) && !parsed.flags.yes && !parsed.flags.json;
if (interactive) {
gates = await promptYesNo("Generate harness-driven CI quality gates?", gates);
precommit = await promptYesNo("Scaffold a dependency-free pre-commit hook (.githooks/pre-commit)?", precommit);
if (precommit && !hooksPath) {
hooksPath = await promptYesNo("Point git core.hooksPath at .githooks now?", false);
}
}
const result = initProject(targetPath, {
force: parsed.flags.force,
noWorkflow: parsed.flags.no_workflow,
toolRepo: parsed.flags.tool_repo,
toolRef: parsed.flags.tool_ref,
gates,
precommit,
hooksPath,
});
if (parsed.flags.json) {
printJson(result);
return;
}
printText(formatInitSummary(result));
}
/**
* Ask a yes/no question at an interactive TTY. Used only by `init`; never
* reached for non-interactive callers (guarded by process.stdin.isTTY).
* @param {string} question
* @param {boolean} defaultValue
* @returns {Promise<boolean>}
*/
async function promptYesNo(question, defaultValue) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
try {
const hint = defaultValue ? "Y/n" : "y/N";
const answer = (await rl.question(`${question} [${hint}] `)).trim().toLowerCase();
if (!answer) {
return defaultValue;
}
return answer === "y" || answer === "yes";
} finally {
rl.close();
}
}
async function handleMcp() {
await startMcpServer();
}
/** @param {CliArgs} parsed */
async function handlePr(parsed) {
const repoPath = parsed.positionals[0] ?? ".";
const result = generatePrReview(repoPath, {
number: parsed.flags.number ?? parsed.flags.pr,
github: parsed.flags.github,
comment: parsed.flags.comment,
base: parsed.flags.base,
head: parsed.flags.head,
});
if (parsed.flags.json) {
printJson(result.data);
return;
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, result.markdown);
printText(["PR review context written:", artifact.path, formatCommentResult(result.data.comment)].filter(Boolean).join("\n"));
return;
}
printText([result.markdown, formatCommentResult(result.data.comment)].filter(Boolean).join("\n"));
}
/** @param {CliArgs} parsed */
async function handleReport(parsed) {
const repoPath = parsed.positionals[0] ?? ".";
const result = generateReport(repoPath);
if (parsed.flags.json) {
printJson(result.data);
return;
}
if (parsed.flags.mermaid) {
return writeMermaid(parsed, formatReportMermaid(result.data), "Report diagram");
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, result.markdown);
printText(`Report written: ${artifact.path}`);
return;
}
printText(formatReportTerminal(result.data, { columns: process.stdout.columns }));
}
/** @param {CliArgs} parsed */
async function handleWorkspace(parsed) {
if (parsed.positionals.length < 2) {
throw new Error("workspace requires at least two repo paths, for example: otito workspace ../web ../api");
}
const result = generateWorkspaceReport(parsed.positionals);
if (parsed.flags.json) {
printJson(result.data);
return;
}
if (parsed.flags.mermaid) {
return writeMermaid(parsed, formatWorkspaceMermaid(result.data), "Workspace diagram");
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, result.markdown);
printText(`Workspace report written: ${artifact.path}`);
return;
}
printText(result.markdown);
}
/** @param {CliArgs} parsed */
async function handleHarness(parsed) {
const repoPath = parsed.positionals[0] ?? ".";
const result = generateHarness(repoPath, {
maxSymbols: parsed.flags.max_symbols,
});
if (parsed.flags.json) {
printJson(result.data);
return;
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, result.markdown);
printText(`Harness written: ${artifact.path}`);
return;
}
printText(result.markdown);
}
/** @param {CliArgs} parsed */
async function handleEval(parsed) {
// --accuracy runs the labeled corpus (retrieval precision + risk
// classification) instead of the token-savings eval, and exits non-zero
// when the scoreboard falls below the corpus thresholds so CI can gate on it.
if (parsed.flags.accuracy) {
const result = runRetrievalEval({ corpusPath: parsed.flags.corpus });
noteResult(result.data);
if (parsed.flags.json) {
printJson(result.data);
} else if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, result.markdown);
printText(`Accuracy eval written: ${artifact.path}`);
} else {
printText(result.markdown);
}
if (!(/** @type {{ passed?: boolean }} */ (result.data).passed)) {
process.exitCode = 1;
}
return;
}
// --harness runs only the committed, fixture-backed command corpus. It
// proves that the inferred install/test/typecheck/build commands execute in
// an isolated temp copy rather than executing an inspected user repository.
if (parsed.flags.harness) {
const result = runHarnessExecutionEval({ corpusPath: parsed.flags.corpus });
noteResult(result.data);
if (parsed.flags.json) {
printJson(result.data);
} else if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, result.markdown);
printText(`Harness execution eval written: ${artifact.path}`);
} else {
printText(result.markdown);
}
if (!(/** @type {{ passed?: boolean }} */ (result.data).passed)) {
process.exitCode = 1;
}
return;
}
const repoPath = parsed.positionals[0] ?? ".";
/** @type {EvalOptions} */
const options = {};
if (parsed.flags.query) options.query = parsed.flags.query;
if (parsed.flags.naive_cap) options.naiveFileCap = Number(parsed.flags.naive_cap);
const result = runEval(repoPath, options);
noteResult(result.data);
if (parsed.flags.json) {
printJson(result.data);
return;
}
if (parsed.flags.out) {
const artifact = writeArtifact(parsed.flags.out, result.markdown);
printText(`Eval written: ${artifact.path}`);
return;
}
printText(result.markdown);
}
/** @param {CliArgs} parsed */
async function handleDashboard(parsed) {
// `--clear` purges the local usage log (the "delete your own data" path) and
// does nothing else.
if (parsed.flags.clear) {
const { removed, path: logPath } = clearTelemetryLog();
printText(removed.length ? `Usage log cleared: ${removed.join(", ")}` : `No usage log to clear at ${logPath}`);
return;
}
const repoPath = parsed.positionals[0] ?? ".";
const { data, html } = generateDashboard(repoPath, {
includeArtifacts: !parsed.flags.no_artifacts,
includeGit: !parsed.flags.no_git,
});
if (parsed.flags.json) {
printJson(data);
return;
}
const target = parsed.flags.out ?? join(repoPath, ".otito", "dashboard.html");
const artifact = writeArtifact(target, html);
printText(`Dashboard written: ${artifact.path}`);
if (!data.totals.events) {
printText("No usage events recorded yet. Enable capture with `otito config set telemetry true`, then run some commands.");
}
}
/** @param {CliArgs} parsed */
async function handleTelemetry(parsed) {
const sub = parsed.positionals[0] ?? "status";
if (sub === "share") {
const action = parsed.positionals[1] ?? "status";
if (action === "on" || action === "off") {
const scope = parsed.flags.local ? "local" : "user";
writeConfig(action === "on" ? { telemetry: true, telemetryShare: true } : { telemetryShare: false }, scope);
printText(
action === "on"
? `Anonymous usage sharing on (${getConfigPath(scope)}). Local capture is also on.`
: `Anonymous usage sharing off (${getConfigPath(scope)}). Local capture is unchanged.`,
);
return;
}
if (action !== "status") throw new Error("Usage: otito telemetry share [status|on|off]");
}
if (sub === "on" || sub === "off") {
const scope = parsed.flags.local ? "local" : "user";
writeConfig(sub === "on" ? { telemetry: true } : { telemetry: false, telemetryShare: false }, scope);
printText(
sub === "on"
? `Local telemetry on (${getConfigPath(scope)}). Nothing is shared unless you run \`otito telemetry share on\`.`
: `Telemetry off (${getConfigPath(scope)}). Local capture and anonymous sharing are both disabled.`,
);
return;
}
if (sub === "clear") {
const { removed, path: logPath } = clearTelemetryLog();