@imdeadpool/guardex 8.2.0 → 8.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +68 -10
  2. package/bin/multiagent-safety.js +18 -1
  3. package/package.json +1 -1
  4. package/skills/gitguardex/SKILL.md +26 -2
  5. package/src/agents/message.js +764 -0
  6. package/src/agents/sessions.js +23 -1
  7. package/src/cli/args.js +64 -8
  8. package/src/cli/commands/agents.js +18 -0
  9. package/src/cli/commands/branch.js +94 -2
  10. package/src/cli/commands/finish.js +44 -2
  11. package/src/cli/commands/mcp.js +4 -3
  12. package/src/cli/shared/sandbox.js +5 -53
  13. package/src/cli/shared-locks.js +4 -0
  14. package/src/doctor/index.js +26 -26
  15. package/src/finish/index.js +10 -2
  16. package/src/finish/post-branch-finish-cleanup.js +324 -0
  17. package/src/finish/review-gate.js +47 -6
  18. package/src/git/index.js +9 -4
  19. package/src/mcp/collect.js +52 -3
  20. package/src/mcp/server.js +54 -2
  21. package/src/pr-checks.js +20 -5
  22. package/src/pr.js +122 -1
  23. package/src/scaffold/index.js +13 -0
  24. package/templates/AGENTS.multiagent-safety.md +37 -9
  25. package/templates/AGENTS.multiagent-safety.min.md +10 -4
  26. package/templates/codex/skills/gitguardex/SKILL.md +26 -2
  27. package/templates/githooks/pre-commit +40 -5
  28. package/templates/githooks/pre-push +72 -25
  29. package/templates/scripts/agent-branch-finish.sh +300 -21
  30. package/templates/scripts/agent-branch-start.sh +22 -2
  31. package/templates/scripts/agent-file-locks.py +170 -3
  32. package/templates/scripts/agent-preflight.sh +30 -0
  33. package/templates/scripts/agent-reconcile-openspec-tasks.js +105 -0
  34. package/templates/scripts/agent-worktree-prune.sh +406 -31
  35. package/templates/scripts/guardex-env.sh +291 -0
@@ -223,7 +223,10 @@ OPTIONS
223
223
  --dry-run Print actions without changing branches or worktrees
224
224
  --force-dirty Allow cleanup of dirty worktrees
225
225
  --keep-remote Keep remote agent branches
226
- --keep-clean-worktrees Keep clean worktrees instead of pruning them
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
227
230
  --include-pr-merged Treat branches from merged PRs as merged
228
231
  --idle-minutes <n> Only consider worktrees idle for at least n minutes
229
232
  --watch Repeat cleanup cycles (defaults idle threshold to 60)
@@ -255,6 +258,9 @@ OPTIONS
255
258
  if (!options.keepCleanWorktrees) {
256
259
  args.push('--only-dirty-worktrees');
257
260
  }
261
+ if (options.includeCleanLinkedWorktrees) {
262
+ args.push('--include-clean-linked-worktrees');
263
+ }
258
264
  if (options.includePrMerged) {
259
265
  args.push('--include-pr-merged');
260
266
  }
