sentinelayer-cli 0.1.2 → 0.4.4

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