@imdeadpool/guardex 8.1.0 → 8.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -190,6 +190,16 @@ finds the last published GitHub release, and writes one grouped GitHub release b
190
190
  <details>
191
191
  <summary><strong>v8.x</strong></summary>
192
192
 
193
+ ### v8.2.0
194
+ - Reduced agent preflight and finish token overhead.
195
+ - Preserved dirty worktrees during stale-worktree cleanup and exposed
196
+ command-specific cleanup help.
197
+ - Added the owning tmux pane and worktree to file-lock conflict output.
198
+
199
+ ### v8.1.1
200
+ - Prevented `gx doctor` from pruning dirty detached or managed worktrees during
201
+ stale-worktree repair.
202
+
193
203
  ### v8.1.0
194
204
  - Added shared Git lock state so independent clones coordinate file ownership.
195
205
  - Aligned npm repository metadata with `opencue/gitguardex` for trusted OIDC
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imdeadpool/guardex",
3
- "version": "8.1.0",
3
+ "version": "8.2.0",
4
4
  "description": "Guardian T-Rex for your multi-agent repo. Isolated worktrees, file locks, and PR-only merges stop parallel Codex & Claude agents from overwriting each other's work. Auto-wires Oh My Codex, Oh My Claude, OpenSpec, and Caveman.",
5
5
  "license": "MIT",
6
6
  "preferGlobal": true,
package/src/cli/args.js CHANGED
@@ -1176,6 +1176,7 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1176
1176
  commitMessage: '',
1177
1177
  mergeMode: fastMode ? 'pr' : (defaults.mergeMode || 'pr'),
1178
1178
  fastMode,
1179
+ agentQuiet: false,
1179
1180
  skipPreflight: fastMode,
1180
1181
  // Precedence: explicit flag (set in the loop below) > defaults (caller) >
1181
1182
  // GUARDEX_AUTO_SHIP env > hardcoded off. Note `defaults.gateReview === false`
@@ -1260,6 +1261,10 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1260
1261
  if (arg === '--fast') {
1261
1262
  continue;
1262
1263
  }
