sentinelayer-cli 0.6.2 → 0.8.1

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