@imdeadpool/guardex 8.4.0 → 8.4.2

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 (97) hide show
  1. package/CONTRIBUTING.md +13 -4
  2. package/README.md +223 -1
  3. package/THIRD-PARTY-NOTICES.md +29 -0
  4. package/bin/multiagent-safety.js +9 -12
  5. package/package.json +4 -2
  6. package/skills/gitguardex/SKILL.md +28 -0
  7. package/skills/pr-lens/SKILL.md +87 -0
  8. package/src/abide.js +534 -0
  9. package/src/agents/activity.js +23 -4
  10. package/src/agents/inspect.js +15 -6
  11. package/src/agents/launch.js +6 -1
  12. package/src/agents/process-lease.js +84 -0
  13. package/src/agents/sessions.js +96 -16
  14. package/src/agents/start.js +18 -9
  15. package/src/agents/status.js +35 -14
  16. package/src/agents/supervise.js +87 -0
  17. package/src/budget/index.js +6 -1
  18. package/src/cli/args.js +71 -77
  19. package/src/cli/commands/agents.js +38 -10
  20. package/src/cli/commands/branch.js +116 -103
  21. package/src/cli/commands/claude.js +604 -50
  22. package/src/cli/commands/codex.js +359 -0
  23. package/src/cli/commands/context.js +52 -0
  24. package/src/cli/commands/mcp.js +5 -1
  25. package/src/cli/commands/pr.js +138 -3
  26. package/src/cli/commands/review.js +3 -1
  27. package/src/cli/commands/setup.js +25 -0
  28. package/src/cli/commands/status.js +128 -60
  29. package/src/cli/commands/storage.js +24 -0
  30. package/src/cli/commands/usage.js +48 -0
  31. package/src/cli/commands/watch.js +157 -47
  32. package/src/cli/commands/worktree-copy-ignored.js +38 -0
  33. package/src/cli/commands/worktree-estimate.js +69 -0
  34. package/src/cli/commands/worktree-hooks.js +62 -0
  35. package/src/cli/commands/worktree-navigation.js +71 -0
  36. package/src/cli/commands/worktree-provision.js +92 -0
  37. package/src/cli/main.js +229 -110
  38. package/src/cli/shared/gate-flags.js +131 -0
  39. package/src/cli/shared/scaffolding.js +31 -3
  40. package/src/cli/shared-locks.js +3 -1
  41. package/src/cockpit/pane-actions.js +43 -7
  42. package/src/context.js +373 -17
  43. package/src/doctor/index.js +29 -35
  44. package/src/finish/events.js +254 -0
  45. package/src/finish/index.js +322 -62
  46. package/src/finish/post-branch-finish-cleanup.js +316 -22
  47. package/src/finish/preflight.js +44 -1
  48. package/src/finish/progress.js +36 -0
  49. package/src/finish/review-gate.js +317 -127
  50. package/src/finish/review-receipt.js +156 -0
  51. package/src/finish/with-claims-lock.py +29 -0
  52. package/src/git/index.js +179 -42
  53. package/src/hooks/index.js +68 -3
  54. package/src/mcp/collect.js +61 -5
  55. package/src/mcp/server.js +4 -0
  56. package/src/output/index.js +167 -1
  57. package/src/pr-lens-publish.js +93 -0
  58. package/src/pr-lens.js +184 -0
  59. package/src/pr-respond.js +860 -0
  60. package/src/pr-review.js +519 -159
  61. package/src/pr.js +73 -14
  62. package/src/provider-binary.js +21 -0
  63. package/src/review-diff-context.js +90 -0
  64. package/src/review-fix.js +23 -17
  65. package/src/scaffold/agent-worktree-prep.js +14 -12
  66. package/src/scaffold/dependency-store.js +234 -0
  67. package/src/scaffold/index.js +13 -1
  68. package/src/scaffold/provision-approvals.js +83 -0
  69. package/src/scaffold/provision-config.js +169 -40
  70. package/src/shared-git-state.js +11 -1
  71. package/src/speckit/index.js +12 -1
  72. package/src/storage/run-artifacts.js +185 -0
  73. package/src/toolchain/index.js +322 -2
  74. package/src/worktree-copy-ignored.js +200 -0
  75. package/src/worktree-hook-worker.js +29 -0
  76. package/src/worktree-hooks.js +333 -0
  77. package/src/worktree-navigation.js +248 -0
  78. package/src/worktree-picker.js +89 -0
  79. package/src/worktree-quota.js +100 -0
  80. package/src/worktree-start.js +100 -0
  81. package/templates/AGENTS.multiagent-safety.md +8 -0
  82. package/templates/AGENTS.multiagent-safety.min.md +3 -1
  83. package/templates/codex/skills/gitguardex/SKILL.md +28 -0
  84. package/templates/codex/skills/opensrc/SKILL.md +24 -0
  85. package/templates/githooks/post-merge +16 -2
  86. package/templates/scripts/agent-autofinish-watch.sh +17 -18
  87. package/templates/scripts/agent-branch-finish.sh +180 -19
  88. package/templates/scripts/agent-branch-merge.sh +7 -32
  89. package/templates/scripts/agent-branch-start.sh +202 -43
  90. package/templates/scripts/agent-claude-stop-finish.sh +4 -27
  91. package/templates/scripts/agent-file-locks.py +257 -29
  92. package/templates/scripts/agent-preflight.sh +3 -0
  93. package/templates/scripts/agent-worktree-prune.sh +975 -63
  94. package/templates/scripts/codex-agent.sh +55 -5
  95. package/templates/scripts/lib/guardex-base-branch.sh +207 -0
  96. package/templates/scripts/openspec/init-change-workspace.sh +10 -18
  97. package/templates/scripts/review-bot-watch.sh +171 -4
@@ -12,6 +12,7 @@ const { TOOL_NAME } = require('../context');
12
12
  const pr = require('../pr');
13
13
  const prReview = require('../pr-review');
14
14
  const reviewFix = require('../review-fix');
