agentic-sdlc-mcp 1.5.0 → 1.7.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 (72) hide show
  1. package/README.md +38 -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/context.d.ts +10 -0
  10. package/dist/github/context.d.ts.map +1 -1
  11. package/dist/github/context.js +10 -0
  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/policy/pull-request-policy.d.ts +35 -0
  18. package/dist/policy/pull-request-policy.d.ts.map +1 -0
  19. package/dist/policy/pull-request-policy.js +99 -0
  20. package/dist/policy/pull-request-policy.js.map +1 -0
  21. package/dist/policy/repository-policy-loader.d.ts +37 -0
  22. package/dist/policy/repository-policy-loader.d.ts.map +1 -0
  23. package/dist/policy/repository-policy-loader.js +144 -0
  24. package/dist/policy/repository-policy-loader.js.map +1 -0
  25. package/dist/policy/repository-policy.d.ts +98 -0
  26. package/dist/policy/repository-policy.d.ts.map +1 -0
  27. package/dist/policy/repository-policy.js +331 -0
  28. package/dist/policy/repository-policy.js.map +1 -0
  29. package/dist/rendering/markdown.d.ts +8 -0
  30. package/dist/rendering/markdown.d.ts.map +1 -0
  31. package/dist/rendering/markdown.js +27 -0
  32. package/dist/rendering/markdown.js.map +1 -0
  33. package/dist/review/pull-request-review.d.ts +77 -0
  34. package/dist/review/pull-request-review.d.ts.map +1 -0
  35. package/dist/review/pull-request-review.js +1185 -0
  36. package/dist/review/pull-request-review.js.map +1 -0
  37. package/dist/security/secret-scanner-evidence.d.ts +58 -0
  38. package/dist/security/secret-scanner-evidence.d.ts.map +1 -0
  39. package/dist/security/secret-scanner-evidence.js +414 -0
  40. package/dist/security/secret-scanner-evidence.js.map +1 -0
  41. package/dist/tools/agent-handoff.d.ts +50 -0
  42. package/dist/tools/agent-handoff.d.ts.map +1 -1
  43. package/dist/tools/agent-handoff.js +62 -1
  44. package/dist/tools/agent-handoff.js.map +1 -1
  45. package/dist/tools/plan-from-context.d.ts +23 -0
  46. package/dist/tools/plan-from-context.d.ts.map +1 -1
  47. package/dist/tools/plan-from-context.js +68 -6
  48. package/dist/tools/plan-from-context.js.map +1 -1
  49. package/dist/tools/quality-gate-status.d.ts +313 -5
  50. package/dist/tools/quality-gate-status.d.ts.map +1 -1
  51. package/dist/tools/quality-gate-status.js +737 -95
  52. package/dist/tools/quality-gate-status.js.map +1 -1
  53. package/dist/tools/release-readiness.d.ts +64 -0
  54. package/dist/tools/release-readiness.d.ts.map +1 -1
  55. package/dist/tools/release-readiness.js +170 -45
  56. package/dist/tools/release-readiness.js.map +1 -1
  57. package/dist/tools/repo-context.d.ts +44 -0
  58. package/dist/tools/repo-context.d.ts.map +1 -1
  59. package/dist/tools/repo-context.js +57 -0
  60. package/dist/tools/repo-context.js.map +1 -1
  61. package/dist/tools/review-pr.d.ts +134 -29
  62. package/dist/tools/review-pr.d.ts.map +1 -1
  63. package/dist/tools/review-pr.js +337 -313
  64. package/dist/tools/review-pr.js.map +1 -1
  65. package/dist/tools/workflow-permissions-audit.d.ts +14 -1
  66. package/dist/tools/workflow-permissions-audit.d.ts.map +1 -1
  67. package/dist/tools/workflow-permissions-audit.js +40 -15
  68. package/dist/tools/workflow-permissions-audit.js.map +1 -1
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. package/package.json +3 -1
  72. package/server.json +54 -0
