@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
@@ -8,9 +8,14 @@ FORCE_DIRTY=0
8
8
  DELETE_BRANCHES=0
9
9
  DELETE_REMOTE_BRANCHES=0
10
10
  ONLY_DIRTY_WORKTREES=0
11
+ INCLUDE_CLEAN_LINKED_WORKTREES=0
11
12
  INCLUDE_PR_MERGED=0
13
+ PRESERVE_OPEN_PRS=0
14
+ PRUNE_STALE_LANES=0
12
15
  TARGET_BRANCH=""
13
16
  IDLE_MINUTES=0
17
+ MAX_BRANCHES=0
18
+ MAX_BRANCHES_EXPLICIT=0
14
19
  NOW_EPOCH_RAW="${GUARDEX_PRUNE_NOW_EPOCH:-}"
15
20
  IDLE_SECONDS=0
16
21
  NOW_EPOCH=0
@@ -18,6 +23,12 @@ GH_BIN="${GUARDEX_GH_BIN:-gh}"
18
23
  PR_MERGED_LOOKUP_DISABLED=0
19
24
  PR_MERGED_LOOKUP_LOADED=0
20
25
  declare -A MERGED_PR_BRANCHES=()
26
+ OPEN_PR_LOOKUP_UNAVAILABLE=0
27
+ LANE_PR_LOOKUP_LOADED=0
28
+ LANE_PR_LOOKUP_UNAVAILABLE=0
29
+ declare -A LANE_PR_STATES=()
30
+ declare -A LANE_PR_BASES=()
31
+ declare -A LANE_PR_HEAD_SHAS=()
21
32
  WORKTREE_ROOT_RELS=(
22
33
  ".omx/agent-worktrees"
23
34
  ".omx/.tmp-worktrees"
@@ -56,10 +67,22 @@ while [[ $# -gt 0 ]]; do
56
67
  ONLY_DIRTY_WORKTREES=1
57
68
  shift
58
69
  ;;
70
+ --include-clean-linked-worktrees)
71
+ INCLUDE_CLEAN_LINKED_WORKTREES=1
72
+ shift
73
+ ;;
59
74
  --include-pr-merged)
60
75
  INCLUDE_PR_MERGED=1
61
76
  shift
62
77
  ;;
78
+ --preserve-open-prs)
79
+ PRESERVE_OPEN_PRS=1
80
+ shift
81
+ ;;
82
+ --prune-stale-lanes)
83
+ PRUNE_STALE_LANES=1
84
+ shift
85
+ ;;
63
86
  --branch)
64
87
  TARGET_BRANCH="${2:-}"
65
88
  shift 2
@@ -68,9 +91,14 @@ while [[ $# -gt 0 ]]; do
68
91
  IDLE_MINUTES="${2:-}"
69
92
  shift 2
70
93
  ;;
94
+ --max-branches)
95
+ MAX_BRANCHES="${2:-}"
96
+ MAX_BRANCHES_EXPLICIT=1
97
+ shift 2
98
+ ;;
71
99
  *)
72
100
  echo "[agent-worktree-prune] Unknown argument: $1" >&2
73
- echo "Usage: $0 [--base <branch>] [--dry-run] [--force-dirty] [--delete-branches] [--delete-remote-branches] [--only-dirty-worktrees] [--include-pr-merged] [--branch <agent/...>] [--idle-minutes <minutes>]" >&2
101
+ echo "Usage: $0 [--base <branch>] [--dry-run] [--force-dirty] [--delete-branches] [--delete-remote-branches] [--only-dirty-worktrees] [--include-clean-linked-worktrees] [--include-pr-merged] [--preserve-open-prs] [--prune-stale-lanes] [--branch <agent/...>] [--idle-minutes <minutes>] [--max-branches <count>]" >&2
74
102
  exit 1
75
103
  ;;
76
104
  esac
@@ -195,6 +223,136 @@ branch_has_merged_pr() {
195
223
  [[ -n "${MERGED_PR_BRANCHES[$branch]:-}" ]]
196
224
  }
197
225
 
