@imdeadpool/guardex 7.1.0 → 8.1.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 (58) hide show
  1. package/README.md +122 -322
  2. package/package.json +25 -5
  3. package/scripts/prepublish-bump-version.js +191 -0
  4. package/skills/gitguardex/SKILL.md +83 -3
  5. package/src/agents/activity.js +279 -0
  6. package/src/agents/finish.js +15 -0
  7. package/src/ci-init/index.js +0 -1
  8. package/src/cli/args.js +203 -6
  9. package/src/cli/commands/agents.js +17 -0
  10. package/src/cli/commands/branch.js +267 -14
  11. package/src/cli/commands/claude.js +15 -0
  12. package/src/cli/commands/doctor.js +26 -0
  13. package/src/cli/commands/onboard.js +293 -0
  14. package/src/cli/commands/prompt.js +15 -3
  15. package/src/cli/commands/review.js +18 -0
  16. package/src/cli/commands/setup.js +8 -6
  17. package/src/cli/commands/status.js +12 -0
  18. package/src/cli/main.js +2 -0
  19. package/src/cli/shared-locks.js +304 -0
  20. package/src/context.js +21 -3
  21. package/src/core/runtime.js +33 -1
  22. package/src/doctor/index.js +58 -5
  23. package/src/finish/heartbeat.js +169 -0
  24. package/src/finish/index.js +106 -4
  25. package/src/finish/progress.js +262 -0
  26. package/src/finish/review-gate.js +453 -32
  27. package/src/github-api.js +59 -0
  28. package/src/mcp/collect.js +111 -12
  29. package/src/mcp/server.js +10 -4
  30. package/src/output/index.js +210 -0
  31. package/src/pr-checks.js +121 -0
  32. package/src/pr-review.js +581 -51
  33. package/src/pr.js +143 -21
  34. package/src/provider-binary.js +101 -0
  35. package/src/review-diff.js +116 -0
  36. package/src/review-fix.js +229 -0
  37. package/src/sandbox/index.js +11 -5
  38. package/src/scaffold/agent-worktree-prep.js +9 -2
  39. package/src/scaffold/index.js +4 -16
  40. package/src/scaffold/provision-config.js +314 -0
  41. package/src/shared-git-state.js +566 -0
  42. package/src/terminal/kitty.js +20 -0
  43. package/src/terminal/tmux.js +9 -0
  44. package/templates/AGENTS.multiagent-safety.md +73 -11
  45. package/templates/AGENTS.multiagent-safety.min.md +1 -0
  46. package/templates/codex/skills/gitguardex/SKILL.md +83 -3
  47. package/templates/githooks/post-checkout +4 -9
  48. package/templates/githooks/pre-commit +17 -1
  49. package/templates/github/workflows/README.md +30 -23
  50. package/templates/scripts/agent-autofinish-watch.sh +280 -0
  51. package/templates/scripts/agent-branch-finish.sh +363 -26
  52. package/templates/scripts/agent-branch-start.sh +76 -25
  53. package/templates/scripts/agent-claude-stop-finish.sh +194 -0
  54. package/templates/scripts/agent-file-locks.py +390 -52
  55. package/templates/scripts/agent-preflight.sh +14 -2
  56. package/templates/scripts/agent-stalled-report.sh +40 -0
  57. package/templates/scripts/codex-agent.sh +10 -63
  58. package/templates/github/workflows/cr.yml +0 -46
@@ -1,11 +1,20 @@
1
1
  #!/usr/bin/env python3
2
2
  """Per-file lock registry for concurrent agent branches.
3
3
 
4
+ Locks are scoped by *owner identity* = (branch, agent). The agent dimension is
5
+ optional: pass `--agent <id>` or set GUARDEX_AGENT_ID. It exists so that two
6
+ agents sharing ONE worktree (and therefore one branch) can still hold distinct
7
+ claims against each other — without it the owner is the branch alone, so
8
+ same-branch agents never conflict and silently overwrite each other. When no
9
+ agent identity is supplied anywhere, behavior is byte-identical to branch-only
10
+ locking (every identity collapses to (branch, "")).
11
+
4
12
  Usage examples:
5
13
  gx locks claim --branch agent/a path/to/file1 path/to/file2
14
+ gx locks claim --branch agent/a --agent alice path/to/file1
6
15
  gx locks claim --branch agent/a --allow-delete path/to/obsolete-file
7
16
  gx locks allow-delete --branch agent/a path/to/obsolete-file
8
- gx locks validate --branch agent/a --staged
17
+ gx locks validate --branch agent/a --agent alice --staged
9
18
  gx locks release --branch agent/a
10
19
  """
11
20
 
