@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
@@ -1,6 +1,10 @@
1
1
  #!/usr/bin/env bash
2
2
  set -euo pipefail
3
3
 
4
+ _PRUNE_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
5
+ # shellcheck source=lib/guardex-base-branch.sh
6
+ source "${_PRUNE_SCRIPT_DIR}/lib/guardex-base-branch.sh"
7
+
4
8
  BASE_BRANCH="${GUARDEX_BASE_BRANCH:-}"
5
9
  BASE_BRANCH_EXPLICIT=0
6
10
  DRY_RUN=0
@@ -8,7 +12,13 @@ FORCE_DIRTY=0
8
12
  DELETE_BRANCHES=0
9
13
  DELETE_REMOTE_BRANCHES=0
10
14
  ONLY_DIRTY_WORKTREES=0
15
+ # Set by another lane's post-merge sweep: a clean worktree whose branch still
16
+ # has commits not on the base is someone's in-progress lane, not leftovers.
17
+ KEEP_CLEAN_UNMERGED=0
11
18
  INCLUDE_CLEAN_LINKED_WORKTREES=0
19
+ # Linked worktrees outside the managed agent dirs, but ONLY merged agent lanes
20
+ # (never clean-but-unmerged, detached or non-agent ones) — safe for the bot.
21
+ INCLUDE_MERGED_LINKED_WORKTREES=0
12
22
  INCLUDE_PR_MERGED=0
13
23
  PRESERVE_OPEN_PRS=0
14
24
  PRUNE_STALE_LANES=0
@@ -22,8 +32,26 @@ NOW_EPOCH=0
22
32
  GH_BIN="${GUARDEX_GH_BIN:-gh}"
23
33
  PR_MERGED_LOOKUP_DISABLED=0
24
34
  PR_MERGED_LOOKUP_LOADED=0
35
+ PR_MERGED_LOOKUP_TRUNCATED=0
36
+ MERGED_PR_LOOKUP_LIMIT="${GUARDEX_MERGED_PR_LOOKUP_LIMIT:-500}"
25
37
  declare -A MERGED_PR_BRANCHES=()
38
+ # Per-branch merged-PR fallback cache used when the bulk lookup was truncated.
39
+ declare -A MERGED_PR_BRANCH_FALLBACK_CACHE=()
40
+ # `git worktree list --porcelain` was re-run for EVERY branch (104 times in one
41
+ # traced sweep) even though the answer only changes when this script itself
42
+ # removes a worktree. Same for `rev-parse --verify refs/heads/<b>`: one branch
43
+ # was resolved up to 88 times. Both are memoized, and both caches are dropped
44
+ # at the points where this script mutates the thing they describe — a stale
45
+ # "branch still has a worktree" would keep a branch that became deletable, and
46
+ # a stale tip would be used to pick a remote ref to delete.
47
+ WORKTREE_BRANCHES_LOADED=0
48
+ declare -A WORKTREE_BRANCHES=()
49
+ declare -A BRANCH_TIP_CACHE=()
26
50
  OPEN_PR_LOOKUP_UNAVAILABLE=0
51
+ OPEN_PR_LOOKUP_LOADED=0
52
+ OPEN_PR_LOOKUP_TRUNCATED=0
53
+ OPEN_PR_LOOKUP_LIMIT="${GUARDEX_OPEN_PR_LOOKUP_LIMIT:-200}"
54
+ declare -A OPEN_PR_BRANCHES=()
27
55
  LANE_PR_LOOKUP_LOADED=0
28
56
  LANE_PR_LOOKUP_UNAVAILABLE=0
29
57
  declare -A LANE_PR_STATES=()
@@ -36,6 +64,20 @@ WORKTREE_ROOT_RELS=(
36
64
  ".omc/.tmp-worktrees"
37
65
  )
38
66
 
67
+ run_lifecycle_hook() {
68
+ local event="$1" worktree="$2" branch="$3"
69
+ local args=(worktree hook "$event" --source "$repo_root" --worktree "$worktree")
70
+ [[ -z "$branch" ]] || args+=(--branch "$branch")
71
+ if [[ -n "${GUARDEX_CLI_ENTRY:-}" ]]; then
72
+ "${GUARDEX_NODE_BIN:-node}" "$GUARDEX_CLI_ENTRY" "${args[@]}"
73
+ elif command -v gx >/dev/null 2>&1; then
74
+ gx "${args[@]}"
75
+ else
76
+ echo "[agent-worktree-prune] Lifecycle runner unavailable; preserving worktree." >&2
77
+ return 1
78
+ fi
79
+ }
80
+
39
81
  if [[ -n "$BASE_BRANCH" ]]; then
40
82
  BASE_BRANCH_EXPLICIT=1
41
83
  fi
@@ -67,10 +109,18 @@ while [[ $# -gt 0 ]]; do
67
109
  ONLY_DIRTY_WORKTREES=1
68
110
  shift
69
111
  ;;
112
+ --keep-clean-unmerged)
113
+ KEEP_CLEAN_UNMERGED=1
114
+ shift
115
+ ;;
70
116
  --include-clean-linked-worktrees)
71
117
  INCLUDE_CLEAN_LINKED_WORKTREES=1
72
118
  shift
73
119
  ;;
120
+ --include-merged-linked-worktrees)
121
+ INCLUDE_MERGED_LINKED_WORKTREES=1
122
+ shift
123
+ ;;
74
124
  --include-pr-merged)
75
125
  INCLUDE_PR_MERGED=1
76
126
  shift
