@imdeadpool/guardex 7.1.1 → 8.2.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 (51) hide show
  1. package/README.md +123 -322
  2. package/package.json +23 -5
  3. package/skills/gitguardex/SKILL.md +83 -3
  4. package/src/agents/finish.js +15 -0
  5. package/src/ci-init/index.js +0 -1
  6. package/src/cli/args.js +142 -3
  7. package/src/cli/commands/branch.js +294 -14
  8. package/src/cli/commands/claude.js +15 -0
  9. package/src/cli/commands/doctor.js +26 -0
  10. package/src/cli/commands/onboard.js +293 -0
  11. package/src/cli/commands/prompt.js +15 -3
  12. package/src/cli/commands/review.js +18 -0
  13. package/src/cli/commands/setup.js +8 -6
  14. package/src/cli/commands/status.js +12 -0
  15. package/src/cli/main.js +2 -0
  16. package/src/cli/shared-locks.js +304 -0
  17. package/src/context.js +21 -3
  18. package/src/core/runtime.js +33 -1
  19. package/src/doctor/index.js +58 -6
  20. package/src/finish/heartbeat.js +169 -0
  21. package/src/finish/index.js +165 -18
  22. package/src/finish/progress.js +316 -0
  23. package/src/finish/review-gate.js +453 -32
  24. package/src/github-api.js +59 -0
  25. package/src/mcp/collect.js +155 -19
  26. package/src/mcp/server.js +35 -19
  27. package/src/output/index.js +210 -0
  28. package/src/pr-checks.js +121 -0
  29. package/src/pr-review.js +581 -51
  30. package/src/pr.js +143 -21
  31. package/src/provider-binary.js +101 -0
  32. package/src/review-diff.js +116 -0
  33. package/src/review-fix.js +229 -0
  34. package/src/sandbox/index.js +11 -5
  35. package/src/scaffold/index.js +4 -16
  36. package/src/shared-git-state.js +566 -0
  37. package/templates/AGENTS.multiagent-safety.md +63 -11
  38. package/templates/AGENTS.multiagent-safety.min.md +1 -0
  39. package/templates/codex/skills/gitguardex/SKILL.md +83 -3
  40. package/templates/githooks/post-checkout +4 -9
  41. package/templates/githooks/pre-commit +17 -1
  42. package/templates/github/workflows/README.md +30 -23
  43. package/templates/scripts/agent-autofinish-watch.sh +280 -0
  44. package/templates/scripts/agent-branch-finish.sh +354 -23
  45. package/templates/scripts/agent-branch-start.sh +49 -22
  46. package/templates/scripts/agent-claude-stop-finish.sh +194 -0
  47. package/templates/scripts/agent-file-locks.py +198 -29
  48. package/templates/scripts/agent-preflight.sh +14 -2
  49. package/templates/scripts/agent-stalled-report.sh +40 -0
  50. package/templates/scripts/codex-agent.sh +10 -63
  51. package/templates/github/workflows/cr.yml +0 -46
@@ -11,10 +11,14 @@ const { run } = require('../core/runtime');
11
11
  const { TOOL_NAME } = require('../context');
12
12
  const pr = require('../pr');
13
13
  const prReview = require('../pr-review');
14
+ const reviewFix = require('../review-fix');
15
+ const { mapWorktreePathsByBranch } = require('../git');
14
16
 
15
17
  const DEFAULT_GATE_TIMEOUT_SECONDS = 1800; // 30 min — CI can be slow.
16
18
  const DEFAULT_GATE_POLL_SECONDS = 15;
17
19
  const DEFAULT_NO_CHECKS_GRACE_SECONDS = 60; // let CI register check runs after promote.
20
+ const DEFAULT_PR_HEAD_TIMEOUT_SECONDS = 60;
21
+ const DEFAULT_PR_HEAD_POLL_SECONDS = 2;
18
22
  // GitHub mergeStateStatus values that mean "mergeable under current protection".
19
23
  const MERGEABLE_STATES = new Set(['CLEAN', 'HAS_HOOKS']);
20
24
  // mergeStateStatus values that mean "GitHub will not allow this merge as-is".
@@ -26,6 +30,82 @@ function gateLog(message) {
26
30
  console.log(`[${TOOL_NAME}] [gate] ${message}`);
27
31
  }
28
32
 
