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
@@ -1,14 +1,22 @@
1
1
  /**
2
2
  * Tool: quality_gate_status
3
3
  *
4
- * Core logic extracted as `categorizeChecks` and `handleQualityGateStatus`
5
- * for unit testing without MCP machinery.
4
+ * Evaluates real pull-request merge evidence while preserving ref-only CI
5
+ * compatibility and the legacy check-run summary fields.
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 { collectCiEvidence, collectPullRequestEvidence, } from "../github/pull-request-evidence.js";
10
+ import { safeMarkdownInline } from "../rendering/markdown.js";
9
11
  // ---------------------------------------------------------------------------
10
12
  // Schema
11
13
  // ---------------------------------------------------------------------------
14
+ export const DEFAULT_BLOCKING_LABELS = [
15
+ "blocked",
16
+ "do-not-merge",
17
+ "release-blocker",
18
+ "security-blocker",
19
+ ];
12
20
  export const QualityGateInputSchema = z.object({
13
21
  owner: z.string().optional().describe("GitHub owner. Falls back to GITHUB_OWNER."),
14
22
  repo: z.string().optional().describe("GitHub repo. Falls back to GITHUB_REPO."),
@@ -18,6 +26,11 @@ export const QualityGateInputSchema = z.object({
18
26
  ref: z
19
27
  .string().optional()
20
28
  .describe("Git ref (branch name, commit SHA). Ignored if pullNumber is set."),
29
+ blockingLabels: z
30
+ .array(z.string().min(1))
31
+ .max(50)
32
+ .default([...DEFAULT_BLOCKING_LABELS])
33
+ .describe("Exact, case-insensitive PR labels that block the gate. Pass [] to disable."),
21
34
  });
22
35
  const CheckStatusShape = z.object({
23
36
  name: z.string(),
@@ -25,137 +38,693 @@ const CheckStatusShape = z.object({
25
38
  conclusion: z.string().nullable(),
26
39
  url: z.string().nullable(),
27
40
  });
41
+ const GateSignalShape = z.object({
42
+ name: z.string(),
43
+ source: z.enum(["check_run", "commit_status"]),
44
+ appId: z.number().int().nullable(),
45
+ state: z.enum(["passing", "failing", "pending", "skipped"]),
46
+ rawStatus: z.string().nullable(),
47
+ rawConclusion: z.string().nullable(),
48
+ rawState: z.string().nullable(),
49
+ url: z.string().nullable(),
50
+ });
51
+ const RequiredStatusCheckShape = z.object({
52
+ context: z.string(),
53
+ appId: z.number().int().nullable(),
54
+ });
55
+ const SignalBucketsShape = z.object({
56
+ passing: z.array(GateSignalShape),
57
+ failing: z.array(GateSignalShape),
58
+ pending: z.array(GateSignalShape),
59
+ skipped: z.array(GateSignalShape),
60
+ total: z.number().int().nonnegative(),
61
+ });
62
+ const LinkedIssueShape = z.object({
63
+ number: z.number().int().positive(),
64
+ title: z.string(),
65
+ url: z.string(),
66
+ });
67
+ const OwnershipGapShape = z.object({
68
+ owner: z.string(),
69
+ paths: z.array(z.string()),
70
+ });
71
+ const QualityGateEvidenceShape = z.object({
72
+ scope: z.enum(["pull_request", "ref"]),
73
+ checks: z.object({
74
+ checkRuns: SignalBucketsShape,
75
+ commitStatuses: SignalBucketsShape,
76
+ totalSignals: z.number().int().nonnegative(),
77
+ requiredContexts: z.array(z.string()),
78
+ requiredChecks: z.array(RequiredStatusCheckShape),
79
+ missingRequiredContexts: z.array(z.string()),
80
+ }),
81
+ pullRequest: z
82
+ .object({
83
+ draft: z.boolean(),
84
+ mergeable: z.boolean().nullable(),
85
+ mergeableState: z.string().nullable(),
86
+ baseBranch: z.string(),
87
+ })
88
+ .nullable(),
89
+ reviews: z
90
+ .object({
91
+ reviewDecision: z.enum(["APPROVED", "CHANGES_REQUESTED", "REVIEW_REQUIRED"]).nullable(),
92
+ approved: z.number().int().nonnegative(),
93
+ approvedUsers: z.array(z.string()),
94
+ changesRequestedUsers: z.array(z.string()),
95
+ requestedUsers: z.array(z.string()),
96
+ requestedTeams: z.array(z.string()),
97
+ required: z.number().int().nonnegative().nullable(),
98
+ requireCodeOwnerReviews: z.boolean().nullable(),
99
+ codeOwnerReviewSatisfied: z.boolean().nullable(),
100
+ ownershipGaps: z.array(OwnershipGapShape),
101
+ })
102
+ .nullable(),
103
+ branchProtection: z
104
+ .object({
105
+ classicEnabled: z.boolean(),
106
+ rulesetRuleTypes: z.array(z.string()),
107
+ pullRequestRuleRequirements: z.object({
108
+ allowedMergeMethods: z.array(z.string()).nullable(),
109
+ dismissStaleReviews: z.boolean(),
110
+ lockBranch: z.boolean(),
111
+ requiredConversationResolution: z.boolean(),
112
+ requireLastPushApproval: z.boolean(),
113
+ requiredLinearHistory: z.boolean(),
114
+ requiredReviewThreadResolution: z.boolean(),
115
+ requiredReviewersConfigured: z.boolean(),
116
+ requiredSignatures: z.boolean(),
117
+ strictRequiredStatusChecksPolicy: z.boolean(),
118
+ }),
119
+ })
120
+ .nullable(),
121
+ labels: z
122
+ .object({
123
+ all: z.array(z.string()),
124
+ blocking: z.array(z.string()),
125
+ })
126
+ .nullable(),
127
+ linkedIssues: z.array(LinkedIssueShape).nullable(),
128
+ });
28
129
  export const QualityGateOutputSchema = {
29
130
  contextLabel: z.string(),
30
131
  headSha: z.string(),
31
- conclusion: z.enum(["passing", "failing", "pending"]),
132
+ conclusion: z.enum([
133
+ "passing",
134
+ "failing",
135
+ "pending",
136
+ "needs_review",
137
+ "policy_gap",
138
+ "no_evidence",
139
+ ]),
32
140
  categories: z.object({
33
141
  failing: z.array(CheckStatusShape),
34
142
  pending: z.array(CheckStatusShape),
35
143
  passing: z.array(CheckStatusShape),
36
144
  skipped: z.array(CheckStatusShape),
37
145
  }),
38
- totalChecks: z.number().int(),
146
+ totalChecks: z.number().int().nonnegative(),
147
+ evidence: QualityGateEvidenceShape,
148
+ blockers: z.array(z.string()),
149
+ warnings: z.array(z.string()),
150
+ nextActions: z.array(z.string()),
151
+ degraded: z.boolean(),
152
+ unverifiedSignals: z.array(z.string()),
153
+ errors: z.array(z.string()),
39
154
  };
40
155
  // ---------------------------------------------------------------------------
41
- // Pure helpers (exported for testing)
156
+ // Pure helpers
42
157
  // ---------------------------------------------------------------------------
43
158
  /** Categorise raw check-run objects into pass/fail/pending/skipped buckets. */
