@imdeadpool/guardex 8.4.0 → 8.4.2

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 (97) hide show
  1. package/CONTRIBUTING.md +13 -4
  2. package/README.md +223 -1
  3. package/THIRD-PARTY-NOTICES.md +29 -0
  4. package/bin/multiagent-safety.js +9 -12
  5. package/package.json +4 -2
  6. package/skills/gitguardex/SKILL.md +28 -0
  7. package/skills/pr-lens/SKILL.md +87 -0
  8. package/src/abide.js +534 -0
  9. package/src/agents/activity.js +23 -4
  10. package/src/agents/inspect.js +15 -6
  11. package/src/agents/launch.js +6 -1
  12. package/src/agents/process-lease.js +84 -0
  13. package/src/agents/sessions.js +96 -16
  14. package/src/agents/start.js +18 -9
  15. package/src/agents/status.js +35 -14
  16. package/src/agents/supervise.js +87 -0
  17. package/src/budget/index.js +6 -1
  18. package/src/cli/args.js +71 -77
  19. package/src/cli/commands/agents.js +38 -10
  20. package/src/cli/commands/branch.js +116 -103
  21. package/src/cli/commands/claude.js +604 -50
  22. package/src/cli/commands/codex.js +359 -0
  23. package/src/cli/commands/context.js +52 -0
  24. package/src/cli/commands/mcp.js +5 -1
  25. package/src/cli/commands/pr.js +138 -3
  26. package/src/cli/commands/review.js +3 -1
  27. package/src/cli/commands/setup.js +25 -0
  28. package/src/cli/commands/status.js +128 -60
  29. package/src/cli/commands/storage.js +24 -0
  30. package/src/cli/commands/usage.js +48 -0
  31. package/src/cli/commands/watch.js +157 -47
  32. package/src/cli/commands/worktree-copy-ignored.js +38 -0
  33. package/src/cli/commands/worktree-estimate.js +69 -0
  34. package/src/cli/commands/worktree-hooks.js +62 -0
  35. package/src/cli/commands/worktree-navigation.js +71 -0
  36. package/src/cli/commands/worktree-provision.js +92 -0
  37. package/src/cli/main.js +229 -110
  38. package/src/cli/shared/gate-flags.js +131 -0
  39. package/src/cli/shared/scaffolding.js +31 -3
  40. package/src/cli/shared-locks.js +3 -1
  41. package/src/cockpit/pane-actions.js +43 -7
  42. package/src/context.js +373 -17
  43. package/src/doctor/index.js +29 -35
  44. package/src/finish/events.js +254 -0
  45. package/src/finish/index.js +322 -62
  46. package/src/finish/post-branch-finish-cleanup.js +316 -22
  47. package/src/finish/preflight.js +44 -1
  48. package/src/finish/progress.js +36 -0
  49. package/src/finish/review-gate.js +317 -127
  50. package/src/finish/review-receipt.js +156 -0
  51. package/src/finish/with-claims-lock.py +29 -0
  52. package/src/git/index.js +179 -42
  53. package/src/hooks/index.js +68 -3
  54. package/src/mcp/collect.js +61 -5
  55. package/src/mcp/server.js +4 -0
  56. package/src/output/index.js +167 -1
  57. package/src/pr-lens-publish.js +93 -0
  58. package/src/pr-lens.js +184 -0
  59. package/src/pr-respond.js +860 -0
  60. package/src/pr-review.js +519 -159
  61. package/src/pr.js +73 -14
  62. package/src/provider-binary.js +21 -0
  63. package/src/review-diff-context.js +90 -0
  64. package/src/review-fix.js +23 -17
  65. package/src/scaffold/agent-worktree-prep.js +14 -12
  66. package/src/scaffold/dependency-store.js +234 -0
  67. package/src/scaffold/index.js +13 -1
  68. package/src/scaffold/provision-approvals.js +83 -0
  69. package/src/scaffold/provision-config.js +169 -40
  70. package/src/shared-git-state.js +11 -1
  71. package/src/speckit/index.js +12 -1
  72. package/src/storage/run-artifacts.js +185 -0
  73. package/src/toolchain/index.js +322 -2
  74. package/src/worktree-copy-ignored.js +200 -0
  75. package/src/worktree-hook-worker.js +29 -0
  76. package/src/worktree-hooks.js +333 -0
  77. package/src/worktree-navigation.js +248 -0
  78. package/src/worktree-picker.js +89 -0
  79. package/src/worktree-quota.js +100 -0
  80. package/src/worktree-start.js +100 -0
  81. package/templates/AGENTS.multiagent-safety.md +8 -0
  82. package/templates/AGENTS.multiagent-safety.min.md +3 -1
  83. package/templates/codex/skills/gitguardex/SKILL.md +28 -0
  84. package/templates/codex/skills/opensrc/SKILL.md +24 -0
  85. package/templates/githooks/post-merge +16 -2
  86. package/templates/scripts/agent-autofinish-watch.sh +17 -18
  87. package/templates/scripts/agent-branch-finish.sh +180 -19
  88. package/templates/scripts/agent-branch-merge.sh +7 -32
  89. package/templates/scripts/agent-branch-start.sh +202 -43
  90. package/templates/scripts/agent-claude-stop-finish.sh +4 -27
  91. package/templates/scripts/agent-file-locks.py +257 -29
  92. package/templates/scripts/agent-preflight.sh +3 -0
  93. package/templates/scripts/agent-worktree-prune.sh +975 -63
  94. package/templates/scripts/codex-agent.sh +55 -5
  95. package/templates/scripts/lib/guardex-base-branch.sh +207 -0
  96. package/templates/scripts/openspec/init-change-workspace.sh +10 -18
  97. package/templates/scripts/review-bot-watch.sh +171 -4
