sentinelayer-cli 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +62 -54
  6. package/src/agents/jules/config/definition.js +209 -209
  7. package/src/agents/jules/config/system-prompt.js +175 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +377 -377
  10. package/src/agents/jules/loop.js +367 -367
  11. package/src/agents/jules/pulse.js +319 -319
  12. package/src/agents/jules/stream.js +186 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +308 -308
  18. package/src/agents/jules/tools/auth-audit.js +226 -222
  19. package/src/agents/jules/tools/dispatch.js +327 -327
  20. package/src/agents/jules/tools/file-edit.js +180 -180
  21. package/src/agents/jules/tools/file-read.js +100 -100
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  23. package/src/agents/jules/tools/glob.js +168 -168
  24. package/src/agents/jules/tools/grep.js +228 -228
  25. package/src/agents/jules/tools/index.js +29 -29
  26. package/src/agents/jules/tools/path-guards.js +161 -161
  27. package/src/agents/jules/tools/runtime-audit.js +493 -493
  28. package/src/agents/jules/tools/shell.js +383 -383
  29. package/src/ai/aidenid.js +972 -945
  30. package/src/ai/client.js +508 -508
  31. package/src/ai/domain-target-store.js +268 -268
  32. package/src/ai/identity-store.js +270 -270
  33. package/src/ai/site-store.js +145 -145
  34. package/src/audit/agents/architecture.js +180 -180
  35. package/src/audit/agents/compliance.js +179 -179
  36. package/src/audit/agents/documentation.js +165 -165
  37. package/src/audit/agents/performance.js +145 -145
  38. package/src/audit/agents/security.js +215 -215
  39. package/src/audit/agents/testing.js +172 -172
  40. package/src/audit/orchestrator.js +557 -557
  41. package/src/audit/package.js +204 -204
  42. package/src/audit/registry.js +284 -284
  43. package/src/audit/replay.js +103 -103
  44. package/src/auth/http.js +113 -113
  45. package/src/auth/service.js +891 -848
  46. package/src/auth/session-store.js +359 -345
  47. package/src/cli.js +252 -252
  48. package/src/commands/ai/identity-lifecycle.js +1338 -1337
  49. package/src/commands/ai/provision-governance.js +1272 -1246
  50. package/src/commands/ai/shared.js +147 -147
  51. package/src/commands/ai.js +11 -11
  52. package/src/commands/apply.js +12 -12
  53. package/src/commands/audit.js +1166 -1147
  54. package/src/commands/auth.js +375 -366
  55. package/src/commands/chat.js +191 -191
  56. package/src/commands/config.js +184 -184
  57. package/src/commands/cost.js +311 -311
  58. package/src/commands/daemon/core.js +850 -850
  59. package/src/commands/daemon/extended.js +1048 -1048
  60. package/src/commands/daemon/shared.js +213 -213
  61. package/src/commands/daemon.js +11 -11
  62. package/src/commands/guide.js +174 -174
  63. package/src/commands/ingest.js +58 -58
  64. package/src/commands/init.js +55 -55
  65. package/src/commands/legacy-args.js +10 -10
  66. package/src/commands/mcp.js +461 -404
  67. package/src/commands/omargate.js +15 -15
  68. package/src/commands/persona.js +20 -20
  69. package/src/commands/plugin.js +260 -260
  70. package/src/commands/policy.js +132 -132
  71. package/src/commands/prompt.js +238 -238
  72. package/src/commands/review.js +704 -704
  73. package/src/commands/scan.js +866 -788
  74. package/src/commands/spec.js +716 -716
  75. package/src/commands/swarm.js +651 -651
  76. package/src/commands/telemetry.js +202 -202
  77. package/src/commands/watch.js +510 -510
  78. package/src/config/agent-dictionary.js +182 -182
  79. package/src/config/io.js +56 -56
  80. package/src/config/paths.js +18 -18
  81. package/src/config/schema.js +55 -55
  82. package/src/config/service.js +184 -184
  83. package/src/cost/budget.js +235 -235
  84. package/src/cost/history.js +188 -188
  85. package/src/cost/tracker.js +171 -171
  86. package/src/daemon/artifact-lineage.js +534 -534
  87. package/src/daemon/assignment-ledger.js +770 -770
  88. package/src/daemon/ast-parser-layer.js +258 -258
  89. package/src/daemon/budget-governor.js +633 -633
  90. package/src/daemon/callgraph-overlay.js +646 -646
  91. package/src/daemon/error-worker.js +626 -626
  92. package/src/daemon/hybrid-mapper.js +929 -929
  93. package/src/daemon/ingest-refresh.js +195 -0
  94. package/src/daemon/jira-lifecycle.js +632 -632
  95. package/src/daemon/operator-control.js +657 -657
  96. package/src/daemon/reliability-lane.js +471 -471
  97. package/src/daemon/watchdog.js +971 -971
  98. package/src/guide/generator.js +316 -316
  99. package/src/ingest/engine.js +918 -918
  100. package/src/interactive/action-menu.js +132 -0
  101. package/src/interactive/auto-ingest.js +111 -0
  102. package/src/interactive/index.js +95 -0
  103. package/src/interactive/workspace.js +92 -0
  104. package/src/legacy-cli.js +2548 -2435
  105. package/src/mcp/registry.js +695 -695
  106. package/src/memory/blackboard.js +301 -301
  107. package/src/memory/retrieval.js +581 -581
  108. package/src/plugin/manifest.js +553 -553
  109. package/src/policy/packs.js +144 -144
  110. package/src/prompt/generator.js +118 -106
  111. package/src/review/ai-review.js +669 -669
  112. package/src/review/local-review.js +1284 -1284
  113. package/src/review/replay.js +235 -235
  114. package/src/review/report.js +664 -664
  115. package/src/review/spec-binding.js +487 -487
  116. package/src/scaffold/generator.js +67 -0
  117. package/src/scaffold/templates.js +150 -0
  118. package/src/scan/generator.js +418 -351
  119. package/src/scan/gh-secrets.js +107 -0
  120. package/src/spec/generator.js +519 -519
  121. package/src/spec/regenerate.js +237 -237
  122. package/src/spec/templates.js +91 -91
  123. package/src/swarm/dashboard.js +247 -247
  124. package/src/swarm/factory.js +363 -363
  125. package/src/swarm/pentest.js +934 -934
  126. package/src/swarm/registry.js +419 -419
  127. package/src/swarm/report.js +158 -158
  128. package/src/swarm/runtime.js +576 -576
  129. package/src/swarm/scenario-dsl.js +272 -272
  130. package/src/telemetry/ledger.js +302 -302
  131. package/src/telemetry/session-tracker.js +118 -0
  132. package/src/telemetry/sync.js +190 -0
  133. package/src/ui/markdown.js +220 -220