@@ -564,8 +570,9 @@ function finish(rawArgs, defaults = {}) {
564
570
  // Opt-in merge gate (--gate-review / gx ship): enforce a clean AI review +
565
571
  // green CI + GitHub-mergeable verdict BEFORE the shell merge runs. Throws on
566
572
  // failure, which the catch below turns into a finish failure (no merge).
573
+ let gateResult;
567
574
  if (options.mergeMode === 'pr' && options.gateReview) {
568
- runReviewGate({
575
+ gateResult = runReviewGate({
569
576
  repoRoot, worktreePath, branch, baseBranch, options, progress,
570
577
  });
571
578
  } else {
@@ -596,6 +603,7 @@ function finish(rawArgs, defaults = {}) {
596
603
  GUARDEX_FINISH_ACTIVE_CWD: activeCwd,
597
604
  GUARDEX_FINISH_CHECKLIST: '1',
598
605
  GUARDEX_FINISH_GATE_DONE: options.gateReview ? '1' : '0',
606
+ GUARDEX_FINISH_REQUIRE_PREFLIGHT: gateResult?.billingChecksWaived?.length > 0 ? '1' : '0',
599
607
  ...progress.eventEnv,
600
608
  },
601
609
  });
@@ -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
 
@@ -104,6 +104,51 @@ function listWorktrees(repoRoot) {
104
104
  return worktrees;
105
105
  }
106
106
 
107
+ function knownBranchNames(repoRoot, worktrees) {
108
+ const names = new Set(worktrees.map((wt) => wt.branch).filter(Boolean));
109
+ const refs = git(repoRoot, ['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes']);
110
+ if (refs == null) return names;
111
+ for (const ref of refs.split('\n').filter(Boolean)) {
112
+ if (ref.startsWith('refs/heads/')) {
113
+ names.add(ref.slice('refs/heads/'.length));
114
+ continue;
115
+ }
116
+ if (!ref.startsWith('refs/remotes/')) continue;
117
+ const remoteAndBranch = ref.slice('refs/remotes/'.length);
118
+ const slash = remoteAndBranch.indexOf('/');
119
+ if (slash !== -1) names.add(remoteAndBranch.slice(slash + 1));
120
+ }
121
+ return names;
122
+ }
123
+
124
+ // `pane` survives in the lock entry after an agent lane exits. If the lane's
125
+ // branch/ref is also gone, the pane's current checkout is the last local proof
126
+ // of ownership. Unknown states fail closed; only a confirmed different branch
127
+ // makes the entry orphaned.
128
+ function paneStillOwnsBranch(mainRoot, pane, branch) {
129
+ if (!/^%\d+$/.test(String(pane || ''))) return null;
130
+ const result = cp.spawnSync(
131
+ 'tmux',
132
+ ['display-message', '-p', '-t', pane, '#{pane_current_path}'],
133
+ { encoding: 'utf8', timeout: 3000, maxBuffer: 1024 * 1024 },
134
+ );
135
+ if (result.error) return null;
136
+ if (!result || result.status !== 0) return null;
137
+ const paneCwd = (result.stdout || '').trim();
138
+ if (!paneCwd || !fs.existsSync(paneCwd)) return null;
139
+ const paneRepoRoot = mainRepoRoot(paneCwd);
140
+ if (!paneRepoRoot || path.resolve(paneRepoRoot) !== path.resolve(mainRoot)) return null;
141
+ const paneBranch = git(paneCwd, ['rev-parse', '--abbrev-ref', 'HEAD']);
142
+ if (!paneBranch || paneBranch === 'HEAD') return null;
143
+ return paneBranch === branch;
144
+ }
145
+
146
+ function isOrphanedLocalLock(mainRoot, entry, knownBranches) {
147
+ const branch = String((entry && entry.branch) || '');
148
+ if (!branch || knownBranches.has(branch)) return false;
149
+ return paneStillOwnsBranch(mainRoot, entry.pane, branch) === false;
150
+ }
151
+
107
152
  function readLockMap(repoRoot) {
108
153
  const lockPath = path.join(repoRoot, LOCK_FILE_RELATIVE);
109
154
  let raw;
@@ -373,12 +418,16 @@ function whoOwnsMany(files, { cwd = process.cwd(), repoPath } = {}) {
373
418
  target.owners.push(owner);
374
419
  };
375
420
 
376
- // Read each worktree lock map once for the whole requested batch.
377
- for (const wt of listWorktrees(mainRoot)) {
421
+ // Read each worktree lock map once for the whole requested batch. A lock is
422
+ // ignored only when its branch/ref disappeared and its recorded pane is
423
+ // confirmed to be on another checkout; ambiguous ownership remains blocking.
424
+ const worktrees = listWorktrees(mainRoot);
425
+ const knownBranches = knownBranchNames(mainRoot, worktrees);
426
+ for (const wt of worktrees) {
378
427
  const map = readLockMap(wt.path);
379
428
  for (const target of targets) {
380
429
  const entry = map[target.rel] || map[target.file];
381
- if (!entry) continue;
430
+ if (!entry || isOrphanedLocalLock(mainRoot, entry, knownBranches)) continue;
382
431
  addOwner(target, {
383
432
  branch: entry.branch,
384
433
  agent: entry.agent || parseAgentName(entry.branch),
package/src/mcp/server.js CHANGED
@@ -5,13 +5,14 @@
5
5
  // newline-delimited JSON-RPC 2.0; we implement the small surface an agent
6
6
  // needs: initialize, tools/list, tools/call, ping.
7
7
  //
8
- // All tools are READ-ONLY — the server only reflects git/worktree/lock/PR
9
- // state, it never mutates a repo.
8
+ // Radar tools are read-only. Messaging tools write only to GitGuardex's local
9
+ // authenticated agent inbox and guarded terminal-delivery state.
10
10
 
11
11
  const readline = require('node:readline');
12
12
 
13
13
  const collect = require('./collect');
14
14
  const { packageJson } = require('../context');
15
+ const agentMessage = require('../agents/message');
15
16
 
16
17
  const PROTOCOL_VERSION = '2024-11-05';
17
18
 
@@ -79,6 +80,43 @@ const TOOLS = [
79
80
  },
80
81
  },
81
82
  },
83
+ {
84
+ name: 'send_agent_message',
85
+ description:
86
+ 'Send to an authenticated GitGuardex agent session. Delivers live when safe, otherwise queues durably.',
87
+ inputSchema: {
88
+ type: 'object',
89
+ properties: {
90
+ session_id: { type: 'string', description: 'Target session id.' },
91
+ branch: { type: 'string', description: 'Target branch instead of session_id.' },
92
+ message: { type: 'string', description: 'Message body.' },
93
+ from_session: { type: 'string', description: 'Explicit source session id; caller ownership is verified.' },
94
+ },
95
+ required: ['message'],
96
+ },
97
+ },
98
+ {
99
+ name: 'read_agent_messages',
100
+ description: 'Read pending messages for the authenticated calling agent session.',
101
+ inputSchema: {
102
+ type: 'object',
103
+ properties: {
104
+ session_id: { type: 'string', description: 'Explicit caller session id; caller ownership is verified.' },
105
+ },
106
+ },
107
+ },
108
+ {
109
+ name: 'ack_agent_message',
110
+ description: 'Acknowledge and remove one queued message from the authenticated calling agent inbox.',
111
+ inputSchema: {
112
+ type: 'object',
113
+ properties: {
114
+ session_id: { type: 'string', description: 'Explicit caller session id; caller ownership is verified.' },
115
+ message_id: { type: 'string', description: 'Queued message id.' },
116
+ },
117
+ required: ['message_id'],
118
+ },
119
+ },
82
120
  ];
83
121
 
84
122
  function callTool(name, args = {}) {
@@ -107,6 +145,20 @@ function callTool(name, args = {}) {
107
145
  }
108
146
  return collect.myContext({ includePr: includePrs });
109
147
  }
148
+ case 'send_agent_message':
149
+ return agentMessage.sendOrQueueAgentMessage(process.cwd(), {
150
+ sessionId: args.session_id,
151
+ branch: args.branch,
152
+ sourceSessionId: args.from_session,
153
+ message: args.message,
154
+ });
155
+ case 'read_agent_messages':
156
+ return agentMessage.readAgentInbox(process.cwd(), { sessionId: args.session_id });
157
+ case 'ack_agent_message':
158
+ return agentMessage.acknowledgeAgentMessage(process.cwd(), {
159
+ sessionId: args.session_id,
160
+ messageId: args.message_id,
161
+ });
110
162
  default:
111
163
  throw new Error(`Unknown tool: ${name}`);
112
164
  }
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 = {