sentinelayer-cli 0.4.4 → 0.6.2

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