33
+ function reportProgress(progress, method, stage, detail) {
34
+ if (progress && typeof progress[method] === 'function') {
35
+ progress[method](stage, detail);
36
+ }
37
+ }
38
+
39
+ function requireGhAction(result, failureMessage) {
40
+ if (result && result.ok === false) {
41
+ throw new Error(
42
+ `${failureMessage}${result.output ? `\n${result.output}` : ''}`,
43
+ );
44
+ }
45
+ }
46
+
47
+ /**
48
+ * A review that never reached the PR does not count as a review.
49
+ *
50
+ * `runPrReview` can come back `posted: false` — GitHub auth unavailable to the
51
+ * runner, or any path that writes a local artifact instead of posting. Treating
52
+ * that as a pass makes two failures look like success: an in-memory verdict
53
+ * cannot be audited after the merge, and a provider that returned nothing is
54
+ * indistinguishable from a clean review.
55
+ */
56
+ function requirePostedReview(review, prNumber) {
57
+ if (review.posted) return;
58
+ const why = review.reason === 'github-auth-unavailable'
59
+ ? 'GitHub auth was unavailable to the review runner'
60
+ : `the review runner reported posted=${JSON.stringify(review.posted)}`;
61
+ throw new Error(
62
+ `review gate: the AI review was not posted to PR #${prNumber} (${why}). Refusing to merge — `
63
+ + 'an unposted review leaves no evidence the diff was examined, and a provider that returns '
64
+ + 'nothing then looks exactly like a clean pass.'
65
+ + (review.artifactPath ? `\nLocal artifact: ${review.artifactPath}` : '')
66
+ + '\nFix the provider/auth issue and re-run, or bypass with --skip-review-gate.',
67
+ );
68
+ }
69
+
70
+ /** The commit checked out in `cwd`, or '' when git cannot answer. */
71
+ function readHeadSha(cwd) {
72
+ const result = run('git', ['-C', cwd, 'rev-parse', 'HEAD'], { cwd, allowFailure: true });
73
+ return result.status === 0 ? String(result.stdout || '').trim() : '';
74
+ }
75
+
76
+ /** Worktree holding `branch`, or `repoRoot` when git cannot tell us. */
77
+ function resolveWorktreeForBranch(repoRoot, branch) {
78
+ try {
79
+ return mapWorktreePathsByBranch(repoRoot).get(branch) || repoRoot;
80
+ } catch (_error) {
81
+ return repoRoot;
82
+ }
83
+ }
84
+
85
+ /** Wait until GitHub exposes the pushed commit before fetching the PR diff. */
86
+ function waitForPullRequestHead(repoRoot, branch, expectedHeadSha, options = {}) {
87
+ const expected = String(expectedHeadSha || '').trim();
88
+ if (!expected) return { status: 'missing-head' };
89
+
90
+ const timeoutSeconds = options.timeoutSeconds || DEFAULT_PR_HEAD_TIMEOUT_SECONDS;
91
+ const pollSeconds = options.pollSeconds || DEFAULT_PR_HEAD_POLL_SECONDS;
92
+ const sleep = options.sleep || ((seconds) => run('sleep', [String(seconds)], { cwd: repoRoot }));
93
+ const now = options.now || (() => Date.now());
94
+ const getStatus = options.getStatus || ((r, b) => pr.getPullRequestStatus(r, b));
95
+ const deadline = now() + timeoutSeconds * 1000;
96
+ let snapshot;
97
+
98
+ // eslint-disable-next-line no-constant-condition
99
+ while (true) {
100
+ snapshot = getStatus(repoRoot, branch);
101
+ if (snapshot?.headSha === expected) return { status: 'current', pr: snapshot };
102
+ if (now() >= deadline) {
103
+ return snapshot ? { status: 'stale-head', pr: snapshot } : { status: 'no-pr' };
104
+ }
105
+ sleep(pollSeconds);
106
+ }
107
+ }
108
+
29
109
  /**
30
110
  * Poll the PR's CI until it settles. Fail-closed: red checks, timeout, or a
31
111
  * check-less PR (after a grace window) all return a non-green status the caller
@@ -40,7 +120,7 @@ function gateLog(message) {
40
120
  * - a check-less PR is only declared `no-checks` after a grace window, so a freshly
41
121
  * promoted PR whose checks have not registered yet is not misread.
42
122
  *
43
- * @returns {{status: 'green'|'checks-failed'|'merge-blocked'|'no-checks'|'timeout'|'no-pr', pr?: object}}
123
+ * @returns {{status: 'green'|'checks-failed'|'merge-blocked'|'no-checks'|'stale-head'|'timeout'|'no-pr', pr?: object}}
44
124
  */
