@cratis/pi 7.179.2 → 7.179.3

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.
@@ -45,10 +45,9 @@ dumps, and similar coordination files. These are **work records, not documentati
45
45
  main checkout when a PR merges or you finish a task (hooks and **ship-changes** also run it). It
46
46
  removes a worktree and its branch only on evidence the work reached the default branch —
47
47
  pushed is not merged — and never forces. It keeps worktrees with non-empty `.ai-work/`
48
- directories; manual `--include-work-records` deletes them once you have preserved what you
49
- need; hooks never opt in. Pin a long-lived worktree with `git worktree lock <path>`;
50
- locked worktrees are always kept, even with opt-in. Ignored files (`.env`, local databases) are
51
- deleted with a removed worktree: move what you need out first. Do not hand-remove worktrees
48
+ directories; manual `--include-work-records=<path>` lifts that for that worktree only;
49
+ hooks never opt in. Ignored or untracked files, a live process using it, or a failed holder
50
+ check (hooks README) keep a worktree. `git worktree lock <path>` pins one: locked worktrees are always kept. Do not hand-remove worktrees
52
51
  or `git branch -D` a delivered branch when the script can; `gh pr merge --delete-branch`
53
52
  inside a worktree leaves the worktree and branch behind. If the branch must outlive the task
54
53
  unmerged, leave the worktree and say so in the handoff. Never `--force` a removal; a
@@ -282,10 +282,19 @@ cannot delete a branch that a worktree still has checked out, so the pair is lef
282
282
  It removes only on **evidence of delivery**, never on a guess: the tip is merged into `origin/<default>`
283
283
  and was integrated rather than merely sitting on the default branch's first-parent history (where a
284
284
  brand-new empty branch sits), or it is merged and its upstream is gone, or GitHub reports a merged pull
285
- request whose head is exactly that tip. It never forces: a dirty, locked or current worktree is kept, as
286
- is anything undelivered, and every kept item is reported with its reason. Worktrees with non-empty
287
- `.ai-work/` directories are kept as "has untracked work records (.ai-work/)" by default, including
288
- ignored records. Other ignored files (`node_modules`, build output) go with a delivered worktree.
285
+ request whose head is exactly that tip. It never forces: a dirty, locked, current or live-held worktree
286
+ is kept, as is anything undelivered, and every kept item is reported with its reason. Before removal
287
+ (including dry-run), it checks for live processes with a cwd or open file under the worktree, preferring
288
+ validated `pi-holders --json` results with `jq`, falling back to `lsof` when either is unavailable.
289
+ The fallback takes one process-wide name listing per candidate, not inode-based `lsof +D`, with up
290
+ to three attempts on errors/incomplete results. Unrelated absolute-path FD-info diagnostics are
291
+ ignored; unresolved errors, incomplete target names, unknown paths and shared-inode ambiguity keep
292
+ the worktree. Only the script and its descendants are excluded; ancestors, including a parent shell
293
+ or agent session with cwd in another worktree, still count. Missing tools keep it. Git status is
294
+ rechecked after the holder check, immediately before removal. Ignored/untracked files
295
+ (`node_modules`, build output, `.env`, local databases, `.ai-work/`) also keep it: archive or remove them
296
+ first. Non-empty `.ai-work/` directories, even when tracked, are additionally kept as
297
+ "has work records (.ai-work/)" by default.
289
298
 
290
299
  - **When it runs.** After a Bash command that delivers or integrates work, and at the start of every
291
300
  session, so orphans left by any earlier session, crash or harness are collected too.
@@ -294,9 +303,11 @@ ignored records. Other ignored files (`node_modules`, build output) go with a de
294
303
  final step runs the same script, and on running it by hand.
295
304
  - **By hand.** `bash .cratis/ai/hooks/scripts/cratis-cleanup-worktrees.sh [--dry-run]` from any worktree;
296
305
  run from the main checkout to also collect the worktree you are standing in. Add
