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