#!/usr/bin/env bash
# IR-156 measured leak arm (doyle D3GY32HJ). Each binary runs SOLO. Census every process running
# `<exe> daemon|node run|brain` (a test may copy spt to a private path, so the exe path is NOT the key);
# NEW = absent from this binary's own baseline. Read at +5 s and +30 s after the run; then kill only NEW
# survivors whose SPT_HOME is under /tmp (a test home), and re-census.
# Negative control FIRST: io_events_poll_e2e (literal daemon stop).
set -u
. ~/.cargo/env
REPO=/home/reavus/projects/spt-core/spt-core; RIG=$REPO/.worktrees/hertz-leak; O=/tmp/hertz-leak-out; MAIN=$1
mkdir -p $O; cd $REPO || exit 9
git fetch -q /tmp/hertz-leak.bundle refs/remotes/origin/main:refs/heads/hertz/leak-main || exit 2
git worktree add -q --detach $RIG $MAIN || exit 3
cd $RIG; git rev-parse HEAD > $O/sha.txt
cargo run -q -p xtask -- pool-claim --pool $RIG/target --label hertz-leak > $O/claim.txt 2>&1; echo $? >> $O/claim.txt
BINS="io_events_poll_e2e poll_envelope_e2e gateway_e2e io_state_payload_e2e listen_seed_retry_e2e shell_hints_e2e shortform_dispatch_e2e active_only_never_relay_e2e"
TESTS=""; for b in $BINS; do TESTS="$TESTS --test $b"; done
t0=$(date +%s); cargo nextest run -p spt $TESTS --no-run > $O/build.txt 2>&1; echo "$? $(( $(date +%s)-t0 ))s" > $O/build.exit
census() { pgrep -f '[ /]spt(\.exe)? (daemon|node) (run|brain)' | sort -n | tr '\n' ' '; }
newpids() { for p in $(census); do case " $1 " in *" $p "*) ;; *) printf '%s ' "$p";; esac; done; }
for b in $BINS; do
  B=$(census); echo "before=$B" > $O/$b.census
  t1=$(date +%s)
  cargo nextest run -p spt --test $b --no-fail-fast > $O/$b.nextest.txt 2>&1; echo $? > $O/$b.exit
  echo "dur=$(( $(date +%s)-t1 ))s" >> $O/$b.census
  sleep 5;  echo "after5_new=$(newpids "$B")" >> $O/$b.census
  sleep 25; P=$(newpids "$B"); echo "after30_new=$P" >> $O/$b.census
  for p in $P; do
    echo "pid $p: $(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null | cut -c1-200) | $(tr '\0' '\n' < /proc/$p/environ 2>/dev/null | grep '^SPT_HOME=')" >> $O/$b.census
  done
  for p in $P; do
    if tr '\0' '\n' < /proc/$p/environ 2>/dev/null | grep -q '^SPT_HOME=/tmp/'; then kill -9 $p 2>/dev/null; fi
  done
  sleep 1; echo "after_kill_new=$(newpids "$B")" >> $O/$b.census
done
date -u +%T > $O/end.txt
