@imdeadpool/guardex 8.2.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.
@@ -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
+ }
@@ -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 };
package/src/git/index.js CHANGED
@@ -1087,10 +1087,10 @@ function branchExists(repoRoot, branch) {
1087
1087
  }
1088
1088
 
1089
1089
  /**
1090
- * Resolve the base branch for the finish flow: CLI override wins; otherwise
1091
- * the per-branch `branch.<source>.guardexBase` recorded at branch-start;
1092
- * otherwise the repo-wide configured base; otherwise the repo's detected
1093
- * default branch.
1090
+ * Resolve the base branch for the finish flow: CLI override wins and repairs
1091
+ * the branch metadata before any gate can restart the finish; otherwise the
1092
+ * per-branch `branch.<source>.guardexBase` recorded at branch-start; otherwise
1093
+ * the repo-wide configured base; otherwise the repo's detected default branch.
1094
1094
  *
1095
1095
  * @param {string} repoRoot Repo to inspect.
1096
1096
  * @param {string} sourceBranch Source agent branch (used for per-branch base).
@@ -1099,6 +1099,11 @@ function branchExists(repoRoot, branch) {
1099
1099
  */
1100
1100
  function resolveFinishBaseBranch(repoRoot, sourceBranch, explicitBase) {
1101
1101
  if (explicitBase) {
1102
+ const explicitBaseExists = branchExists(repoRoot, explicitBase)
1103
+ || gitRefExists(repoRoot, `refs/remotes/origin/${explicitBase}`);
1104
+ if (sourceBranch && explicitBaseExists) {
1105
+ gitRun(repoRoot, ['config', `branch.${sourceBranch}.guardexBase`, explicitBase]);
1106
+ }
1102
1107
  return explicitBase;
1103
1108
  }
1104
1109
 
package/src/pr-checks.js CHANGED
@@ -90,19 +90,28 @@ function latestStatusChecks(value) {
90
90
  };
91
91
  }
92
92
 
