sentinelayer-cli 0.6.2 → 0.8.0

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