@@ -16,13 +25,20 @@ import json
16
25
  import os
17
26
  import subprocess
18
27
  import sys
28
+ from contextlib import contextmanager
19
29
  from dataclasses import dataclass
20
30
  from datetime import datetime, timezone
21
31
  from pathlib import Path
22
32
  from typing import Any
23
33
 
34
+ try:
35
+ import fcntl
36
+ except ImportError: # non-POSIX (e.g. Windows): cross-worktree locking degrades to best-effort
37
+ fcntl = None
38
+
24
39
 
25
40
  LOCK_FILE_RELATIVE = Path('.omx/state/agent-file-locks.json')
41
+ AGENT_ID_ENV = 'GUARDEX_AGENT_ID'
26
42
  CRITICAL_GUARDRAIL_PATHS = {
27
43
  'AGENTS.md',
28
44
  '.githooks/pre-commit',
@@ -32,6 +48,11 @@ CRITICAL_GUARDRAIL_PATHS = {
32
48
  'scripts/guardex-env.sh',
33
49
  }
34
50
  ALLOW_GUARDRAIL_DELETE_ENV = 'AGENT_ALLOW_GUARDRAIL_DELETE'
51
+ LOCK_TTL_HOURS_ENV = 'GUARDEX_LOCK_TTL_HOURS'
52
+ LOCK_NOW_EPOCH_ENV = 'GUARDEX_LOCK_NOW_EPOCH'
53
+ # Generous default so an active long-running lane is never reaped; `reap` is an
54
+ # explicit, opt-in maintenance command, not an automatic background sweep.
55
+ DEFAULT_LOCK_TTL_HOURS = 168.0 # 7 days
35
56
 
36
57
 
37
58
  @dataclass
@@ -39,6 +60,7 @@ class LockEntry:
39
60
  branch: str
40
61
  claimed_at: str
41
62
  allow_delete: bool = False
63
+ agent: str = ''
42
64
 
43
65
 
44
66
  class LockError(Exception):
@@ -79,6 +101,41 @@ def lock_file_path(repo_root: Path) -> Path:
79
101
  return repo_root / LOCK_FILE_RELATIVE
80
102
 
81
103
 
104
+ def resolve_agent(args: argparse.Namespace) -> str:
105
+ """Owner agent id: explicit --agent wins, else GUARDEX_AGENT_ID, else ''.
106
+
107
+ Empty string means "no agent identity" — the legacy branch-only owner.
108
+ """
109
+ value = getattr(args, 'agent', None)
110
+ if not value:
111
+ value = os.environ.get(AGENT_ID_ENV, '')
112
+ return (value or '').strip()
113
+
114
+
115
+ def owner_label(entry: dict[str, Any]) -> str:
116
+ branch = str(entry.get('branch', ''))
117
+ agent = str(entry.get('agent', ''))
118
+ return f'{branch} as {agent}' if agent else branch
119
+
120
+
121
+ def owner_matches(entry: dict[str, Any], branch: str, agent: str) -> bool:
122
+ """Does this branch+agent own the entry?
123
+
124
+ Branch must always match. The agent dimension is a *refinement*: when either
125
+ side is unscoped (agent == '' — the legacy branch-only owner) ownership falls
126
+ back to branch level, so anonymous callers and branch-wide operations keep
127
+ working and a named agent can adopt a pre-existing anonymous lock on its own
128
+ branch. Two DIFFERENT named agents on the same branch do not match — that is
129
+ the mutual exclusion this feature adds.
130
+ """
131
+ if str(entry.get('branch', '')) != branch:
132
+ return False
133
+ entry_agent = str(entry.get('agent', ''))
134
+ if not agent or not entry_agent:
135
+ return True
136
+ return entry_agent == agent
137
+
138
+
82
139
  def load_state(repo_root: Path) -> dict[str, Any]:
83
140
  path = lock_file_path(repo_root)
84
141
  if not path.exists():
@@ -94,7 +151,7 @@ def load_state(repo_root: Path) -> dict[str, Any]:
94
151
  if not isinstance(locks, dict):
95
152
  return {'locks': {}}
96
153
 
97
- # Backward-compat normalization for older lock schema.
154
+ # Backward-compat normalization for older lock schema (no `agent` field).
98
155
  normalized_locks: dict[str, dict[str, Any]] = {}
99
156
  for file_path, entry in locks.items():
100
157
  if not isinstance(entry, dict):
@@ -102,10 +159,12 @@ def load_state(repo_root: Path) -> dict[str, Any]:
102
159
  branch = str(entry.get('branch', ''))
103
160
  claimed_at = str(entry.get('claimed_at', ''))
104
161
  allow_delete = bool(entry.get('allow_delete', False))
162
+ agent = str(entry.get('agent', ''))
105
163
  normalized_locks[str(file_path)] = {
106
164
  'branch': branch,
107
165
  'claimed_at': claimed_at,
108
166
  'allow_delete': allow_delete,
167
+ 'agent': agent,
109
168
  }
110
169
 
111
170
  return {'locks': normalized_locks}
@@ -120,7 +179,7 @@ def write_state(repo_root: Path, state: dict[str, Any]) -> None:
120
179
 
121
180
 
122
181
  def now_iso() -> str:
123
- return datetime.now(timezone.utc).isoformat()
182
+ return datetime.fromtimestamp(now_epoch(), tz=timezone.utc).isoformat()
124
183
 
125
184
 
126
185
  def env_truthy(value: str | None) -> bool:
@@ -129,6 +188,71 @@ def env_truthy(value: str | None) -> bool:
129
188
  return value.strip().lower() in {'1', 'true', 'yes', 'on'}
130
189
 
131
190
 
191
+ def now_epoch() -> float:
192
+ """Current unix time, overridable via GUARDEX_LOCK_NOW_EPOCH for tests."""
193
+ override = os.environ.get(LOCK_NOW_EPOCH_ENV)
194
+ if override:
195
+ try:
196
+ return float(override)
197
+ except ValueError:
198
+ pass
199
+ return datetime.now(timezone.utc).timestamp()
200
+
201
+
202
+ def parse_iso_epoch(value: str) -> float | None:
203
+ """Parse a `claimed_at` ISO-8601 stamp to a unix epoch, or None if unset
204
+ or unparseable. Naive stamps are assumed UTC (claims are written in UTC)."""
205
+ if not value:
206
+ return None
207
+ try:
208
+ dt = datetime.fromisoformat(value)
209
+ except ValueError:
210
+ return None
211
+ if dt.tzinfo is None:
212
+ dt = dt.replace(tzinfo=timezone.utc)
213
+ return dt.timestamp()
214
+
215
+
216
+ def has_live_process_in_worktree(worktree: Path) -> bool:
217
+ """True when any running process has its cwd inside `worktree` (Linux /proc
218
+ only; best-effort no elsewhere). Guards reap from touching an active lane."""
219
+ proc = Path('/proc')
220
+ if not proc.is_dir():
221
+ return False
222
+ wt = str(worktree)
223
+ try:
224
+ entries = list(proc.iterdir())
225
+ except OSError:
226
+ return False
227
+ for entry in entries:
228
+ if not entry.name.isdigit():
229
+ continue
230
+ try:
231
+ target = os.readlink(entry / 'cwd')
232
+ except OSError:
233
+ continue
234
+ if target.endswith(' (deleted)'):
235
+ target = target[: -len(' (deleted)')]
236
+ if target == wt or target.startswith(wt + os.sep):
237
+ return True
238
+ return False
239
+
240
+
241
+ def resolve_ttl_hours(args: argparse.Namespace) -> float:
242
+ """Reap TTL in hours: --ttl-hours wins, then GUARDEX_LOCK_TTL_HOURS, then
243
+ the 7-day default."""
244
+ explicit = getattr(args, 'ttl_hours', None)
245
+ if explicit is not None:
246
+ return float(explicit)
247
+ env = os.environ.get(LOCK_TTL_HOURS_ENV)
248
+ if env:
249
+ try:
250
+ return float(env)
251
+ except ValueError:
252
+ pass
253
+ return DEFAULT_LOCK_TTL_HOURS
254
+
255
+
132
256
  def staged_changes(repo_root: Path) -> list[tuple[str, str]]:
133
257
  out = run_git(['diff', '--cached', '--name-status', '--diff-filter=ACMRDTUXB'], cwd=repo_root)
134
258
  if not out:
@@ -155,43 +279,153 @@ def staged_changes(repo_root: Path) -> list[tuple[str, str]]:
155
279
  return results
156
280
 
157
281
 
282
+ def list_worktree_roots(repo_root: Path) -> list[Path]:
283
+ """Every worktree path for this repo (porcelain), ALWAYS including the
284
+ caller's own repo_root. Submodules checked out inside a LINKED worktree
285
+ report their gitdir (<parent>/.git/worktrees/<wt>/modules/<sub>) as the
286
+ worktree path, not the actual working tree — repo_root (resolved via
287
+ --show-toplevel) is where claims are written, so it must be in the list
288
+ or claim/validate/status never see this checkout's own lock file. Lock
289
+ enforcement fails closed when Git cannot enumerate every sibling."""
290
+ try:
291
+ out = run_git(['worktree', 'list', '--porcelain'], cwd=repo_root)
292
+ except LockError as exc:
293
+ raise LockError(
294
+ 'cannot safely enumerate sibling worktrees; lock operation blocked'
295
+ ) from exc
296
+ roots: list[Path] = []
297
+ for line in out.splitlines():
298
+ if line.startswith('worktree '):
299
+ roots.append(Path(line[len('worktree '):].strip()).resolve())
300
+ if repo_root not in roots:
301
+ roots.append(repo_root)
302
+ return roots
303
+
304
+
305
+ def load_all_locks(repo_root: Path) -> dict[str, list[dict[str, Any]]]:
306
+ """Union of EVERY worktree's lock map: file path -> list of owner entries
307
+ (one per worktree that claims it). Each worktree owns a separate lock file on
308
+ disk, so a file's full ownership is only visible by reading them all. With a
309
+ single worktree this is exactly that worktree's own locks (unchanged)."""
310
+ merged: dict[str, list[dict[str, Any]]] = {}
311
+ for root in list_worktree_roots(repo_root):
312
+ try:
313
+ state = load_state(root)
314
+ except LockError as exc:
315
+ raise LockError(
316
+ f'cannot safely inspect sibling lock registry in {root}; '
317
+ 'lock operation blocked'
318
+ ) from exc
319
+ for file_path, entry in state['locks'].items():
320
+ merged.setdefault(file_path, []).append(entry)
321
+ return merged
322
+
323
+
324
+ def common_git_dir(repo_root: Path) -> Path:
325
+ """Absolute git common dir — shared by every worktree of the repo."""
326
+ common = run_git(['rev-parse', '--git-common-dir'], cwd=repo_root)
327
+ path = Path(common)
328
+ if not path.is_absolute():
329
+ path = repo_root / path
330
+ return path.resolve()
331
+
332
+
333
+ @contextmanager
334
+ def cross_worktree_lock(repo_root: Path):
335
+ """Exclusive OS lock shared by ALL worktrees of the repo (it lives in the
336
+ common git dir), so concurrent claim/release/validate runs — in the same or
337
+ different worktrees — are serialized. Without it, two claims race on the
338
+ read-modify-write of separate lock files and can both win the same path or
339
+ drop each other's writes. Mutual exclusion is a safety boundary: unavailable
340
+ OS locking or an inaccessible common lock file blocks the command."""
341
+ if fcntl is None:
342
+ raise LockError('OS file locking is unavailable; lock operation blocked')
343
+ try:
344
+ lock_path = common_git_dir(repo_root) / 'agent-file-locks.lock'
345
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
346
+ handle = open(lock_path, 'w')
347
+ except (OSError, LockError) as exc:
348
+ raise LockError('cannot open the shared worktree lock; operation blocked') from exc
349
+ acquired = False
350
+ try:
351
+ try:
352
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
353
+ acquired = True
354
+ except OSError as exc:
355
+ raise LockError('cannot acquire the shared worktree lock; operation blocked') from exc
356
+ yield
357
+ finally:
358
+ try:
359
+ if acquired:
360
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
361
+ finally:
362
+ handle.close()
363
+
364
+
158
365
  def cmd_claim(args: argparse.Namespace, repo_root: Path) -> int:
159
366
  state = load_state(repo_root)
160
367
  locks: dict[str, dict[str, Any]] = state['locks']
161
368
 
369
+ claim_agent = resolve_agent(args)
162
370
  files = [normalize_repo_path(repo_root, p) for p in args.files]
163
371
  conflicts: list[tuple[str, str]] = []
164
372
 
373
+ # Conflict detection spans EVERY worktree of the repo, not just this one: a
374
+ # file claimed by another owner in a sibling worktree must still block this
375
+ # claim (each worktree keeps a separate lock file). The write below still
376
+ # records the claim in THIS worktree's lock file.
377
+ all_locks = load_all_locks(repo_root)
378
+ ttl_seconds = resolve_ttl_hours(args) * 3600.0
379
+ now = now_epoch()
380
+ any_stale = False
165
381
  for file_path in files:
166
- existing = locks.get(file_path)
167
- if existing and existing.get('branch') != args.branch:
168
- conflicts.append((file_path, str(existing.get('branch'))))
382
+ foreign = [e for e in all_locks.get(file_path, []) if not owner_matches(e, args.branch, claim_agent)]
383
+ if foreign:
384
+ conflicts.append((file_path, owner_label(foreign[0])))
385
+ claimed = parse_iso_epoch(str(foreign[0].get('claimed_at', '')))
386
+ if claimed is not None and (now - claimed) >= ttl_seconds:
387
+ any_stale = True
169
388
 
170
389
  if conflicts:
171
- print('[agent-file-locks] Cannot claim files already locked by other branches:', file=sys.stderr)
172
- for file_path, owner_branch in conflicts:
173
- print(f' - {file_path} (locked by {owner_branch})', file=sys.stderr)
390
+ print('[agent-file-locks] Cannot claim files already locked by another owner:', file=sys.stderr)
391
+ for file_path, owner in conflicts:
392
+ print(f' - {file_path} (locked by {owner})', file=sys.stderr)
393
+ if any_stale:
394
+ print(
395
+ '[agent-file-locks] Some blocking locks are past the staleness TTL; if their '
396
+ 'lane is abandoned, run `gx locks reap` to clear them.',
397
+ file=sys.stderr,
398
+ )
174
399
  return 1
175
400
 
176
401
  for file_path in files:
177
402
  existing = locks.get(file_path, {})
178
403
  existing_allow_delete = bool(existing.get('allow_delete', False))
404
+ # A named claim adopts/upgrades the entry's agent; an anonymous claim
405
+ # keeps any existing agent rather than silently downgrading it.
406
+ resolved_owner_agent = claim_agent or str(existing.get('agent', ''))
179
407
  locks[file_path] = LockEntry(
180
408
  branch=args.branch,
181
409
  claimed_at=now_iso(),
182
410
  allow_delete=args.allow_delete or existing_allow_delete,
411
+ agent=resolved_owner_agent,
183
412
  ).__dict__
184
413
 
185
414
  write_state(repo_root, state)
186
415
  delete_note = ' (delete-approved)' if args.allow_delete else ''
187
- print(f"[agent-file-locks] Claimed {len(files)} file(s) for {args.branch}{delete_note}.")
416
+ agent_note = f' as {claim_agent}' if claim_agent else ''
417
+ print(f"[agent-file-locks] Claimed {len(files)} file(s) for {args.branch}{agent_note}{delete_note}.")
188
418
  return 0
189
419
 
190
420
 
191
421
  def cmd_allow_delete(args: argparse.Namespace, repo_root: Path) -> int:
422
+ # Operates on THIS worktree's lock file only — run it from the worktree where
423
+ # the claim was made. (claim/validate union across worktrees; the write side
424
+ # stays local.)
192
425
  state = load_state(repo_root)
193
426
  locks: dict[str, dict[str, Any]] = state['locks']
194
427
  files = [normalize_repo_path(repo_root, p) for p in args.files]
428
+ agent = resolve_agent(args)
195
429
 
196
430
  missing: list[str] = []
197
431
  foreign: list[tuple[str, str]] = []
@@ -200,9 +434,8 @@ def cmd_allow_delete(args: argparse.Namespace, repo_root: Path) -> int:
200
434
  if not entry:
201
435
  missing.append(file_path)
202
436
  continue
203
- owner = str(entry.get('branch', ''))
204
- if owner != args.branch:
205
- foreign.append((file_path, owner))
437
+ if not owner_matches(entry, args.branch, agent):
438
+ foreign.append((file_path, owner_label(entry)))
206
439
  continue
207
440
  entry['allow_delete'] = True
208
441
 
@@ -212,7 +445,7 @@ def cmd_allow_delete(args: argparse.Namespace, repo_root: Path) -> int:
212
445
  for file_path in missing:
213
446
  print(f' - {file_path}', file=sys.stderr)
214
447
  if foreign:
215
- print('[agent-file-locks] Cannot enable delete: files are owned by another branch:', file=sys.stderr)
448
+ print('[agent-file-locks] Cannot enable delete: files are owned by another owner:', file=sys.stderr)
216
449
  for file_path, owner in foreign:
217
450
  print(f' - {file_path} (owner: {owner})', file=sys.stderr)
218
451
  return 1
@@ -223,15 +456,18 @@ def cmd_allow_delete(args: argparse.Namespace, repo_root: Path) -> int:
223
456
 
224
457
 
225
458
  def cmd_release(args: argparse.Namespace, repo_root: Path) -> int:
459
+ # Local-only, like allow-delete: releases claims recorded in THIS worktree's
460
+ # lock file. Run it from the worktree that made the claim.
226
461
  state = load_state(repo_root)
227
462
  locks: dict[str, dict[str, Any]] = state['locks']
463
+ agent = resolve_agent(args)
228
464
 
229
465
  to_release: set[str]
230
466
  if args.files:
231
467
  requested = {normalize_repo_path(repo_root, p) for p in args.files}
232
- to_release = {p for p in requested if locks.get(p, {}).get('branch') == args.branch}
468
+ to_release = {p for p in requested if owner_matches(locks.get(p, {}), args.branch, agent)}
233
469
  else:
234
- to_release = {p for p, entry in locks.items() if entry.get('branch') == args.branch}
470
+ to_release = {p for p, entry in locks.items() if owner_matches(entry, args.branch, agent)}
235
471
 
236
472
  for file_path in to_release:
237
473
  locks.pop(file_path, None)
@@ -241,33 +477,97 @@ def cmd_release(args: argparse.Namespace, repo_root: Path) -> int:
241
477
  return 0
242
478
 
243
479
 
244
- def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
245
- state = load_state(repo_root)
246
- locks: dict[str, dict[str, Any]] = state['locks']
247
-
248
- rows: list[tuple[str, str, str, bool]] = []
249
- for file_path, entry in sorted(locks.items()):
250
- branch = str(entry.get('branch', ''))
251
- if args.branch and branch != args.branch:
480
+ def cmd_reap(args: argparse.Namespace, repo_root: Path) -> int:
481
+ # Clear locks held by ABANDONED worktrees: present on disk, idle past the
482
+ # TTL, and with no live process inside. Dead worktrees self-clean (their lock
483
+ # file lives inside them), so this targets the lingering-but-idle case where
484
+ # a crashed or forgotten lane keeps blocking a file forever. The caller's own
485
+ # worktree always has a live process, so reap never clears its active locks.
486
+ ttl_hours = resolve_ttl_hours(args)
487
+ ttl_seconds = ttl_hours * 3600.0
488
+ now = now_epoch()
489
+ roots = list_worktree_roots(repo_root)
490
+ reaped: list[tuple[str, str, str, int]] = [] # worktree, file, branch, age_hours
491
+ for root in roots:
492
+ try:
493
+ state = load_state(root)
494
+ except LockError as exc:
495
+ raise LockError(
496
+ f'cannot safely inspect sibling lock registry in {root}; '
497
+ 'reap operation blocked'
498
+ ) from exc
499
+ locks = state['locks']
500
+ if not locks:
252
501
  continue
253
- claimed_at = str(entry.get('claimed_at', ''))
254
- allow_delete = bool(entry.get('allow_delete', False))
255
- rows.append((file_path, branch, claimed_at, allow_delete))
502
+ if has_live_process_in_worktree(root):
503
+ continue
504
+ survivors: dict[str, Any] = {}
505
+ changed = False
506
+ for file_path, entry in locks.items():
507
+ claimed = parse_iso_epoch(str(entry.get('claimed_at', '')))
508
+ if claimed is not None and (now - claimed) >= ttl_seconds:
509
+ reaped.append((str(root), file_path, str(entry.get('branch', '')), int((now - claimed) // 3600)))
510
+ changed = True
511
+ else:
512
+ survivors[file_path] = entry
513
+ if changed and not args.dry_run:
514
+ write_state(root, {**state, 'locks': survivors})
515
+
516
+ if not reaped:
517
+ print(f'[agent-file-locks] reap: no stale locks (ttl={int(ttl_hours)}h, scanned {len(roots)} worktree(s)).')
518
+ return 0
519
+ label = '[agent-file-locks] [dry-run] would reap' if args.dry_run else '[agent-file-locks] reaped'
520
+ print(f'{label} {len(reaped)} stale lock(s) (ttl={int(ttl_hours)}h):')
521
+ for root, file_path, branch, age_hours in reaped:
522
+ print(f' - {file_path} | {branch} | idle {age_hours}h | {root}')
523
+ return 0
524
+
525
+
526
+ def cmd_status(args: argparse.Namespace, repo_root: Path) -> int:
527
+ # Union across worktrees so status reflects what claim/validate now enforce —
528
+ # a sibling worktree's claims would otherwise be invisible here.
529
+ agent_filter = resolve_agent(args)
530
+ roots = list_worktree_roots(repo_root)
531
+
532
+ rows: list[tuple[str, str, str, str, bool, str]] = []
533
+ for root in roots:
534
+ try:
535
+ locks = load_state(root)['locks']
536
+ except LockError as exc:
537
+ raise LockError(
538
+ f'cannot safely inspect sibling lock registry in {root}; '
539
+ 'status is unavailable'
540
+ ) from exc
541
+ for file_path, entry in locks.items():
542
+ branch = str(entry.get('branch', ''))
543
+ if args.branch and branch != args.branch:
544
+ continue
545
+ agent = str(entry.get('agent', ''))
546
+ if agent_filter and agent != agent_filter:
547
+ continue
548
+ claimed_at = str(entry.get('claimed_at', ''))
549
+ allow_delete = bool(entry.get('allow_delete', False))
550
+ rows.append((file_path, branch, agent, claimed_at, allow_delete, str(root)))
551
+ rows.sort()
256
552
 
257
553
  if not rows:
258
554
  print('[agent-file-locks] No active locks.')
259
555
  return 0
260
556
 
557
+ multi = len(roots) > 1
261
558
  print('[agent-file-locks] Active locks:')
262
- for file_path, branch, claimed_at, allow_delete in rows:
559
+ for file_path, branch, agent, claimed_at, allow_delete, worktree in rows:
263
560
  delete_flag = ' delete-ok' if allow_delete else ''
264
- print(f' - {file_path} | {branch} | {claimed_at}{delete_flag}')
561
+ agent_flag = f' [{agent}]' if agent else ''
562
+ # Annotate the worktree only when there is more than one, so a single-
563
+ # worktree repo's output is unchanged.
564
+ wt_flag = f' @ {worktree}' if multi else ''
565
+ print(f' - {file_path} | {branch}{agent_flag} | {claimed_at}{delete_flag}{wt_flag}')
265
566
  return 0
266
567
 
267
568
 
268
569
  def cmd_validate(args: argparse.Namespace, repo_root: Path) -> int:
269
- state = load_state(repo_root)
270
- locks: dict[str, dict[str, Any]] = state['locks']
570
+ agent = resolve_agent(args)
271
571
 
272
572
  if args.staged:
273
573
  file_changes = staged_changes(repo_root)
@@ -289,35 +589,39 @@ def cmd_validate(args: argparse.Namespace, repo_root: Path) -> int:
289
589
 
290
590
  allow_guardrail_delete = env_truthy(os.environ.get(ALLOW_GUARDRAIL_DELETE_ENV))
291
591
 
592
+ # Enforce claims across ALL worktrees: a file owned by another agent in a
593
+ # sibling worktree blocks this commit, not just one claimed in this worktree.
594
+ all_locks = load_all_locks(repo_root)
292
595
  for status, file_path in file_changes:
293
- entry = locks.get(file_path)
294
- if not entry:
596
+ owners = all_locks.get(file_path, [])
597
+ if not owners:
295
598
  missing.append(file_path)
296
599
  continue
297
600
 
298
- owner = str(entry.get('branch', ''))
299
- if owner != args.branch:
300
- foreign.append((file_path, owner))
601
+ foreign_owners = [e for e in owners if not owner_matches(e, args.branch, agent)]
602
+ if foreign_owners:
603
+ foreign.append((file_path, owner_label(foreign_owners[0])))
301
604
  continue
302
605
 
303
606
  if status == 'D':
304
607
  if file_path in CRITICAL_GUARDRAIL_PATHS and not allow_guardrail_delete:
305
608
  guardrail_delete_blocked.append(file_path)
306
609
 
307
- allow_delete = bool(entry.get('allow_delete', False))
610
+ mine = next((e for e in owners if owner_matches(e, args.branch, agent)), None)
611
+ allow_delete = bool(mine.get('allow_delete', False)) if mine else False
308
612
  if not allow_delete:
309
613
  delete_not_allowed.append(file_path)
310
614
 
311
615
  if not missing and not foreign and not delete_not_allowed and not guardrail_delete_blocked:
312
616
  return 0
313
617
 
314
- print('[agent-file-locks] Commit blocked: staged files must be safely claimed by this branch first.', file=sys.stderr)
618
+ print('[agent-file-locks] Commit blocked: staged files must be safely claimed by this owner first.', file=sys.stderr)
315
619
  if missing:
316
620
  print(' Unclaimed files:', file=sys.stderr)
317
621
  for file_path in missing:
318
622
  print(f' - {file_path}', file=sys.stderr)
319
623
  if foreign:
320
- print(' Files claimed by another branch:', file=sys.stderr)
624
+ print(' Files claimed by another owner:', file=sys.stderr)
321
625
  for file_path, owner in foreign:
322
626
  print(f' - {file_path} (owner: {owner})', file=sys.stderr)
323
627
  if delete_not_allowed:
@@ -347,12 +651,21 @@ def cmd_validate(args: argparse.Namespace, repo_root: Path) -> int:
347
651
  return 1
348
652
 
349
653
 
654
+ def add_agent_arg(parser: argparse.ArgumentParser) -> None:
655
+ parser.add_argument(
656
+ '--agent',
657
+ default=None,
658
+ help=f'Owner agent id (defaults to ${AGENT_ID_ENV}); scopes ownership within a shared branch',
659
+ )
660
+
661
+
350
662
  def build_parser() -> argparse.ArgumentParser:
351
663
  parser = argparse.ArgumentParser(description='Concurrent agent file-lock utility')
352
664
  sub = parser.add_subparsers(dest='command', required=True)
353
665
 
354
666
  claim = sub.add_parser('claim', help='Claim file locks for a branch')
355
667
  claim.add_argument('--branch', required=True, help='Owner branch name (e.g., agent/foo/...)')
668
+ add_agent_arg(claim)
356
669
  claim.add_argument(
357
670
  '--allow-delete',
358
671
  action='store_true',
@@ -362,42 +675,67 @@ def build_parser() -> argparse.ArgumentParser:
362
675
 
363
676
  allow_delete = sub.add_parser('allow-delete', help='Enable delete approval on already claimed files')
364
677
  allow_delete.add_argument('--branch', required=True, help='Owner branch name')
678
+ add_agent_arg(allow_delete)
365
679
  allow_delete.add_argument('files', nargs='+', help='Files to mark as delete-approved')
366
680
 
367
681
  release = sub.add_parser('release', help='Release file locks for a branch')
368
682
  release.add_argument('--branch', required=True, help='Owner branch name')
683
+ add_agent_arg(release)
369
684
  release.add_argument('files', nargs='*', help='Optional files; omit to release all branch locks')
370
685
 
371
686
  status = sub.add_parser('status', help='Show lock status')
372
687
  status.add_argument('--branch', help='Filter by branch')
688
+ add_agent_arg(status)
689
+
690
+ reap = sub.add_parser('reap', help='Clear stale locks from abandoned (idle past TTL, no live process) worktrees')
691
+ reap.add_argument(
692
+ '--ttl-hours',
693
+ type=float,
694
+ default=None,
695
+ help=f'Idle hours before a lock is stale (default {int(DEFAULT_LOCK_TTL_HOURS)}h or ${LOCK_TTL_HOURS_ENV})',
696
+ )
697
+ reap.add_argument('--dry-run', action='store_true', help='Report stale locks without removing them')
373
698
 
374
699
  validate = sub.add_parser('validate', help='Validate staged files are locked by branch')
375
700
  validate.add_argument('--branch', required=True, help='Owner branch name')
701
+ add_agent_arg(validate)
376
702
  validate.add_argument('--staged', action='store_true', help='Validate staged files from git index')
377
703
  validate.add_argument('files', nargs='*', help='Files to validate when --staged is not used')
378
704
 
379
705
  return parser
380
706
 
381
707
 
708
+ def dispatch_command(args: argparse.Namespace, repo_root: Path) -> int:
709
+ if args.command == 'claim':
710
+ return cmd_claim(args, repo_root)
711
+ if args.command == 'allow-delete':
712
+ return cmd_allow_delete(args, repo_root)
713
+ if args.command == 'release':
714
+ return cmd_release(args, repo_root)
715
+ if args.command == 'reap':
716
+ return cmd_reap(args, repo_root)
717
+ if args.command == 'status':
718
+ return cmd_status(args, repo_root)
719
+ if args.command == 'validate':
720
+ if not args.staged and not args.files:
721
+ raise LockError('validate requires --staged or one or more file paths')
722
+ return cmd_validate(args, repo_root)
723
+ raise LockError(f'Unknown command: {args.command}')
724
+
725
+
382
726
  def main() -> int:
383
727
  parser = build_parser()
384
728
  args = parser.parse_args()
385
729
 
386
730
  try:
387
731
  repo_root = resolve_repo_root()
388
- if args.command == 'claim':
389
- return cmd_claim(args, repo_root)
390
- if args.command == 'allow-delete':
391
- return cmd_allow_delete(args, repo_root)
392
- if args.command == 'release':
393
- return cmd_release(args, repo_root)
394
- if args.command == 'status':
395
- return cmd_status(args, repo_root)
396
- if args.command == 'validate':
397
- if not args.staged and not args.files:
398
- raise LockError('validate requires --staged or one or more file paths')
399
- return cmd_validate(args, repo_root)
400
- raise LockError(f'Unknown command: {args.command}')
732
+ # Serialize state-changing commands (and validate's snapshot read) across
733
+ # ALL worktrees with one shared lock, so concurrent runs can't clobber
734
+ # each other or both win the same file. status is a pure read -> unlocked.
735
+ if args.command in {'claim', 'allow-delete', 'release', 'reap', 'validate'}:
736
+ with cross_worktree_lock(repo_root):
737
+ return dispatch_command(args, repo_root)
738
+ return dispatch_command(args, repo_root)
401
739
  except LockError as exc:
402
740
  print(f'[agent-file-locks] {exc}', file=sys.stderr)
403
741
  return 2