@@ -98,7 +148,7 @@ while [[ $# -gt 0 ]]; do
98
148
  ;;
99
149
  *)
100
150
  echo "[agent-worktree-prune] Unknown argument: $1" >&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
151
+ echo "Usage: $0 [--base <branch>] [--dry-run] [--force-dirty] [--delete-branches] [--delete-remote-branches] [--only-dirty-worktrees] [--keep-clean-unmerged] [--include-clean-linked-worktrees] [--include-merged-linked-worktrees] [--include-pr-merged] [--preserve-open-prs] [--prune-stale-lanes] [--branch <agent/...>] [--idle-minutes <minutes>] [--max-branches <count>]" >&2
102
152
  exit 1
103
153
  ;;
104
154
  esac
@@ -159,32 +209,6 @@ is_temporary_worktree_path() {
159
209
  [[ "$name" == __agent_integrate-* || "$name" == __source-probe-* ]]
160
210
  }
161
211
 
162
- resolve_base_branch() {
163
- local configured=""
164
- local current=""
165
-
166
- configured="$(git -C "$repo_root" config --get multiagent.baseBranch || true)"
167
- if [[ -n "$configured" ]] && git -C "$repo_root" show-ref --verify --quiet "refs/heads/${configured}"; then
168
- printf '%s' "$configured"
169
- return 0
170
- fi
171
-
172
- current="$(git -C "$repo_root" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
173
- if [[ -n "$current" && "$current" != "HEAD" ]] && git -C "$repo_root" show-ref --verify --quiet "refs/heads/${current}"; then
174
- printf '%s' "$current"
175
- return 0
176
- fi
177
-
178
- for fallback in main dev; do
179
- if git -C "$repo_root" show-ref --verify --quiet "refs/heads/${fallback}"; then
180
- printf '%s' "$fallback"
181
- return 0
182
- fi
183
- done
184
-
185
- printf '%s' ""
186
- }
187
-
188
212
  load_merged_pr_branches() {
189
213
  if [[ "$INCLUDE_PR_MERGED" -ne 1 ]]; then
190
214
  return 1
@@ -193,6 +217,9 @@ load_merged_pr_branches() {
193
217
  return 1
194
218
  fi
195
219
  if [[ "$PR_MERGED_LOOKUP_LOADED" -eq 1 ]]; then
220
+ # Loaded but truncated is still "loaded" for the bulk-lookup; callers that
221
+ # need a definitive answer for a specific branch use the per-branch fallback
222
+ # via branch_has_merged_pr_checked().
196
223
  return 0
197
224
  fi
198
225
  if ! command -v "$GH_BIN" >/dev/null 2>&1; then
@@ -200,27 +227,156 @@ load_merged_pr_branches() {
200
227
  return 1
201
228
  fi
202
229
 
230
+ # Name -> space-separated merged PR head SHAs. The SHA is what makes the
231
+ # name match safe: a reused branch name, or commits pushed after the PR
232
+ # merged, must not read as "merged" (see branch_has_merged_pr).
233
+ #
234
+ # Limit is configurable (GUARDEX_MERGED_PR_LOOKUP_LIMIT, default 500).
235
+ # When the result count hits the limit the lookup may be incomplete, so we
236
+ # set PR_MERGED_LOOKUP_TRUNCATED=1 and fall back to a per-branch probe in
237
+ # branch_has_merged_pr() — fail closed: a branch not in the truncated set is
238
+ # only treated as "not merged" after the per-branch check confirms it.
203
239
  local merged_branches=""
204
240
  merged_branches="$(
205
- "$GH_BIN" pr list --state merged --base "$BASE_BRANCH" --limit 200 --json headRefName --jq '.[].headRefName' 2>/dev/null || true
241
+ "$GH_BIN" pr list --state merged --base "$BASE_BRANCH" \
242
+ --limit "$MERGED_PR_LOOKUP_LIMIT" \
243
+ --json headRefName,headRefOid \
244
+ --jq '.[] | "\(.headRefName) \(.headRefOid)"' 2>/dev/null || true
206
245
  )"
246
+ local row_count=0
207
247
  if [[ -n "$merged_branches" ]]; then
208
- while IFS= read -r merged_branch; do
209
- [[ -z "$merged_branch" ]] && continue
210
- MERGED_PR_BRANCHES["$merged_branch"]=1
248
+ local merged_branch merged_oid
249
+ while IFS=' ' read -r merged_branch merged_oid; do
250
+ [[ -z "$merged_branch" || -z "$merged_oid" ]] && continue
251
+ MERGED_PR_BRANCHES["$merged_branch"]="${MERGED_PR_BRANCHES[$merged_branch]:-} ${merged_oid}"
252
+ row_count=$((row_count + 1))
211
253
  done <<< "$merged_branches"
212
254
  fi
255
+ if (( row_count >= MERGED_PR_LOOKUP_LIMIT )); then
256
+ PR_MERGED_LOOKUP_TRUNCATED=1
257
+ fi
213
258
  PR_MERGED_LOOKUP_LOADED=1
214
259
  return 0
215
260
  }
216
261
 
262
+ # Per-branch fallback for merged-PR detection, used when the bulk lookup was
263
+ # truncated (PR_MERGED_LOOKUP_TRUNCATED=1). Caches each result so a branch
264
+ # is never queried twice in one run.
265
+ #
266
+ # Returns 0 when the branch has a confirmed merged PR; 1 otherwise.
267
+ # Never fail-open: a gh failure is treated as "not confirmed merged".
268
+ _load_merged_pr_branch_fallback() {
269
+ local branch="$1"
270
+ if [[ -n "${MERGED_PR_BRANCH_FALLBACK_CACHE[$branch]+set}" ]]; then
271
+ [[ "${MERGED_PR_BRANCH_FALLBACK_CACHE[$branch]}" == "1" ]]
272
+ return
273
+ fi
274
+ local result=""
275
+ result="$(
276
+ "$GH_BIN" pr list --state merged --head "$branch" --base "$BASE_BRANCH" \
277
+ --limit 5 --json headRefName,headRefOid \
278
+ --jq '.[] | "\(.headRefName) \(.headRefOid)"' 2>/dev/null || true
279
+ )"
280
+ if [[ -n "$result" ]]; then
281
+ local fb_branch fb_oid
282
+ while IFS=' ' read -r fb_branch fb_oid; do
283
+ [[ -z "$fb_branch" || -z "$fb_oid" ]] && continue
284
+ MERGED_PR_BRANCHES["$fb_branch"]="${MERGED_PR_BRANCHES[$fb_branch]:-} ${fb_oid}"
285
+ done <<< "$result"
286
+ MERGED_PR_BRANCH_FALLBACK_CACHE["$branch"]="1"
287
+ return 0
288
+ fi
289
+ MERGED_PR_BRANCH_FALLBACK_CACHE["$branch"]="0"
290
+ return 1
291
+ }
292
+
293
+ # One `gh pr list` for every open PR instead of one per branch. The merged
294
+ # lookup above has always worked this way; the open-PR probe did not, so an
295
+ # unattended cleanup paid a forge round-trip per candidate lane — ~30 s on a
296
+ # repo with a couple of dozen agent worktrees, which is time a `git pull` spent
297
+ # waiting because post-merge cleanup runs inline.
298
+ #
299
+ # The set is only trusted when it is COMPLETE. `gh pr list` silently caps at
300
+ # --limit, and a truncated set would read as "this branch has no open PR" for
301
+ # every lane past the cap — i.e. it would DELETE lanes that still have a PR.
302
+ # The per-branch probe cannot make that mistake, so on truncation (or any
303
+ # failure) the caller falls back to it and the fail-closed contract holds.
304
+ load_open_pr_lookup() {
305
+ if [[ "$OPEN_PR_LOOKUP_LOADED" -eq 1 ]]; then
306
+ return 0
307
+ fi
308
+ # A truncated or failed bulk list stays unusable for the rest of this run;
309
+ # without this, every caller re-ran the full `gh pr list` (one per worktree).
310
+ if [[ "$OPEN_PR_LOOKUP_TRUNCATED" -eq 1 || "${OPEN_PR_LOOKUP_FAILED:-0}" -eq 1 ]]; then
311
+ return 1
312
+ fi
313
+ if ! command -v "$GH_BIN" >/dev/null 2>&1; then
314
+ return 1
315
+ fi
316
+ local open_branches=""
317
+ if ! open_branches="$(
318
+ "$GH_BIN" pr list --state open --limit "$OPEN_PR_LOOKUP_LIMIT" --json headRefName --jq '.[].headRefName' 2>/dev/null
319
+ )"; then
320
+ OPEN_PR_LOOKUP_FAILED=1
321
+ return 1
322
+ fi
323
+ local count=0
324
+ if [[ -n "$open_branches" ]]; then
325
+ while IFS= read -r open_branch; do
326
+ [[ -z "$open_branch" ]] && continue
327
+ OPEN_PR_BRANCHES["$open_branch"]=1
328
+ count=$((count + 1))
329
+ done <<< "$open_branches"
330
+ fi
331
+ if (( count >= OPEN_PR_LOOKUP_LIMIT )); then
332
+ OPEN_PR_LOOKUP_TRUNCATED=1
333
+ return 1
334
+ fi
335
+ OPEN_PR_LOOKUP_LOADED=1
336
+ return 0
337
+ }
338
+
217
339
  branch_has_merged_pr() {
218
340
  local branch="$1"
219
341
  if [[ "$INCLUDE_PR_MERGED" -ne 1 ]]; then
220
342
  return 1
221
343
  fi
222
344
  load_merged_pr_branches || return 1
223
- [[ -n "${MERGED_PR_BRANCHES[$branch]:-}" ]]
345
+ local merged_oids="${MERGED_PR_BRANCHES[$branch]:-}"
346
+ # When the bulk lookup was truncated and this branch was not in the result,
347
+ # fall back to a per-branch query rather than treating "not in truncated set"
348
+ # as "not merged" (which would be fail-open and potentially delete live work).
349
+ if [[ -z "$merged_oids" && "$PR_MERGED_LOOKUP_TRUNCATED" -eq 1 ]]; then
350
+ _load_merged_pr_branch_fallback "$branch" || return 1
351
+ merged_oids="${MERGED_PR_BRANCHES[$branch]:-}"
352
+ fi
353
+ [[ -n "$merged_oids" ]] || return 1
354
+ # Merged only if every tip we can see — the local branch AND origin's —
355
+ # IS a merged PR's head or is contained in one. Anything newer (commits
356
+ # pushed after the merge, locally or to origin; a reused name) is unmerged
357
+ # work — fail closed. A PR head we do not have locally cannot prove
358
+ # containment, so only the exact-SHA match applies then.
359
+ local tips=() ref resolved
360
+ for ref in "refs/heads/${branch}" "refs/remotes/origin/${branch}"; do
361
+ resolved="$(git -C "$repo_root" rev-parse --verify --quiet "${ref}^{commit}" 2>/dev/null || true)"
362
+ [[ -n "$resolved" ]] && tips+=("$resolved")
363
+ done
364
+ [[ ${#tips[@]} -gt 0 ]] || return 1
365
+ local tip oid contained
366
+ local oids_arr=()
367
+ read -ra oids_arr <<< "${merged_oids//$'\n'/ }"
368
+ for tip in "${tips[@]}"; do
369
+ contained=0
370
+ for oid in "${oids_arr[@]}"; do
371
+ [[ "$oid" =~ ^[0-9a-f]{40}$ ]] || continue
372
+ if [[ "$tip" == "$oid" ]] || git -C "$repo_root" merge-base --is-ancestor "$tip" "$oid" >/dev/null 2>&1; then
373
+ contained=1
374
+ break
375
+ fi
376
+ done
377
+ [[ "$contained" -eq 1 ]] || return 1
378
+ done
379
+ return 0
224
380
  }
225
381
 
226
382
  load_lane_pr_metadata() {
@@ -301,6 +457,27 @@ closed_pr_has_remote_recovery() {
301
457
  [[ "$remote_head" == "$classified_head" ]]
302
458
  }
303
459
 
460
+ # Open-PR state for a non-agent linked worktree's branch, independent of
461
+ # --preserve-open-prs: 0 = has an open PR, 1 = none, 2 = unknown (fail closed).
462
+ # Uses the bulk list when complete, else one cached per-branch probe.
463
+ declare -A LINKED_OPEN_PR_CACHE=()
464
+ linked_branch_open_pr_state() {
465
+ local branch="$1" cached="${LINKED_OPEN_PR_CACHE[$1]:-}" head=""
466
+ if [[ -n "$cached" ]]; then
467
+ return "$cached"
468
+ fi
469
+ local state=2
470
+ if ! command -v "$GH_BIN" >/dev/null 2>&1; then
471
+ state=2
472
+ elif load_open_pr_lookup; then
473
+ if [[ -n "${OPEN_PR_BRANCHES[$branch]:-}" ]]; then state=0; else state=1; fi
474
+ elif head="$("$GH_BIN" pr list --state open --head "$branch" --limit 1 --json headRefName --jq '.[0].headRefName // ""' 2>/dev/null)"; then
475
+ if [[ -n "$head" ]]; then state=0; else state=1; fi
476
+ fi
477
+ LINKED_OPEN_PR_CACHE["$branch"]="$state"
478
+ return "$state"
479
+ }
480
+
304
481
  should_preserve_open_pr_branch() {
305
482
  local branch="$1"
306
483
  local open_branch=""
@@ -322,6 +499,13 @@ should_preserve_open_pr_branch() {
322
499
  OPEN_PR_LOOKUP_UNAVAILABLE=1
323
500
  return 0
324
501
  fi
502
+ # One batched list answers every lane. Only when it is unusable — gh failed,
503
+ # or the list hit --limit and may be missing branches — do we fall through to
504
+ # the per-branch probe below.
505
+ if load_open_pr_lookup; then
506
+ [[ -n "${OPEN_PR_BRANCHES[$branch]:-}" ]]
507
+ return
508
+ fi
325
509
  if ! open_branch="$(
326
510
  "$GH_BIN" pr list --state open --head "$branch" --limit 1 --json headRefName --jq '.[0].headRefName // ""' 2>/dev/null
327
511
  )"; then
@@ -379,7 +563,7 @@ if [[ -n "$NOW_EPOCH_RAW" && ! "$NOW_EPOCH_RAW" =~ ^[0-9]+$ ]]; then
379
563
  fi
380
564
 
381
565
  if [[ "$BASE_BRANCH_EXPLICIT" -eq 0 ]]; then
382
- BASE_BRANCH="$(resolve_base_branch)"
566
+ BASE_BRANCH="$(resolve_base_branch "$repo_root")"
383
567
  fi
384
568
 
385
569
  if [[ -z "$BASE_BRANCH" ]]; then
@@ -419,9 +603,48 @@ delete_local_branch() {
419
603
  run_cmd git -C "$repo_root" branch -d "$branch"
420
604
  }
421
605
 
606
+ load_worktree_branches() {
607
+ if [[ "$WORKTREE_BRANCHES_LOADED" -eq 1 ]]; then
608
+ return 0
609
+ fi
610
+ WORKTREE_BRANCHES=()
611
+ local line=""
612
+ while IFS= read -r line; do
613
+ [[ "$line" == branch\ refs/heads/* ]] || continue
614
+ WORKTREE_BRANCHES["${line#branch refs/heads/}"]=1
615
+ done < <(git -C "$repo_root" worktree list --porcelain 2>/dev/null || true)
616
+ WORKTREE_BRANCHES_LOADED=1
617
+ return 0
618
+ }
619
+
620
+ invalidate_worktree_branches() {
621
+ WORKTREE_BRANCHES_LOADED=0
622
+ }
623
+
422
624
  branch_has_worktree() {
423
625
  local branch="$1"
424
- git -C "$repo_root" worktree list --porcelain | grep -q "^branch refs/heads/${branch}$"
626
+ load_worktree_branches
627
+ [[ -n "${WORKTREE_BRANCHES[$branch]:-}" ]]
628
+ }
629
+
630
+ # The tip of a local branch, memoized. Empty (and cached as empty) when the
631
+ # branch does not exist, which is what the callers' `|| true` already treated
632
+ # as "no tip".
633
+ branch_tip() {
634
+ local branch="$1"
635
+ if [[ -n "${BRANCH_TIP_CACHE[$branch]+set}" ]]; then
636
+ printf '%s' "${BRANCH_TIP_CACHE[$branch]}"
637
+ return 0
638
+ fi
639
+ local tip=""
640
+ tip="$(git -C "$repo_root" rev-parse --verify "refs/heads/${branch}^{commit}" 2>/dev/null || true)"
641
+ BRANCH_TIP_CACHE["$branch"]="$tip"
642
+ printf '%s' "$tip"
643
+ return 0
644
+ }
645
+
646
+ invalidate_branch_tip() {
647
+ unset "BRANCH_TIP_CACHE[$1]" 2>/dev/null || true
425
648
  }
426
649
 
427
650
  # Globs treated as agent state, not real work. Worktrees whose only "dirty"
@@ -459,6 +682,162 @@ is_clean_worktree() {
459
682
  && [[ -z "$(git -C "$wt" ls-files --others --exclude-standard -- . "${STATE_EXCLUDE_PATHSPEC_ARGS[@]}")" ]]
460
683
  }
461
684
 
685
+ # Directories / patterns whose .gitignore-excluded presence is safe to discard.
686
+ # Addable via GUARDEX_PRUNE_DISPOSABLE_IGNORED (space-separated, appended).
687
+ # Matched against the FIRST path component only: generic names (build, out,
688
+ # target, dist, ...) also name real directories that can hold secrets deeper in
689
+ # a tree (config/out/secrets.json), so they are trusted only at the top.
690
+ PRUNE_DISPOSABLE_IGNORED_DEFAULT=(
691
+ node_modules dist dist-server build out .next .nuxt .turbo .cache
692
+ .parcel-cache .vite coverage target .venv venv __pycache__ .pytest_cache
693
+ .mypy_cache .codegraph .omc .omx
694
+ )
695
+ # Matched at ANY depth: names only build tools produce, so a monorepo's
696
+ # apps/web/.next or packages/x/node_modules is disposable too.
697
+ PRUNE_DISPOSABLE_IGNORED_ANY_DEPTH=(
698
+ node_modules .next .nuxt .turbo .parcel-cache .vite dist-server
699
+ __pycache__ .pytest_cache .mypy_cache
700
+ )
701
+ # Generic build-output names that are disposable below the top level too, but
702
+ # ONLY directly inside a directory with a tracked package.json — a workspace
703
+ # package's own build output (web/dist, packages/cli/dist). Field 2026-11-18: a
704
+ # pnpm workspace kept 35 merged worktrees forever because web/dist/ counted as
705
+ # precious, and the disk filled up. Only names that mean build output and
706
+ # nothing else: `out` and `build` are left out on purpose, because a package
707
+ # can keep exports or script results there (api/out/db-snapshot.json), and
708
+ # config/out/secrets.json stays precious either way (no package.json beside it).
709
+ PRUNE_DISPOSABLE_PACKAGE_OUTPUT=(dist coverage .cache)
710
+ # A top-level .vercel/ is disposable only while it holds nothing but what the
711
+ # Vercel CLI regenerates; anything else in it (an env file pulled with
712
+ # --filename .vercel/...) keeps the worktree.
713
+ PRUNE_VERCEL_REGENERABLE=(output project.json README.txt cache)
714
+ PRUNE_DISPOSABLE_IGNORED=("${PRUNE_DISPOSABLE_IGNORED_DEFAULT[@]}")
715
+ if [[ -n "${GUARDEX_PRUNE_DISPOSABLE_IGNORED:-}" ]]; then
716
+ read -ra _extra_disposable <<< "$GUARDEX_PRUNE_DISPOSABLE_IGNORED"
717
+ PRUNE_DISPOSABLE_IGNORED+=("${_extra_disposable[@]}")
718
+ fi
719
+
720
+ # Returns 0 and prints offending paths (up to 5) when the worktree has
721
+ # .gitignore-excluded files that are NOT under a disposable directory and are
722
+ # NOT matched by the existing STATE_EXCLUDE_PATHSPEC globs or *.log/.DS_Store.
723
+ # Returns 1 when all ignored content is disposable.
724
+ worktree_has_precious_ignored_files() {
725
+ local wt="$1"
726
+ local ignored_paths=""
727
+ ignored_paths="$(
728
+ git -C "$wt" ls-files --others --ignored --exclude-standard \
729
+ --directory --no-empty-directory 2>/dev/null || true
730
+ )"
731
+ [[ -n "$ignored_paths" ]] || return 1
732
+
733
+ local -a offenders=()
734
+ local entry clean
735
+ while IFS= read -r entry; do
736
+ [[ -n "$entry" ]] || continue
737
+ # Strip trailing slash from directory entries.
738
+ clean="${entry%/}"
739
+
740
+ # Disposable dirs: any listed name as the first component, or a
741
+ # build-tool-only name at any depth (apps/web/.next).
742
+ local disposable=0
743
+ local d part
744
+ local -a parts=()
745
+ IFS='/' read -ra parts <<< "$clean"
746
+ for d in "${PRUNE_DISPOSABLE_IGNORED[@]}"; do
747
+ if [[ "${parts[0]}" == "$d" ]]; then
748
+ disposable=1
749
+ break
750
+ fi
751
+ done
752
+ if [[ "$disposable" -eq 0 ]]; then
753
+ for part in "${parts[@]}"; do
754
+ for d in "${PRUNE_DISPOSABLE_IGNORED_ANY_DEPTH[@]}"; do
755
+ if [[ "$part" == "$d" ]]; then
756
+ disposable=1
757
+ break 2
758
+ fi
759
+ done
760
+ done
761
+ fi
762
+ if [[ "$disposable" -eq 0 && "$clean" == ".vercel" && -d "${wt}/.vercel" ]]; then
763
+ disposable=1
764
+ local vercel_entry vercel_ok
765
+ while IFS= read -r vercel_entry; do
766
+ [[ -n "$vercel_entry" ]] || continue
767
+ vercel_ok=0
768
+ for d in "${PRUNE_VERCEL_REGENERABLE[@]}"; do
769
+ [[ "$vercel_entry" == "$d" ]] && { vercel_ok=1; break; }
770
+ done
771
+ [[ "$vercel_ok" -eq 1 ]] || { disposable=0; break; }
772
+ done < <(ls -A "${wt}/.vercel" 2>/dev/null)
773
+ fi
774
+ if [[ "$disposable" -eq 0 && "${#parts[@]}" -ge 2 ]]; then
775
+ # A package's own build output: <pkg>/dist where <pkg>/package.json is tracked.
776
+ local i parent
777
+ for (( i = 1; i < ${#parts[@]}; i++ )); do
778
+ for d in "${PRUNE_DISPOSABLE_PACKAGE_OUTPUT[@]}"; do
779
+ if [[ "${parts[$i]}" == "$d" ]]; then
780
+ parent="$(IFS=/; printf '%s' "${parts[*]:0:$i}")"
781
+ if git -C "$wt" ls-files --error-unmatch -- "${parent}/package.json" >/dev/null 2>&1; then
782
+ disposable=1
783
+ break 2
784
+ fi
785
+ fi
786
+ done
787
+ done
788
+ fi
789
+ [[ "$disposable" -eq 1 ]] && continue
790
+
791
+ # Check generated files: logs, .DS_Store, TypeScript build info, Next's
792
+ # generated type stub.
793
+ case "${clean##*/}" in
794
+ *.log|.DS_Store|*.tsbuildinfo|next-env.d.ts) continue ;;
795
+ esac
796
+
797
+ # Check the existing STATE_EXCLUDE_PATHSPEC globs (simple prefix match).
798
+ local globs_raw="${WORKTREE_STATE_EXCLUDE_GLOBS_RAW:-}"
799
+ if [[ -n "$globs_raw" ]]; then
800
+ local glob matched_state=0
801
+ local -a globs_arr=()
802
+ IFS=':' read -ra globs_arr <<< "$globs_raw"
803
+ for glob in "${globs_arr[@]}"; do
804
+ [[ -z "$glob" ]] && continue
805
+ # Strip leading ** or ./ for a simple prefix match.
806
+ local bare_glob="${glob#\*\*/}"
807
+ bare_glob="${bare_glob#./}"
808
+ if [[ "$clean" == $bare_glob || "$clean" == ${bare_glob%%\**}* ]]; then
809
+ matched_state=1
810
+ break
811
+ fi
812
+ done
813
+ [[ "$matched_state" -eq 1 ]] && continue
814
+ fi
815
+
816
+ offenders+=("$entry")
817
+ [[ "${#offenders[@]}" -ge 5 ]] && break
818
+ done <<< "$ignored_paths"
819
+
820
+ if [[ "${#offenders[@]}" -gt 0 ]]; then
821
+ local o
822
+ for o in "${offenders[@]}"; do
823
+ printf '%s\n' "$o"
824
+ done
825
+ return 0
826
+ fi
827
+ return 1
828
+ }
829
+
830
+ # --force-dirty is an explicit operator override ("Allow cleanup of dirty
831
+ # worktrees"); no automated caller passes it. It therefore applies to every
832
+ # removal reason, but the uncommitted files it is about to destroy are always
833
+ # printed first (warn_force_dirty_removal) so the loss is never silent.
834
+ # It does NOT override the precious-ignored-files guard below.
835
+ warn_force_dirty_removal() {
836
+ local wt="$1" reason="$2"
837
+ echo "[agent-worktree-prune] WARNING: --force-dirty removes a dirty worktree (${reason}); these uncommitted changes will be lost: ${wt}" >&2
838
+ summarize_worktree_dirt "$wt" >&2
839
+ }
840
+
462
841
  # Returns a short, human-readable summary of why a worktree is considered dirty:
463
842
  # up to 3 modified-tracked paths + up to 3 untracked paths + a "(+N more)" tail.
464
843
  # Used to surface actionable context next to "Skipping dirty worktree" log lines
@@ -466,12 +845,12 @@ is_clean_worktree() {
466
845
  summarize_worktree_dirt() {
467
846
  local wt="$1"
468
847
  local modified_paths untracked_paths
469
- modified_paths="$(git -C "$wt" diff --name-only --diff-filter=AMDR -- . "${STATE_EXCLUDE_PATHSPEC_ARGS[@]}" 2>/dev/null | head -3)"
848
+ modified_paths="$(git -C "$wt" diff --name-only --diff-filter=AMDR -- . "${STATE_EXCLUDE_PATHSPEC_ARGS[@]}" 2>/dev/null | head -3 || true)"
470
849
  local modified_count
471
- modified_count="$(git -C "$wt" diff --name-only --diff-filter=AMDR -- . "${STATE_EXCLUDE_PATHSPEC_ARGS[@]}" 2>/dev/null | wc -l | tr -d ' ')"
472
- untracked_paths="$(git -C "$wt" ls-files --others --exclude-standard -- . "${STATE_EXCLUDE_PATHSPEC_ARGS[@]}" 2>/dev/null | head -3)"
850
+ modified_count="$(git -C "$wt" diff --name-only --diff-filter=AMDR -- . "${STATE_EXCLUDE_PATHSPEC_ARGS[@]}" 2>/dev/null | wc -l | tr -d ' ' || true)"
851
+ untracked_paths="$(git -C "$wt" ls-files --others --exclude-standard -- . "${STATE_EXCLUDE_PATHSPEC_ARGS[@]}" 2>/dev/null | head -3 || true)"
473
852
  local untracked_count
474
- untracked_count="$(git -C "$wt" ls-files --others --exclude-standard -- . "${STATE_EXCLUDE_PATHSPEC_ARGS[@]}" 2>/dev/null | wc -l | tr -d ' ')"
853
+ untracked_count="$(git -C "$wt" ls-files --others --exclude-standard -- . "${STATE_EXCLUDE_PATHSPEC_ARGS[@]}" 2>/dev/null | wc -l | tr -d ' ' || true)"
475
854
 
476
855
  if [[ -n "$modified_paths" ]]; then
477
856
  while IFS= read -r p; do
@@ -552,6 +931,34 @@ read_branch_activity_epoch() {
552
931
  fi
553
932
  fi
554
933
  fi
934
+
935
+ # Extend the activity epoch with the newest mtime of any non-disposable file
936
+ # in the worktree. A file actively written — e.g. an IDE scratch file, a
937
+ # spec draft, a half-finished shell script — has no git record but IS a signal
938
+ # that someone is working in this worktree. Using `find -printf '%T@'` (GNU)
939
+ # gives us the whole tree in one pass; on platforms without -printf the block
940
+ # produces nothing and we fall through to the git-only epoch (safe degradation).
941
+ #
942
+ # Exclude .git and the PRUNE_DISPOSABLE_IGNORED dirs (node_modules, dist, …)
943
+ # to keep the scan cheap and avoid false-recent signals from tooling writes.
944
+ local _prune_find_args=( \( -name '.git' )
945
+ local _d
946
+ for _d in "${PRUNE_DISPOSABLE_IGNORED[@]}"; do
947
+ _prune_find_args+=( -o -name "$_d" )
948
+ done
949
+ _prune_find_args+=( \) -prune -o -not -type d )
950
+ local newest_file_mtime=""
951
+ newest_file_mtime="$(
952
+ find "$wt" -mindepth 1 -maxdepth 6 \
953
+ "${_prune_find_args[@]}" \
954
+ -printf '%T@\n' 2>/dev/null \
955
+ | sort -rn | head -1 | cut -d. -f1 || true
956
+ )"
957
+ if [[ "$newest_file_mtime" =~ ^[0-9]+$ ]]; then
958
+ if [[ -z "$activity_epoch" || "$newest_file_mtime" -gt "$activity_epoch" ]]; then
959
+ activity_epoch="$newest_file_mtime"
960
+ fi
961
+ fi
555
962
  fi
556
963
 
557
964
  printf '%s' "$activity_epoch"
@@ -562,23 +969,141 @@ skipped_recent=0
562
969
  has_live_process_in_worktree() {
563
970
  local wt="$1"
564
971
  local proc_cwd=""
972
+ # Set to 1 when the process-lease probe explicitly confirmed no live process
973
+ # (exit status 1 = "inactive"). When 0, an empty /proc scan is inconclusive
974
+ # and must be treated as "possibly live" (fail closed).
975
+ local lease_authoritative=0
976
+ # GUARDEX_PROC_DIR overrides the /proc root for the outer liveness check.
977
+ # Used by tests to inject a fake proc tree without affecting the in-mutex
978
+ # Python re-check (proc_has_live_process), which always reads real /proc.
979
+ local _proc_dir="${GUARDEX_PROC_DIR:-/proc}"
980
+
981
+ if [[ -d "${repo_common_dir}/gx-process-leases" ]]; then
982
+ local lease_probe="${GUARDEX_CLI_ENTRY:-}"
983
+ [[ -n "$lease_probe" ]] || return 0
984
+ lease_probe="$(dirname "$lease_probe")/../src/agents/process-lease.js"
985
+ [[ -f "$lease_probe" ]] || return 0
986
+ local lease_status=0
987
+ "${GUARDEX_NODE_BIN:-node}" "$lease_probe" "$wt" || lease_status=$?
988
+ # Unknown probes fail closed too; only explicit inactive (1) can continue.
989
+ [[ "$lease_status" -eq 1 ]] || return 0
990
+ lease_authoritative=1
991
+ fi
565
992
 
566
- [[ -d /proc ]] || return 1
567
-
568
- for proc_cwd in /proc/[0-9]*/cwd; do
569
- [[ -e "$proc_cwd" ]] || continue
570
- local live_cwd=""
571
- live_cwd="$(readlink "$proc_cwd" 2>/dev/null || true)"
993
+ [[ -d "$_proc_dir" ]] || return 1
994
+
995
+ # ONE readlink for every process, not one per process. `readlink` takes many
996
+ # operands and prints a line each, and this check only needs the SET of live
997
+ # cwds — which pid owns one is never used.
998
+ #
999
+ # The old loop spawned a readlink per /proc entry. On a workstation with ~4000
1000
+ # processes that is ~4000 forks, and an `execve` count of a full post-merge
1001
+ # sweep was 6602 processes — 4074 of them this readlink — which is where the
1002
+ # ~30 s a `git pull` spent waiting on post-merge cleanup actually went. It was
1003
+ # never the forge: the same sweep makes 5 HTTPS calls.
1004
+ #
1005
+ # Unreadable entries (other users' processes) print nothing and are skipped,
1006
+ # exactly as the per-entry version's empty result was skipped.
1007
+ #
1008
+ # Not a multi-operand `readlink`: uutils coreutils (Ubuntu 26.04's default)
1009
+ # aborts at the FIRST unreadable operand — /proc/1/cwd for a non-root user —
1010
+ # and prints nothing, so every worktree looked process-free and was pruned
1011
+ # while in use. GNU find's -printf '%l' reads each link in one process and
1012
+ # skips unreadable entries.
1013
+ local live_cwds=""
1014
+ live_cwds="$(find "$_proc_dir" -mindepth 2 -maxdepth 2 -name cwd -printf '%l\n' 2>/dev/null || true)"
1015
+ if [[ -z "$live_cwds" ]]; then
1016
+ # No GNU find (-printf unsupported): one readlink per entry.
1017
+ local proc_entry=""
1018
+ for proc_entry in "${_proc_dir}"/[0-9]*; do
1019
+ proc_cwd="$(readlink "${proc_entry}/cwd" 2>/dev/null || true)"
1020
+ [[ -n "$proc_cwd" ]] && live_cwds+="${proc_cwd}"$'\n'
1021
+ done
1022
+ fi
1023
+ if [[ -z "$live_cwds" ]]; then
1024
+ # Empty result: either no processes exist or every /proc/*/cwd belongs to
1025
+ # another UID and is unreadable by the current user (multi-user / container
1026
+ # setups). An empty scan is inconclusive — it cannot prove absence of live
1027
+ # processes. Only trust "no live process" when the lease guard explicitly
1028
+ # confirmed inactivity; otherwise fail closed (assume possibly live).
1029
+ [[ "$lease_authoritative" -eq 1 ]] && return 1 || return 0
1030
+ fi
1031
+ local live_cwd=""
1032
+ while IFS= read -r live_cwd; do
572
1033
  [[ -n "$live_cwd" ]] || continue
573
1034
  live_cwd="${live_cwd% (deleted)}"
574
1035
  if [[ "$live_cwd" == "$wt" || "$live_cwd" == "${wt}"/* ]]; then
575
1036
  return 0
576
1037
  fi
577
- done
1038
+ done <<< "$live_cwds"
578
1039
 
579
1040
  return 1
580
1041
  }
581
1042
 
1043
+ # ── Interrupted removals ─────────────────────────────────────────────────────
1044
+ # `git worktree remove` deletes the worktree's .git entry first. If the process
1045
+ # is killed after that (field 2026-11-18: an OOM killer hit the removal on a
1046
+ # loaded machine), a half-deleted directory stays behind that no later cycle
1047
+ # can judge any more, so it is kept forever. A marker written AFTER the worktree
1048
+ # passed every safety check lets the next cycle finish exactly that removal.
1049
+ PENDING_REMOVALS_DIR="${repo_common_dir}/guardex-pending-removals"
1050
+
1051
+ pending_removal_marker() {
1052
+ local key
1053
+ if command -v sha256sum >/dev/null 2>&1; then
1054
+ key="$(printf '%s' "$1" | sha256sum | cut -c1-40)"
1055
+ else
1056
+ key="$(printf '%s' "$1" | cksum | tr -c -d '0-9')"
1057
+ fi
1058
+ printf '%s/%s' "$PENDING_REMOVALS_DIR" "$key"
1059
+ }
1060
+
1061
+ mark_pending_removal() {
1062
+ [[ "$DRY_RUN" -eq 1 ]] && return 0
1063
+ mkdir -p "$PENDING_REMOVALS_DIR" 2>/dev/null || return 0
1064
+ printf '%s\n' "$1" > "$(pending_removal_marker "$1")" 2>/dev/null || true
1065
+ }
1066
+
1067
+ clear_pending_removal() {
1068
+ rm -f -- "$(pending_removal_marker "$1")" 2>/dev/null || true
1069
+ }
1070
+
1071
+ # Finish removals a previous cycle started but did not complete. Only a
1072
+ # directory that has already lost its .git entry is deleted, and only while no
1073
+ # file in it is newer than the marker: an intact worktree (the removal never
1074
+ # began, or the path was reused) and a leftover someone has written to since
1075
+ # are both left alone.
1076
+ finish_interrupted_removals() {
1077
+ [[ "$DRY_RUN" -eq 1 ]] && return 0
1078
+ [[ -d "$PENDING_REMOVALS_DIR" ]] || return 0
1079
+ local marker path finished=0
1080
+ for marker in "$PENDING_REMOVALS_DIR"/*; do
1081
+ [[ -f "$marker" ]] || continue
1082
+ path="$(head -n 1 "$marker" 2>/dev/null || true)"
1083
+ if [[ "$path" == /* && "$path" != "/" && "$path" != "$repo_root" && "$repo_root" != "$path"/* \
1084
+ && -d "$path" && ! -L "$path" && ! -e "${path}/.git" ]]; then
1085
+ # Someone kept working in the leftover (or put a new directory there):
1086
+ # a file written after the removal began is not ours to delete.
1087
+ if [[ -n "$(find "$path" -type f -newer "$marker" -print -quit 2>/dev/null)" ]]; then
1088
+ echo "[agent-worktree-prune] Warning: interrupted removal NOT finished, files changed since: ${path}" >&2
1089
+ rm -f -- "$marker" 2>/dev/null || true
1090
+ continue
1091
+ fi
1092
+ echo "[agent-worktree-prune] Finishing interrupted removal: ${path}"
1093
+ if ! rm -rf -- "$path" 2>/dev/null; then
1094
+ echo "[agent-worktree-prune] Warning: could not finish interrupted removal: ${path}" >&2
1095
+ continue
1096
+ fi
1097
+ finished=1
1098
+ fi
1099
+ rm -f -- "$marker" 2>/dev/null || true
1100
+ done
1101
+ if [[ "$finished" -eq 1 ]]; then
1102
+ git -C "$repo_root" worktree prune >/dev/null 2>&1 || true
1103
+ fi
1104
+ return 0
1105
+ }
1106
+
582
1107
  remove_worktree_with_lock_guard() {
583
1108
  local worktree="$1"
584
1109
  local remove_reason="$2"
@@ -593,6 +1118,7 @@ remove_worktree_with_lock_guard() {
593
1118
 
594
1119
  python3 - "$shared_lock" "$lock_file" "$repo_root" "$worktree" "$remove_reason" "$branch" "$DRY_RUN" <<'PY'
595
1120
  import json
1121
+ import os
596
1122
  import subprocess
597
1123
  import sys
598
1124
 
@@ -602,11 +1128,60 @@ except ImportError:
602
1128
  print('[agent-worktree-prune] OS file locking is unavailable; prune blocked', file=sys.stderr)
603
1129
  raise SystemExit(10)
604
1130
 
1131
+
1132
+ def proc_has_live_process(wt_path):
1133
+ """Return True when a live process has wt_path as its cwd, or when the
1134
+ result is inconclusive (all /proc/*/cwd entries were unreadable, meaning
1135
+ agent processes may belong to a different UID). Returns False only when
1136
+ at least one /proc entry was readable and none matched the worktree.
1137
+ Fails closed so that an unreadable /proc never silently authorises removal.
1138
+ """
1139
+ if not os.path.isdir('/proc'):
1140
+ return False # Non-Linux: skip the re-check
1141
+ real_wt = os.path.realpath(wt_path)
1142
+ any_readable = False
1143
+ try:
1144
+ for entry in os.scandir('/proc'):
1145
+ if not entry.name.isdigit():
1146
+ continue
1147
+ try:
1148
+ cwd = os.readlink(entry.path + '/cwd')
1149
+ any_readable = True
1150
+ # Strip the " (deleted)" suffix that Linux appends after an
1151
+ # unlink, mirroring the shell function's handling.
1152
+ if cwd.endswith(' (deleted)'):
1153
+ cwd = cwd[:-len(' (deleted)')]
1154
+ if cwd == real_wt or cwd.startswith(real_wt + '/'):
1155
+ return True
1156
+ except (OSError, PermissionError):
1157
+ continue
1158
+ except OSError:
1159
+ return True # Cannot read /proc at all — fail closed
1160
+ if not any_readable:
1161
+ # Every /proc/*/cwd was unreadable (other UIDs in a multi-user or
1162
+ # container setup). We cannot prove absence of live processes.
1163
+ return True # fail closed
1164
+ return False
1165
+
1166
+
605
1167
  shared_lock, lock_file, repo_root, worktree, remove_reason, branch, dry_run = sys.argv[1:]
606
1168
  try:
607
1169
  with open(shared_lock, 'a+', encoding='utf-8') as lock_handle:
608
1170
  fcntl.flock(lock_handle.fileno(), fcntl.LOCK_EX)
609
1171
 
1172
+ # An ignored child worktree can contain active or uncommitted work
1173
+ # even when the parent appears clean. Never recursively remove it.
1174
+ registered = subprocess.run(
1175
+ ['git', '-C', repo_root, 'worktree', 'list', '--porcelain', '-z'],
1176
+ stdout=subprocess.PIPE, check=True,
1177
+ )
1178
+ parent = os.path.realpath(worktree)
1179
+ for field in registered.stdout.split(b'\0'):
1180
+ if field.startswith(b'worktree '):
1181
+ child = os.path.realpath(os.fsdecode(field[len(b'worktree '):]))
1182
+ if child != parent and os.path.commonpath([parent, child]) == parent:
1183
+ raise SystemExit(11)
1184
+
610
1185
  try:
611
1186
  with open(lock_file, encoding='utf-8') as handle:
612
1187
  state = json.load(handle)
@@ -634,7 +1209,11 @@ try:
634
1209
  file=sys.stderr,
635
1210
  )
636
1211
  raise SystemExit(10)
637
- if not branch.startswith(('agent/', 'work/')) or entry.get('branch') != branch:
1212
+ # Block removal only when a lock entry belongs to a *different*
1213
+ # branch. The old prefix guard (`not branch.startswith(('agent/',
1214
+ # 'work/'))`) unconditionally refused feat/* and fix/* worktrees
1215
+ # even when every lock entry was self-owned, leaving them stranded.
1216
+ if entry.get('branch') != branch:
638
1217
  raise SystemExit(10)
639
1218
 
640
1219
  if locks:
@@ -645,6 +1224,14 @@ try:
645
1224
  flush=True,
646
1225
  )
647
1226
 
1227
+ # TOCTOU guard: re-check process liveness after acquiring the mutex.
1228
+ # A process may have entered the worktree between the shell-side check
1229
+ # and this point. git worktree remove --force deletes the working tree
1230
+ # unconditionally; removing it under a live process leaves the process
1231
+ # with an unlinked CWD and causes ENOENT on every subsequent file op.
1232
+ if dry_run != '1' and proc_has_live_process(worktree):
1233
+ raise SystemExit(10)
1234
+
648
1235
  print(f'[agent-worktree-prune] Removing worktree ({remove_reason}): {worktree}', flush=True)
649
1236
  command = ['git', '-C', repo_root, 'worktree', 'remove', worktree, '--force']
650
1237
  if dry_run == '1':
@@ -653,7 +1240,7 @@ try:
653
1240
 
654
1241
  result = subprocess.run(command, check=False)
655
1242
  raise SystemExit(0 if result.returncode == 0 else 1)
656
- except OSError:
1243
+ except (OSError, subprocess.CalledProcessError):
657
1244
  print(
658
1245
  f'[agent-worktree-prune] Cannot safely acquire active lock guard: {shared_lock}',
659
1246
  file=sys.stderr,
@@ -676,7 +1263,12 @@ branch_idle_gate() {
676
1263
  local last_activity_epoch=""
677
1264
  last_activity_epoch="$(read_branch_activity_epoch "$branch" "$wt")"
678
1265
  if [[ ! "$last_activity_epoch" =~ ^[0-9]+$ ]]; then
679
- return 0
1266
+ # Cannot determine when the branch was last active — fail closed: treat as
1267
+ # recent and skip removal rather than allow it. A branch with no reflog
1268
+ # and no git history is an unusual edge-case; preserving it is the safe choice.
1269
+ skipped_recent=$((skipped_recent + 1))
1270
+ echo "[agent-worktree-prune] Skipping branch with undetermined activity epoch (fail closed): ${branch} (${reason})"
1271
+ return 1
680
1272
  fi
681
1273
 
682
1274
  local idle_age=$((NOW_EPOCH - last_activity_epoch))
@@ -755,6 +1347,7 @@ removed_worktrees=0
755
1347
  removed_branches=0
756
1348
  skipped_active=0
757
1349
  skipped_dirty=0
1350
+ skipped_broken=0
758
1351
  skipped_open_pr=0
759
1352
  processed_branches=0
760
1353
  skipped_limited=0
@@ -771,14 +1364,104 @@ reserve_branch_slot() {
771
1364
 
772
1365
  relocate_foreign_worktree_entries
773
1366
 
1367
+ # Stricter than branch_has_merged_pr, for worktrees that are not agent lanes:
1368
+ # the local tip, and origin's tip when there is one, must each EQUAL a merged
1369
+ # PR head SHA. Fails closed when PR detection is off or gh is unavailable.
1370
+ branch_is_exact_merged_pr_head() {
1371
+ local branch="$1"
1372
+ [[ "$INCLUDE_PR_MERGED" -eq 1 ]] || return 1
1373
+ load_merged_pr_branches || return 1
1374
+ local merged_oids=" ${MERGED_PR_BRANCHES[$branch]:-} "
1375
+ # Same truncation fallback as branch_has_merged_pr: if the bulk list was
1376
+ # capped and this branch was not found, probe it individually.
1377
+ if [[ -z "${merged_oids// /}" && "$PR_MERGED_LOOKUP_TRUNCATED" -eq 1 ]]; then
1378
+ _load_merged_pr_branch_fallback "$branch" || return 1
1379
+ merged_oids=" ${MERGED_PR_BRANCHES[$branch]:-} "
1380
+ fi
1381
+ [[ -n "${merged_oids// /}" ]] || return 1
1382
+ local ref resolved seen=0
1383
+ for ref in "refs/heads/${branch}" "refs/remotes/origin/${branch}"; do
1384
+ resolved="$(git -C "$repo_root" rev-parse --verify --quiet "${ref}^{commit}" 2>/dev/null || true)"
1385
+ [[ -n "$resolved" ]] || continue
1386
+ seen=1
1387
+ [[ "$merged_oids" == *" ${resolved} "* ]] || return 1
1388
+ done
1389
+ [[ "$seen" -eq 1 ]]
1390
+ }
1391
+
1392
+ # Never reclaim a linked worktree that has the base or a long-lived branch
1393
+ # checked out, whatever a forge says about a same-named PR.
1394
+ is_protected_linked_branch() {
1395
+ local branch="$1"
1396
+ [[ -z "$branch" || "$branch" == "$BASE_BRANCH" ]] && return 0
1397
+ case "$branch" in
1398
+ main|master|dev|develop|trunk|release/*|hotfix/*) return 0 ;;
1399
+ esac
1400
+ return 1
1401
+ }
1402
+
1403
+ # True when the detached HEAD of worktree $1 is contained in the base branch,
1404
+ # locally or on origin (the local base is often behind: deploys check out
1405
+ # origin/<base>).
1406
+ # Also refuses (returns 1) while a rebase / merge / cherry-pick / revert /
1407
+ # bisect is in progress there — HEAD is detached at a base commit then, but the
1408
+ # operation's state lives in the worktree's git dir and would be lost — and,
1409
+ # when an idle threshold is set, while the worktree was touched recently (a
1410
+ # fresh `git worktree add --detach` an agent has not started using yet).
1411
+ detached_head_is_merged() {
1412
+ local wt="$1" head ref marker path newest=0 mtime
1413
+ for marker in rebase-merge rebase-apply MERGE_HEAD CHERRY_PICK_HEAD REVERT_HEAD BISECT_LOG; do
1414
+ path="$(git -C "$wt" rev-parse --git-path "$marker" 2>/dev/null)" || return 1
1415
+ [[ "$path" == /* ]] || path="${wt}/${path}"
1416
+ if [[ -e "$path" ]]; then
1417
+ echo "[agent-worktree-prune] Keeping detached worktree with an operation in progress (${marker}): ${wt}"
1418
+ return 1
1419
+ fi
1420
+ done
1421
+ if [[ "$IDLE_SECONDS" -gt 0 ]]; then
1422
+ for marker in HEAD index; do
1423
+ path="$(git -C "$wt" rev-parse --git-path "$marker" 2>/dev/null)" || continue
1424
+ [[ "$path" == /* ]] || path="${wt}/${path}"
1425
+ mtime="$(stat -c %Y -- "$path" 2>/dev/null || stat -f %m "$path" 2>/dev/null || echo "")"
1426
+ [[ "$mtime" =~ ^[0-9]+$ && "$mtime" -gt "$newest" ]] && newest="$mtime"
1427
+ done
1428
+ mtime="$(stat -c %Y -- "$wt" 2>/dev/null || stat -f %m "$wt" 2>/dev/null || echo "")"
1429
+ [[ "$mtime" =~ ^[0-9]+$ && "$mtime" -gt "$newest" ]] && newest="$mtime"
1430
+ if [[ "$newest" -le 0 || $((NOW_EPOCH - newest)) -lt "$IDLE_SECONDS" ]]; then
1431
+ skipped_recent=$((skipped_recent + 1))
1432
+ echo "[agent-worktree-prune] Skipping recent detached worktree (merged-detached-worktree): ${wt}"
1433
+ return 1
1434
+ fi
1435
+ fi
1436
+ head="$(git -C "$wt" rev-parse --verify --quiet HEAD 2>/dev/null)" || return 1
1437
+ [[ -n "$head" ]] || return 1
1438
+ for ref in "$BASE_BRANCH" "refs/remotes/origin/${BASE_BRANCH}"; do
1439
+ git -C "$repo_root" rev-parse --verify --quiet "$ref" >/dev/null 2>&1 || continue
1440
+ if git -C "$repo_root" merge-base --is-ancestor "$head" "$ref" 2>/dev/null; then
1441
+ return 0
1442
+ fi
1443
+ done
1444
+ return 1
1445
+ }
1446
+
774
1447
  process_entry() {
775
1448
  local wt="$1"
776
1449
  local branch_ref="$2"
777
1450
 
778
1451
  [[ -z "$wt" ]] && return
779
1452
  [[ "$wt" == "$repo_root" ]] && return
780
- if ! is_managed_worktree_path "$wt" && [[ "$INCLUDE_CLEAN_LINKED_WORKTREES" -ne 1 ]]; then
781
- return
1453
+ # A linked worktree outside the managed dirs is only considered when asked
1454
+ # for. Under --include-merged-linked-worktrees alone it may go ONLY as a
1455
+ # merged agent lane (checked after the reason is known, below).
1456
+ local linked_merged_only=0
1457
+ if ! is_managed_worktree_path "$wt"; then
1458
+ if [[ "$INCLUDE_CLEAN_LINKED_WORKTREES" -eq 1 ]]; then
1459
+ :
1460
+ elif [[ "$INCLUDE_MERGED_LINKED_WORKTREES" -eq 1 ]]; then
1461
+ linked_merged_only=1
1462
+ else
1463
+ return 0
1464
+ fi
782
1465
  fi
783
1466
 
784
1467
  local branch=""
@@ -800,7 +1483,14 @@ process_entry() {
800
1483
  echo "[agent-worktree-prune] Skipping live process worktree: ${wt}"
801
1484
  return
802
1485
  fi
803
- if [[ "$branch" == agent/* || "$branch" == work/* ]] && should_preserve_open_pr_branch "$branch"; then
1486
+ # Apply open-PR guard to every named non-protected branch when PRESERVE_OPEN_PRS=1.
1487
+ # Previously only agent/* and work/* were checked; broadening to all named branches
1488
+ # ensures that --include-clean-linked-worktrees / --include-merged-linked-worktrees
1489
+ # cannot accidentally reclaim a feat/*, fix/*, or personal lane with an open PR.
1490
+ # (should_preserve_open_pr_branch returns false immediately when PRESERVE_OPEN_PRS=0,
1491
+ # so this change is a no-op when the flag is not set.)
1492
+ if [[ -n "$branch" ]] && ! is_protected_linked_branch "$branch" \
1493
+ && should_preserve_open_pr_branch "$branch"; then
804
1494
  skipped_open_pr=$((skipped_open_pr + 1))
805
1495
  if [[ "$OPEN_PR_LOOKUP_UNAVAILABLE" -eq 1 ]]; then
806
1496
  echo "[agent-worktree-prune] Skipping open-PR worktree because PR state is unavailable (fail closed): ${wt}"
@@ -810,6 +1500,28 @@ process_entry() {
810
1500
  return
811
1501
  fi
812
1502
 
1503
+ # For linked-worktree reclaim modes (--include-clean-linked-worktrees or
1504
+ # --include-merged-linked-worktrees), ALWAYS check for an open PR on non-agent
1505
+ # branches — regardless of PRESERVE_OPEN_PRS. We use the bulk open-PR lookup
1506
+ # and fail closed when it is unavailable or truncated, because a false
1507
+ # "no open PR" answer would silently destroy someone's in-flight work.
1508
+ if [[ -n "$branch" ]] && ! is_managed_worktree_path "$wt" \
1509
+ && [[ "$branch" != agent/* && "$branch" != work/* ]] \
1510
+ && ! is_protected_linked_branch "$branch" \
1511
+ && [[ "$INCLUDE_CLEAN_LINKED_WORKTREES" -eq 1 || "$linked_merged_only" -eq 1 ]]; then
1512
+ local _linked_open_state=0
1513
+ linked_branch_open_pr_state "$branch" || _linked_open_state=$?
1514
+ if [[ "$_linked_open_state" -eq 0 ]]; then
1515
+ skipped_open_pr=$((skipped_open_pr + 1))
1516
+ echo "[agent-worktree-prune] Skipping linked worktree with open PR: ${wt}"
1517
+ return
1518
+ elif [[ "$_linked_open_state" -eq 2 ]]; then
1519
+ skipped_open_pr=$((skipped_open_pr + 1))
1520
+ echo "[agent-worktree-prune] Skipping linked worktree because open-PR state is unavailable (fail closed): ${wt}"
1521
+ return
1522
+ fi
1523
+ fi
1524
+
813
1525
  local remove_reason=""
814
1526
  local branch_delete_mode="safe"
815
1527
  local branch_delete_label="merged"
@@ -849,14 +1561,68 @@ process_entry() {
849
1561
  elif [[ "$DELETE_BRANCHES" -eq 1 ]] && branch_has_merged_pr "$branch"; then
850
1562
  remove_reason="merged-agent-pr"
851
1563
  branch_delete_mode="force"
852
- expected_branch_head="$(git -C "$repo_root" rev-parse --verify "refs/heads/${branch}^{commit}" 2>/dev/null || true)"
1564
+ expected_branch_head="$(branch_tip "$branch")"
853
1565
  elif [[ "$ONLY_DIRTY_WORKTREES" -eq 1 ]] && is_clean_worktree "$wt"; then
854
- remove_reason="clean-agent-worktree"
1566
+ local branch_ahead_count=0
1567
+ if [[ "$KEEP_CLEAN_UNMERGED" -eq 1 ]]; then
1568
+ branch_ahead_count="$(git -C "$repo_root" rev-list --count "${BASE_BRANCH}..${branch}" 2>/dev/null || echo 1)"
1569
+ fi
1570
+ if [[ "$branch_ahead_count" -eq 0 ]]; then
1571
+ remove_reason="clean-agent-worktree"
1572
+ fi
855
1573
  fi
856
1574
  elif [[ "$branch" == __agent_integrate_* || "$branch" == __source-probe-* ]]; then
857
1575
  remove_reason="temporary-worktree"
858
1576
  elif [[ "$INCLUDE_CLEAN_LINKED_WORKTREES" -eq 1 ]] && is_clean_worktree "$wt"; then
859
- remove_reason="clean-linked-worktree"
1577
+ # Only reclaim if the branch has no commits ahead of BASE_BRANCH, OR the
1578
+ # branch already passes the merged-PR check (the worktree is truly done).
1579
+ # A clean linked worktree that is ahead of base holds unmerged, potentially
1580
+ # unpushed work — reclaiming it would silently discard that work.
1581
+ # Detached worktrees have no branch ref: keep the existing reclaim behavior.
1582
+ if [[ -z "$branch" ]]; then
1583
+ remove_reason="clean-linked-worktree"
1584
+ elif branch_is_exact_merged_pr_head "$branch" || branch_has_merged_pr "$branch"; then
1585
+ remove_reason="clean-linked-worktree"
1586
+ else
1587
+ local ahead_count=0
1588
+ ahead_count="$(git -C "$repo_root" rev-list --count "${BASE_BRANCH}..${branch}" 2>/dev/null || echo 1)"
1589
+ if [[ "$ahead_count" -eq 0 ]]; then
1590
+ remove_reason="clean-linked-worktree"
1591
+ else
1592
+ echo "[agent-worktree-prune] Keeping linked worktree with unmerged commits (${ahead_count} ahead of ${BASE_BRANCH}): ${wt}"
1593
+ fi
1594
+ fi
1595
+ elif [[ "$linked_merged_only" -eq 1 && "$branch" != work/* ]] \
1596
+ && ! is_protected_linked_branch "$branch" && branch_is_exact_merged_pr_head "$branch"; then
1597
+ # A non-agent worktree (feat/*, fix/*, a person's own lane) goes ONLY on
1598
+ # forge evidence: its tip IS a merged PR's head. Containment is not
1599
+ # enough here — a branch name re-created off the base (no commits yet)
1600
+ # is an ancestor of the old PR's head, and of the base too. The branch
1601
+ # itself is kept.
1602
+ remove_reason="merged-linked-pr"
1603
+ fi
1604
+
1605
+ # A detached linked worktree (e.g. checked out at origin/main to build a deploy
1606
+ # after its PR merged) holds no branch and nothing to lose when its HEAD is
1607
+ # already in the base branch: it goes as a merged lane too. A detached HEAD
1608
+ # with commits the base does not have stays (no branch points at them). The
1609
+ # dirty check below still protects uncommitted changes.
1610
+ if [[ "$linked_merged_only" -eq 1 && "$remove_reason" == "detached-worktree" ]] \
1611
+ && detached_head_is_merged "$wt"; then
1612
+ remove_reason="merged-detached-worktree"
1613
+ fi
1614
+
1615
+ if [[ "$linked_merged_only" -eq 1 ]]; then
1616
+ case "$remove_reason" in
1617
+ merged-agent-branch|merged-agent-pr|merged-pr:*|merged-linked-pr|merged-detached-worktree) ;;
1618
+ *)
1619
+ if [[ -z "$remove_reason" && -n "$branch" && "$branch" != agent/* ]] \
1620
+ && git -C "$repo_root" show-ref --verify --quiet "refs/heads/${branch}"; then
1621
+ echo "[agent-worktree-prune] Keeping non-agent linked worktree (tip is not a merged PR head for ${branch}): ${wt}"
1622
+ fi
1623
+ return 0
1624
+ ;;
1625
+ esac
860
1626
  fi
861
1627
 
862
1628
  if [[ -z "$remove_reason" ]]; then
@@ -867,16 +1633,34 @@ process_entry() {
867
1633
  return
868
1634
  fi
869
1635
 
1636
+ # A registered worktree whose directory is no longer a git checkout (its .git
1637
+ # file is gone — an interrupted removal). Every git command in it fails, and
1638
+ # `git diff` there even exits 129, which used to abort the WHOLE prune cycle
1639
+ # under `set -e` (field 2026-11-18: two such leftovers kept 400+ worktrees
1640
+ # from ever being cleaned). Its content cannot be judged, so leave it alone
1641
+ # and carry on with the rest.
1642
+ # Test the worktree's own .git entry: `git rev-parse` would succeed for a
1643
+ # worktree nested inside the main checkout by resolving to the parent repo.
1644
+ if [[ ! -e "${wt}/.git" ]]; then
1645
+ skipped_broken=$((skipped_broken + 1))
1646
+ echo "[agent-worktree-prune] Skipping broken worktree (${remove_reason}; not a git checkout, .git is missing): ${wt}"
1647
+ return
1648
+ fi
1649
+
870
1650
  if [[ "$remove_reason" == "temporary-worktree" ]]; then
871
1651
  git -C "$wt" rebase --abort >/dev/null 2>&1 || true
872
1652
  git -C "$wt" merge --abort >/dev/null 2>&1 || true
873
1653
  fi
874
1654
 
875
- if [[ "$FORCE_DIRTY" -ne 1 ]] && ! is_clean_worktree "$wt"; then
876
- skipped_dirty=$((skipped_dirty + 1))
877
- echo "[agent-worktree-prune] Skipping dirty worktree (${remove_reason}): ${wt}"
878
- summarize_worktree_dirt "$wt"
879
- return
1655
+ if ! is_clean_worktree "$wt"; then
1656
+ if [[ "$FORCE_DIRTY" -eq 1 ]]; then
1657
+ warn_force_dirty_removal "$wt" "$remove_reason"
1658
+ else
1659
+ skipped_dirty=$((skipped_dirty + 1))
1660
+ echo "[agent-worktree-prune] Skipping dirty worktree (${remove_reason}): ${wt}"
1661
+ summarize_worktree_dirt "$wt"
1662
+ return
1663
+ fi
880
1664
  fi
881
1665
 
882
1666
  if [[ "$remove_reason" == closed-pr:* ]] && ! closed_pr_has_remote_recovery "$branch"; then
@@ -890,10 +1674,78 @@ process_entry() {
890
1674
  fi
891
1675
 
892
1676
  local remove_status=0
1677
+ if [[ "$DRY_RUN" -ne 1 && "$remove_reason" != "temporary-worktree" ]]; then
1678
+ local before_hook_head after_hook_head
1679
+ before_hook_head="$(git -C "$wt" rev-parse HEAD)" || return
1680
+ if ! run_lifecycle_hook pre-remove "$wt" "$branch"; then
1681
+ echo "[agent-worktree-prune] pre-remove vetoed removal: ${wt}" >&2
1682
+ return
1683
+ fi
1684
+ after_hook_head="$(git -C "$wt" rev-parse HEAD)" || return
1685
+ # Hooks run outside the claims mutex to avoid deadlocking GX commands.
1686
+ # Re-check mutable eligibility before the mutex-protected removal.
1687
+ if [[ "$before_hook_head" != "$after_hook_head" ]] || has_live_process_in_worktree "$wt"; then
1688
+ echo "[agent-worktree-prune] Worktree changed or became active during pre-remove: ${wt}" >&2
1689
+ return
1690
+ fi
1691
+ if ! is_clean_worktree "$wt"; then
1692
+ if [[ "$FORCE_DIRTY" -ne 1 ]]; then
1693
+ echo "[agent-worktree-prune] pre-remove left changes; preserving: ${wt}" >&2
1694
+ return
1695
+ fi
1696
+ warn_force_dirty_removal "$wt" "${remove_reason} after pre-remove hook"
1697
+ fi
1698
+ fi
1699
+ # Refused for non-temporary worktrees that contain precious ignored files
1700
+ # (gitignored content NOT under a disposable directory such as node_modules,
1701
+ # dist, .next, .venv, etc.). `git worktree remove --force` deletes the
1702
+ # working tree unconditionally; .env, local certs, and similar secrets-or-
1703
+ # state files would be gone forever. --force-dirty does NOT override this
1704
+ # check — an ignored file is never covered by is_clean_worktree(), so the
1705
+ # caller never saw it as "dirty" and explicitly chose to override it.
1706
+ if [[ "$remove_reason" != "temporary-worktree" ]]; then
1707
+ local _precious_ignored=""
1708
+ _precious_ignored="$(worktree_has_precious_ignored_files "$wt" 2>/dev/null || true)"
1709
+ if [[ -n "$_precious_ignored" ]]; then
1710
+ skipped_dirty=$((skipped_dirty + 1))
1711
+ echo "[agent-worktree-prune] Skipping worktree with precious ignored files (${remove_reason}): ${wt}"
1712
+ while IFS= read -r _pi_path; do
1713
+ [[ -n "$_pi_path" ]] && echo "[agent-worktree-prune] ignored: ${_pi_path}"
1714
+ done <<< "$_precious_ignored"
1715
+ return
1716
+ fi
1717
+ else
1718
+ # gx's own scratch worktrees (integration / source probes) stay disposable,
1719
+ # but never lose ignored files silently.
1720
+ local _tmp_ignored=""
1721
+ _tmp_ignored="$(worktree_has_precious_ignored_files "$wt" 2>/dev/null || true)"
1722
+ if [[ -n "$_tmp_ignored" ]]; then
1723
+ echo "[agent-worktree-prune] WARNING: removing temporary worktree with ignored files: ${wt}" >&2
1724
+ while IFS= read -r _pi_path; do
1725
+ [[ -n "$_pi_path" ]] && echo "[agent-worktree-prune] ignored: ${_pi_path}" >&2
1726
+ done <<< "$_tmp_ignored"
1727
+ fi
1728
+ fi
1729
+
1730
+ mark_pending_removal "$wt"
893
1731
  if remove_worktree_with_lock_guard "$wt" "$remove_reason" "$branch"; then
1732
+ clear_pending_removal "$wt"
1733
+ # The worktree list just changed; branch_has_worktree must re-read it.
1734
+ invalidate_worktree_branches
894
1735
  removed_worktrees=$((removed_worktrees + 1))
1736
+ if [[ "$DRY_RUN" -ne 1 && "$remove_reason" != "temporary-worktree" ]]; then
1737
+ run_lifecycle_hook post-remove "$wt" "$branch" \
1738
+ || echo "[agent-worktree-prune] Warning: post-remove hook could not be queued." >&2
1739
+ fi
895
1740
  else
896
1741
  remove_status=$?
1742
+ # Refused or failed before anything was deleted: nothing to finish later.
1743
+ [[ -e "${wt}/.git" ]] && clear_pending_removal "$wt"
1744
+ if [[ "$remove_status" -eq 11 ]]; then
1745
+ skipped_active=$((skipped_active + 1))
1746
+ echo "[agent-worktree-prune] Skipping worktree with registered descendants: ${wt}"
1747
+ return
1748
+ fi
897
1749
  if [[ "$remove_status" -ne 10 ]]; then
898
1750
  exit "$remove_status"
899
1751
  fi
@@ -910,7 +1762,7 @@ process_entry() {
910
1762
  if [[ ( "$branch" == agent/* || "$branch" == work/* ) && "$DELETE_BRANCHES" -eq 1 && "$remove_reason" != "stale-no-pr-worktree" ]]; then
911
1763
  local deleted_label="$branch_delete_label"
912
1764
  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)"
1765
+ remote_delete_head="$(classified_merged_pr_head "$branch" || branch_tip "$branch")"
914
1766
  fi
915
1767
  if delete_local_branch "$branch" "$branch_delete_mode" "$expected_branch_head" >/dev/null 2>&1; then
916
1768
  removed_branches=$((removed_branches + 1))
@@ -927,12 +1779,16 @@ process_entry() {
927
1779
  fi
928
1780
  elif [[ "$branch" == __agent_integrate_* || "$branch" == __source-probe-* ]]; then
929
1781
  run_cmd git -C "$repo_root" branch -D "$branch" >/dev/null 2>&1 || true
1782
+ invalidate_branch_tip "$branch"
930
1783
  removed_branches=$((removed_branches + 1))
931
1784
  echo "[agent-worktree-prune] Deleted temporary branch: ${branch}"
932
1785
  fi
933
1786
  fi
934
1787
  }
935
1788
 
1789
+ # Before listing worktrees: finish what a killed cycle left half-done.
1790
+ finish_interrupted_removals
1791
+
936
1792
  current_wt=""
937
1793
  current_branch_ref=""
938
1794
 
@@ -969,6 +1825,7 @@ if [[ "$DELETE_BRANCHES" -eq 1 ]]; then
969
1825
  if ! branch_idle_gate "$branch" "" "temporary-worktree"; then
970
1826
  continue
971
1827
  fi
1828
+ invalidate_branch_tip "$branch"
972
1829
  if run_cmd git -C "$repo_root" branch -D "$branch" >/dev/null 2>&1; then
973
1830
  removed_branches=$((removed_branches + 1))
974
1831
  echo "[agent-worktree-prune] Deleted stale temporary branch: ${branch}"
@@ -1012,7 +1869,7 @@ if [[ "$DELETE_BRANCHES" -eq 1 ]]; then
1012
1869
  merged_by_ancestor=1
1013
1870
  elif [[ "$PRUNE_STALE_LANES" -ne 1 ]] && branch_has_merged_pr "$branch"; then
1014
1871
  merged_by_pr=1
1015
- expected_branch_head="$(git -C "$repo_root" rev-parse --verify "refs/heads/${branch}^{commit}" 2>/dev/null || true)"
1872
+ expected_branch_head="$(branch_tip "$branch")"
1016
1873
  fi
1017
1874
  if [[ "$merged_by_ancestor" -eq 1 || "$merged_by_pr" -eq 1 || "$closed_by_pr" -eq 1 ]]; then
1018
1875
  if ! reserve_branch_slot "$branch"; then
@@ -1037,7 +1894,7 @@ if [[ "$DELETE_BRANCHES" -eq 1 ]]; then
1037
1894
  continue
1038
1895
  fi
1039
1896
  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)"
1897
+ remote_delete_head="$(classified_merged_pr_head "$branch" || branch_tip "$branch")"
1041
1898
  fi
1042
1899
  if delete_local_branch "$branch" "$branch_delete_mode" "$expected_branch_head" >/dev/null 2>&1; then
1043
1900
  removed_branches=$((removed_branches + 1))
@@ -1058,13 +1915,68 @@ fi
1058
1915
 
1059
1916
  run_cmd git -C "$repo_root" worktree prune
1060
1917
 
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}"
1918
+ # ── Dependency snapshot retention ────────────────────────────────────────────
1919
+ # <git-common-dir>/gx-dependency-snapshots holds full copies of node_modules &
1920
+ # co., one per lockfile/content key. They are a cache (consumers copy out of
1921
+ # them, nothing links in), but nothing ever deleted one: field 2026-11-18,
1922
+ # 4 x 1.6 GB in a single repo. Keep the newest KEEP and any used within
1923
+ # MAX_AGE_DAYS; mirrors pruneSnapshots() in src/scaffold/dependency-store.js.
1924
+ prune_dependency_snapshots() {
1925
+ local store="${repo_common_dir}/gx-dependency-snapshots"
1926
+ [[ -d "$store" && ! -L "$store" ]] || return 0
1927
+ local keep="${GUARDEX_DEPENDENCY_SNAPSHOT_KEEP:-2}"
1928
+ local max_age_days="${GUARDEX_DEPENDENCY_SNAPSHOT_MAX_AGE_DAYS:-14}"
1929
+ [[ "$keep" =~ ^[0-9]+$ ]] || keep=2
1930
+ [[ "$max_age_days" =~ ^[0-9]+$ ]] || max_age_days=14
1931
+ local now cutoff index=0 mtime name dir
1932
+ now="$(date +%s)"
1933
+ cutoff=$((now - max_age_days * 86400))
1934
+ while IFS=$'\t' read -r mtime name; do
1935
+ [[ "$name" =~ ^[0-9a-f]{64}-[0-9a-f]{64}$ ]] || continue
1936
+ index=$((index + 1))
1937
+ [[ "$index" -le "$keep" ]] && continue
1938
+ [[ "${mtime%.*}" -ge "$cutoff" ]] && continue
1939
+ dir="${store}/${name}"
1940
+ [[ -d "$dir" && ! -L "$dir" ]] || continue
1941
+ # A provision that reused it since the listing has touched it: still in use.
1942
+ [[ "$(stat -c %Y -- "$dir" 2>/dev/null || echo "$now")" -lt "$cutoff" ]] || continue
1943
+ if [[ "$DRY_RUN" -eq 1 ]]; then
1944
+ echo "[agent-worktree-prune] [dry-run] Would remove unused dependency snapshot: ${dir}"
1945
+ continue
1946
+ fi
1947
+ # Sealed read-only on creation.
1948
+ chmod -R u+w -- "$dir" 2>/dev/null || true
1949
+ if rm -rf -- "$dir" 2>/dev/null; then
1950
+ removed_snapshots=$((removed_snapshots + 1))
1951
+ echo "[agent-worktree-prune] Removed unused dependency snapshot: ${dir}"
1952
+ else
1953
+ echo "[agent-worktree-prune] Warning: could not remove dependency snapshot: ${dir}" >&2
1954
+ fi
1955
+ done < <(find "$store" -mindepth 1 -maxdepth 1 -type d -printf '%T@\t%f\n' 2>/dev/null | sort -rn || true)
1956
+
1957
+ # Staging directories of provisions that died (a live one is seconds old).
1958
+ if [[ "$DRY_RUN" -ne 1 ]]; then
1959
+ while IFS= read -r -d '' dir; do
1960
+ [[ -d "$dir" && ! -L "$dir" ]] || continue
1961
+ chmod -R u+w -- "$dir" 2>/dev/null || true
1962
+ rm -rf -- "$dir" 2>/dev/null || true
1963
+ done < <(find "$store" -mindepth 1 -maxdepth 1 -type d -name '.snapshot-*' -mmin +1440 -print0 2>/dev/null || true)
1964
+ fi
1965
+ return 0
1966
+ }
1967
+ removed_snapshots=0
1968
+ prune_dependency_snapshots
1969
+
1970
+ 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}, skipped_broken=${skipped_broken}, removed_snapshots=${removed_snapshots}"
1062
1971
  if [[ "$relocated_foreign" -gt 0 || "$skipped_foreign" -gt 0 ]]; then
1063
1972
  echo "[agent-worktree-prune] Foreign routing: relocated=${relocated_foreign}, skipped=${skipped_foreign}"
1064
1973
  fi
1065
1974
  if [[ "$skipped_active" -gt 0 ]]; then
1066
1975
  echo "[agent-worktree-prune] Tip: leave active agent worktree directories, then run this command again for full cleanup." >&2
1067
1976
  fi
1977
+ if [[ "$skipped_broken" -gt 0 ]]; then
1978
+ echo "[agent-worktree-prune] Tip: broken worktrees (no .git) were left alone. Check their content, delete the directory, then run 'git worktree prune'." >&2
1979
+ fi
1068
1980
  if [[ "$skipped_dirty" -gt 0 ]]; then
1069
1981
  echo "[agent-worktree-prune] Tip: dirty worktrees were preserved. Clean/finish them first, or pass --force-dirty to remove anyway." >&2
1070
1982
  fi