15
+ const { reviewReceipt } = require('./review-receipt');
15
16
  const { mapWorktreePathsByBranch } = require('../git');
16
17
 
17
18
  const DEFAULT_GATE_TIMEOUT_SECONDS = 1800; // 30 min — CI can be slow.
@@ -26,6 +27,14 @@ const MERGEABLE_STATES = new Set(['CLEAN', 'HAS_HOOKS']);
26
27
  // check unmet; DIRTY = conflicts; BEHIND = base moved. All fail closed.
27
28
  const BLOCKED_STATES = new Set(['DIRTY', 'BLOCKED', 'BEHIND', 'UNSTABLE']);
28
29
 
30
+ function disabledActionsFallback(repoRoot) {
31
+ const config = run('git', ['config', '--local', '--type=bool', '--get', 'multiagent.ciFallbackWhenDisabled'], {
32
+ cwd: repoRoot, allowFailure: true,
33
+ });
34
+ return config.status === 0 && String(config.stdout || '').trim() === 'true'
35
+ && pr.githubActionsWorkflowsDisabled(repoRoot);
36
+ }
37
+
29
38
  function gateLog(message) {
30
39
  console.log(`[${TOOL_NAME}] [gate] ${message}`);
31
40
  }
@@ -38,9 +47,7 @@ function reportProgress(progress, method, stage, detail) {
38
47
 
39
48
  function requireGhAction(result, failureMessage) {
40
49
  if (result && result.ok === false) {
41
- throw new Error(
42
- `${failureMessage}${result.output ? `\n${result.output}` : ''}`,
43
- );
50
+ throw new Error(`${failureMessage}${result.output ? `\n${result.output}` : ''}`);
44
51
  }
45
52
  }
46
53
 
@@ -55,15 +62,16 @@ function requireGhAction(result, failureMessage) {
55
62
  */
56
63
  function requirePostedReview(review, prNumber) {
57
64
  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)}`;
65
+ const why =
66
+ review.reason === 'github-auth-unavailable'
67
+ ? 'GitHub auth was unavailable to the review runner'
68
+ : `the review runner reported posted=${JSON.stringify(review.posted)}`;
61
69
  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.',
70
+ `review gate: the AI review was not posted to PR #${prNumber} (${why}). Refusing to merge — ` +
71
+ 'an unposted review leaves no evidence the diff was examined, and a provider that returns ' +
72
+ 'nothing then looks exactly like a clean pass.' +
73
+ (review.artifactPath ? `\nLocal artifact: ${review.artifactPath}` : '') +
74
+ '\nFix the provider/auth issue and re-run, or bypass with --skip-review-gate.'
67
75
  );
68
76
  }
69
77
 
@@ -73,6 +81,22 @@ function readHeadSha(cwd) {
73
81
  return result.status === 0 ? String(result.stdout || '').trim() : '';
74
82
  }
75
83
 
84
+ function readBaseSha(cwd, baseBranch) {
85
+ const result = run(
86
+ 'git',
87
+ ['-C', cwd, 'ls-remote', '--exit-code', 'origin', `refs/heads/${baseBranch}`],
88
+ {
89
+ cwd,
90
+ allowFailure: true
91
+ }
92
+ );
93
+ return result.status === 0
94
+ ? String(result.stdout || '')
95
+ .trim()
96
+ .split(/\s+/)[0]
97
+ : '';
98
+ }
99
+
76
100
  /** Worktree holding `branch`, or `repoRoot` when git cannot tell us. */
