#!/usr/bin/env bash
# IR-156 measured leak arm (doyle D3GY32HJ): each predicted leaker SOLO, census spt daemon/brain
# processes by exe path (the rig pool's spt only) before, +5 s and +30 s after; then kill the
# survivors (rig-scoped by exe path) and re-census. Negative control: 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"
t0=$(date +%s); cargo nextest run -p spt $(for b in $BINS; do printf -- '--test %s ' $b; done) --no-run > $O/build.txt 2>&1; echo "$? $(( $(date +%s)-t0 ))s" > $O/build.exit
SPT=$RIG/target/debug/spt
census(){ pgrep -f "^$SPT (daemon|node) (run|brain)" | tr '\n' ' '; }
for b in $BINS; do
  echo "before=$(census)" > $O/$b.census
  nextest_t0=$(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)-nextest_t0 ))s" >> $O/$b.census
  sleep 5;  echo "after5=$(census)" >> $O/$b.census
  sleep 25; P=$(census); echo "after30=$P" >> $O/$b.census
  for p in $P; do echo "pid $p: $(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null | cut -c1-200) home=$(tr '\0' '\n' < /proc/$p/environ 2>/dev/null | grep ^SPT_HOME=)" >> $O/$b.census; done
  for p in $P; do kill -9 $p 2>/dev/null; done; sleep 1
  echo "after-kill=$(census)" >> $O/$b.census
done
date -u +%T > $O/end.txt
