sentinelayer-cli 0.1.2 → 0.4.4

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