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,1284 +1,1284 @@
1
- import { spawnSync } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
3
- import fsp from "node:fs/promises";
4
- import path from "node:path";
5
-
6
- import { resolveOutputRoot } from "../config/service.js";
7
- import { resolveCodebaseIngest } from "../ingest/engine.js";
8
- import { runSpecBindingChecks } from "./spec-binding.js";
9
-
10
- const IGNORED_DIRS = new Set([
11
- ".git",
12
- "node_modules",
13
- ".venv",
14
- ".next",
15
- "dist",
16
- "build",
17
- ".sentinelayer",
18
- ]);
19
- const MAX_FILE_SIZE_BYTES = 512 * 1024;
20
- const MAX_FINDINGS = 250;
21
- const STATIC_CHECK_TIMEOUT_MS = 120_000;
22
-
23
- const SOURCE_CODE_EXTENSIONS = new Set([
24
- ".js",
25
- ".jsx",
26
- ".mjs",
27
- ".cjs",
28
- ".ts",
29
- ".tsx",
30
- ".py",
31
- ".go",
32
- ".rs",
33
- ".java",
34
- ".kt",
35
- ".cs",
36
- ".rb",
37
- ".php",
38
- ".sql",
39
- ]);
40
-
41
- const SEVERITY_ORDER = new Map([
42
- ["P0", 0],
43
- ["P1", 1],
44
- ["P2", 2],
45
- ["P3", 3],
46
- ]);
47
-
48
- const REVIEW_RULES = Object.freeze([
49
- {
50
- severity: "P1",
51
- message: "Possible AWS access key detected.",
52
- regex: /AKIA[0-9A-Z]{16}/,
53
- },
54
- {
55
- severity: "P1",
56
- message: "Possible private key material detected.",
57
- regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
58
- },
59
- {
60
- severity: "P1",
61
- message: "Possible provider API key detected.",
62
- regex: /\b(sk-[A-Za-z0-9]{20,}|ghp_[A-Za-z0-9]{20,})\b/,
63
- },
64
- {
65
- severity: "P2",
66
- message: "Possible hardcoded credential literal.",
67
- regex: /(api[_-]?key|secret|token)\s*[:=]\s*['\"][^'\"]{20,}['\"]/i,
68
- },
69
- {
70
- severity: "P2",
71
- message: "Work-item marker found.",
72
- regex: /\b(?:\x54\x4f\x44\x4f|\x46\x49\x58\x4d\x45|\x48\x41\x43\x4b)\b/,
73
- },
74
- ]);
75
-
76
- const DETERMINISTIC_REVIEW_RULES = Object.freeze([
77
- {
78
- id: "SL-SEC-001",
79
- severity: "P1",
80
- message: "Possible AWS access key detected.",
81
- suggestedFix: "Remove committed credentials and rotate the key.",
82
- regex: /AKIA[0-9A-Z]{16}/,
83
- sourceOnly: true,
84
- },
85
- {
86
- id: "SL-SEC-002",
87
- severity: "P1",
88
- message: "Possible private key material detected.",
89
- suggestedFix: "Delete committed key material and rotate any dependent certs.",
90
- regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
91
- },
92
- {
93
- id: "SL-SEC-003",
94
- severity: "P1",
95
- message: "Possible GitHub token detected.",
96
- suggestedFix: "Revoke and rotate token; source from secure runtime config.",
97
- regex: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/,
98
- sourceOnly: true,
99
- },
100
- {
101
- id: "SL-SEC-004",
102
- severity: "P1",
103
- message: "Possible provider API key detected.",
104
- suggestedFix: "Rotate API keys and move to managed secret storage.",
105
- regex: /\b(sk-[A-Za-z0-9]{20,})\b/,
106
- sourceOnly: true,
107
- },
108
- {
109
- id: "SL-SEC-005",
110
- severity: "P2",
111
- message: "Possible hardcoded credential literal.",
112
- suggestedFix: "Replace literal with environment/secret-manager lookup.",
113
- regex: /(api[_-]?key|secret|token|password|passwd)\s*[:=]\s*['\"][^'\"]{12,}['\"]/i,
114
- sourceOnly: true,
115
- },
116
- {
117
- id: "SL-SEC-006",
118
- severity: "P2",
119
- message: "Possible hardcoded bearer token.",
120
- suggestedFix: "Remove token literals and rotate exposed credentials.",
121
- regex: /Bearer\s+[A-Za-z0-9._\-]{20,}/,
122
- sourceOnly: true,
123
- },
124
- {
125
- id: "SL-SEC-007",
126
- severity: "P2",
127
- message: "Possible embedded JWT detected.",
128
- suggestedFix: "Do not store JWTs in source code.",
129
- regex: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,
130
- sourceOnly: true,
131
- },
132
- {
133
- id: "SL-SEC-008",
134
- severity: "P2",
135
- message: "Potential database connection string with inline credentials.",
136
- suggestedFix: "Externalize DSN and rotate embedded credentials.",
137
- regex: /(postgres|mysql|mariadb|sqlserver):\/\/[^\s:@]+:[^\s@]+@/i,
138
- sourceOnly: true,
139
- },
140
- {
141
- id: "SL-SEC-009",
142
- severity: "P2",
143
- message: "Potential MongoDB URI with inline credentials.",
144
- suggestedFix: "Use secret-managed URI and avoid inline username/password.",
145
- regex: /mongodb(?:\+srv)?:\/\/[^\s:@]+:[^\s@]+@/i,
146
- sourceOnly: true,
147
- },
148
- {
149
- id: "SL-SEC-010",
150
- severity: "P2",
151
- message: "Potential Redis URI with inline credentials.",
152
- suggestedFix: "Move Redis credentials to secret manager.",
153
- regex: /redis(?:\+tls)?:\/\/[^\s:@]+:[^\s@]+@/i,
154
- sourceOnly: true,
155
- },
156
- {
157
- id: "SL-SEC-011",
158
- severity: "P1",
159
- message: "Possible Slack webhook URL detected.",
160
- suggestedFix: "Rotate webhook and store it outside source control.",
161
- regex: /https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9/]+/,
162
- sourceOnly: true,
163
- },
164
- {
165
- id: "SL-SEC-012",
166
- severity: "P1",
167
- message: "Possible Stripe live secret key detected.",
168
- suggestedFix: "Rotate Stripe key and use secure runtime injection.",
169
- regex: /\bsk_live_[A-Za-z0-9]{16,}\b/,
170
- sourceOnly: true,
171
- },
172
- {
173
- id: "SL-SEC-013",
174
- severity: "P2",
175
- message: "Plain HTTP endpoint literal found.",
176
- suggestedFix: "Prefer HTTPS endpoints in production paths.",
177
- regex: /\bhttp:\/\/[^\s'"]+/i,
178
- sourceOnly: true,
179
- },
180
- {
181
- id: "SL-SEC-014",
182
- severity: "P2",
183
- message: "Work-item marker detected (TODO/FIXME/HACK).",
184
- suggestedFix: "Resolve or scope pending work before release.",
185
- regex: /\b(?:TODO|FIXME|HACK)\b/,
186
- sourceOnly: true,
187
- },
188
- {
189
- id: "SL-SEC-015",
190
- severity: "P1",
191
- message: "Dynamic code execution primitive detected (`eval`).",
192
- suggestedFix: "Replace eval with explicit parser or safe handlers.",
193
- regex: /\beval\s*\(/,
194
- sourceOnly: true,
195
- },
196
- {
197
- id: "SL-SEC-016",
198
- severity: "P2",
199
- message: "Template-literal shell execution detected.",
200
- suggestedFix: "Avoid shell interpolation with untrusted inputs.",
201
- regex: /exec(?:Sync)?\s*\(\s*`[^`]*\$\{[^}]+\}[^`]*`\s*\)/,
202
- sourceOnly: true,
203
- },
204
- {
205
- id: "SL-SEC-017",
206
- severity: "P2",
207
- message: "Possible SQL string concatenation detected.",
208
- suggestedFix: "Use parameterized queries and prepared statements.",
209
- regex: /\b(?:SELECT|INSERT|UPDATE|DELETE)\b[^;\n]{0,140}\+/i,
210
- sourceOnly: true,
211
- },
212
- {
213
- id: "SL-SEC-018",
214
- severity: "P1",
215
- message: "Potential wildcard CORS policy detected.",
216
- suggestedFix: "Replace wildcard CORS with explicit allowlist.",
217
- regex: /Access-Control-Allow-Origin\s*[:=]\s*['"]\*['"]/i,
218
- sourceOnly: true,
219
- },
220
- {
221
- id: "SL-SEC-019",
222
- severity: "P1",
223
- message: "TLS certificate verification appears disabled.",
224
- suggestedFix: "Remove insecure TLS bypass and use valid certificates.",
225
- regex: /NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0['"]?/i,
226
- sourceOnly: true,
227
- },
228
- {
229
- id: "SL-SEC-020",
230
- severity: "P2",
231
- message: "Potentially sensitive value logged directly.",
232
- suggestedFix: "Redact secrets/tokens before logging.",
233
- regex: /console\.(?:log|debug|info)\([^)]*(token|secret|password|api[_-]?key)/i,
234
- sourceOnly: true,
235
- },
236
- {
237
- id: "SL-SEC-021",
238
- severity: "P2",
239
- message: "Tracked environment file may contain secrets.",
240
- suggestedFix: "Commit only sanitized `.env.example` files.",
241
- kind: "file",
242
- filePattern: /(^|\/)\.env(\.[^/]+)?$/i,
243
- excludePathPattern: /\.example$/i,
244
- },
245
- {
246
- id: "SL-SEC-022",
247
- severity: "P2",
248
- message: "Hardcoded localhost callback URL detected.",
249
- suggestedFix: "Externalize callback URLs to environment config.",
250
- regex: /https?:\/\/localhost:\d{2,5}\//i,
251
- sourceOnly: true,
252
- },
253
- ]);
254
-
255
- function formatTimestampForFile() {
256
- const now = new Date();
257
- const pad = (value) => String(value).padStart(2, "0");
258
- return `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}-${pad(
259
- now.getUTCHours()
260
- )}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`;
261
- }
262
-
263
- function toPosixPath(value) {
264
- return String(value || "").replace(/\\/g, "/");
265
- }
266
-
267
- function normalizeMode(mode, { allowedModes = ["full", "diff", "staged"] } = {}) {
268
- const normalized = String(mode || "full").trim().toLowerCase();
269
- if (!allowedModes.includes(normalized)) {
270
- throw new Error(`mode must be one of: ${allowedModes.join(", ")}.`);
271
- }
272
- return normalized;
273
- }
274
-
275
- function isSourceLikeFile(relativePath) {
276
- const extension = path.extname(relativePath).toLowerCase();
277
- return SOURCE_CODE_EXTENSIONS.has(extension);
278
- }
279
-
280
- function severityRank(value) {
281
- return SEVERITY_ORDER.has(value) ? SEVERITY_ORDER.get(value) : 99;
282
- }
283
-
284
- function regexMatches(regex, input) {
285
- const flags = regex.flags.replace(/g/g, "");
286
- return new RegExp(regex.source, flags).test(input);
287
- }
288
-
289
- function sanitizeLineForExcerpt(line) {
290
- return String(line || "")
291
- .trim()
292
- .replace(/\s+/g, " ")
293
- .slice(0, 180);
294
- }
295
-
296
- function createFinding({
297
- severity,
298
- file,
299
- line,
300
- message,
301
- excerpt,
302
- ruleId,
303
- suggestedFix,
304
- layer,
305
- }) {
306
- return {
307
- severity,
308
- file,
309
- line,
310
- message,
311
- excerpt,
312
- ruleId,
313
- suggestedFix,
314
- layer,
315
- };
316
- }
317
-
318
- function tryPushFinding(findings, finding, maxFindings) {
319
- if (findings.length >= maxFindings) {
320
- return false;
321
- }
322
- findings.push(finding);
323
- return true;
324
- }
325
-
326
- function ruleAppliesToPath(rule, relativePath) {
327
- if (rule.filePattern && !rule.filePattern.test(relativePath)) {
328
- return false;
329
- }
330
- if (rule.excludePathPattern && rule.excludePathPattern.test(relativePath)) {
331
- return false;
332
- }
333
- if (Array.isArray(rule.allowedExtensions) && rule.allowedExtensions.length > 0) {
334
- const extension = path.extname(relativePath).toLowerCase();
335
- if (!rule.allowedExtensions.includes(extension)) {
336
- return false;
337
- }
338
- }
339
- if (rule.sourceOnly && !isSourceLikeFile(relativePath)) {
340
- return false;
341
- }
342
- return true;
343
- }
344
-
345
- function isIgnoredPath(rootPath, candidatePath) {
346
- const relative = path.relative(rootPath, candidatePath);
347
- if (!relative || relative.startsWith("..")) {
348
- return true;
349
- }
350
- const parts = relative.split(/[\\/]+/g).filter(Boolean);
351
- return parts.some((part) => IGNORED_DIRS.has(part));
352
- }
353
-
354
- async function includeFileIfScannable(rootPath, filePath, outputSet) {
355
- if (isIgnoredPath(rootPath, filePath)) {
356
- return;
357
- }
358
-
359
- try {
360
- const stat = await fsp.stat(filePath);
361
- if (!stat.isFile()) {
362
- return;
363
- }
364
- if (stat.size > MAX_FILE_SIZE_BYTES) {
365
- return;
366
- }
367
- } catch {
368
- return;
369
- }
370
-
371
- outputSet.add(path.resolve(filePath));
372
- }
373
-
374
- async function collectAllScanFiles(rootPath) {
375
- const files = new Set();
376
- const stack = [rootPath];
377
-
378
- while (stack.length > 0) {
379
- const current = stack.pop();
380
- if (!current) {
381
- continue;
382
- }
383
- let entries = [];
384
- try {
385
- entries = await fsp.readdir(current, { withFileTypes: true });
386
- } catch {
387
- continue;
388
- }
389
-
390
- for (const entry of entries) {
391
- const fullPath = path.join(current, entry.name);
392
- if (entry.isDirectory()) {
393
- if (IGNORED_DIRS.has(entry.name)) {
394
- continue;
395
- }
396
- stack.push(fullPath);
397
- continue;
398
- }
399
- if (!entry.isFile()) {
400
- continue;
401
- }
402
- await includeFileIfScannable(rootPath, fullPath, files);
403
- }
404
- }
405
-
406
- return [...files].sort((left, right) => left.localeCompare(right));
407
- }
408
-
409
- function runGitList(cwd, args) {
410
- const result = spawnSync("git", args, {
411
- cwd,
412
- encoding: "utf-8",
413
- });
414
- if (result.status !== 0) {
415
- return [];
416
- }
417
- return String(result.stdout || "")
418
- .split(/\r?\n/g)
419
- .map((line) => line.trim())
420
- .filter(Boolean);
421
- }
422
-
423
- async function collectDiffScanFiles(rootPath) {
424
- const revParse = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], {
425
- cwd: rootPath,
426
- encoding: "utf-8",
427
- });
428
- if (revParse.status !== 0 || !String(revParse.stdout || "").trim().toLowerCase().includes("true")) {
429
- throw new Error("Diff review mode requires a git repository.");
430
- }
431
-
432
- const changedRelativePaths = new Set([
433
- ...runGitList(rootPath, ["diff", "--name-only", "--diff-filter=ACMRTUXB"]),
434
- ...runGitList(rootPath, ["diff", "--name-only", "--cached", "--diff-filter=ACMRTUXB"]),
435
- ...runGitList(rootPath, ["ls-files", "--others", "--exclude-standard"]),
436
- ]);
437
-
438
- const files = new Set();
439
- for (const relativePath of changedRelativePaths) {
440
- const absolutePath = path.resolve(rootPath, relativePath);
441
- await includeFileIfScannable(rootPath, absolutePath, files);
442
- }
443
-
444
- return [...files].sort((left, right) => left.localeCompare(right));
445
- }
446
-
447
- async function collectStagedScanFiles(rootPath) {
448
- const revParse = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], {
449
- cwd: rootPath,
450
- encoding: "utf-8",
451
- });
452
- if (revParse.status !== 0 || !String(revParse.stdout || "").trim().toLowerCase().includes("true")) {
453
- throw new Error("Staged review mode requires a git repository.");
454
- }
455
-
456
- const changedRelativePaths = runGitList(rootPath, [
457
- "diff",
458
- "--name-only",
459
- "--cached",
460
- "--diff-filter=ACMRTUXB",
461
- ]);
462
-
463
- const files = new Set();
464
- for (const relativePath of changedRelativePaths) {
465
- const absolutePath = path.resolve(rootPath, relativePath);
466
- await includeFileIfScannable(rootPath, absolutePath, files);
467
- }
468
-
469
- return [...files].sort((left, right) => left.localeCompare(right));
470
- }
471
-
472
- async function collectModeFilePaths(rootPath, mode) {
473
- if (mode === "diff") {
474
- return collectDiffScanFiles(rootPath);
475
- }
476
- if (mode === "staged") {
477
- return collectStagedScanFiles(rootPath);
478
- }
479
- return collectAllScanFiles(rootPath);
480
- }
481
-
482
- async function scanRulesForFiles({ rootPath, filePaths, rules, maxFindings = MAX_FINDINGS, layer = "structural" } = {}) {
483
- const findings = [];
484
-
485
- for (const filePath of filePaths) {
486
- if (findings.length >= maxFindings) {
487
- break;
488
- }
489
-
490
- const relativePath = toPosixPath(path.relative(rootPath, filePath));
491
- const activeRules = rules.filter((rule) => ruleAppliesToPath(rule, relativePath));
492
- if (activeRules.length === 0) {
493
- continue;
494
- }
495
-
496
- const fileRules = activeRules.filter((rule) => String(rule.kind || "line") === "file");
497
- for (const rule of fileRules) {
498
- const pushed = tryPushFinding(
499
- findings,
500
- createFinding({
501
- severity: rule.severity,
502
- file: relativePath,
503
- line: 1,
504
- message: rule.message,
505
- excerpt: "File-level policy match",
506
- ruleId: rule.id || "SL-RULE",
507
- suggestedFix: rule.suggestedFix || "Review and remediate this finding.",
508
- layer,
509
- }),
510
- maxFindings
511
- );
512
- if (!pushed) {
513
- break;
514
- }
515
- }
516
- if (findings.length >= maxFindings) {
517
- break;
518
- }
519
-
520
- let text = "";
521
- try {
522
- text = await fsp.readFile(filePath, "utf-8");
523
- } catch {
524
- continue;
525
- }
526
- const lines = text.split(/\r?\n/g);
527
- const lineRules = activeRules.filter((rule) => String(rule.kind || "line") !== "file");
528
- for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
529
- if (findings.length >= maxFindings) {
530
- break;
531
- }
532
- const line = lines[lineIndex];
533
- if (!line) {
534
- continue;
535
- }
536
- if (line.includes("<your-token>") || line.includes("example")) {
537
- continue;
538
- }
539
- for (const rule of lineRules) {
540
- if (!regexMatches(rule.regex, line)) {
541
- continue;
542
- }
543
- const pushed = tryPushFinding(
544
- findings,
545
- createFinding({
546
- severity: rule.severity,
547
- file: relativePath,
548
- line: lineIndex + 1,
549
- message: rule.message,
550
- excerpt: sanitizeLineForExcerpt(line),
551
- ruleId: rule.id || "SL-RULE",
552
- suggestedFix: rule.suggestedFix || "Review and remediate this finding.",
553
- layer,
554
- }),
555
- maxFindings
556
- );
557
- if (!pushed) {
558
- break;
559
- }
560
- }
561
- }
562
- }
563
-
564
- return findings;
565
- }
566
-
567
- async function scanFileSet(rootPath, filePaths) {
568
- const findings = await scanRulesForFiles({
569
- rootPath,
570
- filePaths,
571
- rules: REVIEW_RULES,
572
- maxFindings: MAX_FINDINGS,
573
- layer: "scan",
574
- });
575
-
576
- const p1 = findings.filter((item) => item.severity === "P1").length;
577
- const p2 = findings.filter((item) => item.severity === "P2").length;
578
-
579
- return {
580
- scannedFiles: filePaths.length,
581
- findings,
582
- p1,
583
- p2,
584
- };
585
- }
586
-
587
- function resolveLineNumberFromIndex(text, index) {
588
- if (!Number.isFinite(index) || index < 0) {
589
- return 1;
590
- }
591
- const prior = String(text || "").slice(0, index);
592
- return prior.split(/\r?\n/g).length;
593
- }
594
-
595
- async function runPatternChecks({ rootPath, filePaths, maxFindings = MAX_FINDINGS } = {}) {
596
- const findings = [];
597
-
598
- for (const filePath of filePaths) {
599
- if (findings.length >= maxFindings) {
600
- break;
601
- }
602
-
603
- const relativePath = toPosixPath(path.relative(rootPath, filePath));
604
- if (!isSourceLikeFile(relativePath)) {
605
- continue;
606
- }
607
-
608
- let text = "";
609
- try {
610
- text = await fsp.readFile(filePath, "utf-8");
611
- } catch {
612
- continue;
613
- }
614
- const lines = text.split(/\r?\n/g);
615
- const extension = path.extname(relativePath).toLowerCase();
616
-
617
- if ((extension === ".tsx" || extension === ".jsx") && lines.length >= 700) {
618
- tryPushFinding(
619
- findings,
620
- createFinding({
621
- severity: "P2",
622
- file: relativePath,
623
- line: 1,
624
- message: "Large UI component detected (possible god component).",
625
- excerpt: `${lines.length} lines`,
626
- ruleId: "SL-PAT-001",
627
- suggestedFix: "Split component into smaller focused units with explicit ownership.",
628
- layer: "pattern",
629
- }),
630
- maxFindings
631
- );
632
- }
633
-
634
- for (let index = 0; index < lines.length; index += 1) {
635
- if (findings.length >= maxFindings) {
636
- break;
637
- }
638
- const line = lines[index];
639
- if (!line) {
640
- continue;
641
- }
642
-
643
- if (/dangerouslySetInnerHTML/.test(line) || /innerHTML\s*=/.test(line)) {
644
- tryPushFinding(
645
- findings,
646
- createFinding({
647
- severity: "P1",
648
- file: relativePath,
649
- line: index + 1,
650
- message: "Direct HTML sink detected; validate/sanitize untrusted content.",
651
- excerpt: sanitizeLineForExcerpt(line),
652
- ruleId: "SL-PAT-002",
653
- suggestedFix: "Apply strict sanitization and avoid raw HTML sinks.",
654
- layer: "pattern",
655
- }),
656
- maxFindings
657
- );
658
- }
659
-
660
- if (/useEffect\s*\(/.test(line)) {
661
- const window = lines.slice(index, Math.min(lines.length, index + 14)).join("\n");
662
- if ((/addEventListener|setInterval|fetch\(/.test(window) || /subscribe\(/.test(window)) && !/return\s*\(\s*\)\s*=>/.test(window)) {
663
- tryPushFinding(
664
- findings,
665
- createFinding({
666
- severity: "P2",
667
- file: relativePath,
668
- line: index + 1,
669
- message: "Possible useEffect side-effect without cleanup.",
670
- excerpt: sanitizeLineForExcerpt(line),
671
- ruleId: "SL-PAT-003",
672
- suggestedFix: "Add cleanup in useEffect return and verify dependency intent.",
673
- layer: "pattern",
674
- }),
675
- maxFindings
676
- );
677
- }
678
- }
679
-
680
- if (/(for|while)\s*\([^)]*\)/.test(line)) {
681
- const window = lines.slice(index, Math.min(lines.length, index + 10)).join("\n");
682
- if (/findMany\(|query\(|SELECT\b|fetch\(/i.test(window)) {
683
- tryPushFinding(
684
- findings,
685
- createFinding({
686
- severity: "P2",
687
- file: relativePath,
688
- line: index + 1,
689
- message: "Possible N+1 or repeated remote/database call in loop.",
690
- excerpt: sanitizeLineForExcerpt(line),
691
- ruleId: "SL-PAT-004",
692
- suggestedFix: "Batch queries/calls and prefetch outside iterative loops.",
693
- layer: "pattern",
694
- }),
695
- maxFindings
696
- );
697
- }
698
- }
699
- }
700
-
701
- const sqlConcat = /\b(?:SELECT|INSERT|UPDATE|DELETE)\b[^\n]{0,160}\+/i.exec(text);
702
- if (sqlConcat && findings.length < maxFindings) {
703
- const lineNumber = resolveLineNumberFromIndex(text, sqlConcat.index);
704
- tryPushFinding(
705
- findings,
706
- createFinding({
707
- severity: "P2",
708
- file: relativePath,
709
- line: lineNumber,
710
- message: "Potential SQL string interpolation detected.",
711
- excerpt: sanitizeLineForExcerpt(sqlConcat[0]),
712
- ruleId: "SL-PAT-005",
713
- suggestedFix: "Use parameterized query placeholders instead of string concatenation.",
714
- layer: "pattern",
715
- }),
716
- maxFindings
717
- );
718
- }
719
- }
720
-
721
- return findings;
722
- }
723
-
724
- function buildStaticChecks(ingest = {}) {
725
- const detectedManifests = Array.isArray(ingest.manifests?.detected) ? ingest.manifests.detected : [];
726
- if (!detectedManifests.includes("package.json")) {
727
- return [];
728
- }
729
-
730
- return [
731
- {
732
- id: "npm-lint",
733
- label: "npm run lint --if-present",
734
- command: "npm",
735
- args: ["run", "lint", "--if-present"],
736
- fileHint: "package.json",
737
- },
738
- {
739
- id: "npm-typecheck",
740
- label: "npm run typecheck --if-present",
741
- command: "npm",
742
- args: ["run", "typecheck", "--if-present"],
743
- fileHint: "package.json",
744
- },
745
- {
746
- id: "npm-format-check",
747
- label: "npm run format:check --if-present",
748
- command: "npm",
749
- args: ["run", "format:check", "--if-present"],
750
- fileHint: "package.json",
751
- },
752
- {
753
- id: "npm-test",
754
- label: "npm test --if-present",
755
- command: "npm",
756
- args: ["test", "--if-present"],
757
- fileHint: "package.json",
758
- },
759
- ];
760
- }
761
-
762
- async function executeStaticCheck({ check, targetPath, runDir } = {}) {
763
- const checksDir = path.join(runDir, "checks");
764
- await fsp.mkdir(checksDir, { recursive: true });
765
-
766
- const startedAt = Date.now();
767
- const result = spawnSync(check.command, check.args, {
768
- cwd: targetPath,
769
- encoding: "utf-8",
770
- timeout: STATIC_CHECK_TIMEOUT_MS,
771
- env: {
772
- ...process.env,
773
- CI: "1",
774
- FORCE_COLOR: "0",
775
- },
776
- });
777
-
778
- const durationMs = Date.now() - startedAt;
779
- const stdout = String(result.stdout || "");
780
- const stderr = String(result.stderr || "");
781
- const stdoutPath = path.join(checksDir, `${check.id}.stdout.log`);
782
- const stderrPath = path.join(checksDir, `${check.id}.stderr.log`);
783
- await fsp.writeFile(stdoutPath, stdout, "utf-8");
784
- await fsp.writeFile(stderrPath, stderr, "utf-8");
785
-
786
- if (result.error && result.error.code === "ENOENT") {
787
- return {
788
- id: check.id,
789
- label: check.label,
790
- command: `${check.command} ${check.args.join(" ")}`,
791
- status: "skipped",
792
- reason: `${check.command} not found in PATH`,
793
- exitCode: null,
794
- durationMs,
795
- stdoutPath,
796
- stderrPath,
797
- fileHint: check.fileHint,
798
- };
799
- }
800
-
801
- if (result.error && result.error.code === "ETIMEDOUT") {
802
- return {
803
- id: check.id,
804
- label: check.label,
805
- command: `${check.command} ${check.args.join(" ")}`,
806
- status: "timeout",
807
- reason: `Timed out after ${STATIC_CHECK_TIMEOUT_MS}ms`,
808
- exitCode: null,
809
- durationMs,
810
- stdoutPath,
811
- stderrPath,
812
- fileHint: check.fileHint,
813
- };
814
- }
815
-
816
- if (result.error) {
817
- return {
818
- id: check.id,
819
- label: check.label,
820
- command: `${check.command} ${check.args.join(" ")}`,
821
- status: "error",
822
- reason: result.error.message,
823
- exitCode: result.status,
824
- durationMs,
825
- stdoutPath,
826
- stderrPath,
827
- fileHint: check.fileHint,
828
- };
829
- }
830
-
831
- return {
832
- id: check.id,
833
- label: check.label,
834
- command: `${check.command} ${check.args.join(" ")}`,
835
- status: result.status === 0 ? "pass" : "fail",
836
- reason: result.status === 0 ? "ok" : "Command returned non-zero exit code",
837
- exitCode: result.status,
838
- durationMs,
839
- stdoutPath,
840
- stderrPath,
841
- fileHint: check.fileHint,
842
- };
843
- }
844
-
845
- async function runStaticAnalysisLayer({ targetPath, ingest, runDir, maxFindings = MAX_FINDINGS } = {}) {
846
- const checks = buildStaticChecks(ingest);
847
- const results = [];
848
- const findings = [];
849
-
850
- for (const check of checks) {
851
- const result = await executeStaticCheck({
852
- check,
853
- targetPath,
854
- runDir,
855
- });
856
- results.push(result);
857
-
858
- if (findings.length >= maxFindings) {
859
- continue;
860
- }
861
-
862
- if (result.status === "fail" || result.status === "timeout" || result.status === "error") {
863
- findings.push(
864
- createFinding({
865
- severity: "P2",
866
- file: result.fileHint || "package.json",
867
- line: 1,
868
- message: `Static analysis check failed: ${result.label}`,
869
- excerpt: `${result.status}${result.exitCode === null ? "" : ` (exit ${result.exitCode})`}`,
870
- ruleId: `SL-STA-${check.id.toUpperCase().replace(/[^A-Z0-9]+/g, "-")}`,
871
- suggestedFix: "Review check logs and remediate lint/typecheck/test failures.",
872
- layer: "static_analysis",
873
- })
874
- );
875
- }
876
- }
877
-
878
- return {
879
- checks: results,
880
- findings,
881
- };
882
- }
883
-
884
- async function fileExists(filePath) {
885
- try {
886
- await fsp.access(filePath);
887
- return true;
888
- } catch {
889
- return false;
890
- }
891
- }
892
-
893
- async function runReadinessChecks({ targetPath, maxFindings = MAX_FINDINGS } = {}) {
894
- const findings = [];
895
-
896
- const hasOmarWorkflow = await fileExists(path.join(targetPath, ".github", "workflows", "omar-gate.yml"));
897
- if (!hasOmarWorkflow && findings.length < maxFindings) {
898
- findings.push(
899
- createFinding({
900
- severity: "P2",
901
- file: ".github/workflows/omar-gate.yml",
902
- line: 1,
903
- message: "Omar Gate workflow is missing.",
904
- excerpt: "Required workflow not found",
905
- ruleId: "SL-READINESS-001",
906
- suggestedFix: "Initialize or restore `.github/workflows/omar-gate.yml`.",
907
- layer: "readiness",
908
- })
909
- );
910
- }
911
-
912
- const hasSpec =
913
- (await fileExists(path.join(targetPath, "SPEC.md"))) ||
914
- (await fileExists(path.join(targetPath, "docs", "spec.md")));
915
- if (!hasSpec && findings.length < maxFindings) {
916
- findings.push(
917
- createFinding({
918
- severity: "P2",
919
- file: "SPEC.md",
920
- line: 1,
921
- message: "Spec document is missing.",
922
- excerpt: "Expected SPEC.md or docs/spec.md",
923
- ruleId: "SL-READINESS-002",
924
- suggestedFix: "Generate and commit a current spec before final review runs.",
925
- layer: "readiness",
926
- })
927
- );
928
- }
929
-
930
- return findings;
931
- }
932
-
933
- function sortFindings(findings = []) {
934
- return [...findings].sort((left, right) => {
935
- const severityDelta = severityRank(left.severity) - severityRank(right.severity);
936
- if (severityDelta !== 0) {
937
- return severityDelta;
938
- }
939
- const fileDelta = String(left.file || "").localeCompare(String(right.file || ""));
940
- if (fileDelta !== 0) {
941
- return fileDelta;
942
- }
943
- const lineDelta = Number(left.line || 0) - Number(right.line || 0);
944
- if (lineDelta !== 0) {
945
- return lineDelta;
946
- }
947
- return String(left.ruleId || "").localeCompare(String(right.ruleId || ""));
948
- });
949
- }
950
-
951
- function summarizeSeverity(findings = []) {
952
- return findings.reduce(
953
- (accumulator, finding) => {
954
- const severity = String(finding.severity || "P3").toUpperCase();
955
- if (!Object.prototype.hasOwnProperty.call(accumulator, severity)) {
956
- accumulator[severity] = 0;
957
- }
958
- accumulator[severity] += 1;
959
- return accumulator;
960
- },
961
- {
962
- P0: 0,
963
- P1: 0,
964
- P2: 0,
965
- P3: 0,
966
- }
967
- );
968
- }
969
-
970
- function formatStaticCheckMarkdown(checks = []) {
971
- if (!checks.length) {
972
- return "- none";
973
- }
974
- return checks
975
- .map(
976
- (check) =>
977
- `- ${check.id}: ${check.status} (${check.durationMs}ms) :: ${check.command}${check.reason ? ` :: ${check.reason}` : ""}`
978
- )
979
- .join("\n");
980
- }
981
-
982
- function formatDeterministicFindingsMarkdown(findings = []) {
983
- if (!findings.length) {
984
- return "- none";
985
- }
986
- return findings
987
- .map(
988
- (finding, index) =>
989
- `${index + 1}. [${finding.severity}] (${finding.ruleId}) ${finding.file}:${finding.line} - ${finding.message}\n` +
990
- ` suggested_fix: ${finding.suggestedFix}\n` +
991
- ` excerpt: ${finding.excerpt}`
992
- )
993
- .join("\n");
994
- }
995
-
996
- function buildDeterministicReviewMarkdown(result) {
997
- const frameworks = result.layers.ingest.frameworks.length
998
- ? result.layers.ingest.frameworks.join(", ")
999
- : "none";
1000
- const riskSurfaces = result.layers.ingest.riskSurfaces.length
1001
- ? result.layers.ingest.riskSurfaces.map((item) => item.surface).join(", ")
1002
- : "none";
1003
- const scopedPreview = result.scope.scannedRelativeFiles.slice(0, 80);
1004
- const omitted = Math.max(0, result.scope.scannedRelativeFiles.length - scopedPreview.length);
1005
-
1006
- return `# REVIEW_DETERMINISTIC
1007
-
1008
- Generated: ${result.generatedAt}
1009
- Run ID: ${result.runId}
1010
- Target: ${result.targetPath}
1011
- Mode: ${result.mode}
1012
-
1013
- Summary:
1014
- - Files scoped: ${result.scope.scannedFiles}
1015
- - Findings: P0=${result.summary.P0} P1=${result.summary.P1} P2=${result.summary.P2} P3=${result.summary.P3}
1016
- - Blocking: ${result.summary.blocking ? "yes" : "no"}
1017
-
1018
- Layer 1 - Codebase ingest:
1019
- - Files scanned: ${result.layers.ingest.summary.filesScanned}
1020
- - Total LOC: ${result.layers.ingest.summary.totalLoc}
1021
- - Frameworks: ${frameworks}
1022
- - Risk surfaces: ${riskSurfaces}
1023
- - Refresh: ${result.layers.ingest.refresh?.refreshed ? "yes" : "no"}
1024
- - Stale: ${result.layers.ingest.refresh?.stale ? "yes" : "no"}
1025
- - Refresh reasons: ${(result.layers.ingest.refresh?.reasons || []).join(", ") || "none"}
1026
-
1027
- Layer 2 - Structural analysis:
1028
- - Rules evaluated: ${result.layers.structural.ruleCount}
1029
- - Findings: ${result.layers.structural.findingCount}
1030
-
1031
- Layer 3 - Static analysis orchestration:
1032
- ${formatStaticCheckMarkdown(result.layers.staticAnalysis.checks)}
1033
-
1034
- Layer 4 - Spec binding checks:
1035
- - Enabled: ${result.layers.specBinding.enabled ? "yes" : "no"}
1036
- - Spec path: ${result.layers.specBinding.specPath || "none"}
1037
- - Spec hash: ${result.layers.specBinding.specHashSha256 || "none"}
1038
- - Spec endpoints: ${result.layers.specBinding.endpointCount}
1039
- - Acceptance criteria: ${result.layers.specBinding.acceptanceCriteriaCount}
1040
- - Findings: ${result.layers.specBinding.findingCount}
1041
-
1042
- Layer 5 - Pattern checks:
1043
- - Findings: ${result.layers.pattern.findingCount}
1044
-
1045
- Readiness checks:
1046
- - Findings: ${result.layers.readiness.findingCount}
1047
-
1048
- Scoped files:
1049
- ${scopedPreview.length > 0 ? scopedPreview.map((item) => `- ${item}`).join("\n") : "- none"}
1050
- ${omitted > 0 ? `- ... ${omitted} more files omitted` : ""}
1051
-
1052
- Findings:
1053
- ${formatDeterministicFindingsMarkdown(result.findings)}
1054
- `;
1055
- }
1056
-
1057
- async function writeDeterministicReviewArtifacts({ result, runDir } = {}) {
1058
- const markdownPath = path.join(runDir, "REVIEW_DETERMINISTIC.md");
1059
- const jsonPath = path.join(runDir, "REVIEW_DETERMINISTIC.json");
1060
-
1061
- await fsp.writeFile(markdownPath, `${buildDeterministicReviewMarkdown(result).trim()}\n`, "utf-8");
1062
- await fsp.writeFile(jsonPath, `${JSON.stringify(result, null, 2)}\n`, "utf-8");
1063
-
1064
- return {
1065
- markdownPath,
1066
- jsonPath,
1067
- };
1068
- }
1069
-
1070
- export async function runDeterministicReviewPipeline({
1071
- targetPath,
1072
- mode = "full",
1073
- outputDir = "",
1074
- specFile = "",
1075
- refreshIngest = false,
1076
- } = {}) {
1077
- const normalizedTargetPath = path.resolve(String(targetPath || "."));
1078
- const normalizedMode = normalizeMode(mode, {
1079
- allowedModes: ["full", "diff", "staged"],
1080
- });
1081
-
1082
- const outputRoot = await resolveOutputRoot({
1083
- cwd: normalizedTargetPath,
1084
- outputDirOverride: outputDir,
1085
- });
1086
- const runId = `review-${formatTimestampForFile()}-${randomUUID().slice(0, 8)}`;
1087
- const runDir = path.join(outputRoot, "reviews", runId);
1088
- await fsp.mkdir(runDir, { recursive: true });
1089
-
1090
- const ingestResolution = await resolveCodebaseIngest({
1091
- rootPath: normalizedTargetPath,
1092
- outputDir,
1093
- refresh: Boolean(refreshIngest),
1094
- });
1095
- const ingest = ingestResolution.ingest;
1096
- const scopedFiles = await collectModeFilePaths(normalizedTargetPath, normalizedMode);
1097
-
1098
- const structuralFindings = await scanRulesForFiles({
1099
- rootPath: normalizedTargetPath,
1100
- filePaths: scopedFiles,
1101
- rules: DETERMINISTIC_REVIEW_RULES,
1102
- maxFindings: MAX_FINDINGS,
1103
- layer: "structural",
1104
- });
1105
-
1106
- let remainingBudget = Math.max(0, MAX_FINDINGS - structuralFindings.length);
1107
- const patternFindings = await runPatternChecks({
1108
- rootPath: normalizedTargetPath,
1109
- filePaths: scopedFiles,
1110
- maxFindings: remainingBudget,
1111
- });
1112
-
1113
- remainingBudget = Math.max(0, remainingBudget - patternFindings.length);
1114
- const readinessFindings = await runReadinessChecks({
1115
- targetPath: normalizedTargetPath,
1116
- maxFindings: remainingBudget,
1117
- });
1118
-
1119
- remainingBudget = Math.max(0, remainingBudget - readinessFindings.length);
1120
- const specBinding = await runSpecBindingChecks({
1121
- targetPath: normalizedTargetPath,
1122
- mode: normalizedMode,
1123
- scopedFilePaths: scopedFiles,
1124
- maxFindings: remainingBudget,
1125
- specFile,
1126
- });
1127
-
1128
- remainingBudget = Math.max(0, remainingBudget - specBinding.findings.length);
1129
- const staticAnalysis = await runStaticAnalysisLayer({
1130
- targetPath: normalizedTargetPath,
1131
- ingest,
1132
- runDir,
1133
- maxFindings: remainingBudget,
1134
- });
1135
-
1136
- const findings = sortFindings([
1137
- ...structuralFindings,
1138
- ...patternFindings,
1139
- ...readinessFindings,
1140
- ...specBinding.findings,
1141
- ...staticAnalysis.findings,
1142
- ]);
1143
- const severity = summarizeSeverity(findings);
1144
-
1145
- const result = {
1146
- schemaVersion: "1.0.0",
1147
- generatedAt: new Date().toISOString(),
1148
- runId,
1149
- targetPath: normalizedTargetPath,
1150
- mode: normalizedMode,
1151
- scope: {
1152
- scannedFiles: scopedFiles.length,
1153
- scannedRelativeFiles: scopedFiles.map((filePath) => toPosixPath(path.relative(normalizedTargetPath, filePath))),
1154
- },
1155
- layers: {
1156
- ingest: {
1157
- summary: ingest.summary,
1158
- frameworks: Array.isArray(ingest.frameworks) ? ingest.frameworks : [],
1159
- entryPoints: Array.isArray(ingest.entryPoints) ? ingest.entryPoints : [],
1160
- manifests: Array.isArray(ingest.manifests?.detected) ? ingest.manifests.detected : [],
1161
- riskSurfaces: Array.isArray(ingest.riskSurfaces) ? ingest.riskSurfaces : [],
1162
- refresh: {
1163
- outputPath: ingestResolution.outputPath,
1164
- refreshed: ingestResolution.refreshed,
1165
- stale: ingestResolution.stale,
1166
- reasons: ingestResolution.reasons,
1167
- refreshedBecause: ingestResolution.refreshedBecause,
1168
- lastCommitAt: ingestResolution.lastCommitAt,
1169
- contentHash: ingestResolution.fingerprint?.contentHash || "",
1170
- },
1171
- },
1172
- structural: {
1173
- ruleCount: DETERMINISTIC_REVIEW_RULES.length,
1174
- findingCount: structuralFindings.length,
1175
- },
1176
- staticAnalysis: {
1177
- checkCount: staticAnalysis.checks.length,
1178
- checks: staticAnalysis.checks,
1179
- findingCount: staticAnalysis.findings.length,
1180
- },
1181
- specBinding: {
1182
- enabled: Boolean(specBinding.metadata.enabled),
1183
- specPath: specBinding.metadata.specPath
1184
- ? toPosixPath(path.relative(normalizedTargetPath, specBinding.metadata.specPath))
1185
- : "",
1186
- specHashSha256: specBinding.metadata.specHashSha256 || "",
1187
- endpointCount: specBinding.metadata.endpointCount || 0,
1188
- acceptanceCriteriaCount: specBinding.metadata.acceptanceCriteriaCount || 0,
1189
- endpointsPreview: Array.isArray(specBinding.metadata.endpointsPreview)
1190
- ? specBinding.metadata.endpointsPreview
1191
- : [],
1192
- findingCount: specBinding.findings.length,
1193
- },
1194
- pattern: {
1195
- findingCount: patternFindings.length,
1196
- },
1197
- readiness: {
1198
- findingCount: readinessFindings.length,
1199
- },
1200
- },
1201
- findings,
1202
- summary: {
1203
- P0: severity.P0,
1204
- P1: severity.P1,
1205
- P2: severity.P2,
1206
- P3: severity.P3,
1207
- blocking: severity.P0 > 0 || severity.P1 > 0,
1208
- },
1209
- };
1210
-
1211
- const artifacts = await writeDeterministicReviewArtifacts({
1212
- result,
1213
- runDir,
1214
- });
1215
-
1216
- return {
1217
- ...result,
1218
- artifacts: {
1219
- runDirectory: runDir,
1220
- ...artifacts,
1221
- },
1222
- };
1223
- }
1224
-
1225
- export async function runLocalReviewScan({ targetPath, mode = "full", specFile = "" } = {}) {
1226
- const normalizedTargetPath = path.resolve(String(targetPath || "."));
1227
- const normalizedMode = normalizeMode(mode, {
1228
- allowedModes: ["full", "diff", "staged"],
1229
- });
1230
-
1231
- const filePaths = await collectModeFilePaths(normalizedTargetPath, normalizedMode);
1232
-
1233
- const scan = await scanFileSet(normalizedTargetPath, filePaths);
1234
- const remainingBudget = Math.max(0, MAX_FINDINGS - scan.findings.length);
1235
- const specBinding = await runSpecBindingChecks({
1236
- targetPath: normalizedTargetPath,
1237
- mode: normalizedMode,
1238
- scopedFilePaths: filePaths,
1239
- maxFindings: remainingBudget,
1240
- specFile,
1241
- });
1242
- const findings = sortFindings([...scan.findings, ...specBinding.findings]);
1243
- const p1 = findings.filter((item) => item.severity === "P1").length;
1244
- const p2 = findings.filter((item) => item.severity === "P2").length;
1245
-
1246
- return {
1247
- targetPath: normalizedTargetPath,
1248
- mode: normalizedMode,
1249
- scannedRelativeFiles: filePaths.map((filePath) =>
1250
- toPosixPath(path.relative(normalizedTargetPath, filePath))
1251
- ),
1252
- scannedFiles: filePaths.length,
1253
- findings,
1254
- p1,
1255
- p2,
1256
- specBinding: specBinding.metadata,
1257
- };
1258
- }
1259
-
1260
- export function formatFindingsMarkdown(findings = []) {
1261
- if (!Array.isArray(findings) || findings.length === 0) {
1262
- return "- none";
1263
- }
1264
- return findings
1265
- .map((item, index) => `${index + 1}. [${item.severity}] ${item.file}:${item.line} - ${item.message}`)
1266
- .join("\n");
1267
- }
1268
-
1269
- export async function writeReviewReport({
1270
- targetPath,
1271
- mode,
1272
- outputDir = "",
1273
- reportMarkdown,
1274
- } = {}) {
1275
- const outputRoot = await resolveOutputRoot({
1276
- cwd: targetPath,
1277
- outputDirOverride: outputDir,
1278
- });
1279
- const reportDir = path.join(outputRoot, "reports");
1280
- await fsp.mkdir(reportDir, { recursive: true });
1281
- const reportPath = path.join(reportDir, `review-scan-${mode}-${formatTimestampForFile()}.md`);
1282
- await fsp.writeFile(reportPath, `${String(reportMarkdown || "").trim()}\n`, "utf-8");
1283
- return reportPath;
1284
- }
1
+ import { spawnSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import fsp from "node:fs/promises";
4
+ import path from "node:path";
5
+
6
+ import { resolveOutputRoot } from "../config/service.js";
7
+ import { resolveCodebaseIngest } from "../ingest/engine.js";
8
+ import { runSpecBindingChecks } from "./spec-binding.js";
9
+
10
+ const IGNORED_DIRS = new Set([
11
+ ".git",
12
+ "node_modules",
13
+ ".venv",
14
+ ".next",
15
+ "dist",
16
+ "build",
17
+ ".sentinelayer",
18
+ ]);
19
+ const MAX_FILE_SIZE_BYTES = 512 * 1024;
20
+ const MAX_FINDINGS = 250;
21
+ const STATIC_CHECK_TIMEOUT_MS = 120_000;
22
+
23
+ const SOURCE_CODE_EXTENSIONS = new Set([
24
+ ".js",
25
+ ".jsx",
26
+ ".mjs",
27
+ ".cjs",
28
+ ".ts",
29
+ ".tsx",
30
+ ".py",
31
+ ".go",
32
+ ".rs",
33
+ ".java",
34
+ ".kt",
35
+ ".cs",
36
+ ".rb",
37
+ ".php",
38
+ ".sql",
39
+ ]);
40
+
41
+ const SEVERITY_ORDER = new Map([
42
+ ["P0", 0],
43
+ ["P1", 1],
44
+ ["P2", 2],
45
+ ["P3", 3],
46
+ ]);
47
+
48
+ const REVIEW_RULES = Object.freeze([
49
+ {
50
+ severity: "P1",
51
+ message: "Possible AWS access key detected.",
52
+ regex: /AKIA[0-9A-Z]{16}/,
53
+ },
54
+ {
55
+ severity: "P1",
56
+ message: "Possible private key material detected.",
57
+ regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
58
+ },
59
+ {
60
+ severity: "P1",
61
+ message: "Possible provider API key detected.",
62
+ regex: /\b(sk-[A-Za-z0-9]{20,}|ghp_[A-Za-z0-9]{20,})\b/,
63
+ },
64
+ {
65
+ severity: "P2",
66
+ message: "Possible hardcoded credential literal.",
67
+ regex: /(api[_-]?key|secret|token)\s*[:=]\s*['\"][^'\"]{20,}['\"]/i,
68
+ },
69
+ {
70
+ severity: "P2",
71
+ message: "Work-item marker found.",
72
+ regex: /\b(?:\x54\x4f\x44\x4f|\x46\x49\x58\x4d\x45|\x48\x41\x43\x4b)\b/,
73
+ },
74
+ ]);
75
+
76
+ const DETERMINISTIC_REVIEW_RULES = Object.freeze([
77
+ {
78
+ id: "SL-SEC-001",
79
+ severity: "P1",
80
+ message: "Possible AWS access key detected.",
81
+ suggestedFix: "Remove committed credentials and rotate the key.",
82
+ regex: /AKIA[0-9A-Z]{16}/,
83
+ sourceOnly: true,
84
+ },
85
+ {
86
+ id: "SL-SEC-002",
87
+ severity: "P1",
88
+ message: "Possible private key material detected.",
89
+ suggestedFix: "Delete committed key material and rotate any dependent certs.",
90
+ regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
91
+ },
92
+ {
93
+ id: "SL-SEC-003",
94
+ severity: "P1",
95
+ message: "Possible GitHub token detected.",
96
+ suggestedFix: "Revoke and rotate token; source from secure runtime config.",
97
+ regex: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/,
98
+ sourceOnly: true,
99
+ },
100
+ {
101
+ id: "SL-SEC-004",
102
+ severity: "P1",
103
+ message: "Possible provider API key detected.",
104
+ suggestedFix: "Rotate API keys and move to managed secret storage.",
105
+ regex: /\b(sk-[A-Za-z0-9]{20,})\b/,
106
+ sourceOnly: true,
107
+ },
108
+ {
109
+ id: "SL-SEC-005",
110
+ severity: "P2",
111
+ message: "Possible hardcoded credential literal.",
112
+ suggestedFix: "Replace literal with environment/secret-manager lookup.",
113
+ regex: /(api[_-]?key|secret|token|password|passwd)\s*[:=]\s*['\"][^'\"]{12,}['\"]/i,
114
+ sourceOnly: true,
115
+ },
116
+ {
117
+ id: "SL-SEC-006",
118
+ severity: "P2",
119
+ message: "Possible hardcoded bearer token.",
120
+ suggestedFix: "Remove token literals and rotate exposed credentials.",
121
+ regex: /Bearer\s+[A-Za-z0-9._\-]{20,}/,
122
+ sourceOnly: true,
123
+ },
124
+ {
125
+ id: "SL-SEC-007",
126
+ severity: "P2",
127
+ message: "Possible embedded JWT detected.",
128
+ suggestedFix: "Do not store JWTs in source code.",
129
+ regex: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,
130
+ sourceOnly: true,
131
+ },
132
+ {
133
+ id: "SL-SEC-008",
134
+ severity: "P2",
135
+ message: "Potential database connection string with inline credentials.",
136
+ suggestedFix: "Externalize DSN and rotate embedded credentials.",
137
+ regex: /(postgres|mysql|mariadb|sqlserver):\/\/[^\s:@]+:[^\s@]+@/i,
138
+ sourceOnly: true,
139
+ },
140
+ {
141
+ id: "SL-SEC-009",
142
+ severity: "P2",
143
+ message: "Potential MongoDB URI with inline credentials.",
144
+ suggestedFix: "Use secret-managed URI and avoid inline username/password.",
145
+ regex: /mongodb(?:\+srv)?:\/\/[^\s:@]+:[^\s@]+@/i,
146
+ sourceOnly: true,
147
+ },
148
+ {
149
+ id: "SL-SEC-010",
150
+ severity: "P2",
151
+ message: "Potential Redis URI with inline credentials.",
152
+ suggestedFix: "Move Redis credentials to secret manager.",
153
+ regex: /redis(?:\+tls)?:\/\/[^\s:@]+:[^\s@]+@/i,
154
+ sourceOnly: true,
155
+ },
156
+ {
157
+ id: "SL-SEC-011",
158
+ severity: "P1",
159
+ message: "Possible Slack webhook URL detected.",
160
+ suggestedFix: "Rotate webhook and store it outside source control.",
161
+ regex: /https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9/]+/,
162
+ sourceOnly: true,
163
+ },
164
+ {
165
+ id: "SL-SEC-012",
166
+ severity: "P1",
167
+ message: "Possible Stripe live secret key detected.",
168
+ suggestedFix: "Rotate Stripe key and use secure runtime injection.",
169
+ regex: /\bsk_live_[A-Za-z0-9]{16,}\b/,
170
+ sourceOnly: true,
171
+ },
172
+ {
173
+ id: "SL-SEC-013",
174
+ severity: "P2",
175
+ message: "Plain HTTP endpoint literal found.",
176
+ suggestedFix: "Prefer HTTPS endpoints in production paths.",
177
+ regex: /\bhttp:\/\/[^\s'"]+/i,
178
+ sourceOnly: true,
179
+ },
180
+ {
181
+ id: "SL-SEC-014",
182
+ severity: "P2",
183
+ message: "Work-item marker detected (TODO/FIXME/HACK).",
184
+ suggestedFix: "Resolve or scope pending work before release.",
185
+ regex: /\b(?:TODO|FIXME|HACK)\b/,
186
+ sourceOnly: true,
187
+ },
188
+ {
189
+ id: "SL-SEC-015",
190
+ severity: "P1",
191
+ message: "Dynamic code execution primitive detected (`eval`).",
192
+ suggestedFix: "Replace eval with explicit parser or safe handlers.",
193
+ regex: /\beval\s*\(/,
194
+ sourceOnly: true,
195
+ },
196
+ {
197
+ id: "SL-SEC-016",
198
+ severity: "P2",
199
+ message: "Template-literal shell execution detected.",
200
+ suggestedFix: "Avoid shell interpolation with untrusted inputs.",
201
+ regex: /exec(?:Sync)?\s*\(\s*`[^`]*\$\{[^}]+\}[^`]*`\s*\)/,
202
+ sourceOnly: true,
203
+ },
204
+ {
205
+ id: "SL-SEC-017",
206
+ severity: "P2",
207
+ message: "Possible SQL string concatenation detected.",
208
+ suggestedFix: "Use parameterized queries and prepared statements.",
209
+ regex: /\b(?:SELECT|INSERT|UPDATE|DELETE)\b[^;\n]{0,140}\+/i,
210
+ sourceOnly: true,
211
+ },
212
+ {
213
+ id: "SL-SEC-018",
214
+ severity: "P1",
215
+ message: "Potential wildcard CORS policy detected.",
216
+ suggestedFix: "Replace wildcard CORS with explicit allowlist.",
217
+ regex: /Access-Control-Allow-Origin\s*[:=]\s*['"]\*['"]/i,
218
+ sourceOnly: true,
219
+ },
220
+ {
221
+ id: "SL-SEC-019",
222
+ severity: "P1",
223
+ message: "TLS certificate verification appears disabled.",
224
+ suggestedFix: "Remove insecure TLS bypass and use valid certificates.",
225
+ regex: /NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0['"]?/i,
226
+ sourceOnly: true,
227
+ },
228
+ {
229
+ id: "SL-SEC-020",
230
+ severity: "P2",
231
+ message: "Potentially sensitive value logged directly.",
232
+ suggestedFix: "Redact secrets/tokens before logging.",
233
+ regex: /console\.(?:log|debug|info)\([^)]*(token|secret|password|api[_-]?key)/i,
234
+ sourceOnly: true,
235
+ },
236
+ {
237
+ id: "SL-SEC-021",
238
+ severity: "P2",
239
+ message: "Tracked environment file may contain secrets.",
240
+ suggestedFix: "Commit only sanitized `.env.example` files.",
241
+ kind: "file",
242
+ filePattern: /(^|\/)\.env(\.[^/]+)?$/i,
243
+ excludePathPattern: /\.example$/i,
244
+ },
245
+ {
246
+ id: "SL-SEC-022",
247
+ severity: "P2",
248
+ message: "Hardcoded localhost callback URL detected.",
249
+ suggestedFix: "Externalize callback URLs to environment config.",
250
+ regex: /https?:\/\/localhost:\d{2,5}\//i,
251
+ sourceOnly: true,
252
+ },
253
+ ]);
254
+
255
+ function formatTimestampForFile() {
256
+ const now = new Date();
257
+ const pad = (value) => String(value).padStart(2, "0");
258
+ return `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}-${pad(
259
+ now.getUTCHours()
260
+ )}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`;
261
+ }
262
+
263
+ function toPosixPath(value) {
264
+ return String(value || "").replace(/\\/g, "/");
265
+ }
266
+
267
+ function normalizeMode(mode, { allowedModes = ["full", "diff", "staged"] } = {}) {
268
+ const normalized = String(mode || "full").trim().toLowerCase();
269
+ if (!allowedModes.includes(normalized)) {
270
+ throw new Error(`mode must be one of: ${allowedModes.join(", ")}.`);
271
+ }
272
+ return normalized;
273
+ }
274
+
275
+ function isSourceLikeFile(relativePath) {
276
+ const extension = path.extname(relativePath).toLowerCase();
277
+ return SOURCE_CODE_EXTENSIONS.has(extension);
278
+ }
279
+
280
+ function severityRank(value) {
281
+ return SEVERITY_ORDER.has(value) ? SEVERITY_ORDER.get(value) : 99;
282
+ }
283
+
284
+ function regexMatches(regex, input) {
285
+ const flags = regex.flags.replace(/g/g, "");
286
+ return new RegExp(regex.source, flags).test(input);
287
+ }
288
+
289
+ function sanitizeLineForExcerpt(line) {
290
+ return String(line || "")
291
+ .trim()
292
+ .replace(/\s+/g, " ")
293
+ .slice(0, 180);
294
+ }
295
+
296
+ function createFinding({
297
+ severity,
298
+ file,
299
+ line,
300
+ message,
301
+ excerpt,
302
+ ruleId,
303
+ suggestedFix,
304
+ layer,
305
+ }) {
306
+ return {
307
+ severity,
308
+ file,
309
+ line,
310
+ message,
311
+ excerpt,
312
+ ruleId,
313
+ suggestedFix,
314
+ layer,
315
+ };
316
+ }
317
+
318
+ function tryPushFinding(findings, finding, maxFindings) {
319
+ if (findings.length >= maxFindings) {
320
+ return false;
321
+ }
322
+ findings.push(finding);
323
+ return true;
324
+ }
325
+
326
+ function ruleAppliesToPath(rule, relativePath) {
327
+ if (rule.filePattern && !rule.filePattern.test(relativePath)) {
328
+ return false;
329
+ }
330
+ if (rule.excludePathPattern && rule.excludePathPattern.test(relativePath)) {
331
+ return false;
332
+ }
333
+ if (Array.isArray(rule.allowedExtensions) && rule.allowedExtensions.length > 0) {
334
+ const extension = path.extname(relativePath).toLowerCase();
335
+ if (!rule.allowedExtensions.includes(extension)) {
336
+ return false;
337
+ }
338
+ }
339
+ if (rule.sourceOnly && !isSourceLikeFile(relativePath)) {
340
+ return false;
341
+ }
342
+ return true;
343
+ }
344
+
345
+ function isIgnoredPath(rootPath, candidatePath) {
346
+ const relative = path.relative(rootPath, candidatePath);
347
+ if (!relative || relative.startsWith("..")) {
348
+ return true;
349
+ }
350
+ const parts = relative.split(/[\\/]+/g).filter(Boolean);
351
+ return parts.some((part) => IGNORED_DIRS.has(part));
352
+ }
353
+
354
+ async function includeFileIfScannable(rootPath, filePath, outputSet) {
355
+ if (isIgnoredPath(rootPath, filePath)) {
356
+ return;
357
+ }
358
+
359
+ try {
360
+ const stat = await fsp.stat(filePath);
361
+ if (!stat.isFile()) {
362
+ return;
363
+ }
364
+ if (stat.size > MAX_FILE_SIZE_BYTES) {
365
+ return;
366
+ }
367
+ } catch {
368
+ return;
369
+ }
370
+
371
+ outputSet.add(path.resolve(filePath));
372
+ }
373
+
374
+ async function collectAllScanFiles(rootPath) {
375
+ const files = new Set();
376
+ const stack = [rootPath];
377
+
378
+ while (stack.length > 0) {
379
+ const current = stack.pop();
380
+ if (!current) {
381
+ continue;
382
+ }
383
+ let entries = [];
384
+ try {
385
+ entries = await fsp.readdir(current, { withFileTypes: true });
386
+ } catch {
387
+ continue;
388
+ }
389
+
390
+ for (const entry of entries) {
391
+ const fullPath = path.join(current, entry.name);
392
+ if (entry.isDirectory()) {
393
+ if (IGNORED_DIRS.has(entry.name)) {
394
+ continue;
395
+ }
396
+ stack.push(fullPath);
397
+ continue;
398
+ }
399
+ if (!entry.isFile()) {
400
+ continue;
401
+ }
402
+ await includeFileIfScannable(rootPath, fullPath, files);
403
+ }
404
+ }
405
+
406
+ return [...files].sort((left, right) => left.localeCompare(right));
407
+ }
408
+
409
+ function runGitList(cwd, args) {
410
+ const result = spawnSync("git", args, {
411
+ cwd,
412
+ encoding: "utf-8",
413
+ });
414
+ if (result.status !== 0) {
415
+ return [];
416
+ }
417
+ return String(result.stdout || "")
418
+ .split(/\r?\n/g)
419
+ .map((line) => line.trim())
420
+ .filter(Boolean);
421
+ }
422
+
423
+ async function collectDiffScanFiles(rootPath) {
424
+ const revParse = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], {
425
+ cwd: rootPath,
426
+ encoding: "utf-8",
427
+ });
428
+ if (revParse.status !== 0 || !String(revParse.stdout || "").trim().toLowerCase().includes("true")) {
429
+ throw new Error("Diff review mode requires a git repository.");
430
+ }
431
+
432
+ const changedRelativePaths = new Set([
433
+ ...runGitList(rootPath, ["diff", "--name-only", "--diff-filter=ACMRTUXB"]),
434
+ ...runGitList(rootPath, ["diff", "--name-only", "--cached", "--diff-filter=ACMRTUXB"]),
435
+ ...runGitList(rootPath, ["ls-files", "--others", "--exclude-standard"]),
436
+ ]);
437
+
438
+ const files = new Set();
439
+ for (const relativePath of changedRelativePaths) {
440
+ const absolutePath = path.resolve(rootPath, relativePath);
441
+ await includeFileIfScannable(rootPath, absolutePath, files);
442
+ }
443
+
444
+ return [...files].sort((left, right) => left.localeCompare(right));
445
+ }
446
+
447
+ async function collectStagedScanFiles(rootPath) {
448
+ const revParse = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], {
449
+ cwd: rootPath,
450
+ encoding: "utf-8",
451
+ });
452
+ if (revParse.status !== 0 || !String(revParse.stdout || "").trim().toLowerCase().includes("true")) {
453
+ throw new Error("Staged review mode requires a git repository.");
454
+ }
455
+
456
+ const changedRelativePaths = runGitList(rootPath, [
457
+ "diff",
458
+ "--name-only",
459
+ "--cached",
460
+ "--diff-filter=ACMRTUXB",
461
+ ]);
462
+
463
+ const files = new Set();
464
+ for (const relativePath of changedRelativePaths) {
465
+ const absolutePath = path.resolve(rootPath, relativePath);
466
+ await includeFileIfScannable(rootPath, absolutePath, files);
467
+ }
468
+
469
+ return [...files].sort((left, right) => left.localeCompare(right));
470
+ }
471
+
472
+ async function collectModeFilePaths(rootPath, mode) {
473
+ if (mode === "diff") {
474
+ return collectDiffScanFiles(rootPath);
475
+ }
476
+ if (mode === "staged") {
477
+ return collectStagedScanFiles(rootPath);
478
+ }
479
+ return collectAllScanFiles(rootPath);
480
+ }
481
+
482
+ async function scanRulesForFiles({ rootPath, filePaths, rules, maxFindings = MAX_FINDINGS, layer = "structural" } = {}) {
483
+ const findings = [];
484
+
485
+ for (const filePath of filePaths) {
486
+ if (findings.length >= maxFindings) {
487
+ break;
488
+ }
489
+
490
+ const relativePath = toPosixPath(path.relative(rootPath, filePath));
491
+ const activeRules = rules.filter((rule) => ruleAppliesToPath(rule, relativePath));
492
+ if (activeRules.length === 0) {
493
+ continue;
494
+ }
495
+
496
+ const fileRules = activeRules.filter((rule) => String(rule.kind || "line") === "file");
497
+ for (const rule of fileRules) {
498
+ const pushed = tryPushFinding(
499
+ findings,
500
+ createFinding({
501
+ severity: rule.severity,
502
+ file: relativePath,
503
+ line: 1,
504
+ message: rule.message,
505
+ excerpt: "File-level policy match",
506
+ ruleId: rule.id || "SL-RULE",
507
+ suggestedFix: rule.suggestedFix || "Review and remediate this finding.",
508
+ layer,
509
+ }),
510
+ maxFindings
511
+ );
512
+ if (!pushed) {
513
+ break;
514
+ }
515
+ }
516
+ if (findings.length >= maxFindings) {
517
+ break;
518
+ }
519
+
520
+ let text = "";
521
+ try {
522
+ text = await fsp.readFile(filePath, "utf-8");
523
+ } catch {
524
+ continue;
525
+ }
526
+ const lines = text.split(/\r?\n/g);
527
+ const lineRules = activeRules.filter((rule) => String(rule.kind || "line") !== "file");
528
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
529
+ if (findings.length >= maxFindings) {
530
+ break;
531
+ }
532
+ const line = lines[lineIndex];
533
+ if (!line) {
534
+ continue;
535
+ }
536
+ if (line.includes("<your-token>") || line.includes("example")) {
537
+ continue;
538
+ }
539
+ for (const rule of lineRules) {
540
+ if (!regexMatches(rule.regex, line)) {
541
+ continue;
542
+ }
543
+ const pushed = tryPushFinding(
544
+ findings,
545
+ createFinding({
546
+ severity: rule.severity,
547
+ file: relativePath,
548
+ line: lineIndex + 1,
549
+ message: rule.message,
550
+ excerpt: sanitizeLineForExcerpt(line),
551
+ ruleId: rule.id || "SL-RULE",
552
+ suggestedFix: rule.suggestedFix || "Review and remediate this finding.",
553
+ layer,
554
+ }),
555
+ maxFindings
556
+ );
557
+ if (!pushed) {
558
+ break;
559
+ }
560
+ }
561
+ }
562
+ }
563
+
564
+ return findings;
565
+ }
566
+
567
+ async function scanFileSet(rootPath, filePaths) {
568
+ const findings = await scanRulesForFiles({
569
+ rootPath,
570
+ filePaths,
571
+ rules: REVIEW_RULES,
572
+ maxFindings: MAX_FINDINGS,
573
+ layer: "scan",
574
+ });
575
+
576
+ const p1 = findings.filter((item) => item.severity === "P1").length;
577
+ const p2 = findings.filter((item) => item.severity === "P2").length;
578
+
579
+ return {
580
+ scannedFiles: filePaths.length,
581
+ findings,
582
+ p1,
583
+ p2,
584
+ };
585
+ }
586
+
587
+ function resolveLineNumberFromIndex(text, index) {
588
+ if (!Number.isFinite(index) || index < 0) {
589
+ return 1;
590
+ }
591
+ const prior = String(text || "").slice(0, index);
592
+ return prior.split(/\r?\n/g).length;
593
+ }
594
+
595
+ async function runPatternChecks({ rootPath, filePaths, maxFindings = MAX_FINDINGS } = {}) {
596
+ const findings = [];
597
+
598
+ for (const filePath of filePaths) {
599
+ if (findings.length >= maxFindings) {
600
+ break;
601
+ }
602
+
603
+ const relativePath = toPosixPath(path.relative(rootPath, filePath));
604
+ if (!isSourceLikeFile(relativePath)) {
605
+ continue;
606
+ }
607
+
608
+ let text = "";
609
+ try {
610
+ text = await fsp.readFile(filePath, "utf-8");
611
+ } catch {
612
+ continue;
613
+ }
614
+ const lines = text.split(/\r?\n/g);
615
+ const extension = path.extname(relativePath).toLowerCase();
616
+
617
+ if ((extension === ".tsx" || extension === ".jsx") && lines.length >= 700) {
618
+ tryPushFinding(
619
+ findings,
620
+ createFinding({
621
+ severity: "P2",
622
+ file: relativePath,
623
+ line: 1,
624
+ message: "Large UI component detected (possible god component).",
625
+ excerpt: `${lines.length} lines`,
626
+ ruleId: "SL-PAT-001",
627
+ suggestedFix: "Split component into smaller focused units with explicit ownership.",
628
+ layer: "pattern",
629
+ }),
630
+ maxFindings
631
+ );
632
+ }
633
+
634
+ for (let index = 0; index < lines.length; index += 1) {
635
+ if (findings.length >= maxFindings) {
636
+ break;
637
+ }
638
+ const line = lines[index];
639
+ if (!line) {
640
+ continue;
641
+ }
642
+
643
+ if (/dangerouslySetInnerHTML/.test(line) || /innerHTML\s*=/.test(line)) {
644
+ tryPushFinding(
645
+ findings,
646
+ createFinding({
647
+ severity: "P1",
648
+ file: relativePath,
649
+ line: index + 1,
650
+ message: "Direct HTML sink detected; validate/sanitize untrusted content.",
651
+ excerpt: sanitizeLineForExcerpt(line),
652
+ ruleId: "SL-PAT-002",
653
+ suggestedFix: "Apply strict sanitization and avoid raw HTML sinks.",
654
+ layer: "pattern",
655
+ }),
656
+ maxFindings
657
+ );
658
+ }
659
+
660
+ if (/useEffect\s*\(/.test(line)) {
661
+ const window = lines.slice(index, Math.min(lines.length, index + 14)).join("\n");
662
+ if ((/addEventListener|setInterval|fetch\(/.test(window) || /subscribe\(/.test(window)) && !/return\s*\(\s*\)\s*=>/.test(window)) {
663
+ tryPushFinding(
664
+ findings,
665
+ createFinding({
666
+ severity: "P2",
667
+ file: relativePath,
668
+ line: index + 1,
669
+ message: "Possible useEffect side-effect without cleanup.",
670
+ excerpt: sanitizeLineForExcerpt(line),
671
+ ruleId: "SL-PAT-003",
672
+ suggestedFix: "Add cleanup in useEffect return and verify dependency intent.",
673
+ layer: "pattern",
674
+ }),
675
+ maxFindings
676
+ );
677
+ }
678
+ }
679
+
680
+ if (/(for|while)\s*\([^)]*\)/.test(line)) {
681
+ const window = lines.slice(index, Math.min(lines.length, index + 10)).join("\n");
682
+ if (/findMany\(|query\(|SELECT\b|fetch\(/i.test(window)) {
683
+ tryPushFinding(
684
+ findings,
685
+ createFinding({
686
+ severity: "P2",
687
+ file: relativePath,
688
+ line: index + 1,
689
+ message: "Possible N+1 or repeated remote/database call in loop.",
690
+ excerpt: sanitizeLineForExcerpt(line),
691
+ ruleId: "SL-PAT-004",
692
+ suggestedFix: "Batch queries/calls and prefetch outside iterative loops.",
693
+ layer: "pattern",
694
+ }),
695
+ maxFindings
696
+ );
697
+ }
698
+ }
699
+ }
700
+
701
+ const sqlConcat = /\b(?:SELECT|INSERT|UPDATE|DELETE)\b[^\n]{0,160}\+/i.exec(text);
702
+ if (sqlConcat && findings.length < maxFindings) {
703
+ const lineNumber = resolveLineNumberFromIndex(text, sqlConcat.index);
704
+ tryPushFinding(
705
+ findings,
706
+ createFinding({
707
+ severity: "P2",
708
+ file: relativePath,
709
+ line: lineNumber,
710
+ message: "Potential SQL string interpolation detected.",
711
+ excerpt: sanitizeLineForExcerpt(sqlConcat[0]),
712
+ ruleId: "SL-PAT-005",
713
+ suggestedFix: "Use parameterized query placeholders instead of string concatenation.",
714
+ layer: "pattern",
715
+ }),
716
+ maxFindings
717
+ );
718
+ }
719
+ }
720
+
721
+ return findings;
722
+ }
723
+
724
+ function buildStaticChecks(ingest = {}) {
725
+ const detectedManifests = Array.isArray(ingest.manifests?.detected) ? ingest.manifests.detected : [];
726
+ if (!detectedManifests.includes("package.json")) {
727
+ return [];
728
+ }
729
+
730
+ return [
731
+ {
732
+ id: "npm-lint",
733
+ label: "npm run lint --if-present",
734
+ command: "npm",
735
+ args: ["run", "lint", "--if-present"],
736
+ fileHint: "package.json",
737
+ },
738
+ {
739
+ id: "npm-typecheck",
740
+ label: "npm run typecheck --if-present",
741
+ command: "npm",
742
+ args: ["run", "typecheck", "--if-present"],
743
+ fileHint: "package.json",
744
+ },
745
+ {
746
+ id: "npm-format-check",
747
+ label: "npm run format:check --if-present",
748
+ command: "npm",
749
+ args: ["run", "format:check", "--if-present"],
750
+ fileHint: "package.json",
751
+ },
752
+ {
753
+ id: "npm-test",
754
+ label: "npm test --if-present",
755
+ command: "npm",
756
+ args: ["test", "--if-present"],
757
+ fileHint: "package.json",
758
+ },
759
+ ];
760
+ }
761
+
762
+ async function executeStaticCheck({ check, targetPath, runDir } = {}) {
763
+ const checksDir = path.join(runDir, "checks");
764
+ await fsp.mkdir(checksDir, { recursive: true });
765
+
766
+ const startedAt = Date.now();
767
+ const result = spawnSync(check.command, check.args, {
768
+ cwd: targetPath,
769
+ encoding: "utf-8",
770
+ timeout: STATIC_CHECK_TIMEOUT_MS,
771
+ env: {
772
+ ...process.env,
773
+ CI: "1",
774
+ FORCE_COLOR: "0",
775
+ },
776
+ });
777
+
778
+ const durationMs = Date.now() - startedAt;
779
+ const stdout = String(result.stdout || "");
780
+ const stderr = String(result.stderr || "");
781
+ const stdoutPath = path.join(checksDir, `${check.id}.stdout.log`);
782
+ const stderrPath = path.join(checksDir, `${check.id}.stderr.log`);
783
+ await fsp.writeFile(stdoutPath, stdout, "utf-8");
784
+ await fsp.writeFile(stderrPath, stderr, "utf-8");
785
+
786
+ if (result.error && result.error.code === "ENOENT") {
787
+ return {
788
+ id: check.id,
789
+ label: check.label,
790
+ command: `${check.command} ${check.args.join(" ")}`,
791
+ status: "skipped",
792
+ reason: `${check.command} not found in PATH`,
793
+ exitCode: null,
794
+ durationMs,
795
+ stdoutPath,
796
+ stderrPath,
797
+ fileHint: check.fileHint,
798
+ };
799
+ }
800
+
801
+ if (result.error && result.error.code === "ETIMEDOUT") {
802
+ return {
803
+ id: check.id,
804
+ label: check.label,
805
+ command: `${check.command} ${check.args.join(" ")}`,
806
+ status: "timeout",
807
+ reason: `Timed out after ${STATIC_CHECK_TIMEOUT_MS}ms`,
808
+ exitCode: null,
809
+ durationMs,
810
+ stdoutPath,
811
+ stderrPath,
812
+ fileHint: check.fileHint,
813
+ };
814
+ }
815
+
816
+ if (result.error) {
817
+ return {
818
+ id: check.id,
819
+ label: check.label,
820
+ command: `${check.command} ${check.args.join(" ")}`,
821
+ status: "error",
822
+ reason: result.error.message,
823
+ exitCode: result.status,
824
+ durationMs,
825
+ stdoutPath,
826
+ stderrPath,
827
+ fileHint: check.fileHint,
828
+ };
829
+ }
830
+
831
+ return {
832
+ id: check.id,
833
+ label: check.label,
834
+ command: `${check.command} ${check.args.join(" ")}`,
835
+ status: result.status === 0 ? "pass" : "fail",
836
+ reason: result.status === 0 ? "ok" : "Command returned non-zero exit code",
837
+ exitCode: result.status,
838
+ durationMs,
839
+ stdoutPath,
840
+ stderrPath,
841
+ fileHint: check.fileHint,
842
+ };
843
+ }
844
+
845
+ async function runStaticAnalysisLayer({ targetPath, ingest, runDir, maxFindings = MAX_FINDINGS } = {}) {
846
+ const checks = buildStaticChecks(ingest);
847
+ const results = [];
848
+ const findings = [];
849
+
850
+ for (const check of checks) {
851
+ const result = await executeStaticCheck({
852
+ check,
853
+ targetPath,
854
+ runDir,
855
+ });
856
+ results.push(result);
857
+
858
+ if (findings.length >= maxFindings) {
859
+ continue;
860
+ }
861
+
862
+ if (result.status === "fail" || result.status === "timeout" || result.status === "error") {
863
+ findings.push(
864
+ createFinding({
865
+ severity: "P2",
866
+ file: result.fileHint || "package.json",
867
+ line: 1,
868
+ message: `Static analysis check failed: ${result.label}`,
869
+ excerpt: `${result.status}${result.exitCode === null ? "" : ` (exit ${result.exitCode})`}`,
870
+ ruleId: `SL-STA-${check.id.toUpperCase().replace(/[^A-Z0-9]+/g, "-")}`,
871
+ suggestedFix: "Review check logs and remediate lint/typecheck/test failures.",
872
+ layer: "static_analysis",
873
+ })
874
+ );
875
+ }
876
+ }
877
+
878
+ return {
879
+ checks: results,
880
+ findings,
881
+ };
882
+ }
883
+
884
+ async function fileExists(filePath) {
885
+ try {
886
+ await fsp.access(filePath);
887
+ return true;
888
+ } catch {
889
+ return false;
890
+ }
891
+ }
892
+
893
+ async function runReadinessChecks({ targetPath, maxFindings = MAX_FINDINGS } = {}) {
894
+ const findings = [];
895
+
896
+ const hasOmarWorkflow = await fileExists(path.join(targetPath, ".github", "workflows", "omar-gate.yml"));
897
+ if (!hasOmarWorkflow && findings.length < maxFindings) {
898
+ findings.push(
899
+ createFinding({
900
+ severity: "P2",
901
+ file: ".github/workflows/omar-gate.yml",
902
+ line: 1,
903
+ message: "Omar Gate workflow is missing.",
904
+ excerpt: "Required workflow not found",
905
+ ruleId: "SL-READINESS-001",
906
+ suggestedFix: "Initialize or restore `.github/workflows/omar-gate.yml`.",
907
+ layer: "readiness",
908
+ })
909
+ );
910
+ }
911
+
912
+ const hasSpec =
913
+ (await fileExists(path.join(targetPath, "SPEC.md"))) ||
914
+ (await fileExists(path.join(targetPath, "docs", "spec.md")));
915
+ if (!hasSpec && findings.length < maxFindings) {
916
+ findings.push(
917
+ createFinding({
918
+ severity: "P2",
919
+ file: "SPEC.md",
920
+ line: 1,
921
+ message: "Spec document is missing.",
922
+ excerpt: "Expected SPEC.md or docs/spec.md",
923
+ ruleId: "SL-READINESS-002",
924
+ suggestedFix: "Generate and commit a current spec before final review runs.",
925
+ layer: "readiness",
926
+ })
927
+ );
928
+ }
929
+
930
+ return findings;
931
+ }
932
+
933
+ function sortFindings(findings = []) {
934
+ return [...findings].sort((left, right) => {
935
+ const severityDelta = severityRank(left.severity) - severityRank(right.severity);
936
+ if (severityDelta !== 0) {
937
+ return severityDelta;
938
+ }
939
+ const fileDelta = String(left.file || "").localeCompare(String(right.file || ""));
940
+ if (fileDelta !== 0) {
941
+ return fileDelta;
942
+ }
943
+ const lineDelta = Number(left.line || 0) - Number(right.line || 0);
944
+ if (lineDelta !== 0) {
945
+ return lineDelta;
946
+ }
947
+ return String(left.ruleId || "").localeCompare(String(right.ruleId || ""));
948
+ });
949
+ }
950
+
951
+ function summarizeSeverity(findings = []) {
952
+ return findings.reduce(
953
+ (accumulator, finding) => {
954
+ const severity = String(finding.severity || "P3").toUpperCase();
955
+ if (!Object.prototype.hasOwnProperty.call(accumulator, severity)) {
956
+ accumulator[severity] = 0;
957
+ }
958
+ accumulator[severity] += 1;
959
+ return accumulator;
960
+ },
961
+ {
962
+ P0: 0,
963
+ P1: 0,
964
+ P2: 0,
965
+ P3: 0,
966
+ }
967
+ );
968
+ }
969
+
970
+ function formatStaticCheckMarkdown(checks = []) {
971
+ if (!checks.length) {
972
+ return "- none";
973
+ }
974
+ return checks
975
+ .map(
976
+ (check) =>
977
+ `- ${check.id}: ${check.status} (${check.durationMs}ms) :: ${check.command}${check.reason ? ` :: ${check.reason}` : ""}`
978
+ )
979
+ .join("\n");
980
+ }
981
+
982
+ function formatDeterministicFindingsMarkdown(findings = []) {
983
+ if (!findings.length) {
984
+ return "- none";
985
+ }
986
+ return findings
987
+ .map(
988
+ (finding, index) =>
989
+ `${index + 1}. [${finding.severity}] (${finding.ruleId}) ${finding.file}:${finding.line} - ${finding.message}\n` +
990
+ ` suggested_fix: ${finding.suggestedFix}\n` +
991
+ ` excerpt: ${finding.excerpt}`
992
+ )
993
+ .join("\n");
994
+ }
995
+
996
+ function buildDeterministicReviewMarkdown(result) {
997
+ const frameworks = result.layers.ingest.frameworks.length
998
+ ? result.layers.ingest.frameworks.join(", ")
999
+ : "none";
1000
+ const riskSurfaces = result.layers.ingest.riskSurfaces.length
1001
+ ? result.layers.ingest.riskSurfaces.map((item) => item.surface).join(", ")
1002
+ : "none";
1003
+ const scopedPreview = result.scope.scannedRelativeFiles.slice(0, 80);
1004
+ const omitted = Math.max(0, result.scope.scannedRelativeFiles.length - scopedPreview.length);
1005
+
1006
+ return `# REVIEW_DETERMINISTIC
1007
+
1008
+ Generated: ${result.generatedAt}
1009
+ Run ID: ${result.runId}
1010
+ Target: ${result.targetPath}
1011
+ Mode: ${result.mode}
1012
+
1013
+ Summary:
1014
+ - Files scoped: ${result.scope.scannedFiles}
1015
+ - Findings: P0=${result.summary.P0} P1=${result.summary.P1} P2=${result.summary.P2} P3=${result.summary.P3}
1016
+ - Blocking: ${result.summary.blocking ? "yes" : "no"}
1017
+
1018
+ Layer 1 - Codebase ingest:
1019
+ - Files scanned: ${result.layers.ingest.summary.filesScanned}
1020
+ - Total LOC: ${result.layers.ingest.summary.totalLoc}
1021
+ - Frameworks: ${frameworks}
1022
+ - Risk surfaces: ${riskSurfaces}
1023
+ - Refresh: ${result.layers.ingest.refresh?.refreshed ? "yes" : "no"}
1024
+ - Stale: ${result.layers.ingest.refresh?.stale ? "yes" : "no"}
1025
+ - Refresh reasons: ${(result.layers.ingest.refresh?.reasons || []).join(", ") || "none"}
1026
+
1027
+ Layer 2 - Structural analysis:
1028
+ - Rules evaluated: ${result.layers.structural.ruleCount}
1029
+ - Findings: ${result.layers.structural.findingCount}
1030
+
1031
+ Layer 3 - Static analysis orchestration:
1032
+ ${formatStaticCheckMarkdown(result.layers.staticAnalysis.checks)}
1033
+
1034
+ Layer 4 - Spec binding checks:
1035
+ - Enabled: ${result.layers.specBinding.enabled ? "yes" : "no"}
1036
+ - Spec path: ${result.layers.specBinding.specPath || "none"}
1037
+ - Spec hash: ${result.layers.specBinding.specHashSha256 || "none"}
1038
+ - Spec endpoints: ${result.layers.specBinding.endpointCount}
1039
+ - Acceptance criteria: ${result.layers.specBinding.acceptanceCriteriaCount}
1040
+ - Findings: ${result.layers.specBinding.findingCount}
1041
+
1042
+ Layer 5 - Pattern checks:
1043
+ - Findings: ${result.layers.pattern.findingCount}
1044
+
1045
+ Readiness checks:
1046
+ - Findings: ${result.layers.readiness.findingCount}
1047
+
1048
+ Scoped files:
1049
+ ${scopedPreview.length > 0 ? scopedPreview.map((item) => `- ${item}`).join("\n") : "- none"}
1050
+ ${omitted > 0 ? `- ... ${omitted} more files omitted` : ""}
1051
+
1052
+ Findings:
1053
+ ${formatDeterministicFindingsMarkdown(result.findings)}
1054
+ `;
1055
+ }
1056
+
1057
+ async function writeDeterministicReviewArtifacts({ result, runDir } = {}) {
1058
+ const markdownPath = path.join(runDir, "REVIEW_DETERMINISTIC.md");
1059
+ const jsonPath = path.join(runDir, "REVIEW_DETERMINISTIC.json");
1060
+
1061
+ await fsp.writeFile(markdownPath, `${buildDeterministicReviewMarkdown(result).trim()}\n`, "utf-8");
1062
+ await fsp.writeFile(jsonPath, `${JSON.stringify(result, null, 2)}\n`, "utf-8");
1063
+
1064
+ return {
1065
+ markdownPath,
1066
+ jsonPath,
1067
+ };
1068
+ }
1069
+
1070
+ export async function runDeterministicReviewPipeline({
1071
+ targetPath,
1072
+ mode = "full",
1073
+ outputDir = "",
1074
+ specFile = "",
1075
+ refreshIngest = false,
1076
+ } = {}) {
1077
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
1078
+ const normalizedMode = normalizeMode(mode, {
1079
+ allowedModes: ["full", "diff", "staged"],
1080
+ });
1081
+
1082
+ const outputRoot = await resolveOutputRoot({
1083
+ cwd: normalizedTargetPath,
1084
+ outputDirOverride: outputDir,
1085
+ });
1086
+ const runId = `review-${formatTimestampForFile()}-${randomUUID().slice(0, 8)}`;
1087
+ const runDir = path.join(outputRoot, "reviews", runId);
1088
+ await fsp.mkdir(runDir, { recursive: true });
1089
+
1090
+ const ingestResolution = await resolveCodebaseIngest({
1091
+ rootPath: normalizedTargetPath,
1092
+ outputDir,
1093
+ refresh: Boolean(refreshIngest),
1094
+ });
1095
+ const ingest = ingestResolution.ingest;
1096
+ const scopedFiles = await collectModeFilePaths(normalizedTargetPath, normalizedMode);
1097
+
1098
+ const structuralFindings = await scanRulesForFiles({
1099
+ rootPath: normalizedTargetPath,
1100
+ filePaths: scopedFiles,
1101
+ rules: DETERMINISTIC_REVIEW_RULES,
1102
+ maxFindings: MAX_FINDINGS,
1103
+ layer: "structural",
1104
+ });
1105
+
1106
+ let remainingBudget = Math.max(0, MAX_FINDINGS - structuralFindings.length);
1107
+ const patternFindings = await runPatternChecks({
1108
+ rootPath: normalizedTargetPath,
1109
+ filePaths: scopedFiles,
1110
+ maxFindings: remainingBudget,
1111
+ });
1112
+
1113
+ remainingBudget = Math.max(0, remainingBudget - patternFindings.length);
1114
+ const readinessFindings = await runReadinessChecks({
1115
+ targetPath: normalizedTargetPath,
1116
+ maxFindings: remainingBudget,
1117
+ });
1118
+
1119
+ remainingBudget = Math.max(0, remainingBudget - readinessFindings.length);
1120
+ const specBinding = await runSpecBindingChecks({
1121
+ targetPath: normalizedTargetPath,
1122
+ mode: normalizedMode,
1123
+ scopedFilePaths: scopedFiles,
1124
+ maxFindings: remainingBudget,
1125
+ specFile,
1126
+ });
1127
+
1128
+ remainingBudget = Math.max(0, remainingBudget - specBinding.findings.length);
1129
+ const staticAnalysis = await runStaticAnalysisLayer({
1130
+ targetPath: normalizedTargetPath,
1131
+ ingest,
1132
+ runDir,
1133
+ maxFindings: remainingBudget,
1134
+ });
1135
+
1136
+ const findings = sortFindings([
1137
+ ...structuralFindings,
1138
+ ...patternFindings,
1139
+ ...readinessFindings,
1140
+ ...specBinding.findings,
1141
+ ...staticAnalysis.findings,
1142
+ ]);
1143
+ const severity = summarizeSeverity(findings);
1144
+
1145
+ const result = {
1146
+ schemaVersion: "1.0.0",
1147
+ generatedAt: new Date().toISOString(),
1148
+ runId,
1149
+ targetPath: normalizedTargetPath,
1150
+ mode: normalizedMode,
1151
+ scope: {
1152
+ scannedFiles: scopedFiles.length,
1153
+ scannedRelativeFiles: scopedFiles.map((filePath) => toPosixPath(path.relative(normalizedTargetPath, filePath))),
1154
+ },
1155
+ layers: {
1156
+ ingest: {
1157
+ summary: ingest.summary,
1158
+ frameworks: Array.isArray(ingest.frameworks) ? ingest.frameworks : [],
1159
+ entryPoints: Array.isArray(ingest.entryPoints) ? ingest.entryPoints : [],
1160
+ manifests: Array.isArray(ingest.manifests?.detected) ? ingest.manifests.detected : [],
1161
+ riskSurfaces: Array.isArray(ingest.riskSurfaces) ? ingest.riskSurfaces : [],
1162
+ refresh: {
1163
+ outputPath: ingestResolution.outputPath,
1164
+ refreshed: ingestResolution.refreshed,
1165
+ stale: ingestResolution.stale,
1166
+ reasons: ingestResolution.reasons,
1167
+ refreshedBecause: ingestResolution.refreshedBecause,
1168
+ lastCommitAt: ingestResolution.lastCommitAt,
1169
+ contentHash: ingestResolution.fingerprint?.contentHash || "",
1170
+ },
1171
+ },
1172
+ structural: {
1173
+ ruleCount: DETERMINISTIC_REVIEW_RULES.length,
1174
+ findingCount: structuralFindings.length,
1175
+ },
1176
+ staticAnalysis: {
1177
+ checkCount: staticAnalysis.checks.length,
1178
+ checks: staticAnalysis.checks,
1179
+ findingCount: staticAnalysis.findings.length,
1180
+ },
1181
+ specBinding: {
1182
+ enabled: Boolean(specBinding.metadata.enabled),
1183
+ specPath: specBinding.metadata.specPath
1184
+ ? toPosixPath(path.relative(normalizedTargetPath, specBinding.metadata.specPath))
1185
+ : "",
1186
+ specHashSha256: specBinding.metadata.specHashSha256 || "",
1187
+ endpointCount: specBinding.metadata.endpointCount || 0,
1188
+ acceptanceCriteriaCount: specBinding.metadata.acceptanceCriteriaCount || 0,
1189
+ endpointsPreview: Array.isArray(specBinding.metadata.endpointsPreview)
1190
+ ? specBinding.metadata.endpointsPreview
1191
+ : [],
1192
+ findingCount: specBinding.findings.length,
1193
+ },
1194
+ pattern: {
1195
+ findingCount: patternFindings.length,
1196
+ },
1197
+ readiness: {
1198
+ findingCount: readinessFindings.length,
1199
+ },
1200
+ },
1201
+ findings,
1202
+ summary: {
1203
+ P0: severity.P0,
1204
+ P1: severity.P1,
1205
+ P2: severity.P2,
1206
+ P3: severity.P3,
1207
+ blocking: severity.P0 > 0 || severity.P1 > 0,
1208
+ },
1209
+ };
1210
+
1211
+ const artifacts = await writeDeterministicReviewArtifacts({
1212
+ result,
1213
+ runDir,
1214
+ });
1215
+
1216
+ return {
1217
+ ...result,
1218
+ artifacts: {
1219
+ runDirectory: runDir,
1220
+ ...artifacts,
1221
+ },
1222
+ };
1223
+ }
1224
+
1225
+ export async function runLocalReviewScan({ targetPath, mode = "full", specFile = "" } = {}) {
1226
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
1227
+ const normalizedMode = normalizeMode(mode, {
1228
+ allowedModes: ["full", "diff", "staged"],
1229
+ });
1230
+
1231
+ const filePaths = await collectModeFilePaths(normalizedTargetPath, normalizedMode);
1232
+
1233
+ const scan = await scanFileSet(normalizedTargetPath, filePaths);
1234
+ const remainingBudget = Math.max(0, MAX_FINDINGS - scan.findings.length);
1235
+ const specBinding = await runSpecBindingChecks({
1236
+ targetPath: normalizedTargetPath,
1237
+ mode: normalizedMode,
1238
+ scopedFilePaths: filePaths,
1239
+ maxFindings: remainingBudget,
1240
+ specFile,
1241
+ });
1242
+ const findings = sortFindings([...scan.findings, ...specBinding.findings]);
1243
+ const p1 = findings.filter((item) => item.severity === "P1").length;
1244
+ const p2 = findings.filter((item) => item.severity === "P2").length;
1245
+
1246
+ return {
1247
+ targetPath: normalizedTargetPath,
1248
+ mode: normalizedMode,
1249
+ scannedRelativeFiles: filePaths.map((filePath) =>
1250
+ toPosixPath(path.relative(normalizedTargetPath, filePath))
1251
+ ),
1252
+ scannedFiles: filePaths.length,
1253
+ findings,
1254
+ p1,
1255
+ p2,
1256
+ specBinding: specBinding.metadata,
1257
+ };
1258
+ }
1259
+
1260
+ export function formatFindingsMarkdown(findings = []) {
1261
+ if (!Array.isArray(findings) || findings.length === 0) {
1262
+ return "- none";
1263
+ }
1264
+ return findings
1265
+ .map((item, index) => `${index + 1}. [${item.severity}] ${item.file}:${item.line} - ${item.message}`)
1266
+ .join("\n");
1267
+ }
1268
+
1269
+ export async function writeReviewReport({
1270
+ targetPath,
1271
+ mode,
1272
+ outputDir = "",
1273
+ reportMarkdown,
1274
+ } = {}) {
1275
+ const outputRoot = await resolveOutputRoot({
1276
+ cwd: targetPath,
1277
+ outputDirOverride: outputDir,
1278
+ });
1279
+ const reportDir = path.join(outputRoot, "reports");
1280
+ await fsp.mkdir(reportDir, { recursive: true });
1281
+ const reportPath = path.join(reportDir, `review-scan-${mode}-${formatTimestampForFile()}.md`);
1282
+ await fsp.writeFile(reportPath, `${String(reportMarkdown || "").trim()}\n`, "utf-8");
1283
+ return reportPath;
1284
+ }