agentic-sdlc-mcp 1.4.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 (64) hide show
  1. package/README.md +32 -9
  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/context.d.ts +7 -1
  10. package/dist/github/context.d.ts.map +1 -1
  11. package/dist/github/context.js +69 -9
  12. package/dist/github/context.js.map +1 -1
  13. package/dist/github/pull-request-evidence.d.ts +123 -0
  14. package/dist/github/pull-request-evidence.d.ts.map +1 -0
  15. package/dist/github/pull-request-evidence.js +590 -0
  16. package/dist/github/pull-request-evidence.js.map +1 -0
  17. package/dist/index.js +2 -4
  18. package/dist/index.js.map +1 -1
  19. package/dist/rendering/markdown.d.ts +8 -0
  20. package/dist/rendering/markdown.d.ts.map +1 -0
  21. package/dist/rendering/markdown.js +27 -0
  22. package/dist/rendering/markdown.js.map +1 -0
  23. package/dist/review/pull-request-review.d.ts +77 -0
  24. package/dist/review/pull-request-review.d.ts.map +1 -0
  25. package/dist/review/pull-request-review.js +1185 -0
  26. package/dist/review/pull-request-review.js.map +1 -0
  27. package/dist/security/secret-scanner-evidence.d.ts +58 -0
  28. package/dist/security/secret-scanner-evidence.d.ts.map +1 -0
  29. package/dist/security/secret-scanner-evidence.js +414 -0
  30. package/dist/security/secret-scanner-evidence.js.map +1 -0
  31. package/dist/tools/create-issue-set.d.ts +46 -0
  32. package/dist/tools/create-issue-set.d.ts.map +1 -1
  33. package/dist/tools/create-issue-set.js +175 -22
  34. package/dist/tools/create-issue-set.js.map +1 -1
  35. package/dist/tools/plan-from-context.d.ts +24 -2
  36. package/dist/tools/plan-from-context.d.ts.map +1 -1
  37. package/dist/tools/plan-from-context.js +198 -59
  38. package/dist/tools/plan-from-context.js.map +1 -1
  39. package/dist/tools/quality-gate-status.d.ts +292 -5
  40. package/dist/tools/quality-gate-status.d.ts.map +1 -1
  41. package/dist/tools/quality-gate-status.js +665 -95
  42. package/dist/tools/quality-gate-status.js.map +1 -1
  43. package/dist/tools/release-readiness.d.ts.map +1 -1
  44. package/dist/tools/release-readiness.js +81 -39
  45. package/dist/tools/release-readiness.js.map +1 -1
  46. package/dist/tools/repo-context.d.ts +2 -0
  47. package/dist/tools/repo-context.d.ts.map +1 -1
  48. package/dist/tools/repo-context.js +16 -3
  49. package/dist/tools/repo-context.js.map +1 -1
  50. package/dist/tools/review-pr.d.ts +113 -29
  51. package/dist/tools/review-pr.d.ts.map +1 -1
  52. package/dist/tools/review-pr.js +237 -314
  53. package/dist/tools/review-pr.js.map +1 -1
  54. package/dist/tools/workflow-permissions-audit.d.ts +14 -1
  55. package/dist/tools/workflow-permissions-audit.d.ts.map +1 -1
  56. package/dist/tools/workflow-permissions-audit.js +40 -15
  57. package/dist/tools/workflow-permissions-audit.js.map +1 -1
  58. package/dist/types.d.ts +20 -0
  59. package/dist/types.d.ts.map +1 -1
  60. package/dist/version.d.ts +5 -0
  61. package/dist/version.d.ts.map +1 -0
  62. package/dist/version.js +5 -0
  63. package/dist/version.js.map +1 -0
  64. package/package.json +1 -1
@@ -5,7 +5,14 @@
5
5
  * security-focused mode inspects actual patch lines for suspicious patterns.
6
6
  */
7
7
  import { z } from "zod";
8
- import { resolveRepo, getOctokit, paginateAll, handleGitHubError } from "../github/client.js";
8
+ import { resolveRepo, getOctokit, handleGitHubError } from "../github/client.js";
9
+ import { collectPullRequestEvidence } from "../github/pull-request-evidence.js";
10
+ import { findOwnershipGaps, } from "../github/codeowners.js";
11
+ import { evaluateSecretScannerEvidence, isSecretScannerPolicyPath, verifySecretScannerProvenance, } from "../security/secret-scanner-evidence.js";
12
+ import { evaluatePullRequestReview, scanPatchForSecrets as scanSharedPatchForSecrets, } from "../review/pull-request-review.js";
13
+ import { evaluateWorkflowContents, MAX_WORKFLOW_FILES, } from "./workflow-permissions-audit.js";
14
+ import { safeMarkdownInline } from "../rendering/markdown.js";
15
+ export { codeownersPatternMatches, fetchCodeownersRules, ownersForFile, parseCodeowners, } from "../github/codeowners.js";
9
16
  // ---------------------------------------------------------------------------
