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,679 +1,672 @@
1
- import fsp from "node:fs/promises";
2
- import path from "node:path";
3
-
4
- import {
5
- createMultiProviderApiClient,
6
- resolveModel,
7
- resolveProvider,
8
- } from "../ai/client.js";
9
- import { loadConfig } from "../config/service.js";
10
- import { evaluateBudget } from "../cost/budget.js";
11
- import { appendCostEntry, summarizeCostHistory } from "../cost/history.js";
12
- import { estimateModelCost } from "../cost/tracker.js";
13
- import { appendRunEvent, deriveStopClassFromBudget } from "../telemetry/ledger.js";
14
-
15
- const AI_SEVERITIES = new Set(["P0", "P1", "P2", "P3"]);
16
- const DEFAULT_AI_MAX_FINDINGS = 20;
17
- const DEFAULT_REVIEW_AI_MODEL = "gpt-5.3-codex";
18
-
19
- function normalizeString(value) {
20
- return String(value || "").trim();
21
- }
22
-
23
- function parseNonNegativeNumber(rawValue, field) {
24
- const normalized = Number(rawValue || 0);
25
- if (!Number.isFinite(normalized) || normalized < 0) {
26
- throw new Error(`${field} must be a non-negative number.`);
27
- }
28
- return normalized;
29
- }
30
-
31
- function parsePercent(rawValue, field) {
32
- const normalized = Number(rawValue || 0);
33
- if (!Number.isFinite(normalized) || normalized < 0 || normalized > 100) {
34
- throw new Error(`${field} must be between 0 and 100.`);
35
- }
36
- return normalized;
37
- }
38
-
39
- function estimateTokenCount(text) {
40
- const normalized = String(text || "");
41
- if (!normalized) {
42
- return 0;
43
- }
44
- return Math.max(1, Math.ceil(normalized.length / 4));
45
- }
46
-
47
- function resolveConfiguredApiKey(provider, resolvedConfig = {}) {
48
- const normalizedProvider = normalizeString(provider).toLowerCase();
49
- if (normalizedProvider === "openai") {
50
- return normalizeString(resolvedConfig.openaiApiKey);
51
- }
52
- if (normalizedProvider === "anthropic") {
53
- return normalizeString(resolvedConfig.anthropicApiKey);
54
- }
55
- if (normalizedProvider === "google") {
56
- return normalizeString(resolvedConfig.googleApiKey);
57
- }
58
- return "";
59
- }
60
-
61
- function sanitizeExcerpt(text) {
62
- return String(text || "")
63
- .trim()
64
- .replace(/\s+/g, " ")
65
- .slice(0, 180);
66
- }
67
-
68
- function extractJsonPayload(rawText) {
69
- const text = String(rawText || "").trim();
70
- if (!text) {
71
- return null;
72
- }
73
-
74
- const candidates = [];
75
- const fencedMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
76
- if (fencedMatch && fencedMatch[1]) {
77
- candidates.push(fencedMatch[1].trim());
78
- }
79
- candidates.push(text);
80
-
81
- const objectStart = text.indexOf("{");
82
- const objectEnd = text.lastIndexOf("}");
83
- if (objectStart >= 0 && objectEnd > objectStart) {
84
- candidates.push(text.slice(objectStart, objectEnd + 1));
85
- }
86
-
87
- for (const candidate of candidates) {
88
- try {
89
- const parsed = JSON.parse(candidate);
90
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
91
- return parsed;
92
- }
93
- } catch {
94
- continue;
95
- }
96
- }
97
-
98
- return null;
99
- }
100
-
101
- function normalizeSeverity(value) {
102
- const normalized = normalizeString(value).toUpperCase();
103
- if (AI_SEVERITIES.has(normalized)) {
104
- return normalized;
105
- }
106
- return "P2";
107
- }
108
-
109
- function normalizeLine(value) {
110
- const normalized = Number(value || 1);
111
- if (!Number.isFinite(normalized) || normalized < 1) {
112
- return 1;
113
- }
114
- return Math.floor(normalized);
115
- }
116
-
117
- function normalizeConfidence(value) {
118
- if (value === undefined || value === null || value === "") {
119
- return null;
120
- }
121
- const normalized = Number(value);
122
- if (!Number.isFinite(normalized)) {
123
- return null;
124
- }
125
- return Math.max(0, Math.min(1, normalized));
126
- }
127
-
128
- function normalizeAiFinding(rawFinding, index) {
129
- if (!rawFinding || typeof rawFinding !== "object" || Array.isArray(rawFinding)) {
130
- return null;
131
- }
132
-
133
- const message = normalizeString(rawFinding.title || rawFinding.message);
134
- const rationale = normalizeString(rawFinding.rationale || rawFinding.excerpt);
135
- const suggestedFix = normalizeString(rawFinding.suggestedFix);
136
-
137
- return {
138
- severity: normalizeSeverity(rawFinding.severity),
139
- file: normalizeString(rawFinding.file) || "unknown",
140
- line: normalizeLine(rawFinding.line),
141
- message: message || `AI finding ${index + 1}`,
142
- rationale: rationale || "AI reviewer flagged a potential issue requiring validation.",
143
- suggestedFix: suggestedFix || "Review and remediate this finding.",
144
- confidence: normalizeConfidence(rawFinding.confidence),
145
- };
146
- }
147
-
148
- function summarizeFindings(findings = []) {
149
- const summary = {
150
- P0: 0,
151
- P1: 0,
152
- P2: 0,
153
- P3: 0,
154
- };
155
- for (const finding of findings) {
156
- const severity = normalizeSeverity(finding.severity);
157
- summary[severity] += 1;
158
- }
159
- return {
160
- ...summary,
161
- blocking: summary.P0 > 0 || summary.P1 > 0,
162
- };
163
- }
164
-
165
- export function parseAiReviewResponse({ text, maxFindings = DEFAULT_AI_MAX_FINDINGS } = {}) {
166
- const parsed = extractJsonPayload(text);
167
- const normalizedMaxFindings = Math.max(1, Math.floor(Number(maxFindings || DEFAULT_AI_MAX_FINDINGS)));
168
-
169
- if (!parsed) {
170
- return {
171
- parser: "fallback_text",
172
- summary:
173
- sanitizeExcerpt(text) || "AI response could not be parsed as JSON; no structured findings extracted.",
174
- findings: [],
175
- };
176
- }
177
-
178
- const summary = normalizeString(
179
- parsed.summary?.highLevel || parsed.summary?.risk || parsed.summary?.text || parsed.summary
180
- );
181
- const rawFindings = Array.isArray(parsed.findings) ? parsed.findings : [];
182
- const findings = [];
183
- for (let index = 0; index < rawFindings.length; index += 1) {
184
- if (findings.length >= normalizedMaxFindings) {
185
- break;
186
- }
187
- const normalized = normalizeAiFinding(rawFindings[index], index);
188
- if (normalized) {
189
- findings.push(normalized);
190
- }
191
- }
192
-
193
- return {
194
- parser: "json",
195
- summary: summary || "Structured AI response parsed successfully.",
196
- findings,
197
- };
198
- }
199
-
200
- function formatDeterministicFindingLine(finding) {
201
- return `- [${finding.severity}] ${finding.file}:${finding.line} ${finding.message}`;
202
- }
203
-
204
- function buildScopedFileSummary(scopedFiles = [], maxItems = 200) {
205
- const normalized = Array.isArray(scopedFiles) ? scopedFiles : [];
206
- const visible = normalized.slice(0, maxItems);
207
- const omitted = Math.max(0, normalized.length - visible.length);
208
- const lines = visible.map((item) => `- ${item}`);
209
- if (omitted > 0) {
210
- lines.push(`- ... ${omitted} more files omitted`);
211
- }
212
- return lines.join("\n") || "- none";
213
- }
214
-
215
- export function buildAiReviewPrompt({
216
- targetPath,
217
- mode,
218
- deterministicSummary,
219
- deterministicFindings = [],
220
- scopedFiles = [],
221
- specContext = null,
222
- maxFindings = DEFAULT_AI_MAX_FINDINGS,
223
- } = {}) {
224
- const normalizedSummary = deterministicSummary || { P0: 0, P1: 0, P2: 0, P3: 0 };
225
- const findingLines = deterministicFindings
226
- .slice(0, 120)
227
- .map((finding) => formatDeterministicFindingLine(finding))
228
- .join("\n");
229
- const normalizedMaxFindings = Math.max(1, Math.floor(Number(maxFindings || DEFAULT_AI_MAX_FINDINGS)));
230
- const specPath = normalizeString(specContext?.specPath) || "none";
231
- const specHash = normalizeString(specContext?.specHashSha256) || "unknown";
232
- const specEndpointCount = Number(specContext?.endpointCount || 0);
233
- const specAcceptanceCriteriaCount = Number(specContext?.acceptanceCriteriaCount || 0);
234
- const specPreview = Array.isArray(specContext?.endpointsPreview) ? specContext.endpointsPreview : [];
235
-
236
- return [
237
- "You are Sentinelayer Omar reviewer layer 9.3.",
238
- "Review the deterministic findings and scoped files. Add ONLY materially new findings.",
239
- "Do not repeat deterministic findings unless you add new exploitability rationale.",
240
- "Output STRICT JSON only. Do not wrap in markdown.",
241
- "",
242
- "JSON schema:",
243
- "{",
244
- ' "summary": {"risk": "low|medium|high|critical", "highLevel": "short summary"},',
245
- ' "findings": [',
246
- " {",
247
- ' "severity": "P0|P1|P2|P3",',
248
- ' "file": "relative/path",',
249
- ' "line": 1,',
250
- ' "title": "finding title",',
251
- ' "rationale": "why this matters",',
252
- ' "suggestedFix": "specific remediation",',
253
- ' "confidence": 0.0',
254
- " }",
255
- " ]",
256
- "}",
257
- "",
258
- `Maximum findings: ${normalizedMaxFindings}`,
259
- "",
260
- `Target path: ${targetPath}`,
261
- `Review mode: ${mode}`,
262
- `Deterministic summary: P0=${normalizedSummary.P0} P1=${normalizedSummary.P1} P2=${normalizedSummary.P2} P3=${normalizedSummary.P3}`,
263
- `Spec path: ${specPath}`,
264
- `Spec sha256: ${specHash}`,
265
- `Spec endpoints declared: ${specEndpointCount}`,
266
- `Spec acceptance criteria count: ${specAcceptanceCriteriaCount}`,
267
- `Spec endpoint preview: ${specPreview.length > 0 ? specPreview.join(", ") : "none"}`,
268
- "",
269
- "Scoped files:",
270
- buildScopedFileSummary(scopedFiles),
271
- "",
272
- "Deterministic findings:",
273
- findingLines || "- none",
274
- ].join("\n");
275
- }
276
-
277
- function maybeEstimateModelCost({ modelId, inputTokens, outputTokens }) {
278
- try {
279
- return {
280
- costUsd: estimateModelCost({
281
- modelId,
282
- inputTokens,
283
- outputTokens,
284
- }),
285
- pricingFound: true,
286
- };
287
- } catch {
288
- return {
289
- costUsd: 0,
290
- pricingFound: false,
291
- };
292
- }
293
- }
294
-
295
- function composeAiReviewMarkdown({
296
- generatedAt,
297
- runId,
298
- mode,
299
- parser,
300
- summary,
301
- provider,
302
- model,
303
- dryRun,
304
- findings = [],
305
- usage,
306
- combinedSummary,
307
- } = {}) {
308
- const findingLines =
309
- findings.length > 0
310
- ? findings
311
- .map(
312
- (finding, index) =>
313
- `${index + 1}. [${finding.severity}] ${finding.file}:${finding.line} ${finding.message}\n` +
314
- ` rationale: ${finding.rationale}\n` +
315
- ` suggested_fix: ${finding.suggestedFix}` +
316
- (finding.confidence === null ? "" : `\n confidence: ${finding.confidence.toFixed(2)}`)
317
- )
318
- .join("\n")
319
- : "- none";
320
-
321
- return [
322
- "# REVIEW_AI",
323
- "",
324
- `Generated: ${generatedAt}`,
325
- `Run ID: ${runId}`,
326
- `Mode: ${mode}`,
327
- `Provider: ${provider}`,
328
- `Model: ${model}`,
329
- `Dry run: ${dryRun ? "yes" : "no"}`,
330
- `Parser: ${parser}`,
331
- "",
332
- "Summary:",
333
- `- ${summary || "No summary provided."}`,
334
- `- Combined findings: P0=${combinedSummary.P0} P1=${combinedSummary.P1} P2=${combinedSummary.P2} P3=${combinedSummary.P3}`,
335
- `- Blocking: ${combinedSummary.blocking ? "yes" : "no"}`,
336
- `- Usage: input_tokens=${usage.inputTokens} output_tokens=${usage.outputTokens} cost_usd=${usage.costUsd.toFixed(6)} duration_ms=${usage.durationMs}`,
337
- "",
338
- "AI Findings:",
339
- findingLines,
340
- "",
341
- ].join("\n");
342
- }
343
-
344
- function toReviewFinding(aiFinding, index) {
345
- return {
346
- severity: aiFinding.severity,
347
- file: aiFinding.file,
348
- line: aiFinding.line,
349
- message: aiFinding.message,
350
- excerpt: sanitizeExcerpt(aiFinding.rationale),
351
- ruleId: `SL-AI-${String(index + 1).padStart(3, "0")}`,
352
- suggestedFix: aiFinding.suggestedFix,
353
- layer: "ai_reasoning",
354
- confidence: aiFinding.confidence,
355
- };
356
- }
357
-
358
- function buildDryRunResponse({ deterministicSummary, maxFindings } = {}) {
359
- const findingCount = Math.max(1, Math.min(2, Math.floor(Number(maxFindings || 1))));
360
- const findings = [];
361
- for (let index = 0; index < findingCount; index += 1) {
362
- findings.push({
363
- severity: index === 0 ? "P2" : "P3",
364
- file: "src/example.js",
365
- line: 1 + index,
366
- title: `DRY_RUN finding ${index + 1}`,
367
- rationale: `Synthetic AI rationale with deterministic context P1=${deterministicSummary.P1}.`,
368
- suggestedFix: "Validate this path with targeted remediation.",
369
- confidence: index === 0 ? 0.72 : 0.54,
370
- });
371
- }
372
- return JSON.stringify(
373
- {
374
- summary: {
375
- risk: "medium",
376
- highLevel: "DRY_RUN_RESPONSE: synthetic AI review output.",
377
- },
378
- findings,
379
- },
380
- null,
381
- 2
382
- );
383
- }
384
-
385
- export async function runAiReviewLayer({
386
- targetPath,
387
- mode,
388
- runId,
389
- runDirectory,
390
- deterministic,
391
- outputDir = "",
392
- provider,
393
- model,
394
- apiKey,
395
- sessionId,
396
- maxFindings = DEFAULT_AI_MAX_FINDINGS,
397
- maxCostUsd = 1.0,
398
- maxOutputTokens = 0,
399
- maxRuntimeMs = 0,
400
- maxToolCalls = 0,
401
- maxNoProgress = 3,
402
- warningThresholdPercent = 80,
403
- dryRun = false,
404
- env = process.env,
405
- } = {}) {
406
- const normalizedTargetPath = path.resolve(String(targetPath || "."));
407
- const normalizedRunDirectory = path.resolve(String(runDirectory || "."));
408
- const normalizedMode = normalizeString(mode) || "full";
409
- const normalizedMaxFindings = Math.max(
410
- 1,
411
- Math.floor(Number(maxFindings || DEFAULT_AI_MAX_FINDINGS))
412
- );
413
- const normalizedRunId = normalizeString(runId) || "review-ai";
414
-
415
- const config = await loadConfig({ cwd: normalizedTargetPath, env });
416
- let resolvedProvider = resolveProvider({
417
- provider,
418
- configProvider: config.resolved.defaultModelProvider,
419
- env,
420
- });
421
- // If no explicit provider and default fell through to openai,
422
- // check for stored sentinelayer session (async fallback)
423
- if (resolvedProvider === "openai" && !provider && !config.resolved.defaultModelProvider) {
424
- try {
425
- const { resolveProviderAsync } = await import("../ai/client.js");
426
- resolvedProvider = await resolveProviderAsync({ env });
427
- } catch {
428
- // keep sync result
429
- }
430
- }
431
- const resolvedModel = resolveModel({
432
- provider: resolvedProvider,
433
- model,
434
- configModel: config.resolved.defaultModelId || DEFAULT_REVIEW_AI_MODEL,
435
- });
436
- const explicitApiKey = normalizeString(apiKey);
437
- const configuredApiKey = resolveConfiguredApiKey(resolvedProvider, config.resolved);
438
-
439
- const prompt = buildAiReviewPrompt({
440
- targetPath: normalizedTargetPath,
441
- mode: normalizedMode,
442
- deterministicSummary: deterministic?.summary,
443
- deterministicFindings: deterministic?.findings || [],
444
- scopedFiles: deterministic?.scope?.scannedRelativeFiles || [],
445
- specContext: deterministic?.layers?.specBinding || null,
446
- maxFindings: normalizedMaxFindings,
447
- });
448
-
449
- const startedAt = Date.now();
450
- const responseText = dryRun
451
- ? buildDryRunResponse({
452
- deterministicSummary: deterministic?.summary || {},
453
- maxFindings: normalizedMaxFindings,
454
- })
455
- : (
456
- await createMultiProviderApiClient().invoke({
457
- provider: resolvedProvider,
458
- model: resolvedModel,
459
- prompt,
460
- apiKey: explicitApiKey || configuredApiKey,
461
- env,
462
- stream: false,
463
- })
464
- ).text;
465
- const durationMs = Math.max(0, Date.now() - startedAt);
466
-
467
- const parsed = parseAiReviewResponse({
468
- text: responseText,
469
- maxFindings: normalizedMaxFindings,
470
- });
471
- const aiFindings = parsed.findings.map((finding, index) => toReviewFinding(finding, index));
472
- const aiSummary = summarizeFindings(aiFindings);
473
- const deterministicSummary = deterministic?.summary || { P0: 0, P1: 0, P2: 0, P3: 0 };
474
- const combinedSummary = {
475
- P0: deterministicSummary.P0 + aiSummary.P0,
476
- P1: deterministicSummary.P1 + aiSummary.P1,
477
- P2: deterministicSummary.P2 + aiSummary.P2,
478
- P3: deterministicSummary.P3 + aiSummary.P3,
479
- };
480
- combinedSummary.blocking = combinedSummary.P0 > 0 || combinedSummary.P1 > 0;
481
-
482
- const inputTokens = estimateTokenCount(prompt);
483
- const outputTokens = estimateTokenCount(responseText);
484
- const modelCost = maybeEstimateModelCost({
485
- modelId: resolvedModel,
486
- inputTokens,
487
- outputTokens,
488
- });
489
- const normalizedSessionId =
490
- normalizeString(sessionId) || `${normalizedRunId}-ai`;
491
-
492
- const appendedCost = await appendCostEntry(
493
- {
494
- targetPath: normalizedTargetPath,
495
- outputDirOverride: outputDir,
496
- },
497
- {
498
- sessionId: normalizedSessionId,
499
- provider: resolvedProvider,
500
- model: resolvedModel,
501
- inputTokens,
502
- outputTokens,
503
- cacheReadTokens: 0,
504
- cacheWriteTokens: 0,
505
- durationMs,
506
- toolCalls: 1,
507
- costUsd: modelCost.costUsd,
508
- progressScore: aiFindings.length > 0 ? 1 : 0,
509
- }
510
- );
511
- const costSummary = summarizeCostHistory(appendedCost.history);
512
- const sessionSummary = costSummary.sessions.find((entry) => entry.sessionId === normalizedSessionId) || {
513
- sessionId: normalizedSessionId,
514
- invocationCount: 0,
515
- inputTokens: 0,
516
- outputTokens: 0,
517
- cacheReadTokens: 0,
518
- cacheWriteTokens: 0,
519
- durationMs: 0,
520
- toolCalls: 0,
521
- costUsd: 0,
522
- noProgressStreak: 0,
523
- };
524
-
525
- const budget = evaluateBudget({
526
- sessionSummary,
527
- maxCostUsd: parseNonNegativeNumber(maxCostUsd, "maxCostUsd"),
528
- maxOutputTokens: parseNonNegativeNumber(maxOutputTokens, "maxOutputTokens"),
529
- maxNoProgress: parseNonNegativeNumber(maxNoProgress, "maxNoProgress"),
530
- maxRuntimeMs: parseNonNegativeNumber(maxRuntimeMs, "maxRuntimeMs"),
531
- maxToolCalls: parseNonNegativeNumber(maxToolCalls, "maxToolCalls"),
532
- warningThresholdPercent: parsePercent(warningThresholdPercent, "warningThresholdPercent"),
533
- });
534
-
535
- const usageTelemetry = await appendRunEvent(
536
- {
537
- targetPath: normalizedTargetPath,
538
- outputDirOverride: outputDir,
539
- },
540
- {
541
- sessionId: normalizedSessionId,
542
- runId: normalizedRunId,
543
- eventType: "usage",
544
- usage: {
545
- inputTokens,
546
- outputTokens,
547
- cacheReadTokens: 0,
548
- cacheWriteTokens: 0,
549
- costUsd: modelCost.costUsd,
550
- durationMs,
551
- toolCalls: 1,
552
- },
553
- metadata: {
554
- sourceCommand: "review",
555
- layer: "ai_reasoning",
556
- provider: resolvedProvider,
557
- model: resolvedModel,
558
- invocationId: appendedCost.entry.invocationId,
559
- dryRun: Boolean(dryRun),
560
- },
561
- }
562
- );
563
-
564
- let stopTelemetry = null;
565
- if (budget.blocking) {
566
- stopTelemetry = await appendRunEvent(
567
- {
568
- targetPath: normalizedTargetPath,
569
- outputDirOverride: outputDir,
570
- },
571
- {
572
- sessionId: normalizedSessionId,
573
- runId: normalizedRunId,
574
- eventType: "run_stop",
575
- usage: {
576
- inputTokens: sessionSummary.inputTokens,
577
- outputTokens: sessionSummary.outputTokens,
578
- cacheReadTokens: sessionSummary.cacheReadTokens,
579
- cacheWriteTokens: sessionSummary.cacheWriteTokens,
580
- costUsd: sessionSummary.costUsd,
581
- durationMs: sessionSummary.durationMs,
582
- toolCalls: sessionSummary.toolCalls,
583
- },
584
- stop: {
585
- stopClass: deriveStopClassFromBudget(budget),
586
- blocking: true,
587
- reasonCodes: budget.reasons.map((reason) => reason.code),
588
- },
589
- metadata: {
590
- sourceCommand: "review",
591
- layer: "ai_reasoning",
592
- provider: resolvedProvider,
593
- model: resolvedModel,
594
- invocationId: appendedCost.entry.invocationId,
595
- dryRun: Boolean(dryRun),
596
- },
597
- }
598
- );
599
- }
600
-
601
- await fsp.mkdir(normalizedRunDirectory, { recursive: true });
602
- const promptPath = path.join(normalizedRunDirectory, "REVIEW_AI_PROMPT.txt");
603
- const reportMarkdownPath = path.join(normalizedRunDirectory, "REVIEW_AI.md");
604
- const reportJsonPath = path.join(normalizedRunDirectory, "REVIEW_AI.json");
605
- const generatedAt = new Date().toISOString();
606
- const usage = {
607
- inputTokens,
608
- outputTokens,
609
- costUsd: modelCost.costUsd,
610
- durationMs,
611
- toolCalls: 1,
612
- };
613
- const reportPayload = {
614
- schemaVersion: "1.0.0",
615
- generatedAt,
616
- runId: normalizedRunId,
617
- mode: normalizedMode,
618
- parser: parsed.parser,
619
- summary: parsed.summary,
620
- provider: resolvedProvider,
621
- model: resolvedModel,
622
- dryRun: Boolean(dryRun),
623
- usage,
624
- pricingFound: modelCost.pricingFound,
625
- budget,
626
- deterministicSummary,
627
- aiSummary,
628
- combinedSummary,
629
- findings: aiFindings,
630
- };
631
-
632
- const reportMarkdown = composeAiReviewMarkdown({
633
- generatedAt,
634
- runId: normalizedRunId,
635
- mode: normalizedMode,
636
- parser: parsed.parser,
637
- summary: parsed.summary,
638
- provider: resolvedProvider,
639
- model: resolvedModel,
640
- dryRun: Boolean(dryRun),
641
- findings: aiFindings,
642
- usage,
643
- combinedSummary,
644
- });
645
-
646
- await fsp.writeFile(promptPath, `${prompt}\n`, "utf-8");
647
- await fsp.writeFile(reportMarkdownPath, `${reportMarkdown.trim()}\n`, "utf-8");
648
- await fsp.writeFile(reportJsonPath, `${JSON.stringify(reportPayload, null, 2)}\n`, "utf-8");
649
-
650
- return {
651
- parser: parsed.parser,
652
- summary: parsed.summary,
653
- findings: aiFindings,
654
- aiSummary,
655
- combinedSummary,
656
- provider: resolvedProvider,
657
- model: resolvedModel,
658
- dryRun: Boolean(dryRun),
659
- usage,
660
- pricingFound: modelCost.pricingFound,
661
- budget,
662
- artifacts: {
663
- promptPath,
664
- reportMarkdownPath,
665
- reportJsonPath,
666
- },
667
- cost: {
668
- filePath: appendedCost.filePath,
669
- invocationId: appendedCost.entry.invocationId,
670
- sessionId: normalizedSessionId,
671
- },
672
- telemetry: {
673
- filePath: usageTelemetry.filePath,
674
- usageEventId: usageTelemetry.event.eventId,
675
- stopEventId: stopTelemetry?.event?.eventId || null,
676
- },
677
- };
678
- }
679
-
1
+ import fsp from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import {
5
+ createMultiProviderApiClient,
6
+ resolveModel,
7
+ resolveProvider,
8
+ } from "../ai/client.js";
9
+ import { loadConfig } from "../config/service.js";
10
+ import { evaluateBudget } from "../cost/budget.js";
11
+ import { appendCostEntry, summarizeCostHistory } from "../cost/history.js";
12
+ import { estimateModelCost } from "../cost/tracker.js";
13
+ import { estimateTokens } from "../cost/tokenizer.js";
14
+ import { appendRunEvent, deriveStopClassFromBudget } from "../telemetry/ledger.js";
15
+
16
+ const AI_SEVERITIES = new Set(["P0", "P1", "P2", "P3"]);
17
+ const DEFAULT_AI_MAX_FINDINGS = 20;
18
+ const DEFAULT_REVIEW_AI_MODEL = "gpt-5.3-codex";
19
+
20
+ function normalizeString(value) {
21
+ return String(value || "").trim();
22
+ }
23
+
24
+ function parseNonNegativeNumber(rawValue, field) {
25
+ const normalized = Number(rawValue || 0);
26
+ if (!Number.isFinite(normalized) || normalized < 0) {
27
+ throw new Error(`${field} must be a non-negative number.`);
28
+ }
29
+ return normalized;
30
+ }
31
+
32
+ function parsePercent(rawValue, field) {
33
+ const normalized = Number(rawValue || 0);
34
+ if (!Number.isFinite(normalized) || normalized < 0 || normalized > 100) {
35
+ throw new Error(`${field} must be between 0 and 100.`);
36
+ }
37
+ return normalized;
38
+ }
39
+
40
+ function resolveConfiguredApiKey(provider, resolvedConfig = {}) {
41
+ const normalizedProvider = normalizeString(provider).toLowerCase();
42
+ if (normalizedProvider === "openai") {
43
+ return normalizeString(resolvedConfig.openaiApiKey);
44
+ }
45
+ if (normalizedProvider === "anthropic") {
46
+ return normalizeString(resolvedConfig.anthropicApiKey);
47
+ }
48
+ if (normalizedProvider === "google") {
49
+ return normalizeString(resolvedConfig.googleApiKey);
50
+ }
51
+ return "";
52
+ }
53
+
54
+ function sanitizeExcerpt(text) {
55
+ return String(text || "")
56
+ .trim()
57
+ .replace(/\s+/g, " ")
58
+ .slice(0, 180);
59
+ }
60
+
61
+ function extractJsonPayload(rawText) {
62
+ const text = String(rawText || "").trim();
63
+ if (!text) {
64
+ return null;
65
+ }
66
+
67
+ const candidates = [];
68
+ const fencedMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
69
+ if (fencedMatch && fencedMatch[1]) {
70
+ candidates.push(fencedMatch[1].trim());
71
+ }
72
+ candidates.push(text);
73
+
74
+ const objectStart = text.indexOf("{");
75
+ const objectEnd = text.lastIndexOf("}");
76
+ if (objectStart >= 0 && objectEnd > objectStart) {
77
+ candidates.push(text.slice(objectStart, objectEnd + 1));
78
+ }
79
+
80
+ for (const candidate of candidates) {
81
+ try {
82
+ const parsed = JSON.parse(candidate);
83
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
84
+ return parsed;
85
+ }
86
+ } catch {
87
+ continue;
88
+ }
89
+ }
90
+
91
+ return null;
92
+ }
93
+
94
+ function normalizeSeverity(value) {
95
+ const normalized = normalizeString(value).toUpperCase();
96
+ if (AI_SEVERITIES.has(normalized)) {
97
+ return normalized;
98
+ }
99
+ return "P2";
100
+ }
101
+
102
+ function normalizeLine(value) {
103
+ const normalized = Number(value || 1);
104
+ if (!Number.isFinite(normalized) || normalized < 1) {
105
+ return 1;
106
+ }
107
+ return Math.floor(normalized);
108
+ }
109
+
110
+ function normalizeConfidence(value) {
111
+ if (value === undefined || value === null || value === "") {
112
+ return null;
113
+ }
114
+ const normalized = Number(value);
115
+ if (!Number.isFinite(normalized)) {
116
+ return null;
117
+ }
118
+ return Math.max(0, Math.min(1, normalized));
119
+ }
120
+
121
+ function normalizeAiFinding(rawFinding, index) {
122
+ if (!rawFinding || typeof rawFinding !== "object" || Array.isArray(rawFinding)) {
123
+ return null;
124
+ }
125
+
126
+ const message = normalizeString(rawFinding.title || rawFinding.message);
127
+ const rationale = normalizeString(rawFinding.rationale || rawFinding.excerpt);
128
+ const suggestedFix = normalizeString(rawFinding.suggestedFix);
129
+
130
+ return {
131
+ severity: normalizeSeverity(rawFinding.severity),
132
+ file: normalizeString(rawFinding.file) || "unknown",
133
+ line: normalizeLine(rawFinding.line),
134
+ message: message || `AI finding ${index + 1}`,
135
+ rationale: rationale || "AI reviewer flagged a potential issue requiring validation.",
136
+ suggestedFix: suggestedFix || "Review and remediate this finding.",
137
+ confidence: normalizeConfidence(rawFinding.confidence),
138
+ };
139
+ }
140
+
141
+ function summarizeFindings(findings = []) {
142
+ const summary = {
143
+ P0: 0,
144
+ P1: 0,
145
+ P2: 0,
146
+ P3: 0,
147
+ };
148
+ for (const finding of findings) {
149
+ const severity = normalizeSeverity(finding.severity);
150
+ summary[severity] += 1;
151
+ }
152
+ return {
153
+ ...summary,
154
+ blocking: summary.P0 > 0 || summary.P1 > 0,
155
+ };
156
+ }
157
+
158
+ export function parseAiReviewResponse({ text, maxFindings = DEFAULT_AI_MAX_FINDINGS } = {}) {
159
+ const parsed = extractJsonPayload(text);
160
+ const normalizedMaxFindings = Math.max(1, Math.floor(Number(maxFindings || DEFAULT_AI_MAX_FINDINGS)));
161
+
162
+ if (!parsed) {
163
+ return {
164
+ parser: "fallback_text",
165
+ summary:
166
+ sanitizeExcerpt(text) || "AI response could not be parsed as JSON; no structured findings extracted.",
167
+ findings: [],
168
+ };
169
+ }
170
+
171
+ const summary = normalizeString(
172
+ parsed.summary?.highLevel || parsed.summary?.risk || parsed.summary?.text || parsed.summary
173
+ );
174
+ const rawFindings = Array.isArray(parsed.findings) ? parsed.findings : [];
175
+ const findings = [];
176
+ for (let index = 0; index < rawFindings.length; index += 1) {
177
+ if (findings.length >= normalizedMaxFindings) {
178
+ break;
179
+ }
180
+ const normalized = normalizeAiFinding(rawFindings[index], index);
181
+ if (normalized) {
182
+ findings.push(normalized);
183
+ }
184
+ }
185
+
186
+ return {
187
+ parser: "json",
188
+ summary: summary || "Structured AI response parsed successfully.",
189
+ findings,
190
+ };
191
+ }
192
+
193
+ function formatDeterministicFindingLine(finding) {
194
+ return `- [${finding.severity}] ${finding.file}:${finding.line} ${finding.message}`;
195
+ }
196
+
197
+ function buildScopedFileSummary(scopedFiles = [], maxItems = 200) {
198
+ const normalized = Array.isArray(scopedFiles) ? scopedFiles : [];
199
+ const visible = normalized.slice(0, maxItems);
200
+ const omitted = Math.max(0, normalized.length - visible.length);
201
+ const lines = visible.map((item) => `- ${item}`);
202
+ if (omitted > 0) {
203
+ lines.push(`- ... ${omitted} more files omitted`);
204
+ }
205
+ return lines.join("\n") || "- none";
206
+ }
207
+
208
+ export function buildAiReviewPrompt({
209
+ targetPath,
210
+ mode,
211
+ deterministicSummary,
212
+ deterministicFindings = [],
213
+ scopedFiles = [],
214
+ specContext = null,
215
+ maxFindings = DEFAULT_AI_MAX_FINDINGS,
216
+ } = {}) {
217
+ const normalizedSummary = deterministicSummary || { P0: 0, P1: 0, P2: 0, P3: 0 };
218
+ const findingLines = deterministicFindings
219
+ .slice(0, 120)
220
+ .map((finding) => formatDeterministicFindingLine(finding))
221
+ .join("\n");
222
+ const normalizedMaxFindings = Math.max(1, Math.floor(Number(maxFindings || DEFAULT_AI_MAX_FINDINGS)));
223
+ const specPath = normalizeString(specContext?.specPath) || "none";
224
+ const specHash = normalizeString(specContext?.specHashSha256) || "unknown";
225
+ const specEndpointCount = Number(specContext?.endpointCount || 0);
226
+ const specAcceptanceCriteriaCount = Number(specContext?.acceptanceCriteriaCount || 0);
227
+ const specPreview = Array.isArray(specContext?.endpointsPreview) ? specContext.endpointsPreview : [];
228
+
229
+ return [
230
+ "You are Sentinelayer Omar reviewer layer 9.3.",
231
+ "Review the deterministic findings and scoped files. Add ONLY materially new findings.",
232
+ "Do not repeat deterministic findings unless you add new exploitability rationale.",
233
+ "Output STRICT JSON only. Do not wrap in markdown.",
234
+ "",
235
+ "JSON schema:",
236
+ "{",
237
+ ' "summary": {"risk": "low|medium|high|critical", "highLevel": "short summary"},',
238
+ ' "findings": [',
239
+ " {",
240
+ ' "severity": "P0|P1|P2|P3",',
241
+ ' "file": "relative/path",',
242
+ ' "line": 1,',
243
+ ' "title": "finding title",',
244
+ ' "rationale": "why this matters",',
245
+ ' "suggestedFix": "specific remediation",',
246
+ ' "confidence": 0.0',
247
+ " }",
248
+ " ]",
249
+ "}",
250
+ "",
251
+ `Maximum findings: ${normalizedMaxFindings}`,
252
+ "",
253
+ `Target path: ${targetPath}`,
254
+ `Review mode: ${mode}`,
255
+ `Deterministic summary: P0=${normalizedSummary.P0} P1=${normalizedSummary.P1} P2=${normalizedSummary.P2} P3=${normalizedSummary.P3}`,
256
+ `Spec path: ${specPath}`,
257
+ `Spec sha256: ${specHash}`,
258
+ `Spec endpoints declared: ${specEndpointCount}`,
259
+ `Spec acceptance criteria count: ${specAcceptanceCriteriaCount}`,
260
+ `Spec endpoint preview: ${specPreview.length > 0 ? specPreview.join(", ") : "none"}`,
261
+ "",
262
+ "Scoped files:",
263
+ buildScopedFileSummary(scopedFiles),
264
+ "",
265
+ "Deterministic findings:",
266
+ findingLines || "- none",
267
+ ].join("\n");
268
+ }
269
+
270
+ function maybeEstimateModelCost({ modelId, inputTokens, outputTokens }) {
271
+ try {
272
+ return {
273
+ costUsd: estimateModelCost({
274
+ modelId,
275
+ inputTokens,
276
+ outputTokens,
277
+ }),
278
+ pricingFound: true,
279
+ };
280
+ } catch {
281
+ return {
282
+ costUsd: 0,
283
+ pricingFound: false,
284
+ };
285
+ }
286
+ }
287
+
288
+ function composeAiReviewMarkdown({
289
+ generatedAt,
290
+ runId,
291
+ mode,
292
+ parser,
293
+ summary,
294
+ provider,
295
+ model,
296
+ dryRun,
297
+ findings = [],
298
+ usage,
299
+ combinedSummary,
300
+ } = {}) {
301
+ const findingLines =
302
+ findings.length > 0
303
+ ? findings
304
+ .map(
305
+ (finding, index) =>
306
+ `${index + 1}. [${finding.severity}] ${finding.file}:${finding.line} ${finding.message}\n` +
307
+ ` rationale: ${finding.rationale}\n` +
308
+ ` suggested_fix: ${finding.suggestedFix}` +
309
+ (finding.confidence === null ? "" : `\n confidence: ${finding.confidence.toFixed(2)}`)
310
+ )
311
+ .join("\n")
312
+ : "- none";
313
+
314
+ return [
315
+ "# REVIEW_AI",
316
+ "",
317
+ `Generated: ${generatedAt}`,
318
+ `Run ID: ${runId}`,
319
+ `Mode: ${mode}`,
320
+ `Provider: ${provider}`,
321
+ `Model: ${model}`,
322
+ `Dry run: ${dryRun ? "yes" : "no"}`,
323
+ `Parser: ${parser}`,
324
+ "",
325
+ "Summary:",
326
+ `- ${summary || "No summary provided."}`,
327
+ `- Combined findings: P0=${combinedSummary.P0} P1=${combinedSummary.P1} P2=${combinedSummary.P2} P3=${combinedSummary.P3}`,
328
+ `- Blocking: ${combinedSummary.blocking ? "yes" : "no"}`,
329
+ `- Usage: input_tokens=${usage.inputTokens} output_tokens=${usage.outputTokens} cost_usd=${usage.costUsd.toFixed(6)} duration_ms=${usage.durationMs}`,
330
+ "",
331
+ "AI Findings:",
332
+ findingLines,
333
+ "",
334
+ ].join("\n");
335
+ }
336
+
337
+ function toReviewFinding(aiFinding, index) {
338
+ return {
339
+ severity: aiFinding.severity,
340
+ file: aiFinding.file,
341
+ line: aiFinding.line,
342
+ message: aiFinding.message,
343
+ excerpt: sanitizeExcerpt(aiFinding.rationale),
344
+ ruleId: `SL-AI-${String(index + 1).padStart(3, "0")}`,
345
+ suggestedFix: aiFinding.suggestedFix,
346
+ layer: "ai_reasoning",
347
+ confidence: aiFinding.confidence,
348
+ };
349
+ }
350
+
351
+ function buildDryRunResponse({ deterministicSummary, maxFindings } = {}) {
352
+ const findingCount = Math.max(1, Math.min(2, Math.floor(Number(maxFindings || 1))));
353
+ const findings = [];
354
+ for (let index = 0; index < findingCount; index += 1) {
355
+ findings.push({
356
+ severity: index === 0 ? "P2" : "P3",
357
+ file: "src/example.js",
358
+ line: 1 + index,
359
+ title: `DRY_RUN finding ${index + 1}`,
360
+ rationale: `Synthetic AI rationale with deterministic context P1=${deterministicSummary.P1}.`,
361
+ suggestedFix: "Validate this path with targeted remediation.",
362
+ confidence: index === 0 ? 0.72 : 0.54,
363
+ });
364
+ }
365
+ return JSON.stringify(
366
+ {
367
+ summary: {
368
+ risk: "medium",
369
+ highLevel: "DRY_RUN_RESPONSE: synthetic AI review output.",
370
+ },
371
+ findings,
372
+ },
373
+ null,
374
+ 2
375
+ );
376
+ }
377
+
378
+ export async function runAiReviewLayer({
379
+ targetPath,
380
+ mode,
381
+ runId,
382
+ runDirectory,
383
+ deterministic,
384
+ outputDir = "",
385
+ provider,
386
+ model,
387
+ apiKey,
388
+ sessionId,
389
+ maxFindings = DEFAULT_AI_MAX_FINDINGS,
390
+ maxCostUsd = 1.0,
391
+ maxOutputTokens = 0,
392
+ maxRuntimeMs = 0,
393
+ maxToolCalls = 0,
394
+ maxNoProgress = 3,
395
+ warningThresholdPercent = 80,
396
+ dryRun = false,
397
+ env = process.env,
398
+ } = {}) {
399
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
400
+ const normalizedRunDirectory = path.resolve(String(runDirectory || "."));
401
+ const normalizedMode = normalizeString(mode) || "full";
402
+ const normalizedMaxFindings = Math.max(
403
+ 1,
404
+ Math.floor(Number(maxFindings || DEFAULT_AI_MAX_FINDINGS))
405
+ );
406
+ const normalizedRunId = normalizeString(runId) || "review-ai";
407
+
408
+ const config = await loadConfig({ cwd: normalizedTargetPath, env });
409
+ let resolvedProvider = resolveProvider({
410
+ provider,
411
+ configProvider: config.resolved.defaultModelProvider,
412
+ env,
413
+ });
414
+ // If no explicit provider and default fell through to openai,
415
+ // check for stored sentinelayer session (async fallback)
416
+ if (resolvedProvider === "openai" && !provider && !config.resolved.defaultModelProvider) {
417
+ try {
418
+ const { resolveProviderAsync } = await import("../ai/client.js");
419
+ resolvedProvider = await resolveProviderAsync({ env });
420
+ } catch {
421
+ // keep sync result
422
+ }
423
+ }
424
+ const resolvedModel = resolveModel({
425
+ provider: resolvedProvider,
426
+ model,
427
+ configModel: config.resolved.defaultModelId || DEFAULT_REVIEW_AI_MODEL,
428
+ });
429
+ const explicitApiKey = normalizeString(apiKey);
430
+ const configuredApiKey = resolveConfiguredApiKey(resolvedProvider, config.resolved);
431
+
432
+ const prompt = buildAiReviewPrompt({
433
+ targetPath: normalizedTargetPath,
434
+ mode: normalizedMode,
435
+ deterministicSummary: deterministic?.summary,
436
+ deterministicFindings: deterministic?.findings || [],
437
+ scopedFiles: deterministic?.scope?.scannedRelativeFiles || [],
438
+ specContext: deterministic?.layers?.specBinding || null,
439
+ maxFindings: normalizedMaxFindings,
440
+ });
441
+
442
+ const startedAt = Date.now();
443
+ const responseText = dryRun
444
+ ? buildDryRunResponse({
445
+ deterministicSummary: deterministic?.summary || {},
446
+ maxFindings: normalizedMaxFindings,
447
+ })
448
+ : (
449
+ await createMultiProviderApiClient().invoke({
450
+ provider: resolvedProvider,
451
+ model: resolvedModel,
452
+ prompt,
453
+ apiKey: explicitApiKey || configuredApiKey,
454
+ env,
455
+ stream: false,
456
+ })
457
+ ).text;
458
+ const durationMs = Math.max(0, Date.now() - startedAt);
459
+
460
+ const parsed = parseAiReviewResponse({
461
+ text: responseText,
462
+ maxFindings: normalizedMaxFindings,
463
+ });
464
+ const aiFindings = parsed.findings.map((finding, index) => toReviewFinding(finding, index));
465
+ const aiSummary = summarizeFindings(aiFindings);
466
+ const deterministicSummary = deterministic?.summary || { P0: 0, P1: 0, P2: 0, P3: 0 };
467
+ const combinedSummary = {
468
+ P0: deterministicSummary.P0 + aiSummary.P0,
469
+ P1: deterministicSummary.P1 + aiSummary.P1,
470
+ P2: deterministicSummary.P2 + aiSummary.P2,
471
+ P3: deterministicSummary.P3 + aiSummary.P3,
472
+ };
473
+ combinedSummary.blocking = combinedSummary.P0 > 0 || combinedSummary.P1 > 0;
474
+
475
+ const inputTokens = estimateTokens(prompt, { model: resolvedModel });
476
+ const outputTokens = estimateTokens(responseText, { model: resolvedModel });
477
+ const modelCost = maybeEstimateModelCost({
478
+ modelId: resolvedModel,
479
+ inputTokens,
480
+ outputTokens,
481
+ });
482
+ const normalizedSessionId =
483
+ normalizeString(sessionId) || `${normalizedRunId}-ai`;
484
+
485
+ const appendedCost = await appendCostEntry(
486
+ {
487
+ targetPath: normalizedTargetPath,
488
+ outputDirOverride: outputDir,
489
+ },
490
+ {
491
+ sessionId: normalizedSessionId,
492
+ provider: resolvedProvider,
493
+ model: resolvedModel,
494
+ inputTokens,
495
+ outputTokens,
496
+ cacheReadTokens: 0,
497
+ cacheWriteTokens: 0,
498
+ durationMs,
499
+ toolCalls: 1,
500
+ costUsd: modelCost.costUsd,
501
+ progressScore: aiFindings.length > 0 ? 1 : 0,
502
+ }
503
+ );
504
+ const costSummary = summarizeCostHistory(appendedCost.history);
505
+ const sessionSummary = costSummary.sessions.find((entry) => entry.sessionId === normalizedSessionId) || {
506
+ sessionId: normalizedSessionId,
507
+ invocationCount: 0,
508
+ inputTokens: 0,
509
+ outputTokens: 0,
510
+ cacheReadTokens: 0,
511
+ cacheWriteTokens: 0,
512
+ durationMs: 0,
513
+ toolCalls: 0,
514
+ costUsd: 0,
515
+ noProgressStreak: 0,
516
+ };
517
+
518
+ const budget = evaluateBudget({
519
+ sessionSummary,
520
+ maxCostUsd: parseNonNegativeNumber(maxCostUsd, "maxCostUsd"),
521
+ maxOutputTokens: parseNonNegativeNumber(maxOutputTokens, "maxOutputTokens"),
522
+ maxNoProgress: parseNonNegativeNumber(maxNoProgress, "maxNoProgress"),
523
+ maxRuntimeMs: parseNonNegativeNumber(maxRuntimeMs, "maxRuntimeMs"),
524
+ maxToolCalls: parseNonNegativeNumber(maxToolCalls, "maxToolCalls"),
525
+ warningThresholdPercent: parsePercent(warningThresholdPercent, "warningThresholdPercent"),
526
+ });
527
+
528
+ const usageTelemetry = await appendRunEvent(
529
+ {
530
+ targetPath: normalizedTargetPath,
531
+ outputDirOverride: outputDir,
532
+ },
533
+ {
534
+ sessionId: normalizedSessionId,
535
+ runId: normalizedRunId,
536
+ eventType: "usage",
537
+ usage: {
538
+ inputTokens,
539
+ outputTokens,
540
+ cacheReadTokens: 0,
541
+ cacheWriteTokens: 0,
542
+ costUsd: modelCost.costUsd,
543
+ durationMs,
544
+ toolCalls: 1,
545
+ },
546
+ metadata: {
547
+ sourceCommand: "review",
548
+ layer: "ai_reasoning",
549
+ provider: resolvedProvider,
550
+ model: resolvedModel,
551
+ invocationId: appendedCost.entry.invocationId,
552
+ dryRun: Boolean(dryRun),
553
+ },
554
+ }
555
+ );
556
+
557
+ let stopTelemetry = null;
558
+ if (budget.blocking) {
559
+ stopTelemetry = await appendRunEvent(
560
+ {
561
+ targetPath: normalizedTargetPath,
562
+ outputDirOverride: outputDir,
563
+ },
564
+ {
565
+ sessionId: normalizedSessionId,
566
+ runId: normalizedRunId,
567
+ eventType: "run_stop",
568
+ usage: {
569
+ inputTokens: sessionSummary.inputTokens,
570
+ outputTokens: sessionSummary.outputTokens,
571
+ cacheReadTokens: sessionSummary.cacheReadTokens,
572
+ cacheWriteTokens: sessionSummary.cacheWriteTokens,
573
+ costUsd: sessionSummary.costUsd,
574
+ durationMs: sessionSummary.durationMs,
575
+ toolCalls: sessionSummary.toolCalls,
576
+ },
577
+ stop: {
578
+ stopClass: deriveStopClassFromBudget(budget),
579
+ blocking: true,
580
+ reasonCodes: budget.reasons.map((reason) => reason.code),
581
+ },
582
+ metadata: {
583
+ sourceCommand: "review",
584
+ layer: "ai_reasoning",
585
+ provider: resolvedProvider,
586
+ model: resolvedModel,
587
+ invocationId: appendedCost.entry.invocationId,
588
+ dryRun: Boolean(dryRun),
589
+ },
590
+ }
591
+ );
592
+ }
593
+
594
+ await fsp.mkdir(normalizedRunDirectory, { recursive: true });
595
+ const promptPath = path.join(normalizedRunDirectory, "REVIEW_AI_PROMPT.txt");
596
+ const reportMarkdownPath = path.join(normalizedRunDirectory, "REVIEW_AI.md");
597
+ const reportJsonPath = path.join(normalizedRunDirectory, "REVIEW_AI.json");
598
+ const generatedAt = new Date().toISOString();
599
+ const usage = {
600
+ inputTokens,
601
+ outputTokens,
602
+ costUsd: modelCost.costUsd,
603
+ durationMs,
604
+ toolCalls: 1,
605
+ };
606
+ const reportPayload = {
607
+ schemaVersion: "1.0.0",
608
+ generatedAt,
609
+ runId: normalizedRunId,
610
+ mode: normalizedMode,
611
+ parser: parsed.parser,
612
+ summary: parsed.summary,
613
+ provider: resolvedProvider,
614
+ model: resolvedModel,
615
+ dryRun: Boolean(dryRun),
616
+ usage,
617
+ pricingFound: modelCost.pricingFound,
618
+ budget,
619
+ deterministicSummary,
620
+ aiSummary,
621
+ combinedSummary,
622
+ findings: aiFindings,
623
+ };
624
+
625
+ const reportMarkdown = composeAiReviewMarkdown({
626
+ generatedAt,
627
+ runId: normalizedRunId,
628
+ mode: normalizedMode,
629
+ parser: parsed.parser,
630
+ summary: parsed.summary,
631
+ provider: resolvedProvider,
632
+ model: resolvedModel,
633
+ dryRun: Boolean(dryRun),
634
+ findings: aiFindings,
635
+ usage,
636
+ combinedSummary,
637
+ });
638
+
639
+ await fsp.writeFile(promptPath, `${prompt}\n`, "utf-8");
640
+ await fsp.writeFile(reportMarkdownPath, `${reportMarkdown.trim()}\n`, "utf-8");
641
+ await fsp.writeFile(reportJsonPath, `${JSON.stringify(reportPayload, null, 2)}\n`, "utf-8");
642
+
643
+ return {
644
+ parser: parsed.parser,
645
+ summary: parsed.summary,
646
+ findings: aiFindings,
647
+ aiSummary,
648
+ combinedSummary,
649
+ provider: resolvedProvider,
650
+ model: resolvedModel,
651
+ dryRun: Boolean(dryRun),
652
+ usage,
653
+ pricingFound: modelCost.pricingFound,
654
+ budget,
655
+ artifacts: {
656
+ promptPath,
657
+ reportMarkdownPath,
658
+ reportJsonPath,
659
+ },
660
+ cost: {
661
+ filePath: appendedCost.filePath,
662
+ invocationId: appendedCost.entry.invocationId,
663
+ sessionId: normalizedSessionId,
664
+ },
665
+ telemetry: {
666
+ filePath: usageTelemetry.filePath,
667
+ usageEventId: usageTelemetry.event.eventId,
668
+ stopEventId: stopTelemetry?.event?.eventId || null,
669
+ },
670
+ };
671
+ }
672
+