sentinelayer-cli 0.4.5 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +996 -998
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +63 -63
  6. package/src/agents/jules/config/definition.js +160 -209
  7. package/src/agents/jules/config/system-prompt.js +182 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -377
  10. package/src/agents/jules/loop.js +450 -367
  11. package/src/agents/jules/pulse.js +10 -327
  12. package/src/agents/jules/stream.js +186 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +309 -308
  18. package/src/agents/jules/tools/aidenid-email.js +189 -0
  19. package/src/agents/jules/tools/auth-audit.js +1691 -557
  20. package/src/agents/jules/tools/dispatch.js +335 -327
  21. package/src/agents/jules/tools/file-edit.js +2 -180
  22. package/src/agents/jules/tools/file-read.js +2 -100
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -168
  25. package/src/agents/jules/tools/grep.js +2 -228
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -161
  28. package/src/agents/jules/tools/runtime-audit.js +507 -503
  29. package/src/agents/jules/tools/shell.js +2 -383
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +61 -0
  32. package/src/agents/shared-tools/dispatch-core.js +315 -0
  33. package/src/agents/shared-tools/file-edit.js +180 -0
  34. package/src/agents/shared-tools/file-read.js +100 -0
  35. package/src/agents/shared-tools/glob.js +168 -0
  36. package/src/agents/shared-tools/grep.js +228 -0
  37. package/src/agents/shared-tools/index.js +46 -0
  38. package/src/agents/shared-tools/path-guards.js +161 -0
  39. package/src/agents/shared-tools/shell.js +383 -0
  40. package/src/ai/aidenid.js +1009 -972
  41. package/src/ai/client.js +553 -508
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -0
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +371 -126
  57. package/src/auth/http.js +611 -270
  58. package/src/auth/service.js +1106 -891
  59. package/src/auth/session-store.js +813 -359
  60. package/src/cli.js +252 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1166 -1166
  67. package/src/commands/auth.js +419 -375
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -21
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -866
  87. package/src/commands/spec.js +716 -716
  88. package/src/commands/swarm.js +651 -651
  89. package/src/commands/telemetry.js +202 -202
  90. package/src/commands/watch.js +511 -510
  91. package/src/config/agent-dictionary.js +182 -182
  92. package/src/config/io.js +56 -56
  93. package/src/config/paths.js +18 -18
  94. package/src/config/schema.js +55 -55
  95. package/src/config/service.js +184 -184
  96. package/src/cost/budget.js +235 -235
  97. package/src/cost/history.js +188 -188
  98. package/src/cost/tracker.js +171 -171
  99. package/src/daemon/artifact-lineage.js +534 -534
  100. package/src/daemon/assignment-ledger.js +770 -770
  101. package/src/daemon/ast-parser-layer.js +258 -258
  102. package/src/daemon/budget-governor.js +633 -633
  103. package/src/daemon/callgraph-overlay.js +646 -646
  104. package/src/daemon/error-worker.js +626 -626
  105. package/src/daemon/fix-cycle.js +377 -0
  106. package/src/daemon/hybrid-mapper.js +929 -929
  107. package/src/daemon/jira-lifecycle.js +632 -632
  108. package/src/daemon/operator-control.js +657 -657
  109. package/src/daemon/pulse.js +327 -0
  110. package/src/daemon/reliability-lane.js +471 -471
  111. package/src/daemon/watchdog.js +971 -971
  112. package/src/guide/generator.js +316 -316
  113. package/src/ingest/engine.js +918 -918
  114. package/src/interactive/index.js +97 -95
  115. package/src/legacy-cli.js +2994 -2592
  116. package/src/mcp/registry.js +695 -695
  117. package/src/memory/blackboard.js +301 -301
  118. package/src/memory/retrieval.js +581 -581
  119. package/src/plugin/manifest.js +553 -553
  120. package/src/policy/packs.js +144 -144
  121. package/src/prompt/generator.js +118 -118
  122. package/src/review/ai-review.js +679 -669
  123. package/src/review/local-review.js +1305 -1295
  124. package/src/review/omargate-interactive.js +68 -0
  125. package/src/review/omargate-orchestrator.js +300 -0
  126. package/src/review/persona-prompts.js +296 -0
  127. package/src/review/replay.js +235 -235
  128. package/src/review/report.js +664 -664
  129. package/src/review/scan-modes.js +42 -0
  130. package/src/review/spec-binding.js +487 -487
  131. package/src/scaffold/generator.js +67 -67
  132. package/src/scaffold/templates.js +150 -150
  133. package/src/scan/generator.js +418 -418
  134. package/src/scan/gh-secrets.js +107 -107
  135. package/src/spec/generator.js +519 -519
  136. package/src/spec/regenerate.js +237 -237
  137. package/src/spec/templates.js +91 -91
  138. package/src/swarm/dashboard.js +247 -247
  139. package/src/swarm/factory.js +363 -363
  140. package/src/swarm/pentest.js +934 -934
  141. package/src/swarm/registry.js +419 -419
  142. package/src/swarm/report.js +158 -158
  143. package/src/swarm/runtime.js +576 -576
  144. package/src/swarm/scenario-dsl.js +272 -272
  145. package/src/telemetry/ledger.js +302 -302
  146. package/src/telemetry/session-tracker.js +234 -118
  147. package/src/telemetry/sync.js +203 -199
  148. package/src/ui/command-hints.js +13 -0
  149. package/src/ui/markdown.js +220 -220