10
17
  // Schema
11
18
  // ---------------------------------------------------------------------------
@@ -17,6 +24,10 @@ export const ReviewPrInputSchema = z.object({
17
24
  .enum(["basic", "strict", "security-focused"])
18
25
  .default("basic")
19
26
  .describe("Review standard: 'basic', 'strict', or 'security-focused'."),
27
+ workType: z
28
+ .enum(["docs", "feature", "bugfix", "refactor", "security", "release", "infra"])
29
+ .optional()
30
+ .describe("Optional explicit work type. When omitted, it is inferred from PR metadata and paths."),
20
31
  checkOwnership: z
21
32
  .boolean()
22
33
  .default(true)
@@ -34,12 +45,52 @@ export const ReviewPrOutputSchema = {
34
45
  severity: z.enum(["critical", "high", "medium", "low", "info"]),
35
46
  category: z.string(),
36
47
  description: z.string(),
37
- suggestion: z.string().optional(),
48
+ suggestion: z.string(),
49
+ dimension: z.enum(["intent", "scope", "evidence", "ownership", "policy", "fallback", "security"]),
50
+ paths: z.array(z.string()),
51
+ reason: z.string(),
38
52
  })),
39
53
  hasTests: z.boolean(),
40
54
  totalChangedLines: z.number().int(),
41
55
  codeownersFound: z.boolean(),
56
+ workType: z.enum(["docs", "feature", "bugfix", "refactor", "security", "release", "infra"]),
57
+ workTypeConfidence: z.enum(["high", "medium", "low"]),
58
+ workTypeReasoning: z.string(),
59
+ releaseRisk: z.enum(["low", "moderate", "high", "critical"]),
60
+ testCoverageSignal: z.enum(["adequate", "missing", "not_required", "insufficient_evidence"]),
61
+ ownershipRoutingGaps: z.array(z.object({ owner: z.string(), paths: z.array(z.string()) })),
42
62
  errors: z.array(z.string()),
63
+ secretScannerEvidence: z
64
+ .object({
65
+ status: z.enum(["passing", "failing", "pending", "unverified"]),
66
+ verified: z.boolean(),
67
+ degraded: z.boolean(),
68
+ providers: z.array(z.enum([
69
+ "gitleaks",
70
+ "trufflehog",
71
+ "secretlint",
72
+ "detect-secrets",
73
+ "github-secret-scanning",
74
+ ])),
75
+ signals: z.array(z.object({
76
+ name: z.string(),
77
+ provider: z.enum([
78
+ "gitleaks",
79
+ "trufflehog",
80
+ "secretlint",
81
+ "detect-secrets",
82
+ "github-secret-scanning",
83
+ ]),
84
+ source: z.enum(["check_run", "commit_status"]),
85
+ appId: z.number().int().nullable(),
86
+ trusted: z.boolean(),
87
+ provenanceVerified: z.boolean(),
88
+ state: z.enum(["passing", "failing", "pending", "skipped"]),
89
+ url: z.string().nullable(),
90
+ })),
91
+ reason: z.string(),
92
+ })
93
+ .nullable(),
43
94
  };
44
95
  // ---------------------------------------------------------------------------
45
96
  // Pure helpers (exported for testing)
@@ -59,36 +110,16 @@ export function severityIcon(s) {
59
110
  return icons[s] ?? "⚪";
60
111
  }
61
112
  /**
62
- * Secret-like patterns to flag in added patch lines (conservative).
63
- * Only matches lines that look like an assignment, not just the word.
113
+ * Backward-compatible wrapper around the shared heuristic scanner.
114
+ * Mature scanner evidence is evaluated separately from CI check runs.
64
115
  */
