#!/usr/bin/env bash
# Tier 2 + Tier 3 reap (doyle JKY6UQWL / VP3TFJJQ), IR-150 full capture. hertz 2026-09-24.
set -u
R=/home/reavus/projects/spt-core/spt-core/.worktrees
TS="hertz-ir136-fixture hertz-lane1 hertz-w2-proof"
echo "PRE-REGISTERED: reclaim within +/-0.1% of SUM(alloc - escaped_bytes); outside = FINDING. Registered $(date -u +%FT%T.%3NZ) before any measurement."
census(){ echo "WRITERS@$(date -u +%T): $(ps -eo comm= | grep -cE '^(cargo|rustc|cargo-nextest|Runner.Worker|cc1|ld|cc|spt)$') matching procs; loadavg $(cut -d' ' -f1-3 /proc/loadavg)"; ps -eo pid,comm,args | grep -E ' (cargo|rustc|cargo-nextest|Runner.Worker) ' | grep -v grep | cut -c1-120; }
census
SUM=0
for t in $TS; do
  T=$R/$t/target
  echo "== $t"
  echo "OUTBOUND: $(stat -c '%F' $T)  (symlink? $( [ -L $T ] && echo YES || echo no))"
  [ -L $T ] && { echo "ABORT: target is a link"; exit 3; }
  AP=$(du -sb --apparent-size $T | cut -f1); AL=$(du -sB1 $T | cut -f1)
  read EN EB < <(find $T -type f -links +1 -printf '%i %n %s\n' | sort | uniq -c | awk '$1 < $3 { n++; b += $4 } END { print n+0, b+0 }')
  POP=$(find $T -type f -links +1 | wc -l); MAXN=$(find $T -type f -printf '%n\n' | sort -n | tail -1)
  echo "SIZES apparent=$AP allocated=$AL escaped_inodes=$EN escaped_bytes=$EB  (population: files with links>1 = $POP, max nlink = $MAXN)"
  SUM=$((SUM + AL - EB))
  echo "INBOUND symlinks into it: $(find /home/reavus -xdev -type l -lname "*$t/target*" 2>/dev/null | wc -l); mounts: $(findmnt -rn -o TARGET | grep -c "$t/target"); open files: $(lsof +D $T 2>/dev/null | tail -n +2 | wc -l)"
done
# positive control for the escaped-link counter, in a scratch tree on the same fs
C=$(mktemp -d /home/reavus/.hertz-ctl.XXXX); mkdir $C/in; head -c 1000 /dev/zero > $C/in/a; ln $C/in/a $C/in/b; head -c 2000 /dev/zero > $C/in/c; ln $C/in/c $C/out; echo x > $C/in/d
echo "CONTROL escaped counter (expect '1 2000'): $(find $C/in -type f -links +1 -printf '%i %n %s\n' | sort | uniq -c | awk '$1 < $3 { n++; b += $4 } END { print n+0, b+0 }')"; rm -rf $C
echo "EXPECTED reclaim = $SUM"
census
sync; F0=$(df -B1 --output=avail / | tail -1 | tr -d ' '); echo "FREE_BEFORE=$F0 @$(date -u +%T.%3N)"
for t in $TS; do rm -rf $R/$t/target && echo "rm $t/target rc=0 @$(date -u +%T.%3N)"; done
sync; sleep 5; F1=$(df -B1 --output=avail / | tail -1 | tr -d ' '); echo "FREE_AFTER=$F1 @$(date -u +%T.%3N)"
census
D=$((F1 - F0)); echo "RECLAIM=$D EXPECTED=$SUM GAP=$((D - SUM)) PCT=$(awk -v d=$D -v s=$SUM 'BEGIN{printf "%.4f", (d-s)*100/s}')"
for t in $TS; do [ -e $R/$t/target ] && echo "LEFTOVER $t/target" || echo "GONE $t/target"; done