@@ -5,7 +5,16 @@
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, inferWorkType, 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
+ import { loadRepositoryPolicy } from "../policy/repository-policy-loader.js";
16
+ import { evaluatePullRequestPolicy } from "../policy/pull-request-policy.js";
17
+ export { codeownersPatternMatches, fetchCodeownersRules, ownersForFile, parseCodeowners, } from "../github/codeowners.js";
9
18
  // ---------------------------------------------------------------------------
10
19
  // Schema
11
20
  // ---------------------------------------------------------------------------
@@ -17,6 +26,10 @@ export const ReviewPrInputSchema = z.object({
17
26
  .enum(["basic", "strict", "security-focused"])
18
27
  .default("basic")
19
28
  .describe("Review standard: 'basic', 'strict', or 'security-focused'."),
29
+ workType: z
30
+ .enum(["docs", "feature", "bugfix", "refactor", "security", "release", "infra"])
31
+ .optional()
32
+ .describe("Optional explicit work type. When omitted, it is inferred from PR metadata and paths."),
20
33
  checkOwnership: z
21
34
  .boolean()
22
35
  .default(true)
@@ -34,12 +47,59 @@ export const ReviewPrOutputSchema = {
34
47
  severity: z.enum(["critical", "high", "medium", "low", "info"]),
35
48
  category: z.string(),
36
49
  description: z.string(),
37
- suggestion: z.string().optional(),
50
+ suggestion: z.string(),
51
+ dimension: z.enum(["intent", "scope", "evidence", "ownership", "policy", "fallback", "security"]),
52
+ paths: z.array(z.string()),
53
+ reason: z.string(),
38
54
  })),
39
55
  hasTests: z.boolean(),
40
56
  totalChangedLines: z.number().int(),
41
57
  codeownersFound: z.boolean(),
58
+ workType: z.enum(["docs", "feature", "bugfix", "refactor", "security", "release", "infra"]),
59
+ workTypeConfidence: z.enum(["high", "medium", "low"]),
60
+ workTypeReasoning: z.string(),
61
+ releaseRisk: z.enum(["low", "moderate", "high", "critical"]),
62
+ testCoverageSignal: z.enum(["adequate", "missing", "not_required", "insufficient_evidence"]),
63
+ ownershipRoutingGaps: z.array(z.object({ owner: z.string(), paths: z.array(z.string()) })),
42
64
  errors: z.array(z.string()),
65
+ secretScannerEvidence: z
66
+ .object({
67
+ status: z.enum(["passing", "failing", "pending", "unverified"]),
68
+ verified: z.boolean(),
69
+ degraded: z.boolean(),
70
+ providers: z.array(z.enum([
71
+ "gitleaks",
72
+ "trufflehog",
73
+ "secretlint",
74
+ "detect-secrets",
75
+ "github-secret-scanning",
76
+ ])),
77
+ signals: z.array(z.object({
78
+ name: z.string(),
79
+ provider: z.enum([
80
+ "gitleaks",
81
+ "trufflehog",
82
+ "secretlint",
83
+ "detect-secrets",
84
+ "github-secret-scanning",
85
+ ]),
86
+ source: z.enum(["check_run", "commit_status"]),
87
+ appId: z.number().int().nullable(),
88
+ trusted: z.boolean(),
89
+ provenanceVerified: z.boolean(),
90
+ state: z.enum(["passing", "failing", "pending", "skipped"]),
91
+ url: z.string().nullable(),
92
+ })),
93
+ reason: z.string(),
94
+ })
95
+ .nullable(),
96
+ policyDigest: z.string(),
97
+ policySources: z.array(z.object({
98
+ kind: z.enum(["default", "repository"]), path: z.string().nullable(),
99
+ ref: z.string().nullable(), blobSha: z.string().nullable(), digest: z.string(),
100
+ })),
101
+ appliedPolicyRules: z.array(z.object({ id: z.string(), source: z.literal("repository") })),
102
+ policyDegraded: z.boolean(),
43
103
  };
44
104
  // ---------------------------------------------------------------------------
45
105
  // Pure helpers (exported for testing)
@@ -59,36 +119,16 @@ export function severityIcon(s) {
59
119
  return icons[s] ?? "⚪";
60
120
  }