77
101
  function resolveWorktreeForBranch(repoRoot, branch) {
78
102
  try {
@@ -91,7 +115,9 @@ function waitForPullRequestHead(repoRoot, branch, expectedHeadSha, options = {})
91
115
  const pollSeconds = options.pollSeconds || DEFAULT_PR_HEAD_POLL_SECONDS;
92
116
  const sleep = options.sleep || ((seconds) => run('sleep', [String(seconds)], { cwd: repoRoot }));
93
117
  const now = options.now || (() => Date.now());
94
- const getStatus = options.getStatus || ((r, b) => pr.getPullRequestStatus(r, b));
118
+ // Only headSha is needed here; use the lightweight query to avoid fetching
119
+ // the full statusCheckRollup on every 2-second poll.
120
+ const getStatus = options.getStatus || ((r, b) => pr.getPrHeadOid(r, b));
95
121
  const deadline = now() + timeoutSeconds * 1000;
96
122
  let snapshot;
97
123
 
@@ -154,9 +180,12 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
154
180
  const start = now();
155
181
  const deadline = start + timeoutSeconds * 1000;
156
182
  const graceDeadline = start + graceSeconds * 1000;
183
+ let workflowsJustConfirmedDisabled = false;
157
184
 
158
185
  // eslint-disable-next-line no-constant-condition
159
186
  while (true) {
187
+ const confirmedBeforeSnapshot = workflowsJustConfirmedDisabled;
188
+ workflowsJustConfirmedDisabled = false;
160
189
  const snap = getStatus(repoRoot, branch);
161
190
  if (!snap) return { status: 'no-pr' };
162
191
  // A verdict about the wrong commit is not a verdict. Judge nothing — not
@@ -187,10 +216,8 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
187
216
  const settled = count('pending') === 0;
188
217
  const namedFailures = failedNames.length === failingCount;
189
218
  const novelFailures = failedNames.filter((name) => !baseline.has(name));
190
- const onlyBaselineFailures = baselineMode
191
- && failingCount > 0
192
- && namedFailures
193
- && novelFailures.length === 0;
219
+ const onlyBaselineFailures =
220
+ baselineMode && failingCount > 0 && namedFailures && novelFailures.length === 0;
194
221
  if (failingCount > 0) {
195
222
  if (!baselineMode || !namedFailures || novelFailures.length > 0) {
196
223
  return { status: 'checks-failed', pr: snap, newFailures: novelFailures };
@@ -204,13 +231,14 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
204
231
  // base baseline and GitHub still says the branch is mergeable, that state is
205
232
  // the same "no new failures" verdict as UNSTABLE.
206
233
  const baselineBlockedByKnownChecks = mss === 'BLOCKED' && mergeable && onlyBaselineFailures;
207
- const unstableOnlyBecauseBillingChecksWereWaived = mss === 'UNSTABLE'
208
- && namedWaivers
209
- && failingCount === 0
210
- && count('pending') === 0
211
- && count('other') === 0
212
- && count('skipped') === 0
213
- && count('success') + waivedCount === count('total');
234
+ const unstableOnlyBecauseBillingChecksWereWaived =
235
+ mss === 'UNSTABLE' &&
236
+ namedWaivers &&
237
+ failingCount === 0 &&
238
+ count('pending') === 0 &&
239
+ count('other') === 0 &&
240
+ count('skipped') === 0 &&
241
+ count('success') + waivedCount === count('total');
214
242
  // GitHub says this can't merge as-is. Some BLOCKED/UNSTABLE snapshots are
215
243
  // just "required checks are still pending" immediately after a draft PR is
216
244
  // promoted to ready, so wait for pending checks to settle before treating
@@ -219,9 +247,13 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
219
247
  if (mss && (mss === 'DIRTY' || mss === 'BEHIND')) {
220
248
  return { status: 'merge-blocked', pr: snap };
221
249
  }
222
- if (mss && blockedStates.has(mss) && settled
223
- && !baselineBlockedByKnownChecks
224
- && !unstableOnlyBecauseBillingChecksWereWaived) {
250
+ if (
251
+ mss &&
252
+ blockedStates.has(mss) &&
253
+ settled &&
254
+ !baselineBlockedByKnownChecks &&
255
+ !unstableOnlyBecauseBillingChecksWereWaived
256
+ ) {
225
257
  return { status: 'merge-blocked', pr: snap };
226
258
  }
227
259
 
@@ -234,16 +266,18 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
234
266
  // fallback accounts every check as success-or-cleared-failure. `other` must
235
267
  // still be zero either way — an ambiguous state is never a pass.
236
268
  const waiversAccountedFor = waivedCount === 0 || namedWaivers;
237
- const allAccountedFor = waiversAccountedFor && (baselineMode
238
- ? count('other') === 0
239
- && count('success') + failingCount + waivedCount === count('total')
240
- : count('other') === 0
241
- && count('success') + waivedCount === count('total'));
242
- const trusted = waiversAccountedFor && (
243
- baselineBlockedByKnownChecks
244
- || unstableOnlyBecauseBillingChecksWereWaived
245
- || (mss ? trustedStates.has(mss) : allAccountedFor)
246
- );
269
+ const allAccountedFor =
270
+ waiversAccountedFor &&
271
+ (baselineMode
272
+ ? count('other') === 0 &&
273
+ count('success') + failingCount + waivedCount + count('skipped') === count('total')
274
+ : count('other') === 0 &&
275
+ count('success') + waivedCount + count('skipped') === count('total'));
276
+ const trusted =
277
+ waiversAccountedFor &&
278
+ (baselineBlockedByKnownChecks ||
279
+ unstableOnlyBecauseBillingChecksWereWaived ||
280
+ (mss ? trustedStates.has(mss) : allAccountedFor));
247
281
 
248
282
  if (settled && mergeable && hasChecks && trusted) {
249
283
  const result = { status: 'green', pr: snap };
@@ -254,7 +288,19 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
254
288
  if (!requireChecks) return { status: 'green', pr: snap };
255
289
  // No checks yet — give CI a grace window to create check runs before
256
290
  // concluding the PR is genuinely check-less (avoids the promote->merge race).
257
- if (now() >= graceDeadline) return { status: 'no-checks', pr: snap };
291
+ if (now() >= graceDeadline) {
292
+ if (expectHeadSha && MERGEABLE_STATES.has(mss)) {
293
+ if (confirmedBeforeSnapshot) return { status: 'green', pr: snap, requiresLocalPreflight: true };
294
+ if ((options.disabledActionsFallback || disabledActionsFallback)(repoRoot)) {
295
+ // A check or head change may have arrived during the workflow API call.
296
+ if (now() >= deadline) return { status: 'timeout', pr: snap };
297
+ workflowsJustConfirmedDisabled = true;
298
+ // eslint-disable-next-line no-continue
299
+ continue;
300
+ }
301
+ }
302
+ return { status: 'no-checks', pr: snap };
303
+ }
258
304
  }
259
305
  if (now() >= deadline) return { status: 'timeout', pr: snap };
260
306
  sleep(pollSeconds);
@@ -280,7 +326,7 @@ function resolveCarriedFindings(blockedPaths, repairedPaths, currentFindings) {
280
326
  const stillReported = new Set(
281
327
  (Array.isArray(currentFindings) ? currentFindings : [])
282
328
  .map((finding) => finding && finding.path)
283
- .filter(Boolean),
329
+ .filter(Boolean)
284
330
  );
285
331
  return [...blockedPaths]
286
332
  .filter((path) => !repairedPaths.has(path) && !stillReported.has(path))
@@ -292,9 +338,12 @@ function resolveCarriedFindings(blockedPaths, repairedPaths, currentFindings) {
292
338
  * passes a clean AI review AND green CI AND GitHub reports it mergeable. Returns
293
339
  * `{ prNumber }` on pass; the caller then proceeds to the real merge.
294
340
  */
295
- function runReviewGate({
296
- repoRoot, worktreePath, branch, baseBranch, options = {}, progress,
297
- }, deps = {}) {
341
+ function runReviewGate(
342
+ { repoRoot, worktreePath, branch, baseBranch, options = {}, progress, preflight },
343
+ deps = {}
344
+ ) {
345
+ // Quiet mode suppresses successful narration, never warnings or blocking errors.
346
+ const logProgress = options.agentQuiet ? () => {} : gateLog;
298
347
  const openPullRequest = deps.openPullRequest || pr.openPullRequest;
299
348
  const runPrReview = deps.runPrReview || prReview.runPrReview;
300
349
  const markReady = deps.markPullRequestReady || pr.markPullRequestReady;
@@ -306,9 +355,10 @@ function runReviewGate({
306
355
  const runFix = deps.runReviewFix || reviewFix.runReviewFix;
307
356
  const pushBranch = deps.pushBranch || pr.pushBranch;
308
357
  const headSha = deps.readHeadSha || readHeadSha;
358
+ const baseSha = deps.readBaseSha || readBaseSha;
309
359
  const waitHead = deps.waitForPullRequestHead || waitForPullRequestHead;
310
360
 
311
- const provider = options.reviewProvider || 'codex';
361
+ const provider = options.reviewProvider;
312
362
  const requireChecks = !options.allowNoChecks;
313
363
  // Fix rounds are opt-in and bounded: an unfixable finding must fall through to
314
364
  // the block rather than spin the provider forever.
@@ -329,20 +379,42 @@ function runReviewGate({
329
379
  }
330
380
  const prNumber = opened.pr.number;
331
381
  const initialHeadSha = headSha(fixCwd);
332
- const initialHeadSync = waitHead(repoRoot, branch, initialHeadSha, {
333
- timeoutSeconds: options.gateHeadTimeoutSeconds,
334
- pollSeconds: options.gateHeadPollSeconds,
335
- });
336
- if (initialHeadSync.status !== 'current') {
337
- const seen = initialHeadSync.pr?.headSha || 'unknown';
338
- reportProgress(progress, 'fail', 'pr', `PR head is still ${seen}`);
339
- throw new Error(
340
- `review gate: PR #${prNumber} still reports head ${seen}, not the pushed commit `
341
- + `${initialHeadSha || 'unknown'}. Refusing to review a stale PR diff.`,
342
- );
382
+ const reviewedBaseSha = baseSha(fixCwd, baseBranch);
383
+ if (!reviewedBaseSha) {
384
+ throw new Error('review gate: cannot resolve the remote base commit. Refusing to merge.');
385
+ }
386
+ // The post-push PR lookup can already confirm visibility. The review still
387
+ // checks the exact PR's live head before spending a provider call.
388
+ if (
389
+ !initialHeadSha ||
390
+ opened.pr.headRefOid !== initialHeadSha ||
391
+ opened.pr.baseRefName !== baseBranch
392
+ ) {
393
+ const initialHeadSync = waitHead(repoRoot, branch, initialHeadSha, {
394
+ timeoutSeconds: options.gateHeadTimeoutSeconds,
395
+ pollSeconds: options.gateHeadPollSeconds
396
+ });
397
+ if (initialHeadSync.status !== 'current') {
398
+ const seen = initialHeadSync.pr?.headSha || 'unknown';
399
+ reportProgress(progress, 'fail', 'pr', `PR head is still ${seen}`);
400
+ throw new Error(
401
+ `review gate: PR #${prNumber} still reports head ${seen}, not the pushed commit ` +
402
+ `${initialHeadSha || 'unknown'}. Refusing to review a stale PR diff.`
403
+ );
404
+ }
343
405
  }
344
406
  reportProgress(progress, 'complete', 'pr', `PR #${prNumber}`);
345
- gateLog(`PR #${prNumber}: enforcing review + CI gate before merge`);
407
+ logProgress(`PR #${prNumber}: enforcing review + CI gate before merge`);
408
+ const getReceipt = (head) => (
409
+ opened.pr.baseRefName === baseBranch && opened.pr.url
410
+ ? (deps.reviewReceipt || reviewReceipt)(repoRoot, {
411
+ prNumber, prUrl: opened.pr.url, baseBranch, head, base: reviewedBaseSha,
412
+ }, options)
413
+ : null
414
+ );
415
+ const reusable = opened.pr.headRefOid === initialHeadSha
416
+ ? getReceipt(initialHeadSha)?.read()
417
+ : null;
346
418
 
347
419
  // 1b. The default keeps the PR draft while review is pending. The explicit
348
420
  // `--no-gate-serial-ci` fast mode promotes first so CI overlaps the review:
@@ -350,19 +422,19 @@ function runReviewGate({
350
422
  // its verdict, so even green CI cannot be merged manually or by automation.
351
423
  // Undefined stays serial as a fail-safe for direct/internal callers.
352
424
  const serialCi = options.gateSerialCi !== false;
353
- if (serialCi && opened.pr.isDraft === false) {
425
+ if (!reusable && serialCi && opened.pr.isDraft === false) {
354
426
  requireGhAction(
355
427
  markDraft(repoRoot, prNumber),
356
- `review gate: could not hold PR #${prNumber} as draft before review. Refusing to merge.`,
428
+ `review gate: could not hold PR #${prNumber} as draft before review. Refusing to merge.`
357
429
  );
358
- gateLog(`PR #${prNumber}: held as draft while the review runs`);
430
+ logProgress(`PR #${prNumber}: held as draft while the review runs`);
359
431
  }
360
- if (!serialCi) {
432
+ if (!serialCi && !(reusable && opened.pr.isDraft === false)) {
361
433
  requireGhAction(
362
434
  markReady(repoRoot, prNumber),
363
- `review gate: could not promote PR #${prNumber} before review. Refusing to merge.`,
435
+ `review gate: could not promote PR #${prNumber} before review. Refusing to merge.`
364
436
  );
365
- gateLog(`PR #${prNumber}: promoted to ready — CI runs alongside the review`);
437
+ logProgress(`PR #${prNumber}: promoted to ready — CI runs alongside the review`);
366
438
  }
367
439
 
368
440
  // 2. AI review — FAIL CLOSED. A provider error / timeout / unparseable output
@@ -371,23 +443,33 @@ function runReviewGate({
371
443
  // With --gate-autofix, a dirty verdict gets up to `maxFixRounds` repair
372
444
  // rounds: fix in the worktree, push, then RE-REVIEW with a fresh provider
373
445
  // run so the fixer never grades its own homework.
374
- let review;
375
- let verdict;
446
+ let review = reusable ? { findings: [] } : undefined;
447
+ let verdict = reusable ? { clean: true, blocking: [] } : undefined;
376
448
  // Files that have ever carried a BLOCKING finding, and files an auto-fix has
377
449
  // actually edited. A blocking finding that vanishes from a later round is only
378
450
  // treated as repaired when its file was touched — see resolveCarriedFindings.
379
451
  const blockedPaths = new Set();
380
452
  const repairedPaths = new Set();
453
+ // A finding with no .path cannot be keyed into blockedPaths, so it needs its
454
+ // own flag: if one ever blocked a round and then disappears, the gate must
455
+ // fail closed rather than silently treating its absence as a fix.
456
+ let hasPathlessBlocker = false;
381
457
  let autofixAttempted = false;
382
- // Set once an auto-fix round pushes: from then on the CI wait may only judge
383
- // that commit, never the one it replaced.
384
- let pushedHeadSha = '';
385
- for (let round = 0; round <= maxFixRounds; round += 1) {
458
+ // Pin CI from the first review, and advance only after a reviewed autofix.
459
+ let pushedHeadSha = initialHeadSha;
460
+ const assertReviewedRevision = () => {
461
+ if (headSha(fixCwd) !== pushedHeadSha || baseSha(fixCwd, baseBranch) !== reviewedBaseSha) {
462
+ throw new Error(
463
+ 'review gate: source or base changed during review. Rerun the review gate before merging.'
464
+ );
465
+ }
466
+ };
467
+ for (let round = 0; !reusable && round <= maxFixRounds; round += 1) {
386
468
  reportProgress(
387
469
  progress,
388
470
  'start',
389
471
  'review',
390
- `round ${round + 1}/${maxFixRounds + 1} via ${provider}`,
472
+ `round ${round + 1}/${maxFixRounds + 1} via ${provider || 'codex (auto)'}`
391
473
  );
392
474
  try {
393
475
  review = runPrReview({
@@ -395,14 +477,19 @@ function runReviewGate({
395
477
  pr: prNumber,
396
478
  provider,
397
479
  post: true,
480
+ requireCompleteDiff: true,
481
+ expectedHeadSha: pushedHeadSha,
398
482
  model: options.reviewModel,
399
483
  timeoutMs: options.reviewTimeoutMs,
484
+ agentQuiet: options.agentQuiet,
485
+ // abide's AGENTS.md verdicts ride along with the AI review; `act`
486
+ // verdicts block like a high finding. --no-gate-abide turns them off.
487
+ abide: options.gateAbide !== false
400
488
  });
401
489
  } catch (err) {
402
490
  reportProgress(progress, 'fail', 'review', err.message);
403
491
  throw new Error(
404
- `review gate: AI review did not complete (${err.message}). Refusing to merge. `
405
- + 'Fix the provider/auth issue or rerun with --skip-review-gate.',
492
+ `review gate: AI review did not complete (${err.message}). Refusing to merge.`
406
493
  );
407
494
  }
408
495
  // Evidence check, before anything is spent on this review. A review that
@@ -426,22 +513,33 @@ function runReviewGate({
426
513
 
427
514
  verdict = evaluate(review.findings);
428
515
  for (const finding of verdict.blocking) {
429
- if (finding && finding.path) blockedPaths.add(finding.path);
516
+ if (finding && finding.path) {
517
+ blockedPaths.add(finding.path);
518
+ } else if (finding) {
519
+ hasPathlessBlocker = true;
520
+ }
430
521
  }
431
522
  if (verdict.clean || round === maxFixRounds) break;
432
523
 
433
- gateLog(`PR #${prNumber}: ${verdict.blocking.length} blocking finding(s) — auto-fix round ${round + 1}/${maxFixRounds}`);
524
+ logProgress(
525
+ `PR #${prNumber}: ${verdict.blocking.length} blocking finding(s) — auto-fix round ${round + 1}/${maxFixRounds}`
526
+ );
434
527
  autofixAttempted = true;
435
528
  reportProgress(
436
529
  progress,
437
530
  'start',
438
531
  'autofix',
439
- `round ${round + 1}/${maxFixRounds}: ${verdict.blocking.length} blocking finding(s)`,
532
+ `round ${round + 1}/${maxFixRounds}: ${verdict.blocking.length} blocking finding(s)`
440
533
  );
441
534
  let fix;
442
535
  try {
443
536
  fix = runFix({
444
- repoRoot: fixCwd, provider, findings: verdict.blocking, expectBranch: branch,
537
+ repoRoot: fixCwd,
538
+ provider: review.provider || provider,
539
+ model: !provider && review.provider === 'claude' ? null : undefined,
540
+ agentQuiet: options.agentQuiet,
541
+ findings: verdict.blocking,
542
+ expectBranch: branch
445
543
  });
446
544
  } catch (err) {
447
545
  reportProgress(progress, 'fail', 'autofix', err.message);
@@ -454,42 +552,61 @@ function runReviewGate({
454
552
  break;
455
553
  }
456
554
  for (const changed of fix.changedFiles) repairedPaths.add(changed);
457
- gateLog(`auto-fix committed ${fix.changedFiles.length} file(s): ${fix.changedFiles.slice(0, 5).join(', ')}`);
555
+ logProgress(
556
+ `auto-fix committed ${fix.changedFiles.length} file(s): ${fix.changedFiles.slice(0, 5).join(', ')}`
557
+ );
458
558
  const pushed = pushBranch(fixCwd, branch);
459
559
  if (!pushed.ok) {
460
560
  reportProgress(progress, 'fail', 'autofix', 'push failed');
461
561
  gateLog(`push after auto-fix failed: ${pushed.output}`);
462
- break;
562
+ throw new Error(
563
+ `review gate: push after auto-fix failed. Refusing to continue.\n${pushed.output || '(no output)'}`
564
+ );
463
565
  }
464
566
  pushedHeadSha = headSha(fixCwd);
465
567
  const headSync = waitHead(repoRoot, branch, pushedHeadSha, {
466
568
  timeoutSeconds: options.gateHeadTimeoutSeconds,
467
- pollSeconds: options.gateHeadPollSeconds,
569
+ pollSeconds: options.gateHeadPollSeconds
468
570
  });
469
571
  if (headSync.status !== 'current') {
470
572
  const seen = headSync.pr?.headSha || 'unknown';
471
573
  reportProgress(progress, 'fail', 'autofix', `PR head is still ${seen}`);
472
574
  throw new Error(
473
- `review gate: PR #${prNumber} still reports head ${seen}, not the auto-fix commit `
474
- + `${pushedHeadSha || 'unknown'}. Refusing to re-review a stale PR diff.`,
575
+ `review gate: PR #${prNumber} still reports head ${seen}, not the auto-fix commit ` +
576
+ `${pushedHeadSha || 'unknown'}. Refusing to re-review a stale PR diff.`
475
577
  );
476
578
  }
477
- reportProgress(progress, 'complete', 'autofix', `${fix.changedFiles.length} file(s) fixed and pushed`);
579
+ reportProgress(
580
+ progress,
581
+ 'complete',
582
+ 'autofix',
583
+ `${fix.changedFiles.length} file(s) fixed and pushed`
584
+ );
478
585
  }
479
586
 
480
587
  if (!verdict.clean) {
481
- reportProgress(progress, 'fail', 'review', `${verdict.blocking.length} blocking finding(s) remain`);
588
+ reportProgress(
589
+ progress,
590
+ 'fail',
591
+ 'review',
592
+ `${verdict.blocking.length} blocking finding(s) remain`
593
+ );
482
594
  if (!autofixAttempted) {
483
- reportProgress(progress, 'skip', 'autofix', maxFixRounds > 0 ? 'no repair round completed' : 'disabled');
595
+ reportProgress(
596
+ progress,
597
+ 'skip',
598
+ 'autofix',
599
+ maxFixRounds > 0 ? 'no repair round completed' : 'disabled'
600
+ );
484
601
  }
485
602
  const detail = verdict.blocking
486
603
  .map((f) => ` - ${String(f.severity).toUpperCase()} ${f.path}:${f.line} ${f.message}`)
487
604
  .join('\n');
488
605
  throw new Error(
489
- `review gate: ${verdict.blocking.length} blocking finding(s). Refusing to merge.\n${detail}\n`
490
- + (maxFixRounds > 0
491
- ? 'Auto-fix did not clear them. Fix manually or rerun with --skip-review-gate.'
492
- : 'Fix the findings, rerun with --gate-autofix to let the agent repair them, or bypass with --skip-review-gate.'),
606
+ `review gate: ${verdict.blocking.length} blocking finding(s). Refusing to merge.\n${detail}\n` +
607
+ (maxFixRounds > 0
608
+ ? 'Auto-fix did not clear them. Fix manually or rerun with --skip-review-gate.'
609
+ : 'Fix the findings, rerun with --gate-autofix to let the agent repair them, or bypass with --skip-review-gate.')
493
610
  );
494
611
  }
495
612
 
@@ -500,44 +617,84 @@ function runReviewGate({
500
617
  // edited by a fix.
501
618
  const unexplained = resolveCarriedFindings(blockedPaths, repairedPaths, review.findings);
502
619
  if (unexplained.length > 0) {
503
- reportProgress(progress, 'fail', 'review', `${unexplained.length} finding(s) disappeared without a matching edit`);
620
+ reportProgress(
621
+ progress,
622
+ 'fail',
623
+ 'review',
624
+ `${unexplained.length} finding(s) disappeared without a matching edit`
625
+ );
504
626
  throw new Error(
505
- `review gate: ${unexplained.length} earlier blocking finding(s) disappeared without their file being changed. `
506
- + `Refusing to merge — a finding that is merely absent from a later review is not a fixed finding.\n`
507
- + unexplained.map((p) => ` - ${p} (blocked earlier, never edited, no current finding)`).join('\n')
508
- + '\nRe-run the review, fix these by hand, or bypass with --skip-review-gate.',
627
+ `review gate: ${unexplained.length} earlier blocking finding(s) disappeared without their file being changed. ` +
628
+ `Refusing to merge — a finding that is merely absent from a later review is not a fixed finding.\n` +
629
+ unexplained
630
+ .map((p) => ` - ${p} (blocked earlier, never edited, no current finding)`)
631
+ .join('\n') +
632
+ '\nRe-run the review, fix these by hand, or bypass with --skip-review-gate.'
509
633
  );
510
634
  }
511
- const threadResolution = resolveThreads(prNumber, repoRoot, review.findings);
635
+ // A pathless blocker (no .path on the finding) cannot be keyed into
636
+ // blockedPaths or verified by resolveCarriedFindings. If one appeared in any
637
+ // earlier round and is absent from the final clean verdict, it may still
638
+ // exist — the gate must fail closed rather than read the silence as a fix.
639
+ if (hasPathlessBlocker) {
640
+ reportProgress(
641
+ progress,
642
+ 'fail',
643
+ 'review',
644
+ 'blocking finding with no file path disappeared without explanation'
645
+ );
646
+ throw new Error(
647
+ `review gate: a blocking finding with no file path was present in an earlier review round ` +
648
+ `but is absent from the final round. ` +
649
+ `Refusing to merge — a finding absent from one review is not a fixed finding.\n` +
650
+ `Re-run the review, fix the issue by hand, or bypass with --skip-review-gate.`
651
+ );
652
+ }
653
+ const threadResolution = reusable
654
+ ? { ok: true, resolved: 0 }
655
+ : resolveThreads(prNumber, repoRoot, review.findings);
512
656
  if (threadResolution.ok === false) {
513
657
  gateLog(
514
- `PR #${prNumber}: could not inspect outdated GitGuardex review threads`
515
- + `${threadResolution.output ? ` (${threadResolution.output})` : ''}; merge-state gate remains authoritative`,
658
+ `PR #${prNumber}: could not inspect outdated GitGuardex review threads` +
659
+ `${threadResolution.output ? ` (${threadResolution.output})` : ''}; merge-state gate remains authoritative`
516
660
  );
517
661
  } else if (threadResolution.resolved > 0) {
518
- gateLog(`PR #${prNumber}: resolved ${threadResolution.resolved} outdated GitGuardex review thread(s)`);
662
+ logProgress(
663
+ `PR #${prNumber}: resolved ${threadResolution.resolved} outdated GitGuardex review thread(s)`
664
+ );
519
665
  }
520
666
  reportProgress(
521
667
  progress,
522
668
  'complete',
523
669
  'review',
524
- `clean review posted${threadResolution.resolved > 0 ? `; ${threadResolution.resolved} stale thread(s) resolved` : ''}`,
670
+ reusable
671
+ ? 'reused verified Codex review for unchanged head and base'
672
+ : `clean review posted${threadResolution.resolved > 0 ? `; ${threadResolution.resolved} stale thread(s) resolved` : ''}`
525
673
  );
526
674
  if (!autofixAttempted) {
527
675
  reportProgress(progress, 'skip', 'autofix', 'not needed');
528
676
  }
529
- gateLog(
530
- `PR #${prNumber}: review clean (${review.findings.length} non-blocking finding(s)), posted to the PR`,
531
- );
677
+ if (reusable) {
678
+ logProgress(`PR #${prNumber}: reusing its verified Codex review (${reusable.count} non-blocking finding(s))`);
679
+ } else {
680
+ logProgress(
681
+ `PR #${prNumber}: review clean (${review.findings.length} non-blocking finding(s)), posted to the PR`
682
+ );
683
+ const receipt = threadResolution.ok !== false && getReceipt(pushedHeadSha);
684
+ if (receipt) {
685
+ assertReviewedRevision();
686
+ receipt.write(review);
687
+ }
688
+ }
532
689
 
533
690
  // 3. Promote draft -> ready so required CI checks fire. Already done in step
534
691
  // 1b unless serial CI held the draft barrier until the review came in clean.
535
- if (serialCi) {
692
+ if (serialCi && !(reusable && opened.pr.isDraft === false)) {
536
693
  requireGhAction(
537
694
  markReady(repoRoot, prNumber),
538
- `review gate: could not promote PR #${prNumber} after a clean review. Refusing to merge.`,
695
+ `review gate: could not promote PR #${prNumber} after a clean review. Refusing to merge.`
539
696
  );
540
- gateLog(`PR #${prNumber}: promoted to ready after a clean review`);
697
+ logProgress(`PR #${prNumber}: promoted to ready after a clean review`);
541
698
  }
542
699
 
543
700
  // 4. Wait for CI to settle green + GitHub to report mergeable. waitForGreenCi
@@ -550,12 +707,26 @@ function runReviewGate({
550
707
  if (options.gateBaseline) {
551
708
  const baseline = readBaseline(repoRoot, baseBranch);
552
709
  baselineFailures = baseline.failing;
553
- gateLog(baselineFailures.size > 0
554
- ? `baseline from ${baseline.source}: ${baselineFailures.size} check(s) already failing — [${[...baselineFailures].join(', ')}]`
555
- : `baseline from ${baseline.source}: no known failures — every failing check counts as new`);
710
+ gateLog(
711
+ baselineFailures.size > 0
712
+ ? `baseline from ${baseline.source}: ${baselineFailures.size} check(s) already failing — [${[...baselineFailures].join(', ')}]`
713
+ : `baseline from ${baseline.source}: no known failures — every failing check counts as new`
714
+ );
556
715
  }
557
716
 
558
717
  reportProgress(progress, 'start', 'ci', 'waiting for required GitHub checks');
718
+ const revision = { reviewedHeadSha: pushedHeadSha, reviewedBaseSha };
719
+ // Promotion has already started remote CI. Run the pinned local preflight
720
+ // now instead of serializing it after the CI wait. Neither pass replaces the
721
+ // other, and the final publish step rechecks fingerprint and revision.
722
+ if (preflight) {
723
+ try {
724
+ preflight(revision);
725
+ } catch (error) {
726
+ reportProgress(progress, 'fail', 'preflight', error.message);
727
+ throw error;
728
+ }
729
+ }
559
730
  let ci;
560
731
  try {
561
732
  ci = waitGreen(repoRoot, branch, {
@@ -563,7 +734,7 @@ function runReviewGate({
563
734
  pollSeconds: options.gatePollSeconds,
564
735
  requireChecks,
565
736
  baselineFailures,
566
- expectHeadSha: pushedHeadSha,
737
+ expectHeadSha: pushedHeadSha
567
738
  });
568
739
  } catch (error) {
569
740
  reportProgress(progress, 'fail', 'ci', error.message);
@@ -571,36 +742,46 @@ function runReviewGate({
571
742
  }
572
743
  if (ci.status === 'checks-failed') {
573
744
  reportProgress(progress, 'fail', 'ci', 'checks failed or were cancelled');
574
- const novel = Array.isArray(ci.newFailures) && ci.newFailures.length > 0
575
- ? ` New failure(s) vs '${baseBranch}': ${ci.newFailures.join(', ')}.`
576
- : '';
745
+ const novel =
746
+ Array.isArray(ci.newFailures) && ci.newFailures.length > 0
747
+ ? ` New failure(s) vs '${baseBranch}': ${ci.newFailures.join(', ')}.`
748
+ : '';
577
749
  throw new Error(
578
- `review gate: CI checks failed/cancelled on PR #${prNumber}. Refusing to merge.${novel}`
579
- + (options.gateBaseline ? '' : ' Pass --gate-baseline to ignore failures already red on the base branch.'),
750
+ `review gate: CI checks failed/cancelled on PR #${prNumber}. Refusing to merge.${novel}` +
751
+ (options.gateBaseline
752
+ ? ''
753
+ : ' Pass --gate-baseline to ignore failures already red on the base branch.')
580
754
  );
581
755
  }
582
756
  if (ci.status === 'merge-blocked') {
583
757
  const mss = (ci.pr && ci.pr.mergeStateStatus) || 'BLOCKED';
758
+ const mssHints = {
759
+ DIRTY: `resolve conflicts first (${TOOL_NAME} pr sync, or merge the base branch)`,
760
+ BEHIND: `update the branch to head of base (${TOOL_NAME} pr sync)`,
761
+ BLOCKED: 'required reviews or conversations are unresolved',
762
+ UNSTABLE: 'wait for non-required checks or investigate failing ones'
763
+ };
764
+ const hint = mssHints[mss] || 'check branch-protection requirements';
584
765
  reportProgress(progress, 'fail', 'ci', `mergeStateStatus=${mss}`);
585
766
  throw new Error(
586
- `review gate: GitHub reports mergeStateStatus=${mss} for PR #${prNumber} `
587
- + '(not mergeable under branch protection). Refusing to merge.',
767
+ `review gate: GitHub reports mergeStateStatus=${mss} for PR #${prNumber} ` +
768
+ `(not mergeable under branch protection — ${hint}). Refusing to merge.`
588
769
  );
589
770
  }
590
771
  if (ci.status === 'no-checks') {
591
772
  reportProgress(progress, 'fail', 'ci', 'no CI checks configured');
592
773
  throw new Error(
593
- `review gate: PR #${prNumber} has no CI checks configured. Refusing to merge an `
594
- + 'unverified PR. Pass --allow-no-checks to override.',
774
+ `review gate: PR #${prNumber} has no CI checks configured. Refusing to merge an ` +
775
+ 'unverified PR. Pass --allow-no-checks to override.'
595
776
  );
596
777
  }
597
778
  if (ci.status === 'stale-head') {
598
779
  const seen = (ci.pr && ci.pr.headSha) || 'unknown';
599
780
  reportProgress(progress, 'fail', 'ci', `stale PR head ${seen}`);
600
781
  throw new Error(
601
- `review gate: PR #${prNumber} still reports head ${seen}, not the auto-fix commit `
602
- + `${pushedHeadSha}. Refusing to merge — the checks GitHub is reporting describe a `
603
- + 'commit that push replaced, so their green says nothing about the code being merged.',
782
+ `review gate: PR #${prNumber} still reports head ${seen}, not the auto-fix commit ` +
783
+ `${pushedHeadSha}. Refusing to merge — the checks GitHub is reporting describe a ` +
784
+ 'commit that push replaced, so their green says nothing about the code being merged.'
604
785
  );
605
786
  }
606
787
  if (ci.status === 'timeout') {
@@ -612,26 +793,35 @@ function runReviewGate({
612
793
  throw new Error(`review gate: PR #${prNumber} not in a mergeable state (${ci.status}).`);
613
794
  }
614
795
 
796
+ assertReviewedRevision();
797
+ if (reusable && getReceipt(pushedHeadSha)?.read()?.id !== reusable.id) {
798
+ throw new Error('review gate: the saved Codex review changed during CI. Rerun before merging.');
799
+ }
615
800
  const mss = ci.pr && ci.pr.mergeStateStatus;
616
- const billingChecksWaived = Array.isArray(ci.billingWaivedNames)
617
- ? ci.billingWaivedNames
618
- : [];
801
+ const billingChecksWaived = Array.isArray(ci.billingWaivedNames) ? ci.billingWaivedNames : [];
619
802
  if (billingChecksWaived.length > 0) {
620
803
  reportProgress(
621
804
  progress,
622
805
  'complete',
623
806
  'ci',
624
- `${billingChecksWaived.length} GitHub billing-blocked check(s) waived; local preflight required`,
807
+ `${billingChecksWaived.length} GitHub billing-blocked check(s) waived; local preflight required`
625
808
  );
626
809
  gateLog(
627
- `PR #${prNumber}: review clean; GitHub billing prevented [${billingChecksWaived.join(', ')}] from starting. `
628
- + 'Proceeding only with mandatory repository preflight.',
810
+ `PR #${prNumber}: review clean; GitHub billing prevented [${billingChecksWaived.join(', ')}] from starting. ` +
811
+ 'Proceeding only with mandatory repository preflight.'
629
812
  );
630
- return { prNumber, billingChecksWaived };
813
+ return { prNumber, ...revision, billingChecksWaived, requiresLocalPreflight: true };
814
+ }
815
+ if (ci.requiresLocalPreflight) {
816
+ reportProgress(progress, 'complete', 'ci', 'GitHub Actions workflows disabled; local preflight required');
817
+ gateLog(`PR #${prNumber}: review clean; GitHub confirms workflows are disabled. Proceeding only with mandatory repository preflight.`);
818
+ return { prNumber, ...revision, requiresLocalPreflight: true };
631
819
  }
632
820
  reportProgress(progress, 'complete', 'ci', `green${mss ? `, mergeStateStatus=${mss}` : ''}`);
633
- gateLog(`PR #${prNumber}: review clean + CI green${mss ? ` + mergeStateStatus=${mss}` : ''} — proceeding to merge`);
634
- return { prNumber };
821
+ logProgress(
822
+ `PR #${prNumber}: review clean + CI green${mss ? ` + mergeStateStatus=${mss}` : ''} — proceeding to merge`
823
+ );
824
+ return { prNumber, ...revision };
635
825
  }
636
826
 
637
827
  module.exports = {
@@ -640,5 +830,5 @@ module.exports = {
640
830
  waitForGreenCi,
641
831
  waitForPullRequestHead,
642
832
  DEFAULT_GATE_TIMEOUT_SECONDS,
643
- MERGEABLE_STATES,
833
+ MERGEABLE_STATES
644
834
  };