297
- `--include-work-records` only after preserving any records you still need: it permits deleting
298
- `.ai-work/` content, but never overrides locks or other safety checks. Hook mode ignores this flag;
299
- automatic hooks never opt in.
306
+ `--include-work-records=<path>` only after preserving any records you still need. It bypasses the
307
+ record-preservation check for that exact worktree only (repeat for multiple paths), permitting clean
308
+ tracked `.ai-work/` content to go with it, never ignored/untracked files. Bare `--include-work-records`
309
+ exits 2 with guidance. It never overrides locks, live holders or other safety checks. Hook mode
310
+ ignores scoped opt-ins; automatic hooks never opt in.
300
311
  - **GitHub lookups.** The complete worktree and branch sweep is planned before any removal. Git
301
312
  ancestry is checked first; only a plan needing more evidence triggers the single REST batch. It
302
313
  reads the latest 100 closed pull requests, so older merged branches absent from that page are simply
@@ -11,15 +11,23 @@
11
11
  # default branch's first-parent history, which is where a brand-new, empty branch sits), or
12
12
  # 2. its tip is merged into origin/<default> and its upstream is gone (the PR branch was deleted), or
13
13
  # 3. GitHub reports a merged pull request whose head commit is exactly this tip.
14
- # Anything else is KEPT and reported with the reason. Nothing is ever forced: a dirty, locked or
15
- # current worktree is kept, as is one holding .ai-work/ records unless explicitly opted in.
14
+ # Anything else is KEPT and reported with the reason. Nothing is ever forced: a dirty, locked,
15
+ # current or live-held worktree is kept. Ignored/untracked files must be archived or removed first,
16
+ # including .ai-work/. A non-empty .ai-work/ is also preserved when tracked, unless opted in below.
17
+ # Holder checks prefer validated pi-holders --json with jq, otherwise per-process lsof names (never
18
+ # +D): one process-wide listing per candidate, up to three attempts on errors/incomplete results.
19
+ # Only this script and its descendants are excluded; ancestor sessions still count as holders.
20
+ # Missing, failed, unparseable or ambiguous checks keep the worktree (including shared-inode names).
16
21
  # `git worktree remove` is never given --force.
17
22
  #
18
23
  # Usage:
19
- # cratis-cleanup-worktrees.sh [--dry-run] [--quiet] [--no-fetch] [--include-work-records]
24
+ # cratis-cleanup-worktrees.sh [--dry-run] [--quiet] [--no-fetch] [--include-work-records=<path>]...
20
25
  # run in the repository (any worktree)
21
- # --include-work-records allow deletion of .ai-work/ records
22
- # by hand only; ignored in hook mode
26
+ # --include-work-records=<path> bypass record preservation for this
27
+ # exact worktree only; repeatable, manual
28
+ # only, ignored in hook mode. It permits
29
+ # clean tracked records, never ignored or
30
+ # untracked files. Bare flag exits 2.
23
31
  # cratis-cleanup-worktrees.sh --hook Claude hook mode: reads the hook JSON
24
32
  # on stdin, acts only when relevant
25
33
  # cratis-cleanup-worktrees.sh --self-test plants cases and fails if any is wrong
@@ -29,12 +37,17 @@
29
37
  # shellcheck disable=SC2016 # the self-test checks are single-quoted on purpose: they are eval-ed later
30
38
  set -uo pipefail
31
39
 
32
- DRY=0; QUIET=0; FETCH=1; HOOK=0; SELFTEST=0; INCLUDE_WORK_RECORDS=0
40
+ DRY=0; QUIET=0; FETCH=1; HOOK=0; SELFTEST=0; WORK_RECORD_PATHS=()
33
41
  for a in "$@"; do
34
42
  case "$a" in
35
43
  --dry-run) DRY=1 ;; --quiet) QUIET=1 ;; --no-fetch) FETCH=0 ;;
36
44
  --hook) HOOK=1; QUIET=1 ;; --self-test) SELFTEST=1 ;;
37
- --include-work-records) INCLUDE_WORK_RECORDS=1 ;;
45
+ --include-work-records|--include-work-records=)
46
+ echo "cratis-cleanup-worktrees: --include-work-records requires an explicit worktree path (--include-work-records=<path>)" >&2; exit 2 ;;
47
+ --include-work-records=*)
48
+ record_path=${a#*=}
49
+ record_path=$(cd "$record_path" 2>/dev/null && pwd -P) || { echo "cratis-cleanup-worktrees: cannot resolve worktree path '${a#*=}'" >&2; exit 2; }
50
+ WORK_RECORD_PATHS+=("$record_path") ;;
38
51
  *) echo "cratis-cleanup-worktrees: unknown argument '$a'" >&2; exit 2 ;;