93
- function summarizeStatusCheckRollup(value) {
93
+ function summarizeStatusCheckRollup(value, { isWaived = () => false } = {}) {
94
94
  const { checks, superseded } = latestStatusChecks(value);
95
95
  const failedNames = [];
96
+ const waivedNames = [];
97
+ let waivedCount = 0;
96
98
  const summary = checks.reduce(
97
99
  (acc, check) => {
98
100
  const state = String(check?.conclusion || check?.state || check?.status || '').toUpperCase();
99
- if (state === 'SUCCESS') acc.success += 1;
101
+ const failing = FAILING_CONCLUSIONS.has(state);
102
+ const waived = failing && isWaived(check);
103
+ if (waived) {
104
+ const name = checkName(check);
105
+ if (name) waivedNames.push(name);
106
+ waivedCount += 1;
107
+ } else if (state === 'SUCCESS') acc.success += 1;
108
+ else if (state === 'SKIPPED') acc.skipped = (acc.skipped || 0) + 1;
100
109
  else if (state === 'CANCELLED') acc.cancelled += 1;
101
- else if (FAILING_CONCLUSIONS.has(state)) acc.failed += 1;
110
+ else if (failing) acc.failed += 1;
102
111
  else if (state === 'PENDING' || state === 'IN_PROGRESS' || state === 'QUEUED') acc.pending += 1;
103
112
  else acc.other += 1;
104
113
 
105
- if (FAILING_CONCLUSIONS.has(state)) {
114
+ if (failing && !waived) {
106
115
  const name = checkName(check);
107
116
  if (name) failedNames.push(name);
108
117
  }
@@ -110,8 +119,14 @@ function summarizeStatusCheckRollup(value) {
110
119
  },
111
120
  { success: 0, failed: 0, pending: 0, cancelled: 0, other: 0, total: checks.length },
112
121
  );
122
+ if (waivedCount > 0) summary.waived = waivedCount;
113
123
 
114
- return { summary, failedNames, supersededCount: superseded.length };
124
+ return {
125
+ summary,
126
+ failedNames,
127
+ waivedNames,
128
+ supersededCount: superseded.length,
129
+ };
115
130
  }
116
131
 
117
132
  module.exports = {
package/src/pr.js CHANGED
@@ -18,6 +18,8 @@ const {
18
18
  const { repoApiPath } = require('./github-api');
19
19
  const { FAILING_CONCLUSIONS, summarizeStatusCheckRollup } = require('./pr-checks');
20
20
 
21
+ const BILLING_BLOCKED_JOB_MESSAGE = /^The job was not started because recent account payments have failed or your spending limit needs to be increased\. Please check the ['"]Billing & plans['"] section in your settings\.?$/i;
22
+
21
23
  const DEFAULT_POLL_INTERVAL_MS = 5_000;
22
24
  const DEFAULT_POLL_TIMEOUT_MS = 10 * 60 * 1000;
23
25
 
@@ -57,6 +59,114 @@ function ghJson(repoRoot, args) {
57
59
  }
58
60
  }
59
61
 
62
+ function githubActionsJobId(check) {
63
+ if (String(check?.__typename || '') !== 'CheckRun') return '';
64
+ if (!String(check?.name || '').trim()) return '';
65
+ const state = String(check?.conclusion || '').toUpperCase();
66
+ if (!FAILING_CONCLUSIONS.has(state)) return '';
67
+
68
+ try {
69
+ const url = new URL(String(check?.detailsUrl || ''));
70
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com') return '';
71
+ const match = url.pathname.match(/\/actions\/runs\/\d+\/job\/(\d+)(?:\/|$)/);
72
+ return match ? match[1] : '';
73
+ } catch (_error) {
74
+ return '';
75
+ }
76
+ }
77
+
78
+ function githubCheckRunAnnotationsPath(job, expectedCheckRunId) {
79
+ try {
80
+ const url = new URL(String(job?.check_run_url || ''));
81
+ if (url.protocol !== 'https:' || url.hostname !== 'api.github.com') return '';
82
+ const match = url.pathname.match(/^\/repos\/[^/]+\/[^/]+\/check-runs\/(\d+)\/?$/);
83
+ return match && match[1] === String(expectedCheckRunId)
84
+ ? `check-runs/${match[1]}/annotations`
85
+ : '';
86
+ } catch (_error) {
87
+ return '';
88
+ }
89
+ }
90
+
91
+ function commitCheckRuns(repoRoot, headSha, runner = run) {
92
+ const sha = String(headSha || '').trim();
93
+ if (!/^[0-9a-f]{7,64}$/i.test(sha)) return [];
94
+
95
+ const result = runner(GH_BIN, [
96
+ 'api',
97
+ repoApiPath(repoRoot, `commits/${sha}/check-runs?per_page=100`, runner),
98
+ ], { cwd: repoRoot, timeout: 60_000, allowFailure: true });
99
+ if (result.status !== 0) return [];
100
+
101
+ try {
102
+ const payload = JSON.parse(String(result.stdout || ''));
103
+ const checkRuns = Array.isArray(payload?.check_runs) ? payload.check_runs : [];
104
+ return Number(payload?.total_count) === checkRuns.length ? checkRuns : [];
105
+ } catch (_error) {
106
+ return [];
107
+ }
108
+ }
109
+
110
+ function matchingCheckRunId(check, checkRuns) {
111
+ const matches = checkRuns.filter((candidate) => String(candidate?.app?.slug || '') === 'github-actions'
112
+ && String(candidate?.name || '') === String(check?.name || '')
113
+ && String(candidate?.details_url || '') === String(check?.detailsUrl || '')
114
+ && String(candidate?.status || '').toUpperCase() === String(check?.status || '').toUpperCase()
115
+ && String(candidate?.conclusion || '').toUpperCase() === String(check?.conclusion || '').toUpperCase());
116
+ if (matches.length !== 1) return '';
117
+ const id = String(matches[0]?.id || '');
118
+ return /^\d+$/.test(id) ? id : '';
119
+ }
120
+
121
+ function isBillingBlockedCheckRun(repoRoot, check, expectedCheckRunId, runner = run) {
122
+ const jobId = githubActionsJobId(check);
123
+ if (!jobId || !expectedCheckRunId) return false;
124
+
125
+ const jobResult = runner(GH_BIN, [
126
+ 'api',
127
+ repoApiPath(repoRoot, `actions/jobs/${jobId}`, runner),
128
+ ], { cwd: repoRoot, timeout: 60_000, allowFailure: true });
129
+ if (jobResult.status !== 0) return false;
130
+
131
+ let job;
132
+ try {
133
+ job = JSON.parse(String(jobResult.stdout || ''));
134
+ } catch (_error) {
135
+ return false;
136
+ }
137
+ if (String(job?.status || '').toLowerCase() !== 'completed'
138
+ || String(job?.conclusion || '').toLowerCase() !== 'failure'
139
+ || job?.runner_id !== 0
140
+ || String(job?.runner_name || '') !== ''
141
+ || !Array.isArray(job?.steps)
142
+ || job.steps.length !== 0) return false;
143
+
144
+ const annotationsPath = githubCheckRunAnnotationsPath(job, expectedCheckRunId);
145
+ if (!annotationsPath) return false;
146
+
147
+ const result = runner(GH_BIN, [
148
+ 'api',
149
+ repoApiPath(repoRoot, annotationsPath, runner),
150
+ ], { cwd: repoRoot, timeout: 60_000, allowFailure: true });
151
+ if (result.status !== 0) return false;
152
+
153
+ let annotations;
154
+ try {
155
+ annotations = JSON.parse(String(result.stdout || ''));
156
+ } catch (_error) {
157
+ return false;
158
+ }
159
+ if (!Array.isArray(annotations) || annotations.length !== 1) return false;
160
+
161
+ const [annotation] = annotations;
162
+ return annotation?.path === '.github'
163
+ && Number(annotation?.start_line) === 1
164
+ && String(annotation?.annotation_level || '').toLowerCase() === 'failure'
165
+ && String(annotation?.title || '') === ''
166
+ && String(annotation?.raw_details || '') === ''
167
+ && BILLING_BLOCKED_JOB_MESSAGE.test(String(annotation?.message || '').trim());
168
+ }
169
+
60
170
  /**
61
171
  * Resolve the PR for `branch` if any exists on the origin remote.
62
172
  * Returns null when no PR is open (or any are merged / closed only).
@@ -249,7 +359,15 @@ function getPullRequestStatus(repoRoot, branch) {
249
359
  const pr = findOpenPrForBranch(repoRoot, branch);
250
360
  if (!pr) return null;
251
361
 
252
- const rollup = summarizeStatusCheckRollup(pr.statusCheckRollup);
362
+ let checkRuns;
363
+ const expectedCheckRunId = (check) => {
364
+ if (!checkRuns) checkRuns = commitCheckRuns(repoRoot, pr.headRefOid);
365
+ return matchingCheckRunId(check, checkRuns);
366
+ };
367
+
368
+ const rollup = summarizeStatusCheckRollup(pr.statusCheckRollup, {
369
+ isWaived: (check) => isBillingBlockedCheckRun(repoRoot, check, expectedCheckRunId(check)),
370
+ });
253
371
 
254
372
  return {
255
373
  number: pr.number,
@@ -268,6 +386,7 @@ function getPullRequestStatus(repoRoot, branch) {
268
386
  base: pr.baseRefName,
269
387
  checks: rollup.summary,
270
388
  failedNames: rollup.failedNames,
389
+ billingWaivedNames: rollup.waivedNames,
271
390
  supersededChecks: rollup.supersededCount,
272
391
  };
273
392
  }
@@ -491,6 +610,8 @@ module.exports = {
491
610
  pushBranch,
492
611
  openPullRequest,
493
612
  getPullRequestStatus,
613
+ githubActionsJobId,
614
+ isBillingBlockedCheckRun,
494
615
  checkOutcomes,
495
616
  baselineFailures,
496
617
  enableAutoMerge,
@@ -716,6 +716,16 @@ function buildRepoVscodeSettings(existingSettings = {}) {
716
716
  ? existingSettings[REPO_SCAN_IGNORED_FOLDERS_SETTING]
717
717
  : [];
718
718
 
719
+ // Keep normal subfolder discovery, but do not auto-register a worktree just
720
+ // because one of its files was opened in the primary workspace. Otherwise
721
+ // pruning it can leave a stale, endlessly syncing SCM provider behind.
722
+ if (existingSettings['git.autoRepositoryDetection'] !== false) {
723
+ nextSettings['git.autoRepositoryDetection'] = 'subFolders';
724
+ }
725
+ // Repository scan ignores do not affect VS Code's separate Git worktree
726
+ // detector. Disable it for the primary checkout so a removed Guardex
727
+ // worktree cannot remain registered as an endlessly syncing SCM provider.
728
+ nextSettings['git.detectWorktrees'] = false;
719
729
  nextSettings[REPO_SCAN_IGNORED_FOLDERS_SETTING] = uniqueStringList([
720
730
  ...existingIgnoredFolders,
721
731
  ...MANAGED_REPO_SCAN_IGNORED_FOLDERS,