44
159
  export function categorizeChecks(checkRuns) {
45
160
  const toStatus = (run) => ({
46
161
  name: run.name,
47
- status: run.status ?? "unknown",
48
- conclusion: run.conclusion ?? null,
162
+ status: toCheckRunStatus(run.status),
163
+ conclusion: toCheckRunConclusion(run.conclusion),
49
164
  url: run.html_url ?? null,
50
165
  });
51
166
  return {
52
167
  failing: checkRuns
53
- .filter((c) => c.conclusion === "failure" || c.conclusion === "timed_out")
168
+ .filter((run) => ["failure", "timed_out", "cancelled", "action_required"].includes(run.conclusion ?? ""))
54
169
  .map(toStatus),
55
170
  pending: checkRuns
56
- .filter((c) => c.status === "queued" || c.status === "in_progress" || c.status === "pending")
171
+ .filter((run) => ["queued", "in_progress", "pending"].includes(run.status ?? ""))
57
172
  .map(toStatus),
58
- passing: checkRuns.filter((c) => c.conclusion === "success").map(toStatus),
173
+ passing: checkRuns.filter((run) => run.conclusion === "success").map(toStatus),
59
174
  skipped: checkRuns
60
- .filter((c) => c.conclusion === "skipped" || c.conclusion === "neutral")
175
+ .filter((run) => run.conclusion === "skipped" || run.conclusion === "neutral")
61
176
  .map(toStatus),
62
177
  };
63
178
  }