39
52
  esac
40
53
  done
@@ -42,7 +55,7 @@ done
42
55
  # ── Hook mode: decide whether this event is worth a sweep ─────────────────────
43
56
  EVENT="PostToolUse"
44
57
  if [ "$HOOK" = 1 ]; then
45
- INCLUDE_WORK_RECORDS=0
58
+ WORK_RECORD_PATHS=()
46
59
  payload=''; IFS= read -r -d '' payload || true
47
60
  [ "${CRATIS_HOOKS_SKIP_CLEANUP:-}" = 1 ] && exit 0
48
61
  case "$payload" in *'"SessionStart"'*) EVENT="SessionStart" ;; esac
@@ -62,24 +75,34 @@ fi
62
75
  # ── Self-test ─────────────────────────────────────────────────────────────────
63
76
  if [ "$SELFTEST" = 1 ]; then
64
77
  self=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")
65
- t=$(mktemp -d "${TMPDIR:-/tmp}/cleanup-selftest.XXXXXX"); trap 'rm -rf "$t"' EXIT
78
+ t=$(mktemp -d "${TMPDIR:-/tmp}/cleanup-selftest.XXXXXX"); holder=''
79
+ trap '[ -z "$holder" ] || { kill "$holder" 2>/dev/null; wait "$holder" 2>/dev/null; }; rm -rf "$t"' EXIT
66
80
  t=$(cd "$t" && pwd -P)
67
81
  export GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@t GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@t CRATIS_CLEANUP_NO_GH=1
68
82
  git init -q --bare -b main "$t/origin.git"
69
83
  git clone -q "$t/origin.git" "$t/repo" 2>/dev/null; cd "$t/repo" || exit 2
84
+ git config core.excludesFile /dev/null
70
85
  git checkout -q -b main 2>/dev/null; echo a > a; git add a; git commit -qm base; git push -q origin main
71
- mk() { git worktree add -q -b "$1" "$t/wt-$1" main; }
86
+ base=$(git rev-parse main)
87
+ mk() { git worktree add -q -b "$1" "$t/wt-$1" "$base"; }
72
88
  mk delivered; (cd "$t/wt-delivered" && echo d > d && git add d && git commit -qm d)
73
89
  mk dirty; (cd "$t/wt-dirty" && echo x > x && git add x && git commit -qm x)
74
90
  mk unmerged; (cd "$t/wt-unmerged" && echo u > u && git add u && git commit -qm u)
75
91
  mk fresh # brand new, no commits: must survive
76
- for b in records empty-records locked locked-detached; do
92
+ for b in records empty-records locked locked-detached tracked-records scoped-records ignored live-holder; do
77
93
  mk "$b"; (cd "$t/wt-$b" && echo "$b" > "$b" && git add "$b" && git commit -qm "$b")
94
+ case "$b" in
95
+ tracked-records|scoped-records)
96
+ mkdir "$t/wt-$b/.ai-work"; echo handoff > "$t/wt-$b/.ai-work/.handoff"
97
+ git -C "$t/wt-$b" add .ai-work; git -C "$t/wt-$b" commit -qm records ;;
98
+ esac
78
99
  git merge -q --no-ff "$b" -m "merge $b"
79
100
  done
80
101
  mkdir "$t/wt-records/.ai-work" "$t/wt-empty-records/.ai-work"
81
- echo '.ai-work/' >> "$t/repo/.git/info/exclude"
102
+ printf '.ai-work/\nignored-output\n' >> "$t/repo/.git/info/exclude"
82
103
  echo handoff > "$t/wt-records/.ai-work/.handoff"
104
+ echo build > "$t/wt-ignored/ignored-output"
105
+ (cd "$t/wt-live-holder" && exec sleep 120) & holder=$!
83
106
  git -C "$t/wt-locked-detached" checkout -q --detach
84
107
  git worktree lock "$t/wt-locked"
85
108
  git worktree lock --reason pinned "$t/wt-locked-detached"
@@ -88,7 +111,7 @@ if [ "$SELFTEST" = 1 ]; then
88
111
  git push -q origin main