61
121
  /**
62
- * Secret-like patterns to flag in added patch lines (conservative).
63
- * Only matches lines that look like an assignment, not just the word.
122
+ * Backward-compatible wrapper around the shared heuristic scanner.
123
+ * Mature scanner evidence is evaluated separately from CI check runs.
64
124
  */
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
125
  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;
126
+ return scanSharedPatchForSecrets(filename, patch).map((item) => ({
127
+ severity: item.severity,
128
+ category: "Security",
129
+ description: item.description,
130
+ suggestion: item.suggestion,
131
+ }));
92
132
  }
93
133
  /**
94
134
  * Classify PR files into categories.
@@ -251,320 +291,304 @@ export function generateFindings(pr, files, standard) {
251
291
  return findings;
252
292
  }
253
293
  // ---------------------------------------------------------------------------
254
- // CODEOWNERS parsing and ownership findings (pure, exported for testing)
294
+ // CODEOWNERS finding presentation
255
295
  // ---------------------------------------------------------------------------
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;
296
+ function ownershipGapsToFindings(gaps) {
297
+ return gaps.map(({ owner, paths }) => ({
298
+ severity: "medium",
299
+ category: "Ownership",
300
+ description: `CODEOWNERS owner ${owner} was not requested as a reviewer and has not reviewed changes to: ${paths.join(", ")}.`,
301
+ suggestion: `Request a review from ${owner}, or confirm CODEOWNERS routing is still correct for these paths.`,
302
+ }));
269
303
  }
270
304
  /**
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).
305
+ * @deprecated Import `findOwnershipGaps` from `../github/codeowners.js` for shared routing logic.
275
306
  */
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];
307
+ export function generateOwnershipFindings(files, rules, requestedUsers, requestedTeams, reviewedUsers, prAuthor) {
308
+ return ownershipGapsToFindings(findOwnershipGaps(files.map((file) => file.filename), rules, requestedUsers, requestedTeams, reviewedUsers, prAuthor));
296
309
  }
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
- }
310
+ // ---------------------------------------------------------------------------
311
+ // Core handler (exported for testing)
312
+ // ---------------------------------------------------------------------------
313
+ export async function handleReviewPr(params, ref, octokit) {
314
+ const evidence = await collectPullRequestEvidence({ pullNumber: params.pullNumber }, ref, octokit);
315
+ const files = evidence.changedFiles;
316
+ const loadedPolicy = await loadRepositoryPolicy(ref, evidence.pullRequest.baseSha ?? evidence.pullRequest.baseBranch, octokit);
317
+ const inferredWorkType = params.workType ?? inferWorkType({
318
+ title: evidence.pullRequest.title,
319
+ body: evidence.pullRequest.body,
320
+ labels: evidence.pullRequest.labels,
321
+ draft: evidence.pullRequest.draft,
322
+ commits: evidence.pullRequest.commits,
323
+ }, files).workType;
324
+ const repositoryPolicy = evaluatePullRequestPolicy(loadedPolicy, {
325
+ paths: files.flatMap((file) => file.previousFilename ? [file.filename, file.previousFilename] : [file.filename]),
326
+ workType: inferredWorkType,
327
+ changedFilesComplete: !evidence.unverifiedSignals.includes("changed_files"),
328
+ linkedIssues: evidence.linkedIssues,
329
+ approvedUsers: evidence.reviews.approvedUsers,
330
+ requestedUsers: evidence.reviews.requestedUsers,
331
+ requestedTeams: evidence.reviews.requestedTeams,
332
+ codeOwnerReviewSatisfied: evidence.reviews.codeOwnerReviewSatisfied,
333
+ });
334
+ const errors = evidence.errors.map((error) => {
335
+ if (error.startsWith("requested_reviewers:")) {
336
+ return `Requested reviewers:${error.slice("requested_reviewers:".length)}`;
326
337
  }
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)));
344
- }
345
- /**
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).
349
- */
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;
366
- }
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;
338
+ if (error.startsWith("reviews:"))
339
+ return `Reviews:${error.slice("reviews:".length)}`;
340
+ if (error.startsWith("codeowners:"))
341
+ return `CODEOWNERS:${error.slice("codeowners:".length)}`;
342
+ if (params.standard === "security-focused" &&
343
+ (error.startsWith("check_runs:") || error.startsWith("commit_statuses:"))) {
344
+ return `Secret scanner CI: ${error}`;
373
345
  }