64
- // ---------------------------------------------------------------------------
65
- // Core handler (exported for testing)
66
- // ---------------------------------------------------------------------------
67
- export async function handleQualityGateStatus(params, ref, octokit) {
68
- let headSha;
69
- let contextLabel;
70
- if (params.pullNumber) {
71
- const { data: pr } = await octokit.pulls.get({
72
- owner: ref.owner,
73
- repo: ref.repo,
74
- pull_number: params.pullNumber,
75
- });
76
- headSha = pr.head.sha;
77
- contextLabel = `PR #${params.pullNumber} (${pr.title})`;
179
+ function toCheckRunStatus(status) {
180
+ if (status === "queued" ||
181
+ status === "in_progress" ||
182
+ status === "completed" ||
183
+ status === "pending") {
184
+ return status;
78
185
  }
79
- else if (params.ref) {
80
- const { data: refData } = await octokit.git.getRef({
81
- owner: ref.owner,
82
- repo: ref.repo,
83
- ref: params.ref.replace(/^refs\//, ""),
84
- });
85
- headSha = refData.object.sha;
86
- contextLabel = `ref: ${params.ref}`;
186
+ return "unknown";
187
+ }
188
+ function toCheckRunConclusion(conclusion) {
189
+ if (conclusion === "success" ||
190
+ conclusion === "failure" ||
191
+ conclusion === "neutral" ||
192
+ conclusion === "cancelled" ||
193
+ conclusion === "skipped" ||
194
+ conclusion === "timed_out" ||
195
+ conclusion === "action_required") {
196
+ return conclusion;
87
197
  }
88
- else {
89
- throw new Error("Either pullNumber or ref is required.");
198
+ return null;
199
+ }
200
+ function signalToCheckStatus(signal) {
201
+ return {
202
+ name: signal.name,
203
+ status: toCheckRunStatus(signal.rawStatus),
204
+ conclusion: toCheckRunConclusion(signal.rawConclusion),
205
+ url: signal.url,
206
+ };
207
+ }
208
+ function categoriesFromCheckRuns(checkRuns) {
209
+ return {
210
+ failing: checkRuns.failing.map(signalToCheckStatus),
211
+ pending: checkRuns.pending.map(signalToCheckStatus),
212
+ passing: checkRuns.passing.map(signalToCheckStatus),
213
+ skipped: checkRuns.skipped.map(signalToCheckStatus),
214
+ };
215
+ }
216
+ function unique(values) {
217
+ return values.filter((value, index, all) => all.indexOf(value) === index);
218
+ }
219
+ function uniqueCaseInsensitive(values) {
220
+ const seen = new Set();
221
+ return values.filter((value) => {
222
+ const normalized = value.toLocaleLowerCase();
223
+ if (seen.has(normalized))
224
+ return false;
225
+ seen.add(normalized);
226
+ return true;
227
+ });
228
+ }
229
+ function nextActionsFor(conclusion) {
230
+ switch (conclusion) {
231
+ case "failing":
232
+ return ["Resolve the known failing merge blockers before proceeding."];
233
+ case "pending":
234
+ return ["Wait for pending signals or required contexts, then run the gate again."];
235
+ case "needs_review":
236
+ return ["Complete the required human review and approval steps."];
237
+ case "policy_gap":
238
+ return ["Restore evidence access or configure the missing merge protection policy."];
239
+ case "no_evidence":
240
+ return ["Run or configure verifiable CI signals before treating this revision as safe."];
241
+ case "passing":
242
+ return ["Request final human merge approval."];
90
243
  }
91
- // Paginate check runs (repos with many checks can exceed 100)
92
- const allRuns = await paginateAll((page, perPage) => octokit.checks
93
- .listForRef({
94
- owner: ref.owner,
95
- repo: ref.repo,
96
- ref: headSha,
97
- per_page: perPage,
98
- page,
99
- })
100
- .then((r) => r.data.check_runs), 300);
101
- const cats = categorizeChecks(allRuns);
102
- const overallConclusion = cats.failing.length > 0
103
- ? "failing"
104
- : cats.pending.length > 0
105
- ? "pending"
106
- : "passing";
107
- const conclusionLabel = overallConclusion === "passing"
108
- ? "[PASS] All checks passed"
109
- : overallConclusion === "failing"
110
- ? "[FAIL] Some checks are failing"
111
- : "[PENDING] Checks are still running";
112
- const structured = {
113
- contextLabel,
244
+ }
245
+ function allSignals(ci) {
246
+ return [
247
+ ...ci.checkRuns.passing,
248
+ ...ci.checkRuns.failing,
249
+ ...ci.checkRuns.pending,
250
+ ...ci.checkRuns.skipped,
251
+ ...ci.commitStatuses.passing,
252
+ ...ci.commitStatuses.failing,
253
+ ...ci.commitStatuses.pending,
254
+ ...ci.commitStatuses.skipped,
255
+ ];
256
+ }
257
+ function requiredContextsState(evidence) {
258
+ const requiredChecks = evidence.branchProtection.requiredStatusChecks?.length > 0
259
+ ? evidence.branchProtection.requiredStatusChecks
260
+ : evidence.branchProtection.requiredStatusContexts.map((context) => ({
261
+ context,
262
+ appId: null,
263
+ }));
264
+ const required = uniqueCaseInsensitive(requiredChecks.map((check) => check.context));
265
+ const signals = allSignals(evidence.ci);
266
+ const satisfiedSignals = signals.filter((signal) => signal.state === "passing" || signal.state === "skipped");
267
+ const matches = (check, signal) => check.context.toLocaleLowerCase() === signal.name.toLocaleLowerCase() &&
268
+ (check.appId === null ||
269
+ (signal.source === "check_run" && signal.appId === check.appId));
270
+ const missingChecks = requiredChecks.filter((check) => !signals.some((signal) => matches(check, signal)));
271
+ return {
272
+ required,
273
+ missing: uniqueCaseInsensitive(missingChecks.map((check) => check.context)),
274
+ satisfiedByPassingOrSkipped: requiredChecks.length > 0 &&
275
+ requiredChecks.every((check) => satisfiedSignals.some((signal) => matches(check, signal))),
276
+ };
277
+ }
278
+ function hasReviewPolicy(evidence) {
279
+ const requirements = evidence.branchProtection.pullRequestRuleRequirements;
280
+ return ((evidence.reviews.requiredApprovals ?? 0) > 0 ||
281
+ evidence.reviews.requireCodeOwnerReviews === true ||
282
+ requirements?.dismissStaleReviews === true ||
283
+ requirements?.requireLastPushApproval === true);
284
+ }
285
+ const MODELED_MERGE_RULE_TYPES = new Set(["pull_request", "required_status_checks"]);
286
+ const SAFE_IGNORE_MERGE_RULE_TYPES = new Set([
287
+ "creation",
288
+ "deletion",
289
+ "non_fast_forward",
290
+ ]);
291
+ function mergePolicyState(evidence) {
292
+ const reviewPolicyConfigured = hasReviewPolicy(evidence);
293
+ const hasRequiredContexts = evidence.branchProtection.requiredStatusContexts.length > 0;
294
+ const pullRequestRequirements = evidence.branchProtection.pullRequestRuleRequirements;
295
+ const unmodeledRules = evidence.branchProtection.rulesetRuleTypes.filter((type) => {
296
+ const normalized = type.toLocaleLowerCase();
297
+ if (normalized === "pull_request")
298
+ return !reviewPolicyConfigured;
299
+ if (normalized === "required_status_checks")
300
+ return !hasRequiredContexts;
301
+ if (SAFE_IGNORE_MERGE_RULE_TYPES.has(normalized))
302
+ return false;
303
+ return !MODELED_MERGE_RULE_TYPES.has(normalized);
304
+ });
305
+ if (pullRequestRequirements?.requiredReviewThreadResolution) {
306
+ unmodeledRules.push("pull_request.required_review_thread_resolution");
307
+ }
308
+ if (pullRequestRequirements?.requiredReviewersConfigured) {
309
+ unmodeledRules.push("pull_request.required_reviewers");
310
+ }
311
+ if (Array.isArray(pullRequestRequirements?.allowedMergeMethods)) {
312
+ unmodeledRules.push("pull_request.allowed_merge_methods");
313
+ }
314
+ if (pullRequestRequirements?.strictRequiredStatusChecksPolicy) {
315
+ unmodeledRules.push("required_status_checks.strict_required_status_checks_policy");
316
+ }
317
+ if (pullRequestRequirements?.requiredConversationResolution) {
318
+ unmodeledRules.push("branch_protection.required_conversation_resolution");
319
+ }
320
+ if (pullRequestRequirements?.requiredSignatures) {
321
+ unmodeledRules.push("branch_protection.required_signatures");
322
+ }
323
+ if (pullRequestRequirements?.requiredLinearHistory) {
324
+ unmodeledRules.push("branch_protection.required_linear_history");
325
+ }
326
+ if (pullRequestRequirements?.lockBranch) {
327
+ unmodeledRules.push("branch_protection.lock_branch");
328
+ }
329
+ const modeled = reviewPolicyConfigured || hasRequiredContexts;
330
+ const uniqueUnmodeledRules = uniqueCaseInsensitive(unmodeledRules);
331
+ return {
332
+ hasAnyPolicy: modeled || uniqueUnmodeledRules.length > 0,
333
+ unmodeledRules: uniqueUnmodeledRules,
334
+ };
335
+ }
336
+ function sourceWarnings(evidence) {
337
+ const warnings = [];
338
+ const unverified = new Set(evidence.unverifiedSignals);
339
+ if (evidence.linkedIssues === null || unverified.has("linked_issues")) {
340
+ warnings.push("linked issue 证据无法验证。 ");
341
+ }
342
+ else if (evidence.linkedIssues.length === 0) {
343
+ warnings.push("此 PR 未关联 issue;建议补充可追溯的工作项。 ");
344
+ }
345
+ if (!unverified.has("branch_protection") &&
346
+ !unverified.has("branch_rules") &&
347
+ !hasReviewPolicy(evidence)) {
348
+ warnings.push("未配置 required review 规则;这在单维护者仓库中可能是合理选择。 ");
349
+ }
350
+ if (evidence.reviews.requireCodeOwnerReviews !== true &&
351
+ evidence.reviews.ownershipGaps.length > 0) {
352
+ warnings.push("CODEOWNERS 路由存在缺口,但未配置强制 CODEOWNER 审查。 ");
353
+ }
354
+ for (const source of evidence.unverifiedSignals) {
355
+ warnings.push(`证据来源 ${source} 无法完整验证。`);
356
+ }
357
+ return unique(warnings.map((warning) => warning.trim()));
358
+ }
359
+ /**
360
+ * Evaluate PR evidence with a stable, explicit decision priority.
361
+ * Known failures always remain authoritative even when other evidence is degraded.
362
+ */
363
+ export function evaluateQualityGate(evidence, blockingLabels) {
364
+ const configuredLabels = new Set(blockingLabels.map((label) => label.toLocaleLowerCase()));
365
+ const matchedBlockingLabels = evidence.pullRequest.labels.filter((label) => configuredLabels.has(label.toLocaleLowerCase()));
366
+ const contexts = requiredContextsState(evidence);
367
+ const reviewPolicyConfigured = hasReviewPolicy(evidence);
368
+ const mergePolicy = mergePolicyState(evidence);
369
+ const unverifiedSignals = unique([
370
+ ...evidence.unverifiedSignals,
371
+ ...evidence.ci.unverifiedSignals,
372
+ ]);
373
+ const unverified = new Set(unverifiedSignals);
374
+ const aggregateReviewUnverified = unverified.has("review_decision");
375
+ const restReviewsVerified = !unverified.has("reviews");
376
+ const failingReasons = [];
377
+ const pendingReasons = [];
378
+ const reviewReasons = [];
379
+ const policyReasons = [];
380
+ const mergeableState = evidence.pullRequest.mergeableState?.toLocaleLowerCase() ?? null;
381
+ const computingMergeableStates = new Set(["unknown", "queued", "checking", "pending"]);
382
+ const explicitlyFailingMergeableStates = new Set(["dirty", "unstable"]);
383
+ const nonBlockingMergeableStates = new Set(["clean", "has_hooks", "draft"]);
384
+ for (const item of [
385
+ ...evidence.ci.checkRuns.failing,
386
+ ...evidence.ci.commitStatuses.failing,
387
+ ]) {
388
+ failingReasons.push(`CI signal failed: ${item.name} (${item.source}).`);
389
+ }
390
+ if (evidence.pullRequest.mergeable === false) {
391
+ failingReasons.push("GitHub reports that the PR is not mergeable.");
392
+ }
393
+ if (mergeableState !== null && explicitlyFailingMergeableStates.has(mergeableState)) {
394
+ failingReasons.push(`GitHub reports a failing mergeability state: ${mergeableState}.`);
395
+ }
396
+ if (evidence.reviews.reviewDecision === "CHANGES_REQUESTED") {
397
+ failingReasons.push(evidence.reviews.changesRequestedUsers.length > 0
398
+ ? `Changes requested by: ${evidence.reviews.changesRequestedUsers.join(", ")}.`
399
+ : "A reviewer requested changes.");
400
+ }
401
+ if (aggregateReviewUnverified &&
402
+ restReviewsVerified &&
403
+ evidence.reviews.changesRequestedUsers.length > 0) {
404
+ failingReasons.push(`Changes requested by: ${evidence.reviews.changesRequestedUsers.join(", ")}.`);
405
+ }
406
+ for (const label of matchedBlockingLabels) {
407
+ failingReasons.push(`Blocking label matched: ${label}.`);
408
+ }
409
+ for (const item of [
410
+ ...evidence.ci.checkRuns.pending,
411
+ ...evidence.ci.commitStatuses.pending,
412
+ ]) {
413
+ pendingReasons.push(`CI signal is pending: ${item.name} (${item.source}).`);
414
+ }
415
+ if (evidence.pullRequest.mergeable === null) {
416
+ pendingReasons.push("GitHub has not finished computing PR mergeability.");
417
+ }
418
+ if (mergeableState !== null && computingMergeableStates.has(mergeableState)) {
419
+ pendingReasons.push(`GitHub mergeability state is still computing: ${mergeableState}.`);
420
+ }
421
+ if (mergeableState === "behind") {
422
+ pendingReasons.push("The pull request head is behind the base branch and must be updated.");
423
+ }
424
+ if (contexts.missing.length > 0) {
425
+ pendingReasons.push(`Required status contexts are missing: ${contexts.missing.join(", ")}.`);
426
+ }
427
+ if (evidence.pullRequest.draft)
428
+ reviewReasons.push("The pull request is still a draft.");
429
+ if (evidence.reviews.reviewDecision === "REVIEW_REQUIRED") {
430
+ reviewReasons.push("GitHub reports that review is required.");
431
+ }
432
+ if (evidence.reviews.reviewDecision === null &&
433
+ !unverified.has("reviews") &&
434
+ evidence.reviews.requiredApprovals !== null &&
435
+ evidence.reviews.requiredApprovals > evidence.reviews.approvedUsers.length) {
436
+ reviewReasons.push(`Approvals are incomplete: ${evidence.reviews.approvedUsers.length}/${evidence.reviews.requiredApprovals}.`);
437
+ }
438
+ const criticalSources = [
439
+ "branch_protection",
440
+ "branch_rules",
441
+ "check_runs",
442
+ "commit_statuses",
443
+ ];
444
+ if (aggregateReviewUnverified) {
445
+ criticalSources.push("review_decision");
446
+ policyReasons.push("Aggregate review decision is unavailable; review blockers cannot be fully ruled out.");
447
+ if (!restReviewsVerified)
448
+ criticalSources.push("reviews");
449
+ }
450
+ if (reviewPolicyConfigured && evidence.reviews.reviewDecision === null) {
451
+ criticalSources.push("review_decision");
452
+ policyReasons.push("Aggregate review decision is unavailable for the configured review policy.");
453
+ }
454
+ if (evidence.reviews.requireCodeOwnerReviews === true) {
455
+ criticalSources.push("code_owner_review", "codeowners", "changed_files");
456
+ }
457
+ const missingCriticalSources = unique(criticalSources.filter((source) => unverified.has(source)));
458
+ if (missingCriticalSources.length > 0) {
459
+ policyReasons.push(`Critical evidence sources are incomplete: ${missingCriticalSources.join(", ")}.`);
460
+ }
461
+ if (evidence.reviews.requireCodeOwnerReviews === true &&
462
+ evidence.reviews.reviewDecision !== "APPROVED" &&
463
+ evidence.reviews.codeOwnerReviewSatisfied === null) {
464
+ policyReasons.push("Required CODEOWNER review 无法验证。 ");
465
+ }
466
+ if (mergePolicy.unmodeledRules.length > 0) {
467
+ policyReasons.push(`Unmodeled merge rules cannot be verified: ${mergePolicy.unmodeledRules.join(", ")}.`);
468
+ }
469
+ if (mergeableState === "blocked") {
470
+ policyReasons.push("GitHub reports that merging is blocked, but the underlying check or review requirement must be resolved from its specific evidence.");
471
+ }
472
+ else if (mergeableState !== null &&
473
+ !computingMergeableStates.has(mergeableState) &&
474
+ mergeableState !== "behind" &&
475
+ !explicitlyFailingMergeableStates.has(mergeableState) &&
476
+ !nonBlockingMergeableStates.has(mergeableState)) {
477
+ policyReasons.push(`GitHub returned an unrecognized mergeability state: ${mergeableState}.`);
478
+ }
479
+ if (!unverified.has("branch_protection") &&
480
+ !unverified.has("branch_rules") &&
481
+ !mergePolicy.hasAnyPolicy) {
482
+ policyReasons.push("No verified merge-relevant protection policy was found.");
483
+ }
484
+ let conclusion;
485
+ if (failingReasons.length > 0)
486
+ conclusion = "failing";
487
+ else if (pendingReasons.length > 0)
488
+ conclusion = "pending";
489
+ else if (reviewReasons.length > 0)
490
+ conclusion = "needs_review";
491
+ else if (policyReasons.length > 0)
492
+ conclusion = "policy_gap";
493
+ else if (evidence.ci.checkRuns.passing.length === 0 &&
494
+ evidence.ci.commitStatuses.passing.length === 0 &&
495
+ !contexts.satisfiedByPassingOrSkipped &&
496
+ !(reviewPolicyConfigured && evidence.reviews.reviewDecision === "APPROVED")) {
497
+ conclusion = "no_evidence";
498
+ }
499
+ else
500
+ conclusion = "passing";
501
+ const noEvidenceReasons = conclusion === "no_evidence"
502
+ ? ["No verified passing CI signal is available for this pull request."]
503
+ : [];
504
+ return {
505
+ conclusion,
506
+ blockers: unique([
507
+ ...failingReasons,
508
+ ...pendingReasons,
509
+ ...reviewReasons,
510
+ ...policyReasons.map((reason) => reason.trim()),
511
+ ...noEvidenceReasons,
512
+ ]),
513
+ warnings: sourceWarnings(evidence),
514
+ nextActions: nextActionsFor(conclusion),
515
+ matchedBlockingLabels,
516
+ missingRequiredContexts: contexts.missing,
517
+ };
518
+ }
519
+ function evaluateRefQualityGate(ci) {
520
+ const failingReasons = [
521
+ ...ci.checkRuns.failing,
522
+ ...ci.commitStatuses.failing,
523
+ ].map((item) => `CI signal failed: ${item.name} (${item.source}).`);
524
+ const pendingReasons = [
525
+ ...ci.checkRuns.pending,
526
+ ...ci.commitStatuses.pending,
527
+ ].map((item) => `CI signal is pending: ${item.name} (${item.source}).`);
528
+ const warnings = ci.unverifiedSignals.map((source) => `CI evidence source ${source} could not be fully verified.`);
529
+ let conclusion;
530
+ if (failingReasons.length > 0)
531
+ conclusion = "failing";
532
+ else if (pendingReasons.length > 0)
533
+ conclusion = "pending";
534
+ else if (ci.unverifiedSignals.length > 0 ||
535
+ ci.totalSignals === 0 ||
536
+ (ci.checkRuns.passing.length === 0 && ci.commitStatuses.passing.length === 0)) {
537
+ conclusion = "no_evidence";
538
+ }
539
+ else
540
+ conclusion = "passing";
541
+ return {
542
+ conclusion,
543
+ blockers: unique([
544
+ ...failingReasons,
545
+ ...pendingReasons,
546
+ ...(conclusion === "no_evidence"
547
+ ? ["No complete, verified passing CI evidence is available for this ref."]
548
+ : []),
549
+ ]),
550
+ warnings,
551
+ nextActions: nextActionsFor(conclusion),
552
+ matchedBlockingLabels: [],
553
+ missingRequiredContexts: [],
554
+ };
555
+ }
556
+ function buildPullRequestResult(evidence, decision) {
557
+ const unverifiedSignals = unique([
558
+ ...evidence.unverifiedSignals,
559
+ ...evidence.ci.unverifiedSignals,
560
+ ]);
561
+ return {
562
+ contextLabel: `PR #${evidence.pullRequest.number} (${evidence.pullRequest.title})`,
563
+ headSha: evidence.pullRequest.headSha,
564
+ conclusion: decision.conclusion,
565
+ categories: categoriesFromCheckRuns(evidence.ci.checkRuns),
566
+ totalChecks: evidence.ci.checkRuns.total,
567
+ evidence: {
568
+ scope: "pull_request",
569
+ checks: {
570
+ checkRuns: evidence.ci.checkRuns,
571
+ commitStatuses: evidence.ci.commitStatuses,
572
+ totalSignals: evidence.ci.totalSignals,
573
+ requiredContexts: uniqueCaseInsensitive(evidence.branchProtection.requiredStatusContexts),
574
+ requiredChecks: evidence.branchProtection.requiredStatusChecks,
575
+ missingRequiredContexts: decision.missingRequiredContexts,
576
+ },
577
+ pullRequest: {
578
+ draft: evidence.pullRequest.draft,
579
+ mergeable: evidence.pullRequest.mergeable,
580
+ mergeableState: evidence.pullRequest.mergeableState,
581
+ baseBranch: evidence.pullRequest.baseBranch,
582
+ },
583
+ reviews: {
584
+ reviewDecision: evidence.reviews.reviewDecision,
585
+ approved: evidence.reviews.approvedUsers.length,
586
+ approvedUsers: evidence.reviews.approvedUsers,
587
+ changesRequestedUsers: evidence.reviews.changesRequestedUsers,
588
+ requestedUsers: evidence.reviews.requestedUsers,
589
+ requestedTeams: evidence.reviews.requestedTeams,
590
+ required: evidence.reviews.requiredApprovals,
591
+ requireCodeOwnerReviews: evidence.reviews.requireCodeOwnerReviews,
592
+ codeOwnerReviewSatisfied: evidence.reviews.codeOwnerReviewSatisfied,
593
+ ownershipGaps: evidence.reviews.ownershipGaps,
594
+ },
595
+ branchProtection: {
596
+ classicEnabled: evidence.branchProtection.classicEnabled,
597
+ rulesetRuleTypes: evidence.branchProtection.rulesetRuleTypes,
598
+ pullRequestRuleRequirements: evidence.branchProtection.pullRequestRuleRequirements,
599
+ },
600
+ labels: {
601
+ all: evidence.pullRequest.labels,
602
+ blocking: decision.matchedBlockingLabels,
603
+ },
604
+ linkedIssues: evidence.linkedIssues,
605
+ },
606
+ blockers: decision.blockers,
607
+ warnings: decision.warnings,
608
+ nextActions: decision.nextActions,
609
+ degraded: evidence.degraded || unverifiedSignals.length > 0,
610
+ unverifiedSignals,
611
+ errors: evidence.errors,
612
+ };
613
+ }
614
+ function buildRefResult(refName, headSha, ci, decision) {
615
+ return {
616
+ contextLabel: `ref: ${refName}`,
114
617
  headSha,
115
- conclusion: overallConclusion,
116
- categories: cats,
117
- totalChecks: allRuns.length,
618
+ conclusion: decision.conclusion,
619
+ categories: categoriesFromCheckRuns(ci.checkRuns),
620
+ totalChecks: ci.checkRuns.total,
621
+ evidence: {
622
+ scope: "ref",
623
+ checks: {
624
+ checkRuns: ci.checkRuns,
625
+ commitStatuses: ci.commitStatuses,
626
+ totalSignals: ci.totalSignals,
627
+ requiredContexts: [],
628
+ requiredChecks: [],
629
+ missingRequiredContexts: [],
630
+ },
631
+ pullRequest: null,
632
+ reviews: null,
633
+ branchProtection: null,
634
+ labels: null,
635
+ linkedIssues: null,
636
+ },
637
+ blockers: decision.blockers,
638
+ warnings: decision.warnings,
639
+ nextActions: decision.nextActions,
640
+ degraded: ci.unverifiedSignals.length > 0,
641
+ unverifiedSignals: unique(ci.unverifiedSignals),
642
+ errors: ci.errors,
118
643
  };
644
+ }
645
+ function renderQualityGateMarkdown(result) {
646
+ const inline = (value, maxLength = 300) => safeMarkdownInline(value, { maxLength });
119
647
  const lines = [
120
- `# Quality Gate Status - ${contextLabel}`,
648
+ `# Quality Gate Status - ${inline(result.contextLabel, 400)}`,
649
+ "",
650
+ `**Commit:** ${inline(result.headSha.slice(0, 40), 80)}`,
651
+ `**Conclusion:** ${inline(result.conclusion)}`,
652
+ `**Evidence degraded:** ${result.degraded ? "yes" : "no"}`,
121
653
  "",
122
- `**Commit:** \`${headSha.slice(0, 8)}\``,
123
- `**Conclusion:** ${conclusionLabel}`,
654
+ "| Check runs | Count |",
655
+ "|---|---:|",
656
+ `| Passing | ${result.categories.passing.length} |`,
657
+ `| Failing | ${result.categories.failing.length} |`,
658
+ `| Pending | ${result.categories.pending.length} |`,
659
+ `| Skipped | ${result.categories.skipped.length} |`,
660
+ `| Total | ${result.totalChecks} |`,
124
661
  "",
125
- `| | Count |`,
126
- `|---|---|`,
127
- `| Passing | ${cats.passing.length} |`,
128
- `| Failing | ${cats.failing.length} |`,
129
- `| Pending | ${cats.pending.length} |`,
130
- `| Skipped | ${cats.skipped.length} |`,
131
- `| Total | ${allRuns.length} |`,
662
+ `**All CI signals:** ${result.evidence.checks.totalSignals}`,
132
663
  ];
133
- if (cats.failing.length > 0) {
134
- lines.push("", "## [FAIL] Failing Checks");
135
- cats.failing.forEach((c) => {
136
- const link = c.url ? ` - [view](${c.url})` : "";
137
- lines.push(`- **${c.name}**: ${c.conclusion}${link}`);
138
- });
664
+ const reviewDetails = result.evidence.reviews;
665
+ if (reviewDetails) {
666
+ const reviewLines = [
667
+ reviewDetails.approvedUsers.length > 0
668
+ ? `- Approved: ${reviewDetails.approvedUsers.map((user) => inline(user)).join(", ")}`
669
+ : null,
670
+ reviewDetails.changesRequestedUsers.length > 0
671
+ ? `- Changes requested: ${reviewDetails.changesRequestedUsers.map((user) => inline(user)).join(", ")}`
672
+ : null,
673
+ reviewDetails.requestedUsers.length > 0
674
+ ? `- Requested users: ${reviewDetails.requestedUsers.map((user) => inline(user)).join(", ")}`
675
+ : null,
676
+ reviewDetails.requestedTeams.length > 0
677
+ ? `- Requested teams: ${reviewDetails.requestedTeams.map((team) => inline(team)).join(", ")}`
678
+ : null,
679
+ ].filter((line) => line !== null);
680
+ if (reviewLines.length > 0)
681
+ lines.push("", "## Review Details", ...reviewLines);
139
682
  }
140
- if (cats.pending.length > 0) {
141
- lines.push("", "## [PENDING] Pending Checks");
142
- cats.pending.forEach((c) => lines.push(`- **${c.name}**: ${c.status}`));
683
+ if (result.blockers.length > 0) {
684
+ lines.push("", "## Blockers", ...result.blockers.map((item) => `- ${inline(item, 500)}`));
143
685
  }
144
- if (cats.passing.length > 0) {
145
- lines.push("", "## [PASS] Passing Checks");
146
- cats.passing.forEach((c) => lines.push(`- ${c.name}`));
686
+ if (result.warnings.length > 0) {
687
+ lines.push("", "## Warnings", ...result.warnings.map((item) => `- ${inline(item, 500)}`));
147
688
  }
148
- lines.push("", "## Next Actions");
149
- if (cats.failing.length > 0) {
150
- lines.push("- Fix the failing checks listed above before proceeding.", "- Use `review_pr_against_standard` for deeper analysis of PR issues.");
689
+ if (result.errors.length > 0) {
690
+ lines.push("", "## Notes", ...result.errors.map((error) => `- ${inline(error, 500)}`));
151
691
  }
152
- else if (cats.pending.length > 0) {
153
- lines.push("- Wait for pending checks to complete, then re-run this tool.");
692
+ if (result.categories.failing.length > 0) {
693
+ lines.push("", "## Failing Check Runs", ...result.categories.failing.map((item) => `- **${inline(item.name)}**: ${inline(item.conclusion ?? "unknown")}`));
694
+ }
695
+ if (result.categories.pending.length > 0) {
696
+ lines.push("", "## Pending Check Runs", ...result.categories.pending.map((item) => `- **${inline(item.name)}**: ${inline(item.status ?? "unknown")}`));
697
+ }
698
+ lines.push("", "## Next Actions", ...result.nextActions.map((item) => `- ${inline(item, 500)}`));
699
+ return lines.join("\n");
700
+ }
701
+ // ---------------------------------------------------------------------------
702
+ // Core handler
703
+ // ---------------------------------------------------------------------------
704
+ function normalizeCommitRef(input) {
705
+ return input.replace(/^refs\/(?=(?:heads|tags)\/)/, "");
706
+ }
707
+ export async function handleQualityGateStatus(params, ref, octokit) {
708
+ let structured;
709
+ if (params.pullNumber) {
710
+ const evidence = await collectPullRequestEvidence({ pullNumber: params.pullNumber }, ref, octokit);
711
+ const decision = evaluateQualityGate(evidence, params.blockingLabels ?? DEFAULT_BLOCKING_LABELS);
712
+ structured = buildPullRequestResult(evidence, decision);
713
+ }
714
+ else if (params.ref) {
715
+ const { data: commit } = await octokit.repos.getCommit({
716
+ owner: ref.owner,
717
+ repo: ref.repo,
718
+ ref: normalizeCommitRef(params.ref),
719
+ });
720
+ const headSha = commit.sha;
721
+ const evidence = await collectCiEvidence(ref, headSha, octokit);
722
+ structured = buildRefResult(params.ref, headSha, evidence, evaluateRefQualityGate(evidence));
154
723
  }
155
724
  else {
156
- lines.push("- All checks pass. Safe to request review or merge.", "- Run `release_readiness_check` for a full pre-release assessment.");
725
+ throw new Error("Either pullNumber or ref is required.");
157
726
  }
158
- return { text: lines.join("\n"), structured };
727
+ return { text: renderQualityGateMarkdown(structured), structured };
159
728
  }
160
729
  // ---------------------------------------------------------------------------
161
730
  // Registration
@@ -163,14 +732,15 @@ export async function handleQualityGateStatus(params, ref, octokit) {
163
732
  export function registerQualityGateStatusTool(server) {
164
733
  server.registerTool("quality_gate_status", {
165
734
  title: "Quality Gate Status",
166
- description: `Read check-run results for a pull request or git ref.
735
+ description: `Evaluate real merge-gate evidence for a pull request or CI evidence for a git ref.
167
736
 
168
737
  Args:
169
738
  - owner, repo: Repository coordinates.
170
- - pullNumber (number?): PR number (preferred).
171
- - ref (string?): Branch name or commit SHA.
739
+ - pullNumber (number?): PR number (preferred); evaluates CI, reviews, policy, labels, and mergeability.
740
+ - ref (string?): Branch name or commit SHA; evaluates CI only.
741
+ - blockingLabels (string[]): Exact case-insensitive PR labels that block merging. Pass [] to disable.
172
742
 
173
- Returns: Summary of all check runs with pass/fail/pending counts and next actions.`,
743
+ Returns: A structured evidence packet, blockers, warnings, next actions, and a conservative conclusion.`,
174
744
  inputSchema: QualityGateInputSchema,
175
745
  outputSchema: QualityGateOutputSchema,
176
746
  annotations: {