@@ -25,6 +25,7 @@ import json
25
25
  import math
26
26
  import os
27
27
  import re
28
+ import shlex
28
29
  import shutil
29
30
  import subprocess
30
31
  import sys
@@ -59,6 +60,10 @@ LOCK_NOW_EPOCH_ENV = 'GUARDEX_LOCK_NOW_EPOCH'
59
60
  DEFAULT_LOCK_TTL_HOURS = 168.0 # 7 days
60
61
  ADAPTIVE_SESSION_LEASE_SECONDS_ENV = 'GUARDEX_ADAPTIVE_SESSION_LEASE_SEC'
61
62
  DEFAULT_ADAPTIVE_SESSION_LEASE_SECONDS = 900.0
63
+ # Override the `gh` binary path for testing or non-PATH installations.
64
+ LOCK_GH_BIN_ENV = 'GUARDEX_GH_BIN'
65
+ # Set to '0' to disable the gh/merge-base merged-branch check entirely.
66
+ LOCK_MERGED_CHECK_ENV = 'GUARDEX_LOCK_MERGED_CHECK'
62
67
 
63
68
 
64
69
  @dataclass
@@ -289,6 +294,120 @@ def resolve_ttl_hours(args: argparse.Namespace) -> float:
289
294
  return DEFAULT_LOCK_TTL_HOURS
290
295
 
291
296
 