65
- const SUSPICIOUS_PATTERNS = [
66
- { name: "hardcoded password assignment", pattern: /password\s*[:=]\s*['"`][^'"`\s]{6,}/i },
67
- { name: "hardcoded API key assignment", pattern: /api[_-]?key\s*[:=]\s*['"`][^'"`\s]{6,}/i },
68
- { name: "hardcoded secret assignment", pattern: /secret\s*[:=]\s*['"`][^'"`\s]{6,}/i },
69
- { name: "hardcoded token assignment", pattern: /token\s*[:=]\s*['"`][^'"`\s]{6,}/i },
70
- { name: "AWS access key ID pattern", pattern: /AKIA[0-9A-Z]{16}/ },
71
- ];
72
- /** Check added lines in a patch for suspicious secret-like patterns. */
73
116
  export function scanPatchForSecrets(filename, patch) {
74
- if (!patch)
75
- return [];
76
- const findings = [];
77
- const addedLines = patch.split("\n").filter((l) => l.startsWith("+") && !l.startsWith("+++"));
78
- for (const line of addedLines) {
79
- for (const { name, pattern } of SUSPICIOUS_PATTERNS) {
80
- if (pattern.test(line)) {
81
- findings.push({
82
- severity: "high",
83
- category: "Security",
84
- description: `Possible ${name} in \`${filename}\` -- needs manual review.`,
85
- suggestion: "If this is a real credential, rotate it immediately and use an environment variable instead.",
86
- });
87
- break; // one finding per line is enough
88
- }
89
- }
90
- }
91
- return findings;
117
+ return scanSharedPatchForSecrets(filename, patch).map((item) => ({
118
+ severity: item.severity,
119
+ category: "Security",
120
+ description: item.description,
121
+ suggestion: item.suggestion,
122
+ }));
92
123
  }
93
124
  /**
94
125
  * Classify PR files into categories.
@@ -251,320 +282,212 @@ export function generateFindings(pr, files, standard) {
251
282
  return findings;
252
283
  }
253
284
  // ---------------------------------------------------------------------------
254
- // CODEOWNERS parsing and ownership findings (pure, exported for testing)
285
+ // CODEOWNERS finding presentation
255
286
  // ---------------------------------------------------------------------------
256
- /** Parse a CODEOWNERS file's contents into ordered rules (file order matters -- last match wins). */
257
- export function parseCodeowners(content) {
258
- const rules = [];
259
- for (const rawLine of content.split("\n")) {
260
- const line = rawLine.trim();
261
- if (!line || line.startsWith("#"))
262
- continue;
263
- const [pattern, ...owners] = line.split(/\s+/);
264
- if (!pattern || owners.length === 0)
265
- continue; // patterns with no owners unset ownership; not tracked here
266
- rules.push({ pattern, owners });
267
- }
268
- return rules;
269
- }
270
- /**
271
- * Match a single path segment against a pattern segment containing `*` (any run of chars)
272
- * and/or `?` (exactly one char). Implemented as a rolling dynamic-programming pass rather
273
- * than a compiled RegExp so adjacent wildcards (e.g. many `*a*a*a...` segments) can never
274
- * trigger catastrophic backtracking -- this is always O(pattern.length * text.length).
275
- */
276
- function segmentMatches(pattern, text) {
277
- const m = pattern.length;
278
- const n = text.length;
279
- let prevRow = new Array(n + 1).fill(false);
280
- prevRow[0] = true;
281
- for (let i = 1; i <= m; i++) {
282
- const currRow = new Array(n + 1).fill(false);
283
- const c = pattern[i - 1];
284
- currRow[0] = c === "*" && prevRow[0];
285
- for (let j = 1; j <= n; j++) {
286
- if (c === "*") {
287
- currRow[j] = prevRow[j] || currRow[j - 1];
288
- }
289
- else if (c === "?" || c === text[j - 1]) {
290
- currRow[j] = prevRow[j - 1];
291
- }
292
- }
293
- prevRow = currRow;
294
- }
295
- return prevRow[n];
296
- }
297
- /**
298
- * Match a full path (split into `/`-separated segments) against pattern segments, where a
299
- * `**` segment matches zero or more whole path segments (including zero, per gitignore semantics).
300
- * Memoized on (pi, si): without this, patterns with many `**` segments against a repetitive path
301
- * cause the same subproblems to be recomputed exponentially -- the recursion re-derives the
302
- * classic ReDoS blowup in hand-rolled form even though no RegExp is involved. Memoizing keeps this
303
- * at O(patternSegs.length * pathSegs.length) subproblems, each doing at most O(pathSegs.length) work.
304
- */
305
- function matchSegments(patternSegs, pathSegs, pi = 0, si = 0, memo = new Map()) {
306
- const key = pi * (pathSegs.length + 1) + si;
307
- const cached = memo.get(key);
308
- if (cached !== undefined)
309
- return cached;
310
- let result;
311
- if (pi >= patternSegs.length) {
312
- result = si === pathSegs.length;
313
- }
314
- else if (patternSegs[pi] === "**") {
315
- if (pi === patternSegs.length - 1) {
316
- result = true;
317
- }
318
- else {
319
- result = false;
320
- for (let k = si; k <= pathSegs.length; k++) {
321
- if (matchSegments(patternSegs, pathSegs, pi + 1, k, memo)) {
322
- result = true;
323
- break;
324
- }
325
- }
326
- }
327
- }
328
- else if (si >= pathSegs.length || !segmentMatches(patternSegs[pi], pathSegs[si])) {
329
- result = false;
330
- }
331
- else {
332
- result = matchSegments(patternSegs, pathSegs, pi + 1, si + 1, memo);
333
- }
334
- memo.set(key, result);
335
- return result;
336
- }
337
- /** A pattern matches a path either exactly, or as a directory prefix (everything nested below it). */
338
- function matchesAnchored(patternSegs, pathSegs) {
339
- if (matchSegments(patternSegs, pathSegs))
340
- return true;
341
- return (pathSegs.length > patternSegs.length &&
342
- patternSegs[patternSegs.length - 1] !== "**" &&
343
- matchSegments(patternSegs, pathSegs.slice(0, patternSegs.length)));
287
+ function ownershipGapsToFindings(gaps) {
288
+ return gaps.map(({ owner, paths }) => ({
289
+ severity: "medium",
290
+ category: "Ownership",
291
+ description: `CODEOWNERS owner ${owner} was not requested as a reviewer and has not reviewed changes to: ${paths.join(", ")}.`,
292
+ suggestion: `Request a review from ${owner}, or confirm CODEOWNERS routing is still correct for these paths.`,
293
+ }));
344
294
  }
345
295
  /**
346
- * Match a repo-relative file path against a single CODEOWNERS/gitignore-style pattern.
347
- * Handles rooted (`/path/`) vs unrooted patterns, `*`/`?`/`**` wildcards, and directory-prefix
348
- * matching (a pattern matching a directory also matches everything nested under it).
296
+ * @deprecated Import `findOwnershipGaps` from `../github/codeowners.js` for shared routing logic.
349
297
  */
350
- export function codeownersPatternMatches(pattern, filePath) {
351
- let p = pattern.trim();
352
- if (p.endsWith("/"))
353
- p = p.slice(0, -1);
354
- const anchored = p.includes("/");
355
- if (p.startsWith("/"))
356
- p = p.slice(1);
357
- const patternSegs = p.split("/");
358
- const pathSegs = filePath.split("/");
359
- if (anchored)
360
- return matchesAnchored(patternSegs, pathSegs);
361
- for (let start = 0; start < pathSegs.length; start++) {
362
- if (matchesAnchored(patternSegs, pathSegs.slice(start)))
363
- return true;
364
- }
365
- return false;
298
+ export function generateOwnershipFindings(files, rules, requestedUsers, requestedTeams, reviewedUsers, prAuthor) {
299
+ return ownershipGapsToFindings(findOwnershipGaps(files.map((file) => file.filename), rules, requestedUsers, requestedTeams, reviewedUsers, prAuthor));
366
300
  }
367
- /** Owners for a file, per CODEOWNERS semantics: rules are evaluated in order, last match wins. */
368
- export function ownersForFile(filePath, rules) {
369
- let matched = [];
370
- for (const rule of rules) {
371
- if (codeownersPatternMatches(rule.pattern, filePath)) {
372
- matched = rule.owners;
301
+ // ---------------------------------------------------------------------------
302
+ // Core handler (exported for testing)
303
+ // ---------------------------------------------------------------------------
304
+ export async function handleReviewPr(params, ref, octokit) {
305
+ const evidence = await collectPullRequestEvidence({ pullNumber: params.pullNumber }, ref, octokit);
306
+ const files = evidence.changedFiles;
307
+ const errors = evidence.errors.map((error) => {
308
+ if (error.startsWith("requested_reviewers:")) {
309
+ return `Requested reviewers:${error.slice("requested_reviewers:".length)}`;
373
310
  }
374
- }
375
- return matched;
376
- }
377
- /**
378
- * Flag CODEOWNERS owners whose files changed but who were neither requested as reviewers,
379
- * nor have already reviewed, nor are the PR author. Pure function -- no I/O.
380
- */
381
- export function generateOwnershipFindings(files, rules, requestedUsers, requestedTeams, reviewedUsers, prAuthor) {
382
- if (rules.length === 0)
383
- return [];
384
- const satisfied = new Set([...requestedUsers, ...requestedTeams, ...reviewedUsers, prAuthor].map((u) => u.toLowerCase()));
385
- const missingOwnerFiles = new Map();
386
- for (const file of files) {
387
- for (const owner of ownersForFile(file.filename, rules)) {
388
- const normalized = owner.replace(/^@/, "").toLowerCase();
389
- if (satisfied.has(normalized))
390
- continue;
391
- const list = missingOwnerFiles.get(owner) ?? [];
392
- list.push(file.filename);
393
- missingOwnerFiles.set(owner, list);
311
+ if (error.startsWith("reviews:"))
312
+ return `Reviews:${error.slice("reviews:".length)}`;
313
+ if (error.startsWith("codeowners:"))
314
+ return `CODEOWNERS:${error.slice("codeowners:".length)}`;
315
+ if (params.standard === "security-focused" &&
316
+ (error.startsWith("check_runs:") || error.startsWith("commit_statuses:"))) {
317
+ return `Secret scanner CI: ${error}`;
394
318
  }
319
+ return error;
320
+ });
321
+ const workflowContents = [];
322
+ const unverifiedWorkflowPaths = [];
323
+ const changedWorkflows = files.filter((file) => file.status !== "removed" &&
324
+ /^\.github\/workflows\/[^/]+\.ya?ml$/i.test(file.filename));
325
+ if (changedWorkflows.length > MAX_WORKFLOW_FILES) {
326
+ errors.push(`Workflow permissions: only the first ${MAX_WORKFLOW_FILES} of ${changedWorkflows.length} changed workflows were audited.`);
327
+ unverifiedWorkflowPaths.push(...changedWorkflows.slice(MAX_WORKFLOW_FILES).map((file) => file.filename));
395
328
  }
396
- const findings = [];
397
- for (const [owner, filenames] of missingOwnerFiles) {
398
- findings.push({
399
- severity: "medium",
400
- category: "Ownership",
401
- description: `CODEOWNERS owner ${owner} was not requested as a reviewer and has not reviewed changes to: ${filenames.join(", ")}.`,
402
- suggestion: `Request a review from ${owner}, or confirm CODEOWNERS routing is still correct for these paths.`,
403
- });
404
- }
405
- return findings;
406
- }
407
- /**
408
- * Fetch and parse the repo's CODEOWNERS file, trying the conventional candidate paths in order.
409
- * A 404 on a candidate is normal (file lives elsewhere or doesn't exist) and tries the next path;
410
- * any other error (e.g. permissions) short-circuits and is reported back to the caller.
411
- */
412
- export async function fetchCodeownersRules(ref, octokit) {
413
- const candidatePaths = [".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS"];
414
- let lastError = null;
415
- for (const path of candidatePaths) {
329
+ for (const file of changedWorkflows.slice(0, MAX_WORKFLOW_FILES)) {
416
330
  try {
417
- const { data } = await octokit.repos.getContent({ owner: ref.owner, repo: ref.repo, path });
418
- if (!Array.isArray(data) && data.type === "file" && data.content) {
419
- const content = Buffer.from(data.content, "base64").toString("utf-8");
420
- return { rules: parseCodeowners(content), error: null };
331
+ const { data } = await octokit.repos.getContent({
332
+ owner: ref.owner,
333
+ repo: ref.repo,
334
+ path: file.filename,
335
+ ref: evidence.pullRequest.headSha,
336
+ });
337
+ if (Array.isArray(data) || data.type !== "file" || !data.content) {
338
+ errors.push(`Workflow permissions: ${file.filename}: unexpected content response.`);
339
+ unverifiedWorkflowPaths.push(file.filename);
340
+ continue;
421
341
  }
342
+ workflowContents.push({
343
+ filename: file.filename,
344
+ content: Buffer.from(data.content, "base64").toString("utf-8"),
345
+ });
422
346
  }
423
- catch (err) {
424
- const message = handleGitHubError(err);
425
- if (!message.toLowerCase().includes("not found")) {
426
- lastError = message;
427
- }
347
+ catch (error) {
348
+ errors.push(`Workflow permissions: ${file.filename}: ${handleGitHubError(error)}`);
349
+ unverifiedWorkflowPaths.push(file.filename);
428
350
  }
429
351
  }
430
- return { rules: [], error: lastError };
431
- }
432
- // ---------------------------------------------------------------------------
433
- // Core handler (exported for testing)
434
- // ---------------------------------------------------------------------------
435
- export async function handleReviewPr(params, ref, octokit) {
436
- const { data: pr } = await octokit.pulls.get({
437
- owner: ref.owner,
438
- repo: ref.repo,
439
- pull_number: params.pullNumber,
440
- });
441
- const rawFiles = await paginateAll((page, perPage) => octokit.pulls
442
- .listFiles({
443
- owner: ref.owner,
444
- repo: ref.repo,
445
- pull_number: params.pullNumber,
446
- per_page: perPage,
447
- page,
448
- })
449
- .then((r) => r.data), 300);
450
- const files = rawFiles.map((f) => ({
451
- filename: f.filename,
452
- status: f.status,
453
- additions: f.additions,
454
- deletions: f.deletions,
455
- patch: f.patch,
352
+ const workflowEvaluation = evaluateWorkflowContents(workflowContents);
353
+ errors.push(...workflowEvaluation.errors.map((error) => `Workflow permissions: ${error}`));
354
+ const scannedWorkflows = new Set(workflowEvaluation.workflowsScanned);
355
+ unverifiedWorkflowPaths.push(...workflowContents
356
+ .filter((workflow) => !scannedWorkflows.has(workflow.filename))
357
+ .map((workflow) => workflow.filename));
358
+ const ownershipRoutingGaps = params.checkOwnership ? evidence.reviews.ownershipGaps : [];
359
+ const ownershipPolicyFindings = ownershipRoutingGaps.map(({ owner, paths }) => ({
360
+ severity: "medium",
361
+ category: "Ownership",
362
+ description: `CODEOWNERS owner ${owner} was not requested as a reviewer and has not reviewed changes to: ${paths.join(", ")}.`,
363
+ suggestion: `Request a review from ${owner}, or confirm CODEOWNERS routing is still correct for these paths.`,
364
+ dimension: "ownership",
365
+ paths,
366
+ reason: "The shared PR evidence layer found an unsatisfied CODEOWNERS routing requirement.",
456
367
  }));
457
- const prMeta = {
458
- number: pr.number,
459
- title: pr.title,
460
- body: pr.body ?? null,
461
- draft: pr.draft ?? false,
462
- commits: pr.commits,
463
- author: pr.user?.login ?? "",
464
- };
465
- const errors = [];
466
- let codeownersFound = false;
467
- let ownershipFindings = [];
468
- if (params.checkOwnership) {
469
- const { rules, error: codeownersError } = await fetchCodeownersRules(ref, octokit);
470
- if (codeownersError)
471
- errors.push(`CODEOWNERS: ${codeownersError}`);
472
- codeownersFound = rules.length > 0;
473
- if (rules.length > 0) {
474
- let requestedUsers = [];
475
- let requestedTeams = [];
476
- try {
477
- const { data: reviewers } = await octokit.pulls.listRequestedReviewers({
478
- owner: ref.owner,
479
- repo: ref.repo,
480
- pull_number: params.pullNumber,
481
- });
482
- requestedUsers = reviewers.users?.map((u) => u.login) ?? [];
483
- requestedTeams = reviewers.teams?.map((t) => `${ref.owner}/${t.slug}`) ?? [];
484
- }
485
- catch (err) {
486
- errors.push(`Requested reviewers: ${handleGitHubError(err)}`);
487
- }
488
- let reviewedUsers = [];
489
- try {
490
- const rawReviews = await paginateAll((page, perPage) => octokit.pulls
491
- .listReviews({
492
- owner: ref.owner,
493
- repo: ref.repo,
494
- pull_number: params.pullNumber,
495
- per_page: perPage,
496
- page,
497
- })
498
- .then((r) => r.data), 300);
499
- reviewedUsers = rawReviews
500
- .map((r) => r.user?.login)
501
- .filter((login) => Boolean(login));
502
- }
503
- catch (err) {
504
- errors.push(`Reviews: ${handleGitHubError(err)}`);
505
- }
506
- ownershipFindings = generateOwnershipFindings(files, rules, requestedUsers, requestedTeams, reviewedUsers, prMeta.author);
507
- }
368
+ const workflowPolicyFindings = workflowEvaluation.findings.map((finding) => {
369
+ const workflow = workflowContents.find((item) => finding.description.startsWith(`${item.filename}:`));
370
+ return {
371
+ ...finding,
372
+ suggestion: finding.suggestion ?? "Review and reduce the workflow token permissions.",
373
+ dimension: "policy",
374
+ paths: workflow ? [workflow.filename] : [],
375
+ reason: "The finding was derived from the complete workflow content at the PR head SHA.",
376
+ };
377
+ });
378
+ const uniqueUnverifiedWorkflowPaths = [...new Set(unverifiedWorkflowPaths)];
379
+ if (uniqueUnverifiedWorkflowPaths.length > 0) {
380
+ workflowPolicyFindings.push({
381
+ severity: "high",
382
+ category: "WorkflowPolicyEvidenceUnavailable",
383
+ description: "Complete workflow permission evidence could not be verified for every changed workflow.",
384
+ suggestion: "Restore repository content access and provide parseable complete workflow files at the PR head SHA before merge.",
385
+ dimension: "policy",
386
+ paths: uniqueUnverifiedWorkflowPaths,
387
+ reason: "Fetching, parsing, or the bounded workflow audit failed, so least-privilege policy cannot be confirmed.",
388
+ });
508
389
  }
509
- const rawFindings = [...generateFindings(prMeta, files, params.standard), ...ownershipFindings];
510
- const sorted = sortFindings(rawFindings);
511
- const hasTests = files.some((f) => f.filename.includes("/test") ||
512
- f.filename.includes("/spec") ||
513
- f.filename.includes("__tests__") ||
514
- /\.(test|spec)\.[jt]sx?$/.test(f.filename));
515
- const totalLines = files.reduce((s, f) => s + f.additions + f.deletions, 0);
516
- const critical = sorted.filter((f) => f.severity === "critical");
517
- const high = sorted.filter((f) => f.severity === "high");
518
- const medium = sorted.filter((f) => f.severity === "medium");
519
- const conclusion = critical.length > 0 || high.length > 0
520
- ? "needs_changes"
521
- : medium.length > 0
522
- ? "risky_but_acceptable"
523
- : "pass";
524
- const conclusionLabel = conclusion === "pass"
525
- ? "PASS"
526
- : conclusion === "needs_changes"
527
- ? "NEEDS CHANGES"
528
- : "RISKY BUT ACCEPTABLE";
390
+ if (evidence.unverifiedSignals.includes("changed_files")) {
391
+ workflowPolicyFindings.push({
392
+ severity: "high",
393
+ category: "WorkflowPolicyEvidenceUnavailable",
394
+ description: "The changed-file list is incomplete, so a workflow policy change may be hidden beyond the collection limit.",
395
+ suggestion: "Reduce or split the PR so every changed file can be enumerated and all workflow content can be audited before merge.",
396
+ dimension: "policy",
397
+ paths: [],
398
+ reason: "GitHub returned more than the bounded changed-file limit or the changed-file source could not be verified.",
399
+ });
400
+ }
401
+ let secretScannerEvidence = null;
402
+ if (params.standard === "security-focused") {
403
+ const provenance = await verifySecretScannerProvenance(evidence.ci, {
404
+ ref,
405
+ headSha: evidence.pullRequest.headSha,
406
+ baseRef: evidence.pullRequest.baseSha ?? evidence.pullRequest.baseBranch,
407
+ octokit,
408
+ });
409
+ errors.push(...provenance.errors.map((error) => `Secret scanner provenance: ${error}`));
410
+ secretScannerEvidence = evaluateSecretScannerEvidence(provenance.ci, {
411
+ policyFilesChanged: files.some((file) => isSecretScannerPolicyPath(file.filename) ||
412
+ (file.previousFilename !== undefined &&
413
+ isSecretScannerPolicyPath(file.previousFilename))),
414
+ incompleteReasons: evidence.unverifiedSignals.includes("changed_files")
415
+ ? ["changed_files"]
416
+ : [],
417
+ });
418
+ }
419
+ const review = evaluatePullRequestReview({
420
+ pr: {
421
+ title: evidence.pullRequest.title,
422
+ body: evidence.pullRequest.body,
423
+ labels: evidence.pullRequest.labels,
424
+ draft: evidence.pullRequest.draft,
425
+ commits: evidence.pullRequest.commits,
426
+ },
427
+ files,
428
+ workType: params.workType,
429
+ standard: params.standard,
430
+ secretScannerEvidence: secretScannerEvidence ?? undefined,
431
+ policyFindings: [...ownershipPolicyFindings, ...workflowPolicyFindings],
432
+ });
529
433
  const structured = {
530
- pullNumber: pr.number,
531
- title: pr.title,
434
+ pullNumber: evidence.pullRequest.number,
435
+ title: evidence.pullRequest.title,
532
436
  standard: params.standard,
533
- conclusion,
534
- findings: sorted,
535
- hasTests,
536
- totalChangedLines: totalLines,
537
- codeownersFound,
437
+ conclusion: review.conclusion,
438
+ findings: review.findings,
439
+ hasTests: review.hasTests,
440
+ totalChangedLines: review.totalChangedLines,
441
+ codeownersFound: params.checkOwnership && evidence.reviews.codeownersFound === true,
442
+ workType: review.workType,
443
+ workTypeConfidence: review.workTypeConfidence,
444
+ workTypeReasoning: review.workTypeReasoning,
445
+ releaseRisk: review.releaseRisk,
446
+ testCoverageSignal: review.testCoverageSignal,
447
+ ownershipRoutingGaps,
538
448
  errors,
449
+ secretScannerEvidence: review.secretScannerEvidence,
539
450
  };
451
+ const conclusionLabel = structured.conclusion === "pass"
452
+ ? "PASS"
453
+ : structured.conclusion === "needs_changes"
454
+ ? "NEEDS CHANGES"
455
+ : "RISKY BUT ACCEPTABLE";
456
+ const inline = (value, maxLength = 300) => safeMarkdownInline(value, { maxLength });
540
457
  const lines = [
541
- `# PR Review: #${pr.number} -- ${pr.title}`,
458
+ `# PR Review: #${structured.pullNumber} -- ${inline(structured.title, 400)}`,
542
459
  "",
543
460
  `**Standard:** ${params.standard}`,
544
461
  `**Conclusion:** ${conclusionLabel}`,
545
- `**Findings:** ${sorted.length} total (${critical.length} critical, ${high.length} high, ${medium.length} medium)`,
546
- `**CODEOWNERS:** ${params.checkOwnership ? (codeownersFound ? "found, ownership checked" : "not found -- ownership not checked") : "checkOwnership disabled"}`,
462
+ `**Findings:** ${structured.findings.length} total`,
463
+ `**CODEOWNERS:** ${params.checkOwnership ? (structured.codeownersFound ? "found, ownership checked" : "not found -- ownership not checked") : "checkOwnership disabled"}`,
547
464
  "",
548
465
  ];
549
466
  if (errors.length > 0) {
550
467
  lines.push("## Notes", "");
551
- errors.forEach((e) => lines.push(`- ${e}`));
468
+ errors.forEach((error) => lines.push(`- ${inline(error, 500)}`));
552
469
  lines.push("");
553
470
  }
554
- lines.push("## Findings");
555
- if (sorted.length === 0) {
556
- lines.push("", "No findings -- looks good!");
557
- }
558
- else {
559
- for (const f of sorted) {
560
- lines.push("", `### ${severityIcon(f.severity)} [${f.severity.toUpperCase()}] ${f.category}: ${f.description}`, f.suggestion ? `> Suggestion: ${f.suggestion}` : "");
471
+ lines.push("## Work Type", "", `**${inline(structured.workType)}** (${inline(structured.workTypeConfidence)} confidence) -- ${inline(structured.workTypeReasoning, 500)}`, "");
472
+ const renderSection = (title, dimensions) => {
473
+ lines.push(`## ${title}`, "");
474
+ const findings = structured.findings.filter((finding) => dimensions.includes(finding.dimension));
475
+ if (findings.length === 0)
476
+ lines.push("No findings.");
477
+ for (const finding of findings) {
478
+ lines.push(`### ${severityIcon(finding.severity)} [${finding.severity.toUpperCase()}] ${inline(finding.category)}`, inline(finding.description, 500), `- Paths: ${finding.paths.length > 0 ? finding.paths.map((path) => inline(path)).join(", ") : "none"}`, `- Reason: ${inline(finding.reason, 500)}`, `> Suggestion: ${inline(finding.suggestion, 500)}`, "");
561
479
  }
480
+ lines.push("");
481
+ };
482
+ renderSection("Intent / Scope / Evidence", ["intent", "scope", "evidence"]);
483
+ renderSection("Ownership", ["ownership"]);
484
+ renderSection("Policy", ["policy"]);
485
+ renderSection("Fallback", ["fallback"]);
486
+ renderSection("Security", ["security"]);
487
+ if (structured.secretScannerEvidence) {
488
+ lines.push("### Mature Secret Scanner Evidence", `- Status: **${structured.secretScannerEvidence.status}**`, `- Providers: ${structured.secretScannerEvidence.providers.map((provider) => inline(provider)).join(", ") || "none"}`, `- Verified: ${structured.secretScannerEvidence.verified ? "yes" : "no"}`, `- Reason: ${inline(structured.secretScannerEvidence.reason, 500)}`, "");
562
489
  }
563
- lines.push("", "## Test Coverage", hasTests ? "Tests included." : "No test files detected in this PR.", "", "## Release Risk", conclusion === "pass"
564
- ? "Low risk -- safe to merge after review."
565
- : conclusion === "risky_but_acceptable"
566
- ? "Moderate risk -- address medium findings before release."
567
- : "High risk -- must fix critical/high findings before merging.", "", "## Conclusion", conclusionLabel);
490
+ lines.push("## Test Coverage", `**${structured.testCoverageSignal}** -- ${structured.hasTests ? "test files changed" : "no test files changed"}.`, "", "## Release Risk", `**${structured.releaseRisk}**`, "", "## Conclusion", conclusionLabel);
568
491
  return { text: lines.join("\n"), structured };
569
492
  }
570
493
  // ---------------------------------------------------------------------------
@@ -578,7 +501,7 @@ export function registerReviewPrTool(server) {
578
501
  Standards:
579
502
  - basic: Core checks (tests, description, draft status, commit count)
580
503
  - strict: basic + large diff detection, missing docs
581
- - security-focused: strict + patch scanning for secret patterns, .env files, lockfile changes, dist files
504
+ - security-focused: strict + mature secret-scanner CI evidence + supplemental patch heuristics, .env files, lockfile changes, dist files
582
505
 
583
506
  Ownership check (independent of standard, runs when checkOwnership is true and a CODEOWNERS file exists):
584
507
  Matches changed files against .github/CODEOWNERS (or CODEOWNERS / docs/CODEOWNERS), and flags any