346
+ return error;
347
+ });
348
+ const workflowContents = [];
349
+ const unverifiedWorkflowPaths = [];
350
+ const changedWorkflows = files.filter((file) => file.status !== "removed" &&
351
+ /^\.github\/workflows\/[^/]+\.ya?ml$/i.test(file.filename));
352
+ if (changedWorkflows.length > MAX_WORKFLOW_FILES) {
353
+ errors.push(`Workflow permissions: only the first ${MAX_WORKFLOW_FILES} of ${changedWorkflows.length} changed workflows were audited.`);
354
+ unverifiedWorkflowPaths.push(...changedWorkflows.slice(MAX_WORKFLOW_FILES).map((file) => file.filename));
374
355
  }
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))
356
+ for (const file of changedWorkflows.slice(0, MAX_WORKFLOW_FILES)) {
357
+ try {
358
+ const { data } = await octokit.repos.getContent({
359
+ owner: ref.owner,
360
+ repo: ref.repo,
361
+ path: file.filename,
362
+ ref: evidence.pullRequest.headSha,
363
+ });
364
+ if (Array.isArray(data) || data.type !== "file" || !data.content) {
365
+ errors.push(`Workflow permissions: ${file.filename}: unexpected content response.`);
366
+ unverifiedWorkflowPaths.push(file.filename);
390
367
  continue;
391
- const list = missingOwnerFiles.get(owner) ?? [];
392
- list.push(file.filename);
393
- missingOwnerFiles.set(owner, list);
368
+ }
369
+ workflowContents.push({
370
+ filename: file.filename,
371
+ content: Buffer.from(data.content, "base64").toString("utf-8"),
372
+ });
373
+ }
374
+ catch (error) {
375
+ errors.push(`Workflow permissions: ${file.filename}: ${handleGitHubError(error)}`);
376
+ unverifiedWorkflowPaths.push(file.filename);
394
377
  }
395
378
  }