45
125
  function waitForGreenCi(repoRoot, branch, options = {}) {
46
126
  const timeoutSeconds = options.timeoutSeconds || DEFAULT_GATE_TIMEOUT_SECONDS;
@@ -50,6 +130,26 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
50
130
  const sleep = options.sleep || ((seconds) => run('sleep', [String(seconds)], { cwd: repoRoot }));
51
131
  const now = options.now || (() => Date.now());
52
132
  const getStatus = options.getStatus || ((r, b) => pr.getPullRequestStatus(r, b));
133
+ // Commit this wait is allowed to judge. Set when the run itself pushed (an
134
+ // auto-fix round), where the checks GitHub reports can still belong to the
135
+ // commit that push replaced.
136
+ const expectHeadSha = String(options.expectHeadSha || '').trim();
137
+ // Checks already failing on the base branch. Empty (the default) reproduces
138
+ // the original absolute-green behavior exactly.
139
+ const baseline = options.baselineFailures instanceof Set ? options.baselineFailures : new Set();
140
+ const baselineMode = baseline.size > 0;
141
+ // Loop-invariant, so build them once. In baseline mode UNSTABLE moves from
142
+ // "blocked" to "trusted": it is exactly what GitHub reports for a red
143
+ // non-required check, and those failures are cleared as pre-existing below.
144
+ // BLOCKED is only trusted when all failed checks are known baseline failures
145
+ // and GitHub still says the branch is mergeable; DIRTY/BEHIND stay blocking
146
+ // either way.
147
+ const blockedStates = baselineMode
148
+ ? new Set([...BLOCKED_STATES].filter((state) => state !== 'UNSTABLE'))
149
+ : BLOCKED_STATES;
150
+ const trustedStates = baselineMode
151
+ ? new Set([...MERGEABLE_STATES, 'UNSTABLE'])
152
+ : MERGEABLE_STATES;
53
153
 
54
154
  const start = now();
55
155
  const deadline = start + timeoutSeconds * 1000;
@@ -59,22 +159,70 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
59
159
  while (true) {
60
160
  const snap = getStatus(repoRoot, branch);
61
161
  if (!snap) return { status: 'no-pr' };
162
+ // A verdict about the wrong commit is not a verdict. Judge nothing — not
163
+ // green, not even a failure — until the PR head matches the commit we
164
+ // pushed. Fail closed on a missing headSha too: unable to prove the rollup
165
+ // is current is the same risk as knowing it is not.
166
+ if (expectHeadSha && snap.headSha !== expectHeadSha) {
167
+ if (now() >= deadline) return { status: 'stale-head', pr: snap };
168
+ sleep(pollSeconds);
169
+ // eslint-disable-next-line no-continue
170
+ continue;
171
+ }
62
172
  const c = snap.checks;
63
- // A failed or cancelled check is terminal and never a pass.
64
- if (c.failed > 0 || c.cancelled > 0) return { status: 'checks-failed', pr: snap };
173
+ // A failed or cancelled check is terminal and never a pass — UNLESS it is
174
+ // already failing on the base branch, in which case this change did not
175
+ // introduce it. A failing check with no resolvable name always blocks: an
176
+ // unnameable failure cannot be proven pre-existing.
177
+ const failedNames = Array.isArray(snap.failedNames) ? snap.failedNames : [];
178
+ // Coerce every counter: a snapshot missing one would make the sums NaN, and
179
+ // `NaN > 0` is false — which would wave a failing check straight through.
180
+ const count = (key) => Number(c[key]) || 0;
181
+ const failingCount = count('failed') + count('cancelled');
182
+ const settled = count('pending') === 0;
183
+ const namedFailures = failedNames.length === failingCount;
184
+ const novelFailures = failedNames.filter((name) => !baseline.has(name));
185
+ const onlyBaselineFailures = baselineMode
186
+ && failingCount > 0
187
+ && namedFailures
188
+ && novelFailures.length === 0;
189
+ if (failingCount > 0) {
190
+ if (!baselineMode || !namedFailures || novelFailures.length > 0) {
191
+ return { status: 'checks-failed', pr: snap, newFailures: novelFailures };
192
+ }
193
+ }
65
194
 
66
195
  const mss = snap.mergeStateStatus;
67
- // GitHub says this can't merge as-is and won't self-resolve within a finish run.
68
- if (mss && BLOCKED_STATES.has(mss)) return { status: 'merge-blocked', pr: snap };
69
-
70
- const settled = c.pending === 0;
71
196
  const mergeable = !snap.isDraft && snap.mergeable === 'MERGEABLE';
197
+ // In baseline mode GitHub can still call the PR BLOCKED solely because a
198
+ // known-red, non-required check failed. If every failure is already in the
199
+ // base baseline and GitHub still says the branch is mergeable, that state is
200
+ // the same "no new failures" verdict as UNSTABLE.
201
+ const baselineBlockedByKnownChecks = mss === 'BLOCKED' && mergeable && onlyBaselineFailures;
202
+ // GitHub says this can't merge as-is. Some BLOCKED/UNSTABLE snapshots are
203
+ // just "required checks are still pending" immediately after a draft PR is
204
+ // promoted to ready, so wait for pending checks to settle before treating
205
+ // those states as terminal. DIRTY/BEHIND do not self-resolve within a finish
206
+ // run and stay immediate blockers.
207
+ if (mss && (mss === 'DIRTY' || mss === 'BEHIND')) {
208
+ return { status: 'merge-blocked', pr: snap };
209
+ }
210
+ if (mss && blockedStates.has(mss) && settled && !baselineBlockedByKnownChecks) {
211
+ return { status: 'merge-blocked', pr: snap };
212
+ }
213
+
72
214
  const hasChecks = c.total > 0;
73
215
  // Trust GitHub's CLEAN/HAS_HOOKS verdict; with no verdict, demand all-success
74
216
  // (every check SUCCESS, zero `other`/ambiguous states).
75
- const trusted = mss
76
- ? MERGEABLE_STATES.has(mss)
77
- : (c.other === 0 && c.success === c.total);
217
+ //
218
+ // Baseline mode widens both halves by exactly the failures already proven
219
+ // pre-existing: UNSTABLE joins the trusted verdicts, and the no-verdict
220
+ // fallback accounts every check as success-or-cleared-failure. `other` must
221
+ // still be zero either way — an ambiguous state is never a pass.
222
+ const allAccountedFor = baselineMode
223
+ ? count('other') === 0 && count('success') + failingCount === count('total')
224
+ : count('other') === 0 && count('success') === count('total');
225
+ const trusted = baselineBlockedByKnownChecks || (mss ? trustedStates.has(mss) : allAccountedFor);
78
226
 
79
227
  if (settled && mergeable && hasChecks && trusted) return { status: 'green', pr: snap };
80
228
  if (settled && mergeable && !hasChecks && (mss ? MERGEABLE_STATES.has(mss) : true)) {
@@ -88,95 +236,368 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
88
236
  }
89
237
  }
90
238
 
239
+ /**
240
+ * Files that carried a blocking finding earlier but can no longer be accounted
241
+ * for: not edited by any auto-fix, and not mentioned by the latest review.
242
+ *
243
+ * Exists because provider output varies run to run. Observed in the wild: a HIGH
244
+ * ("the compact card drops the set-total price line") blocked round 2, the fix
245
+ * round edited a different file entirely, and round 3 just did not report it —
246
+ * flipping the gate to pass with the bug still in the branch. Absence of a
247
+ * finding is not evidence of a fix.
248
+ *
249
+ * @param {Set<string>} blockedPaths every file that has held a blocking finding
250
+ * @param {Set<string>} repairedPaths every file an auto-fix actually edited
251
+ * @param {Array<object>} currentFindings the latest review's findings, any severity
252
+ * @returns {string[]} paths whose disappearance is unexplained
253
+ */
254
+ function resolveCarriedFindings(blockedPaths, repairedPaths, currentFindings) {
255
+ const stillReported = new Set(
256
+ (Array.isArray(currentFindings) ? currentFindings : [])
257
+ .map((finding) => finding && finding.path)
258
+ .filter(Boolean),
259
+ );
260
+ return [...blockedPaths]
261
+ .filter((path) => !repairedPaths.has(path) && !stillReported.has(path))
262
+ .sort();
263
+ }
264
+
91
265
  /**
92
266
  * Enforce the merge gate for `branch`. Throws (blocking the merge) unless the PR
93
267
  * passes a clean AI review AND green CI AND GitHub reports it mergeable. Returns
94
268
  * `{ prNumber }` on pass; the caller then proceeds to the real merge.
95
269
  */
96
- function runReviewGate({ repoRoot, branch, baseBranch, options = {} }, deps = {}) {
270
+ function runReviewGate({
271
+ repoRoot, worktreePath, branch, baseBranch, options = {}, progress,
272
+ }, deps = {}) {
97
273
  const openPullRequest = deps.openPullRequest || pr.openPullRequest;
98
274
  const runPrReview = deps.runPrReview || prReview.runPrReview;
99
275
  const markReady = deps.markPullRequestReady || pr.markPullRequestReady;
276
+ const markDraft = deps.markPullRequestDraft || pr.markPullRequestDraft;
100
277
  const evaluate = deps.evaluateReviewGate || prReview.evaluateReviewGate;
278
+ const resolveThreads = deps.resolveOutdatedReviewThreads || prReview.resolveOutdatedReviewThreads;
101
279
  const waitGreen = deps.waitForGreenCi || waitForGreenCi;
280
+ const readBaseline = deps.baselineFailures || pr.baselineFailures;
281
+ const runFix = deps.runReviewFix || reviewFix.runReviewFix;
282
+ const pushBranch = deps.pushBranch || pr.pushBranch;
283
+ const headSha = deps.readHeadSha || readHeadSha;
284
+ const waitHead = deps.waitForPullRequestHead || waitForPullRequestHead;
102
285
 
103
286
  const provider = options.reviewProvider || 'codex';
104
287
  const requireChecks = !options.allowNoChecks;
288
+ // Fix rounds are opt-in and bounded: an unfixable finding must fall through to
289
+ // the block rather than spin the provider forever.
290
+ const maxFixRounds = options.gateAutofix ? Math.max(1, options.gateAutofixRounds || 1) : 0;
291
+ // Fixes are edits to the checked-out branch, so they run in the worktree that
292
+ // holds it — repoRoot may be the primary checkout sitting on a protected base.
293
+ const fixCwd = worktreePath || resolveWorktreeForBranch(repoRoot, branch);
105
294
 
106
- // 1. Ensure a PR exists (push + open as draft so CI is deferred until the
107
- // review passes and we explicitly promote).
108
- const opened = openPullRequest({ repoRoot, branch, base: baseBranch, push: true });
295
+ // 1. Ensure a PR exists (push + open as draft, so promoting to ready is what
296
+ // starts CI and we control when that happens).
297
+ reportProgress(progress, 'start', 'pr', 'pushing branch and opening or reusing a PR');
298
+ let opened;
299
+ try {
300
+ opened = openPullRequest({ repoRoot, branch, base: baseBranch, push: true });
301
+ } catch (error) {
302
+ reportProgress(progress, 'fail', 'pr', error.message);
303
+ throw error;
304
+ }
109
305
  const prNumber = opened.pr.number;
306
+ const initialHeadSha = headSha(fixCwd);
307
+ const initialHeadSync = waitHead(repoRoot, branch, initialHeadSha, {
308
+ timeoutSeconds: options.gateHeadTimeoutSeconds,
309
+ pollSeconds: options.gateHeadPollSeconds,
310
+ });
311
+ if (initialHeadSync.status !== 'current') {
312
+ const seen = initialHeadSync.pr?.headSha || 'unknown';
313
+ reportProgress(progress, 'fail', 'pr', `PR head is still ${seen}`);
314
+ throw new Error(
315
+ `review gate: PR #${prNumber} still reports head ${seen}, not the pushed commit `
316
+ + `${initialHeadSha || 'unknown'}. Refusing to review a stale PR diff.`,
317
+ );
318
+ }
319
+ reportProgress(progress, 'complete', 'pr', `PR #${prNumber}`);
110
320
  gateLog(`PR #${prNumber}: enforcing review + CI gate before merge`);
111
321
 
322
+ // 1b. The default keeps the PR draft while review is pending. The explicit
323
+ // `--no-gate-serial-ci` fast mode promotes first so CI overlaps the review:
324
+ // draft state is the only GitHub-side hard barrier this gate controls before
325
+ // its verdict, so even green CI cannot be merged manually or by automation.
326
+ // Undefined stays serial as a fail-safe for direct/internal callers.
327
+ const serialCi = options.gateSerialCi !== false;
328
+ if (serialCi && opened.pr.isDraft === false) {
329
+ requireGhAction(
330
+ markDraft(repoRoot, prNumber),
331
+ `review gate: could not hold PR #${prNumber} as draft before review. Refusing to merge.`,
332
+ );
333
+ gateLog(`PR #${prNumber}: held as draft while the review runs`);
334
+ }
335
+ if (!serialCi) {
336
+ requireGhAction(
337
+ markReady(repoRoot, prNumber),
338
+ `review gate: could not promote PR #${prNumber} before review. Refusing to merge.`,
339
+ );
340
+ gateLog(`PR #${prNumber}: promoted to ready — CI runs alongside the review`);
341
+ }
342
+
112
343
  // 2. AI review — FAIL CLOSED. A provider error / timeout / unparseable output
113
344
  // throws here; convert it to a block, never a silent pass.
345
+ //
346
+ // With --gate-autofix, a dirty verdict gets up to `maxFixRounds` repair
347
+ // rounds: fix in the worktree, push, then RE-REVIEW with a fresh provider
348
+ // run so the fixer never grades its own homework.
114
349
  let review;
115
- try {
116
- review = runPrReview({ target: repoRoot, pr: prNumber, provider, post: true });
117
- } catch (err) {
118
- throw new Error(
119
- `review gate: AI review did not complete (${err.message}). Refusing to merge. `
120
- + 'Fix the provider/auth issue or rerun with --skip-review-gate.',
350
+ let verdict;
351
+ // Files that have ever carried a BLOCKING finding, and files an auto-fix has
352
+ // actually edited. A blocking finding that vanishes from a later round is only
353
+ // treated as repaired when its file was touched — see resolveCarriedFindings.
354
+ const blockedPaths = new Set();
355
+ const repairedPaths = new Set();
356
+ let autofixAttempted = false;
357
+ // Set once an auto-fix round pushes: from then on the CI wait may only judge
358
+ // that commit, never the one it replaced.
359
+ let pushedHeadSha = '';
360
+ for (let round = 0; round <= maxFixRounds; round += 1) {
361
+ reportProgress(
362
+ progress,
363
+ 'start',
364
+ 'review',
365
+ `round ${round + 1}/${maxFixRounds + 1} via ${provider}`,
121
366
  );
367
+ try {
368
+ review = runPrReview({
369
+ target: repoRoot,
370
+ pr: prNumber,
371
+ provider,
372
+ post: true,
373
+ model: options.reviewModel,
374
+ timeoutMs: options.reviewTimeoutMs,
375
+ });
376
+ } catch (err) {
377
+ reportProgress(progress, 'fail', 'review', err.message);
378
+ throw new Error(
379
+ `review gate: AI review did not complete (${err.message}). Refusing to merge. `
380
+ + 'Fix the provider/auth issue or rerun with --skip-review-gate.',
381
+ );
382
+ }
383
+ // Evidence check, before anything is spent on this review. A review that
384
+ // did not reach the PR cannot be audited afterwards, and a provider that
385
+ // returned nothing then looks exactly like a clean pass — which is how
386
+ // lifted.sk-storefront #463, #465 and #466 each merged carrying zero
387
+ // reviews while this gate announced it was enforcing one.
388
+ //
389
+ // Here rather than after the loop: `posted` is known the moment the first
390
+ // review returns and its cause does not change between rounds, so deferring
391
+ // would burn every --gate-autofix round and push agent-authored fix commits
392
+ // before refusing. It also keeps the error honest when the review is both
393
+ // unposted and dirty, where the blocking-findings message would otherwise
394
+ // send the operator to a PR that has no review on it.
395
+ try {
396
+ requirePostedReview(review, prNumber);
397
+ } catch (error) {
398
+ reportProgress(progress, 'fail', 'review', error.message);
399
+ throw error;
400
+ }
401
+
402
+ verdict = evaluate(review.findings);
403
+ for (const finding of verdict.blocking) {
404
+ if (finding && finding.path) blockedPaths.add(finding.path);
405
+ }
406
+ if (verdict.clean || round === maxFixRounds) break;
407
+
408
+ gateLog(`PR #${prNumber}: ${verdict.blocking.length} blocking finding(s) — auto-fix round ${round + 1}/${maxFixRounds}`);
409
+ autofixAttempted = true;
410
+ reportProgress(
411
+ progress,
412
+ 'start',
413
+ 'autofix',
414
+ `round ${round + 1}/${maxFixRounds}: ${verdict.blocking.length} blocking finding(s)`,
415
+ );
416
+ let fix;
417
+ try {
418
+ fix = runFix({
419
+ repoRoot: fixCwd, provider, findings: verdict.blocking, expectBranch: branch,
420
+ });
421
+ } catch (err) {
422
+ reportProgress(progress, 'fail', 'autofix', err.message);
423
+ gateLog(`auto-fix failed: ${err.message}`);
424
+ break;
425
+ }
426
+ if (fix.status !== 'fixed') {
427
+ reportProgress(progress, 'fail', 'autofix', fix.reason || fix.status);
428
+ gateLog(`auto-fix changed nothing (${fix.reason || fix.status})`);
429
+ break;
430
+ }
431
+ for (const changed of fix.changedFiles) repairedPaths.add(changed);
432
+ gateLog(`auto-fix committed ${fix.changedFiles.length} file(s): ${fix.changedFiles.slice(0, 5).join(', ')}`);
433
+ const pushed = pushBranch(fixCwd, branch);
434
+ if (!pushed.ok) {
435
+ reportProgress(progress, 'fail', 'autofix', 'push failed');
436
+ gateLog(`push after auto-fix failed: ${pushed.output}`);
437
+ break;
438
+ }
439
+ pushedHeadSha = headSha(fixCwd);
440
+ const headSync = waitHead(repoRoot, branch, pushedHeadSha, {
441
+ timeoutSeconds: options.gateHeadTimeoutSeconds,
442
+ pollSeconds: options.gateHeadPollSeconds,
443
+ });
444
+ if (headSync.status !== 'current') {
445
+ const seen = headSync.pr?.headSha || 'unknown';
446
+ reportProgress(progress, 'fail', 'autofix', `PR head is still ${seen}`);
447
+ throw new Error(
448
+ `review gate: PR #${prNumber} still reports head ${seen}, not the auto-fix commit `
449
+ + `${pushedHeadSha || 'unknown'}. Refusing to re-review a stale PR diff.`,
450
+ );
451
+ }
452
+ reportProgress(progress, 'complete', 'autofix', `${fix.changedFiles.length} file(s) fixed and pushed`);
122
453
  }
123
- const verdict = evaluate(review.findings);
454
+
124
455
  if (!verdict.clean) {
456
+ reportProgress(progress, 'fail', 'review', `${verdict.blocking.length} blocking finding(s) remain`);
457
+ if (!autofixAttempted) {
458
+ reportProgress(progress, 'skip', 'autofix', maxFixRounds > 0 ? 'no repair round completed' : 'disabled');
459
+ }
125
460
  const detail = verdict.blocking
126
461
  .map((f) => ` - ${String(f.severity).toUpperCase()} ${f.path}:${f.line} ${f.message}`)
127
462
  .join('\n');
128
463
  throw new Error(
129
464
  `review gate: ${verdict.blocking.length} blocking finding(s). Refusing to merge.\n${detail}\n`
130
- + 'Fix the findings or rerun with --skip-review-gate.',
465
+ + (maxFixRounds > 0
466
+ ? 'Auto-fix did not clear them. Fix manually or rerun with --skip-review-gate.'
467
+ : 'Fix the findings, rerun with --gate-autofix to let the agent repair them, or bypass with --skip-review-gate.'),
468
+ );
469
+ }
470
+
471
+ // A clean final verdict is not enough on its own. Review providers are
472
+ // nondeterministic: a blocking finding can simply fail to reappear in a later
473
+ // round, and reading that silence as "repaired" merges the bug. Every file
474
+ // that ever blocked must either still be under review or have actually been
475
+ // edited by a fix.
476
+ const unexplained = resolveCarriedFindings(blockedPaths, repairedPaths, review.findings);
477
+ if (unexplained.length > 0) {
478
+ reportProgress(progress, 'fail', 'review', `${unexplained.length} finding(s) disappeared without a matching edit`);
479
+ throw new Error(
480
+ `review gate: ${unexplained.length} earlier blocking finding(s) disappeared without their file being changed. `
481
+ + `Refusing to merge — a finding that is merely absent from a later review is not a fixed finding.\n`
482
+ + unexplained.map((p) => ` - ${p} (blocked earlier, never edited, no current finding)`).join('\n')
483
+ + '\nRe-run the review, fix these by hand, or bypass with --skip-review-gate.',
131
484
  );
132
485
  }
486
+ const threadResolution = resolveThreads(prNumber, repoRoot, review.findings);
487
+ if (threadResolution.ok === false) {
488
+ gateLog(
489
+ `PR #${prNumber}: could not inspect outdated GitGuardex review threads`
490
+ + `${threadResolution.output ? ` (${threadResolution.output})` : ''}; merge-state gate remains authoritative`,
491
+ );
492
+ } else if (threadResolution.resolved > 0) {
493
+ gateLog(`PR #${prNumber}: resolved ${threadResolution.resolved} outdated GitGuardex review thread(s)`);
494
+ }
495
+ reportProgress(
496
+ progress,
497
+ 'complete',
498
+ 'review',
499
+ `clean review posted${threadResolution.resolved > 0 ? `; ${threadResolution.resolved} stale thread(s) resolved` : ''}`,
500
+ );
501
+ if (!autofixAttempted) {
502
+ reportProgress(progress, 'skip', 'autofix', 'not needed');
503
+ }
133
504
  gateLog(
134
- `PR #${prNumber}: review clean (${review.findings.length} non-blocking finding(s))`
135
- + (review.reason === 'github-auth-unavailable' ? ' [not posted: github-auth-unavailable]' : ''),
505
+ `PR #${prNumber}: review clean (${review.findings.length} non-blocking finding(s)), posted to the PR`,
136
506
  );
137
507
 
138
- // 3. Promote draft -> ready so required CI checks fire.
139
- markReady(repoRoot, prNumber);
508
+ // 3. Promote draft -> ready so required CI checks fire. Already done in step
509
+ // 1b unless serial CI held the draft barrier until the review came in clean.
510
+ if (serialCi) {
511
+ requireGhAction(
512
+ markReady(repoRoot, prNumber),
513
+ `review gate: could not promote PR #${prNumber} after a clean review. Refusing to merge.`,
514
+ );
515
+ gateLog(`PR #${prNumber}: promoted to ready after a clean review`);
516
+ }
140
517
 
141
518
  // 4. Wait for CI to settle green + GitHub to report mergeable. waitForGreenCi
142
519
  // is fully fail-closed (failed/cancelled checks, blocked mergeStateStatus,
143
520
  // timeout, and check-less PRs all return non-green statuses).
144
- const ci = waitGreen(repoRoot, branch, {
145
- timeoutSeconds: options.gateTimeoutSeconds,
146
- pollSeconds: options.gatePollSeconds,
147
- requireChecks,
148
- });
521
+ // With --gate-baseline, checks already red on the base branch are excluded
522
+ // from that judgement, so a repo whose base is red can still gate on the
523
+ // only question that matters: does this change ADD a failure?
524
+ let baselineFailures = new Set();
525
+ if (options.gateBaseline) {
526
+ const baseline = readBaseline(repoRoot, baseBranch);
527
+ baselineFailures = baseline.failing;
528
+ gateLog(baselineFailures.size > 0
529
+ ? `baseline from ${baseline.source}: ${baselineFailures.size} check(s) already failing — [${[...baselineFailures].join(', ')}]`
530
+ : `baseline from ${baseline.source}: no known failures — every failing check counts as new`);
531
+ }
532
+
533
+ reportProgress(progress, 'start', 'ci', 'waiting for required GitHub checks');
534
+ let ci;
535
+ try {
536
+ ci = waitGreen(repoRoot, branch, {
537
+ timeoutSeconds: options.gateTimeoutSeconds,
538
+ pollSeconds: options.gatePollSeconds,
539
+ requireChecks,
540
+ baselineFailures,
541
+ expectHeadSha: pushedHeadSha,
542
+ });
543
+ } catch (error) {
544
+ reportProgress(progress, 'fail', 'ci', error.message);
545
+ throw error;
546
+ }
149
547
  if (ci.status === 'checks-failed') {
150
- throw new Error(`review gate: CI checks failed/cancelled on PR #${prNumber}. Refusing to merge.`);
548
+ reportProgress(progress, 'fail', 'ci', 'checks failed or were cancelled');
549
+ const novel = Array.isArray(ci.newFailures) && ci.newFailures.length > 0
550
+ ? ` New failure(s) vs '${baseBranch}': ${ci.newFailures.join(', ')}.`
551
+ : '';
552
+ throw new Error(
553
+ `review gate: CI checks failed/cancelled on PR #${prNumber}. Refusing to merge.${novel}`
554
+ + (options.gateBaseline ? '' : ' Pass --gate-baseline to ignore failures already red on the base branch.'),
555
+ );
151
556
  }
152
557
  if (ci.status === 'merge-blocked') {
153
558
  const mss = (ci.pr && ci.pr.mergeStateStatus) || 'BLOCKED';
559
+ reportProgress(progress, 'fail', 'ci', `mergeStateStatus=${mss}`);
154
560
  throw new Error(
155
561
  `review gate: GitHub reports mergeStateStatus=${mss} for PR #${prNumber} `
156
562
  + '(not mergeable under branch protection). Refusing to merge.',
157
563
  );
158
564
  }
159
565
  if (ci.status === 'no-checks') {
566
+ reportProgress(progress, 'fail', 'ci', 'no CI checks configured');
160
567
  throw new Error(
161
568
  `review gate: PR #${prNumber} has no CI checks configured. Refusing to merge an `
162
569
  + 'unverified PR. Pass --allow-no-checks to override.',
163
570
  );
164
571
  }
572
+ if (ci.status === 'stale-head') {
573
+ const seen = (ci.pr && ci.pr.headSha) || 'unknown';
574
+ reportProgress(progress, 'fail', 'ci', `stale PR head ${seen}`);
575
+ throw new Error(
576
+ `review gate: PR #${prNumber} still reports head ${seen}, not the auto-fix commit `
577
+ + `${pushedHeadSha}. Refusing to merge — the checks GitHub is reporting describe a `
578
+ + 'commit that push replaced, so their green says nothing about the code being merged.',
579
+ );
580
+ }
165
581
  if (ci.status === 'timeout') {
582
+ reportProgress(progress, 'fail', 'ci', 'timed out');
166
583
  throw new Error(`review gate: timed out waiting for CI to go green on PR #${prNumber}.`);
167
584
  }
168
585
  if (ci.status !== 'green') {
586
+ reportProgress(progress, 'fail', 'ci', ci.status);
169
587
  throw new Error(`review gate: PR #${prNumber} not in a mergeable state (${ci.status}).`);
170
588
  }
171
589
 
172
590
  const mss = ci.pr && ci.pr.mergeStateStatus;
591
+ reportProgress(progress, 'complete', 'ci', `green${mss ? `, mergeStateStatus=${mss}` : ''}`);
173
592
  gateLog(`PR #${prNumber}: review clean + CI green${mss ? ` + mergeStateStatus=${mss}` : ''} — proceeding to merge`);
174
593
  return { prNumber };
175
594
  }
176
595
 
177
596
  module.exports = {
178
597
  runReviewGate,
598
+ resolveCarriedFindings,
179
599
  waitForGreenCi,
600
+ waitForPullRequestHead,
180
601
  DEFAULT_GATE_TIMEOUT_SECONDS,
181
602
  MERGEABLE_STATES,
182
603
  };
@@ -0,0 +1,59 @@
1
+ const { GH_BIN } = require('./context');
2
+ const { run } = require('./core/runtime');
3
+ const path = require('node:path');
4
+
5
+ const REPO_SLUG_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
6
+ const repoSlugCacheByRunner = new WeakMap();
7
+
8
+ function cacheForRunner(runner) {
9
+ let cache = repoSlugCacheByRunner.get(runner);
10
+ if (!cache) {
11
+ cache = new Map();
12
+ repoSlugCacheByRunner.set(runner, cache);
13
+ }
14
+ return cache;
15
+ }
16
+
17
+ function resolveRepoNameWithOwner(repoRoot, runner) {
18
+ const result = runner(GH_BIN, [
19
+ 'repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner',
20
+ ], { cwd: repoRoot, timeout: 60_000, allowFailure: true });
21
+ const slug = String(result.stdout || '').trim();
22
+ return result.status === 0 && REPO_SLUG_RE.test(slug) ? slug : '';
23
+ }
24
+
25
+ /**
26
+ * Canonical GitHub repo slug for API paths.
27
+ *
28
+ * `gh api repos/:owner/:repo/...` normally expands from the current remote, but
29
+ * on a moved repository that placeholder can still route a write through the old
30
+ * owner and GitHub answers HTTP 307. Resolve through `gh repo view` first: gh
31
+ * follows the move and returns the canonical `owner/name` that write endpoints
32
+ * accept. Fall back to the placeholder when gh cannot resolve the repository so
33
+ * offline/unit-test callers keep the old behavior.
34
+ *
35
+ * Successful resolutions are memoized for the process lifetime: gated finish
36
+ * flows construct several API paths in one run, and the canonical owner/name is
37
+ * stable for that repo while the process is alive.
38
+ */
39
+ function repoNameWithOwner(repoRoot, runner = run) {
40
+ const cache = cacheForRunner(runner);
41
+ const cacheKey = path.resolve(repoRoot || process.cwd());
42
+ if (cache.has(cacheKey)) return cache.get(cacheKey);
43
+
44
+ const slug = resolveRepoNameWithOwner(repoRoot, runner);
45
+ if (slug) cache.set(cacheKey, slug);
46
+ return slug;
47
+ }
48
+
49
+ function repoApiPath(repoRoot, suffix, runner = run) {
50
+ const normalizedSuffix = String(suffix || '').replace(/^\/+/, '');
51
+ const slug = repoNameWithOwner(repoRoot, runner);
52
+ const prefix = slug ? `repos/${slug}` : 'repos/:owner/:repo';
53
+ return normalizedSuffix ? `${prefix}/${normalizedSuffix}` : prefix;
54
+ }
55
+
56
+ module.exports = {
57
+ repoNameWithOwner,
58
+ repoApiPath,
59
+ };