@@ -1,669 +1,669 @@
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
- const resolvedProvider = resolveProvider({
417
- provider,
418
- configProvider: config.resolved.defaultModelProvider,
419
- env,
420
- });
421
- const resolvedModel = resolveModel({
422
- provider: resolvedProvider,
423
- model,
424
- configModel: config.resolved.defaultModelId || DEFAULT_REVIEW_AI_MODEL,
425
- });
426
- const explicitApiKey = normalizeString(apiKey);
427
- const configuredApiKey = resolveConfiguredApiKey(resolvedProvider, config.resolved);
428
-
429
- const prompt = buildAiReviewPrompt({
430
- targetPath: normalizedTargetPath,
431
- mode: normalizedMode,
432
- deterministicSummary: deterministic?.summary,
433
- deterministicFindings: deterministic?.findings || [],
434
- scopedFiles: deterministic?.scope?.scannedRelativeFiles || [],
435
- specContext: deterministic?.layers?.specBinding || null,
436
- maxFindings: normalizedMaxFindings,
437
- });
438
-
439
- const startedAt = Date.now();
440
- const responseText = dryRun
441
- ? buildDryRunResponse({
442
- deterministicSummary: deterministic?.summary || {},
443
- maxFindings: normalizedMaxFindings,
444
- })
445
- : (
446
- await createMultiProviderApiClient().invoke({
447
- provider: resolvedProvider,
448
- model: resolvedModel,
449
- prompt,
450
- apiKey: explicitApiKey || configuredApiKey,
451
- env,
452
- stream: false,
453
- })
454
- ).text;
455
- const durationMs = Math.max(0, Date.now() - startedAt);
456
-
457
- const parsed = parseAiReviewResponse({
458
- text: responseText,
459
- maxFindings: normalizedMaxFindings,
460
- });
461
- const aiFindings = parsed.findings.map((finding, index) => toReviewFinding(finding, index));
462
- const aiSummary = summarizeFindings(aiFindings);
463
- const deterministicSummary = deterministic?.summary || { P0: 0, P1: 0, P2: 0, P3: 0 };
464
- const combinedSummary = {
465
- P0: deterministicSummary.P0 + aiSummary.P0,
466
- P1: deterministicSummary.P1 + aiSummary.P1,
467
- P2: deterministicSummary.P2 + aiSummary.P2,
468
- P3: deterministicSummary.P3 + aiSummary.P3,
469
- };
470
- combinedSummary.blocking = combinedSummary.P0 > 0 || combinedSummary.P1 > 0;
471
-
472
- const inputTokens = estimateTokenCount(prompt);
473
- const outputTokens = estimateTokenCount(responseText);
474
- const modelCost = maybeEstimateModelCost({
475
- modelId: resolvedModel,
476
- inputTokens,
477
- outputTokens,
478
- });
479
- const normalizedSessionId =
480
- normalizeString(sessionId) || `${normalizedRunId}-ai`;
481
-
482
- const appendedCost = await appendCostEntry(
483
- {
484
- targetPath: normalizedTargetPath,
485
- outputDirOverride: outputDir,
486
- },
487
- {
488
- sessionId: normalizedSessionId,
489
- provider: resolvedProvider,
490
- model: resolvedModel,
491
- inputTokens,
492
- outputTokens,
493
- cacheReadTokens: 0,
494
- cacheWriteTokens: 0,
495
- durationMs,
496
- toolCalls: 1,
497
- costUsd: modelCost.costUsd,
498
- progressScore: aiFindings.length > 0 ? 1 : 0,
499
- }
500
- );
501
- const costSummary = summarizeCostHistory(appendedCost.history);
502
- const sessionSummary = costSummary.sessions.find((entry) => entry.sessionId === normalizedSessionId) || {
503
- sessionId: normalizedSessionId,
504
- invocationCount: 0,
505
- inputTokens: 0,
506
- outputTokens: 0,
507
- cacheReadTokens: 0,
508
- cacheWriteTokens: 0,
509
- durationMs: 0,
510
- toolCalls: 0,
511
- costUsd: 0,
512
- noProgressStreak: 0,
513
- };
514
-
515
- const budget = evaluateBudget({
516
- sessionSummary,
517
- maxCostUsd: parseNonNegativeNumber(maxCostUsd, "maxCostUsd"),
518
- maxOutputTokens: parseNonNegativeNumber(maxOutputTokens, "maxOutputTokens"),
519
- maxNoProgress: parseNonNegativeNumber(maxNoProgress, "maxNoProgress"),
520
- maxRuntimeMs: parseNonNegativeNumber(maxRuntimeMs, "maxRuntimeMs"),
521
- maxToolCalls: parseNonNegativeNumber(maxToolCalls, "maxToolCalls"),
522
- warningThresholdPercent: parsePercent(warningThresholdPercent, "warningThresholdPercent"),
523
- });
524
-
525
- const usageTelemetry = await appendRunEvent(
526
- {
527
- targetPath: normalizedTargetPath,
528
- outputDirOverride: outputDir,
529
- },
530
- {
531
- sessionId: normalizedSessionId,
532
- runId: normalizedRunId,
533
- eventType: "usage",
534
- usage: {
535
- inputTokens,
536
- outputTokens,
537
- cacheReadTokens: 0,
538
- cacheWriteTokens: 0,
539
- costUsd: modelCost.costUsd,
540
- durationMs,
541
- toolCalls: 1,
542
- },
543
- metadata: {
544
- sourceCommand: "review",
545
- layer: "ai_reasoning",
546
- provider: resolvedProvider,
547
- model: resolvedModel,
548
- invocationId: appendedCost.entry.invocationId,
549
- dryRun: Boolean(dryRun),
550
- },
551
- }
552
- );
553
-
554
- let stopTelemetry = null;
555
- if (budget.blocking) {
556
- stopTelemetry = await appendRunEvent(
557
- {
558
- targetPath: normalizedTargetPath,
559
- outputDirOverride: outputDir,
560
- },
561
- {
562
- sessionId: normalizedSessionId,
563
- runId: normalizedRunId,
564
- eventType: "run_stop",
565
- usage: {
566
- inputTokens: sessionSummary.inputTokens,
567
- outputTokens: sessionSummary.outputTokens,
568
- cacheReadTokens: sessionSummary.cacheReadTokens,
569
- cacheWriteTokens: sessionSummary.cacheWriteTokens,
570
- costUsd: sessionSummary.costUsd,
571
- durationMs: sessionSummary.durationMs,
572
- toolCalls: sessionSummary.toolCalls,
573
- },
574
- stop: {
575
- stopClass: deriveStopClassFromBudget(budget),
576
- blocking: true,
577
- reasonCodes: budget.reasons.map((reason) => reason.code),
578
- },
579
- metadata: {
580
- sourceCommand: "review",
581
- layer: "ai_reasoning",
582
- provider: resolvedProvider,
583
- model: resolvedModel,
584
- invocationId: appendedCost.entry.invocationId,
585
- dryRun: Boolean(dryRun),
586
- },
587
- }
588
- );
589
- }
590
-
591
- await fsp.mkdir(normalizedRunDirectory, { recursive: true });
592
- const promptPath = path.join(normalizedRunDirectory, "REVIEW_AI_PROMPT.txt");
593
- const reportMarkdownPath = path.join(normalizedRunDirectory, "REVIEW_AI.md");
594
- const reportJsonPath = path.join(normalizedRunDirectory, "REVIEW_AI.json");
595
- const generatedAt = new Date().toISOString();
596
- const usage = {
597
- inputTokens,
598
- outputTokens,
599
- costUsd: modelCost.costUsd,
600
- durationMs,
601
- toolCalls: 1,
602
- };
603
- const reportPayload = {
604
- schemaVersion: "1.0.0",
605
- generatedAt,
606
- runId: normalizedRunId,
607
- mode: normalizedMode,
608
- parser: parsed.parser,
609
- summary: parsed.summary,
610
- provider: resolvedProvider,
611
- model: resolvedModel,
612
- dryRun: Boolean(dryRun),
613
- usage,
614
- pricingFound: modelCost.pricingFound,
615
- budget,
616
- deterministicSummary,
617
- aiSummary,
618
- combinedSummary,
619
- findings: aiFindings,
620
- };
621
-
622
- const reportMarkdown = composeAiReviewMarkdown({
623
- generatedAt,
624
- runId: normalizedRunId,
625
- mode: normalizedMode,
626
- parser: parsed.parser,
627
- summary: parsed.summary,
628
- provider: resolvedProvider,
629
- model: resolvedModel,
630
- dryRun: Boolean(dryRun),
631
- findings: aiFindings,
632
- usage,
633
- combinedSummary,
634
- });
635
-
636
- await fsp.writeFile(promptPath, `${prompt}\n`, "utf-8");
637
- await fsp.writeFile(reportMarkdownPath, `${reportMarkdown.trim()}\n`, "utf-8");
638
- await fsp.writeFile(reportJsonPath, `${JSON.stringify(reportPayload, null, 2)}\n`, "utf-8");
639
-
640
- return {
641
- parser: parsed.parser,
642
- summary: parsed.summary,
643
- findings: aiFindings,
644
- aiSummary,
645
- combinedSummary,
646
- provider: resolvedProvider,
647
- model: resolvedModel,
648
- dryRun: Boolean(dryRun),
649
- usage,
650
- pricingFound: modelCost.pricingFound,
651
- budget,
652
- artifacts: {
653
- promptPath,
654
- reportMarkdownPath,
655
- reportJsonPath,
656
- },
657
- cost: {
658
- filePath: appendedCost.filePath,
659
- invocationId: appendedCost.entry.invocationId,
660
- sessionId: normalizedSessionId,
661
- },
662
- telemetry: {
663
- filePath: usageTelemetry.filePath,
664
- usageEventId: usageTelemetry.event.eventId,
665
- stopEventId: stopTelemetry?.event?.eventId || null,
666
- },
667
- };
668
- }
669
-
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
+ const resolvedProvider = resolveProvider({
417
+ provider,
418
+ configProvider: config.resolved.defaultModelProvider,
419
+ env,
420
+ });
421
+ const resolvedModel = resolveModel({
422
+ provider: resolvedProvider,
423
+ model,
424
+ configModel: config.resolved.defaultModelId || DEFAULT_REVIEW_AI_MODEL,
425
+ });
426
+ const explicitApiKey = normalizeString(apiKey);
427
+ const configuredApiKey = resolveConfiguredApiKey(resolvedProvider, config.resolved);
428
+
429
+ const prompt = buildAiReviewPrompt({
430
+ targetPath: normalizedTargetPath,
431
+ mode: normalizedMode,
432
+ deterministicSummary: deterministic?.summary,
433
+ deterministicFindings: deterministic?.findings || [],
434
+ scopedFiles: deterministic?.scope?.scannedRelativeFiles || [],
435
+ specContext: deterministic?.layers?.specBinding || null,
436
+ maxFindings: normalizedMaxFindings,
437
+ });
438
+
439
+ const startedAt = Date.now();
440
+ const responseText = dryRun
441
+ ? buildDryRunResponse({
442
+ deterministicSummary: deterministic?.summary || {},
443
+ maxFindings: normalizedMaxFindings,
444
+ })
445
+ : (
446
+ await createMultiProviderApiClient().invoke({
447
+ provider: resolvedProvider,
448
+ model: resolvedModel,
449
+ prompt,
450
+ apiKey: explicitApiKey || configuredApiKey,
451
+ env,
452
+ stream: false,
453
+ })
454
+ ).text;
455
+ const durationMs = Math.max(0, Date.now() - startedAt);
456
+
457
+ const parsed = parseAiReviewResponse({
458
+ text: responseText,
459
+ maxFindings: normalizedMaxFindings,
460
+ });
461
+ const aiFindings = parsed.findings.map((finding, index) => toReviewFinding(finding, index));
462
+ const aiSummary = summarizeFindings(aiFindings);
463
+ const deterministicSummary = deterministic?.summary || { P0: 0, P1: 0, P2: 0, P3: 0 };
464
+ const combinedSummary = {
465
+ P0: deterministicSummary.P0 + aiSummary.P0,
466
+ P1: deterministicSummary.P1 + aiSummary.P1,
467
+ P2: deterministicSummary.P2 + aiSummary.P2,
468
+ P3: deterministicSummary.P3 + aiSummary.P3,
469
+ };
470
+ combinedSummary.blocking = combinedSummary.P0 > 0 || combinedSummary.P1 > 0;
471
+
472
+ const inputTokens = estimateTokenCount(prompt);
473
+ const outputTokens = estimateTokenCount(responseText);
474
+ const modelCost = maybeEstimateModelCost({
475
+ modelId: resolvedModel,
476
+ inputTokens,
477
+ outputTokens,
478
+ });
479
+ const normalizedSessionId =
480
+ normalizeString(sessionId) || `${normalizedRunId}-ai`;
481
+
482
+ const appendedCost = await appendCostEntry(
483
+ {
484
+ targetPath: normalizedTargetPath,
485
+ outputDirOverride: outputDir,
486
+ },
487
+ {
488
+ sessionId: normalizedSessionId,
489
+ provider: resolvedProvider,
490
+ model: resolvedModel,
491
+ inputTokens,
492
+ outputTokens,
493
+ cacheReadTokens: 0,
494
+ cacheWriteTokens: 0,
495
+ durationMs,
496
+ toolCalls: 1,
497
+ costUsd: modelCost.costUsd,
498
+ progressScore: aiFindings.length > 0 ? 1 : 0,
499
+ }
500
+ );
501
+ const costSummary = summarizeCostHistory(appendedCost.history);
502
+ const sessionSummary = costSummary.sessions.find((entry) => entry.sessionId === normalizedSessionId) || {
503
+ sessionId: normalizedSessionId,
504
+ invocationCount: 0,
505
+ inputTokens: 0,
506
+ outputTokens: 0,
507
+ cacheReadTokens: 0,
508
+ cacheWriteTokens: 0,
509
+ durationMs: 0,
510
+ toolCalls: 0,
511
+ costUsd: 0,
512
+ noProgressStreak: 0,
513
+ };
514
+
515
+ const budget = evaluateBudget({
516
+ sessionSummary,
517
+ maxCostUsd: parseNonNegativeNumber(maxCostUsd, "maxCostUsd"),
518
+ maxOutputTokens: parseNonNegativeNumber(maxOutputTokens, "maxOutputTokens"),
519
+ maxNoProgress: parseNonNegativeNumber(maxNoProgress, "maxNoProgress"),
520
+ maxRuntimeMs: parseNonNegativeNumber(maxRuntimeMs, "maxRuntimeMs"),
521
+ maxToolCalls: parseNonNegativeNumber(maxToolCalls, "maxToolCalls"),
522
+ warningThresholdPercent: parsePercent(warningThresholdPercent, "warningThresholdPercent"),
523
+ });
524
+
525
+ const usageTelemetry = await appendRunEvent(
526
+ {
527
+ targetPath: normalizedTargetPath,
528
+ outputDirOverride: outputDir,
529
+ },
530
+ {
531
+ sessionId: normalizedSessionId,
532
+ runId: normalizedRunId,
533
+ eventType: "usage",
534
+ usage: {
535
+ inputTokens,
536
+ outputTokens,
537
+ cacheReadTokens: 0,
538
+ cacheWriteTokens: 0,
539
+ costUsd: modelCost.costUsd,
540
+ durationMs,
541
+ toolCalls: 1,
542
+ },
543
+ metadata: {
544
+ sourceCommand: "review",
545
+ layer: "ai_reasoning",
546
+ provider: resolvedProvider,
547
+ model: resolvedModel,
548
+ invocationId: appendedCost.entry.invocationId,
549
+ dryRun: Boolean(dryRun),
550
+ },
551
+ }
552
+ );
553
+
554
+ let stopTelemetry = null;
555
+ if (budget.blocking) {
556
+ stopTelemetry = await appendRunEvent(
557
+ {
558
+ targetPath: normalizedTargetPath,
559
+ outputDirOverride: outputDir,
560
+ },
561
+ {
562
+ sessionId: normalizedSessionId,
563
+ runId: normalizedRunId,
564
+ eventType: "run_stop",
565
+ usage: {
566
+ inputTokens: sessionSummary.inputTokens,
567
+ outputTokens: sessionSummary.outputTokens,
568
+ cacheReadTokens: sessionSummary.cacheReadTokens,
569
+ cacheWriteTokens: sessionSummary.cacheWriteTokens,
570
+ costUsd: sessionSummary.costUsd,
571
+ durationMs: sessionSummary.durationMs,
572
+ toolCalls: sessionSummary.toolCalls,
573
+ },
574
+ stop: {
575
+ stopClass: deriveStopClassFromBudget(budget),
576
+ blocking: true,
577
+ reasonCodes: budget.reasons.map((reason) => reason.code),
578
+ },
579
+ metadata: {
580
+ sourceCommand: "review",
581
+ layer: "ai_reasoning",
582
+ provider: resolvedProvider,
583
+ model: resolvedModel,
584
+ invocationId: appendedCost.entry.invocationId,
585
+ dryRun: Boolean(dryRun),
586
+ },
587
+ }
588
+ );
589
+ }
590
+
591
+ await fsp.mkdir(normalizedRunDirectory, { recursive: true });
592
+ const promptPath = path.join(normalizedRunDirectory, "REVIEW_AI_PROMPT.txt");
593
+ const reportMarkdownPath = path.join(normalizedRunDirectory, "REVIEW_AI.md");
594
+ const reportJsonPath = path.join(normalizedRunDirectory, "REVIEW_AI.json");
595
+ const generatedAt = new Date().toISOString();
596
+ const usage = {
597
+ inputTokens,
598
+ outputTokens,
599
+ costUsd: modelCost.costUsd,
600
+ durationMs,
601
+ toolCalls: 1,
602
+ };
603
+ const reportPayload = {
604
+ schemaVersion: "1.0.0",
605
+ generatedAt,
606
+ runId: normalizedRunId,
607
+ mode: normalizedMode,
608
+ parser: parsed.parser,
609
+ summary: parsed.summary,
610
+ provider: resolvedProvider,
611
+ model: resolvedModel,
612
+ dryRun: Boolean(dryRun),
613
+ usage,
614
+ pricingFound: modelCost.pricingFound,
615
+ budget,
616
+ deterministicSummary,
617
+ aiSummary,
618
+ combinedSummary,
619
+ findings: aiFindings,
620
+ };
621
+
622
+ const reportMarkdown = composeAiReviewMarkdown({
623
+ generatedAt,
624
+ runId: normalizedRunId,
625
+ mode: normalizedMode,
626
+ parser: parsed.parser,
627
+ summary: parsed.summary,
628
+ provider: resolvedProvider,
629
+ model: resolvedModel,
630
+ dryRun: Boolean(dryRun),
631
+ findings: aiFindings,
632
+ usage,
633
+ combinedSummary,
634
+ });
635
+
636
+ await fsp.writeFile(promptPath, `${prompt}\n`, "utf-8");
637
+ await fsp.writeFile(reportMarkdownPath, `${reportMarkdown.trim()}\n`, "utf-8");
638
+ await fsp.writeFile(reportJsonPath, `${JSON.stringify(reportPayload, null, 2)}\n`, "utf-8");
639
+
640
+ return {
641
+ parser: parsed.parser,
642
+ summary: parsed.summary,
643
+ findings: aiFindings,
644
+ aiSummary,
645
+ combinedSummary,
646
+ provider: resolvedProvider,
647
+ model: resolvedModel,
648
+ dryRun: Boolean(dryRun),
649
+ usage,
650
+ pricingFound: modelCost.pricingFound,
651
+ budget,
652
+ artifacts: {
653
+ promptPath,
654
+ reportMarkdownPath,
655
+ reportJsonPath,
656
+ },
657
+ cost: {
658
+ filePath: appendedCost.filePath,
659
+ invocationId: appendedCost.entry.invocationId,
660
+ sessionId: normalizedSessionId,
661
+ },
662
+ telemetry: {
663
+ filePath: usageTelemetry.filePath,
664
+ usageEventId: usageTelemetry.event.eventId,
665
+ stopEventId: stopTelemetry?.event?.eventId || null,
666
+ },
667
+ };
668
+ }
669
+