297
+ def get_worktree_branch(worktree: Path) -> str | None:
298
+ """Return the branch name currently checked out in `worktree`, or None on error or detached HEAD."""
299
+ try:
300
+ branch = run_git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd=worktree)
301
+ return branch if branch and branch != 'HEAD' else None
302
+ except LockError:
303
+ return None
304
+
305
+
306
+ def is_branch_merged_via_gh(branch: str, gh_bin: str) -> bool | None:
307
+ """Ask the forge whether `branch` has at least one merged PR.
308
+
309
+ Returns True — forge confirmed ≥1 merged PR for this branch.
310
+ Returns False — forge confirmed no merged PR.
311
+ Returns None — gh unavailable, not authenticated, network error, or
312
+ unexpected output: caller must treat as "unknown" (fail safe).
313
+ """
314
+ try:
315
+ result = subprocess.run(
316
+ [gh_bin, 'pr', 'list', '--head', branch, '--state', 'merged',
317
+ '--json', 'state', '--jq', 'length'],
318
+ capture_output=True,
319
+ text=True,
320
+ timeout=15,
321
+ check=False,
322
+ )
323
+ except (OSError, subprocess.TimeoutExpired):
324
+ return None
325
+ if result.returncode != 0:
326
+ return None
327
+ txt = result.stdout.strip()
328
+ if txt.isdigit():
329
+ return int(txt) > 0
330
+ return None
331
+
332
+
333
+ def is_branch_merged_via_git(branch: str, repo_root: Path) -> bool | None:
334
+ """Fall back to git merge-base when gh is unavailable.
335
+
336
+ Returns True — the branch tip is an ancestor of the inferred base
337
+ (origin/<base>), meaning it has been merged.
338
+ Returns False — the branch tip is NOT an ancestor of the base.
339
+ Returns None — cannot determine (missing refs, error).
340
+ """
341
+ # Resolve branch tip.
342
+ try:
343
+ tip = run_git(['rev-parse', '--verify', f'refs/heads/{branch}'], cwd=repo_root)
344
+ except LockError:
345
+ tip = None
346
+ if not tip:
347
+ # Try the remote ref instead.
348
+ try:
349
+ tip = run_git(['rev-parse', '--verify', f'refs/remotes/origin/{branch}'], cwd=repo_root)
350
+ except LockError:
351
+ return None
352
+
353
+ # Discover base: respect GUARDEX_BASE_BRANCH, then origin/HEAD, then 'main'.
354
+ base = os.environ.get('GUARDEX_BASE_BRANCH', '').strip()
355
+ if not base:
356
+ try:
357
+ head = run_git(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], cwd=repo_root)
358
+ if head.startswith('origin/'):
359
+ base = head[len('origin/'):]
360
+ except LockError:
361
+ pass
362
+ if not base:
363
+ base = 'main'
364
+
365
+ base_ref = f'origin/{base}'
366
+ try:
367
+ run_git(['rev-parse', '--verify', base_ref], cwd=repo_root)
368
+ except LockError:
369
+ return None # base ref doesn't exist locally
370
+
371
+ try:
372
+ result = subprocess.run(
373
+ ['git', 'merge-base', '--is-ancestor', tip, base_ref],
374
+ cwd=str(repo_root),
375
+ check=False,
376
+ stdout=subprocess.DEVNULL,
377
+ stderr=subprocess.DEVNULL,
378
+ )
379
+ if result.returncode == 0:
380
+ return True
381
+ if result.returncode == 1:
382
+ return False
383
+ except OSError:
384
+ pass
385
+ return None
386
+
387
+
388
+ def is_branch_merged(branch: str, repo_root: Path, gh_bin: str, gh_warned: list[bool]) -> bool | None:
389
+ """Determine whether `branch` is merged, using gh then git as fallback.
390
+
391
+ Fail safe: returns None (unknown / keep lock) on any error.
392
+ Warns once per reap run when gh is unavailable or fails.
393
+ """
394
+ # Try gh first.
395
+ merged = is_branch_merged_via_gh(branch, gh_bin)
396
+ if merged is not None:
397
+ return merged
398
+
399
+ # gh failed or is unavailable — warn once, then try git fallback.
400
+ if not gh_warned[0]:
401
+ print(
402
+ '[agent-file-locks] reap: gh unavailable or failed; '
403
+ 'falling back to git merge-base for merged-branch detection.',
404
+ file=sys.stderr,
405
+ )
406
+ gh_warned[0] = True
407
+
408
+ return is_branch_merged_via_git(branch, repo_root)
409
+
410
+
292
411
  def staged_changes(repo_root: Path) -> list[tuple[str, str]]:
293
412
  out = run_git(['diff', '--cached', '--name-status', '--diff-filter=ACMRDTUXB'], cwd=repo_root)
294
413
  if not out:
@@ -567,6 +686,22 @@ def cmd_claim(args: argparse.Namespace, repo_root: Path, adaptive_owner: str) ->
567
686
  print('[agent-file-locks] Cannot claim files already locked by another owner:', file=sys.stderr)
568
687
  for file_path, owner in conflicts:
569
688
  print(f' - {file_path} (locked by {owner_description(owner)})', file=sys.stderr)
689
+ # Taking a lock over is an owner decision, so spell out the command
690
+ # rather than leave the next agent to discover where the claim lives.
691
+ owners: dict[str, list[str]] = {}
692
+ for file_path, owner in conflicts:
693
+ owner_agent = str(owner.get('agent', '')).strip()
694
+ owner_args = f"--branch {shlex.quote(str(owner.get('branch', '')))}"
695
+ if owner_agent:
696
+ owner_args += f' --agent {shlex.quote(owner_agent)}'
697
+ owners.setdefault(owner_args, []).append(file_path)
698
+ print(
699
+ '[agent-file-locks] If the owner agreed to hand them over, release them '
700
+ '(works from any worktree), then claim again:',
701
+ file=sys.stderr,
702
+ )
703
+ for owner_args, owned in owners.items():
704
+ print(f' gx locks release {owner_args} {" ".join(shlex.quote(p) for p in owned)}', file=sys.stderr)
570
705
  if any_stale:
571
706
  print(
572
707
  '[agent-file-locks] Some blocking locks are past the staleness TTL; if their '
@@ -635,60 +770,135 @@ def cmd_allow_delete(args: argparse.Namespace, repo_root: Path) -> int:
635
770
 
636
771
 
637
772
  def cmd_release(args: argparse.Namespace, repo_root: Path) -> int:
638
- # Local-only, like allow-delete: releases claims recorded in THIS worktree's
639
- # lock file. Run it from the worktree that made the claim.
640
- state = load_state(repo_root)
641
- locks: dict[str, dict[str, Any]] = state['locks']
773
+ # Spans EVERY worktree of the repo, like claim/validate: a claim lives in the
774
+ # lock file of the worktree that made it, so a release run anywhere else used
775
+ # to report "Released 0" while the claim kept blocking. Naming the owner
776
+ # branch (+ agent) is the explicit intent; only its entries are removed.
642
777
  agent = resolve_agent(args)
778
+ requested = {normalize_repo_path(repo_root, p) for p in args.files} if args.files else None
643
779
 
644
- to_release: set[str]
645
- if args.files:
646
- requested = {normalize_repo_path(repo_root, p) for p in args.files}
647
- to_release = {p for p in requested if owner_matches(locks.get(p, {}), args.branch, agent)}
648
- else:
649
- to_release = {p for p, entry in locks.items() if owner_matches(entry, args.branch, agent)}
650
-
651
- for file_path in to_release:
652
- locks.pop(file_path, None)
653
-
654
- write_state(repo_root, state)
655
- print(f"[agent-file-locks] Released {len(to_release)} file(s) for {args.branch}.")
780
+ released: list[tuple[Path, int]] = []
781
+ for root in list_worktree_roots(repo_root):
782
+ try:
783
+ state = load_state(root)
784
+ except LockError as exc:
785
+ raise LockError(
786
+ f'cannot safely inspect sibling lock registry in {root}; '
787
+ 'release operation blocked'
788
+ ) from exc
789
+ locks: dict[str, dict[str, Any]] = state['locks']
790
+ candidates = requested if requested is not None else set(locks)
791
+ to_release = {p for p in candidates if p in locks and owner_matches(locks[p], args.branch, agent)}
792
+ if not to_release:
793
+ continue
794
+ for file_path in to_release:
795
+ locks.pop(file_path, None)
796
+ write_state(root, state)
797
+ released.append((root, len(to_release)))
798
+
799
+ total = sum(count for _, count in released)
800
+ print(f"[agent-file-locks] Released {total} file(s) for {args.branch}.")
801
+ for root, count in released:
802
+ if root != repo_root:
803
+ print(f' - {count} from worktree {root}')
656
804
  return 0
657
805
 
658
806
 
659
807
  def cmd_reap(args: argparse.Namespace, repo_root: Path) -> int:
660
- # Clear locks held by ABANDONED worktrees: present on disk, idle past the
661
- # TTL, and with no live process inside. Dead worktrees self-clean (their lock
662
- # file lives inside them), so this targets the lingering-but-idle case where
663
- # a crashed or forgotten lane keeps blocking a file forever. The caller's own
664
- # worktree always has a live process, so reap never clears its active locks.
808
+ # Clear locks that are stale by any of three criteria:
809
+ #
810
+ # 1. TTL-expired (existing): worktree has no live process AND the lock is
811
+ # older than the TTL. This handles crashed/forgotten idle lanes.
812
+ #
813
+ # 2. Merged-branch (new): the owning branch has a merged PR (detected via
814
+ # `gh pr list --head <branch> --state merged`, falling back to
815
+ # `git merge-base --is-ancestor`). Stale regardless of TTL or live
816
+ # process — the branch landed; the lock is obsolete. Fails safe: a
817
+ # network/gh error keeps the lock and prints one warning per run.
818
+ #
819
+ # 3. Worktree-branch-mismatch (new): the worktree that holds the lock is
820
+ # now checked out on a DIFFERENT branch than the lock's owner branch.
821
+ # The agent that made the claim has left; the lock is orphaned. Stale
822
+ # regardless of TTL or live process. Only triggered when the current
823
+ # branch is determinable — unknown branch means fail safe (keep lock).
665
824
  ttl_hours = resolve_ttl_hours(args)
666
825
  ttl_seconds = ttl_hours * 3600.0
667
826
  now = now_epoch()
668
827
  roots = list_worktree_roots(repo_root)
669
- reaped: list[tuple[str, str, str, int]] = [] # worktree, file, branch, age_hours
828
+
829
+ # Load every worktree's state once so we can collect all unique branches
830
+ # before issuing any forge calls (one gh call per branch, not per entry).
831
+ worktree_states: dict[Path, dict[str, Any]] = {}
832
+ all_branches: set[str] = set()
670
833
  for root in roots:
671
834
  try:
672
835
  state = load_state(root)
836
+ worktree_states[root] = state
837
+ for entry in state['locks'].values():
838
+ b = str(entry.get('branch', ''))
839
+ if b:
840
+ all_branches.add(b)
673
841
  except LockError as exc:
674
842
  raise LockError(
675
843
  f'cannot safely inspect sibling lock registry in {root}; '
676
844
  'reap operation blocked'
677
845
  ) from exc
846
+
847
+ # Determine which branches are merged (batch: one gh call per branch).
848
+ # Disabled when --no-merged-check is passed or GUARDEX_LOCK_MERGED_CHECK=0.
849
+ merged_check_disabled = (
850
+ getattr(args, 'no_merged_check', False)
851
+ or not env_truthy(os.environ.get(LOCK_MERGED_CHECK_ENV, '1'))
852
+ )
853
+ merged_branches: set[str] = set()
854
+ if not merged_check_disabled and all_branches:
855
+ gh_bin = os.environ.get(LOCK_GH_BIN_ENV, '').strip() or shutil.which('gh') or 'gh'
856
+ gh_warned: list[bool] = [False]
857
+ for branch in sorted(all_branches): # sorted for deterministic output
858
+ result = is_branch_merged(branch, repo_root, gh_bin, gh_warned)
859
+ if result is True:
860
+ merged_branches.add(branch)
861
+
862
+ # Process each worktree.
863
+ reaped: list[tuple[str, str, str, int, str]] = [] # root, file, branch, age_h, reason
864
+ for root in roots:
865
+ state = worktree_states.get(root)
866
+ if state is None:
867
+ continue
678
868
  locks = state['locks']
679
869
  if not locks:
680
870
  continue
681
- if has_live_process_in_worktree(root):
682
- continue
871
+
872
+ worktree_has_live = has_live_process_in_worktree(root)
873
+ wt_branch = get_worktree_branch(root) # None if indeterminate
874
+
683
875
  survivors: dict[str, Any] = {}
684
876
  changed = False
685
877
  for file_path, entry in locks.items():
878
+ branch = str(entry.get('branch', ''))
686
879
  claimed = parse_iso_epoch(str(entry.get('claimed_at', '')))
687
- if claimed is not None and (now - claimed) >= ttl_seconds:
688
- reaped.append((str(root), file_path, str(entry.get('branch', '')), int((now - claimed) // 3600)))
880
+ age_hours = int((now - claimed) // 3600) if claimed is not None else 0
881
+
882
+ reason: str | None = None
883
+
884
+ # Criterion 2: merged branch — stale regardless of TTL or live process.
885
+ if branch and branch in merged_branches:
886
+ reason = 'merged-branch'
887
+
888
+ # Criterion 3: worktree switched to a different branch — orphaned lock.
889
+ elif wt_branch is not None and branch and wt_branch != branch:
890
+ reason = 'branch-switched'
891
+
892
+ # Criterion 1 (original): TTL expired with no live process.
893
+ elif not worktree_has_live and claimed is not None and (now - claimed) >= ttl_seconds:
894
+ reason = 'ttl'
895
+
896
+ if reason:
897
+ reaped.append((str(root), file_path, branch, age_hours, reason))
689
898
  changed = True
690
899
  else:
691
900
  survivors[file_path] = entry
901
+
692
902
  if changed and not args.dry_run:
693
903
  write_state(root, {**state, 'locks': survivors})
694
904
 
@@ -697,8 +907,14 @@ def cmd_reap(args: argparse.Namespace, repo_root: Path) -> int:
697
907
  return 0
698
908
  label = '[agent-file-locks] [dry-run] would reap' if args.dry_run else '[agent-file-locks] reaped'
699
909
  print(f'{label} {len(reaped)} stale lock(s) (ttl={int(ttl_hours)}h):')
700
- for root, file_path, branch, age_hours in reaped:
701
- print(f' - {file_path} | {branch} | idle {age_hours}h | {root}')
910
+ for root, file_path, branch, age_hours, reason in reaped:
911
+ if reason == 'ttl':
912
+ detail = f'idle {age_hours}h'
913
+ elif reason == 'merged-branch':
914
+ detail = 'merged PR'
915
+ else:
916
+ detail = reason # branch-switched or future reasons
917
+ print(f' - {file_path} | {branch} | {detail} | {root}')
702
918
  return 0
703
919
 
704
920
 
@@ -872,7 +1088,14 @@ def build_parser() -> argparse.ArgumentParser:
872
1088
  status.add_argument('--branch', help='Filter by branch')
873
1089
  add_agent_arg(status)
874
1090
 
875
- reap = sub.add_parser('reap', help='Clear stale locks from abandoned (idle past TTL, no live process) worktrees')
1091
+ reap = sub.add_parser(
1092
+ 'reap',
1093
+ help=(
1094
+ 'Clear stale locks: TTL-expired idle lanes, merged-branch locks '
1095
+ '(branch PR merged regardless of TTL), and worktrees switched to a '
1096
+ 'different branch.'
1097
+ ),
1098
+ )
876
1099
  reap.add_argument(
877
1100
  '--ttl-hours',
878
1101
  type=float,
@@ -880,6 +1103,11 @@ def build_parser() -> argparse.ArgumentParser:
880
1103
  help=f'Idle hours before a lock is stale (default {int(DEFAULT_LOCK_TTL_HOURS)}h or ${LOCK_TTL_HOURS_ENV})',
881
1104
  )
882
1105
  reap.add_argument('--dry-run', action='store_true', help='Report stale locks without removing them')
1106
+ reap.add_argument(
1107
+ '--no-merged-check',
1108
+ action='store_true',
1109
+ help='Skip merged-branch and branch-switched checks; only apply the TTL criterion',
1110
+ )
883
1111
 
884
1112
  validate = sub.add_parser('validate', help='Validate staged files are locked by branch')
885
1113
  validate.add_argument('--branch', required=True, help='Owner branch name')
@@ -65,7 +65,10 @@ run_verification_command() {
65
65
  -u GUARDEX_FINISH_ACTIVE_CWD \
66
66
  -u GUARDEX_FINISH_CHECKLIST \
67
67
  -u GUARDEX_FINISH_GATE_DONE \
68
+ -u GUARDEX_FINISH_REVIEWED_HEAD \
69
+ -u GUARDEX_FINISH_REVIEWED_BASE \
68
70
  -u GUARDEX_FINISH_REQUIRE_PREFLIGHT \
71
+ -u GUARDEX_PREFLIGHT_TARGET_WORKTREE \
69
72
  -u GUARDEX_FINISH_EVENT_FILE \
70
73
  -u GUARDEX_FINISH_RUN_ID \
71
74
  -u GUARDEX_FINISH_EVENT_BRANCH \