226
+ load_lane_pr_metadata() {
227
+ if [[ "$LANE_PR_LOOKUP_LOADED" -eq 1 ]]; then
228
+ [[ "$LANE_PR_LOOKUP_UNAVAILABLE" -eq 0 ]]
229
+ return
230
+ fi
231
+ LANE_PR_LOOKUP_LOADED=1
232
+ if ! command -v "$GH_BIN" >/dev/null 2>&1; then
233
+ LANE_PR_LOOKUP_UNAVAILABLE=1
234
+ return 1
235
+ fi
236
+
237
+ local rows=""
238
+ if ! rows="$(
239
+ cd "$repo_root" &&
240
+ "$GH_BIN" api --paginate 'repos/{owner}/{repo}/pulls?state=all&per_page=100' \
241
+ --jq '.[] | [.head.ref, .head.sha, (.head.repo.full_name // "-"), .base.ref, (if .merged_at then "MERGED" else (.state | ascii_upcase) end), .base.repo.full_name] | @tsv' 2>/dev/null
242
+ )"; then
243
+ LANE_PR_LOOKUP_UNAVAILABLE=1
244
+ return 1
245
+ fi
246
+
247
+ local head=""
248
+ local head_sha=""
249
+ local head_repo=""
250
+ local base=""
251
+ local state=""
252
+ local base_repo=""
253
+ local local_tip=""
254
+ local existing=""
255
+ while IFS=$'\t' read -r head head_sha head_repo base state base_repo; do
256
+ [[ "$head" == agent/* || "$head" == work/* ]] || continue
257
+ local_tip="$(git -C "$repo_root" rev-parse --verify "refs/heads/${head}^{commit}" 2>/dev/null || true)"
258
+ existing="${LANE_PR_STATES[$head]:-}"
259
+ if [[ "$state" == "OPEN" ]]; then
260
+ LANE_PR_STATES["$head"]="$state"
261
+ LANE_PR_BASES["$head"]="$base"
262
+ LANE_PR_HEAD_SHAS["$head"]="$head_sha"
263
+ elif [[ -n "$local_tip" && "$head_sha" == "$local_tip" && "${head_repo,,}" == "${base_repo,,}" && -z "$existing" ]]; then
264
+ LANE_PR_STATES["$head"]="$state"
265
+ LANE_PR_BASES["$head"]="$base"
266
+ LANE_PR_HEAD_SHAS["$head"]="$head_sha"
267
+ fi
268
+ done <<< "$rows"
269
+ return 0
270
+ }
271
+
272
+ lane_pr_state() {
273
+ local branch="$1"
274
+ load_lane_pr_metadata || return 1
275
+ printf '%s' "${LANE_PR_STATES[$branch]:-}"
276
+ }
277
+
278
+ lane_pr_base() {
279
+ local branch="$1"
280
+ load_lane_pr_metadata || return 1
281
+ printf '%s' "${LANE_PR_BASES[$branch]:-}"
282
+ }
283
+
284
+ classified_merged_pr_head() {
285
+ local branch="$1"
286
+ load_lane_pr_metadata || return 1
287
+ [[ "${LANE_PR_STATES[$branch]:-}" == "MERGED" ]] || return 1
288
+ local classified_head="${LANE_PR_HEAD_SHAS[$branch]:-}"
289
+ [[ -n "$classified_head" ]] || return 1
290
+ printf '%s' "$classified_head"
291
+ }
292
+
293
+ closed_pr_has_remote_recovery() {
294
+ local branch="$1"
295
+ load_lane_pr_metadata || return 1
296
+ [[ "${LANE_PR_STATES[$branch]:-}" == "CLOSED" ]] || return 1
297
+ local classified_head="${LANE_PR_HEAD_SHAS[$branch]:-}"
298
+ local remote_head=""
299
+ [[ -n "$classified_head" ]] || return 1
300
+ remote_head="$(git -C "$repo_root" ls-remote --heads origin "refs/heads/${branch}" 2>/dev/null | awk 'NR == 1 { print $1 }')"
301
+ [[ "$remote_head" == "$classified_head" ]]
302
+ }
303
+
304
+ should_preserve_open_pr_branch() {
305
+ local branch="$1"
306
+ local open_branch=""
307
+ if [[ "$PRESERVE_OPEN_PRS" -ne 1 ]]; then
308
+ return 1
309
+ fi
310
+ OPEN_PR_LOOKUP_UNAVAILABLE=0
311
+ if [[ "$PRUNE_STALE_LANES" -eq 1 ]]; then
312
+ if ! load_lane_pr_metadata; then
313
+ OPEN_PR_LOOKUP_UNAVAILABLE=1
314
+ return 0
315
+ fi
316
+ [[ "${LANE_PR_STATES[$branch]:-}" == "OPEN" ]]
317
+ return
318
+ fi
319
+ # This flag is used by unattended cleanup. If GitHub cannot prove the lane
320
+ # has no open PR, fail closed and preserve it; a later doctor run can retry.
321
+ if ! command -v "$GH_BIN" >/dev/null 2>&1; then
322
+ OPEN_PR_LOOKUP_UNAVAILABLE=1
323
+ return 0
324
+ fi
325
+ if ! open_branch="$(
326
+ "$GH_BIN" pr list --state open --head "$branch" --limit 1 --json headRefName --jq '.[0].headRefName // ""' 2>/dev/null
327
+ )"; then
328
+ OPEN_PR_LOOKUP_UNAVAILABLE=1
329
+ return 0
330
+ fi
331
+ [[ -n "$open_branch" ]]
332
+ }
333
+
334
+ stale_lane_removal_reason() {
335
+ local branch="$1"
336
+ [[ "$PRUNE_STALE_LANES" -eq 1 ]] || return 1
337
+ load_lane_pr_metadata || return 1
338
+ local state="${LANE_PR_STATES[$branch]:-}"
339
+ local base="${LANE_PR_BASES[$branch]:-unknown}"
340
+ case "$state" in
341
+ MERGED)
342
+ printf 'merged-pr:%s' "$base"
343
+ ;;
344
+ CLOSED)
345
+ printf 'closed-pr:%s' "$base"
346
+ ;;
347
+ "")
348
+ printf 'stale-no-pr-worktree'
349
+ ;;
350
+ *)
351
+ return 1
352
+ ;;
353
+ esac
354
+ }
355
+
198
356
  if [[ "$BASE_BRANCH_EXPLICIT" -eq 1 && -z "$BASE_BRANCH" ]]; then
199
357
  echo "[agent-worktree-prune] --base requires a non-empty branch name." >&2
200
358
  exit 1
@@ -210,6 +368,11 @@ if [[ ! "$IDLE_MINUTES" =~ ^[0-9]+$ ]]; then
210
368
  exit 1
211
369
  fi
212
370
 
371
+ if [[ "$MAX_BRANCHES_EXPLICIT" -eq 1 ]] && { [[ ! "$MAX_BRANCHES" =~ ^[0-9]+$ ]] || [[ "$MAX_BRANCHES" -lt 1 ]]; }; then
372
+ echo "[agent-worktree-prune] --max-branches must be an integer >= 1." >&2
373
+ exit 1
374
+ fi
375
+
213
376
  if [[ -n "$NOW_EPOCH_RAW" && ! "$NOW_EPOCH_RAW" =~ ^[0-9]+$ ]]; then
214
377
  echo "[agent-worktree-prune] GUARDEX_PRUNE_NOW_EPOCH must be a unix timestamp integer." >&2
215
378
  exit 1
@@ -244,6 +407,18 @@ run_cmd() {
244
407
  "$@"
245
408
  }
246
409
 
410
+ delete_local_branch() {
411
+ local branch="$1"
412
+ local mode="$2"
413
+ local expected_head="${3:-}"
414
+ if [[ "$mode" == "force" ]]; then
415
+ [[ -n "$expected_head" ]] || return 1
416
+ run_cmd git -C "$repo_root" update-ref -d "refs/heads/${branch}" "$expected_head"
417
+ return
418
+ fi
419
+ run_cmd git -C "$repo_root" branch -d "$branch"
420
+ }
421
+
247
422
  branch_has_worktree() {
248
423
  local branch="$1"
249
424
  git -C "$repo_root" worktree list --porcelain | grep -q "^branch refs/heads/${branch}$"
@@ -350,12 +525,14 @@ read_branch_activity_epoch() {
350
525
  local branch="$1"
351
526
  local wt="${2:-}"
352
527
  local activity_epoch=""
528
+ local reflog_selector=""
353
529
 
354
- activity_epoch="$(
355
- git -C "$repo_root" reflog show --format='%ct' -n 1 "refs/heads/${branch}" 2>/dev/null \
530
+ reflog_selector="$(
531
+ git -C "$repo_root" reflog show --date=unix --format='%gd' -n 1 "refs/heads/${branch}" 2>/dev/null \
356
532
  | head -n 1 \
357
533
  | tr -d '[:space:]'
358
534
  )"
535
+ activity_epoch="$(printf '%s' "$reflog_selector" | sed -n -E 's/.*@\{([0-9]+)([[:space:]]?[+-][0-9]{4})?\}$/\1/p')"
359
536
  if [[ -z "$activity_epoch" ]]; then
360
537
  activity_epoch="$(
361
538
  git -C "$repo_root" log -1 --format='%ct' "$branch" 2>/dev/null \
@@ -402,6 +579,89 @@ has_live_process_in_worktree() {
402
579
  return 1
403
580
  }
404
581
 
582
+ remove_worktree_with_lock_guard() {
583
+ local worktree="$1"
584
+ local remove_reason="$2"
585
+ local branch="$3"
586
+ local lock_file="${worktree}/.omx/state/agent-file-locks.json"
587
+ local shared_lock="${repo_common_dir}/agent-file-locks.lock"
588
+
589
+ if ! command -v python3 >/dev/null 2>&1; then
590
+ echo "[agent-worktree-prune] Cannot safely lock active claims without python3: ${shared_lock}" >&2
591
+ return 10
592
+ fi
593
+
594
+ python3 - "$shared_lock" "$lock_file" "$repo_root" "$worktree" "$remove_reason" "$branch" "$DRY_RUN" <<'PY'
595
+ import json
596
+ import subprocess
597
+ import sys
598
+
599
+ try:
600
+ import fcntl
601
+ except ImportError:
602
+ print('[agent-worktree-prune] OS file locking is unavailable; prune blocked', file=sys.stderr)
603
+ raise SystemExit(10)
604
+
605
+ shared_lock, lock_file, repo_root, worktree, remove_reason, branch, dry_run = sys.argv[1:]
606
+ try:
607
+ with open(shared_lock, 'a+', encoding='utf-8') as lock_handle:
608
+ fcntl.flock(lock_handle.fileno(), fcntl.LOCK_EX)
609
+
610
+ try:
611
+ with open(lock_file, encoding='utf-8') as handle:
612
+ state = json.load(handle)
613
+ except FileNotFoundError:
614
+ state = {'locks': {}}
615
+ except (OSError, UnicodeError, json.JSONDecodeError):
616
+ print(
617
+ f'[agent-worktree-prune] Cannot safely inspect active locks: {lock_file}',
618
+ file=sys.stderr,
619
+ )
620
+ raise SystemExit(10)
621
+
622
+ locks = state.get('locks') if isinstance(state, dict) else None
623
+ if not isinstance(locks, dict):
624
+ print(
625
+ f'[agent-worktree-prune] Cannot safely inspect active locks: {lock_file}',
626
+ file=sys.stderr,
627
+ )
628
+ raise SystemExit(10)
629
+
630
+ for entry in locks.values():
631
+ if not isinstance(entry, dict):
632
+ print(
633
+ f'[agent-worktree-prune] Cannot safely inspect active locks: {lock_file}',
634
+ file=sys.stderr,
635
+ )
636
+ raise SystemExit(10)
637
+ if not branch.startswith(('agent/', 'work/')) or entry.get('branch') != branch:
638
+ raise SystemExit(10)
639
+
640
+ if locks:
641
+ label = 'lock' if len(locks) == 1 else 'locks'
642
+ print(
643
+ f'[agent-worktree-prune] Releasing {len(locks)} self-owned {label} '
644
+ f'while removing terminal worktree: {worktree}',
645
+ flush=True,
646
+ )
647
+
648
+ print(f'[agent-worktree-prune] Removing worktree ({remove_reason}): {worktree}', flush=True)
649
+ command = ['git', '-C', repo_root, 'worktree', 'remove', worktree, '--force']
650
+ if dry_run == '1':
651
+ print(f"[agent-worktree-prune] [dry-run] {' '.join(command)}")
652
+ raise SystemExit(0)
653
+
654
+ result = subprocess.run(command, check=False)
655
+ raise SystemExit(0 if result.returncode == 0 else 1)
656
+ except OSError:
657
+ print(
658
+ f'[agent-worktree-prune] Cannot safely acquire active lock guard: {shared_lock}',
659
+ file=sys.stderr,
660
+ )
661
+ raise SystemExit(10)
662
+ PY
663
+ }
664
+
405
665
  branch_idle_gate() {
406
666
  local branch="$1"
407
667
  local wt="$2"
@@ -495,6 +755,19 @@ removed_worktrees=0
495
755
  removed_branches=0
496
756
  skipped_active=0
497
757
  skipped_dirty=0
758
+ skipped_open_pr=0
759
+ processed_branches=0
760
+ skipped_limited=0
761
+
762
+ reserve_branch_slot() {
763
+ local branch="$1"
764
+ [[ -z "$branch" ]] && return 0
765
+ if [[ "$MAX_BRANCHES" -gt 0 && "$processed_branches" -ge "$MAX_BRANCHES" ]]; then
766
+ skipped_limited=$((skipped_limited + 1))
767
+ return 1
768
+ fi
769
+ processed_branches=$((processed_branches + 1))
770
+ }
498
771
 
499
772
  relocate_foreign_worktree_entries
500
773
 
@@ -503,7 +776,8 @@ process_entry() {
503
776
  local branch_ref="$2"
504
777
 
505
778
  [[ -z "$wt" ]] && return
506
- if ! is_managed_worktree_path "$wt"; then
779
+ [[ "$wt" == "$repo_root" ]] && return
780
+ if ! is_managed_worktree_path "$wt" && [[ "$INCLUDE_CLEAN_LINKED_WORKTREES" -ne 1 ]]; then
507
781
  return
508
782
  fi
509
783
 
@@ -526,9 +800,22 @@ process_entry() {
526
800
  echo "[agent-worktree-prune] Skipping live process worktree: ${wt}"
527
801
  return
528
802
  fi
803
+ if [[ "$branch" == agent/* || "$branch" == work/* ]] && should_preserve_open_pr_branch "$branch"; then
804
+ skipped_open_pr=$((skipped_open_pr + 1))
805
+ if [[ "$OPEN_PR_LOOKUP_UNAVAILABLE" -eq 1 ]]; then
806
+ echo "[agent-worktree-prune] Skipping open-PR worktree because PR state is unavailable (fail closed): ${wt}"
807
+ else
808
+ echo "[agent-worktree-prune] Skipping open-PR worktree: ${wt}"
809
+ fi
810
+ return
811
+ fi
529
812
 
530
813
  local remove_reason=""
531
814
  local branch_delete_mode="safe"
815
+ local branch_delete_label="merged"
816
+ local delete_remote_branch=1
817
+ local remote_delete_head=""
818
+ local expected_branch_head=""
532
819
 
533
820
  if is_temporary_worktree_path "$wt"; then
534
821
  remove_reason="temporary-worktree"
@@ -536,19 +823,40 @@ process_entry() {
536
823
  remove_reason="detached-worktree"
537
824
  elif ! git -C "$repo_root" show-ref --verify --quiet "refs/heads/${branch}"; then
538
825
  remove_reason="missing-branch"
539
- elif [[ "$branch" == agent/* ]]; then
540
- if git -C "$repo_root" merge-base --is-ancestor "$branch" "$BASE_BRANCH"; then
826
+ elif [[ "$branch" == agent/* ]] || { [[ "$branch" == work/* ]] && is_managed_worktree_path "$wt"; }; then
827
+ if [[ "$PRUNE_STALE_LANES" -eq 1 ]]; then
828
+ load_lane_pr_metadata || true
829
+ remove_reason="$(stale_lane_removal_reason "$branch" || true)"
830
+ case "$remove_reason" in
831
+ merged-pr:*)
832
+ branch_delete_mode="force"
833
+ branch_delete_label="merged PR"
834
+ expected_branch_head="${LANE_PR_HEAD_SHAS[$branch]:-}"
835
+ ;;
836
+ closed-pr:*)
837
+ branch_delete_mode="force"
838
+ branch_delete_label="closed PR"
839
+ expected_branch_head="${LANE_PR_HEAD_SHAS[$branch]:-}"
840
+ # Force-deletion is authorized only after closed_pr_has_remote_recovery
841
+ # verifies the exact PR head is still durable on origin.
842
+ delete_remote_branch=0
843
+ ;;
844
+ esac
845
+ elif git -C "$repo_root" merge-base --is-ancestor "$branch" "$BASE_BRANCH"; then
541
846
  if [[ "$DELETE_BRANCHES" -eq 1 ]]; then
542
847
  remove_reason="merged-agent-branch"
543
848
  fi
544
849
  elif [[ "$DELETE_BRANCHES" -eq 1 ]] && branch_has_merged_pr "$branch"; then
545
850
  remove_reason="merged-agent-pr"
546
851
  branch_delete_mode="force"
852
+ expected_branch_head="$(git -C "$repo_root" rev-parse --verify "refs/heads/${branch}^{commit}" 2>/dev/null || true)"
547
853
  elif [[ "$ONLY_DIRTY_WORKTREES" -eq 1 ]] && is_clean_worktree "$wt"; then
548
854
  remove_reason="clean-agent-worktree"
549
855
  fi
550
856
  elif [[ "$branch" == __agent_integrate_* || "$branch" == __source-probe-* ]]; then
551
857
  remove_reason="temporary-worktree"
858
+ elif [[ "$INCLUDE_CLEAN_LINKED_WORKTREES" -eq 1 ]] && is_clean_worktree "$wt"; then
859
+ remove_reason="clean-linked-worktree"
552
860
  fi
553
861
 
554
862
  if [[ -z "$remove_reason" ]]; then
@@ -571,31 +879,51 @@ process_entry() {
571
879
  return
572
880
  fi
573
881
 
574
- echo "[agent-worktree-prune] Removing worktree (${remove_reason}): ${wt}"
575
- run_cmd git -C "$repo_root" worktree remove "$wt" --force
576
- removed_worktrees=$((removed_worktrees + 1))
882
+ if [[ "$remove_reason" == closed-pr:* ]] && ! closed_pr_has_remote_recovery "$branch"; then
883
+ echo "[agent-worktree-prune] Skipping closed PR worktree without matching remote recovery branch: ${wt}" >&2
884
+ return
885
+ fi
886
+
887
+ if ! reserve_branch_slot "$branch"; then
888
+ echo "[agent-worktree-prune] Skipping branch limit worktree: ${branch} (${wt})"
889
+ return
890
+ fi
891
+
892
+ local remove_status=0
893
+ if remove_worktree_with_lock_guard "$wt" "$remove_reason" "$branch"; then
894
+ removed_worktrees=$((removed_worktrees + 1))
895
+ else
896
+ remove_status=$?
897
+ if [[ "$remove_status" -ne 10 ]]; then
898
+ exit "$remove_status"
899
+ fi
900
+ skipped_active=$((skipped_active + 1))
901
+ echo "[agent-worktree-prune] Skipping actively locked worktree: ${wt}"
902
+ return
903
+ fi
577
904
 
578
905
  if [[ -z "$branch" ]]; then
579
906
  return
580
907
  fi
581
908
 
582
909
  if git -C "$repo_root" show-ref --verify --quiet "refs/heads/${branch}" && ! branch_has_worktree "$branch"; then
583
- if [[ "$branch" == agent/* && "$DELETE_BRANCHES" -eq 1 ]]; then
584
- local delete_flag="-d"
585
- local deleted_label="merged"
586
- if [[ "$branch_delete_mode" == "force" ]]; then
587
- delete_flag="-D"
588
- deleted_label="merged PR"
910
+ if [[ ( "$branch" == agent/* || "$branch" == work/* ) && "$DELETE_BRANCHES" -eq 1 && "$remove_reason" != "stale-no-pr-worktree" ]]; then
911
+ local deleted_label="$branch_delete_label"
912
+ if [[ "$DELETE_REMOTE_BRANCHES" -eq 1 && "$delete_remote_branch" -eq 1 ]]; then
913
+ remote_delete_head="$(classified_merged_pr_head "$branch" || git -C "$repo_root" rev-parse --verify "refs/heads/${branch}^{commit}" 2>/dev/null || true)"
589
914
  fi
590
- if run_cmd git -C "$repo_root" branch "$delete_flag" "$branch" >/dev/null 2>&1; then
915
+ if delete_local_branch "$branch" "$branch_delete_mode" "$expected_branch_head" >/dev/null 2>&1; then
591
916
  removed_branches=$((removed_branches + 1))
592
917
  echo "[agent-worktree-prune] Deleted ${deleted_label} branch: ${branch}"
593
- if [[ "$DELETE_REMOTE_BRANCHES" -eq 1 ]]; then
594
- if git -C "$repo_root" ls-remote --exit-code --heads origin "$branch" >/dev/null 2>&1; then
595
- run_cmd git -C "$repo_root" push origin --delete "$branch" >/dev/null 2>&1 || true
918
+ if [[ -n "$remote_delete_head" ]]; then
919
+ if run_cmd git -C "$repo_root" push --force-with-lease="refs/heads/${branch}:${remote_delete_head}" origin --delete "$branch" >/dev/null 2>&1; then
596
920
  echo "[agent-worktree-prune] Deleted ${deleted_label} remote branch: ${branch}"
921
+ else
922
+ echo "[agent-worktree-prune] Preserved advanced remote branch: ${branch}" >&2
597
923
  fi
598
924
  fi
925
+ elif [[ "$branch_delete_mode" == "force" ]]; then
926
+ echo "[agent-worktree-prune] Preserved advanced local branch: ${branch}" >&2
599
927
  fi
600
928
  elif [[ "$branch" == __agent_integrate_* || "$branch" == __source-probe-* ]]; then
601
929
  run_cmd git -C "$repo_root" branch -D "$branch" >/dev/null 2>&1 || true
@@ -647,7 +975,16 @@ if [[ "$DELETE_BRANCHES" -eq 1 ]]; then
647
975
  fi
648
976
  continue
649
977
  fi
650
- if [[ "$branch" != agent/* ]]; then
978
+ if [[ "$branch" != agent/* && "$branch" != work/* ]]; then
979
+ continue
980
+ fi
981
+ if [[ "$branch" == agent/* || "$branch" == work/* ]] && should_preserve_open_pr_branch "$branch"; then
982
+ skipped_open_pr=$((skipped_open_pr + 1))
983
+ if [[ "$OPEN_PR_LOOKUP_UNAVAILABLE" -eq 1 ]]; then
984
+ echo "[agent-worktree-prune] Skipping open-PR branch because PR state is unavailable (fail closed): ${branch}"
985
+ else
986
+ echo "[agent-worktree-prune] Skipping open-PR branch: ${branch}"
987
+ fi
651
988
  continue
652
989
  fi
653
990
  if ! branch_idle_gate "$branch" "" "stale-merged-branch"; then
@@ -655,27 +992,65 @@ if [[ "$DELETE_BRANCHES" -eq 1 ]]; then
655
992
  fi
656
993
  merged_by_ancestor=0
657
994
  merged_by_pr=0
995
+ closed_by_pr=0
996
+ pr_base=""
997
+ remote_delete_head=""
998
+ expected_branch_head=""
999
+ if [[ "$PRUNE_STALE_LANES" -eq 1 ]]; then
1000
+ load_lane_pr_metadata || true
1001
+ pr_state="${LANE_PR_STATES[$branch]:-}"
1002
+ pr_base="${LANE_PR_BASES[$branch]:-}"
1003
+ if [[ "$pr_state" == "MERGED" ]]; then
1004
+ merged_by_pr=1
1005
+ expected_branch_head="${LANE_PR_HEAD_SHAS[$branch]:-}"
1006
+ elif [[ "$pr_state" == "CLOSED" ]]; then
1007
+ closed_by_pr=1
1008
+ expected_branch_head="${LANE_PR_HEAD_SHAS[$branch]:-}"
1009
+ fi
1010
+ fi
658
1011
  if git -C "$repo_root" merge-base --is-ancestor "$branch" "$BASE_BRANCH"; then
659
1012
  merged_by_ancestor=1
660
- elif branch_has_merged_pr "$branch"; then
1013
+ elif [[ "$PRUNE_STALE_LANES" -ne 1 ]] && branch_has_merged_pr "$branch"; then
661
1014
  merged_by_pr=1
1015
+ expected_branch_head="$(git -C "$repo_root" rev-parse --verify "refs/heads/${branch}^{commit}" 2>/dev/null || true)"
662
1016
  fi
663
- if [[ "$merged_by_ancestor" -eq 1 || "$merged_by_pr" -eq 1 ]]; then
664
- delete_flag="-d"
1017
+ if [[ "$merged_by_ancestor" -eq 1 || "$merged_by_pr" -eq 1 || "$closed_by_pr" -eq 1 ]]; then
1018
+ if ! reserve_branch_slot "$branch"; then
1019
+ echo "[agent-worktree-prune] Skipping branch limit: ${branch}"
1020
+ continue
1021
+ fi
1022
+ branch_delete_mode="safe"
665
1023
  deleted_label="merged"
666
- if [[ "$merged_by_pr" -eq 1 && "$merged_by_ancestor" -eq 0 ]]; then
667
- delete_flag="-D"
668
- deleted_label="merged PR"
1024
+ delete_remote_branch=1
1025
+ if [[ "$closed_by_pr" -eq 1 ]]; then
1026
+ branch_delete_mode="force"
1027
+ deleted_label="closed PR${pr_base:+ to ${pr_base}}"
1028
+ # Match attached-worktree cleanup: force-delete only after verifying
1029
+ # the exact remote PR head remains available for recovery.
1030
+ delete_remote_branch=0
1031
+ elif [[ "$merged_by_pr" -eq 1 && "$merged_by_ancestor" -eq 0 ]]; then
1032
+ branch_delete_mode="force"
1033
+ deleted_label="merged PR${pr_base:+ to ${pr_base}}"
1034
+ fi
1035
+ if [[ "$closed_by_pr" -eq 1 ]] && ! closed_pr_has_remote_recovery "$branch"; then
1036
+ echo "[agent-worktree-prune] Skipping closed PR branch without matching remote recovery branch: ${branch}" >&2
1037
+ continue
1038
+ fi
1039
+ if [[ "$DELETE_REMOTE_BRANCHES" -eq 1 && "$delete_remote_branch" -eq 1 ]]; then
1040
+ remote_delete_head="$(classified_merged_pr_head "$branch" || git -C "$repo_root" rev-parse --verify "refs/heads/${branch}^{commit}" 2>/dev/null || true)"
669
1041
  fi
670
- if run_cmd git -C "$repo_root" branch "$delete_flag" "$branch" >/dev/null 2>&1; then
1042
+ if delete_local_branch "$branch" "$branch_delete_mode" "$expected_branch_head" >/dev/null 2>&1; then
671
1043
  removed_branches=$((removed_branches + 1))
672
1044
  echo "[agent-worktree-prune] Deleted stale ${deleted_label} branch: ${branch}"
673
- if [[ "$DELETE_REMOTE_BRANCHES" -eq 1 ]]; then
674
- if git -C "$repo_root" ls-remote --exit-code --heads origin "$branch" >/dev/null 2>&1; then
675
- run_cmd git -C "$repo_root" push origin --delete "$branch" >/dev/null 2>&1 || true
1045
+ if [[ -n "$remote_delete_head" ]]; then
1046
+ if run_cmd git -C "$repo_root" push --force-with-lease="refs/heads/${branch}:${remote_delete_head}" origin --delete "$branch" >/dev/null 2>&1; then
676
1047
  echo "[agent-worktree-prune] Deleted stale ${deleted_label} remote branch: ${branch}"
1048
+ else
1049
+ echo "[agent-worktree-prune] Preserved advanced remote branch: ${branch}" >&2
677
1050
  fi
678
1051
  fi
1052
+ elif [[ "$branch_delete_mode" == "force" ]]; then
1053
+ echo "[agent-worktree-prune] Preserved advanced local branch: ${branch}" >&2
679
1054
  fi
680
1055
  fi
681
1056
  done < <(git -C "$repo_root" for-each-ref --format='%(refname:short)' refs/heads)
@@ -683,7 +1058,7 @@ fi
683
1058
 
684
1059
  run_cmd git -C "$repo_root" worktree prune
685
1060
 
686
- echo "[agent-worktree-prune] Summary: base=${BASE_BRANCH}, idle_minutes=${IDLE_MINUTES}, removed_worktrees=${removed_worktrees}, removed_branches=${removed_branches}, skipped_active=${skipped_active}, skipped_dirty=${skipped_dirty}, skipped_recent=${skipped_recent}"
1061
+ echo "[agent-worktree-prune] Summary: base=${BASE_BRANCH}, idle_minutes=${IDLE_MINUTES}, removed_worktrees=${removed_worktrees}, removed_branches=${removed_branches}, skipped_active=${skipped_active}, skipped_dirty=${skipped_dirty}, skipped_open_pr=${skipped_open_pr}, skipped_recent=${skipped_recent}, skipped_limited=${skipped_limited}"
687
1062
  if [[ "$relocated_foreign" -gt 0 || "$skipped_foreign" -gt 0 ]]; then
688
1063
  echo "[agent-worktree-prune] Foreign routing: relocated=${relocated_foreign}, skipped=${skipped_foreign}"
689
1064
  fi