sentinelayer-cli 0.6.2 → 0.8.0

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 (159) hide show
  1. package/README.md +996 -996
  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 +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -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 +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  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 -137
  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 +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -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 +1171 -1166
  67. package/src/commands/auth.js +419 -419
  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 -29
  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 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
@@ -1,872 +1,872 @@
1
- import { spawnSync } from "node:child_process";
2
- import fs from "node:fs";
3
- import fsp from "node:fs/promises";
4
- import path from "node:path";
5
-
6
- import pc from "picocolors";
7
- import prompts from "prompts";
8
-
9
- import {
10
- createMultiProviderApiClient,
11
- resolveModel,
12
- resolveProvider,
13
- } from "../ai/client.js";
14
- import { loadConfig, resolveOutputRoot } from "../config/service.js";
15
- import { evaluateBudget } from "../cost/budget.js";
16
- import { appendCostEntry, summarizeCostHistory } from "../cost/history.js";
17
- import { estimateModelCost } from "../cost/tracker.js";
18
- import {
19
- applyPolicyPackToScanProfile,
20
- resolveActivePolicyPack,
21
- } from "../policy/packs.js";
22
- import {
23
- buildSecretSetupInstructions,
24
- buildSecurityReviewWorkflow,
25
- DEFAULT_SCAN_WORKFLOW_PATH,
26
- inferScanProfile,
27
- SUPPORTED_E2E_HINTS,
28
- SUPPORTED_PLAYWRIGHT_MODES,
29
- validateSecurityReviewWorkflow,
30
- } from "../scan/generator.js";
31
- import { detectRepoSlug, setupSecrets } from "../scan/gh-secrets.js";
32
- import { appendRunEvent, deriveStopClassFromBudget } from "../telemetry/ledger.js";
33
- import { resolveActiveAuthSession } from "../auth/service.js";
34
- import { authLoginHint } from "../ui/command-hints.js";
35
-
36
- const LEGACY_SCAN_WORKFLOW_PATH = ".github/workflows/security-review.yml";
37
-
38
- function shouldEmitJson(options, command) {
39
- const local = Boolean(options && options.json);
40
- const globalFromCommand =
41
- command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().json) : false;
42
- return local || globalFromCommand;
43
- }
44
-
45
- function resolveSpecPath(targetPath, explicitSpecFile) {
46
- const explicit = String(explicitSpecFile || "").trim();
47
- if (explicit) {
48
- return path.resolve(targetPath, explicit);
49
- }
50
-
51
- const candidates = [path.join(targetPath, "SPEC.md"), path.join(targetPath, "docs", "spec.md")];
52
- const found = candidates.find((candidate) => fs.existsSync(candidate));
53
- if (!found) {
54
- throw new Error("No spec file found. Provide --spec-file or generate SPEC.md first.");
55
- }
56
- return found;
57
- }
58
-
59
- function normalizeRepoSlug(value) {
60
- return String(value || "").trim().replace(/\.git$/i, "");
61
- }
62
-
63
- function parseRepoSlugFromRemote(remoteUrl) {
64
- const remote = String(remoteUrl || "").trim();
65
- if (!remote) {
66
- return "";
67
- }
68
-
69
- const sshMatch = remote.match(/^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/i);
70
- if (sshMatch) {
71
- return normalizeRepoSlug(`${sshMatch[1]}/${sshMatch[2]}`);
72
- }
73
-
74
- const httpsMatch = remote.match(/^https?:\/\/github\.com\/([^/]+)\/(.+?)(?:\.git)?$/i);
75
- if (httpsMatch) {
76
- return normalizeRepoSlug(`${httpsMatch[1]}/${httpsMatch[2]}`);
77
- }
78
-
79
- const sshUrlMatch = remote.match(/^ssh:\/\/git@github\.com\/([^/]+)\/(.+?)(?:\.git)?$/i);
80
- if (sshUrlMatch) {
81
- return normalizeRepoSlug(`${sshUrlMatch[1]}/${sshUrlMatch[2]}`);
82
- }
83
-
84
- return "";
85
- }
86
-
87
- function detectRepoSlugFromGit(targetPath) {
88
- const result = spawnSync("git", ["config", "--get", "remote.origin.url"], {
89
- cwd: targetPath,
90
- encoding: "utf-8",
91
- });
92
- if (result.status !== 0) {
93
- return "";
94
- }
95
- return parseRepoSlugFromRemote(result.stdout);
96
- }
97
-
98
- function resolveWorkflowPathForCommand({
99
- targetPath,
100
- explicitWorkflowFile = "",
101
- preferExistingLegacy = true,
102
- } = {}) {
103
- const explicit = String(explicitWorkflowFile || "").trim();
104
- if (explicit) {
105
- return {
106
- workflowFile: explicit,
107
- workflowPath: path.resolve(targetPath, explicit),
108
- };
109
- }
110
-
111
- const preferredWorkflowPath = path.resolve(targetPath, DEFAULT_SCAN_WORKFLOW_PATH);
112
- if (fs.existsSync(preferredWorkflowPath)) {
113
- return {
114
- workflowFile: DEFAULT_SCAN_WORKFLOW_PATH,
115
- workflowPath: preferredWorkflowPath,
116
- };
117
- }
118
-
119
- if (preferExistingLegacy) {
120
- const legacyWorkflowPath = path.resolve(targetPath, LEGACY_SCAN_WORKFLOW_PATH);
121
- if (fs.existsSync(legacyWorkflowPath)) {
122
- return {
123
- workflowFile: LEGACY_SCAN_WORKFLOW_PATH,
124
- workflowPath: legacyWorkflowPath,
125
- };
126
- }
127
- }
128
-
129
- return {
130
- workflowFile: DEFAULT_SCAN_WORKFLOW_PATH,
131
- workflowPath: preferredWorkflowPath,
132
- };
133
- }
134
-
135
- function normalizeE2EHint(rawValue) {
136
- const normalized = String(rawValue || "auto").trim().toLowerCase() || "auto";
137
- if (!SUPPORTED_E2E_HINTS.includes(normalized)) {
138
- throw new Error(
139
- `Invalid --has-e2e-tests value '${rawValue}'. Allowed: ${SUPPORTED_E2E_HINTS.join(", ")}`
140
- );
141
- }
142
- return normalized;
143
- }
144
-
145
- function normalizePlaywrightMode(rawValue) {
146
- const normalized = String(rawValue || "auto").trim().toLowerCase() || "auto";
147
- if (!SUPPORTED_PLAYWRIGHT_MODES.includes(normalized)) {
148
- throw new Error(
149
- `Invalid --playwright-mode value '${rawValue}'. Allowed: ${SUPPORTED_PLAYWRIGHT_MODES.join(", ")}`
150
- );
151
- }
152
- return normalized;
153
- }
154
-
155
- function parseNonNegativeNumber(rawValue, field) {
156
- const normalized = Number(rawValue || 0);
157
- if (!Number.isFinite(normalized) || normalized < 0) {
158
- throw new Error(`${field} must be a non-negative number.`);
159
- }
160
- return normalized;
161
- }
162
-
163
- function parsePercent(rawValue, field) {
164
- const normalized = Number(rawValue || 0);
165
- if (!Number.isFinite(normalized) || normalized < 0 || normalized > 100) {
166
- throw new Error(`${field} must be between 0 and 100.`);
167
- }
168
- return normalized;
169
- }
170
-
171
- function estimateTokenCount(text) {
172
- const normalized = String(text || "");
173
- if (!normalized) {
174
- return 0;
175
- }
176
- return Math.max(1, Math.ceil(normalized.length / 4));
177
- }
178
-
179
- function resolveConfiguredApiKey(provider, resolvedConfig = {}) {
180
- const normalizedProvider = String(provider || "").trim().toLowerCase();
181
- if (normalizedProvider === "openai") {
182
- return String(resolvedConfig.openaiApiKey || "").trim();
183
- }
184
- if (normalizedProvider === "anthropic") {
185
- return String(resolvedConfig.anthropicApiKey || "").trim();
186
- }
187
- if (normalizedProvider === "google") {
188
- return String(resolvedConfig.googleApiKey || "").trim();
189
- }
190
- return "";
191
- }
192
-
193
- function maybeEstimateModelCost({ modelId, inputTokens, outputTokens }) {
194
- try {
195
- return {
196
- costUsd: estimateModelCost({
197
- modelId,
198
- inputTokens,
199
- outputTokens,
200
- }),
201
- pricingFound: true,
202
- };
203
- } catch {
204
- return {
205
- costUsd: 0,
206
- pricingFound: false,
207
- };
208
- }
209
- }
210
-
211
- function createTimestampToken() {
212
- return new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-");
213
- }
214
-
215
- async function maybePromptForE2EChoice({ inferredHasE2E, hasE2ETests, nonInteractive }) {
216
- if (hasE2ETests !== "auto") {
217
- return hasE2ETests;
218
- }
219
- if (nonInteractive || !process.stdin.isTTY || !process.stdout.isTTY) {
220
- return hasE2ETests;
221
- }
222
-
223
- const answer = await prompts({
224
- type: "toggle",
225
- name: "hasE2ETests",
226
- message: "Do you have E2E tests in this repository?",
227
- initial: inferredHasE2E ? 1 : 0,
228
- active: "yes",
229
- inactive: "no",
230
- });
231
-
232
- if (!Object.prototype.hasOwnProperty.call(answer, "hasE2ETests")) {
233
- throw new Error("Scan init cancelled.");
234
- }
235
- return answer.hasE2ETests ? "yes" : "no";
236
- }
237
-
238
- function buildAiPreScanPrompt({
239
- targetPath,
240
- specMarkdown,
241
- profile,
242
- } = {}) {
243
- return [
244
- "You are a senior application security reviewer preparing a pre-scan triage report.",
245
- "Return markdown only with the following sections:",
246
- "1. Executive Summary",
247
- "2. Predicted P0 Findings",
248
- "3. Predicted P1 Findings",
249
- "4. Predicted P2 Findings",
250
- "5. Recommended Omar Gate Focus Areas",
251
- "6. Test and Evidence Plan",
252
- "Use concise, actionable bullets and map findings to likely folders/files when possible.",
253
- "",
254
- `Workspace: ${targetPath}`,
255
- `scan_mode=${profile.scanMode}`,
256
- `severity_gate=${profile.severityGate}`,
257
- `playwright_mode=${profile.playwrightMode}`,
258
- `sbom_mode=${profile.sbomMode}`,
259
- "",
260
- "Source spec markdown:",
261
- specMarkdown,
262
- ].join("\n");
263
- }
264
-
265
- function buildPreScanReportMarkdown({
266
- generatedAt,
267
- specPath,
268
- profile,
269
- provider,
270
- model,
271
- aiMarkdown,
272
- } = {}) {
273
- return [
274
- "# AI PRE-SCAN REPORT",
275
- "",
276
- `Generated: ${generatedAt}`,
277
- `Spec: ${specPath}`,
278
- `Provider: ${provider}`,
279
- `Model: ${model}`,
280
- "",
281
- "## Derived Scan Profile",
282
- `- scan_mode: ${profile.scanMode}`,
283
- `- severity_gate: ${profile.severityGate}`,
284
- `- playwright_mode: ${profile.playwrightMode}`,
285
- `- sbom_mode: ${profile.sbomMode}`,
286
- "",
287
- "## AI Review",
288
- String(aiMarkdown || "").trim() || "_No AI output returned._",
289
- "",
290
- ].join("\n");
291
- }
292
-
293
- async function resolvePreScanReportPath({
294
- targetPath,
295
- outputDirOverride,
296
- outputFile,
297
- } = {}) {
298
- const explicit = String(outputFile || "").trim();
299
- if (explicit) {
300
- return path.resolve(targetPath, explicit);
301
- }
302
-
303
- const outputRoot = await resolveOutputRoot({
304
- cwd: targetPath,
305
- outputDirOverride,
306
- env: process.env,
307
- });
308
- return path.join(outputRoot, "reports", `scan-precheck-${createTimestampToken()}.md`);
309
- }
310
-
311
- function printAiPreScanSummary({ reportPath, ai }) {
312
- console.log(pc.bold("AI pre-scan report generated"));
313
- console.log(pc.gray(`Report: ${reportPath}`));
314
- console.log(pc.gray(`Provider: ${ai.provider}, Model: ${ai.model}`));
315
- console.log(
316
- pc.gray(
317
- `Input tokens=${ai.usage.inputTokens}, Output tokens=${ai.usage.outputTokens}, Cost=$${ai.usage.costUsd.toFixed(6)}, DurationMs=${ai.usage.durationMs}`
318
- )
319
- );
320
- if (!ai.pricingFound) {
321
- console.log(pc.yellow("Model pricing missing from local table; cost recorded as 0."));
322
- }
323
- if (ai.budget.blocking) {
324
- console.log(pc.red("AI budget guardrail triggered:"));
325
- for (const reason of ai.budget.reasons) {
326
- console.log(`- ${reason.code}: ${reason.message}`);
327
- }
328
- } else if (ai.budget.warnings.length > 0) {
329
- console.log(pc.yellow("AI budget warning threshold reached:"));
330
- for (const warning of ai.budget.warnings) {
331
- console.log(`- ${warning.code}: ${warning.message}`);
332
- }
333
- }
334
- }
335
-
336
- export function registerScanCommand(program) {
337
- const scan = program.command("scan").description("Generate and validate Omar Gate workflow config");
338
-
339
- scan
340
- .command("init")
341
- .description("Generate .github/workflows/omar-gate.yml from spec context")
342
- .option("--path <path>", "Target workspace path", ".")
343
- .option("--spec-file <path>", "Spec file path relative to --path")
344
- .option("--workflow-file <path>", "Workflow output path relative to --path")
345
- .option(
346
- "--secret-name <name>",
347
- "GitHub Actions secret name for sentinelayer_token",
348
- "SENTINELAYER_TOKEN"
349
- )
350
- .option(
351
- "--has-e2e-tests <mode>",
352
- `E2E hint (${SUPPORTED_E2E_HINTS.join("|")})`,
353
- "auto"
354
- )
355
- .option(
356
- "--playwright-mode <mode>",
357
- `Playwright override (${SUPPORTED_PLAYWRIGHT_MODES.join("|")})`,
358
- "auto"
359
- )
360
- .option("--non-interactive", "Disable wizard prompts and rely on deterministic inference")
361
- .option("--json", "Emit machine-readable output")
362
- .action(async (options, command) => {
363
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
364
- const workflowTarget = resolveWorkflowPathForCommand({
365
- targetPath,
366
- explicitWorkflowFile: options.workflowFile,
367
- preferExistingLegacy: true,
368
- });
369
- const workflowFile = workflowTarget.workflowFile;
370
- const workflowPath = workflowTarget.workflowPath;
371
- const specPath = resolveSpecPath(targetPath, options.specFile);
372
- const specMarkdown = await fsp.readFile(specPath, "utf-8");
373
-
374
- const hasE2EHint = normalizeE2EHint(options.hasE2eTests);
375
- const playwrightMode = normalizePlaywrightMode(options.playwrightMode);
376
- const nonInteractive = Boolean(options.nonInteractive);
377
- const activePolicy = await resolveActivePolicyPack({
378
- cwd: targetPath,
379
- env: process.env,
380
- });
381
-
382
- const initialProfile = inferScanProfile({
383
- specMarkdown,
384
- hasE2ETests: hasE2EHint,
385
- playwrightMode,
386
- });
387
- const resolvedE2EHint = await maybePromptForE2EChoice({
388
- inferredHasE2E: initialProfile.inferredHasE2E,
389
- hasE2ETests: hasE2EHint,
390
- nonInteractive,
391
- });
392
-
393
- const profile = inferScanProfile({
394
- specMarkdown,
395
- hasE2ETests: resolvedE2EHint,
396
- playwrightMode,
397
- });
398
- const appliedProfile = applyPolicyPackToScanProfile(profile, activePolicy.selected);
399
- const workflowMarkdown = buildSecurityReviewWorkflow({
400
- secretName: options.secretName,
401
- profile: appliedProfile,
402
- });
403
-
404
- await fsp.mkdir(path.dirname(workflowPath), { recursive: true });
405
- await fsp.writeFile(workflowPath, workflowMarkdown, "utf-8");
406
-
407
- const instructions = buildSecretSetupInstructions(options.secretName, {
408
- repoSlug: detectRepoSlugFromGit(targetPath),
409
- });
410
- const payload = {
411
- command: "scan init",
412
- targetPath,
413
- specPath,
414
- workflowPath,
415
- profile: appliedProfile,
416
- policyPack: activePolicy.selected
417
- ? {
418
- id: activePolicy.selected.id,
419
- source: activePolicy.selected.source,
420
- }
421
- : null,
422
- instructions,
423
- };
424
-
425
- if (shouldEmitJson(options, command)) {
426
- console.log(JSON.stringify(payload, null, 2));
427
- return;
428
- }
429
-
430
- console.log(pc.bold("Security review workflow generated"));
431
- console.log(pc.gray(`Spec: ${specPath}`));
432
- console.log(pc.gray(`Workflow: ${workflowPath}`));
433
- console.log(
434
- pc.gray(`scan_mode=${appliedProfile.scanMode}, severity_gate=${appliedProfile.severityGate}`)
435
- );
436
- console.log(
437
- pc.gray(
438
- `playwright_mode=${appliedProfile.playwrightMode}, sbom_mode=${appliedProfile.sbomMode}`
439
- )
440
- );
441
- if (activePolicy.selected) {
442
- console.log(pc.gray(`policy_pack=${activePolicy.selected.id} (${activePolicy.selected.source})`));
443
- }
444
- instructions.forEach((line) => console.log(line));
445
- });
446
-
447
- scan
448
- .command("validate")
449
- .description("Validate existing Omar Gate workflow against current spec profile")
450
- .option("--path <path>", "Target workspace path", ".")
451
- .option("--spec-file <path>", "Spec file path relative to --path")
452
- .option("--workflow-file <path>", "Workflow file path relative to --path")
453
- .option("--secret-name <name>", "Expected GitHub Actions secret name", "SENTINELAYER_TOKEN")
454
- .option(
455
- "--has-e2e-tests <mode>",
456
- `E2E hint (${SUPPORTED_E2E_HINTS.join("|")})`,
457
- "auto"
458
- )
459
- .option(
460
- "--playwright-mode <mode>",
461
- `Playwright override (${SUPPORTED_PLAYWRIGHT_MODES.join("|")})`,
462
- "auto"
463
- )
464
- .option("--json", "Emit machine-readable output")
465
- .action(async (options, command) => {
466
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
467
- const specPath = resolveSpecPath(targetPath, options.specFile);
468
- const workflowPath = resolveWorkflowPathForCommand({
469
- targetPath,
470
- explicitWorkflowFile: options.workflowFile,
471
- preferExistingLegacy: true,
472
- }).workflowPath;
473
-
474
- const specMarkdown = await fsp.readFile(specPath, "utf-8");
475
- const workflowMarkdown = await fsp.readFile(workflowPath, "utf-8");
476
- const activePolicy = await resolveActivePolicyPack({
477
- cwd: targetPath,
478
- env: process.env,
479
- });
480
- const inferredProfile = inferScanProfile({
481
- specMarkdown,
482
- hasE2ETests: normalizeE2EHint(options.hasE2eTests),
483
- playwrightMode: normalizePlaywrightMode(options.playwrightMode),
484
- });
485
- const expectedProfile = applyPolicyPackToScanProfile(inferredProfile, activePolicy.selected);
486
-
487
- const validation = validateSecurityReviewWorkflow({
488
- workflowMarkdown,
489
- expectedProfile,
490
- expectedSecretName: options.secretName,
491
- });
492
-
493
- const payload = {
494
- command: "scan validate",
495
- targetPath,
496
- specPath,
497
- workflowPath,
498
- aligned: validation.aligned,
499
- expected: validation.expected,
500
- actual: validation.actual,
501
- mismatches: validation.mismatches,
502
- policyPack: activePolicy.selected
503
- ? {
504
- id: activePolicy.selected.id,
505
- source: activePolicy.selected.source,
506
- }
507
- : null,
508
- };
509
-
510
- if (shouldEmitJson(options, command)) {
511
- console.log(JSON.stringify(payload, null, 2));
512
- } else if (validation.aligned) {
513
- console.log(pc.bold("Security review workflow matches spec profile."));
514
- console.log(pc.gray(`Workflow: ${workflowPath}`));
515
- } else {
516
- console.log(pc.red("Security review workflow drift detected."));
517
- console.log(pc.gray(`Workflow: ${workflowPath}`));
518
- validation.mismatches.forEach((item, index) => {
519
- console.log(
520
- `${index + 1}. ${item.field}: expected '${item.expected}' but found '${item.actual}'.`
521
- );
522
- });
523
- }
524
-
525
- if (!validation.aligned) {
526
- process.exitCode = 2;
527
- }
528
- });
529
-
530
- scan
531
- .command("precheck")
532
- .description("Run AI pre-scan triage from spec context and emit a review-ready report")
533
- .option("--path <path>", "Target workspace path", ".")
534
- .option("--spec-file <path>", "Spec file path relative to --path")
535
- .option("--output-file <path>", "Report output path relative to --path")
536
- .option("--output-dir <path>", "Optional output dir override for report/cost/telemetry artifacts")
537
- .option(
538
- "--has-e2e-tests <mode>",
539
- `E2E hint (${SUPPORTED_E2E_HINTS.join("|")})`,
540
- "auto"
541
- )
542
- .option(
543
- "--playwright-mode <mode>",
544
- `Playwright override (${SUPPORTED_PLAYWRIGHT_MODES.join("|")})`,
545
- "auto"
546
- )
547
- .option("--provider <name>", "AI provider override (openai|anthropic|google)")
548
- .option("--model <id>", "AI model override")
549
- .option("--api-key <key>", "Optional explicit API key override")
550
- .option("--session-id <id>", "Cost/telemetry session id", "scan-ai-precheck")
551
- .option("--max-cost <usd>", "Max AI cost budget per session", "0.5")
552
- .option("--max-tokens <n>", "Max output token budget per session (0 = disabled)", "0")
553
- .option("--max-runtime-ms <n>", "Max runtime budget per session in milliseconds (0 = disabled)", "0")
554
- .option("--max-tool-calls <n>", "Max tool-call budget per session (0 = disabled)", "0")
555
- .option("--max-no-progress <n>", "Max consecutive no-progress events before stop", "3")
556
- .option("--warn-at-percent <n>", "Warning threshold percentage for enabled budgets", "80")
557
- .option("--json", "Emit machine-readable output")
558
- .action(async (options, command) => {
559
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
560
- const specPath = resolveSpecPath(targetPath, options.specFile);
561
- const specMarkdown = await fsp.readFile(specPath, "utf-8");
562
- const activePolicy = await resolveActivePolicyPack({
563
- cwd: targetPath,
564
- env: process.env,
565
- });
566
- const profile = applyPolicyPackToScanProfile(
567
- inferScanProfile({
568
- specMarkdown,
569
- hasE2ETests: normalizeE2EHint(options.hasE2eTests),
570
- playwrightMode: normalizePlaywrightMode(options.playwrightMode),
571
- }),
572
- activePolicy.selected
573
- );
574
-
575
- const config = await loadConfig({ cwd: targetPath });
576
- const resolvedProvider = resolveProvider({
577
- provider: options.provider,
578
- configProvider: config.resolved.defaultModelProvider,
579
- env: process.env,
580
- });
581
- const resolvedModel = resolveModel({
582
- provider: resolvedProvider,
583
- model: options.model,
584
- configModel: config.resolved.defaultModelId,
585
- });
586
- const explicitApiKey = String(options.apiKey || "").trim();
587
- const configuredApiKey = resolveConfiguredApiKey(resolvedProvider, config.resolved);
588
-
589
- const prompt = buildAiPreScanPrompt({
590
- targetPath,
591
- specMarkdown,
592
- profile,
593
- });
594
-
595
- const startedAtMs = Date.now();
596
- const client = createMultiProviderApiClient();
597
- const response = await client.invoke({
598
- provider: resolvedProvider,
599
- model: resolvedModel,
600
- prompt,
601
- apiKey: explicitApiKey || configuredApiKey,
602
- env: process.env,
603
- stream: false,
604
- });
605
- const durationMs = Math.max(0, Date.now() - startedAtMs);
606
- const aiMarkdown = String(response.text || "").trim();
607
- const generatedAt = new Date().toISOString();
608
-
609
- const reportMarkdown = buildPreScanReportMarkdown({
610
- generatedAt,
611
- specPath,
612
- profile,
613
- provider: response.provider,
614
- model: response.model,
615
- aiMarkdown,
616
- });
617
- const reportPath = await resolvePreScanReportPath({
618
- targetPath,
619
- outputDirOverride: options.outputDir,
620
- outputFile: options.outputFile,
621
- });
622
- await fsp.mkdir(path.dirname(reportPath), { recursive: true });
623
- await fsp.writeFile(reportPath, reportMarkdown, "utf-8");
624
-
625
- const inputTokens = estimateTokenCount(prompt);
626
- const outputTokens = estimateTokenCount(aiMarkdown);
627
- const modelCost = maybeEstimateModelCost({
628
- modelId: response.model,
629
- inputTokens,
630
- outputTokens,
631
- });
632
- const sessionId = String(options.sessionId || "scan-ai-precheck").trim() || "scan-ai-precheck";
633
-
634
- const appendedCost = await appendCostEntry(
635
- {
636
- targetPath,
637
- outputDirOverride: options.outputDir,
638
- },
639
- {
640
- sessionId,
641
- provider: response.provider,
642
- model: response.model,
643
- inputTokens,
644
- outputTokens,
645
- cacheReadTokens: 0,
646
- cacheWriteTokens: 0,
647
- durationMs,
648
- toolCalls: 1,
649
- costUsd: modelCost.costUsd,
650
- progressScore: aiMarkdown ? 1 : 0,
651
- }
652
- );
653
-
654
- const costSummary = summarizeCostHistory(appendedCost.history);
655
- const sessionSummary = costSummary.sessions.find((item) => item.sessionId === sessionId) || {
656
- sessionId,
657
- invocationCount: 0,
658
- inputTokens: 0,
659
- outputTokens: 0,
660
- cacheReadTokens: 0,
661
- cacheWriteTokens: 0,
662
- durationMs: 0,
663
- toolCalls: 0,
664
- costUsd: 0,
665
- noProgressStreak: 0,
666
- };
667
-
668
- const budget = evaluateBudget({
669
- sessionSummary,
670
- maxCostUsd: parseNonNegativeNumber(options.maxCost, "maxCost"),
671
- maxOutputTokens: parseNonNegativeNumber(options.maxTokens, "maxTokens"),
672
- maxNoProgress: parseNonNegativeNumber(options.maxNoProgress, "maxNoProgress"),
673
- maxRuntimeMs: parseNonNegativeNumber(options.maxRuntimeMs, "maxRuntimeMs"),
674
- maxToolCalls: parseNonNegativeNumber(options.maxToolCalls, "maxToolCalls"),
675
- warningThresholdPercent: parsePercent(options.warnAtPercent, "warnAtPercent"),
676
- });
677
-
678
- const usageTelemetry = await appendRunEvent(
679
- {
680
- targetPath,
681
- outputDirOverride: options.outputDir,
682
- },
683
- {
684
- sessionId,
685
- runId: sessionId,
686
- eventType: "usage",
687
- usage: {
688
- inputTokens,
689
- outputTokens,
690
- cacheReadTokens: 0,
691
- cacheWriteTokens: 0,
692
- costUsd: modelCost.costUsd,
693
- durationMs,
694
- toolCalls: 1,
695
- },
696
- metadata: {
697
- sourceCommand: "scan precheck",
698
- provider: response.provider,
699
- model: response.model,
700
- invocationId: appendedCost.entry.invocationId,
701
- },
702
- }
703
- );
704
-
705
- let stopTelemetry = null;
706
- if (budget.blocking) {
707
- stopTelemetry = await appendRunEvent(
708
- {
709
- targetPath,
710
- outputDirOverride: options.outputDir,
711
- },
712
- {
713
- sessionId,
714
- runId: sessionId,
715
- eventType: "run_stop",
716
- usage: {
717
- inputTokens: sessionSummary.inputTokens,
718
- outputTokens: sessionSummary.outputTokens,
719
- cacheReadTokens: sessionSummary.cacheReadTokens,
720
- cacheWriteTokens: sessionSummary.cacheWriteTokens,
721
- costUsd: sessionSummary.costUsd,
722
- durationMs: sessionSummary.durationMs,
723
- toolCalls: sessionSummary.toolCalls,
724
- },
725
- stop: {
726
- stopClass: deriveStopClassFromBudget(budget),
727
- blocking: true,
728
- reasonCodes: budget.reasons.map((reason) => reason.code),
729
- },
730
- metadata: {
731
- sourceCommand: "scan precheck",
732
- provider: response.provider,
733
- model: response.model,
734
- invocationId: appendedCost.entry.invocationId,
735
- },
736
- }
737
- );
738
- }
739
-
740
- const payload = {
741
- command: "scan precheck",
742
- targetPath,
743
- specPath,
744
- reportPath,
745
- profile,
746
- policyPack: activePolicy.selected
747
- ? {
748
- id: activePolicy.selected.id,
749
- source: activePolicy.selected.source,
750
- }
751
- : null,
752
- ai: {
753
- provider: response.provider,
754
- model: response.model,
755
- pricingFound: modelCost.pricingFound,
756
- usage: {
757
- inputTokens,
758
- outputTokens,
759
- costUsd: modelCost.costUsd,
760
- durationMs,
761
- toolCalls: 1,
762
- },
763
- budget,
764
- cost: {
765
- filePath: appendedCost.filePath,
766
- invocationId: appendedCost.entry.invocationId,
767
- sessionId,
768
- },
769
- telemetry: {
770
- filePath: usageTelemetry.filePath,
771
- usageEventId: usageTelemetry.event.eventId,
772
- stopEventId: stopTelemetry?.event?.eventId || null,
773
- },
774
- },
775
- };
776
-
777
- if (shouldEmitJson(options, command)) {
778
- console.log(JSON.stringify(payload, null, 2));
779
- } else {
780
- printAiPreScanSummary({
781
- reportPath,
782
- ai: payload.ai,
783
- });
784
- }
785
-
786
- if (budget.blocking) {
787
- process.exitCode = 2;
788
- }
789
- });
790
-
791
- scan
792
- .command("setup-secrets")
793
- .description("Set up required GitHub secrets for Omar Gate workflow")
794
- .option("--path <path>", "Target workspace path", ".")
795
- .option("--secret-name <name>", "GitHub secret name", "SENTINELAYER_TOKEN")
796
- .option("--repo <slug>", "Repo slug override (owner/repo)")
797
- .option("--dry-run", "Print instructions without executing")
798
- .option("--json", "Emit machine-readable output")
799
- .action(async (options, command) => {
800
- const emitJson = shouldEmitJson(options, command);
801
- const targetPath = path.resolve(process.cwd(), String(options.path || "."));
802
- const secretName = String(options.secretName || "SENTINELAYER_TOKEN").trim();
803
- let repoSlug = String(options.repo || "").trim();
804
-
805
- if (!repoSlug) {
806
- repoSlug = detectRepoSlug(targetPath) || "";
807
- }
808
- if (!repoSlug) {
809
- const msg = "Could not detect repo slug. Use --repo owner/name or run from a GitHub-connected repo.";
810
- if (emitJson) {
811
- console.log(JSON.stringify({ command: "scan setup-secrets", ok: false, reason: msg }, null, 2));
812
- } else {
813
- console.error(pc.red(msg));
814
- }
815
- process.exitCode = 1;
816
- return;
817
- }
818
-
819
- if (options.dryRun) {
820
- const result = setupSecrets({ repoSlug, secretName, secretValue: "<token>", dryRun: true });
821
- const payload = { command: "scan setup-secrets", ...result };
822
- if (emitJson) {
823
- console.log(JSON.stringify(payload, null, 2));
824
- } else {
825
- console.log(pc.bold(`Setup secrets for ${repoSlug}`));
826
- console.log(pc.gray("Run these commands:"));
827
- for (const line of result.instructions || []) {
828
- console.log(` ${line}`);
829
- }
830
- }
831
- return;
832
- }
833
-
834
- let tokenValue = "";
835
- try {
836
- const session = await resolveActiveAuthSession({
837
- cwd: targetPath,
838
- env: process.env,
839
- autoRotate: false,
840
- });
841
- if (session && session.token) {
842
- tokenValue = session.token;
843
- }
844
- } catch {
845
- /* no active auth session */
846
- }
847
-
848
- if (!tokenValue) {
849
- const msg =
850
- `No SentinelLayer token found. Run '${authLoginHint()}', set SENTINELAYER_TOKEN, or use --dry-run for instructions.`;
851
- if (emitJson) {
852
- console.log(JSON.stringify({ command: "scan setup-secrets", ok: false, reason: msg }, null, 2));
853
- } else {
854
- console.error(pc.red(msg));
855
- }
856
- process.exitCode = 1;
857
- return;
858
- }
859
-
860
- const result = setupSecrets({ repoSlug, secretName, secretValue: tokenValue, dryRun: false });
861
- const payload = { command: "scan setup-secrets", ...result };
862
- if (emitJson) {
863
- console.log(JSON.stringify(payload, null, 2));
864
- } else if (result.ok) {
865
- console.log(pc.green(`Secret '${secretName}' set on ${repoSlug}`));
866
- } else {
867
- console.error(pc.red(`Failed: ${result.reason}`));
868
- process.exitCode = 1;
869
- }
870
- });
871
- }
872
-
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import fsp from "node:fs/promises";
4
+ import path from "node:path";
5
+
6
+ import pc from "picocolors";
7
+ import prompts from "prompts";
8
+
9
+ import {
10
+ createMultiProviderApiClient,
11
+ resolveModel,
12
+ resolveProvider,
13
+ } from "../ai/client.js";
14
+ import { loadConfig, resolveOutputRoot } from "../config/service.js";
15
+ import { evaluateBudget } from "../cost/budget.js";
16
+ import { appendCostEntry, summarizeCostHistory } from "../cost/history.js";
17
+ import { estimateModelCost } from "../cost/tracker.js";
18
+ import {
19
+ applyPolicyPackToScanProfile,
20
+ resolveActivePolicyPack,
21
+ } from "../policy/packs.js";
22
+ import {
23
+ buildSecretSetupInstructions,
24
+ buildSecurityReviewWorkflow,
25
+ DEFAULT_SCAN_WORKFLOW_PATH,
26
+ inferScanProfile,
27
+ SUPPORTED_E2E_HINTS,
28
+ SUPPORTED_PLAYWRIGHT_MODES,
29
+ validateSecurityReviewWorkflow,
30
+ } from "../scan/generator.js";
31
+ import { detectRepoSlug, setupSecrets } from "../scan/gh-secrets.js";
32
+ import { appendRunEvent, deriveStopClassFromBudget } from "../telemetry/ledger.js";
33
+ import { resolveActiveAuthSession } from "../auth/service.js";
34
+ import { authLoginHint } from "../ui/command-hints.js";
35
+
36
+ const LEGACY_SCAN_WORKFLOW_PATH = ".github/workflows/security-review.yml";
37
+
38
+ function shouldEmitJson(options, command) {
39
+ const local = Boolean(options && options.json);
40
+ const globalFromCommand =
41
+ command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().json) : false;
42
+ return local || globalFromCommand;
43
+ }
44
+
45
+ function resolveSpecPath(targetPath, explicitSpecFile) {
46
+ const explicit = String(explicitSpecFile || "").trim();
47
+ if (explicit) {
48
+ return path.resolve(targetPath, explicit);
49
+ }
50
+
51
+ const candidates = [path.join(targetPath, "SPEC.md"), path.join(targetPath, "docs", "spec.md")];
52
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
53
+ if (!found) {
54
+ throw new Error("No spec file found. Provide --spec-file or generate SPEC.md first.");
55
+ }
56
+ return found;
57
+ }
58
+
59
+ function normalizeRepoSlug(value) {
60
+ return String(value || "").trim().replace(/\.git$/i, "");
61
+ }
62
+
63
+ function parseRepoSlugFromRemote(remoteUrl) {
64
+ const remote = String(remoteUrl || "").trim();
65
+ if (!remote) {
66
+ return "";
67
+ }
68
+
69
+ const sshMatch = remote.match(/^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/i);
70
+ if (sshMatch) {
71
+ return normalizeRepoSlug(`${sshMatch[1]}/${sshMatch[2]}`);
72
+ }
73
+
74
+ const httpsMatch = remote.match(/^https?:\/\/github\.com\/([^/]+)\/(.+?)(?:\.git)?$/i);
75
+ if (httpsMatch) {
76
+ return normalizeRepoSlug(`${httpsMatch[1]}/${httpsMatch[2]}`);
77
+ }
78
+
79
+ const sshUrlMatch = remote.match(/^ssh:\/\/git@github\.com\/([^/]+)\/(.+?)(?:\.git)?$/i);
80
+ if (sshUrlMatch) {
81
+ return normalizeRepoSlug(`${sshUrlMatch[1]}/${sshUrlMatch[2]}`);
82
+ }
83
+
84
+ return "";
85
+ }
86
+
87
+ function detectRepoSlugFromGit(targetPath) {
88
+ const result = spawnSync("git", ["config", "--get", "remote.origin.url"], {
89
+ cwd: targetPath,
90
+ encoding: "utf-8",
91
+ });
92
+ if (result.status !== 0) {
93
+ return "";
94
+ }
95
+ return parseRepoSlugFromRemote(result.stdout);
96
+ }
97
+
98
+ function resolveWorkflowPathForCommand({
99
+ targetPath,
100
+ explicitWorkflowFile = "",
101
+ preferExistingLegacy = true,
102
+ } = {}) {
103
+ const explicit = String(explicitWorkflowFile || "").trim();
104
+ if (explicit) {
105
+ return {
106
+ workflowFile: explicit,
107
+ workflowPath: path.resolve(targetPath, explicit),
108
+ };
109
+ }
110
+
111
+ const preferredWorkflowPath = path.resolve(targetPath, DEFAULT_SCAN_WORKFLOW_PATH);
112
+ if (fs.existsSync(preferredWorkflowPath)) {
113
+ return {
114
+ workflowFile: DEFAULT_SCAN_WORKFLOW_PATH,
115
+ workflowPath: preferredWorkflowPath,
116
+ };
117
+ }
118
+
119
+ if (preferExistingLegacy) {
120
+ const legacyWorkflowPath = path.resolve(targetPath, LEGACY_SCAN_WORKFLOW_PATH);
121
+ if (fs.existsSync(legacyWorkflowPath)) {
122
+ return {
123
+ workflowFile: LEGACY_SCAN_WORKFLOW_PATH,
124
+ workflowPath: legacyWorkflowPath,
125
+ };
126
+ }
127
+ }
128
+
129
+ return {
130
+ workflowFile: DEFAULT_SCAN_WORKFLOW_PATH,
131
+ workflowPath: preferredWorkflowPath,
132
+ };
133
+ }
134
+
135
+ function normalizeE2EHint(rawValue) {
136
+ const normalized = String(rawValue || "auto").trim().toLowerCase() || "auto";
137
+ if (!SUPPORTED_E2E_HINTS.includes(normalized)) {
138
+ throw new Error(
139
+ `Invalid --has-e2e-tests value '${rawValue}'. Allowed: ${SUPPORTED_E2E_HINTS.join(", ")}`
140
+ );
141
+ }
142
+ return normalized;
143
+ }
144
+
145
+ function normalizePlaywrightMode(rawValue) {
146
+ const normalized = String(rawValue || "auto").trim().toLowerCase() || "auto";
147
+ if (!SUPPORTED_PLAYWRIGHT_MODES.includes(normalized)) {
148
+ throw new Error(
149
+ `Invalid --playwright-mode value '${rawValue}'. Allowed: ${SUPPORTED_PLAYWRIGHT_MODES.join(", ")}`
150
+ );
151
+ }
152
+ return normalized;
153
+ }
154
+
155
+ function parseNonNegativeNumber(rawValue, field) {
156
+ const normalized = Number(rawValue || 0);
157
+ if (!Number.isFinite(normalized) || normalized < 0) {
158
+ throw new Error(`${field} must be a non-negative number.`);
159
+ }
160
+ return normalized;
161
+ }
162
+
163
+ function parsePercent(rawValue, field) {
164
+ const normalized = Number(rawValue || 0);
165
+ if (!Number.isFinite(normalized) || normalized < 0 || normalized > 100) {
166
+ throw new Error(`${field} must be between 0 and 100.`);
167
+ }
168
+ return normalized;
169
+ }
170
+
171
+ function estimateTokenCount(text) {
172
+ const normalized = String(text || "");
173
+ if (!normalized) {
174
+ return 0;
175
+ }
176
+ return Math.max(1, Math.ceil(normalized.length / 4));
177
+ }
178
+
179
+ function resolveConfiguredApiKey(provider, resolvedConfig = {}) {
180
+ const normalizedProvider = String(provider || "").trim().toLowerCase();
181
+ if (normalizedProvider === "openai") {
182
+ return String(resolvedConfig.openaiApiKey || "").trim();
183
+ }
184
+ if (normalizedProvider === "anthropic") {
185
+ return String(resolvedConfig.anthropicApiKey || "").trim();
186
+ }
187
+ if (normalizedProvider === "google") {
188
+ return String(resolvedConfig.googleApiKey || "").trim();
189
+ }
190
+ return "";
191
+ }
192
+
193
+ function maybeEstimateModelCost({ modelId, inputTokens, outputTokens }) {
194
+ try {
195
+ return {
196
+ costUsd: estimateModelCost({
197
+ modelId,
198
+ inputTokens,
199
+ outputTokens,
200
+ }),
201
+ pricingFound: true,
202
+ };
203
+ } catch {
204
+ return {
205
+ costUsd: 0,
206
+ pricingFound: false,
207
+ };
208
+ }
209
+ }
210
+
211
+ function createTimestampToken() {
212
+ return new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-");
213
+ }
214
+
215
+ async function maybePromptForE2EChoice({ inferredHasE2E, hasE2ETests, nonInteractive }) {
216
+ if (hasE2ETests !== "auto") {
217
+ return hasE2ETests;
218
+ }
219
+ if (nonInteractive || !process.stdin.isTTY || !process.stdout.isTTY) {
220
+ return hasE2ETests;
221
+ }
222
+
223
+ const answer = await prompts({
224
+ type: "toggle",
225
+ name: "hasE2ETests",
226
+ message: "Do you have E2E tests in this repository?",
227
+ initial: inferredHasE2E ? 1 : 0,
228
+ active: "yes",
229
+ inactive: "no",
230
+ });
231
+
232
+ if (!Object.prototype.hasOwnProperty.call(answer, "hasE2ETests")) {
233
+ throw new Error("Scan init cancelled.");
234
+ }
235
+ return answer.hasE2ETests ? "yes" : "no";
236
+ }
237
+
238
+ function buildAiPreScanPrompt({
239
+ targetPath,
240
+ specMarkdown,
241
+ profile,
242
+ } = {}) {
243
+ return [
244
+ "You are a senior application security reviewer preparing a pre-scan triage report.",
245
+ "Return markdown only with the following sections:",
246
+ "1. Executive Summary",
247
+ "2. Predicted P0 Findings",
248
+ "3. Predicted P1 Findings",
249
+ "4. Predicted P2 Findings",
250
+ "5. Recommended Omar Gate Focus Areas",
251
+ "6. Test and Evidence Plan",
252
+ "Use concise, actionable bullets and map findings to likely folders/files when possible.",
253
+ "",
254
+ `Workspace: ${targetPath}`,
255
+ `scan_mode=${profile.scanMode}`,
256
+ `severity_gate=${profile.severityGate}`,
257
+ `playwright_mode=${profile.playwrightMode}`,
258
+ `sbom_mode=${profile.sbomMode}`,
259
+ "",
260
+ "Source spec markdown:",
261
+ specMarkdown,
262
+ ].join("\n");
263
+ }
264
+
265
+ function buildPreScanReportMarkdown({
266
+ generatedAt,
267
+ specPath,
268
+ profile,
269
+ provider,
270
+ model,
271
+ aiMarkdown,
272
+ } = {}) {
273
+ return [
274
+ "# AI PRE-SCAN REPORT",
275
+ "",
276
+ `Generated: ${generatedAt}`,
277
+ `Spec: ${specPath}`,
278
+ `Provider: ${provider}`,
279
+ `Model: ${model}`,
280
+ "",
281
+ "## Derived Scan Profile",
282
+ `- scan_mode: ${profile.scanMode}`,
283
+ `- severity_gate: ${profile.severityGate}`,
284
+ `- playwright_mode: ${profile.playwrightMode}`,
285
+ `- sbom_mode: ${profile.sbomMode}`,
286
+ "",
287
+ "## AI Review",
288
+ String(aiMarkdown || "").trim() || "_No AI output returned._",
289
+ "",
290
+ ].join("\n");
291
+ }
292
+
293
+ async function resolvePreScanReportPath({
294
+ targetPath,
295
+ outputDirOverride,
296
+ outputFile,
297
+ } = {}) {
298
+ const explicit = String(outputFile || "").trim();
299
+ if (explicit) {
300
+ return path.resolve(targetPath, explicit);
301
+ }
302
+
303
+ const outputRoot = await resolveOutputRoot({
304
+ cwd: targetPath,
305
+ outputDirOverride,
306
+ env: process.env,
307
+ });
308
+ return path.join(outputRoot, "reports", `scan-precheck-${createTimestampToken()}.md`);
309
+ }
310
+
311
+ function printAiPreScanSummary({ reportPath, ai }) {
312
+ console.log(pc.bold("AI pre-scan report generated"));
313
+ console.log(pc.gray(`Report: ${reportPath}`));
314
+ console.log(pc.gray(`Provider: ${ai.provider}, Model: ${ai.model}`));
315
+ console.log(
316
+ pc.gray(
317
+ `Input tokens=${ai.usage.inputTokens}, Output tokens=${ai.usage.outputTokens}, Cost=$${ai.usage.costUsd.toFixed(6)}, DurationMs=${ai.usage.durationMs}`
318
+ )
319
+ );
320
+ if (!ai.pricingFound) {
321
+ console.log(pc.yellow("Model pricing missing from local table; cost recorded as 0."));
322
+ }
323
+ if (ai.budget.blocking) {
324
+ console.log(pc.red("AI budget guardrail triggered:"));
325
+ for (const reason of ai.budget.reasons) {
326
+ console.log(`- ${reason.code}: ${reason.message}`);
327
+ }
328
+ } else if (ai.budget.warnings.length > 0) {
329
+ console.log(pc.yellow("AI budget warning threshold reached:"));
330
+ for (const warning of ai.budget.warnings) {
331
+ console.log(`- ${warning.code}: ${warning.message}`);
332
+ }
333
+ }
334
+ }
335
+
336
+ export function registerScanCommand(program) {
337
+ const scan = program.command("scan").description("Generate and validate Omar Gate workflow config");
338
+
339
+ scan
340
+ .command("init")
341
+ .description("Generate .github/workflows/omar-gate.yml from spec context")
342
+ .option("--path <path>", "Target workspace path", ".")
343
+ .option("--spec-file <path>", "Spec file path relative to --path")
344
+ .option("--workflow-file <path>", "Workflow output path relative to --path")
345
+ .option(
346
+ "--secret-name <name>",
347
+ "GitHub Actions secret name for sentinelayer_token",
348
+ "SENTINELAYER_TOKEN"
349
+ )
350
+ .option(
351
+ "--has-e2e-tests <mode>",
352
+ `E2E hint (${SUPPORTED_E2E_HINTS.join("|")})`,
353
+ "auto"
354
+ )
355
+ .option(
356
+ "--playwright-mode <mode>",
357
+ `Playwright override (${SUPPORTED_PLAYWRIGHT_MODES.join("|")})`,
358
+ "auto"
359
+ )
360
+ .option("--non-interactive", "Disable wizard prompts and rely on deterministic inference")
361
+ .option("--json", "Emit machine-readable output")
362
+ .action(async (options, command) => {
363
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
364
+ const workflowTarget = resolveWorkflowPathForCommand({
365
+ targetPath,
366
+ explicitWorkflowFile: options.workflowFile,
367
+ preferExistingLegacy: true,
368
+ });
369
+ const workflowFile = workflowTarget.workflowFile;
370
+ const workflowPath = workflowTarget.workflowPath;
371
+ const specPath = resolveSpecPath(targetPath, options.specFile);
372
+ const specMarkdown = await fsp.readFile(specPath, "utf-8");
373
+
374
+ const hasE2EHint = normalizeE2EHint(options.hasE2eTests);
375
+ const playwrightMode = normalizePlaywrightMode(options.playwrightMode);
376
+ const nonInteractive = Boolean(options.nonInteractive);
377
+ const activePolicy = await resolveActivePolicyPack({
378
+ cwd: targetPath,
379
+ env: process.env,
380
+ });
381
+
382
+ const initialProfile = inferScanProfile({
383
+ specMarkdown,
384
+ hasE2ETests: hasE2EHint,
385
+ playwrightMode,
386
+ });
387
+ const resolvedE2EHint = await maybePromptForE2EChoice({
388
+ inferredHasE2E: initialProfile.inferredHasE2E,
389
+ hasE2ETests: hasE2EHint,
390
+ nonInteractive,
391
+ });
392
+
393
+ const profile = inferScanProfile({
394
+ specMarkdown,
395
+ hasE2ETests: resolvedE2EHint,
396
+ playwrightMode,
397
+ });
398
+ const appliedProfile = applyPolicyPackToScanProfile(profile, activePolicy.selected);
399
+ const workflowMarkdown = buildSecurityReviewWorkflow({
400
+ secretName: options.secretName,
401
+ profile: appliedProfile,
402
+ });
403
+
404
+ await fsp.mkdir(path.dirname(workflowPath), { recursive: true });
405
+ await fsp.writeFile(workflowPath, workflowMarkdown, "utf-8");
406
+
407
+ const instructions = buildSecretSetupInstructions(options.secretName, {
408
+ repoSlug: detectRepoSlugFromGit(targetPath),
409
+ });
410
+ const payload = {
411
+ command: "scan init",
412
+ targetPath,
413
+ specPath,
414
+ workflowPath,
415
+ profile: appliedProfile,
416
+ policyPack: activePolicy.selected
417
+ ? {
418
+ id: activePolicy.selected.id,
419
+ source: activePolicy.selected.source,
420
+ }
421
+ : null,
422
+ instructions,
423
+ };
424
+
425
+ if (shouldEmitJson(options, command)) {
426
+ console.log(JSON.stringify(payload, null, 2));
427
+ return;
428
+ }
429
+
430
+ console.log(pc.bold("Security review workflow generated"));
431
+ console.log(pc.gray(`Spec: ${specPath}`));
432
+ console.log(pc.gray(`Workflow: ${workflowPath}`));
433
+ console.log(
434
+ pc.gray(`scan_mode=${appliedProfile.scanMode}, severity_gate=${appliedProfile.severityGate}`)
435
+ );
436
+ console.log(
437
+ pc.gray(
438
+ `playwright_mode=${appliedProfile.playwrightMode}, sbom_mode=${appliedProfile.sbomMode}`
439
+ )
440
+ );
441
+ if (activePolicy.selected) {
442
+ console.log(pc.gray(`policy_pack=${activePolicy.selected.id} (${activePolicy.selected.source})`));
443
+ }
444
+ instructions.forEach((line) => console.log(line));
445
+ });
446
+
447
+ scan
448
+ .command("validate")
449
+ .description("Validate existing Omar Gate workflow against current spec profile")
450
+ .option("--path <path>", "Target workspace path", ".")
451
+ .option("--spec-file <path>", "Spec file path relative to --path")
452
+ .option("--workflow-file <path>", "Workflow file path relative to --path")
453
+ .option("--secret-name <name>", "Expected GitHub Actions secret name", "SENTINELAYER_TOKEN")
454
+ .option(
455
+ "--has-e2e-tests <mode>",
456
+ `E2E hint (${SUPPORTED_E2E_HINTS.join("|")})`,
457
+ "auto"
458
+ )
459
+ .option(
460
+ "--playwright-mode <mode>",
461
+ `Playwright override (${SUPPORTED_PLAYWRIGHT_MODES.join("|")})`,
462
+ "auto"
463
+ )
464
+ .option("--json", "Emit machine-readable output")
465
+ .action(async (options, command) => {
466
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
467
+ const specPath = resolveSpecPath(targetPath, options.specFile);
468
+ const workflowPath = resolveWorkflowPathForCommand({
469
+ targetPath,
470
+ explicitWorkflowFile: options.workflowFile,
471
+ preferExistingLegacy: true,
472
+ }).workflowPath;
473
+
474
+ const specMarkdown = await fsp.readFile(specPath, "utf-8");
475
+ const workflowMarkdown = await fsp.readFile(workflowPath, "utf-8");
476
+ const activePolicy = await resolveActivePolicyPack({
477
+ cwd: targetPath,
478
+ env: process.env,
479
+ });
480
+ const inferredProfile = inferScanProfile({
481
+ specMarkdown,
482
+ hasE2ETests: normalizeE2EHint(options.hasE2eTests),
483
+ playwrightMode: normalizePlaywrightMode(options.playwrightMode),
484
+ });
485
+ const expectedProfile = applyPolicyPackToScanProfile(inferredProfile, activePolicy.selected);
486
+
487
+ const validation = validateSecurityReviewWorkflow({
488
+ workflowMarkdown,
489
+ expectedProfile,
490
+ expectedSecretName: options.secretName,
491
+ });
492
+
493
+ const payload = {
494
+ command: "scan validate",
495
+ targetPath,
496
+ specPath,
497
+ workflowPath,
498
+ aligned: validation.aligned,
499
+ expected: validation.expected,
500
+ actual: validation.actual,
501
+ mismatches: validation.mismatches,
502
+ policyPack: activePolicy.selected
503
+ ? {
504
+ id: activePolicy.selected.id,
505
+ source: activePolicy.selected.source,
506
+ }
507
+ : null,
508
+ };
509
+
510
+ if (shouldEmitJson(options, command)) {
511
+ console.log(JSON.stringify(payload, null, 2));
512
+ } else if (validation.aligned) {
513
+ console.log(pc.bold("Security review workflow matches spec profile."));
514
+ console.log(pc.gray(`Workflow: ${workflowPath}`));
515
+ } else {
516
+ console.log(pc.red("Security review workflow drift detected."));
517
+ console.log(pc.gray(`Workflow: ${workflowPath}`));
518
+ validation.mismatches.forEach((item, index) => {
519
+ console.log(
520
+ `${index + 1}. ${item.field}: expected '${item.expected}' but found '${item.actual}'.`
521
+ );
522
+ });
523
+ }
524
+
525
+ if (!validation.aligned) {
526
+ process.exitCode = 2;
527
+ }
528
+ });
529
+
530
+ scan
531
+ .command("precheck")
532
+ .description("Run AI pre-scan triage from spec context and emit a review-ready report")
533
+ .option("--path <path>", "Target workspace path", ".")
534
+ .option("--spec-file <path>", "Spec file path relative to --path")
535
+ .option("--output-file <path>", "Report output path relative to --path")
536
+ .option("--output-dir <path>", "Optional output dir override for report/cost/telemetry artifacts")
537
+ .option(
538
+ "--has-e2e-tests <mode>",
539
+ `E2E hint (${SUPPORTED_E2E_HINTS.join("|")})`,
540
+ "auto"
541
+ )
542
+ .option(
543
+ "--playwright-mode <mode>",
544
+ `Playwright override (${SUPPORTED_PLAYWRIGHT_MODES.join("|")})`,
545
+ "auto"
546
+ )
547
+ .option("--provider <name>", "AI provider override (openai|anthropic|google)")
548
+ .option("--model <id>", "AI model override")
549
+ .option("--api-key <key>", "Optional explicit API key override")
550
+ .option("--session-id <id>", "Cost/telemetry session id", "scan-ai-precheck")
551
+ .option("--max-cost <usd>", "Max AI cost budget per session", "0.5")
552
+ .option("--max-tokens <n>", "Max output token budget per session (0 = disabled)", "0")
553
+ .option("--max-runtime-ms <n>", "Max runtime budget per session in milliseconds (0 = disabled)", "0")
554
+ .option("--max-tool-calls <n>", "Max tool-call budget per session (0 = disabled)", "0")
555
+ .option("--max-no-progress <n>", "Max consecutive no-progress events before stop", "3")
556
+ .option("--warn-at-percent <n>", "Warning threshold percentage for enabled budgets", "80")
557
+ .option("--json", "Emit machine-readable output")
558
+ .action(async (options, command) => {
559
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
560
+ const specPath = resolveSpecPath(targetPath, options.specFile);
561
+ const specMarkdown = await fsp.readFile(specPath, "utf-8");
562
+ const activePolicy = await resolveActivePolicyPack({
563
+ cwd: targetPath,
564
+ env: process.env,
565
+ });
566
+ const profile = applyPolicyPackToScanProfile(
567
+ inferScanProfile({
568
+ specMarkdown,
569
+ hasE2ETests: normalizeE2EHint(options.hasE2eTests),
570
+ playwrightMode: normalizePlaywrightMode(options.playwrightMode),
571
+ }),
572
+ activePolicy.selected
573
+ );
574
+
575
+ const config = await loadConfig({ cwd: targetPath });
576
+ const resolvedProvider = resolveProvider({
577
+ provider: options.provider,
578
+ configProvider: config.resolved.defaultModelProvider,
579
+ env: process.env,
580
+ });
581
+ const resolvedModel = resolveModel({
582
+ provider: resolvedProvider,
583
+ model: options.model,
584
+ configModel: config.resolved.defaultModelId,
585
+ });
586
+ const explicitApiKey = String(options.apiKey || "").trim();
587
+ const configuredApiKey = resolveConfiguredApiKey(resolvedProvider, config.resolved);
588
+
589
+ const prompt = buildAiPreScanPrompt({
590
+ targetPath,
591
+ specMarkdown,
592
+ profile,
593
+ });
594
+
595
+ const startedAtMs = Date.now();
596
+ const client = createMultiProviderApiClient();
597
+ const response = await client.invoke({
598
+ provider: resolvedProvider,
599
+ model: resolvedModel,
600
+ prompt,
601
+ apiKey: explicitApiKey || configuredApiKey,
602
+ env: process.env,
603
+ stream: false,
604
+ });
605
+ const durationMs = Math.max(0, Date.now() - startedAtMs);
606
+ const aiMarkdown = String(response.text || "").trim();
607
+ const generatedAt = new Date().toISOString();
608
+
609
+ const reportMarkdown = buildPreScanReportMarkdown({
610
+ generatedAt,
611
+ specPath,
612
+ profile,
613
+ provider: response.provider,
614
+ model: response.model,
615
+ aiMarkdown,
616
+ });
617
+ const reportPath = await resolvePreScanReportPath({
618
+ targetPath,
619
+ outputDirOverride: options.outputDir,
620
+ outputFile: options.outputFile,
621
+ });
622
+ await fsp.mkdir(path.dirname(reportPath), { recursive: true });
623
+ await fsp.writeFile(reportPath, reportMarkdown, "utf-8");
624
+
625
+ const inputTokens = estimateTokenCount(prompt);
626
+ const outputTokens = estimateTokenCount(aiMarkdown);
627
+ const modelCost = maybeEstimateModelCost({
628
+ modelId: response.model,
629
+ inputTokens,
630
+ outputTokens,
631
+ });
632
+ const sessionId = String(options.sessionId || "scan-ai-precheck").trim() || "scan-ai-precheck";
633
+
634
+ const appendedCost = await appendCostEntry(
635
+ {
636
+ targetPath,
637
+ outputDirOverride: options.outputDir,
638
+ },
639
+ {
640
+ sessionId,
641
+ provider: response.provider,
642
+ model: response.model,
643
+ inputTokens,
644
+ outputTokens,
645
+ cacheReadTokens: 0,
646
+ cacheWriteTokens: 0,
647
+ durationMs,
648
+ toolCalls: 1,
649
+ costUsd: modelCost.costUsd,
650
+ progressScore: aiMarkdown ? 1 : 0,
651
+ }
652
+ );
653
+
654
+ const costSummary = summarizeCostHistory(appendedCost.history);
655
+ const sessionSummary = costSummary.sessions.find((item) => item.sessionId === sessionId) || {
656
+ sessionId,
657
+ invocationCount: 0,
658
+ inputTokens: 0,
659
+ outputTokens: 0,
660
+ cacheReadTokens: 0,
661
+ cacheWriteTokens: 0,
662
+ durationMs: 0,
663
+ toolCalls: 0,
664
+ costUsd: 0,
665
+ noProgressStreak: 0,
666
+ };
667
+
668
+ const budget = evaluateBudget({
669
+ sessionSummary,
670
+ maxCostUsd: parseNonNegativeNumber(options.maxCost, "maxCost"),
671
+ maxOutputTokens: parseNonNegativeNumber(options.maxTokens, "maxTokens"),
672
+ maxNoProgress: parseNonNegativeNumber(options.maxNoProgress, "maxNoProgress"),
673
+ maxRuntimeMs: parseNonNegativeNumber(options.maxRuntimeMs, "maxRuntimeMs"),
674
+ maxToolCalls: parseNonNegativeNumber(options.maxToolCalls, "maxToolCalls"),
675
+ warningThresholdPercent: parsePercent(options.warnAtPercent, "warnAtPercent"),
676
+ });
677
+
678
+ const usageTelemetry = await appendRunEvent(
679
+ {
680
+ targetPath,
681
+ outputDirOverride: options.outputDir,
682
+ },
683
+ {
684
+ sessionId,
685
+ runId: sessionId,
686
+ eventType: "usage",
687
+ usage: {
688
+ inputTokens,
689
+ outputTokens,
690
+ cacheReadTokens: 0,
691
+ cacheWriteTokens: 0,
692
+ costUsd: modelCost.costUsd,
693
+ durationMs,
694
+ toolCalls: 1,
695
+ },
696
+ metadata: {
697
+ sourceCommand: "scan precheck",
698
+ provider: response.provider,
699
+ model: response.model,
700
+ invocationId: appendedCost.entry.invocationId,
701
+ },
702
+ }
703
+ );
704
+
705
+ let stopTelemetry = null;
706
+ if (budget.blocking) {
707
+ stopTelemetry = await appendRunEvent(
708
+ {
709
+ targetPath,
710
+ outputDirOverride: options.outputDir,
711
+ },
712
+ {
713
+ sessionId,
714
+ runId: sessionId,
715
+ eventType: "run_stop",
716
+ usage: {
717
+ inputTokens: sessionSummary.inputTokens,
718
+ outputTokens: sessionSummary.outputTokens,
719
+ cacheReadTokens: sessionSummary.cacheReadTokens,
720
+ cacheWriteTokens: sessionSummary.cacheWriteTokens,
721
+ costUsd: sessionSummary.costUsd,
722
+ durationMs: sessionSummary.durationMs,
723
+ toolCalls: sessionSummary.toolCalls,
724
+ },
725
+ stop: {
726
+ stopClass: deriveStopClassFromBudget(budget),
727
+ blocking: true,
728
+ reasonCodes: budget.reasons.map((reason) => reason.code),
729
+ },
730
+ metadata: {
731
+ sourceCommand: "scan precheck",
732
+ provider: response.provider,
733
+ model: response.model,
734
+ invocationId: appendedCost.entry.invocationId,
735
+ },
736
+ }
737
+ );
738
+ }
739
+
740
+ const payload = {
741
+ command: "scan precheck",
742
+ targetPath,
743
+ specPath,
744
+ reportPath,
745
+ profile,
746
+ policyPack: activePolicy.selected
747
+ ? {
748
+ id: activePolicy.selected.id,
749
+ source: activePolicy.selected.source,
750
+ }
751
+ : null,
752
+ ai: {
753
+ provider: response.provider,
754
+ model: response.model,
755
+ pricingFound: modelCost.pricingFound,
756
+ usage: {
757
+ inputTokens,
758
+ outputTokens,
759
+ costUsd: modelCost.costUsd,
760
+ durationMs,
761
+ toolCalls: 1,
762
+ },
763
+ budget,
764
+ cost: {
765
+ filePath: appendedCost.filePath,
766
+ invocationId: appendedCost.entry.invocationId,
767
+ sessionId,
768
+ },
769
+ telemetry: {
770
+ filePath: usageTelemetry.filePath,
771
+ usageEventId: usageTelemetry.event.eventId,
772
+ stopEventId: stopTelemetry?.event?.eventId || null,
773
+ },
774
+ },
775
+ };
776
+
777
+ if (shouldEmitJson(options, command)) {
778
+ console.log(JSON.stringify(payload, null, 2));
779
+ } else {
780
+ printAiPreScanSummary({
781
+ reportPath,
782
+ ai: payload.ai,
783
+ });
784
+ }
785
+
786
+ if (budget.blocking) {
787
+ process.exitCode = 2;
788
+ }
789
+ });
790
+
791
+ scan
792
+ .command("setup-secrets")
793
+ .description("Set up required GitHub secrets for Omar Gate workflow")
794
+ .option("--path <path>", "Target workspace path", ".")
795
+ .option("--secret-name <name>", "GitHub secret name", "SENTINELAYER_TOKEN")
796
+ .option("--repo <slug>", "Repo slug override (owner/repo)")
797
+ .option("--dry-run", "Print instructions without executing")
798
+ .option("--json", "Emit machine-readable output")
799
+ .action(async (options, command) => {
800
+ const emitJson = shouldEmitJson(options, command);
801
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
802
+ const secretName = String(options.secretName || "SENTINELAYER_TOKEN").trim();
803
+ let repoSlug = String(options.repo || "").trim();
804
+
805
+ if (!repoSlug) {
806
+ repoSlug = detectRepoSlug(targetPath) || "";
807
+ }
808
+ if (!repoSlug) {
809
+ const msg = "Could not detect repo slug. Use --repo owner/name or run from a GitHub-connected repo.";
810
+ if (emitJson) {
811
+ console.log(JSON.stringify({ command: "scan setup-secrets", ok: false, reason: msg }, null, 2));
812
+ } else {
813
+ console.error(pc.red(msg));
814
+ }
815
+ process.exitCode = 1;
816
+ return;
817
+ }
818
+
819
+ if (options.dryRun) {
820
+ const result = setupSecrets({ repoSlug, secretName, secretValue: "<token>", dryRun: true });
821
+ const payload = { command: "scan setup-secrets", ...result };
822
+ if (emitJson) {
823
+ console.log(JSON.stringify(payload, null, 2));
824
+ } else {
825
+ console.log(pc.bold(`Setup secrets for ${repoSlug}`));
826
+ console.log(pc.gray("Run these commands:"));
827
+ for (const line of result.instructions || []) {
828
+ console.log(` ${line}`);
829
+ }
830
+ }
831
+ return;
832
+ }
833
+
834
+ let tokenValue = "";
835
+ try {
836
+ const session = await resolveActiveAuthSession({
837
+ cwd: targetPath,
838
+ env: process.env,
839
+ autoRotate: false,
840
+ });
841
+ if (session && session.token) {
842
+ tokenValue = session.token;
843
+ }
844
+ } catch {
845
+ /* no active auth session */
846
+ }
847
+
848
+ if (!tokenValue) {
849
+ const msg =
850
+ `No SentinelLayer token found. Run '${authLoginHint()}', set SENTINELAYER_TOKEN, or use --dry-run for instructions.`;
851
+ if (emitJson) {
852
+ console.log(JSON.stringify({ command: "scan setup-secrets", ok: false, reason: msg }, null, 2));
853
+ } else {
854
+ console.error(pc.red(msg));
855
+ }
856
+ process.exitCode = 1;
857
+ return;
858
+ }
859
+
860
+ const result = setupSecrets({ repoSlug, secretName, secretValue: tokenValue, dryRun: false });
861
+ const payload = { command: "scan setup-secrets", ...result };
862
+ if (emitJson) {
863
+ console.log(JSON.stringify(payload, null, 2));
864
+ } else if (result.ok) {
865
+ console.log(pc.green(`Secret '${secretName}' set on ${repoSlug}`));
866
+ } else {
867
+ console.error(pc.red(`Failed: ${result.reason}`));
868
+ process.exitCode = 1;
869
+ }
870
+ });
871
+ }
872
+