89
112
  echo junk > "$t/wt-dirty/untracked" # makes the merged worktree dirty
90
113
  out=$("$self" --no-fetch 2>&1) || { echo "FAIL: exit $?"; echo "$out"; exit 1; }
91
- fail=0; chk() { if ! eval "$2"; then echo "FAIL: $1"; fail=1; fi; }
114
+ fail=0; checks=0; chk() { checks=$((checks + 1)); if ! eval "$2"; then echo "FAIL: $1"; fail=1; fi; }
92
115
  chk "delivered worktree removed" '[ ! -d "$t/wt-delivered" ]'
93
116
  chk "delivered branch removed" '! git rev-parse -q --verify refs/heads/delivered >/dev/null'
94
117
  chk "loose merged branch removed" '! git rev-parse -q --verify refs/heads/loose-delivered >/dev/null'
@@ -101,21 +124,32 @@ if [ "$SELFTEST" = 1 ]; then
101
124
  chk "report names the removal" 'grep -q "removed worktree" <<<"$out"'
102
125
  chk "work records kept" '[ -f "$t/wt-records/.ai-work/.handoff" ]'
103
126
  chk "work records branch kept" 'git rev-parse -q --verify refs/heads/records >/dev/null'
104
- chk "work records reason reported" 'grep -Fq "has untracked work records (.ai-work/)" <<<"$out"'
127
+ chk "work records reason reported" 'grep -Fq "has work records (.ai-work/)" <<<"$out"'
105
128
  chk "empty work records removed" '[ ! -d "$t/wt-empty-records" ]'
106
129
  chk "locked worktree kept" '[ -d "$t/wt-locked" ]'
107
130
  chk "locked branch kept" 'git rev-parse -q --verify refs/heads/locked >/dev/null'
108
131
  chk "locked reason reported" 'grep -Fq "worktree $t/wt-locked (locked): locked" <<<"$out"'
109
132
  chk "locked detached kept" '[ -d "$t/wt-locked-detached" ]'
110
133
  chk "locked detached reported" 'grep -Fq "worktree $t/wt-locked-detached (detached): locked" <<<"$out"'
111
- out=$(printf '%s' '{"hook_event_name":"SessionStart"}' | "$self" --no-fetch --include-work-records --hook 2>&1) || { echo "FAIL: hook exit $?"; echo "$out"; exit 1; }
112
- chk "hook ignores opt-in" '[ -f "$t/wt-records/.ai-work/.handoff" ]'
113
- out=$("$self" --no-fetch --include-work-records 2>&1) || { echo "FAIL: opt-in exit $?"; echo "$out"; exit 1; }
114
- chk "opt-in removes work records" '[ ! -d "$t/wt-records" ]'
115
- chk "opt-in removes branch" '! git rev-parse -q --verify refs/heads/records >/dev/null'
134
+ chk "live holder kept" '[ -d "$t/wt-live-holder" ]'
135
+ chk "live holder reason reported" 'grep -F "worktree $t/wt-live-holder (live-holder):" <<<"$out" | grep -E ": (live holder|live process)" >/dev/null'
136
+ chk "ignored file kept" '[ -f "$t/wt-ignored/ignored-output" ]'
137
+ chk "ignored file reason" 'grep -Fq "has ignored/untracked files; archive or remove them first" <<<"$out"'
138
+ out=$("$self" --no-fetch --dry-run 2>&1) || { echo "FAIL: dry-run exit $?"; echo "$out"; exit 1; }
139
+ chk "dry-run reports live holder" 'grep -F "kept worktree $t/wt-live-holder (live-holder):" <<<"$out" | grep -E ": (live holder|live process)" >/dev/null'
140
+ out=$(printf '%s' '{"hook_event_name":"SessionStart"}' | "$self" --no-fetch "--include-work-records=$t/wt-tracked-records" --hook 2>&1) || { echo "FAIL: hook exit $?"; echo "$out"; exit 1; }
141
+ chk "hook ignores opt-in" '[ -f "$t/wt-tracked-records/.ai-work/.handoff" ]'
142
+ out=$("$self" --no-fetch "--include-work-records=$t/wt-records" "--include-work-records=$t/wt-tracked-records" 2>&1) || { echo "FAIL: opt-in exit $?"; echo "$out"; exit 1; }
143
+ chk "opt-in keeps ignored records" '[ -f "$t/wt-records/.ai-work/.handoff" ]'
144
+ chk "opt-in removes tracked records" '[ ! -d "$t/wt-tracked-records" ]'
145
+ chk "opt-in removes branch" '! git rev-parse -q --verify refs/heads/tracked-records >/dev/null'
146
+ chk "opt-in scope preserves others" '[ -f "$t/wt-scoped-records/.ai-work/.handoff" ]'
116
147
  chk "opt-in keeps locked" '[ -d "$t/wt-locked" ]'
