agentic-sdlc-mcp 1.5.0 → 1.6.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 (42) hide show
  1. package/README.md +26 -6
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +1 -1
  4. package/dist/config.js.map +1 -1
  5. package/dist/github/codeowners.d.ts +24 -0
  6. package/dist/github/codeowners.d.ts.map +1 -0
  7. package/dist/github/codeowners.js +153 -0
  8. package/dist/github/codeowners.js.map +1 -0
  9. package/dist/github/pull-request-evidence.d.ts +123 -0
  10. package/dist/github/pull-request-evidence.d.ts.map +1 -0
  11. package/dist/github/pull-request-evidence.js +590 -0
  12. package/dist/github/pull-request-evidence.js.map +1 -0
  13. package/dist/rendering/markdown.d.ts +8 -0
  14. package/dist/rendering/markdown.d.ts.map +1 -0
  15. package/dist/rendering/markdown.js +27 -0
  16. package/dist/rendering/markdown.js.map +1 -0
  17. package/dist/review/pull-request-review.d.ts +77 -0
  18. package/dist/review/pull-request-review.d.ts.map +1 -0
  19. package/dist/review/pull-request-review.js +1185 -0
  20. package/dist/review/pull-request-review.js.map +1 -0
  21. package/dist/security/secret-scanner-evidence.d.ts +58 -0
  22. package/dist/security/secret-scanner-evidence.d.ts.map +1 -0
  23. package/dist/security/secret-scanner-evidence.js +414 -0
  24. package/dist/security/secret-scanner-evidence.js.map +1 -0
  25. package/dist/tools/quality-gate-status.d.ts +292 -5
  26. package/dist/tools/quality-gate-status.d.ts.map +1 -1
  27. package/dist/tools/quality-gate-status.js +665 -95
  28. package/dist/tools/quality-gate-status.js.map +1 -1
  29. package/dist/tools/release-readiness.d.ts.map +1 -1
  30. package/dist/tools/release-readiness.js +81 -39
  31. package/dist/tools/release-readiness.js.map +1 -1
  32. package/dist/tools/review-pr.d.ts +113 -29
  33. package/dist/tools/review-pr.d.ts.map +1 -1
  34. package/dist/tools/review-pr.js +237 -314
  35. package/dist/tools/review-pr.js.map +1 -1
  36. package/dist/tools/workflow-permissions-audit.d.ts +14 -1
  37. package/dist/tools/workflow-permissions-audit.d.ts.map +1 -1
  38. package/dist/tools/workflow-permissions-audit.js +40 -15
  39. package/dist/tools/workflow-permissions-audit.js.map +1 -1
  40. package/dist/version.d.ts +1 -1
  41. package/dist/version.js +1 -1
  42. package/package.json +1 -1
@@ -0,0 +1,1185 @@
1
+ import { isSecretScannerPolicyPath, secretScannerPolicyFinding, unverifiedSecretScannerEvidence, } from "../security/secret-scanner-evidence.js";
2
+ const SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"];
3
+ const LOCK_FILE_NAMES = new Set([
4
+ "bun.lock",
5
+ "bun.lockb",
6
+ "cargo.lock",
7
+ "composer.lock",
8
+ "gemfile.lock",
9
+ "go.sum",
10
+ "npm-shrinkwrap.json",
11
+ "package-lock.json",
12
+ "pipfile.lock",
13
+ "pnpm-lock.yaml",
14
+ "poetry.lock",
15
+ "uv.lock",
16
+ "yarn.lock",
17
+ ]);
18
+ function normalizePath(filename) {
19
+ return filename.replace(/\\/g, "/").replace(/^\.\//, "");
20
+ }
21
+ function normalizeFile(file) {
22
+ return {
23
+ ...file,
24
+ filename: normalizePath(file.filename),
25
+ previousFilename: file.previousFilename === undefined ? undefined : normalizePath(file.previousFilename),
26
+ };
27
+ }
28
+ function isDocsPath(filename) {
29
+ const lower = filename.toLowerCase();
30
+ const basename = lower.split("/").at(-1) ?? lower;
31
+ return (lower.startsWith("docs/") ||
32
+ /\.(?:adoc|md|mdx|rst|txt)$/.test(lower) ||
33
+ /^(?:changelog|contributing|license|readme)(?:\..+)?$/.test(basename));
34
+ }
35
+ function isTestPath(filename) {
36
+ const lower = filename.toLowerCase();
37
+ return (/(?:^|\/)(?:__tests__|tests?|specs?)(?:\/|$)/.test(lower) ||
38
+ /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(lower) ||
39
+ /(?:^|\/)__snapshots__(?:\/|$)/.test(lower) ||
40
+ lower.endsWith(".snap"));
41
+ }
42
+ function isSnapshotPath(filename) {
43
+ const lower = filename.toLowerCase();
44
+ return /(?:^|\/)__snapshots__(?:\/|$)/.test(lower) || lower.endsWith(".snap");
45
+ }
46
+ function isWorkflowPath(filename) {
47
+ return filename.toLowerCase().startsWith(".github/workflows/");
48
+ }
49
+ function isInfrastructurePath(filename) {
50
+ const lower = filename.toLowerCase();
51
+ const basename = lower.split("/").at(-1) ?? lower;
52
+ return (isWorkflowPath(lower) ||
53
+ /(?:^|\/)(?:deploy|deployment|helm|infra|infrastructure|k8s|kubernetes|terraform)(?:\/|$)/.test(lower) ||
54
+ /\.(?:tf|tfvars)$/.test(lower) ||
55
+ /^dockerfile(?:\..+)?$/.test(basename) ||
56
+ /^(?:docker-compose|compose)\.(?:ya?ml)$/.test(basename));
57
+ }
58
+ function isEnvironmentPath(filename) {
59
+ return /(?:^|\/)\.env(?:\.|$)/i.test(filename);
60
+ }
61
+ function isAuthSecurityPath(filename) {
62
+ const lower = filename.toLowerCase();
63
+ return (isEnvironmentPath(lower) ||
64
+ /(?:^|[\/_.-])(?:auth|authorization|credential|credentials|oauth|password|permissions?|secrets?|security|session|tokens?)(?:[\/_.-]|$)/.test(lower));
65
+ }
66
+ function isReleasePath(filename) {
67
+ const lower = filename.toLowerCase();
68
+ const basename = lower.split("/").at(-1) ?? lower;
69
+ return ([".npmrc", "package.json", "server.json"].includes(basename) ||
70
+ /(?:^|\/)version\.[cm]?[jt]s$/.test(lower) ||
71
+ /(?:^|\/)(?:publish|release|releases)(?:\/|$)/.test(lower) ||
72
+ /(?:^|[._-])(?:publish|release)(?:[._-]|$)/.test(basename) ||
73
+ /(?:^|\/)(?:publish|release)\.[^/]+$/.test(lower));
74
+ }
75
+ function isLockPath(filename) {
76
+ return LOCK_FILE_NAMES.has((filename.split("/").at(-1) ?? filename).toLowerCase());
77
+ }
78
+ function isGeneratedPath(filename) {
79
+ const lower = filename.toLowerCase();
80
+ return (/(?:^|\/)(?:build|coverage|dist|generated)(?:\/|$)/.test(lower) ||
81
+ /\.min\.(?:css|js)$/.test(lower));
82
+ }
83
+ export function classifyPrFiles(files) {
84
+ const allFiles = files.map(normalizeFile);
85
+ const docsFiles = allFiles.filter((file) => isDocsPath(file.filename));
86
+ const testFiles = allFiles.filter((file) => isTestPath(file.filename));
87
+ const snapshotTestFiles = testFiles.filter((file) => isSnapshotPath(file.filename));
88
+ const nonSnapshotTestFiles = testFiles.filter((file) => !isSnapshotPath(file.filename));
89
+ const workflowFiles = allFiles.filter((file) => isWorkflowPath(file.filename));
90
+ const infrastructureFiles = allFiles.filter((file) => isInfrastructurePath(file.filename));
91
+ const authSecurityFiles = allFiles.filter((file) => isAuthSecurityPath(file.filename));
92
+ const releaseFiles = allFiles.filter((file) => isReleasePath(file.filename));
93
+ const lockFiles = allFiles.filter((file) => isLockPath(file.filename));
94
+ const envFiles = allFiles.filter((file) => isEnvironmentPath(file.filename));
95
+ const generatedFiles = allFiles.filter((file) => isGeneratedPath(file.filename));
96
+ const sourceFiles = allFiles.filter((file) => !docsFiles.includes(file) &&
97
+ !testFiles.includes(file) &&
98
+ !lockFiles.includes(file) &&
99
+ !generatedFiles.includes(file));
100
+ return {
101
+ allFiles,
102
+ docsFiles,
103
+ testFiles,
104
+ snapshotTestFiles,
105
+ nonSnapshotTestFiles,
106
+ workflowFiles,
107
+ infrastructureFiles,
108
+ authSecurityFiles,
109
+ releaseFiles,
110
+ lockFiles,
111
+ envFiles,
112
+ generatedFiles,
113
+ sourceFiles,
114
+ docsOnly: allFiles.length > 0 && docsFiles.length === allFiles.length,
115
+ };
116
+ }
117
+ function normalizedLabels(labels) {
118
+ return labels.map((label) => label.trim().toLowerCase());
119
+ }
120
+ function hasLabel(labels, pattern) {
121
+ return labels.some((label) => pattern.test(label));
122
+ }
123
+ export function inferWorkType(pr, files) {
124
+ const classified = classifyPrFiles(files);
125
+ const labels = normalizedLabels(pr.labels);
126
+ const title = pr.title.trim();
127
+ const body = pr.body ?? "";
128
+ if (hasLabel(labels, /^(?:security|security-fix|vulnerability)$/) ||
129
+ /\b(?:security|vulnerability|cve-\d+|credential exposure)\b/i.test(title) ||
130
+ /\b(?:security(?: hardening| vulnerability)?|credential exposure|threat model|cve-\d+)\b/i.test(body)) {
131
+ return {
132
+ workType: "security",
133
+ confidence: "high",
134
+ reasoning: "Security-specific label or PR text takes priority over other work signals.",
135
+ };
136
+ }
137
+ if (classified.releaseFiles.length > 0 ||
138
+ hasLabel(labels, /^(?:publish|release|release-.+)$/) ||
139
+ /\b(?:publish|release)\b/i.test(title)) {
140
+ return {
141
+ workType: "release",
142
+ confidence: "high",
143
+ reasoning: "A release/publish path, label, or title explicitly identifies release work.",
144
+ };
145
+ }
146
+ if (classified.infrastructureFiles.length > 0) {
147
+ return {
148
+ workType: "infra",
149
+ confidence: "high",
150
+ reasoning: "Workflow or infrastructure paths are present in the changed files.",
151
+ };
152
+ }
153
+ if (classified.docsOnly) {
154
+ return {
155
+ workType: "docs",
156
+ confidence: "high",
157
+ reasoning: "Every changed file is documentation.",
158
+ };
159
+ }
160
+ if (hasLabel(labels, /^(?:bug|bugfix|defect|fix|regression)$/) ||
161
+ /\b(?:bug|bugfix|crash|defect|fix(?:e[sd])?|regression)\b/i.test(title) ||
162
+ /\b(?:bugfix|bug|crash|defect|regression|reproducible crash|fix(?:e[sd])? (?:a |the )?(?:bug|crash|defect))\b/i.test(body)) {
163
+ return {
164
+ workType: "bugfix",
165
+ confidence: "medium",
166
+ reasoning: "A bug-specific label or conservative bug/regression phrase is present.",
167
+ };
168
+ }
169
+ if (hasLabel(labels, /^(?:refactor|refactoring)$/) ||
170
+ /\b(?:refactor|refactoring)\b/i.test(title)) {
171
+ return {
172
+ workType: "refactor",
173
+ confidence: "medium",
174
+ reasoning: "A refactor label or title identifies behavior-preserving restructuring.",
175
+ };
176
+ }
177
+ return {
178
+ workType: "feature",
179
+ confidence: "low",
180
+ reasoning: "No higher-confidence task signal was found; feature is the conservative default.",
181
+ };
182
+ }
183
+ function finding(severity, category, dimension, description, paths, reason, suggestion) {
184
+ return { severity, category, dimension, description, paths, reason, suggestion };
185
+ }
186
+ function hasDetailedPrefixedLine(body, prefixes) {
187
+ return body.split(/\r?\n/).some((line) => {
188
+ const match = line.match(prefixes);
189
+ return Boolean(match?.[1] && match[1].replace(/\s/g, "").length >= 10);
190
+ });
191
+ }
192
+ function hasNoTestReason(body) {
193
+ return hasDetailedPrefixedLine(body, /^\s*(?:[-*]\s*)?(?:no tests|testing not required)\s*:\s*(.+)$/i);
194
+ }
195
+ function sectionContents(body, names) {
196
+ const lines = body.split(/\r?\n/);
197
+ const namePattern = new RegExp(`^(?:${names})\\s*:?$`, "i");
198
+ const inlinePattern = new RegExp(`^\\s*(?:${names})\\s*:\\s*(.*)$`, "i");
199
+ const sections = [];
200
+ for (let index = 0; index < lines.length; index += 1) {
201
+ const line = lines[index] ?? "";
202
+ const heading = line.match(/^\s*#{1,6}\s+(.+?)\s*#*\s*$/);
203
+ const inline = line.match(inlinePattern);
204
+ if (!heading && !inline)
205
+ continue;
206
+ if (heading && !namePattern.test(heading[1] ?? ""))
207
+ continue;
208
+ const content = [];
209
+ if (inline?.[1])
210
+ content.push(inline[1]);
211
+ for (let cursor = index + 1; cursor < lines.length; cursor += 1) {
212
+ const next = lines[cursor] ?? "";
213
+ if (/^\s*#{1,6}\s+/.test(next))
214
+ break;
215
+ content.push(next);
216
+ }
217
+ sections.push(content.join("\n").trim());
218
+ }
219
+ return sections;
220
+ }
221
+ function hasDetailedSection(body, names) {
222
+ return sectionContents(body, names).some((content) => content.replace(/\s/g, "").length >= 10);
223
+ }
224
+ function hasConcreteVerificationMethod(content) {
225
+ return (/\bmarkdownlint\b|\blink[ -]?check(?:er|ing)?\b/i.test(content) ||
226
+ /\b(?:ran|run|executed|verified with|validated with)\s+`?(?:bun|cargo|dotnet|git|go|gradle|make|markdownlint|mvn|node|npm|npx|pnpm|python|pytest|yarn)\b/i.test(content) ||
227
+ /\brender(?:ed|ing)?\b[^.\n]*\b(?:doc(?:umentation)?|markdown|page|site)\b/i.test(content) ||
228
+ /\b(?:build|built)\b[^.\n]*\b(?:doc(?:umentation)?|example|page|site)\b/i.test(content) ||
229
+ /\b(?:checked|validated|verified)\b[^.\n]*\b(?:example|link|markdown|render(?:ed)?|output)\b/i.test(content));
230
+ }
231
+ function hasDocsVerification(body) {
232
+ const sections = sectionContents(body, "verification|validated");
233
+ return sections.length > 0
234
+ ? sections.some(hasConcreteVerificationMethod)
235
+ : hasConcreteVerificationMethod(body);
236
+ }
237
+ function hasBugReproduction(body) {
238
+ return hasDetailedSection(body, "reproduction|steps? to reproduce|before");
239
+ }
240
+ function hasFallback(body) {
241
+ return hasDetailedSection(body, "rollback|fallback|revert");
242
+ }
243
+ function hasSecurityValidation(body) {
244
+ return (hasDetailedSection(body, "security verification|security validation") ||
245
+ /\b(?:codeql|dast|npm audit|penetration test(?:ing)?|sast|security test(?:ing)?|threat model (?:validated|verified))\b/i.test(body));
246
+ }
247
+ const SECRET_ASSIGNMENTS = [
248
+ {
249
+ name: "credential assignment",
250
+ pattern: /(?:^|[,{;]\s*|\b(?:const|let|var)\s+)\s*["']?[\w.-]*(?:api[_-]?key|client[_-]?secret|credential|password|private[_-]?key|secret|token)[\w.-]*["']?\s*[:=]\s*(?:"([^"]+)"|'([^']+)'|`([^`]+)`|([^\s,;]+))/i,
251
+ },
252
+ {
253
+ name: "AWS access key assignment",
254
+ pattern: /\b[\w.-]+\s*[:=]\s*(?:"(AKIA[0-9A-Z]{16})"|'(AKIA[0-9A-Z]{16})'|`(AKIA[0-9A-Z]{16})`|(AKIA[0-9A-Z]{16}))\b/,
255
+ },
256
+ ];
257
+ function isPlaceholderSecret(value) {
258
+ const normalized = value.trim();
259
+ return (normalized.length < 8 ||
260
+ /(?:process|import\.meta)\.env|\bsecrets\.|(?:os\.)?getenv\s*\(|\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*\b/.test(normalized) ||
261
+ /^(?:<[^>]+>|\*+|redacted|fake|your[_ -]|change[_ -]?me|dummy|example|placeholder|sample|test)/i.test(normalized) ||
262
+ /^x+$/i.test(normalized) ||
263
+ /^(?:AKIA[0-9A-Z]*EXAMPLE|(?:ghp_|github_pat_|sk-|xox[a-z]-)(?:x+|your(?:[-_ ]|$)|example|dummy|redacted|change[-_ ]?me|placeholder))/i.test(normalized) ||
264
+ /(?:_example|example_|your[_ -]?token|not[_ -]?a[_ -]?secret)/i.test(normalized));
265
+ }
266
+ function isHighConfidenceUnquotedSecret(value) {
267
+ const normalized = value.trim();
268
+ if (/^(?:ghp_|github_pat_|sk-|AKIA[0-9A-Z]|xox[a-z]-|eyJ[a-zA-Z0-9_-]*\.)/.test(normalized)) {
269
+ return true;
270
+ }
271
+ if (/^(?:undefined|null|true|false)$/i.test(normalized) ||
272
+ /^[A-Za-z_$][\w$]*$/.test(normalized) ||
273
+ /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(normalized) ||
274
+ /[(){}[\]]/.test(normalized)) {
275
+ return false;
276
+ }
277
+ if (normalized.length < 20)
278
+ return false;
279
+ const classes = [/[a-z]/, /[A-Z]/, /\d/, /[^A-Za-z0-9]/].filter((pattern) => pattern.test(normalized)).length;
280
+ return classes >= 3;
281
+ }
282
+ function maskSecretCodeLine(line, state) {
283
+ if (state.mode === "code" && /^(?:\s*#|\s*\*)/.test(line))
284
+ return " ".repeat(line.length);
285
+ let code = "";
286
+ for (let index = 0; index < line.length; index += 1) {
287
+ const character = line[index] ?? "";
288
+ const next = line[index + 1] ?? "";
289
+ if (state.mode === "block_comment") {
290
+ if (character === "*" && next === "/") {
291
+ code += " ";
292
+ index += 1;
293
+ state.mode = "code";
294
+ }
295
+ else {
296
+ code += " ";
297
+ }
298
+ continue;
299
+ }
300
+ if (state.mode !== "code") {
301
+ code += " ";
302
+ if (state.escaped) {
303
+ state.escaped = false;
304
+ }
305
+ else if (character === "\\") {
306
+ state.escaped = true;
307
+ }
308
+ else if ((state.mode === "single" && character === "'") ||
309
+ (state.mode === "double" && character === '"') ||
310
+ (state.mode === "template" && character === "`")) {
311
+ state.mode = "code";
312
+ }
313
+ continue;
314
+ }
315
+ if (character === "/" && next === "/")
316
+ break;
317
+ if (character === "/" && next === "*") {
318
+ code += " ";
319
+ index += 1;
320
+ state.mode = "block_comment";
321
+ }
322
+ else if (character === "'" || character === '"' || character === "`") {
323
+ state.mode =
324
+ character === "'" ? "single" : character === '"' ? "double" : "template";
325
+ state.escaped = false;
326
+ code += " ";
327
+ }
328
+ else {
329
+ code += character;
330
+ }
331
+ }
332
+ return code.padEnd(line.length, " ");
333
+ }
334
+ function maskSecretCommentsLine(line, state) {
335
+ if (state.mode === "code" && /^(?:\s*#|\s*\*)/.test(line))
336
+ return " ".repeat(line.length);
337
+ let content = "";
338
+ for (let index = 0; index < line.length; index += 1) {
339
+ const character = line[index] ?? "";
340
+ const next = line[index + 1] ?? "";
341
+ if (state.mode === "block_comment") {
342
+ if (character === "*" && next === "/") {
343
+ content += " ";
344
+ index += 1;
345
+ state.mode = "code";
346
+ }
347
+ else {
348
+ content += " ";
349
+ }
350
+ continue;
351
+ }
352
+ if (state.mode !== "code") {
353
+ content += character;
354
+ if (state.escaped)
355
+ state.escaped = false;
356
+ else if (character === "\\")
357
+ state.escaped = true;
358
+ else if ((state.mode === "single" && character === "'") ||
359
+ (state.mode === "double" && character === '"') ||
360
+ (state.mode === "template" && character === "`")) {
361
+ state.mode = "code";
362
+ }
363
+ continue;
364
+ }
365
+ if (character === "/" && next === "/")
366
+ break;
367
+ if (character === "/" && next === "*") {
368
+ content += " ";
369
+ index += 1;
370
+ state.mode = "block_comment";
371
+ }
372
+ else if (character === "#" && (index === 0 || /\s/.test(line[index - 1] ?? ""))) {
373
+ break;
374
+ }
375
+ else {
376
+ content += character;
377
+ if (character === "'" || character === '"' || character === "`") {
378
+ state.mode = character === "'" ? "single" : character === '"' ? "double" : "template";
379
+ state.escaped = false;
380
+ }
381
+ }
382
+ }
383
+ return content.padEnd(line.length, " ");
384
+ }
385
+ const MAX_SECRET_STATEMENT_LINES = 100;
386
+ const MAX_SECRET_STATEMENT_CHARS = 64_000;
387
+ const MAX_SECRET_FINDING_GROUPS = 20;
388
+ function bracketDepth(code) {
389
+ let depth = 0;
390
+ for (const character of code) {
391
+ if (character === "(" || character === "[" || character === "{")
392
+ depth += 1;
393
+ else if (character === ")" || character === "]" || character === "}") {
394
+ depth = Math.max(0, depth - 1);
395
+ }
396
+ }
397
+ return depth;
398
+ }
399
+ function buildSecretStatements(lines) {
400
+ const statements = [];
401
+ let raw = "";
402
+ let code = "";
403
+ let semantic = "";
404
+ let added = [];
405
+ let lineCount = 0;
406
+ let containsAddedLine = false;
407
+ let truncated = false;
408
+ let activeHunk = lines[0]?.hunk ?? 0;
409
+ const flush = () => {
410
+ if (semantic.trim().length > 0) {
411
+ statements.push({
412
+ hunk: activeHunk,
413
+ raw,
414
+ code,
415
+ semantic,
416
+ added,
417
+ containsAddedLine,
418
+ truncated,
419
+ });
420
+ }
421
+ raw = "";
422
+ code = "";
423
+ semantic = "";
424
+ added = [];
425
+ lineCount = 0;
426
+ containsAddedLine = false;
427
+ truncated = false;
428
+ };
429
+ for (let index = 0; index < lines.length; index += 1) {
430
+ const line = lines[index];
431
+ if (!line)
432
+ continue;
433
+ if (line.hunk !== activeHunk) {
434
+ flush();
435
+ activeHunk = line.hunk;
436
+ }
437
+ const capacity = Math.max(0, MAX_SECRET_STATEMENT_CHARS - raw.length - 1);
438
+ const length = Math.min(line.text.length, capacity);
439
+ raw += `${line.text.slice(0, length)}\n`;
440
+ code += `${line.code.slice(0, length)}\n`;
441
+ semantic += `${line.semantic.slice(0, length)}\n`;
442
+ for (let charIndex = 0; charIndex < length; charIndex += 1)
443
+ added.push(line.added);
444
+ added.push(false);
445
+ if (length < line.text.length)
446
+ truncated = true;
447
+ containsAddedLine ||= line.added;
448
+ lineCount += 1;
449
+ let nextMeaningful;
450
+ for (let nextIndex = index + 1; nextIndex < lines.length; nextIndex += 1) {
451
+ const candidate = lines[nextIndex];
452
+ if (!candidate || candidate.hunk !== line.hunk)
453
+ break;
454
+ if (candidate.code.trim().length > 0) {
455
+ nextMeaningful = candidate;
456
+ break;
457
+ }
458
+ }
459
+ const trimmedCode = code.trimEnd();
460
+ const continues = line.modeAfter !== "code" ||
461
+ bracketDepth(code) > 0 ||
462
+ /(?:[=+%.,?:|&\\]|\b(?:return|yield))\s*$/.test(trimmedCode) ||
463
+ /^\s*(?:[=+%]|\.(?:append|concat|format|join)\b)/.test(nextMeaningful?.code ?? "");
464
+ const terminated = /;\s*$/.test(line.code) || !continues;
465
+ const limitReached = lineCount >= MAX_SECRET_STATEMENT_LINES || raw.length >= MAX_SECRET_STATEMENT_CHARS;
466
+ if (!terminated && limitReached)
467
+ truncated = true;
468
+ if (terminated ||
469
+ limitReached) {
470
+ flush();
471
+ }
472
+ }
473
+ flush();
474
+ return statements;
475
+ }
476
+ function assignmentOperatorIndexes(code) {
477
+ const indexes = [];
478
+ for (let index = 0; index < code.length; index += 1) {
479
+ const character = code[index] ?? "";
480
+ const previous = code[index - 1] ?? "";
481
+ const next = code[index + 1] ?? "";
482
+ if (character === "=") {
483
+ if (next === "=" || next === ">" || /[=!<>]/.test(previous))
484
+ continue;
485
+ indexes.push(index);
486
+ }
487
+ else if (character === ":") {
488
+ if (next === "=" || previous === ":" || previous === "?")
489
+ continue;
490
+ indexes.push(index);
491
+ }
492
+ }
493
+ return indexes;
494
+ }
495
+ function assignmentExpressionEnd(code, start) {
496
+ let depth = 0;
497
+ for (let index = start; index < code.length; index += 1) {
498
+ const character = code[index] ?? "";
499
+ if (character === "(" || character === "[" || character === "{")
500
+ depth += 1;
501
+ else if (character === ")" || character === "]" || character === "}") {
502
+ depth = Math.max(0, depth - 1);
503
+ }
504
+ else if (depth === 0 && (character === "," || character === ";")) {
505
+ return index;
506
+ }
507
+ }
508
+ return code.length;
509
+ }
510
+ function assignmentTargetStart(code, operatorIndex) {
511
+ let start = 0;
512
+ for (const delimiter of [";", ",", "{", "}"]) {
513
+ start = Math.max(start, code.lastIndexOf(delimiter, operatorIndex - 1) + 1);
514
+ }
515
+ return start;
516
+ }
517
+ function isCredentialMetadataTarget(normalizedTarget) {
518
+ return /(?:apikey|authorization(?:header)?|token|secret|password|credential)(?:bucket|cache|config|count|expir(?:y|es?)|factory|id|index|length|manager|metadata|names?|options|parser|policy|prefix|provider|service|status|store|strength|suffix|ttl|type|validation|validator|izer|ization)$/.test(normalizedTarget);
519
+ }
520
+ function isCredentialTarget(target) {
521
+ const normalized = target.toLowerCase().replace(/[^a-z0-9]/g, "");
522
+ if (!normalized || isCredentialMetadataTarget(normalized))
523
+ return false;
524
+ return /(?:apikey|authorization(?:header|token)?|clientsecret|credentials?|password|privatekey|secrets?|tokens?)/.test(normalized);
525
+ }
526
+ function assignedIdentifier(target) {
527
+ const match = target
528
+ .trim()
529
+ .match(/^(?:(?:const|let|var|final|val|auto|string|String)\s+)?([A-Za-z_$][\w$]*)$/);
530
+ return match?.[1] ?? null;
531
+ }
532
+ function targetUsesCredentialAlias(target, aliases) {
533
+ for (const alias of aliases) {
534
+ const escaped = alias.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
535
+ if (new RegExp(`\\[\\s*${escaped}\\s*\\]`).test(target))
536
+ return true;
537
+ }
538
+ return false;
539
+ }
540
+ function isTrustedRuntimeSecretExpression(value) {
541
+ let remainder = value
542
+ .replace(/(?:process|import\.meta|Bun)\.env(?:\.[A-Za-z_$][\w$]*|\[\s*["'][^"']+["']\s*\])/gi, "")
543
+ .replace(/\bsecrets(?:\.[A-Za-z_$][\w$]*|\[\s*["'][^"']+["']\s*\])/gi, "")
544
+ .replace(/(?:os\.)?getenv\s*\(\s*["'][^"']+["']\s*\)/gi, "")
545
+ .replace(/(?:os\.environ|ENV)\s*\[\s*["'][^"']+["']\s*\]/gi, "")
546
+ .replace(/(?:Deno\.env\.get|System\.getenv|Environment\.GetEnvironmentVariable)\s*\(\s*["'][^"']+["']\s*\)/gi, "")
547
+ .replace(/\b(?:vault|secretManager|secretsClient)\.(?:get|getSecret|accessSecretVersion)\s*\([^)]*\)/gi, "")
548
+ .replace(/(["'`])(?:Bearer|Basic|Token|[\s.:/_-]*)\1/gi, "")
549
+ .replace(/[\s+%(){}[\]$;,.?:|&!"'`]+/g, "");
550
+ remainder = remainder.replace(/^(?:f|undefined|null)$/i, "");
551
+ return remainder.length === 0;
552
+ }
553
+ function isDynamicSecretExpression(value, codeValue) {
554
+ const normalized = value.trim();
555
+ if (!normalized || isTrustedRuntimeSecretExpression(normalized))
556
+ return false;
557
+ return (codeValue.includes("+") ||
558
+ codeValue.includes("%") ||
559
+ /\.(?:append|concat|format|join)\s*\(/i.test(codeValue) ||
560
+ /\b(?:String\.format|fmt\.Sprintf|format!|concat!)\s*\(/i.test(codeValue) ||
561
+ /\b(?:Buffer\.from|Convert\.FromBase64String|String\.fromCharCode|TextDecoder\s*\([^)]*\)\.decode|atob|base64\.(?:b64decode|urlsafe_b64decode)|btoa|decodeURIComponent)\s*\(/i.test(codeValue) ||
562
+ /`[^`]*\$\{[^}]+\}[^`]*`/s.test(normalized) ||
563
+ /\bf["'][^"']*\{[^}]+\}[^"']*["']/is.test(normalized) ||
564
+ /\$@?["'][^"']*\{[^}]+\}[^"']*["']/s.test(normalized) ||
565
+ /#\{[^}]+\}|\{\$[A-Za-z_][\w]*\}|\\\([^)]+\)/s.test(normalized) ||
566
+ /["'][^"']*\$[A-Za-z_][\w]*[^"']*["']/s.test(normalized));
567
+ }
568
+ function assignmentIsInCode(match, codeLine) {
569
+ const value = match.slice(1).find((capture) => capture !== undefined);
570
+ if (!value || match.index === undefined)
571
+ return false;
572
+ const valueOffset = match[0].lastIndexOf(value);
573
+ const prefix = valueOffset >= 0 ? match[0].slice(0, valueOffset) : match[0];
574
+ const operatorOffset = Math.max(prefix.lastIndexOf("="), prefix.lastIndexOf(":"));
575
+ if (operatorOffset < 0)
576
+ return false;
577
+ const operatorIndex = match.index + operatorOffset;
578
+ return (codeLine[operatorIndex] ?? " ").trim().length > 0;
579
+ }
580
+ export function scanPatchForSecrets(filename, patch) {
581
+ if (!patch)
582
+ return [];
583
+ const normalizedFilename = normalizePath(filename);
584
+ const patchLines = newSidePatchLines(patch);
585
+ const scannedLines = [];
586
+ let activeHunk = -1;
587
+ let codeState = { mode: "code", escaped: false };
588
+ let semanticState = { mode: "code", escaped: false };
589
+ for (const line of patchLines) {
590
+ if (line.hunk !== activeHunk) {
591
+ activeHunk = line.hunk;
592
+ codeState = { mode: "code", escaped: false };
593
+ semanticState = { mode: "code", escaped: false };
594
+ }
595
+ const code = maskSecretCodeLine(line.text, codeState);
596
+ const semantic = maskSecretCommentsLine(line.text, semanticState);
597
+ scannedLines.push({ ...line, code, semantic, modeAfter: codeState.mode });
598
+ }
599
+ const findingGroups = new Map();
600
+ let suppressedGroups = 0;
601
+ const recordFinding = (item) => {
602
+ const key = `${item.severity}\u0000${item.category}\u0000${item.paths.join("\u0000")}`;
603
+ const existing = findingGroups.get(key);
604
+ if (existing) {
605
+ existing.count += 1;
606
+ return;
607
+ }
608
+ if (findingGroups.size >= MAX_SECRET_FINDING_GROUPS) {
609
+ suppressedGroups += 1;
610
+ return;
611
+ }
612
+ findingGroups.set(key, { finding: item, count: 1 });
613
+ };
614
+ const statements = buildSecretStatements(scannedLines);
615
+ const credentialAliasesByHunk = new Map();
616
+ for (const statement of statements) {
617
+ const aliases = credentialAliasesByHunk.get(statement.hunk) ?? new Set();
618
+ credentialAliasesByHunk.set(statement.hunk, aliases);
619
+ if (statement.truncated && statement.containsAddedLine) {
620
+ recordFinding(finding("high", "SecretScanEvidenceIncomplete", "security", `An added statement in \`${normalizedFilename}\` exceeded the bounded secret heuristic.`, [normalizedFilename], `The statement exceeded the ${MAX_SECRET_STATEMENT_LINES}-line or ${MAX_SECRET_STATEMENT_CHARS.toLocaleString("en-US")}-character limit, so the patch-local heuristic cannot safely inspect all credential construction after the limit.`, "Split the statement into reviewable units and require trusted scanner or SAST evidence plus manual review before merging."));
621
+ }
622
+ for (const operatorIndex of assignmentOperatorIndexes(statement.code)) {
623
+ const targetStart = assignmentTargetStart(statement.code, operatorIndex);
624
+ const expressionEnd = assignmentExpressionEnd(statement.code, operatorIndex + 1);
625
+ const target = statement.raw.slice(targetStart, operatorIndex);
626
+ const expression = statement.semantic.slice(operatorIndex + 1, expressionEnd);
627
+ const codeExpression = statement.code.slice(operatorIndex + 1, expressionEnd);
628
+ const codeTarget = statement.code.slice(targetStart, operatorIndex);
629
+ const usesCredentialAlias = targetUsesCredentialAlias(target, aliases);
630
+ const meaningfulAdded = statement.added
631
+ .slice(targetStart, expressionEnd)
632
+ .some((isAdded, offset) => {
633
+ if (!isAdded)
634
+ return false;
635
+ const absolute = targetStart + offset;
636
+ return /\S/.test(statement.semantic[absolute] ?? "");
637
+ });
638
+ if (meaningfulAdded &&
639
+ (usesCredentialAlias || isCredentialTarget(target)) &&
640
+ (usesCredentialAlias ||
641
+ isDynamicSecretExpression(expression, codeExpression) ||
642
+ isDynamicSecretExpression(target, codeTarget))) {
643
+ recordFinding(finding("high", "DynamicSecretConstruction", "security", `Credential-like value is dynamically constructed in \`${normalizedFilename}\`.`, [normalizedFilename], "An added part of this assignment combines, interpolates, formats, joins, decodes, or indirectly assigns data into a credential-like target, so patch-local literal matching cannot establish whether the result is safe.", "Verify every input source, remove hardcoded fragments, prefer a secret manager or environment variable, and require trusted scanner or SAST evidence plus manual review."));
644
+ }
645
+ const identifier = assignedIdentifier(target);
646
+ if (identifier &&
647
+ aliases.size < 100 &&
648
+ isCredentialTarget(expression) &&
649
+ isDynamicSecretExpression(expression, codeExpression)) {
650
+ aliases.add(identifier);
651
+ }
652
+ }
653
+ const credentialSinkPattern = /\.(?:setHeader|setRequestProperty|set)\s*\(\s*(["'])([^"']+)\1\s*,/gi;
654
+ for (const match of statement.semantic.matchAll(credentialSinkPattern)) {
655
+ if (match.index === undefined || !isCredentialTarget(match[2] ?? ""))
656
+ continue;
657
+ const expressionStart = match.index + match[0].length;
658
+ const expression = statement.semantic.slice(expressionStart);
659
+ const codeExpression = statement.code.slice(expressionStart);
660
+ const meaningfulAdded = statement.added
661
+ .slice(match.index, statement.semantic.length)
662
+ .some((isAdded, offset) => isAdded ? /\S/.test(statement.semantic[match.index + offset] ?? "") : false);
663
+ if (!meaningfulAdded || !isDynamicSecretExpression(expression, codeExpression))
664
+ continue;
665
+ recordFinding(finding("high", "DynamicSecretConstruction", "security", `Credential-like value is dynamically constructed in \`${normalizedFilename}\`.`, [normalizedFilename], "An added API call constructs a credential-like header value dynamically, so patch-local literal matching cannot establish whether the result is safe.", "Verify every input source, remove hardcoded fragments, prefer a secret manager or environment variable, and require trusted scanner or SAST evidence plus manual review."));
666
+ }
667
+ }
668
+ for (const line of scannedLines) {
669
+ const codeLine = line.code;
670
+ if (!line.added)
671
+ continue;
672
+ for (const { name, pattern } of SECRET_ASSIGNMENTS) {
673
+ let offset = 0;
674
+ while (offset < line.text.length) {
675
+ const match = line.text.slice(offset).match(pattern);
676
+ if (!match || match.index === undefined)
677
+ break;
678
+ const matchOffset = offset + match.index;
679
+ if (assignmentIsInCode(match, codeLine.slice(offset))) {
680
+ const quotedValue = match.slice(1, 4).find((capture) => capture !== undefined);
681
+ const unquotedValue = match[4];
682
+ const value = quotedValue ?? unquotedValue;
683
+ if (value &&
684
+ !isPlaceholderSecret(value) &&
685
+ (quotedValue !== undefined || isHighConfidenceUnquotedSecret(value))) {
686
+ recordFinding(finding("high", "SecretLikeAssignment", "security", `Possible ${name} added in \`${normalizedFilename}\`.`, [normalizedFilename], "The added patch line assigns a non-placeholder literal to a credential-like name.", "Confirm this is not a real credential; if it is, remove and rotate it, then load it from a secret store or environment variable."));
687
+ }
688
+ }
689
+ offset = matchOffset + Math.max(1, match[0].length);
690
+ }
691
+ }
692
+ }
693
+ const findings = [...findingGroups.values()].map(({ finding: item, count }) => count > 1
694
+ ? {
695
+ ...item,
696
+ description: `${item.description} ${count} matching occurrences were aggregated.`,
697
+ reason: `${item.reason} The response aggregates repeated findings by category and path.`,
698
+ }
699
+ : item);
700
+ if (suppressedGroups > 0) {
701
+ findings.push(finding("high", "SecretHeuristicFindingsTruncated", "security", `Additional secret-heuristic finding groups were omitted in \`${normalizedFilename}\`.`, [normalizedFilename], `The bounded response omitted ${suppressedGroups} distinct finding group(s) after the ${MAX_SECRET_FINDING_GROUPS}-group limit.`, "Split the PR and run trusted scanner/SAST evidence before review."));
702
+ }
703
+ return findings;
704
+ }
705
+ function newSidePatchLines(patch) {
706
+ const lines = [];
707
+ let hunk = 0;
708
+ for (const rawLine of patch.split(/\r?\n/)) {
709
+ if (rawLine.startsWith("@@")) {
710
+ hunk += 1;
711
+ continue;
712
+ }
713
+ if (rawLine.startsWith("+++") ||
714
+ rawLine.startsWith("---") ||
715
+ rawLine.startsWith("\\ No newline") ||
716
+ rawLine.startsWith("-")) {
717
+ continue;
718
+ }
719
+ if (rawLine.startsWith("+")) {
720
+ lines.push({ text: rawLine.slice(1), added: true, hunk });
721
+ }
722
+ else if (rawLine.startsWith(" ")) {
723
+ lines.push({ text: rawLine.slice(1), added: false, hunk });
724
+ }
725
+ }
726
+ return lines;
727
+ }
728
+ function addedPatchLines(file) {
729
+ if (!file.patch)
730
+ return null;
731
+ return newSidePatchLines(file.patch)
732
+ .filter((line) => line.added)
733
+ .map((line) => line.text);
734
+ }
735
+ function lexAssertionContent(content, added) {
736
+ let state = "code";
737
+ let escaped = false;
738
+ let result = "";
739
+ const meaningfulAdded = Array.from({ length: content.length }, () => false);
740
+ for (let index = 0; index < content.length; index += 1) {
741
+ const character = content[index] ?? "";
742
+ const next = content[index + 1] ?? "";
743
+ if (state === "line_comment") {
744
+ if (character === "\n") {
745
+ state = "code";
746
+ result += "\n";
747
+ }
748
+ else {
749
+ result += " ";
750
+ }
751
+ continue;
752
+ }
753
+ if (state === "block_comment") {
754
+ if (character === "*" && next === "/") {
755
+ result += " ";
756
+ index += 1;
757
+ state = "code";
758
+ }
759
+ else {
760
+ result += character === "\n" ? "\n" : " ";
761
+ }
762
+ continue;
763
+ }
764
+ if (state !== "code") {
765
+ result += character === "\n" ? "\n" : " ";
766
+ if (character !== "\n" &&
767
+ added[index]) {
768
+ meaningfulAdded[index] = true;
769
+ }
770
+ if (escaped) {
771
+ escaped = false;
772
+ }
773
+ else if (character === "\\") {
774
+ escaped = true;
775
+ }
776
+ else if ((state === "single" && character === "'") ||
777
+ (state === "double" && character === '"') ||
778
+ (state === "template" && character === "`")) {
779
+ state = "code";
780
+ }
781
+ continue;
782
+ }
783
+ if (character === "/" && next === "/") {
784
+ result += " ";
785
+ index += 1;
786
+ state = "line_comment";
787
+ }
788
+ else if (character === "/" && next === "*") {
789
+ result += " ";
790
+ index += 1;
791
+ state = "block_comment";
792
+ }
793
+ else if (character === "'") {
794
+ result += " ";
795
+ state = "single";
796
+ meaningfulAdded[index] = Boolean(added[index]);
797
+ }
798
+ else if (character === '"') {
799
+ result += " ";
800
+ state = "double";
801
+ meaningfulAdded[index] = Boolean(added[index]);
802
+ }
803
+ else if (character === "`") {
804
+ result += " ";
805
+ state = "template";
806
+ meaningfulAdded[index] = Boolean(added[index]);
807
+ }
808
+ else {
809
+ result += character;
810
+ meaningfulAdded[index] = Boolean(added[index] && !/\s/.test(character));
811
+ }
812
+ }
813
+ return { content: result, meaningfulAdded };
814
+ }
815
+ function buildNewSideCharacterStream(patch) {
816
+ let content = "";
817
+ const added = [];
818
+ for (const line of newSidePatchLines(patch)) {
819
+ const segment = `${line.text}\n`;
820
+ content += segment;
821
+ added.push(...Array.from({ length: segment.length }, () => line.added));
822
+ }
823
+ return lexAssertionContent(content, added);
824
+ }
825
+ function skipWhitespace(content, start) {
826
+ let cursor = start;
827
+ while (/\s/.test(content[cursor] ?? ""))
828
+ cursor += 1;
829
+ return cursor;
830
+ }
831
+ function findClosingParenthesis(content, openingIndex) {
832
+ let depth = 0;
833
+ for (let cursor = openingIndex; cursor < content.length; cursor += 1) {
834
+ const character = content[cursor];
835
+ if (character === "(")
836
+ depth += 1;
837
+ if (character === ")") {
838
+ depth -= 1;
839
+ if (depth === 0)
840
+ return cursor;
841
+ }
842
+ }
843
+ return null;
844
+ }
845
+ function spanContainsMeaningfulAdded(meaningfulAdded, start, end) {
846
+ for (let cursor = start; cursor <= end; cursor += 1) {
847
+ if (meaningfulAdded[cursor])
848
+ return true;
849
+ }
850
+ return false;
851
+ }
852
+ function hasAddedExpectAssertion(stream) {
853
+ const expectCall = /\bexpect\s*\(/g;
854
+ for (const match of stream.content.matchAll(expectCall)) {
855
+ const start = match.index;
856
+ const openingIndex = stream.content.indexOf("(", start);
857
+ const expectClose = findClosingParenthesis(stream.content, openingIndex);
858
+ if (expectClose === null)
859
+ continue;
860
+ let cursor = expectClose + 1;
861
+ while (cursor < stream.content.length) {
862
+ cursor = skipWhitespace(stream.content, cursor);
863
+ if (stream.content[cursor] !== ".")
864
+ break;
865
+ cursor = skipWhitespace(stream.content, cursor + 1);
866
+ const nameMatch = stream.content.slice(cursor).match(/^([A-Za-z_$][\w$]*)/);
867
+ const name = nameMatch?.[1];
868
+ if (!name)
869
+ break;
870
+ cursor += name.length;
871
+ if (["not", "rejects", "resolves"].includes(name))
872
+ continue;
873
+ cursor = skipWhitespace(stream.content, cursor);
874
+ if (stream.content[cursor] !== "(")
875
+ break;
876
+ const matcherClose = findClosingParenthesis(stream.content, cursor);
877
+ if (matcherClose === null)
878
+ break;
879
+ if (!name.toLowerCase().includes("snapshot") &&
880
+ spanContainsMeaningfulAdded(stream.meaningfulAdded, start, matcherClose)) {
881
+ return true;
882
+ }
883
+ break;
884
+ }
885
+ }
886
+ return false;
887
+ }
888
+ const NODE_ASSERT_METHODS = new Set([
889
+ "deepEqual",
890
+ "deepStrictEqual",
891
+ "doesNotMatch",
892
+ "doesNotReject",
893
+ "doesNotThrow",
894
+ "equal",
895
+ "fail",
896
+ "ifError",
897
+ "match",
898
+ "notDeepEqual",
899
+ "notDeepStrictEqual",
900
+ "notEqual",
901
+ "notStrictEqual",
902
+ "ok",
903
+ "rejects",
904
+ "strictEqual",
905
+ "throws",
906
+ ]);
907
+ function hasAddedNodeAssertion(stream) {
908
+ const assertCall = /\bassert(?:\s*\.\s*([A-Za-z_$][\w$]*))?\s*\(/g;
909
+ for (const match of stream.content.matchAll(assertCall)) {
910
+ const method = match[1];
911
+ if (method && !NODE_ASSERT_METHODS.has(method))
912
+ continue;
913
+ const start = match.index;
914
+ const openingIndex = stream.content.indexOf("(", start);
915
+ const closingIndex = findClosingParenthesis(stream.content, openingIndex);
916
+ if (closingIndex !== null &&
917
+ spanContainsMeaningfulAdded(stream.meaningfulAdded, start, closingIndex)) {
918
+ return true;
919
+ }
920
+ }
921
+ return false;
922
+ }
923
+ function hasNonSnapshotAssertion(file) {
924
+ if (!file.patch)
925
+ return false;
926
+ const stream = buildNewSideCharacterStream(file.patch);
927
+ return hasAddedExpectAssertion(stream) || hasAddedNodeAssertion(stream);
928
+ }
929
+ function evaluateTestEvidence(workType, body, classified, findings) {
930
+ const changedPaths = classified.allFiles.map((file) => file.filename);
931
+ const hasNonSnapshotTests = classified.nonSnapshotTestFiles.length > 0;
932
+ const hasSnapshotTests = classified.snapshotTestFiles.length > 0;
933
+ const noTestReason = hasNoTestReason(body);
934
+ if (workType === "docs") {
935
+ if (hasDocsVerification(body))
936
+ return "not_required";
937
+ findings.push(finding("medium", "MissingDocsVerification", "evidence", "Documentation changes do not include a reviewable verification method.", classified.docsFiles.map((file) => file.filename), "Docs-only work does not need code tests, but still needs Markdown, link, example, or command verification.", "Add a Verification or Validated section naming the command or manual documentation check performed."));
938
+ return "insufficient_evidence";
939
+ }
940
+ if (workType === "bugfix") {
941
+ const regressionTestPaths = classified.nonSnapshotTestFiles
942
+ .filter(hasNonSnapshotAssertion)
943
+ .map((file) => file.filename);
944
+ const hasRegressionAssertion = regressionTestPaths.length > 0;
945
+ if (!hasBugReproduction(body)) {
946
+ findings.push(finding("high", "MissingReproduction", "intent", "The bugfix does not include a concrete reproduction or before-state.", changedPaths, "A reviewer cannot confirm that the change addresses the reported failure without reproduction evidence.", "Add a Reproduction, Steps to reproduce, or Before section with the failing behavior."));
947
+ }
948
+ if (!hasRegressionAssertion) {
949
+ const hasUnavailableTestPatch = classified.nonSnapshotTestFiles.some((file) => addedPatchLines(file) === null);
950
+ findings.push(finding("high", "MissingRegressionTest", "evidence", "The bugfix does not include a non-snapshot regression test.", classified.testFiles.map((file) => file.filename), hasUnavailableTestPatch
951
+ ? "The changed test patch is unavailable, so a non-snapshot regression assertion cannot be verified."
952
+ : hasSnapshotTests || hasNonSnapshotTests
953
+ ? "Snapshot-only updates do not demonstrate the repaired behavior with a focused assertion."
954
+ : "No changed non-snapshot test protects the repaired behavior from regression.", "Add or update a focused unit or integration test that fails before the fix and passes after it."));
955
+ return hasSnapshotTests || hasNonSnapshotTests
956
+ ? "insufficient_evidence"
957
+ : "missing";
958
+ }
959
+ return "adequate";
960
+ }
961
+ if (hasNonSnapshotTests)
962
+ return "adequate";
963
+ if (noTestReason)
964
+ return "not_required";
965
+ findings.push(finding("high", "MissingTests", "evidence", "The change has no non-snapshot test evidence or qualified no-test explanation.", changedPaths, hasSnapshotTests
966
+ ? "Only snapshot evidence changed, which is insufficient for behavior coverage."
967
+ : "No changed test file demonstrates the new or preserved behavior.", "Add a focused unit/integration test, or include `No tests:` / `Testing not required:` followed by a specific reviewable reason."));
968
+ return hasSnapshotTests ? "insufficient_evidence" : "missing";
969
+ }
970
+ const SEMVER_SOURCE = "([0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?)";
971
+ function isReleaseVersionSource(filename) {
972
+ const lower = normalizePath(filename).toLowerCase();
973
+ const basename = lower.split("/").at(-1) ?? lower;
974
+ return (basename === "package.json" ||
975
+ basename === "server.json" ||
976
+ /(?:^|\/)version\.[cm]?[jt]s$/.test(lower));
977
+ }
978
+ function extractReleaseTargetVersions(title, body) {
979
+ const versions = [];
980
+ const hasReleaseTitleSemantics = /^\s*(?:(?:chore|build)\((?:release|publish)\)|(?:release|publish))(?:\s*:|\b)/i.test(title);
981
+ if (hasReleaseTitleSemantics) {
982
+ const titleVersions = new RegExp(`\\bv?${SEMVER_SOURCE}\\b`, "gi");
983
+ for (const match of title.matchAll(titleVersions)) {
984
+ if (match[1])
985
+ versions.push(match[1]);
986
+ }
987
+ }
988
+ const declaration = new RegExp(`^\\s*(?:[-*]\\s*)?(?:release target|target version|publish version|release version)\\s*:\\s*v?${SEMVER_SOURCE}\\s*$`, "gim");
989
+ for (const match of body.matchAll(declaration)) {
990
+ if (match[1])
991
+ versions.push(match[1]);
992
+ }
993
+ return versions;
994
+ }
995
+ function extractAddedReleaseVersion(file) {
996
+ const lines = addedPatchLines(file);
997
+ if (!lines)
998
+ return null;
999
+ const lower = file.filename.toLowerCase();
1000
+ const basename = lower.split("/").at(-1) ?? lower;
1001
+ const matcher = basename === "package.json" || basename === "server.json"
1002
+ ? new RegExp(`^[\\s]*["']version["']\\s*:\\s*["']v?${SEMVER_SOURCE}["']`, "i")
1003
+ : new RegExp(`\\b(?:server_info\\s*\\.\\s*)?(?:server_)?version\\b[^\\n]*?["'\`]v?${SEMVER_SOURCE}["'\`]`, "i");
1004
+ for (const line of lines) {
1005
+ const match = line.match(matcher);
1006
+ if (match?.[1])
1007
+ return match[1];
1008
+ }
1009
+ return null;
1010
+ }
1011
+ function addReleaseVersionFindings(title, body, classified, findings) {
1012
+ const versionFiles = classified.allFiles.filter((file) => isReleaseVersionSource(file.filename));
1013
+ const sources = versionFiles.map((file) => ({
1014
+ path: file.filename,
1015
+ version: extractAddedReleaseVersion(file),
1016
+ }));
1017
+ const unverifiable = sources.filter((source) => source.version === null);
1018
+ if (unverifiable.length > 0) {
1019
+ findings.push(finding("high", "UnverifiedReleaseVersion", "policy", "One or more changed release version sources have no verifiable added version.", unverifiable.map((source) => source.path), "A missing or truncated patch prevents the reviewer from confirming the version that will be published.", "Provide the complete patch and update the explicit package/server/runtime version field to the intended release target."));
1020
+ }
1021
+ const verified = sources.filter((source) => source.version !== null);
1022
+ const distinctVersions = new Set(verified.map((source) => source.version));
1023
+ if (distinctVersions.size > 1) {
1024
+ findings.push(finding("high", "InconsistentReleaseVersions", "policy", "Changed release version sources do not agree on one artifact version.", verified.map((source) => source.path), `The patch contains multiple release versions: ${[...distinctVersions].join(", ")}.`, "Align every package, server metadata, and runtime version source to the same semantic version."));
1025
+ }
1026
+ const targets = [...new Set(extractReleaseTargetVersions(title, body))];
1027
+ if (targets.length !== 1)
1028
+ return;
1029
+ const target = targets[0];
1030
+ if (!target)
1031
+ return;
1032
+ const mismatched = verified.filter((source) => source.version !== target);
1033
+ if (mismatched.length > 0) {
1034
+ findings.push(finding("high", "ReleaseVersionMismatch", "policy", `The changed release metadata does not match the declared target version ${target}.`, mismatched.map((source) => source.path), `The mismatched sources contain ${[...new Set(mismatched.map((source) => source.version))].join(", ")}.`, `Update these version sources to ${target}, or correct the declared release target before publishing.`));
1035
+ }
1036
+ }
1037
+ function addWorkTypeEvidenceFindings(workType, title, body, classified, findings) {
1038
+ const paths = classified.allFiles.map((file) => file.filename);
1039
+ if ((workType === "release" || workType === "infra") && !hasDocsVerification(body)) {
1040
+ findings.push(finding("high", "MissingOperationalVerification", "evidence", `${workType === "release" ? "Release" : "Infrastructure"} work lacks explicit verification evidence.`, paths, "Operational changes need a named command or validation procedure before merge.", "Add a Verification section with the command or environment validation performed."));
1041
+ }
1042
+ if ((workType === "release" || workType === "infra") && !hasFallback(body)) {
1043
+ findings.push(finding("high", "MissingFallback", "fallback", `${workType === "release" ? "Release" : "Infrastructure"} work lacks a detailed rollback or fallback.`, paths, "High-impact operational changes need an executable recovery path, not an empty heading.", "Add a Rollback, Fallback, or Revert section with concrete recovery steps."));
1044
+ }
1045
+ if (workType === "release") {
1046
+ const targets = [...new Set(extractReleaseTargetVersions(title, body))];
1047
+ if (targets.length === 0) {
1048
+ findings.push(finding("high", "MissingReleaseVersion", "policy", "Release work does not identify the version being published.", paths, "The version is required to compare source metadata, release configuration, and the intended artifact.", "Declare `Release target: x.y.z` in the PR body or name the release version explicitly in the title."));
1049
+ }
1050
+ else if (targets.length > 1) {
1051
+ findings.push(finding("high", "ConflictingReleaseTargets", "policy", "The PR declares more than one release target version.", paths, `Explicit release targets conflict: ${targets.join(", ")}.`, "Choose one release target and align the PR title, body declaration, and changed version sources."));
1052
+ }
1053
+ addReleaseVersionFindings(title, body, classified, findings);
1054
+ }
1055
+ if (workType === "infra" && classified.workflowFiles.length > 0) {
1056
+ if (!/\b(?:pull_request|push|schedule|trigger(?:ed|s)?|workflow_dispatch)\b|\bon\s*:/i.test(body)) {
1057
+ findings.push(finding("high", "MissingWorkflowTrigger", "policy", "Workflow work does not document the intended trigger conditions.", classified.workflowFiles.map((file) => file.filename), "A reviewer cannot determine when the changed automation will run.", "Describe the exact events, branches, paths, or schedules that should trigger the workflow."));
1058
+ }
1059
+ if (!/\b(?:error path|fail(?:ed|s|ure)?|timeout|cancelled|canceled)\b/i.test(body)) {
1060
+ findings.push(finding("high", "MissingWorkflowFailurePath", "fallback", "Workflow work does not describe failure behavior.", classified.workflowFiles.map((file) => file.filename), "Operational automation needs an explicit failure path so partial or stalled execution is reviewable.", "Describe failure, timeout, and cancellation behavior and how an operator should recover."));
1061
+ }
1062
+ }
1063
+ if (workType === "security") {
1064
+ const requirements = [
1065
+ [/\b(?:threat|attack|vulnerability|risk)\b/i, "MissingThreatAnalysis", "threat or risk"],
1066
+ [/\b(?:access|authorization|permission|privilege)\b/i, "MissingPermissionAnalysis", "permission impact"],
1067
+ [/\b(?:credential|key|secret|token)\b/i, "MissingSecretAnalysis", "credential and secret handling"],
1068
+ ];
1069
+ for (const [pattern, category, subject] of requirements) {
1070
+ if (pattern.test(body))
1071
+ continue;
1072
+ findings.push(finding("high", category, "security", `Security work does not document ${subject}.`, paths, `The approved security review standard requires an explicit ${subject} assessment.`, `Document the ${subject} and the evidence used to validate it.`));
1073
+ }
1074
+ if (!hasSecurityValidation(body)) {
1075
+ findings.push(finding("high", "MissingSecurityValidation", "security", "Security work does not describe security-specific validation.", paths, "General test files do not prove that the identified threat or permission boundary was validated.", "Document a security verification method such as a focused abuse-case test, CodeQL/SAST result, audit, or threat-model validation."));
1076
+ }
1077
+ }
1078
+ }
1079
+ function addSecurityFocusedFindings(classified, findings) {
1080
+ if (classified.envFiles.length > 0) {
1081
+ findings.push(finding("critical", "EnvironmentFileChanged", "security", "An environment configuration file is included in the change.", classified.envFiles.map((file) => file.filename), "Environment files can contain deploy-time credentials or private configuration.", "Confirm no real secret is present, keep runtime environment files ignored, and rotate any exposed credential."));
1082
+ }
1083
+ if (classified.lockFiles.length > 0) {
1084
+ findings.push(finding("medium", "LockfileChanged", "security", "A dependency lockfile changed.", classified.lockFiles.map((file) => file.filename), "Dependency resolution changed and may alter the shipped software supply chain.", "Review the dependency diff and run the ecosystem's vulnerability audit before release."));
1085
+ }
1086
+ if (classified.generatedFiles.length > 0) {
1087
+ findings.push(finding("medium", "GeneratedArtifactChanged", "scope", "Generated or built artifacts are included in the change.", classified.generatedFiles.map((file) => file.filename), "Generated output is harder to review and can conceal behavior not evident in source changes.", "Verify the artifacts are intentionally versioned and reproducible from reviewed source."));
1088
+ }
1089
+ }
1090
+ function addSecretScannerEvidenceFinding(evidence, findings) {
1091
+ const issue = secretScannerPolicyFinding(evidence);
1092
+ if (!issue)
1093
+ return;
1094
+ findings.push(finding(issue.severity, issue.category, "security", issue.description, [], issue.reason, issue.suggestion));
1095
+ }
1096
+ function addStrictFindings(classified, totalChangedLines, findings) {
1097
+ if (totalChangedLines <= 800)
1098
+ return;
1099
+ findings.push(finding("medium", "LargeChangeScope", "scope", `The PR changes ${totalChangedLines} lines, which is difficult to review as one unit.`, classified.allFiles.map((file) => file.filename), "Large diffs increase the chance that intent, tests, or security-sensitive details are missed during review.", "Split independent concerns into smaller PRs, or document why this change must remain atomic."));
1100
+ }
1101
+ function calculateReleaseRisk(findings, classified) {
1102
+ if (findings.some((item) => item.severity === "critical"))
1103
+ return "critical";
1104
+ if (findings.some((item) => item.severity === "high") ||
1105
+ classified.workflowFiles.length > 0 ||
1106
+ classified.authSecurityFiles.length > 0 ||
1107
+ classified.releaseFiles.length > 0 ||
1108
+ classified.lockFiles.length > 0) {
1109
+ return "high";
1110
+ }
1111
+ if (findings.some((item) => item.severity === "medium"))
1112
+ return "moderate";
1113
+ return "low";
1114
+ }
1115
+ function calculateConclusion(findings) {
1116
+ if (findings.some((item) => item.severity === "critical" || item.severity === "high")) {
1117
+ return "needs_changes";
1118
+ }
1119
+ if (findings.some((item) => item.severity === "medium"))
1120
+ return "risky_but_acceptable";
1121
+ return "pass";
1122
+ }
1123
+ function sortFindings(findings) {
1124
+ return [...findings].sort((left, right) => SEVERITY_ORDER.indexOf(left.severity) - SEVERITY_ORDER.indexOf(right.severity));
1125
+ }
1126
+ export function evaluatePullRequestReview(input) {
1127
+ const classified = classifyPrFiles(input.files);
1128
+ const inferred = inferWorkType(input.pr, classified.allFiles);
1129
+ const workType = input.workType ?? inferred.workType;
1130
+ const workTypeConfidence = input.workType ? "high" : inferred.confidence;
1131
+ const workTypeReasoning = input.workType
1132
+ ? `The caller explicitly selected the ${input.workType} work type.`
1133
+ : inferred.reasoning;
1134
+ const body = input.pr.body ?? "";
1135
+ const findings = [...(input.policyFindings ?? [])];
1136
+ const standard = input.standard ?? "basic";
1137
+ const suppliedSecretScannerEvidence = input.secretScannerEvidence ??
1138
+ unverifiedSecretScannerEvidence("The security-focused review did not receive CI evidence from a mature secret scanner.");
1139
+ const scannerPolicyChanged = classified.allFiles.some((file) => isSecretScannerPolicyPath(file.filename) ||
1140
+ (file.previousFilename !== undefined &&
1141
+ isSecretScannerPolicyPath(file.previousFilename)));
1142
+ const effectiveSecretScannerEvidence = suppliedSecretScannerEvidence.status === "passing" && scannerPolicyChanged
1143
+ ? {
1144
+ ...unverifiedSecretScannerEvidence("The PR changes secret-scanner workflow or configuration policy, so its supplied passing evidence is not trusted."),
1145
+ providers: suppliedSecretScannerEvidence.providers,
1146
+ signals: suppliedSecretScannerEvidence.signals,
1147
+ }
1148
+ : suppliedSecretScannerEvidence;
1149
+ const totalChangedLines = classified.allFiles.reduce((total, file) => total + (file.changes ?? (file.additions ?? 0) + (file.deletions ?? 0)), 0);
1150
+ if (input.pr.draft) {
1151
+ findings.push(finding("info", "Status", "scope", "PR is still marked as a draft.", [], "Draft status indicates that the author has not yet declared the change ready for final review.", "Mark the PR as ready for review when the implementation and evidence are complete."));
1152
+ }
1153
+ if (input.pr.commits > 20) {
1154
+ findings.push(finding("low", "Hygiene", "scope", `PR has ${input.pr.commits} commits -- consider squashing for cleaner history.`, [], "A very large commit count makes review history and later investigation harder to follow.", "Squash closely related fixup commits while preserving meaningful reviewable milestones."));
1155
+ }
1156
+ if (body.trim().length < 20) {
1157
+ findings.push(finding("high", "MissingIntent", "intent", "The PR description does not provide enough intent for review.", [], "A short or empty body does not explain why the change is needed or how it should be evaluated.", "Explain the problem, intended outcome, and relevant constraints in the PR description."));
1158
+ }
1159
+ const testCoverageSignal = evaluateTestEvidence(workType, body, classified, findings);
1160
+ addWorkTypeEvidenceFindings(workType, input.pr.title, body, classified, findings);
1161
+ for (const file of classified.allFiles) {
1162
+ findings.push(...scanPatchForSecrets(file.filename, file.patch));
1163
+ }
1164
+ if (standard === "strict" || standard === "security-focused") {
1165
+ addStrictFindings(classified, totalChangedLines, findings);
1166
+ }
1167
+ if (standard === "security-focused") {
1168
+ addSecretScannerEvidenceFinding(effectiveSecretScannerEvidence, findings);
1169
+ addSecurityFocusedFindings(classified, findings);
1170
+ }
1171
+ const sortedFindings = sortFindings(findings);
1172
+ return {
1173
+ workType,
1174
+ workTypeConfidence,
1175
+ workTypeReasoning,
1176
+ findings: sortedFindings,
1177
+ releaseRisk: calculateReleaseRisk(sortedFindings, classified),
1178
+ testCoverageSignal,
1179
+ conclusion: calculateConclusion(sortedFindings),
1180
+ hasTests: classified.testFiles.length > 0,
1181
+ totalChangedLines,
1182
+ secretScannerEvidence: standard === "security-focused" ? effectiveSecretScannerEvidence : null,
1183
+ };
1184
+ }
1185
+ //# sourceMappingURL=pull-request-review.js.map