@@ -1,704 +1,704 @@
1
- import fsp from "node:fs/promises";
2
- import path from "node:path";
3
- import process from "node:process";
4
-
5
- import pc from "picocolors";
6
-
7
- import { formatIngestResolutionNotice, resolveCodebaseIngest } from "../ingest/engine.js";
8
- import { runAiReviewLayer } from "../review/ai-review.js";
9
- import {
10
- formatFindingsMarkdown,
11
- runDeterministicReviewPipeline,
12
- runLocalReviewScan,
13
- writeReviewReport,
14
- } from "../review/local-review.js";
15
- import {
16
- buildUnifiedReviewReport,
17
- exportUnifiedReviewReport,
18
- loadUnifiedReviewReport,
19
- recordReviewDecision,
20
- writeUnifiedReviewArtifacts,
21
- } from "../review/report.js";
22
- import {
23
- compareUnifiedReports,
24
- loadReviewRunContext,
25
- writeReviewComparisonArtifact,
26
- writeReviewRunContext,
27
- } from "../review/replay.js";
28
-
29
- function shouldEmitJson(options, command) {
30
- const local = Boolean(options && options.json);
31
- const globalFromCommand =
32
- command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().json) : false;
33
- return local || globalFromCommand;
34
- }
35
-
36
- function resolveModeFromOptions(options = {}, { defaultMode = "full" } = {}) {
37
- const explicitMode = String(options.mode || "").trim().toLowerCase();
38
- const diffFlag = Boolean(options.diff);
39
- const stagedFlag = Boolean(options.staged);
40
-
41
- if (diffFlag && stagedFlag) {
42
- throw new Error("Use only one of --diff or --staged.");
43
- }
44
-
45
- let modeFromFlags = "";
46
- if (diffFlag) {
47
- modeFromFlags = "diff";
48
- } else if (stagedFlag) {
49
- modeFromFlags = "staged";
50
- }
51
-
52
- if (explicitMode && modeFromFlags && explicitMode !== modeFromFlags) {
53
- throw new Error(`Conflicting mode selection: --mode ${explicitMode} with --${modeFromFlags}.`);
54
- }
55
-
56
- if (explicitMode) {
57
- return explicitMode;
58
- }
59
- if (modeFromFlags) {
60
- return modeFromFlags;
61
- }
62
- return defaultMode;
63
- }
64
-
65
- function resolveTargetPath(targetPathArg, options = {}) {
66
- return path.resolve(process.cwd(), String(options.path || targetPathArg || "."));
67
- }
68
-
69
- function printUnifiedSummary(report) {
70
- console.log(pc.bold("Unified review report"));
71
- console.log(pc.gray(`Run: ${report.runId}`));
72
- console.log(pc.gray(`Mode: ${report.mode}`));
73
- console.log(
74
- `Findings: P0=${report.summary.P0} P1=${report.summary.P1} P2=${report.summary.P2} P3=${report.summary.P3}`
75
- );
76
- for (const finding of report.findings || []) {
77
- const verdict = finding.adjudication?.verdict || "pending";
78
- console.log(
79
- `- [${finding.severity}] ${finding.findingId} ${finding.file}:${finding.line} (${verdict}) ${finding.message}`
80
- );
81
- }
82
- }
83
-
84
- async function executeReviewRun({
85
- targetPath,
86
- mode,
87
- outputDir = "",
88
- specFile = "",
89
- refreshIngest = false,
90
- aiConfig = {},
91
- replaySourceRunId = "",
92
- } = {}) {
93
- const deterministic = await runDeterministicReviewPipeline({
94
- targetPath,
95
- mode,
96
- outputDir,
97
- specFile,
98
- refreshIngest,
99
- });
100
-
101
- let aiLayer = null;
102
- if (aiConfig.enable) {
103
- aiLayer = await runAiReviewLayer({
104
- targetPath: deterministic.targetPath,
105
- mode: deterministic.mode,
106
- runId: deterministic.runId,
107
- runDirectory: deterministic.artifacts.runDirectory,
108
- deterministic,
109
- outputDir,
110
- provider: aiConfig.provider,
111
- model: aiConfig.model,
112
- apiKey: aiConfig.apiKey,
113
- sessionId: aiConfig.sessionId,
114
- maxFindings: aiConfig.aiMaxFindings,
115
- maxCostUsd: aiConfig.maxCost,
116
- maxOutputTokens: aiConfig.maxTokens,
117
- maxRuntimeMs: aiConfig.maxRuntimeMs,
118
- maxToolCalls: aiConfig.maxToolCalls,
119
- maxNoProgress: aiConfig.maxNoProgress,
120
- warningThresholdPercent: aiConfig.warnAtPercent,
121
- dryRun: Boolean(aiConfig.aiDryRun),
122
- env: process.env,
123
- });
124
- }
125
-
126
- const unified = await buildUnifiedReviewReport({
127
- targetPath: deterministic.targetPath,
128
- mode: deterministic.mode,
129
- runId: deterministic.runId,
130
- deterministic,
131
- aiLayer,
132
- specFile,
133
- });
134
- const unifiedArtifacts = await writeUnifiedReviewArtifacts({
135
- runDirectory: deterministic.artifacts.runDirectory,
136
- report: unified.report,
137
- markdown: unified.markdown,
138
- });
139
-
140
- const contextWrite = await writeReviewRunContext({
141
- runDirectory: deterministic.artifacts.runDirectory,
142
- runId: deterministic.runId,
143
- targetPath: deterministic.targetPath,
144
- mode: deterministic.mode,
145
- invocation: {
146
- aiEnabled: Boolean(aiConfig.enable),
147
- aiDryRun: Boolean(aiConfig.aiDryRun),
148
- provider: aiConfig.provider,
149
- model: aiConfig.model,
150
- sessionId: aiConfig.sessionId,
151
- aiMaxFindings: aiConfig.aiMaxFindings,
152
- maxCost: aiConfig.maxCost,
153
- maxTokens: aiConfig.maxTokens,
154
- maxRuntimeMs: aiConfig.maxRuntimeMs,
155
- maxToolCalls: aiConfig.maxToolCalls,
156
- maxNoProgress: aiConfig.maxNoProgress,
157
- warnAtPercent: aiConfig.warnAtPercent,
158
- outputDir,
159
- specFile,
160
- refreshIngest: Boolean(refreshIngest),
161
- },
162
- replay: {
163
- sourceRunId: replaySourceRunId,
164
- replayed: Boolean(replaySourceRunId),
165
- },
166
- });
167
-
168
- const summary = unified.report.summary;
169
- const blocking = Boolean(summary.blocking) || Boolean(aiLayer?.budget?.blocking);
170
-
171
- const payload = {
172
- command: "review",
173
- targetPath: deterministic.targetPath,
174
- mode: deterministic.mode,
175
- runId: deterministic.runId,
176
- runDirectory: deterministic.artifacts.runDirectory,
177
- reportPath: deterministic.artifacts.markdownPath,
178
- reportJsonPath: deterministic.artifacts.jsonPath,
179
- reportUnifiedPath: unifiedArtifacts.reportMarkdownPath,
180
- reportUnifiedJsonPath: unifiedArtifacts.reportJsonPath,
181
- runContextPath: contextWrite.contextPath,
182
- scannedFiles: deterministic.scope.scannedFiles,
183
- scopedFiles: deterministic.scope.scannedRelativeFiles,
184
- specPath: deterministic.layers.specBinding?.specPath || "",
185
- specHashSha256: deterministic.layers.specBinding?.specHashSha256 || "",
186
- findingCount: unified.report.findings.length,
187
- p0: summary.P0,
188
- p1: summary.P1,
189
- p2: summary.P2,
190
- p3: summary.P3,
191
- blocking,
192
- deterministicSummary: deterministic.summary,
193
- ingestRefresh: deterministic.layers?.ingest?.refresh || null,
194
- ai: aiLayer
195
- ? {
196
- enabled: true,
197
- dryRun: aiLayer.dryRun,
198
- parser: aiLayer.parser,
199
- summary: aiLayer.summary,
200
- provider: aiLayer.provider,
201
- model: aiLayer.model,
202
- findingCount: aiLayer.findings.length,
203
- reportPath: aiLayer.artifacts.reportMarkdownPath,
204
- reportJsonPath: aiLayer.artifacts.reportJsonPath,
205
- promptPath: aiLayer.artifacts.promptPath,
206
- usage: aiLayer.usage,
207
- pricingFound: aiLayer.pricingFound,
208
- budget: aiLayer.budget,
209
- cost: aiLayer.cost,
210
- telemetry: aiLayer.telemetry,
211
- }
212
- : {
213
- enabled: false,
214
- },
215
- };
216
-
217
- return {
218
- deterministic,
219
- aiLayer,
220
- unified,
221
- unifiedArtifacts,
222
- contextWrite,
223
- payload,
224
- blocking,
225
- };
226
- }
227
-
228
- function registerVerdictCommand(review, verdict) {
229
- review
230
- .command(`${verdict} <findingId>`)
231
- .description(`Record HITL verdict '${verdict}' for a unified review finding`)
232
- .option("--run-id <id>", "Explicit review run id")
233
- .option("--path <path>", "Target workspace path", ".")
234
- .option("--output-dir <path>", "Optional artifact output root override")
235
- .option("--note <text>", "Optional human note for this verdict", "")
236
- .option("--actor <id>", "Operator identifier for audit trail", "")
237
- .option("--json", "Emit machine-readable output")
238
- .action(async (findingId, options, command) => {
239
- const emitJson = shouldEmitJson(options, command);
240
- const targetPath = resolveTargetPath(".", options);
241
- const result = await recordReviewDecision({
242
- targetPath,
243
- runId: options.runId,
244
- outputDir: options.outputDir,
245
- findingId,
246
- verdict,
247
- note: options.note,
248
- actor: options.actor,
249
- env: process.env,
250
- });
251
-
252
- const payload = {
253
- command: `review ${verdict}`,
254
- runId: result.runId,
255
- runDirectory: result.runDirectory,
256
- findingId: result.findingId,
257
- decision: result.decision,
258
- reportPath: result.reportMarkdownPath,
259
- reportJsonPath: result.reportJsonPath,
260
- decisionsPath: result.decisionsPath,
261
- };
262
-
263
- if (emitJson) {
264
- console.log(JSON.stringify(payload, null, 2));
265
- } else {
266
- console.log(pc.bold(`Recorded verdict '${verdict}'`));
267
- console.log(pc.gray(`Run: ${result.runId}`));
268
- console.log(pc.gray(`Finding: ${result.findingId}`));
269
- console.log(pc.gray(`Report: ${result.reportMarkdownPath}`));
270
- }
271
- });
272
- }
273
-
274
- export function registerReviewCommand(program) {
275
- const review = program
276
- .command("review")
277
- .description("Run deterministic local review with optional AI reasoning layer")
278
- .argument("[targetPath]", "Target workspace path", ".")
279
- .option("--path <path>", "Target workspace path override")
280
- .option("--diff", "Alias for --mode diff")
281
- .option("--staged", "Alias for --mode staged")
282
- .option("--ai", "Enable AI reasoning layer over deterministic findings")
283
- .option("--ai-dry-run", "Run AI layer in dry-run mode (no provider call)")
284
- .option("--provider <name>", "AI provider override (openai|anthropic|google)")
285
- .option("--model <id>", "AI model override")
286
- .option("--api-key <key>", "Optional explicit API key override")
287
- .option("--session-id <id>", "AI cost/telemetry session id override")
288
- .option("--ai-max-findings <n>", "Max number of structured AI findings", "20")
289
- .option("--max-cost <usd>", "Max AI cost budget for this review session", "1.0")
290
- .option("--max-tokens <n>", "Max AI output token budget (0 disables)", "0")
291
- .option("--max-runtime-ms <n>", "Max AI runtime budget in ms (0 disables)", "0")
292
- .option("--max-tool-calls <n>", "Max AI tool-call budget (0 disables)", "0")
293
- .option("--max-no-progress <n>", "Max no-progress streak before stop", "3")
294
- .option("--warn-at-percent <n>", "Warning threshold percentage for enabled budgets", "80")
295
- .option("--spec <path>", "Spec file path relative to target (defaults to SPEC.md or docs/spec.md)")
296
- .option("--output-dir <path>", "Optional artifact output root override")
297
- .option("--refresh", "Refresh CODEBASE_INGEST before deterministic review")
298
- .option("--json", "Emit machine-readable output")
299
- .action(async (targetPathArg, options, command) => {
300
- const emitJson = shouldEmitJson(options, command);
301
- const targetPath = resolveTargetPath(targetPathArg, options);
302
- const mode = resolveModeFromOptions(options, {
303
- defaultMode: "full",
304
- });
305
-
306
- const outcome = await executeReviewRun({
307
- targetPath,
308
- mode,
309
- outputDir: options.outputDir,
310
- specFile: options.spec,
311
- refreshIngest: Boolean(options.refresh),
312
- aiConfig: {
313
- enable: Boolean(options.ai),
314
- aiDryRun: Boolean(options.aiDryRun),
315
- provider: options.provider,
316
- model: options.model,
317
- apiKey: options.apiKey,
318
- sessionId: options.sessionId,
319
- aiMaxFindings: options.aiMaxFindings,
320
- maxCost: options.maxCost,
321
- maxTokens: options.maxTokens,
322
- maxRuntimeMs: options.maxRuntimeMs,
323
- maxToolCalls: options.maxToolCalls,
324
- maxNoProgress: options.maxNoProgress,
325
- warnAtPercent: options.warnAtPercent,
326
- },
327
- });
328
-
329
- if (emitJson) {
330
- console.log(JSON.stringify(outcome.payload, null, 2));
331
- } else {
332
- console.log(pc.bold("Deterministic review complete"));
333
- console.log(pc.gray(`Run: ${outcome.deterministic.runId}`));
334
- console.log(pc.gray(`Mode: ${outcome.deterministic.mode}`));
335
- console.log(pc.gray(`Report: ${outcome.deterministic.artifacts.markdownPath}`));
336
- console.log(pc.gray(`JSON: ${outcome.deterministic.artifacts.jsonPath}`));
337
- console.log(pc.gray(`Unified report: ${outcome.unifiedArtifacts.reportMarkdownPath}`));
338
- console.log(pc.gray(`Unified JSON: ${outcome.unifiedArtifacts.reportJsonPath}`));
339
- console.log(pc.gray(`Run context: ${outcome.contextWrite.contextPath}`));
340
- if (outcome.payload.ingestRefresh?.stale || outcome.payload.ingestRefresh?.refreshed) {
341
- const color =
342
- outcome.payload.ingestRefresh?.stale && !outcome.payload.ingestRefresh?.refreshed
343
- ? pc.yellow
344
- : pc.gray;
345
- console.log(color(formatIngestResolutionNotice(outcome.payload.ingestRefresh)));
346
- }
347
- if (outcome.aiLayer) {
348
- console.log(
349
- pc.gray(
350
- `AI: ${outcome.aiLayer.provider}/${outcome.aiLayer.model} findings=${outcome.aiLayer.findings.length} dry_run=${outcome.aiLayer.dryRun ? "yes" : "no"}`
351
- )
352
- );
353
- console.log(pc.gray(`AI report: ${outcome.aiLayer.artifacts.reportMarkdownPath}`));
354
- }
355
- console.log(`Files scanned: ${outcome.deterministic.scope.scannedFiles}`);
356
- console.log(
357
- `Findings: P0=${outcome.unified.report.summary.P0} P1=${outcome.unified.report.summary.P1} P2=${outcome.unified.report.summary.P2} P3=${outcome.unified.report.summary.P3}`
358
- );
359
- }
360
-
361
- if (outcome.blocking) {
362
- if (!emitJson) {
363
- console.log(pc.red("Blocking findings detected (P0/P1 > 0 or budget stop)."));
364
- }
365
- process.exitCode = 2;
366
- }
367
- });
368
-
369
- review
370
- .command("show")
371
- .description("Show latest or specified unified review report")
372
- .option("--run-id <id>", "Explicit review run id")
373
- .option("--path <path>", "Target workspace path", ".")
374
- .option("--output-dir <path>", "Optional artifact output root override")
375
- .option("--json", "Emit machine-readable output")
376
- .action(async (options, command) => {
377
- const emitJson = shouldEmitJson(options, command);
378
- const targetPath = resolveTargetPath(".", options);
379
- const loaded = await loadUnifiedReviewReport({
380
- targetPath,
381
- runId: options.runId,
382
- outputDir: options.outputDir,
383
- env: process.env,
384
- });
385
-
386
- const payload = {
387
- command: "review show",
388
- runId: loaded.report.runId,
389
- runDirectory: loaded.runDirectory,
390
- reportPath: loaded.reportMarkdownPath,
391
- reportJsonPath: loaded.reportJsonPath,
392
- decisionsPath: loaded.decisionsPath,
393
- report: loaded.report,
394
- };
395
-
396
- if (emitJson) {
397
- console.log(JSON.stringify(payload, null, 2));
398
- return;
399
- }
400
-
401
- console.log(pc.gray(`Report: ${loaded.reportMarkdownPath}`));
402
- printUnifiedSummary(loaded.report);
403
- });
404
-
405
- review
406
- .command("export")
407
- .description("Export unified review report in md/json/sarif/github-annotations format")
408
- .option("--run-id <id>", "Explicit review run id")
409
- .option("--path <path>", "Target workspace path", ".")
410
- .option("--output-dir <path>", "Optional artifact output root override")
411
- .option("--format <format>", "Export format (sarif|json|md|github-annotations)", "md")
412
- .option("--output-file <path>", "Optional custom export output path")
413
- .option("--json", "Emit machine-readable output")
414
- .action(async (options, command) => {
415
- const emitJson = shouldEmitJson(options, command);
416
- const targetPath = resolveTargetPath(".", options);
417
- const exported = await exportUnifiedReviewReport({
418
- targetPath,
419
- runId: options.runId,
420
- outputDir: options.outputDir,
421
- format: options.format,
422
- outputFile: options.outputFile,
423
- env: process.env,
424
- });
425
-
426
- const payload = {
427
- command: "review export",
428
- runId: exported.runId,
429
- runDirectory: exported.runDirectory,
430
- format: exported.format,
431
- outputPath: exported.outputPath,
432
- };
433
-
434
- if (emitJson) {
435
- console.log(JSON.stringify(payload, null, 2));
436
- return;
437
- }
438
-
439
- console.log(pc.bold("Review report exported"));
440
- console.log(pc.gray(`Run: ${exported.runId}`));
441
- console.log(pc.gray(`Format: ${exported.format}`));
442
- console.log(pc.gray(`Output: ${exported.outputPath}`));
443
- });
444
-
445
- review
446
- .command("replay <runId>")
447
- .description("Replay a previous unified review run with captured context and compare drift")
448
- .option("--path <path>", "Target workspace path override")
449
- .option("--spec <path>", "Spec file path override for replay run")
450
- .option("--output-dir <path>", "Optional artifact output root override")
451
- .option("--refresh", "Refresh CODEBASE_INGEST before replay run")
452
- .option("--no-ai", "Disable AI layer for replay run")
453
- .option("--ai-dry-run", "Force AI dry-run during replay")
454
- .option("--json", "Emit machine-readable output")
455
- .action(async (runId, options, command) => {
456
- const emitJson = shouldEmitJson(options, command);
457
- const lookupPath = resolveTargetPath(".", options);
458
- const source = await loadUnifiedReviewReport({
459
- targetPath: lookupPath,
460
- runId,
461
- outputDir: options.outputDir,
462
- env: process.env,
463
- });
464
-
465
- let sourceContext = null;
466
- try {
467
- sourceContext = await loadReviewRunContext(source.runDirectory);
468
- } catch {
469
- sourceContext = null;
470
- }
471
-
472
- const invocation = sourceContext?.context?.invocation || {};
473
- const replayTargetPath = options.path
474
- ? resolveTargetPath(".", options)
475
- : path.resolve(sourceContext?.context?.targetPath || source.report.targetPath || lookupPath);
476
- const aiEnabled = options.noAi ? false : Boolean(invocation.aiEnabled);
477
-
478
- const replayOutcome = await executeReviewRun({
479
- targetPath: replayTargetPath,
480
- mode: sourceContext?.context?.mode || source.report.mode || "full",
481
- outputDir: options.outputDir || invocation.outputDir || "",
482
- specFile: options.spec || invocation.specFile || "",
483
- refreshIngest: Boolean(options.refresh || invocation.refreshIngest),
484
- aiConfig: {
485
- enable: aiEnabled,
486
- aiDryRun: Boolean(options.aiDryRun || invocation.aiDryRun),
487
- provider: invocation.provider,
488
- model: invocation.model,
489
- sessionId: invocation.sessionId,
490
- aiMaxFindings: invocation.aiMaxFindings || "20",
491
- maxCost: invocation.maxCost || "1.0",
492
- maxTokens: invocation.maxTokens || "0",
493
- maxRuntimeMs: invocation.maxRuntimeMs || "0",
494
- maxToolCalls: invocation.maxToolCalls || "0",
495
- maxNoProgress: invocation.maxNoProgress || "3",
496
- warnAtPercent: invocation.warnAtPercent || "80",
497
- },
498
- replaySourceRunId: source.report.runId,
499
- });
500
-
501
- const comparison = compareUnifiedReports(source.report, replayOutcome.unified.report);
502
- const artifact = await writeReviewComparisonArtifact({
503
- runDirectory: replayOutcome.deterministic.artifacts.runDirectory,
504
- baseRunId: source.report.runId,
505
- candidateRunId: replayOutcome.unified.report.runId,
506
- comparison,
507
- });
508
-
509
- const payload = {
510
- command: "review replay",
511
- sourceRunId: source.report.runId,
512
- replayRunId: replayOutcome.unified.report.runId,
513
- runDirectory: replayOutcome.deterministic.artifacts.runDirectory,
514
- sourceReportPath: source.reportMarkdownPath,
515
- replayReportPath: replayOutcome.unifiedArtifacts.reportMarkdownPath,
516
- replayReportJsonPath: replayOutcome.unifiedArtifacts.reportJsonPath,
517
- comparisonPath: artifact.artifactPath,
518
- deterministicEquivalent: comparison.deterministicEquivalent,
519
- driftDetected: !comparison.deterministicEquivalent,
520
- counts: comparison.counts,
521
- summaryDelta: comparison.summaryDelta,
522
- };
523
-
524
- if (emitJson) {
525
- console.log(JSON.stringify(payload, null, 2));
526
- } else {
527
- console.log(pc.bold("Review replay complete"));
528
- console.log(pc.gray(`Source run: ${payload.sourceRunId}`));
529
- console.log(pc.gray(`Replay run: ${payload.replayRunId}`));
530
- console.log(pc.gray(`Comparison: ${payload.comparisonPath}`));
531
- console.log(
532
- `Drift: ${payload.driftDetected ? "detected" : "none"} (added=${payload.counts.added}, removed=${payload.counts.removed}, severity_changed=${payload.counts.severityChanged})`
533
- );
534
- }
535
- });
536
-
537
- review
538
- .command("diff <baseRunId> <candidateRunId>")
539
- .description("Compare two unified review runs")
540
- .option("--path <path>", "Target workspace path", ".")
541
- .option("--output-dir <path>", "Optional artifact output root override")
542
- .option("--output-file <path>", "Optional custom output path for comparison JSON")
543
- .option("--json", "Emit machine-readable output")
544
- .action(async (baseRunId, candidateRunId, options, command) => {
545
- const emitJson = shouldEmitJson(options, command);
546
- const targetPath = resolveTargetPath(".", options);
547
- const base = await loadUnifiedReviewReport({
548
- targetPath,
549
- runId: baseRunId,
550
- outputDir: options.outputDir,
551
- env: process.env,
552
- });
553
- const candidate = await loadUnifiedReviewReport({
554
- targetPath,
555
- runId: candidateRunId,
556
- outputDir: options.outputDir,
557
- env: process.env,
558
- });
559
-
560
- const comparison = compareUnifiedReports(base.report, candidate.report);
561
- const artifact = await writeReviewComparisonArtifact({
562
- runDirectory: candidate.runDirectory,
563
- baseRunId: base.report.runId,
564
- candidateRunId: candidate.report.runId,
565
- comparison,
566
- });
567
-
568
- let outputPath = artifact.artifactPath;
569
- if (options.outputFile) {
570
- outputPath = path.resolve(targetPath, String(options.outputFile));
571
- await fsp.mkdir(path.dirname(outputPath), { recursive: true });
572
- await fsp.writeFile(outputPath, `${JSON.stringify(artifact.payload, null, 2)}\n`, "utf-8");
573
- }
574
-
575
- const payload = {
576
- command: "review diff",
577
- baseRunId: base.report.runId,
578
- candidateRunId: candidate.report.runId,
579
- deterministicEquivalent: comparison.deterministicEquivalent,
580
- counts: comparison.counts,
581
- summaryDelta: comparison.summaryDelta,
582
- outputPath,
583
- };
584
-
585
- if (emitJson) {
586
- console.log(JSON.stringify(payload, null, 2));
587
- } else {
588
- console.log(pc.bold("Review run diff complete"));
589
- console.log(pc.gray(`Base: ${payload.baseRunId}`));
590
- console.log(pc.gray(`Candidate: ${payload.candidateRunId}`));
591
- console.log(pc.gray(`Output: ${payload.outputPath}`));
592
- console.log(
593
- `Delta: added=${payload.counts.added}, removed=${payload.counts.removed}, severity_changed=${payload.counts.severityChanged}`
594
- );
595
- }
596
- });
597
-
598
- registerVerdictCommand(review, "accept");
599
- registerVerdictCommand(review, "reject");
600
- registerVerdictCommand(review, "defer");
601
-
602
- review
603
- .command("scan")
604
- .description("Compatibility mode: run lightweight policy scan")
605
- .option("--mode <mode>", "Scan mode: full, diff, or staged", "full")
606
- .option("--diff", "Alias for --mode diff")
607
- .option("--staged", "Alias for --mode staged")
608
- .option("--path <path>", "Target workspace path", ".")
609
- .option("--spec <path>", "Spec file path relative to target (defaults to SPEC.md or docs/spec.md)")
610
- .option("--output-dir <path>", "Optional artifact output root override")
611
- .option("--refresh", "Refresh CODEBASE_INGEST prior to compatibility scan")
612
- .option("--json", "Emit machine-readable output")
613
- .action(async (options, command) => {
614
- const emitJson = shouldEmitJson(options, command);
615
- const targetPath = resolveTargetPath(".", options);
616
- let ingestRefresh = null;
617
- if (options.refresh) {
618
- const ingestResolution = await resolveCodebaseIngest({
619
- rootPath: targetPath,
620
- outputDir: options.outputDir,
621
- refresh: true,
622
- });
623
- ingestRefresh = {
624
- outputPath: ingestResolution.outputPath,
625
- refreshed: ingestResolution.refreshed,
626
- stale: ingestResolution.stale,
627
- reasons: ingestResolution.reasons,
628
- refreshedBecause: ingestResolution.refreshedBecause,
629
- lastCommitAt: ingestResolution.lastCommitAt,
630
- contentHash: ingestResolution.fingerprint?.contentHash || "",
631
- };
632
- }
633
- const mode = resolveModeFromOptions(options, {
634
- defaultMode: String(options.mode || "full").trim().toLowerCase() || "full",
635
- });
636
- const scan = await runLocalReviewScan({
637
- targetPath,
638
- mode,
639
- specFile: options.spec,
640
- });
641
-
642
- const report = `# Local Review Scan
643
-
644
- Generated: ${new Date().toISOString()}
645
- Target: ${scan.targetPath}
646
- Mode: ${scan.mode}
647
-
648
- Summary:
649
- - Files scanned: ${scan.scannedFiles}
650
- - P1 findings: ${scan.p1}
651
- - P2 findings: ${scan.p2}
652
-
653
- Scoped files:
654
- ${scan.scannedRelativeFiles.length > 0 ? scan.scannedRelativeFiles.map((item) => `- ${item}`).join("\n") : "- none"}
655
-
656
- Findings:
657
- ${formatFindingsMarkdown(scan.findings)}
658
- `;
659
-
660
- const reportPath = await writeReviewReport({
661
- targetPath: scan.targetPath,
662
- mode: scan.mode,
663
- outputDir: options.outputDir,
664
- reportMarkdown: report,
665
- });
666
-
667
- const payload = {
668
- command: "review scan",
669
- targetPath: scan.targetPath,
670
- mode: scan.mode,
671
- reportPath,
672
- scannedFiles: scan.scannedFiles,
673
- scopedFiles: scan.scannedRelativeFiles,
674
- specPath: scan.specBinding?.specPath || "",
675
- specHashSha256: scan.specBinding?.specHashSha256 || "",
676
- p1: scan.p1,
677
- p2: scan.p2,
678
- blocking: scan.p1 > 0,
679
- ingestRefresh,
680
- };
681
-
682
- if (emitJson) {
683
- console.log(JSON.stringify(payload, null, 2));
684
- } else {
685
- console.log(pc.bold("Local review scan complete"));
686
- console.log(pc.gray(`Mode: ${scan.mode}`));
687
- console.log(pc.gray(`Report: ${reportPath}`));
688
- if (ingestRefresh) {
689
- console.log(pc.gray(formatIngestResolutionNotice(ingestRefresh)));
690
- }
691
- console.log(`Files scanned: ${scan.scannedFiles}`);
692
- console.log(`P1 findings: ${scan.p1}`);
693
- console.log(`P2 findings: ${scan.p2}`);
694
- }
695
-
696
- if (scan.p1 > 0) {
697
- if (!emitJson) {
698
- console.log(pc.red("Blocking findings detected (P1 > 0)."));
699
- }
700
- process.exitCode = 2;
701
- }
702
- });
703
- }
704
-
1
+ import fsp from "node:fs/promises";
2
+ import path from "node:path";
3
+ import process from "node:process";
4
+
5
+ import pc from "picocolors";
6
+
7
+ import { formatIngestResolutionNotice, resolveCodebaseIngest } from "../ingest/engine.js";
8
+ import { runAiReviewLayer } from "../review/ai-review.js";
9
+ import {
10
+ formatFindingsMarkdown,
11
+ runDeterministicReviewPipeline,
12
+ runLocalReviewScan,
13
+ writeReviewReport,
14
+ } from "../review/local-review.js";
15
+ import {
16
+ buildUnifiedReviewReport,
17
+ exportUnifiedReviewReport,
18
+ loadUnifiedReviewReport,
19
+ recordReviewDecision,
20
+ writeUnifiedReviewArtifacts,
21
+ } from "../review/report.js";
22
+ import {
23
+ compareUnifiedReports,
24
+ loadReviewRunContext,
25
+ writeReviewComparisonArtifact,
26
+ writeReviewRunContext,
27
+ } from "../review/replay.js";
28
+
29
+ function shouldEmitJson(options, command) {
30
+ const local = Boolean(options && options.json);
31
+ const globalFromCommand =
32
+ command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().json) : false;
33
+ return local || globalFromCommand;
34
+ }
35
+
36
+ function resolveModeFromOptions(options = {}, { defaultMode = "full" } = {}) {
37
+ const explicitMode = String(options.mode || "").trim().toLowerCase();
38
+ const diffFlag = Boolean(options.diff);
39
+ const stagedFlag = Boolean(options.staged);
40
+
41
+ if (diffFlag && stagedFlag) {
42
+ throw new Error("Use only one of --diff or --staged.");
43
+ }
44
+
45
+ let modeFromFlags = "";
46
+ if (diffFlag) {
47
+ modeFromFlags = "diff";
48
+ } else if (stagedFlag) {
49
+ modeFromFlags = "staged";
50
+ }
51
+
52
+ if (explicitMode && modeFromFlags && explicitMode !== modeFromFlags) {
53
+ throw new Error(`Conflicting mode selection: --mode ${explicitMode} with --${modeFromFlags}.`);
54
+ }
55
+
56
+ if (explicitMode) {
57
+ return explicitMode;
58
+ }
59
+ if (modeFromFlags) {
60
+ return modeFromFlags;
61
+ }
62
+ return defaultMode;
63
+ }
64
+
65
+ function resolveTargetPath(targetPathArg, options = {}) {
66
+ return path.resolve(process.cwd(), String(options.path || targetPathArg || "."));
67
+ }
68
+
69
+ function printUnifiedSummary(report) {
70
+ console.log(pc.bold("Unified review report"));
71
+ console.log(pc.gray(`Run: ${report.runId}`));
72
+ console.log(pc.gray(`Mode: ${report.mode}`));
73
+ console.log(
74
+ `Findings: P0=${report.summary.P0} P1=${report.summary.P1} P2=${report.summary.P2} P3=${report.summary.P3}`
75
+ );
76
+ for (const finding of report.findings || []) {
77
+ const verdict = finding.adjudication?.verdict || "pending";
78
+ console.log(
79
+ `- [${finding.severity}] ${finding.findingId} ${finding.file}:${finding.line} (${verdict}) ${finding.message}`
80
+ );
81
+ }
82
+ }
83
+
84
+ async function executeReviewRun({
85
+ targetPath,
86
+ mode,
87
+ outputDir = "",
88
+ specFile = "",
89
+ refreshIngest = false,
90
+ aiConfig = {},
91
+ replaySourceRunId = "",
92
+ } = {}) {
93
+ const deterministic = await runDeterministicReviewPipeline({
94
+ targetPath,
95
+ mode,
96
+ outputDir,
97
+ specFile,
98
+ refreshIngest,
99
+ });
100
+
101
+ let aiLayer = null;
102
+ if (aiConfig.enable) {
103
+ aiLayer = await runAiReviewLayer({
104
+ targetPath: deterministic.targetPath,
105
+ mode: deterministic.mode,
106
+ runId: deterministic.runId,
107
+ runDirectory: deterministic.artifacts.runDirectory,
108
+ deterministic,
109
+ outputDir,
110
+ provider: aiConfig.provider,
111
+ model: aiConfig.model,
112
+ apiKey: aiConfig.apiKey,
113
+ sessionId: aiConfig.sessionId,
114
+ maxFindings: aiConfig.aiMaxFindings,
115
+ maxCostUsd: aiConfig.maxCost,
116
+ maxOutputTokens: aiConfig.maxTokens,
117
+ maxRuntimeMs: aiConfig.maxRuntimeMs,
118
+ maxToolCalls: aiConfig.maxToolCalls,
119
+ maxNoProgress: aiConfig.maxNoProgress,
120
+ warningThresholdPercent: aiConfig.warnAtPercent,
121
+ dryRun: Boolean(aiConfig.aiDryRun),
122
+ env: process.env,
123
+ });
124
+ }
125
+
126
+ const unified = await buildUnifiedReviewReport({
127
+ targetPath: deterministic.targetPath,
128
+ mode: deterministic.mode,
129
+ runId: deterministic.runId,
130
+ deterministic,
131
+ aiLayer,
132
+ specFile,
133
+ });
134
+ const unifiedArtifacts = await writeUnifiedReviewArtifacts({
135
+ runDirectory: deterministic.artifacts.runDirectory,
136
+ report: unified.report,
137
+ markdown: unified.markdown,
138
+ });
139
+
140
+ const contextWrite = await writeReviewRunContext({
141
+ runDirectory: deterministic.artifacts.runDirectory,
142
+ runId: deterministic.runId,
143
+ targetPath: deterministic.targetPath,
144
+ mode: deterministic.mode,
145
+ invocation: {
146
+ aiEnabled: Boolean(aiConfig.enable),
147
+ aiDryRun: Boolean(aiConfig.aiDryRun),
148
+ provider: aiConfig.provider,
149
+ model: aiConfig.model,
150
+ sessionId: aiConfig.sessionId,
151
+ aiMaxFindings: aiConfig.aiMaxFindings,
152
+ maxCost: aiConfig.maxCost,
153
+ maxTokens: aiConfig.maxTokens,
154
+ maxRuntimeMs: aiConfig.maxRuntimeMs,
155
+ maxToolCalls: aiConfig.maxToolCalls,
156
+ maxNoProgress: aiConfig.maxNoProgress,
157
+ warnAtPercent: aiConfig.warnAtPercent,
158
+ outputDir,
159
+ specFile,
160
+ refreshIngest: Boolean(refreshIngest),
161
+ },
162
+ replay: {
163
+ sourceRunId: replaySourceRunId,
164
+ replayed: Boolean(replaySourceRunId),
165
+ },
166
+ });
167
+
168
+ const summary = unified.report.summary;
169
+ const blocking = Boolean(summary.blocking) || Boolean(aiLayer?.budget?.blocking);
170
+
171
+ const payload = {
172
+ command: "review",
173
+ targetPath: deterministic.targetPath,
174
+ mode: deterministic.mode,
175
+ runId: deterministic.runId,
176
+ runDirectory: deterministic.artifacts.runDirectory,
177
+ reportPath: deterministic.artifacts.markdownPath,
178
+ reportJsonPath: deterministic.artifacts.jsonPath,
179
+ reportUnifiedPath: unifiedArtifacts.reportMarkdownPath,
180
+ reportUnifiedJsonPath: unifiedArtifacts.reportJsonPath,
181
+ runContextPath: contextWrite.contextPath,
182
+ scannedFiles: deterministic.scope.scannedFiles,
183
+ scopedFiles: deterministic.scope.scannedRelativeFiles,
184
+ specPath: deterministic.layers.specBinding?.specPath || "",
185
+ specHashSha256: deterministic.layers.specBinding?.specHashSha256 || "",
186
+ findingCount: unified.report.findings.length,
187
+ p0: summary.P0,
188
+ p1: summary.P1,
189
+ p2: summary.P2,
190
+ p3: summary.P3,
191
+ blocking,
192
+ deterministicSummary: deterministic.summary,
193
+ ingestRefresh: deterministic.layers?.ingest?.refresh || null,
194
+ ai: aiLayer
195
+ ? {
196
+ enabled: true,
197
+ dryRun: aiLayer.dryRun,
198
+ parser: aiLayer.parser,
199
+ summary: aiLayer.summary,
200
+ provider: aiLayer.provider,
201
+ model: aiLayer.model,
202
+ findingCount: aiLayer.findings.length,
203
+ reportPath: aiLayer.artifacts.reportMarkdownPath,
204
+ reportJsonPath: aiLayer.artifacts.reportJsonPath,
205
+ promptPath: aiLayer.artifacts.promptPath,
206
+ usage: aiLayer.usage,
207
+ pricingFound: aiLayer.pricingFound,
208
+ budget: aiLayer.budget,
209
+ cost: aiLayer.cost,
210
+ telemetry: aiLayer.telemetry,
211
+ }
212
+ : {
213
+ enabled: false,
214
+ },
215
+ };
216
+
217
+ return {
218
+ deterministic,
219
+ aiLayer,
220
+ unified,
221
+ unifiedArtifacts,
222
+ contextWrite,
223
+ payload,
224
+ blocking,
225
+ };
226
+ }
227
+
228
+ function registerVerdictCommand(review, verdict) {
229
+ review
230
+ .command(`${verdict} <findingId>`)
231
+ .description(`Record HITL verdict '${verdict}' for a unified review finding`)
232
+ .option("--run-id <id>", "Explicit review run id")
233
+ .option("--path <path>", "Target workspace path", ".")
234
+ .option("--output-dir <path>", "Optional artifact output root override")
235
+ .option("--note <text>", "Optional human note for this verdict", "")
236
+ .option("--actor <id>", "Operator identifier for audit trail", "")
237
+ .option("--json", "Emit machine-readable output")
238
+ .action(async (findingId, options, command) => {
239
+ const emitJson = shouldEmitJson(options, command);
240
+ const targetPath = resolveTargetPath(".", options);
241
+ const result = await recordReviewDecision({
242
+ targetPath,
243
+ runId: options.runId,
244
+ outputDir: options.outputDir,
245
+ findingId,
246
+ verdict,
247
+ note: options.note,
248
+ actor: options.actor,
249
+ env: process.env,
250
+ });
251
+
252
+ const payload = {
253
+ command: `review ${verdict}`,
254
+ runId: result.runId,
255
+ runDirectory: result.runDirectory,
256
+ findingId: result.findingId,
257
+ decision: result.decision,
258
+ reportPath: result.reportMarkdownPath,
259
+ reportJsonPath: result.reportJsonPath,
260
+ decisionsPath: result.decisionsPath,
261
+ };
262
+
263
+ if (emitJson) {
264
+ console.log(JSON.stringify(payload, null, 2));
265
+ } else {
266
+ console.log(pc.bold(`Recorded verdict '${verdict}'`));
267
+ console.log(pc.gray(`Run: ${result.runId}`));
268
+ console.log(pc.gray(`Finding: ${result.findingId}`));
269
+ console.log(pc.gray(`Report: ${result.reportMarkdownPath}`));
270
+ }
271
+ });
272
+ }
273
+
274
+ export function registerReviewCommand(program) {
275
+ const review = program
276
+ .command("review")
277
+ .description("Run deterministic local review with optional AI reasoning layer")
278
+ .argument("[targetPath]", "Target workspace path", ".")
279
+ .option("--path <path>", "Target workspace path override")
280
+ .option("--diff", "Alias for --mode diff")
281
+ .option("--staged", "Alias for --mode staged")
282
+ .option("--ai", "Enable AI reasoning layer over deterministic findings")
283
+ .option("--ai-dry-run", "Run AI layer in dry-run mode (no provider call)")
284
+ .option("--provider <name>", "AI provider override (openai|anthropic|google)")
285
+ .option("--model <id>", "AI model override")
286
+ .option("--api-key <key>", "Optional explicit API key override")
287
+ .option("--session-id <id>", "AI cost/telemetry session id override")
288
+ .option("--ai-max-findings <n>", "Max number of structured AI findings", "20")
289
+ .option("--max-cost <usd>", "Max AI cost budget for this review session", "1.0")
290
+ .option("--max-tokens <n>", "Max AI output token budget (0 disables)", "0")
291
+ .option("--max-runtime-ms <n>", "Max AI runtime budget in ms (0 disables)", "0")
292
+ .option("--max-tool-calls <n>", "Max AI tool-call budget (0 disables)", "0")
293
+ .option("--max-no-progress <n>", "Max no-progress streak before stop", "3")
294
+ .option("--warn-at-percent <n>", "Warning threshold percentage for enabled budgets", "80")
295
+ .option("--spec <path>", "Spec file path relative to target (defaults to SPEC.md or docs/spec.md)")
296
+ .option("--output-dir <path>", "Optional artifact output root override")
297
+ .option("--refresh", "Refresh CODEBASE_INGEST before deterministic review")
298
+ .option("--json", "Emit machine-readable output")
299
+ .action(async (targetPathArg, options, command) => {
300
+ const emitJson = shouldEmitJson(options, command);
301
+ const targetPath = resolveTargetPath(targetPathArg, options);
302
+ const mode = resolveModeFromOptions(options, {
303
+ defaultMode: "full",
304
+ });
305
+
306
+ const outcome = await executeReviewRun({
307
+ targetPath,
308
+ mode,
309
+ outputDir: options.outputDir,
310
+ specFile: options.spec,
311
+ refreshIngest: Boolean(options.refresh),
312
+ aiConfig: {
313
+ enable: Boolean(options.ai),
314
+ aiDryRun: Boolean(options.aiDryRun),
315
+ provider: options.provider,
316
+ model: options.model,
317
+ apiKey: options.apiKey,
318
+ sessionId: options.sessionId,
319
+ aiMaxFindings: options.aiMaxFindings,
320
+ maxCost: options.maxCost,
321
+ maxTokens: options.maxTokens,
322
+ maxRuntimeMs: options.maxRuntimeMs,
323
+ maxToolCalls: options.maxToolCalls,
324
+ maxNoProgress: options.maxNoProgress,
325
+ warnAtPercent: options.warnAtPercent,
326
+ },
327
+ });
328
+
329
+ if (emitJson) {
330
+ console.log(JSON.stringify(outcome.payload, null, 2));
331
+ } else {
332
+ console.log(pc.bold("Deterministic review complete"));
333
+ console.log(pc.gray(`Run: ${outcome.deterministic.runId}`));
334
+ console.log(pc.gray(`Mode: ${outcome.deterministic.mode}`));
335
+ console.log(pc.gray(`Report: ${outcome.deterministic.artifacts.markdownPath}`));
336
+ console.log(pc.gray(`JSON: ${outcome.deterministic.artifacts.jsonPath}`));
337
+ console.log(pc.gray(`Unified report: ${outcome.unifiedArtifacts.reportMarkdownPath}`));
338
+ console.log(pc.gray(`Unified JSON: ${outcome.unifiedArtifacts.reportJsonPath}`));
339
+ console.log(pc.gray(`Run context: ${outcome.contextWrite.contextPath}`));
340
+ if (outcome.payload.ingestRefresh?.stale || outcome.payload.ingestRefresh?.refreshed) {
341
+ const color =
342
+ outcome.payload.ingestRefresh?.stale && !outcome.payload.ingestRefresh?.refreshed
343
+ ? pc.yellow
344
+ : pc.gray;
345
+ console.log(color(formatIngestResolutionNotice(outcome.payload.ingestRefresh)));
346
+ }
347
+ if (outcome.aiLayer) {
348
+ console.log(
349
+ pc.gray(
350
+ `AI: ${outcome.aiLayer.provider}/${outcome.aiLayer.model} findings=${outcome.aiLayer.findings.length} dry_run=${outcome.aiLayer.dryRun ? "yes" : "no"}`
351
+ )
352
+ );
353
+ console.log(pc.gray(`AI report: ${outcome.aiLayer.artifacts.reportMarkdownPath}`));
354
+ }
355
+ console.log(`Files scanned: ${outcome.deterministic.scope.scannedFiles}`);
356
+ console.log(
357
+ `Findings: P0=${outcome.unified.report.summary.P0} P1=${outcome.unified.report.summary.P1} P2=${outcome.unified.report.summary.P2} P3=${outcome.unified.report.summary.P3}`
358
+ );
359
+ }
360
+
361
+ if (outcome.blocking) {
362
+ if (!emitJson) {
363
+ console.log(pc.red("Blocking findings detected (P0/P1 > 0 or budget stop)."));
364
+ }
365
+ process.exitCode = 2;
366
+ }
367
+ });
368
+
369
+ review
370
+ .command("show")
371
+ .description("Show latest or specified unified review report")
372
+ .option("--run-id <id>", "Explicit review run id")
373
+ .option("--path <path>", "Target workspace path", ".")
374
+ .option("--output-dir <path>", "Optional artifact output root override")
375
+ .option("--json", "Emit machine-readable output")
376
+ .action(async (options, command) => {
377
+ const emitJson = shouldEmitJson(options, command);
378
+ const targetPath = resolveTargetPath(".", options);
379
+ const loaded = await loadUnifiedReviewReport({
380
+ targetPath,
381
+ runId: options.runId,
382
+ outputDir: options.outputDir,
383
+ env: process.env,
384
+ });
385
+
386
+ const payload = {
387
+ command: "review show",
388
+ runId: loaded.report.runId,
389
+ runDirectory: loaded.runDirectory,
390
+ reportPath: loaded.reportMarkdownPath,
391
+ reportJsonPath: loaded.reportJsonPath,
392
+ decisionsPath: loaded.decisionsPath,
393
+ report: loaded.report,
394
+ };
395
+
396
+ if (emitJson) {
397
+ console.log(JSON.stringify(payload, null, 2));
398
+ return;
399
+ }
400
+
401
+ console.log(pc.gray(`Report: ${loaded.reportMarkdownPath}`));
402
+ printUnifiedSummary(loaded.report);
403
+ });
404
+
405
+ review
406
+ .command("export")
407
+ .description("Export unified review report in md/json/sarif/github-annotations format")
408
+ .option("--run-id <id>", "Explicit review run id")
409
+ .option("--path <path>", "Target workspace path", ".")
410
+ .option("--output-dir <path>", "Optional artifact output root override")
411
+ .option("--format <format>", "Export format (sarif|json|md|github-annotations)", "md")
412
+ .option("--output-file <path>", "Optional custom export output path")
413
+ .option("--json", "Emit machine-readable output")
414
+ .action(async (options, command) => {
415
+ const emitJson = shouldEmitJson(options, command);
416
+ const targetPath = resolveTargetPath(".", options);
417
+ const exported = await exportUnifiedReviewReport({
418
+ targetPath,
419
+ runId: options.runId,
420
+ outputDir: options.outputDir,
421
+ format: options.format,
422
+ outputFile: options.outputFile,
423
+ env: process.env,
424
+ });
425
+
426
+ const payload = {
427
+ command: "review export",
428
+ runId: exported.runId,
429
+ runDirectory: exported.runDirectory,
430
+ format: exported.format,
431
+ outputPath: exported.outputPath,
432
+ };
433
+
434
+ if (emitJson) {
435
+ console.log(JSON.stringify(payload, null, 2));
436
+ return;
437
+ }
438
+
439
+ console.log(pc.bold("Review report exported"));
440
+ console.log(pc.gray(`Run: ${exported.runId}`));
441
+ console.log(pc.gray(`Format: ${exported.format}`));
442
+ console.log(pc.gray(`Output: ${exported.outputPath}`));
443
+ });
444
+
445
+ review
446
+ .command("replay <runId>")
447
+ .description("Replay a previous unified review run with captured context and compare drift")
448
+ .option("--path <path>", "Target workspace path override")
449
+ .option("--spec <path>", "Spec file path override for replay run")
450
+ .option("--output-dir <path>", "Optional artifact output root override")
451
+ .option("--refresh", "Refresh CODEBASE_INGEST before replay run")
452
+ .option("--no-ai", "Disable AI layer for replay run")
453
+ .option("--ai-dry-run", "Force AI dry-run during replay")
454
+ .option("--json", "Emit machine-readable output")
455
+ .action(async (runId, options, command) => {
456
+ const emitJson = shouldEmitJson(options, command);
457
+ const lookupPath = resolveTargetPath(".", options);
458
+ const source = await loadUnifiedReviewReport({
459
+ targetPath: lookupPath,
460
+ runId,
461
+ outputDir: options.outputDir,
462
+ env: process.env,
463
+ });
464
+
465
+ let sourceContext = null;
466
+ try {
467
+ sourceContext = await loadReviewRunContext(source.runDirectory);
468
+ } catch {
469
+ sourceContext = null;
470
+ }
471
+
472
+ const invocation = sourceContext?.context?.invocation || {};
473
+ const replayTargetPath = options.path
474
+ ? resolveTargetPath(".", options)
475
+ : path.resolve(sourceContext?.context?.targetPath || source.report.targetPath || lookupPath);
476
+ const aiEnabled = options.noAi ? false : Boolean(invocation.aiEnabled);
477
+
478
+ const replayOutcome = await executeReviewRun({
479
+ targetPath: replayTargetPath,
480
+ mode: sourceContext?.context?.mode || source.report.mode || "full",
481
+ outputDir: options.outputDir || invocation.outputDir || "",
482
+ specFile: options.spec || invocation.specFile || "",
483
+ refreshIngest: Boolean(options.refresh || invocation.refreshIngest),
484
+ aiConfig: {
485
+ enable: aiEnabled,
486
+ aiDryRun: Boolean(options.aiDryRun || invocation.aiDryRun),
487
+ provider: invocation.provider,
488
+ model: invocation.model,
489
+ sessionId: invocation.sessionId,
490
+ aiMaxFindings: invocation.aiMaxFindings || "20",
491
+ maxCost: invocation.maxCost || "1.0",
492
+ maxTokens: invocation.maxTokens || "0",
493
+ maxRuntimeMs: invocation.maxRuntimeMs || "0",
494
+ maxToolCalls: invocation.maxToolCalls || "0",
495
+ maxNoProgress: invocation.maxNoProgress || "3",
496
+ warnAtPercent: invocation.warnAtPercent || "80",
497
+ },
498
+ replaySourceRunId: source.report.runId,
499
+ });
500
+
501
+ const comparison = compareUnifiedReports(source.report, replayOutcome.unified.report);
502
+ const artifact = await writeReviewComparisonArtifact({
503
+ runDirectory: replayOutcome.deterministic.artifacts.runDirectory,
504
+ baseRunId: source.report.runId,
505
+ candidateRunId: replayOutcome.unified.report.runId,
506
+ comparison,
507
+ });
508
+
509
+ const payload = {
510
+ command: "review replay",
511
+ sourceRunId: source.report.runId,
512
+ replayRunId: replayOutcome.unified.report.runId,
513
+ runDirectory: replayOutcome.deterministic.artifacts.runDirectory,
514
+ sourceReportPath: source.reportMarkdownPath,
515
+ replayReportPath: replayOutcome.unifiedArtifacts.reportMarkdownPath,
516
+ replayReportJsonPath: replayOutcome.unifiedArtifacts.reportJsonPath,
517
+ comparisonPath: artifact.artifactPath,
518
+ deterministicEquivalent: comparison.deterministicEquivalent,
519
+ driftDetected: !comparison.deterministicEquivalent,
520
+ counts: comparison.counts,
521
+ summaryDelta: comparison.summaryDelta,
522
+ };
523
+
524
+ if (emitJson) {
525
+ console.log(JSON.stringify(payload, null, 2));
526
+ } else {
527
+ console.log(pc.bold("Review replay complete"));
528
+ console.log(pc.gray(`Source run: ${payload.sourceRunId}`));
529
+ console.log(pc.gray(`Replay run: ${payload.replayRunId}`));
530
+ console.log(pc.gray(`Comparison: ${payload.comparisonPath}`));
531
+ console.log(
532
+ `Drift: ${payload.driftDetected ? "detected" : "none"} (added=${payload.counts.added}, removed=${payload.counts.removed}, severity_changed=${payload.counts.severityChanged})`
533
+ );
534
+ }
535
+ });
536
+
537
+ review
538
+ .command("diff <baseRunId> <candidateRunId>")
539
+ .description("Compare two unified review runs")
540
+ .option("--path <path>", "Target workspace path", ".")
541
+ .option("--output-dir <path>", "Optional artifact output root override")
542
+ .option("--output-file <path>", "Optional custom output path for comparison JSON")
543
+ .option("--json", "Emit machine-readable output")
544
+ .action(async (baseRunId, candidateRunId, options, command) => {
545
+ const emitJson = shouldEmitJson(options, command);
546
+ const targetPath = resolveTargetPath(".", options);
547
+ const base = await loadUnifiedReviewReport({
548
+ targetPath,
549
+ runId: baseRunId,
550
+ outputDir: options.outputDir,
551
+ env: process.env,
552
+ });
553
+ const candidate = await loadUnifiedReviewReport({
554
+ targetPath,
555
+ runId: candidateRunId,
556
+ outputDir: options.outputDir,
557
+ env: process.env,
558
+ });
559
+
560
+ const comparison = compareUnifiedReports(base.report, candidate.report);
561
+ const artifact = await writeReviewComparisonArtifact({
562
+ runDirectory: candidate.runDirectory,
563
+ baseRunId: base.report.runId,
564
+ candidateRunId: candidate.report.runId,
565
+ comparison,
566
+ });
567
+
568
+ let outputPath = artifact.artifactPath;
569
+ if (options.outputFile) {
570
+ outputPath = path.resolve(targetPath, String(options.outputFile));
571
+ await fsp.mkdir(path.dirname(outputPath), { recursive: true });
572
+ await fsp.writeFile(outputPath, `${JSON.stringify(artifact.payload, null, 2)}\n`, "utf-8");
573
+ }
574
+
575
+ const payload = {
576
+ command: "review diff",
577
+ baseRunId: base.report.runId,
578
+ candidateRunId: candidate.report.runId,
579
+ deterministicEquivalent: comparison.deterministicEquivalent,
580
+ counts: comparison.counts,
581
+ summaryDelta: comparison.summaryDelta,
582
+ outputPath,
583
+ };
584
+
585
+ if (emitJson) {
586
+ console.log(JSON.stringify(payload, null, 2));
587
+ } else {
588
+ console.log(pc.bold("Review run diff complete"));
589
+ console.log(pc.gray(`Base: ${payload.baseRunId}`));
590
+ console.log(pc.gray(`Candidate: ${payload.candidateRunId}`));
591
+ console.log(pc.gray(`Output: ${payload.outputPath}`));
592
+ console.log(
593
+ `Delta: added=${payload.counts.added}, removed=${payload.counts.removed}, severity_changed=${payload.counts.severityChanged}`
594
+ );
595
+ }
596
+ });
597
+
598
+ registerVerdictCommand(review, "accept");
599
+ registerVerdictCommand(review, "reject");
600
+ registerVerdictCommand(review, "defer");
601
+
602
+ review
603
+ .command("scan")
604
+ .description("Compatibility mode: run lightweight policy scan")
605
+ .option("--mode <mode>", "Scan mode: full, diff, or staged", "full")
606
+ .option("--diff", "Alias for --mode diff")
607
+ .option("--staged", "Alias for --mode staged")
608
+ .option("--path <path>", "Target workspace path", ".")
609
+ .option("--spec <path>", "Spec file path relative to target (defaults to SPEC.md or docs/spec.md)")
610
+ .option("--output-dir <path>", "Optional artifact output root override")
611
+ .option("--refresh", "Refresh CODEBASE_INGEST prior to compatibility scan")
612
+ .option("--json", "Emit machine-readable output")
613
+ .action(async (options, command) => {
614
+ const emitJson = shouldEmitJson(options, command);
615
+ const targetPath = resolveTargetPath(".", options);
616
+ let ingestRefresh = null;
617
+ if (options.refresh) {
618
+ const ingestResolution = await resolveCodebaseIngest({
619
+ rootPath: targetPath,
620
+ outputDir: options.outputDir,
621
+ refresh: true,
622
+ });
623
+ ingestRefresh = {
624
+ outputPath: ingestResolution.outputPath,
625
+ refreshed: ingestResolution.refreshed,
626
+ stale: ingestResolution.stale,
627
+ reasons: ingestResolution.reasons,
628
+ refreshedBecause: ingestResolution.refreshedBecause,
629
+ lastCommitAt: ingestResolution.lastCommitAt,
630
+ contentHash: ingestResolution.fingerprint?.contentHash || "",
631
+ };
632
+ }
633
+ const mode = resolveModeFromOptions(options, {
634
+ defaultMode: String(options.mode || "full").trim().toLowerCase() || "full",
635
+ });
636
+ const scan = await runLocalReviewScan({
637
+ targetPath,
638
+ mode,
639
+ specFile: options.spec,
640
+ });
641
+
642
+ const report = `# Local Review Scan
643
+
644
+ Generated: ${new Date().toISOString()}
645
+ Target: ${scan.targetPath}
646
+ Mode: ${scan.mode}
647
+
648
+ Summary:
649
+ - Files scanned: ${scan.scannedFiles}
650
+ - P1 findings: ${scan.p1}
651
+ - P2 findings: ${scan.p2}
652
+
653
+ Scoped files:
654
+ ${scan.scannedRelativeFiles.length > 0 ? scan.scannedRelativeFiles.map((item) => `- ${item}`).join("\n") : "- none"}
655
+
656
+ Findings:
657
+ ${formatFindingsMarkdown(scan.findings)}
658
+ `;
659
+
660
+ const reportPath = await writeReviewReport({
661
+ targetPath: scan.targetPath,
662
+ mode: scan.mode,
663
+ outputDir: options.outputDir,
664
+ reportMarkdown: report,
665
+ });
666
+
667
+ const payload = {
668
+ command: "review scan",
669
+ targetPath: scan.targetPath,
670
+ mode: scan.mode,
671
+ reportPath,
672
+ scannedFiles: scan.scannedFiles,
673
+ scopedFiles: scan.scannedRelativeFiles,
674
+ specPath: scan.specBinding?.specPath || "",
675
+ specHashSha256: scan.specBinding?.specHashSha256 || "",
676
+ p1: scan.p1,
677
+ p2: scan.p2,
678
+ blocking: scan.p1 > 0,
679
+ ingestRefresh,
680
+ };
681
+
682
+ if (emitJson) {
683
+ console.log(JSON.stringify(payload, null, 2));
684
+ } else {
685
+ console.log(pc.bold("Local review scan complete"));
686
+ console.log(pc.gray(`Mode: ${scan.mode}`));
687
+ console.log(pc.gray(`Report: ${reportPath}`));
688
+ if (ingestRefresh) {
689
+ console.log(pc.gray(formatIngestResolutionNotice(ingestRefresh)));
690
+ }
691
+ console.log(`Files scanned: ${scan.scannedFiles}`);
692
+ console.log(`P1 findings: ${scan.p1}`);
693
+ console.log(`P2 findings: ${scan.p2}`);
694
+ }
695
+
696
+ if (scan.p1 > 0) {
697
+ if (!emitJson) {
698
+ console.log(pc.red("Blocking findings detected (P1 > 0)."));
699
+ }
700
+ process.exitCode = 2;
701
+ }
702
+ });
703
+ }
704
+