396
- const findings = [];
397
- for (const [owner, filenames] of missingOwnerFiles) {
398
- findings.push({
379
+ const workflowEvaluation = evaluateWorkflowContents(workflowContents);
380
+ errors.push(...workflowEvaluation.errors.map((error) => `Workflow permissions: ${error}`));
381
+ const scannedWorkflows = new Set(workflowEvaluation.workflowsScanned);
382
+ unverifiedWorkflowPaths.push(...workflowContents
383
+ .filter((workflow) => !scannedWorkflows.has(workflow.filename))
384
+ .map((workflow) => workflow.filename));
385
+ const ownershipRoutingGaps = params.checkOwnership ? evidence.reviews.ownershipGaps : [];
386
+ const ownershipPolicyFindings = ownershipRoutingGaps.map(({ owner, paths }) => ({
387
+ severity: "medium",
388
+ category: "Ownership",
389
+ description: `CODEOWNERS owner ${owner} was not requested as a reviewer and has not reviewed changes to: ${paths.join(", ")}.`,
390
+ suggestion: `Request a review from ${owner}, or confirm CODEOWNERS routing is still correct for these paths.`,
391
+ dimension: "ownership",
392
+ paths,
393
+ reason: "The shared PR evidence layer found an unsatisfied CODEOWNERS routing requirement.",
394
+ }));
395
+ const workflowPolicyFindings = workflowEvaluation.findings.map((finding) => {
396
+ const workflow = workflowContents.find((item) => finding.description.startsWith(`${item.filename}:`));
397
+ return {
398
+ ...finding,
399
+ suggestion: finding.suggestion ?? "Review and reduce the workflow token permissions.",
400
+ dimension: "policy",
401
+ paths: workflow ? [workflow.filename] : [],
402
+ reason: "The finding was derived from the complete workflow content at the PR head SHA.",
403
+ };
404
+ });
405
+ const repositoryPolicyFindings = [
406
+ ...(repositoryPolicy.matchedProtectedPaths.length > 0
407
+ ? [{
408
+ severity: "medium",
409
+ category: "ProtectedPath",
410
+ description: `Changed files match protected path rules: ${repositoryPolicy.matchedProtectedPaths.join(", ")}.`,
411
+ suggestion: "Apply focused ownership and risk review before merge.",
412
+ dimension: "policy",
413
+ paths: files.map((file) => file.filename),
414
+ reason: "Repository policy rule paths.protected matched the changed paths.",
415
+ }]
416
+ : []),
417
+ ...(files.some((file) => file.filename.toLocaleLowerCase() === ".agentic-sdlc.yml" ||
418
+ file.previousFilename?.toLocaleLowerCase() === ".agentic-sdlc.yml")
419
+ ? [{
420
+ severity: "high",
421
+ category: "RepositoryPolicyChange",
422
+ description: "This pull request changes the repository policy file.",
423
+ suggestion: "Review the policy change independently; this review intentionally uses the base-SHA policy.",
424
+ dimension: "policy",
425
+ paths: [".agentic-sdlc.yml"],
426
+ reason: "Policy self-modification cannot govern the pull request that proposes it.",
427
+ }]
428
+ : []),
429
+ ...repositoryPolicy.blockers.map((reason) => ({
430
+ severity: "high",
431
+ category: "RepositoryPolicy",
432
+ description: reason.message,
433
+ suggestion: "Satisfy the repository policy requirement before merge.",
434
+ dimension: "policy",
435
+ paths: repositoryPolicy.matchedProtectedPaths,
436
+ reason: `Repository policy rule ${reason.ruleId} from the PR base SHA was not satisfied.`,
437
+ })),
438
+ ...repositoryPolicy.pendingReviews.map((reason) => ({
399
439
  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.`,
440
+ category: "RepositoryPolicyReviewPending",
441
+ description: reason.message,
442
+ suggestion: "Wait for the requested reviewer to approve the current PR head.",
443
+ dimension: "policy",
444
+ paths: repositoryPolicy.matchedProtectedPaths,
445
+ reason: `Repository policy rule ${reason.ruleId} is pending.`,
446
+ })),
447
+ ...repositoryPolicy.policyGaps.map((reason) => ({
448
+ severity: "high",
449
+ category: "RepositoryPolicyEvidenceUnavailable",
450
+ description: reason.message,
451
+ suggestion: "Restore complete policy evidence and rerun the review before merge.",
452
+ dimension: "policy",
453
+ paths: [],
454
+ reason: `Repository policy rule ${reason.ruleId} could not be verified.`,
455
+ })),
456
+ ...loadedPolicy.policy.riskRules
457
+ .filter((rule) => repositoryPolicy.matchedRiskRuleIds.includes(rule.id))
458
+ .map((rule) => ({
459
+ severity: rule.level,
460
+ category: "RepositoryRiskRule",
461
+ description: `Changed paths match ${rule.id} (${rule.domains.join(", ")}).`,
462
+ suggestion: "Apply defensive review and testing appropriate to the matched risk domains.",
463
+ dimension: "policy",
464
+ paths: files.map((file) => file.filename),
465
+ reason: `Repository policy risk rule ${rule.id} matched the changed paths.`,
466
+ })),
467
+ ];
468
+ const uniqueUnverifiedWorkflowPaths = [...new Set(unverifiedWorkflowPaths)];
469
+ if (uniqueUnverifiedWorkflowPaths.length > 0) {
470
+ workflowPolicyFindings.push({
471
+ severity: "high",
472
+ category: "WorkflowPolicyEvidenceUnavailable",
473
+ description: "Complete workflow permission evidence could not be verified for every changed workflow.",
474
+ suggestion: "Restore repository content access and provide parseable complete workflow files at the PR head SHA before merge.",
475
+ dimension: "policy",
476
+ paths: uniqueUnverifiedWorkflowPaths,
477
+ reason: "Fetching, parsing, or the bounded workflow audit failed, so least-privilege policy cannot be confirmed.",
403
478
  });
404
479
  }
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) {
416
- 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 };
421
- }
422
- }
423
- catch (err) {
424
- const message = handleGitHubError(err);
425
- if (!message.toLowerCase().includes("not found")) {
426
- lastError = message;
427
- }
428
- }
480
+ if (evidence.unverifiedSignals.includes("changed_files")) {
481
+ workflowPolicyFindings.push({
482
+ severity: "high",
483
+ category: "WorkflowPolicyEvidenceUnavailable",
484
+ description: "The changed-file list is incomplete, so a workflow policy change may be hidden beyond the collection limit.",
485
+ suggestion: "Reduce or split the PR so every changed file can be enumerated and all workflow content can be audited before merge.",
486
+ dimension: "policy",
487
+ paths: [],
488
+ reason: "GitHub returned more than the bounded changed-file limit or the changed-file source could not be verified.",
489
+ });
429
490
  }
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,
456
- }));
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
- }
491
+ let secretScannerEvidence = null;
492
+ if (params.standard === "security-focused") {
493
+ const provenance = await verifySecretScannerProvenance(evidence.ci, {
494
+ ref,
495
+ headSha: evidence.pullRequest.headSha,
496
+ baseRef: evidence.pullRequest.baseSha ?? evidence.pullRequest.baseBranch,
497
+ octokit,
498
+ });
499
+ errors.push(...provenance.errors.map((error) => `Secret scanner provenance: ${error}`));
500
+ secretScannerEvidence = evaluateSecretScannerEvidence(provenance.ci, {
501
+ policyFilesChanged: files.some((file) => isSecretScannerPolicyPath(file.filename) ||
502
+ (file.previousFilename !== undefined &&
503
+ isSecretScannerPolicyPath(file.previousFilename))),
504
+ incompleteReasons: evidence.unverifiedSignals.includes("changed_files")
505
+ ? ["changed_files"]
506
+ : [],
507
+ });
508
508
  }
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";
509
+ const review = evaluatePullRequestReview({
510
+ pr: {
511
+ title: evidence.pullRequest.title,
512
+ body: evidence.pullRequest.body,
513
+ labels: evidence.pullRequest.labels,
514
+ draft: evidence.pullRequest.draft,
515
+ commits: evidence.pullRequest.commits,
516
+ },
517
+ files,
518
+ workType: params.workType,
519
+ standard: params.standard,
520
+ secretScannerEvidence: secretScannerEvidence ?? undefined,
521
+ policyFindings: [
522
+ ...ownershipPolicyFindings,
523
+ ...workflowPolicyFindings,
524
+ ...repositoryPolicyFindings,
525
+ ],
526
+ });
529
527
  const structured = {
530
- pullNumber: pr.number,
531
- title: pr.title,
528
+ pullNumber: evidence.pullRequest.number,
529
+ title: evidence.pullRequest.title,
532
530
  standard: params.standard,
533
- conclusion,
534
- findings: sorted,
535
- hasTests,
536
- totalChangedLines: totalLines,
537
- codeownersFound,
531
+ conclusion: review.conclusion,
532
+ findings: review.findings,
533
+ hasTests: review.hasTests,
534
+ totalChangedLines: review.totalChangedLines,
535
+ codeownersFound: params.checkOwnership && evidence.reviews.codeownersFound === true,
536
+ workType: review.workType,
537
+ workTypeConfidence: review.workTypeConfidence,
538
+ workTypeReasoning: review.workTypeReasoning,
539
+ releaseRisk: review.releaseRisk,
540
+ testCoverageSignal: review.testCoverageSignal,
541
+ ownershipRoutingGaps,
538
542
  errors,
543
+ secretScannerEvidence: review.secretScannerEvidence,
544
+ policyDigest: repositoryPolicy.policyDigest,
545
+ policySources: repositoryPolicy.policySources,
546
+ appliedPolicyRules: loadedPolicy.appliedRules,
547
+ policyDegraded: repositoryPolicy.policyDegraded,
539
548
  };
549
+ const conclusionLabel = structured.conclusion === "pass"
550
+ ? "PASS"
551
+ : structured.conclusion === "needs_changes"
552
+ ? "NEEDS CHANGES"
553
+ : "RISKY BUT ACCEPTABLE";
554
+ const inline = (value, maxLength = 300) => safeMarkdownInline(value, { maxLength });
540
555
  const lines = [
541
- `# PR Review: #${pr.number} -- ${pr.title}`,
556
+ `# PR Review: #${structured.pullNumber} -- ${inline(structured.title, 400)}`,
542
557
  "",
543
558
  `**Standard:** ${params.standard}`,
544
559
  `**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"}`,
560
+ `**Findings:** ${structured.findings.length} total`,
561
+ `**CODEOWNERS:** ${params.checkOwnership ? (structured.codeownersFound ? "found, ownership checked" : "not found -- ownership not checked") : "checkOwnership disabled"}`,
547
562
  "",
548
563
  ];
549
564
  if (errors.length > 0) {
550
565
  lines.push("## Notes", "");
551
- errors.forEach((e) => lines.push(`- ${e}`));
566
+ errors.forEach((error) => lines.push(`- ${inline(error, 500)}`));
552
567
  lines.push("");
553
568
  }
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}` : "");
569
+ lines.push("## Policy Provenance", "", `- Digest: \`${inline(structured.policyDigest, 80)}\``, `- Status: ${structured.policyDegraded ? "degraded" : "verified"}`, `- Applied rules: ${structured.appliedPolicyRules.map((rule) => inline(rule.id)).join(", ") || "none"}`);
570
+ structured.policySources.forEach((source) => lines.push(`- Source: ${inline(source.path ?? "built-in")} @ ${inline(source.ref ?? "default")} (blob: ${inline(source.blobSha ?? "n/a")})`));
571
+ lines.push("");
572
+ lines.push("## Work Type", "", `**${inline(structured.workType)}** (${inline(structured.workTypeConfidence)} confidence) -- ${inline(structured.workTypeReasoning, 500)}`, "");
573
+ const renderSection = (title, dimensions) => {
574
+ lines.push(`## ${title}`, "");
575
+ const findings = structured.findings.filter((finding) => dimensions.includes(finding.dimension));
576
+ if (findings.length === 0)
577
+ lines.push("No findings.");
578
+ for (const finding of findings) {
579
+ 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
580
  }
581
+ lines.push("");
582
+ };
583
+ renderSection("Intent / Scope / Evidence", ["intent", "scope", "evidence"]);
584
+ renderSection("Ownership", ["ownership"]);
585
+ renderSection("Policy", ["policy"]);
586
+ renderSection("Fallback", ["fallback"]);
587
+ renderSection("Security", ["security"]);
588
+ if (structured.secretScannerEvidence) {
589
+ 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
590
  }
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);
591
+ lines.push("## Test Coverage", `**${structured.testCoverageSignal}** -- ${structured.hasTests ? "test files changed" : "no test files changed"}.`, "", "## Release Risk", `**${structured.releaseRisk}**`, "", "## Conclusion", conclusionLabel);
568
592
  return { text: lines.join("\n"), structured };
569
593
  }
570
594
  // ---------------------------------------------------------------------------
@@ -578,7 +602,7 @@ export function registerReviewPrTool(server) {
578
602
  Standards:
579
603
  - basic: Core checks (tests, description, draft status, commit count)
580
604
  - strict: basic + large diff detection, missing docs
581
- - security-focused: strict + patch scanning for secret patterns, .env files, lockfile changes, dist files
605
+ - security-focused: strict + mature secret-scanner CI evidence + supplemental patch heuristics, .env files, lockfile changes, dist files
582
606
 
583
607
  Ownership check (independent of standard, runs when checkOwnership is true and a CODEOWNERS file exists):
584
608
  Matches changed files against .github/CODEOWNERS (or CODEOWNERS / docs/CODEOWNERS), and flags any