117
148
  chk "opt-in keeps locked detached" '[ -d "$t/wt-locked-detached" ]'
118
- [ "$fail" = 0 ] && echo "cratis-cleanup-worktrees self-test: 24 checks passed" && exit 0
149
+ out=$("$self" --include-work-records 2>&1); code=$?
150
+ chk "bare opt-in rejected" "[ '$code' = 2 ]"
151
+ chk "bare opt-in guidance" 'grep -Fq "requires an explicit worktree path" <<<"$out"'
152
+ [ "$fail" = 0 ] && echo "cratis-cleanup-worktrees self-test: $checks checks passed" && exit 0
119
153
  echo "$out"; exit 1
120
154
  fi
121
155
 
@@ -257,19 +291,177 @@ process_worktree() {
257
291
  case "$here/" in "$wt"/*) note_kept "worktree $wt ($name): it is the current directory - run the sweep from the main checkout"; return 0 ;; esac
258
292
  plan_item worktree "$wt" "$sha" "$br"
259
293
  }
294
+ # $$ remains the script's root PID in Bash subshells, including Bash 3.2 without BASHPID.
295
+ # Ancestors are deliberately not excluded: their cwd or open files may hold another worktree.
296
+ check_pi_holders() {
297
+ local target="$1" processes="$2" report code own
298
+ report=$(pi-holders --json "$target" 2>/dev/null); code=$?
299
+ if [ "$code" -gt 1 ]; then HOLDER_REASON="live holder or failed holder check (pi-holders)"; return 1; fi
300
+ command -v jq >/dev/null 2>&1 || { HOLDER_REASON="holder check unavailable (pi-holders JSON requires jq)"; return 1; }
301
+ own=$(awk -v root="$$" '
302
+ { parent[$1] = $2 }
303
+ END {
304
+ for (pid in parent) {
305
+ ancestor = pid
306
+ while (ancestor > 0 && ancestor != root) ancestor = parent[ancestor]
307
+ if (ancestor == root) print pid
308
+ }
309
+ }
310
+ ' <<< "$processes") || { HOLDER_REASON="holder check failed (process inspection)"; return 1; }
311
+ if ! jq -s -e --arg target "$target" --arg own "$own" --argjson code "$code" '
312
+ def positive_pid: tostring | test("^[1-9][0-9]*$");
313
+ def holder:
314
+ type == "object" and (.pid | positive_pid) and (.command | type == "string") and
315
+ (.kind == "cwd" or .kind == "open") and
316
+ (.name | type == "string" and (. == $target or startswith($target + "/")));
317
+ ($own | split("\n")) as $excluded |
318
+ length == 1 and (.[0] |
319
+ type == "object" and (.status == "clear" or .status == "held") and
320
+ ($code == (if .status == "held" then 1 else 0 end)) and
321
+ (.paths | type == "array" and length == 1) and
322
+ (.paths[0] |
323
+ .path == $target and .resolved == $target and (.held | type == "boolean") and
324
+ (.holders | type == "array" and all(.[]; holder)) and
325
+ (.held == (.holders | length > 0)) and .ambiguous == 0) and
326
+ (.paths[0].held == (.status == "held")) and
327
+ all(.paths[0].holders[]; (.pid | tostring) as $pid | $excluded | index($pid) != null)
328
+ )
329
+ ' <<< "$report" >/dev/null 2>&1; then
330
+ HOLDER_REASON="live holder or invalid/ambiguous holder check (pi-holders)"; return 1
331
+ fi
332
+ return 0
333
+ }
334
+ # Parse names, not inode traversal. Incomplete names inside the target (or without any path) are
335
+ # unsafe; incomplete records naming other absolute paths cannot hide a target name in that record.
336
+ # This avoids unrelated FD-info errors from process churn poisoning every candidate.
337
+ lsof_matches() {
338
+ local target="$1" processes="$2" listing="$3"
339
+ awk -v root="$$" -v target="$target" '
340
+ function under_target(path) { return path == target || index(path, target "/") == 1 }
341
+ function unsafe(detail) { if (!bad) first_bad = detail; bad = 1 }
342
+ NR == FNR { parent[$1] = $2; next }
343
+ /^p[1-9][0-9]*$/ {
344
+ pid = substr($0, 2); ignored = 0; ancestor = pid; kind = ""; type = ""; seen_pid = 1
345
+ while (ancestor > 0 && !ignored) {
346
+ if (ancestor == root) ignored = 1
347
+ ancestor = parent[ancestor]
348
+ }
349
+ next
350
+ }
351
+ /^f./ { kind = substr($0, 2); type = ""; next }
352
+ /^t./ { type = substr($0, 2); next }
353
+ /^n/ {
354
+ seen_name = 1; path = substr($0, 2)
355
+ if (ignored || path == "(revoked)") next
356
+ # A diagnostic suffix can follow the target directory itself, not just a child path.
357
+ sub(/ (\(stat:|\(FD info error:|FD info error:).*/, "", path)
358
+ if (under_target(path)) {
359
+ if (!seen_pid || kind == "" || type == "") unsafe("incomplete " kind " " type " " path)
360
+ else print kind "|" path
361
+ } else if (path !~ /^\//) {
362
+ # Kernel/network object names are not filesystem paths. Unix sockets may have paths,
363
+ # so only their non-path addresses are exempt; unknown names may hide a target file.
364
+ if (kind != "cwd" && type ~ /^(PIPE|NPOLICY|NEXUS|KQUEUE|IPv4|IPv6|systm|CHAN)$/) next
365
+ if (kind != "cwd" && type == "unix" && path ~ /^(->0x[[:xdigit:]]+|->\(none\)|@.*|[[:alnum:]_.-]*)$/) next
366
+ # Linux anonymous objects have typed pseudo-names, not filesystem paths.
367
+ # Require a descriptor and a known type/name pair; cwd and incomplete records stay unsafe.
368
+ if (kind != "" && kind != "cwd") {
369
+ if (type == "FIFO" && path ~ /^pipe(:\[[0-9]+\])?$/) next
370
+ if (type == "sock" && path ~ /^(socket:\[[0-9]+\]|protocol: [[:alnum:]_-]+)$/) next
371
+ # Anonymous-inode names are kernel objects whatever the reported type (for example a
372
+ # memory-mapped `anon_inode:[io_uring]` is type REG), so the name alone exempts them.
373
+ if (path ~ /^(anon_inode:)?\[[[:alnum:]_]+(:[0-9]+(,[0-9]+)*)?\]$/) next
374
+ if (type == "a_inode" && path ~ /^(anon_inode:)?[[:alnum:]_]+$/) next
375
+ if (type == "unix" && path ~ /^type=[[:upper:]]+( \([[:upper:]]+\))?$/) next
376
+ if (type == "netlink" && path ~ /^[[:upper:]_]+$/) next
377
+ }
378
+ unsafe("unrecognised " kind " " type " " path)
379
+ }
380
+ next
381
+ }
382
+ { if (!ignored) unsafe("unexpected record " $0) }
383
+ END {
384
+ if (!seen_pid || !seen_name) unsafe("empty listing")
385
+ if (bad) { print "!" first_bad; exit 1 }
386
+ }
387
+ ' <(printf '%s\n' "$processes") <(printf '%s\n' "$listing")
388
+ }
389
+ # One process-wide listing per candidate, retried at most three times before failing closed.
390
+ check_lsof_holders() {
391
+ local target="$1" processes="$2" listing matches detail kind path links attempt
392
+ for attempt in 1 2 3; do
393
+ if ! listing=$(lsof -nP -w -F pfnt 2>/dev/null); then
394
+ HOLDER_REASON="holder check failed (lsof)"; continue
395
+ fi
396
+ if matches=$(lsof_matches "$target" "$processes" "$listing"); then HOLDER_REASON=''; break; fi
397
+ # The first unsafe record is the last output line; builtins only (PATH may be minimal).
398
+ detail=${matches##*$'\n'}
399
+ HOLDER_REASON="holder check failed (path inspection: ${detail#!})"
400
+ done
401
+ [ "$attempt" != 3 ] || [ -z "${HOLDER_REASON:-}" ] || return 1
402
+ while IFS='|' read -r kind path; do
403
+ [ -n "$path" ] || continue
404
+ # Shared hard-link names cannot identify which worktree the process actually holds.
405
+ if [ "$kind" != cwd ] && [ -f "$path" ]; then
406
+ links=$(stat -c '%h' "$path" 2>/dev/null || stat -f '%l' "$path" 2>/dev/null) || links=0
407
+ if ! [[ "$links" =~ ^[0-9]+$ ]] || [ "$links" != 1 ]; then
408
+ HOLDER_REASON="ambiguous holder check (shared or unknown inode: $path)"; return 1
409
+ fi
410
+ fi
411
+ HOLDER_REASON="live process holds worktree ($kind: $path)"; return 1
412
+ done <<< "$matches"
413
+ return 0
414
+ }
415
+ check_holders() {
416
+ local target processes use_pi=0
417
+ HOLDER_REASON=''
418
+ target=$(cd "$1" 2>/dev/null && pwd -P) || { HOLDER_REASON="could not resolve worktree for holder check"; return 1; }
419
+ if command -v pi-holders >/dev/null 2>&1 && command -v jq >/dev/null 2>&1; then use_pi=1
420
+ elif ! command -v lsof >/dev/null 2>&1; then
421
+ HOLDER_REASON="no holder check tool available (pi-holders+jq/lsof)"; return 1
422
+ fi
423
+ processes=$(ps -axo pid=,ppid= 2>/dev/null) || { HOLDER_REASON="holder check failed (ps)"; return 1; }
424
+ if ! awk -v root="$$" '$1 == root { found = 1 } END { exit !found }' <<< "$processes"; then
425
+ HOLDER_REASON="holder check incomplete (ps)"; return 1
426
+ fi
427
+ if [ "$use_pi" = 1 ]; then check_pi_holders "$target" "$processes"
428
+ else check_lsof_holders "$target" "$processes"; fi
429
+ }
430
+ include_work_records() {
431
+ [ "$HOOK" = 0 ] || return 1
432
+ local path target
433
+ target=$(cd "$1" 2>/dev/null && pwd -P) || return 1
434
+ for path in "${WORK_RECORD_PATHS[@]+"${WORK_RECORD_PATHS[@]}"}"; do
435
+ [ "$path" != "$target" ] || return 0
436
+ done
437
+ return 1
438
+ }
439
+ worktree_clean() {
440
+ local status
441
+ if ! status=$(git -C "$wt" status --porcelain --ignored 2>/dev/null); then
442
+ note_kept "worktree $wt ($name): could not inspect worktree status"; return 1
443
+ fi
444
+ if [[ "$status" == '?? '* || "$status" == '!! '* || "$status" == *$'\n?? '* || "$status" == *$'\n!! '* ]]; then
445
+ note_kept "worktree $wt ($name): has ignored/untracked files; archive or remove them first"; return 1
446
+ fi
447
+ if [ -n "$status" ]; then note_kept "worktree $wt ($name): delivered but has uncommitted changes"; return 1; fi
448
+ return 0
449
+ }
260
450
  execute_worktree() {
261
451
  local name="${br:-detached}" ev="$1" current
262
452
  current=$(git -C "$wt" rev-parse HEAD 2>/dev/null) || return 0
263
453
  [ "$current" = "$sha" ] || { note_kept "worktree $wt ($name): tip changed since planning"; return 0; }
264
- if [ "$INCLUDE_WORK_RECORDS" = 0 ] && [ -d "$wt/.ai-work" ]; then
454
+ if ! include_work_records "$wt" && [ -d "$wt/.ai-work" ]; then
265
455
  local records
266
456
  if ! records=$(find "$wt/.ai-work/." -mindepth 1 -maxdepth 1 -print -quit); then
267
457
  note_kept "worktree $wt ($name): could not inspect work records (.ai-work/)"; return 0
268
458
  fi
269
- if [ -n "$records" ]; then note_kept "worktree $wt ($name): has untracked work records (.ai-work/)"; return 0; fi
459
+ if [ -n "$records" ]; then note_kept "worktree $wt ($name): has work records (.ai-work/)"; return 0; fi
270
460
  fi
271
- if [ -n "$(git -C "$wt" status --porcelain 2>/dev/null)" ]; then note_kept "worktree $wt ($name): delivered but has uncommitted changes"; return 0; fi
461
+ worktree_clean || return 0
272
462
  local kb; kb=$(du -sk "$wt" 2>/dev/null | awk '{print $1}')
463
+ if ! check_holders "$wt"; then note_kept "worktree $wt ($name): $HOLDER_REASON"; return 0; fi
464
+ worktree_clean || return 0
273
465
  if [ "$DRY" = 1 ]; then note_removed "worktree $wt ($name): would remove, $ev"; return 0; fi
274
466
  if git worktree remove "$wt" >/dev/null 2>&1; then
275
467
  FREED_KB=$((FREED_KB + ${kb:-0})); note_removed "worktree $wt ($name): $ev"
@@ -82,8 +82,15 @@ cost real disk and accumulate across sessions. After the merge succeeds:
82
82
  It fetches, checks out nothing, and removes only worktrees and local branches whose work is
83
83
  verifiably on the default branch; it never forces and reports what it kept and why. Worktrees holding
84
84
  non-empty `.ai-work/` directories are kept by default. Preserve any needed records before a manual
85
- `--include-work-records` opt-in; automatic hooks never opt in. Use `git worktree lock <path>` to pin a
86
- long-lived worktree; locked worktrees remain kept even with opt-in.
85
+ `--include-work-records=<path>` opt-in (repeatable, exact worktree only; bare flag exits 2).
86
+ This permits clean tracked records, never ignored/untracked files: archive or remove those first,
87
+ including `.ai-work/`. Automatic hooks never opt in. Use `git worktree lock <path>` to pin a
88
+ long-lived worktree; locked and live-held worktrees remain kept even with opt-in. Holder checks
89
+ prefer validated `pi-holders --json` with `jq`, otherwise one process-wide `lsof` name listing per
90
+ candidate (not `+D`, up to three attempts on incomplete/error results). Only the script/descendants
91
+ are excluded; ancestor shells/sessions still count. Unrelated absolute-path FD-info diagnostics do
92
+ not block cleanup; missing tools, unresolved errors, incomplete target/unknown paths and shared-inode
93
+ ambiguity keep it. Status is rechecked after holders, immediately before removal.
87
94
  3. `git switch main && git pull --ff-only` in the main checkout so it matches the merged result.
88
95
 
89
96
  Claude Code and Pi also run the script from a hook after `gh pr merge` and at session start; running it
@@ -44,10 +44,9 @@ dumps, and similar coordination files. These are **work records, not documentati
44
44
  main checkout when a PR merges or you finish a task (hooks and **ship-changes** also run it). It
45
45
  removes a worktree and its branch only on evidence the work reached the default branch —
46
46
  pushed is not merged — and never forces. It keeps worktrees with non-empty `.ai-work/`
47
- directories; manual `--include-work-records` deletes them once you have preserved what you
48
- need; hooks never opt in. Pin a long-lived worktree with `git worktree lock <path>`;
49
- locked worktrees are always kept, even with opt-in. Ignored files (`.env`, local databases) are
50
- deleted with a removed worktree: move what you need out first. Do not hand-remove worktrees
47
+ directories; manual `--include-work-records=<path>` lifts that for that worktree only;
48
+ hooks never opt in. Ignored or untracked files, a live process using it, or a failed holder
49
+ check (hooks README) keep a worktree. `git worktree lock <path>` pins one: locked worktrees are always kept. Do not hand-remove worktrees
51
50
  or `git branch -D` a delivered branch when the script can; `gh pr merge --delete-branch`
52
51
  inside a worktree leaves the worktree and branch behind. If the branch must outlive the task
53
52
  unmerged, leave the worktree and say so in the handoff. Never `--force` a removal; a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.179.2",
3
+ "version": "7.179.3",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [