@imdeadpool/guardex 8.1.0 → 8.3.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.
@@ -1,5 +1,5 @@
1
1
  // @ts-check
2
- const { TOOL_NAME, LOCK_FILE_RELATIVE, path, fs } = require('../context');
2
+ const { TOOL_NAME, SHORT_TOOL_NAME, LOCK_FILE_RELATIVE, path, fs } = require('../context');
3
3
  const { isTerseMode } = require('../output');
4
4
  const { run, runPackageAsset, assetStdio } = require('../core/runtime');
5
5
  const {
@@ -31,7 +31,7 @@ const {
31
31
  const submoduleModule = require('../submodule');
32
32
  const { runPreflight, summarizePreflight } = require('./preflight');
33
33
  const { runReviewGate } = require('./review-gate');
34
- const { createFinishProgress } = require('./progress');
34
+ const { createFinishProgress, summarizeFinishRun } = require('./progress');
35
35
 
36
36
  /**
37
37
  * Options recognized by {@link autoCommitWorktreeForFinish} and the public
@@ -53,6 +53,7 @@ const { createFinishProgress } = require('./progress');
53
53
  * @property {string} [branch] Single branch to finish (skips discovery).
54
54
  * @property {string} [base] Explicit base branch override.
55
55
  * @property {string} [target] Path inside the target repo (defaults to cwd).
56
+ * @property {boolean} [agentQuiet] Capture narrative finish output and emit compact JSON summaries.
56
57
  */
57
58
 
58
59
  /**
@@ -210,6 +211,33 @@ function autoCommitWorktreeForFinish(repoRoot, worktreePath, branch, options) {
210
211
  * @throws {Error} When the underlying prune subprocess exits non-zero or the watch sleep fails.
211
212
  */
212
213
  function cleanup(rawArgs) {
214
+ if (rawArgs.some((arg) => arg === '--help' || arg === '-h') || (rawArgs.length === 1 && rawArgs[0] === 'help')) {
215
+ console.log(`USAGE: ${SHORT_TOOL_NAME} cleanup [options]
216
+
217
+ Prune merged or stale agent branches and worktrees.
218
+
219
+ OPTIONS
220
+ --target <path> Target repository (default: current directory)
221
+ --base <branch> Base branch used to determine merged branches
222
+ --branch <agent/*> Limit cleanup to one agent branch
223
+ --dry-run Print actions without changing branches or worktrees
224
+ --force-dirty Allow cleanup of dirty worktrees
225
+ --keep-remote Keep remote agent branches
226
+ --prune-clean-worktrees Explicitly prune clean, unmerged agent worktrees
227
+ --keep-clean-worktrees Preserve clean, unmerged agent worktrees (default)
228
+ --include-clean-linked-worktrees
229
+ Also prune clean linked worktrees outside managed agent directories
230
+ --include-pr-merged Treat branches from merged PRs as merged
231
+ --idle-minutes <n> Only consider worktrees idle for at least n minutes
232
+ --watch Repeat cleanup cycles (defaults idle threshold to 60)
233
+ --interval <seconds> Watch interval in seconds (minimum: 5; default: 60)
234
+ --once Run one cleanup cycle when used with --watch
235
+ --max-branches <n> Limit branches processed per cycle
236
+ -h, --help Show this help`);
237
+ process.exitCode = 0;
238
+ return;
239
+ }
240
+
213
241
  const activeCwd = process.cwd();
214
242
  const options = parseCleanupArgs(rawArgs);
215
243
  const repoRoot = resolveRepoRoot(options.target);
@@ -230,6 +258,9 @@ function cleanup(rawArgs) {
230
258
  if (!options.keepCleanWorktrees) {
231
259
  args.push('--only-dirty-worktrees');
232
260
  }
261
+ if (options.includeCleanLinkedWorktrees) {
262
+ args.push('--include-clean-linked-worktrees');
263
+ }
233
264
  if (options.includePrMerged) {
234
265
  args.push('--include-pr-merged');
235
266
  }
@@ -394,7 +425,7 @@ function finish(rawArgs, defaults = {}) {
394
425
  let succeeded = 0;
395
426
  let failed = 0;
396
427
  let autoCommitted = 0;
397
- const terse = isTerseMode();
428
+ const terse = isTerseMode() || options.agentQuiet;
398
429
 
399
430
  for (const candidate of candidates) {
400
431
  const { branch, baseBranch, worktreePath } = candidate;
@@ -403,6 +434,7 @@ function finish(rawArgs, defaults = {}) {
403
434
  branch,
404
435
  baseBranch,
405
436
  persistEvents: !options.dryRun,
437
+ quiet: options.agentQuiet,
406
438
  });
407
439
  // In terse mode, defer the "Finishing X -> Y" line until we know whether
408
440
  // we also need to announce an auto-commit, then emit a single combined
@@ -425,9 +457,11 @@ function finish(rawArgs, defaults = {}) {
425
457
  const suffix = commitState.committed
426
458
  ? ' [auto-committed]'
427
459
  : (commitState.changed && commitState.dryRun ? ' [dry-run: would auto-commit]' : '');
428
- console.log(
429
- `[${TOOL_NAME}] Finishing '${branch}' -> '${baseBranch}'${worktreePath ? ` (${worktreePath})` : ''}${suffix}`,
430
- );
460
+ if (!options.agentQuiet) {
461
+ console.log(
462
+ `[${TOOL_NAME}] Finishing '${branch}' -> '${baseBranch}'${worktreePath ? ` (${worktreePath})` : ''}${suffix}`,
463
+ );
464
+ }
431
465
  if (commitState.committed) {
432
466
  autoCommitted += 1;
433
467
  }
@@ -510,7 +544,7 @@ function finish(rawArgs, defaults = {}) {
510
544
  const preflight = runPreflight(repoRoot, worktreePath, branch, baseBranch, {
511
545
  verbose: !terse,
512
546
  });
513
- console.log(`[${TOOL_NAME}] ${summarizePreflight(preflight)}`);
547
+ if (!options.agentQuiet) console.log(`[${TOOL_NAME}] ${summarizePreflight(preflight)}`);
514
548
  if (preflight.status === 'failed') {
515
549
  progress.fail('preflight', `${preflight.failures.length} script(s) failed`);
516
550
  for (const f of preflight.failures) {
@@ -536,8 +570,9 @@ function finish(rawArgs, defaults = {}) {
536
570
  // Opt-in merge gate (--gate-review / gx ship): enforce a clean AI review +
537
571
  // green CI + GitHub-mergeable verdict BEFORE the shell merge runs. Throws on
538
572
  // failure, which the catch below turns into a finish failure (no merge).
573
+ let gateResult;
539
574
  if (options.mergeMode === 'pr' && options.gateReview) {
540
- runReviewGate({
575
+ gateResult = runReviewGate({
541
576
  repoRoot, worktreePath, branch, baseBranch, options, progress,
542
577
  });
543
578
  } else {
@@ -563,20 +598,29 @@ function finish(rawArgs, defaults = {}) {
563
598
  // drift apart.
564
599
  const finishResult = runPackageAsset('branchFinish', finishArgs, {
565
600
  cwd: repoRoot,
566
- stdio: assetStdio('branchFinish'),
601
+ stdio: options.agentQuiet ? 'pipe' : assetStdio('branchFinish'),
567
602
  env: {
568
603
  GUARDEX_FINISH_ACTIVE_CWD: activeCwd,
569
604
  GUARDEX_FINISH_CHECKLIST: '1',
570
605
  GUARDEX_FINISH_GATE_DONE: options.gateReview ? '1' : '0',
606
+ GUARDEX_FINISH_REQUIRE_PREFLIGHT: gateResult?.billingChecksWaived?.length > 0 ? '1' : '0',
571
607
  ...progress.eventEnv,
572
608
  },
573
609
  });
574
- // Null under 'inherit'; kept so an explicit pipe still prints.
575
- if (finishResult.stdout) {
576
- process.stdout.write(finishResult.stdout);
577
- }
578
- if (finishResult.stderr) {
579
- process.stderr.write(finishResult.stderr);
610
+ if (options.agentQuiet) {
611
+ const summary = summarizeFinishRun({
612
+ eventFile: progress.eventEnv.GUARDEX_FINISH_EVENT_FILE,
613
+ branch,
614
+ baseBranch,
615
+ stdout: finishResult.stdout,
616
+ stderr: finishResult.stderr,
617
+ status: finishResult.status,
618
+ });
619
+ process.stdout.write(`[gx:finish] ${JSON.stringify(summary)}\n`);
620
+ } else {
621
+ // Null under 'inherit'; kept so an explicit pipe still prints.
622
+ if (finishResult.stdout) process.stdout.write(finishResult.stdout);
623
+ if (finishResult.stderr) process.stderr.write(finishResult.stderr);
580
624
  }
581
625
  if (finishResult.status !== 0) {
582
626
  throw new Error(`agent-branch-finish exited with status ${finishResult.status}`);
@@ -592,9 +636,18 @@ function finish(rawArgs, defaults = {}) {
592
636
  }
593
637
  }
594
638
 
595
- console.log(
596
- `[${TOOL_NAME}] Finish summary: total=${candidates.length}, success=${succeeded}, failed=${failed}, autoCommitted=${autoCommitted}`,
597
- );
639
+ if (options.agentQuiet) {
640
+ process.stdout.write(`[gx:finish] ${JSON.stringify({
641
+ total: candidates.length,
642
+ success: succeeded,
643
+ failed,
644
+ autoCommitted,
645
+ })}\n`);
646
+ } else {
647
+ console.log(
648
+ `[${TOOL_NAME}] Finish summary: total=${candidates.length}, success=${succeeded}, failed=${failed}, autoCommitted=${autoCommitted}`,
649
+ );
650
+ }
598
651
 
599
652
  // Bulk `--all` finish self-cleans: sweep merged-but-stranded worktree dirs
600
653
  // whose branch was merged out-of-band and never reaped (the post-merge
@@ -607,10 +660,10 @@ function finish(rawArgs, defaults = {}) {
607
660
  if (baseForSweep) {
608
661
  sweepArgs.push('--base', baseForSweep);
609
662
  }
610
- console.log(`[${TOOL_NAME}] Sweeping merged-but-stranded worktrees...`);
663
+ if (!options.agentQuiet) console.log(`[${TOOL_NAME}] Sweeping merged-but-stranded worktrees...`);
611
664
  const sweep = runPackageAsset('worktreePrune', sweepArgs, {
612
665
  cwd: repoRoot,
613
- stdio: 'inherit',
666
+ stdio: options.agentQuiet ? 'pipe' : 'inherit',
614
667
  env: { GUARDEX_PRUNE_ACTIVE_CWD: activeCwd },
615
668
  });
616
669
  if (sweep.status !== 0) {
@@ -0,0 +1,324 @@
1
+ const crypto = require('node:crypto');
2
+ const { cp, fs, path, TOOL_NAME } = require('../context');
3
+ const { currentBranchName, listAgentWorktrees, resolveRepoRoot } = require('../git');
4
+ const { extractTargetedArgs, run } = require('../core/runtime');
5
+
6
+ function booleanLike(value, fallback) {
7
+ if (value == null || String(value).trim() === '') return fallback;
8
+ return !['0', 'false', 'no', 'off'].includes(String(value).trim().toLowerCase());
9
+ }
10
+
11
+ function cleanupRequested(args, env = process.env) {
12
+ let requested = booleanLike(env.GUARDEX_FINISH_CLEANUP, true);
13
+ for (const arg of args) {
14
+ if (arg === '--cleanup') requested = true;
15
+ if (arg === '--no-cleanup') requested = false;
16
+ }
17
+ return requested;
18
+ }
19
+
20
+ function flagValue(args, flag) {
21
+ const index = args.indexOf(flag);
22
+ if (index >= 0 && index + 1 < args.length) return args[index + 1];
23
+ const inline = args.find((arg) => arg.startsWith(`${flag}=`));
24
+ return inline ? inline.slice(flag.length + 1) : '';
25
+ }
26
+
27
+ function pathContains(root, candidate) {
28
+ const relative = path.relative(root, candidate);
29
+ return (
30
+ relative === '' ||
31
+ (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
32
+ );
33
+ }
34
+
35
+ function captureWorktreeIdentity(worktreePath, runner = run) {
36
+ try {
37
+ const gitDirResult = runner('git', ['-C', worktreePath, 'rev-parse', '--absolute-git-dir'], {
38
+ cwd: worktreePath
39
+ });
40
+ if (gitDirResult.status !== 0 || !String(gitDirResult.stdout || '').trim()) return null;
41
+ const gitDir = path.resolve(String(gitDirResult.stdout).trim());
42
+ const markerPath = path.join(gitDir, 'gitguardex-finish-cleanup-id');
43
+ let token;
44
+ try {
45
+ token = crypto.randomUUID();
46
+ fs.writeFileSync(markerPath, `${token}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
47
+ } catch (error) {
48
+ if (error.code !== 'EEXIST') return null;
49
+ token = fs.readFileSync(markerPath, 'utf8').trim();
50
+ }
51
+ return token ? { gitDir, token } : null;
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ function worktreeIdentityMatches(plan, runner = run) {
58
+ if (!plan?.worktreeIdentity) return false;
59
+ try {
60
+ const gitDirResult = runner(
61
+ 'git',
62
+ ['-C', plan.worktreePath, 'rev-parse', '--absolute-git-dir'],
63
+ { cwd: plan.worktreePath }
64
+ );
65
+ if (gitDirResult.status !== 0) return false;
66
+ const gitDir = path.resolve(String(gitDirResult.stdout || '').trim());
67
+ if (gitDir !== plan.worktreeIdentity.gitDir) return false;
68
+ return (
69
+ fs.readFileSync(path.join(gitDir, 'gitguardex-finish-cleanup-id'), 'utf8').trim() ===
70
+ plan.worktreeIdentity.token
71
+ );
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ function resolveSharedRepoRoot(target) {
78
+ const worktreeRoot = resolveRepoRoot(target);
79
+ const commonDir = run('git', ['-C', worktreeRoot, 'rev-parse', '--git-common-dir'], {
80
+ cwd: worktreeRoot
81
+ });
82
+ if (commonDir.status !== 0 || !String(commonDir.stdout || '').trim()) {
83
+ throw new Error('Unable to resolve the shared git directory');
84
+ }
85
+ return path.dirname(path.resolve(worktreeRoot, String(commonDir.stdout).trim()));
86
+ }
87
+
88
+ function isManagedAgentWorktree(repoRoot, worktreePath) {
89
+ const relative = path.relative(repoRoot, worktreePath).split(path.sep).join('/');
90
+ return (
91
+ relative.startsWith('.omx/agent-worktrees/') || relative.startsWith('.omc/agent-worktrees/')
92
+ );
93
+ }
94
+
95
+ function hasUnsafeWorktreeChanges(output) {
96
+ return String(output || '')
97
+ .split('\0')
98
+ .filter(Boolean)
99
+ .some((entry) => {
100
+ if (!entry.startsWith('!! ')) return true;
101
+ const ignoredPath = entry.slice(3).replace(/\/$/, '');
102
+ const segments = ignoredPath.split('/');
103
+ return !(
104
+ segments[0] === '.omx' ||
105
+ segments[0] === '.omc' ||
106
+ segments.includes('node_modules')
107
+ );
108
+ });
109
+ }
110
+
111
+ function probeLiveProcessInWorktree(worktreePath, options = {}) {
112
+ const procRoot = options.procRoot ?? (process.platform === 'linux' ? '/proc' : '');
113
+ const readlink = options.readlink || fs.readlinkSync;
114
+ const runner = options.runner || run;
115
+ let procScanIncomplete = false;
116
+
117
+ if (procRoot && fs.existsSync(procRoot)) {
118
+ try {
119
+ for (const entry of fs.readdirSync(procRoot, { withFileTypes: true })) {
120
+ if (!entry.isDirectory() || !/^\d+$/.test(entry.name)) continue;
121
+ const processDir = path.join(procRoot, entry.name);
122
+ try {
123
+ if (
124
+ typeof process.geteuid === 'function' &&
125
+ fs.statSync(processDir).uid !== process.geteuid()
126
+ ) {
127
+ continue;
128
+ }
129
+ const liveCwd = readlink(path.join(processDir, 'cwd')).replace(/ \(deleted\)$/, '');
130
+ if (pathContains(worktreePath, liveCwd)) return { supported: true, active: true };
131
+ } catch (error) {
132
+ if (!['ENOENT', 'ESRCH'].includes(error.code)) {
133
+ procScanIncomplete = true;
134
+ }
135
+ }
136
+ }
137
+ } catch {
138
+ procScanIncomplete = true;
139
+ }
140
+ if (!procScanIncomplete) return { supported: true, active: false };
141
+ }
142
+
143
+ const lsofArgs = ['-a'];
144
+ if (typeof process.geteuid === 'function') lsofArgs.push('-u', String(process.geteuid()));
145
+ lsofArgs.push('-d', 'cwd', '-Fn');
146
+ const lsof = runner('lsof', lsofArgs, {
147
+ cwd: path.dirname(worktreePath)
148
+ });
149
+ if (![0, 1].includes(lsof.status)) return { supported: false, active: true };
150
+ const active = String(lsof.stdout || '')
151
+ .split(/\r?\n/)
152
+ .filter((line) => line.startsWith('n'))
153
+ .map((line) => line.slice(1).replace(/ \(deleted\)$/, ''))
154
+ .some((liveCwd) => pathContains(worktreePath, liveCwd));
155
+ return { supported: true, active };
156
+ }
157
+
158
+ function hasLiveProcessInWorktree(
159
+ worktreePath,
160
+ procRoot = process.platform === 'linux' ? '/proc' : '',
161
+ runner = run
162
+ ) {
163
+ return probeLiveProcessInWorktree(worktreePath, { procRoot, runner }).active;
164
+ }
165
+
166
+ function prepareBranchFinishCleanup(argv, activeCwd) {
167
+ if (argv[0] !== 'branch' || argv[1] !== 'finish') return null;
168
+ const finishArgs = argv.slice(2);
169
+ if (finishArgs.some((arg) => arg === '--help' || arg === '-h') || !cleanupRequested(finishArgs)) {
170
+ return null;
171
+ }
172
+
173
+ try {
174
+ const { target, passthrough } = extractTargetedArgs(finishArgs, activeCwd);
175
+ const repoRoot = resolveSharedRepoRoot(target);
176
+ const branch = flagValue(passthrough, '--branch') || currentBranchName(target);
177
+ const worktreePath = listAgentWorktrees(repoRoot).find(
178
+ (entry) => entry.branch === branch
179
+ )?.worktreePath;
180
+ if (
181
+ !worktreePath ||
182
+ !isManagedAgentWorktree(repoRoot, worktreePath) ||
183
+ !pathContains(worktreePath, activeCwd)
184
+ ) {
185
+ return null;
186
+ }
187
+ const worktreeIdentity = captureWorktreeIdentity(worktreePath);
188
+ return worktreeIdentity ? { repoRoot, worktreePath, worktreeIdentity } : null;
189
+ } catch {
190
+ return null;
191
+ }
192
+ }
193
+
194
+ function cleanupFinishedDetachedWorktree(plan) {
195
+ if (!plan || !worktreeIdentityMatches(plan)) return false;
196
+
197
+ try {
198
+ process.chdir(plan.repoRoot);
199
+ if (hasLiveProcessInWorktree(plan.worktreePath)) return false;
200
+ if (!worktreeIdentityMatches(plan)) return false;
201
+ const status = run(
202
+ 'git',
203
+ ['-C', plan.worktreePath, 'status', '--porcelain=v1', '-z', '--ignored'],
204
+ { cwd: plan.repoRoot }
205
+ );
206
+ const head = run('git', ['-C', plan.worktreePath, 'rev-parse', '--abbrev-ref', 'HEAD'], {
207
+ cwd: plan.repoRoot
208
+ });
209
+ if (
210
+ status.status !== 0 ||
211
+ hasUnsafeWorktreeChanges(status.stdout) ||
212
+ head.status !== 0 ||
213
+ String(head.stdout || '').trim() !== 'HEAD'
214
+ ) {
215
+ return false;
216
+ }
217
+ if (!worktreeIdentityMatches(plan)) return false;
218
+
219
+ const remove = run('git', ['-C', plan.repoRoot, 'worktree', 'remove', plan.worktreePath], {
220
+ cwd: plan.repoRoot
221
+ });
222
+ if (remove.status !== 0) {
223
+ console.error(
224
+ `[${TOOL_NAME}] Warning: finished detached worktree cleanup failed: ${plan.worktreePath}`
225
+ );
226
+ return false;
227
+ }
228
+ run('git', ['-C', plan.repoRoot, 'worktree', 'prune'], { cwd: plan.repoRoot });
229
+ console.log(
230
+ `[${TOOL_NAME}] Removed finished detached worktree after finish worker exit: ${plan.worktreePath}`
231
+ );
232
+ return true;
233
+ } catch (error) {
234
+ console.error(
235
+ `[${TOOL_NAME}] Warning: finished detached worktree cleanup failed: ${error.message}`
236
+ );
237
+ return false;
238
+ }
239
+ }
240
+
241
+ function scheduleFinishedDetachedWorktreeCleanup(plan, options = {}) {
242
+ if (!plan || !fs.existsSync(plan.worktreePath)) return false;
243
+
244
+ try {
245
+ const runner = options.runner || run;
246
+ const worktreeIdentity =
247
+ plan.worktreeIdentity || captureWorktreeIdentity(plan.worktreePath, runner);
248
+ if (!worktreeIdentity) return false;
249
+ const cleanupPlan = { ...plan, worktreeIdentity };
250
+ if (!worktreeIdentityMatches(cleanupPlan, runner)) return false;
251
+ const probe = probeLiveProcessInWorktree(plan.worktreePath, options);
252
+ if (!probe.supported) {
253
+ console.error(
254
+ `[${TOOL_NAME}] Warning: cannot safely monitor the finished worktree; deferred cleanup was not started: ${plan.worktreePath}`
255
+ );
256
+ return false;
257
+ }
258
+ const payload = Buffer.from(JSON.stringify(cleanupPlan), 'utf8').toString('base64url');
259
+ const child = (options.spawn || cp.spawn)(
260
+ process.execPath,
261
+ [__filename, '--deferred-worker', payload],
262
+ {
263
+ cwd: plan.repoRoot,
264
+ detached: true,
265
+ stdio: 'ignore'
266
+ }
267
+ );
268
+ child.once('error', (error) => {
269
+ console.error(
270
+ `[${TOOL_NAME}] Warning: deferred cleanup worker failed to start: ${error.message}`
271
+ );
272
+ });
273
+ child.unref();
274
+ console.log(
275
+ `[${TOOL_NAME}] Scheduled finished worktree cleanup after active processes leave: ${plan.worktreePath}`
276
+ );
277
+ return true;
278
+ } catch (error) {
279
+ console.error(
280
+ `[${TOOL_NAME}] Warning: could not schedule finished worktree cleanup: ${error.message}`
281
+ );
282
+ return false;
283
+ }
284
+ }
285
+
286
+ async function runDeferredCleanupWorker(plan, options = {}) {
287
+ const attempts = options.attempts ?? Number.POSITIVE_INFINITY;
288
+ const intervalMs = options.intervalMs ?? 1000;
289
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
290
+ if (!fs.existsSync(plan.worktreePath)) return true;
291
+ if (!worktreeIdentityMatches(plan, options.runner || run)) return false;
292
+ const probe = probeLiveProcessInWorktree(plan.worktreePath, options);
293
+ if (!probe.supported) return false;
294
+ if (!probe.active) {
295
+ return cleanupFinishedDetachedWorktree(plan);
296
+ }
297
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
298
+ }
299
+ return false;
300
+ }
301
+
302
+ module.exports = {
303
+ captureWorktreeIdentity,
304
+ cleanupFinishedDetachedWorktree,
305
+ hasUnsafeWorktreeChanges,
306
+ hasLiveProcessInWorktree,
307
+ isManagedAgentWorktree,
308
+ probeLiveProcessInWorktree,
309
+ prepareBranchFinishCleanup,
310
+ runDeferredCleanupWorker,
311
+ scheduleFinishedDetachedWorktreeCleanup,
312
+ worktreeIdentityMatches
313
+ };
314
+
315
+ if (require.main === module && process.argv[2] === '--deferred-worker') {
316
+ try {
317
+ const plan = JSON.parse(Buffer.from(process.argv[3] || '', 'base64url').toString('utf8'));
318
+ void runDeferredCleanupWorker(plan).then((cleaned) => {
319
+ process.exitCode = cleaned ? 0 : 1;
320
+ });
321
+ } catch {
322
+ process.exitCode = 1;
323
+ }
324
+ }
@@ -119,10 +119,14 @@ function createFinishProgress({
119
119
  now = Date.now,
120
120
  heartbeat,
121
121
  heartbeatIntervalMs = 15_000,
122
+ quiet = false,
122
123
  } = {}) {
123
- const output = write || ((line) => process.stderr.write(`${line}\n`));
124
- const heartbeatFactory = heartbeat === undefined
125
- ? (write ? null : startStageHeartbeat)
124
+ const sink = write || ((line) => process.stderr.write(`${line}\n`));
125
+ const output = quiet ? () => {} : sink;
126
+ const heartbeatFactory = quiet
127
+ ? null
128
+ : heartbeat === undefined
129
+ ? (write ? null : startStageHeartbeat)
126
130
  : heartbeat;
127
131
  const clock = typeof now === 'function' ? now : Date.now;
128
132
  const eventStream = persistEvents ? createEventStream(repoRoot, branch, baseBranch) : null;
@@ -251,10 +255,60 @@ function createFinishProgress({
251
255
  };
252
256
  }
253
257
 
258
+ function readFinishEvents(filePath) {
259
+ if (!filePath) return [];
260
+ try {
261
+ return fs.readFileSync(filePath, 'utf8')
262
+ .split('\n')
263
+ .filter(Boolean)
264
+ .map((line) => JSON.parse(line));
265
+ } catch (_error) {
266
+ return [];
267
+ }
268
+ }
269
+
270
+ /** Build one bounded machine-readable result from a captured finish run. */
271
+ function summarizeFinishRun({
272
+ eventFile,
273
+ branch,
274
+ baseBranch,
275
+ stdout = '',
276
+ stderr = '',
277
+ status = 0,
278
+ } = {}) {
279
+ const events = readFinishEvents(eventFile);
280
+ const latest = new Map();
281
+ for (const event of events) {
282
+ if (event && event.stage && event.stage !== 'finish') latest.set(event.stage, event);
283
+ }
284
+ const stages = {};
285
+ for (const [id] of STAGES) {
286
+ const event = latest.get(id);
287
+ if (!event || event.state === 'pending') continue;
288
+ stages[id] = event.detail ? `${event.state}: ${event.detail}` : event.state;
289
+ }
290
+ const combined = `${stdout}\n${stderr}`;
291
+ const pr = combined.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/)?.[0] || undefined;
292
+ const result = {
293
+ branch: branch || '',
294
+ base: baseBranch || '',
295
+ result: status === 0 ? 'success' : 'failed',
296
+ stages,
297
+ };
298
+ if (pr) result.pr = pr;
299
+ if (status !== 0) {
300
+ const lines = combined.split('\n').map((line) => line.trim()).filter(Boolean);
301
+ const tail = lines.slice(-12).join('\n');
302
+ if (tail) result.error = tail.slice(-2_000);
303
+ }
304
+ return result;
305
+ }
306
+
254
307
  module.exports = {
255
308
  STAGES,
256
309
  createEventStream,
257
310
  createFinishProgress,
311
+ summarizeFinishRun,
258
312
  };
259
313
  const crypto = require('node:crypto');
260
314
  const fs = require('node:fs');
@@ -179,6 +179,11 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
179
179
  // `NaN > 0` is false — which would wave a failing check straight through.
180
180
  const count = (key) => Number(c[key]) || 0;
181
181
  const failingCount = count('failed') + count('cancelled');
182
+ const waivedCount = count('waived');
183
+ const billingWaivedNames = Array.isArray(snap.billingWaivedNames)
184
+ ? snap.billingWaivedNames
185
+ : [];
186
+ const namedWaivers = waivedCount > 0 && billingWaivedNames.length === waivedCount;
182
187
  const settled = count('pending') === 0;
183
188
  const namedFailures = failedNames.length === failingCount;
184
189
  const novelFailures = failedNames.filter((name) => !baseline.has(name));
@@ -199,6 +204,13 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
199
204
  // base baseline and GitHub still says the branch is mergeable, that state is
200
205
  // the same "no new failures" verdict as UNSTABLE.
201
206
  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');
202
214
  // GitHub says this can't merge as-is. Some BLOCKED/UNSTABLE snapshots are
203
215
  // just "required checks are still pending" immediately after a draft PR is
204
216
  // promoted to ready, so wait for pending checks to settle before treating
@@ -207,7 +219,9 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
207
219
  if (mss && (mss === 'DIRTY' || mss === 'BEHIND')) {
208
220
  return { status: 'merge-blocked', pr: snap };
209
221
  }
210
- if (mss && blockedStates.has(mss) && settled && !baselineBlockedByKnownChecks) {
222
+ if (mss && blockedStates.has(mss) && settled
223
+ && !baselineBlockedByKnownChecks
224
+ && !unstableOnlyBecauseBillingChecksWereWaived) {
211
225
  return { status: 'merge-blocked', pr: snap };
212
226
  }
213
227
 
@@ -219,12 +233,23 @@ function waitForGreenCi(repoRoot, branch, options = {}) {
219
233
  // pre-existing: UNSTABLE joins the trusted verdicts, and the no-verdict
220
234
  // fallback accounts every check as success-or-cleared-failure. `other` must
221
235
  // 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);
236
+ 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
+ );
226
247
 
227
- if (settled && mergeable && hasChecks && trusted) return { status: 'green', pr: snap };
248
+ if (settled && mergeable && hasChecks && trusted) {
249
+ const result = { status: 'green', pr: snap };
250
+ if (namedWaivers) result.billingWaivedNames = billingWaivedNames;
251
+ return result;
252
+ }
228
253
  if (settled && mergeable && !hasChecks && (mss ? MERGEABLE_STATES.has(mss) : true)) {
229
254
  if (!requireChecks) return { status: 'green', pr: snap };
230
255
  // No checks yet — give CI a grace window to create check runs before
@@ -588,6 +613,22 @@ function runReviewGate({
588
613
  }
589
614
 
590
615
  const mss = ci.pr && ci.pr.mergeStateStatus;
616
+ const billingChecksWaived = Array.isArray(ci.billingWaivedNames)
617
+ ? ci.billingWaivedNames
618
+ : [];
619
+ if (billingChecksWaived.length > 0) {
620
+ reportProgress(
621
+ progress,
622
+ 'complete',
623
+ 'ci',
624
+ `${billingChecksWaived.length} GitHub billing-blocked check(s) waived; local preflight required`,
625
+ );
626
+ gateLog(
627
+ `PR #${prNumber}: review clean; GitHub billing prevented [${billingChecksWaived.join(', ')}] from starting. `
628
+ + 'Proceeding only with mandatory repository preflight.',
629
+ );
630
+ return { prNumber, billingChecksWaived };
631
+ }
591
632
  reportProgress(progress, 'complete', 'ci', `green${mss ? `, mergeStateStatus=${mss}` : ''}`);
592
633
  gateLog(`PR #${prNumber}: review clean + CI green${mss ? ` + mergeStateStatus=${mss}` : ''} — proceeding to merge`);
593
634
  return { prNumber };