1264
+ if (arg === '--agent-quiet') {
1265
+ options.agentQuiet = true;
1266
+ continue;
1267
+ }
1263
1268
  if (arg === '--wait-for-merge') {
1264
1269
  options.waitForMerge = true;
1265
1270
  continue;
@@ -19,7 +19,7 @@ const {
19
19
  invokePackageAsset,
20
20
  } = require('../../core/runtime');
21
21
  const { runReviewGate } = require('../../finish/review-gate');
22
- const { createFinishProgress } = require('../../finish/progress');
22
+ const { createFinishProgress, summarizeFinishRun } = require('../../finish/progress');
23
23
  const { autoCommitWorktreeForFinish } = require('../../finish');
24
24
  const { finish, merge } = require('./finish');
25
25
  const { locks } = require('../shared-locks');
@@ -44,10 +44,13 @@ function splitGateReviewFlags(args) {
44
44
  let reviewTimeoutMs;
45
45
  let noAutoCommit = false;
46
46
  let commitMessage = '';
47
+ let agentQuiet = false;
47
48
  for (let index = 0; index < args.length; index += 1) {
48
49
  const arg = args[index];
49
50
  if (arg === '--fast') {
50
51
  fastMode = true;
52
+ } else if (arg === '--agent-quiet') {
53
+ agentQuiet = true;
51
54
  } else if (arg === '--no-auto-commit') {
52
55
  noAutoCommit = true;
53
56
  } else if (arg === '--commit-message') {
@@ -173,6 +176,7 @@ function splitGateReviewFlags(args) {
173
176
  gateSerialCi,
174
177
  noAutoCommit,
175
178
  commitMessage,
179
+ agentQuiet,
176
180
  scriptArgs,
177
181
  };
178
182
  }
@@ -215,6 +219,7 @@ function branch(rawArgs) {
215
219
  gateSerialCi,
216
220
  noAutoCommit,
217
221
  commitMessage,
222
+ agentQuiet,
218
223
  scriptArgs,
219
224
  } = splitGateReviewFlags(passthrough);
220
225
  const finishBranch = readFlagValue(scriptArgs, '--branch') || currentBranchName(repoRoot);
@@ -228,7 +233,12 @@ function branch(rawArgs) {
228
233
  const autoCommitWorktree = finishWorktree && isLinkedAgentWorktree(finishWorktree)
229
234
  ? finishWorktree
230
235
  : '';
231
- const progress = createFinishProgress({ repoRoot, branch: finishBranch, baseBranch: finishBase });
236
+ const progress = createFinishProgress({
237
+ repoRoot,
238
+ branch: finishBranch,
239
+ baseBranch: finishBase,
240
+ quiet: agentQuiet,
241
+ });
232
242
  progress.start(
233
243
  'prepare',
234
244
  autoCommitWorktree ? 'checking worktree and pending changes' : 'resolving branch and finish policy',
@@ -236,7 +246,7 @@ function branch(rawArgs) {
236
246
  const commitState = autoCommitWorktree
237
247
  ? autoCommitWorktreeForFinish(repoRoot, autoCommitWorktree, finishBranch, { noAutoCommit, commitMessage })
238
248
  : { changed: false, committed: false };
239
- if (commitState.committed) {
249
+ if (commitState.committed && !agentQuiet) {
240
250
  console.log(`[${TOOL_NAME}] Auto-committed '${finishBranch}' before finish.`);
241
251
  }
242
252
  progress.complete(
@@ -272,7 +282,7 @@ function branch(rawArgs) {
272
282
  progress.skip('autofix', 'review gate disabled');
273
283
  progress.skip('ci', 'review gate disabled; repository policy controls merge readiness');
274
284
  }
275
- invokePackageAsset('branchFinish', scriptArgs, {
285
+ const assetOptions = {
276
286
  cwd: repoRoot,
277
287
  env: {
278
288
  GUARDEX_FINISH_ACTIVE_CWD: activeCwd,
@@ -280,7 +290,24 @@ function branch(rawArgs) {
280
290
  GUARDEX_FINISH_GATE_DONE: gateReview ? '1' : '0',
281
291
  ...progress.eventEnv,
282
292
  },
283
- });
293
+ };
294
+ if (agentQuiet) {
295
+ const result = runPackageAsset('branchFinish', scriptArgs, { ...assetOptions, stdio: 'pipe' });
296
+ const summary = summarizeFinishRun({
297
+ eventFile: progress.eventEnv.GUARDEX_FINISH_EVENT_FILE,
298
+ branch: finishBranch,
299
+ baseBranch: finishBase,
300
+ stdout: result.stdout,
301
+ stderr: result.stderr,
302
+ status: result.status,
303
+ });
304
+ process.stdout.write(`[gx:finish] ${JSON.stringify(summary)}\n`);
305
+ if (result.status !== 0) {
306
+ throw new Error(`branchFinish command failed with status ${result.status}`);
307
+ }
308
+ } else {
309
+ invokePackageAsset('branchFinish', scriptArgs, assetOptions);
310
+ }
284
311
  return;
285
312
  }
286
313
  if (subcommand === 'merge') return merge(rest);
@@ -1106,7 +1106,6 @@ function pruneStaleAgentWorktrees(repoRoot, options = {}) {
1106
1106
  '--delete-branches',
1107
1107
  '--delete-remote-branches',
1108
1108
  '--include-pr-merged',
1109
- '--force-dirty',
1110
1109
  ];
1111
1110
  if (baseBranch && baseBranch !== 'HEAD' && !baseBranch.startsWith('agent/')) {
1112
1111
  args.push('--base', baseBranch);
@@ -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,30 @@ 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
+ --keep-clean-worktrees Keep clean worktrees instead of pruning them
227
+ --include-pr-merged Treat branches from merged PRs as merged
228
+ --idle-minutes <n> Only consider worktrees idle for at least n minutes
229
+ --watch Repeat cleanup cycles (defaults idle threshold to 60)
230
+ --interval <seconds> Watch interval in seconds (minimum: 5; default: 60)
231
+ --once Run one cleanup cycle when used with --watch
232
+ --max-branches <n> Limit branches processed per cycle
233
+ -h, --help Show this help`);
234
+ process.exitCode = 0;
235
+ return;
236
+ }
237
+
213
238
  const activeCwd = process.cwd();
214
239
  const options = parseCleanupArgs(rawArgs);
215
240
  const repoRoot = resolveRepoRoot(options.target);
@@ -394,7 +419,7 @@ function finish(rawArgs, defaults = {}) {
394
419
  let succeeded = 0;
395
420
  let failed = 0;
396
421
  let autoCommitted = 0;
397
- const terse = isTerseMode();
422
+ const terse = isTerseMode() || options.agentQuiet;
398
423
 
399
424
  for (const candidate of candidates) {
400
425
  const { branch, baseBranch, worktreePath } = candidate;
@@ -403,6 +428,7 @@ function finish(rawArgs, defaults = {}) {
403
428
  branch,
404
429
  baseBranch,
405
430
  persistEvents: !options.dryRun,
431
+ quiet: options.agentQuiet,
406
432
  });
407
433
  // In terse mode, defer the "Finishing X -> Y" line until we know whether
408
434
  // we also need to announce an auto-commit, then emit a single combined
@@ -425,9 +451,11 @@ function finish(rawArgs, defaults = {}) {
425
451
  const suffix = commitState.committed
426
452
  ? ' [auto-committed]'
427
453
  : (commitState.changed && commitState.dryRun ? ' [dry-run: would auto-commit]' : '');
428
- console.log(
429
- `[${TOOL_NAME}] Finishing '${branch}' -> '${baseBranch}'${worktreePath ? ` (${worktreePath})` : ''}${suffix}`,
430
- );
454
+ if (!options.agentQuiet) {
455
+ console.log(
456
+ `[${TOOL_NAME}] Finishing '${branch}' -> '${baseBranch}'${worktreePath ? ` (${worktreePath})` : ''}${suffix}`,
457
+ );
458
+ }
431
459
  if (commitState.committed) {
432
460
  autoCommitted += 1;
433
461
  }
@@ -510,7 +538,7 @@ function finish(rawArgs, defaults = {}) {
510
538
  const preflight = runPreflight(repoRoot, worktreePath, branch, baseBranch, {
511
539
  verbose: !terse,
512
540
  });
513
- console.log(`[${TOOL_NAME}] ${summarizePreflight(preflight)}`);
541
+ if (!options.agentQuiet) console.log(`[${TOOL_NAME}] ${summarizePreflight(preflight)}`);
514
542
  if (preflight.status === 'failed') {
515
543
  progress.fail('preflight', `${preflight.failures.length} script(s) failed`);
516
544
  for (const f of preflight.failures) {
@@ -563,7 +591,7 @@ function finish(rawArgs, defaults = {}) {
563
591
  // drift apart.
564
592
  const finishResult = runPackageAsset('branchFinish', finishArgs, {
565
593
  cwd: repoRoot,
566
- stdio: assetStdio('branchFinish'),
594
+ stdio: options.agentQuiet ? 'pipe' : assetStdio('branchFinish'),
567
595
  env: {
568
596
  GUARDEX_FINISH_ACTIVE_CWD: activeCwd,
569
597
  GUARDEX_FINISH_CHECKLIST: '1',
@@ -571,12 +599,20 @@ function finish(rawArgs, defaults = {}) {
571
599
  ...progress.eventEnv,
572
600
  },
573
601
  });
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);
602
+ if (options.agentQuiet) {
603
+ const summary = summarizeFinishRun({
604
+ eventFile: progress.eventEnv.GUARDEX_FINISH_EVENT_FILE,
605
+ branch,
606
+ baseBranch,
607
+ stdout: finishResult.stdout,
608
+ stderr: finishResult.stderr,
609
+ status: finishResult.status,
610
+ });
611
+ process.stdout.write(`[gx:finish] ${JSON.stringify(summary)}\n`);
612
+ } else {
613
+ // Null under 'inherit'; kept so an explicit pipe still prints.
614
+ if (finishResult.stdout) process.stdout.write(finishResult.stdout);
615
+ if (finishResult.stderr) process.stderr.write(finishResult.stderr);
580
616
  }
581
617
  if (finishResult.status !== 0) {
582
618
  throw new Error(`agent-branch-finish exited with status ${finishResult.status}`);
@@ -592,9 +628,18 @@ function finish(rawArgs, defaults = {}) {
592
628
  }
593
629
  }
594
630
 
595
- console.log(
596
- `[${TOOL_NAME}] Finish summary: total=${candidates.length}, success=${succeeded}, failed=${failed}, autoCommitted=${autoCommitted}`,
597
- );
631
+ if (options.agentQuiet) {
632
+ process.stdout.write(`[gx:finish] ${JSON.stringify({
633
+ total: candidates.length,
634
+ success: succeeded,
635
+ failed,
636
+ autoCommitted,
637
+ })}\n`);
638
+ } else {
639
+ console.log(
640
+ `[${TOOL_NAME}] Finish summary: total=${candidates.length}, success=${succeeded}, failed=${failed}, autoCommitted=${autoCommitted}`,
641
+ );
642
+ }
598
643
 
599
644
  // Bulk `--all` finish self-cleans: sweep merged-but-stranded worktree dirs
600
645
  // whose branch was merged out-of-band and never reaped (the post-merge
@@ -607,10 +652,10 @@ function finish(rawArgs, defaults = {}) {
607
652
  if (baseForSweep) {
608
653
  sweepArgs.push('--base', baseForSweep);
609
654
  }
610
- console.log(`[${TOOL_NAME}] Sweeping merged-but-stranded worktrees...`);
655
+ if (!options.agentQuiet) console.log(`[${TOOL_NAME}] Sweeping merged-but-stranded worktrees...`);
611
656
  const sweep = runPackageAsset('worktreePrune', sweepArgs, {
612
657
  cwd: repoRoot,
613
- stdio: 'inherit',
658
+ stdio: options.agentQuiet ? 'pipe' : 'inherit',
614
659
  env: { GUARDEX_PRUNE_ACTIVE_CWD: activeCwd },
615
660
  });
616
661
  if (sweep.status !== 0) {
@@ -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');
@@ -349,32 +349,52 @@ function repoState(repoOrCwd, { includePrs = true } = {}) {
349
349
  // Aggregate locks across ALL worktrees of the repo. Lock files are per-worktree
350
350
  // on disk, so a single worktree's file only shows its own claims — the
351
351
  // collision view requires the union.
352
- function whoOwns(file, { cwd = process.cwd(), repoPath } = {}) {
353
- if (!file) return { file: null, owner: null, error: 'no file given' };
352
+ function whoOwnsMany(files, { cwd = process.cwd(), repoPath } = {}) {
353
+ const requested = [...new Set(
354
+ (Array.isArray(files) ? files : [])
355
+ .filter((file) => typeof file === 'string' && file.trim())
356
+ .map((file) => file.trim()),
357
+ )].slice(0, 200);
358
+ if (requested.length === 0) return [];
354
359
  const mainRoot = mainRepoRoot(repoPath || cwd);
355
- if (!mainRoot) return { file, owner: null, error: 'not a git repo' };
356
- const rel = path.isAbsolute(file) ? path.relative(mainRoot, file) : file;
357
- const owners = [];
358
- const seenOwner = new Set();
360
+ if (!mainRoot) {
361
+ return requested.map((file) => ({ file, owner: null, error: 'not a git repo' }));
362
+ }
363
+ const targets = requested.map((file) => ({
364
+ file,
365
+ rel: path.isAbsolute(file) ? path.relative(mainRoot, file) : file,
366
+ owners: [],
367
+ seen: new Set(),
368
+ }));
369
+ const addOwner = (target, owner) => {
370
+ const key = `${owner.branch}\0${owner.agent || ''}`;
371
+ if (!owner.branch || target.seen.has(key)) return;
372
+ target.seen.add(key);
373
+ target.owners.push(owner);
374
+ };
375
+
376
+ // Read each worktree lock map once for the whole requested batch.
359
377
  for (const wt of listWorktrees(mainRoot)) {
360
378
  const map = readLockMap(wt.path);
361
- const entry = map[rel] || map[file];
362
- const key = entry && `${entry.branch}\0${entry.agent || ''}`;
363
- if (entry && entry.branch && !seenOwner.has(key)) {
364
- seenOwner.add(key);
365
- owners.push({
379
+ for (const target of targets) {
380
+ const entry = map[target.rel] || map[target.file];
381
+ if (!entry) continue;
382
+ addOwner(target, {
366
383
  branch: entry.branch,
367
384
  agent: entry.agent || parseAgentName(entry.branch),
368
385
  claimed_at: entry.claimed_at || null,
369
- worktree: wt.path
386
+ worktree: wt.path,
370
387
  });
371
388
  }
372
389
  }
373
390
  if (sharedGitState.settings(mainRoot).enabled) {
374
- const entry = sharedGitState.getLock(mainRoot, rel);
375
- const key = entry && `${entry.branch}\0${entry.agent || ''}`;
376
- if (entry && !seenOwner.has(key)) {
377
- owners.push({
391
+ const sharedByFile = new Map(
392
+ sharedGitState.listLocks(mainRoot).map((entry) => [entry.file, entry]),
393
+ );
394
+ for (const target of targets) {
395
+ const entry = sharedByFile.get(target.rel) || sharedByFile.get(target.file);
396
+ if (!entry) continue;
397
+ addOwner(target, {
378
398
  branch: entry.branch,
379
399
  agent: entry.agent || parseAgentName(entry.branch),
380
400
  claimed_at: entry.claimedAt,
@@ -384,13 +404,20 @@ function whoOwns(file, { cwd = process.cwd(), repoPath } = {}) {
384
404
  });
385
405
  }
386
406
  }
387
- if (owners.length === 0) return { file: rel, owner: null };
388
- return {
389
- file: rel,
390
- owner: owners.length === 1 ? owners[0] : null,
391
- owners,
392
- conflict: owners.length > 1
393
- };
407
+ return targets.map(({ rel, owners }) => {
408
+ if (owners.length === 0) return { file: rel, owner: null };
409
+ return {
410
+ file: rel,
411
+ owner: owners.length === 1 ? owners[0] : null,
412
+ owners,
413
+ conflict: owners.length > 1,
414
+ };
415
+ });
416
+ }
417
+
418
+ function whoOwns(file, options = {}) {
419
+ if (!file) return { file: null, owner: null, error: 'no file given' };
420
+ return whoOwnsMany([file], options)[0];
394
421
  }
395
422
 
396
423
  // Slim "radar" projection of a lane for list_agents — who-is-on-what at a
@@ -450,12 +477,46 @@ function myContext({ cwd = process.cwd(), includePr = true } = {}) {
450
477
  };
451
478
  }
452
479
 
480
+ function compactOwnership(result) {
481
+ const compactOwner = (owner) => {
482
+ if (!owner) return null;
483
+ const value = { branch: owner.branch, agent: owner.agent };
484
+ if (owner.remote) value.remote = true;
485
+ if (owner.machine) value.machine = owner.machine;
486
+ return value;
487
+ };
488
+ if (!result.owner && !result.conflict) return { file: result.file, owner: null };
489
+ if (result.conflict) {
490
+ return {
491
+ file: result.file,
492
+ owner: null,
493
+ owners: result.owners.map(compactOwner),
494
+ conflict: true,
495
+ };
496
+ }
497
+ return { file: result.file, owner: compactOwner(result.owner) };
498
+ }
499
+
500
+ /** One compact, repo-scoped snapshot for an agent about to edit files. */
501
+ function editContext({ cwd = process.cwd(), files = [], includePrs = false } = {}) {
502
+ const context = myContext({ cwd, includePr: includePrs });
503
+ if (context.error) return context;
504
+ const otherAgents = collectRepoAgents(context.repoPath, { includePrs })
505
+ .filter((agent) => agent.branch !== context.branch)
506
+ .map(radarRecord);
507
+ const ownership = whoOwnsMany(files, { repoPath: context.repoPath })
508
+ .map(compactOwnership);
509
+ return { ...context, otherAgents, ownership };
510
+ }
511
+
453
512
  module.exports = {
454
513
  collectAllAgents,
455
514
  collectRepoAgents,
456
515
  repoState,
457
516
  whoOwns,
517
+ whoOwnsMany,
458
518
  myContext,
519
+ editContext,
459
520
  radarRecord,
460
521
  indexPrsByBranch,
461
522
  daysSince,
package/src/mcp/server.js CHANGED
@@ -19,45 +19,45 @@ const TOOLS = [
19
19
  {
20
20
  name: 'list_agents',
21
21
  description:
22
- 'List every active agent lane across all discovered repos. Returns a COMPACT radar by default — per lane: repo, branch, agent, task, dirty (count of files changed right now), locks (count), pr (number), last (commit date), and flags stale / onPrimary / unpushed when set. Use it to see who is working on what before you start. For full detail on a lane (worktree path, the actual dirty/lock file lists, full PR), call repo_state or my_context, or pass detail:true here (where the onPrimary flag appears as warning + onPrimaryCheckout instead). Read-only.',
22
+ 'Cross-repo agent radar. Compact by default; use detail only for paths and file lists.',
23
23
  inputSchema: {
24
24
  type: 'object',
25
25
  properties: {
26
26
  include_prs: {
27
27
  type: 'boolean',
28
- description: 'Fetch PR state via gh (one call per repo that has lanes). Default true; pass false to skip gh entirely.',
28
+ description: 'Fetch PRs. Default false.',
29
29
  },
30
30
  roots: {
31
31
  type: 'array',
32
32
  items: { type: 'string' },
33
- description: 'Override repo search roots. Default: ~/Documents, ~/code, ~/src, ~/projects.',
33
+ description: 'Override search roots.',
34
34
  },
35
- limit: { type: 'number', description: 'Max number of repos to scan.' },
36
- detail: { type: 'boolean', description: 'Return full lane records (worktree path, dirty/lock file lists, full PR) instead of the compact radar. Default false.' },
35
+ limit: { type: 'number', description: 'Repo scan cap.' },
36
+ detail: { type: 'boolean', description: 'Return full lane records. Default false.' },
37
37
  },
38
38
  },
39
39
  },
40
40
  {
41
41
  name: 'repo_state',
42
42
  description:
43
- 'Agent lanes for a single repository (branches, worktrees, file locks, PRs). Pass a repo path; defaults to the current working repo.',
43
+ 'Agent lanes for one repo.',
44
44
  inputSchema: {
45
45
  type: 'object',
46
46
  properties: {
47
- repo: { type: 'string', description: 'Path inside the target repo. Defaults to cwd.' },
48
- include_prs: { type: 'boolean', description: 'Fetch PR state. Default true.' },
47
+ repo: { type: 'string', description: 'Repo path; default cwd.' },
48
+ include_prs: { type: 'boolean', description: 'Fetch PRs. Default false.' },
49
49
  },
50
50
  },
51
51
  },
52
52
  {
53
53
  name: 'who_owns',
54
54
  description:
55
- 'Check which agent/branch holds the gitguardex file lock on a path BEFORE you edit it, to avoid colliding with another agent. Returns owner=null when the file is unclaimed.',
55
+ 'Find the lock owner for one file. owner=null means unclaimed.',
56
56
  inputSchema: {
57
57
  type: 'object',
58
58
  properties: {
59
- file: { type: 'string', description: 'Repo-relative or absolute path to check.' },
60
- repo: { type: 'string', description: 'Path inside the target repo. Defaults to cwd.' },
59
+ file: { type: 'string', description: 'File path.' },
60
+ repo: { type: 'string', description: 'Repo path; default cwd.' },
61
61
  },
62
62
  required: ['file'],
63
63
  },
@@ -65,19 +65,30 @@ const TOOLS = [
65
65
  {
66
66
  name: 'my_context',
67
67
  description:
68
- 'Report THIS session: current repo, branch, worktree, whether it is the protected primary checkout (where edits are unsafe), held locks, and the PR for the branch.',
69
- inputSchema: { type: 'object', properties: {} },
68
+ 'Current lane. Pass files to also return compact same-repo radar and batch ownership in this one call.',
69
+ inputSchema: {
70
+ type: 'object',
71
+ properties: {
72
+ files: {
73
+ type: 'array',
74
+ items: { type: 'string' },
75
+ maxItems: 200,
76
+ description: 'Files intended for editing.',
77
+ },
78
+ include_prs: { type: 'boolean', description: 'Fetch PRs. Default false.' },
79
+ },
80
+ },
70
81
  },
71
82
  ];
72
83
 
73
84
  function callTool(name, args = {}) {
74
85
  switch (name) {
75
86
  case 'list_agents': {
76
- // PRs on by default: one gh call per repo that has active lanes (most
77
- // repos have none, so they cost nothing). Pass include_prs:false to skip.
87
+ // PR lookup is one batched gh call per repo with active lanes. Keep it
88
+ // opt-in so the default radar stays fast and compact.
78
89
  const full = collect.collectAllAgents({
79
90
  roots: args.roots,
80
- includePrs: args.include_prs !== false,
91
+ includePrs: args.include_prs === true,
81
92
  limit: args.limit,
82
93
  });
83
94
  // Compact radar by default (~80% fewer tokens); detail:true keeps the
@@ -86,11 +97,16 @@ function callTool(name, args = {}) {
86
97
  return { ...full, agents: full.agents.map(collect.radarRecord) };
87
98
  }
88
99
  case 'repo_state':
89
- return collect.repoState(args.repo || process.cwd(), { includePrs: args.include_prs !== false });
100
+ return collect.repoState(args.repo || process.cwd(), { includePrs: args.include_prs === true });
90
101
  case 'who_owns':
91
102
  return collect.whoOwns(args.file, { repoPath: args.repo });
92
- case 'my_context':
93
- return collect.myContext({});
103
+ case 'my_context': {
104
+ const includePrs = args.include_prs === true;
105
+ if (Array.isArray(args.files) && args.files.length > 0) {
106
+ return collect.editContext({ files: args.files, includePrs });
107
+ }
108
+ return collect.myContext({ includePr: includePrs });
109
+ }
94
110
  default:
95
111
  throw new Error(`Unknown tool: ${name}`);
96
112
  }
@@ -23,6 +23,7 @@ from __future__ import annotations
23
23
  import argparse
24
24
  import json
25
25
  import os
26
+ import re
26
27
  import subprocess
27
28
  import sys
28
29
  from contextlib import contextmanager
@@ -39,6 +40,7 @@ except ImportError: # non-POSIX (e.g. Windows): cross-worktree locking degrades
39
40
 
40
41
  LOCK_FILE_RELATIVE = Path('.omx/state/agent-file-locks.json')
41
42
  AGENT_ID_ENV = 'GUARDEX_AGENT_ID'
43
+ PANE_ID_ENV = 'TMUX_PANE'
42
44
  CRITICAL_GUARDRAIL_PATHS = {
43
45
  'AGENTS.md',
44
46
  '.githooks/pre-commit',
@@ -61,6 +63,7 @@ class LockEntry:
61
63
  claimed_at: str
62
64
  allow_delete: bool = False
63
65
  agent: str = ''
66
+ pane: str = ''
64
67
 
65
68
 
66
69
  class LockError(Exception):
@@ -112,12 +115,30 @@ def resolve_agent(args: argparse.Namespace) -> str:
112
115
  return (value or '').strip()
113
116
 
114
117
 
118
+ def resolve_pane() -> str:
119
+ """Return the caller's tmux pane when it has the canonical `%<number>` form."""
120
+ value = os.environ.get(PANE_ID_ENV, '').strip()
121
+ return value if re.fullmatch(r'%\d+', value) else ''
122
+
123
+
115
124
  def owner_label(entry: dict[str, Any]) -> str:
116
125
  branch = str(entry.get('branch', ''))
117
126
  agent = str(entry.get('agent', ''))
118
127
  return f'{branch} as {agent}' if agent else branch
119
128
 
120
129
 
130
+ def owner_description(entry: dict[str, Any]) -> str:
131
+ details: list[str] = []
132
+ pane = str(entry.get('pane', '')).strip()
133
+ worktree = str(entry.get('_worktree', '')).strip()
134
+ if pane:
135
+ details.append(f'pane {pane}')
136
+ if worktree:
137
+ details.append(f'worktree {worktree}')
138
+ suffix = f"; {'; '.join(details)}" if details else ''
139
+ return f'{owner_label(entry)}{suffix}'
140
+
141
+
121
142
  def owner_matches(entry: dict[str, Any], branch: str, agent: str) -> bool:
122
143
  """Does this branch+agent own the entry?
123
144
 
@@ -151,7 +172,7 @@ def load_state(repo_root: Path) -> dict[str, Any]:
151
172
  if not isinstance(locks, dict):
152
173
  return {'locks': {}}
153
174
 
154
- # Backward-compat normalization for older lock schema (no `agent` field).
175
+ # Backward-compat normalization for older lock schemas (no `agent`/`pane` fields).
155
176
  normalized_locks: dict[str, dict[str, Any]] = {}
156
177
  for file_path, entry in locks.items():
157
178
  if not isinstance(entry, dict):
@@ -160,11 +181,13 @@ def load_state(repo_root: Path) -> dict[str, Any]:
160
181
  claimed_at = str(entry.get('claimed_at', ''))
161
182
  allow_delete = bool(entry.get('allow_delete', False))
162
183
  agent = str(entry.get('agent', ''))
184
+ pane = str(entry.get('pane', ''))
163
185
  normalized_locks[str(file_path)] = {
164
186
  'branch': branch,
165
187
  'claimed_at': claimed_at,
166
188
  'allow_delete': allow_delete,
167
189
  'agent': agent,
190
+ 'pane': pane,
168
191
  }
169
192
 
170
193
  return {'locks': normalized_locks}
@@ -317,7 +340,7 @@ def load_all_locks(repo_root: Path) -> dict[str, list[dict[str, Any]]]:
317
340
  'lock operation blocked'
318
341
  ) from exc
319
342
  for file_path, entry in state['locks'].items():
320
- merged.setdefault(file_path, []).append(entry)
343
+ merged.setdefault(file_path, []).append({**entry, '_worktree': str(root)})
321
344
  return merged
322
345
 
323
346
 
@@ -367,8 +390,9 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
367
390
  locks: dict[str, dict[str, Any]] = state['locks']
368
391
 
369
392
  claim_agent = resolve_agent(args)
393
+ claim_pane = resolve_pane()
370
394
  files = [normalize_repo_path(repo_root, p) for p in args.files]
371
- conflicts: list[tuple[str, str]] = []
395
+ conflicts: list[tuple[str, dict[str, Any]]] = []
372
396
 
373
397
  # Conflict detection spans EVERY worktree of the repo, not just this one: a
374
398
  # file claimed by another owner in a sibling worktree must still block this
@@ -381,7 +405,7 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
381
405
  for file_path in files:
382
406
  foreign = [e for e in all_locks.get(file_path, []) if not owner_matches(e, args.branch, claim_agent)]
383
407
  if foreign:
384
- conflicts.append((file_path, owner_label(foreign[0])))
408
+ conflicts.append((file_path, foreign[0]))
385
409
  claimed = parse_iso_epoch(str(foreign[0].get('claimed_at', '')))
386
410
  if claimed is not None and (now - claimed) >= ttl_seconds:
387
411
  any_stale = True
@@ -389,7 +413,7 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
389
413
  if conflicts:
390
414
  print('[agent-file-locks] Cannot claim files already locked by another owner:', file=sys.stderr)
391
415
  for file_path, owner in conflicts:
392
- print(f' - {file_path} (locked by {owner})', file=sys.stderr)
416
+ print(f' - {file_path} (locked by {owner_description(owner)})', file=sys.stderr)
393
417
  if any_stale:
394
418
  print(
395
419
  '[agent-file-locks] Some blocking locks are past the staleness TTL; if their '
@@ -404,11 +428,13 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
404
428
  # A named claim adopts/upgrades the entry's agent; an anonymous claim
405
429
  # keeps any existing agent rather than silently downgrading it.
406
430
  resolved_owner_agent = claim_agent or str(existing.get('agent', ''))
431
+ resolved_owner_pane = claim_pane or str(existing.get('pane', ''))
407
432
  locks[file_path] = LockEntry(
408
433
  branch=args.branch,
409
434
  claimed_at=now_iso(),
410
435
  allow_delete=args.allow_delete or existing_allow_delete,
411
436
  agent=resolved_owner_agent,
437
+ pane=resolved_owner_pane,
412
438
  ).__dict__
413
439
 
414
440
  write_state(repo_root, state)