#!/usr/bin/env bash
# twohost-ladder-local.sh — run BOTH roles of crates/spt-daemon/tests/twohost.rs (the LADDER)
# on ONE box (peer ip 127.0.0.1) as gate leg 9b's witness. Sibling of twohost-web-local.sh,
# parametrized on the TEST binary rather than hardcoding it (doyle ruling 2026-09-08 10:37Z).
#
# Why it exists: XFER retirement (#246) rewrote the ladder's cross-host side-channel — B's
# drive sid, B's B-2 ticker sid and A's completion barrier moved off the retired transfer
# family onto replicated notif rows (SID_SIGNAL / SID2_SIGNAL / LADDER_DONE). A rewritten
# cross-host barrier that no leg runs is UNWITNESSED by construction.
#
# usage: twohost-ladder-local.sh <worktree> <label> [test-binary]
# Writes <worktree>/.spt/twohost-ladder/<label>/{build,b,a}.{raw,exit}
# Identity trio + SPT_HOME are scrubbed for every child (a perch-launched battery inherits the
# endpoint identity and every daemon-stopping arm refuses — memory 2026-09-06).
set -u
GW=$1; LABEL=$2; TESTBIN=${3:-twohost}
OUT=$GW/.spt/twohost-ladder/$LABEL
mkdir -p "$OUT"
cd "$GW" || exit 9
unset OWL_SESSION_ID SPT_AGENT_ID SPT_ENDPOINT_ID SPT_HOME
# ONE BOX ports: A 7460, B 7470 (ten clear, the web rig's measured spacing), the B-2 attacher
# child 7462. Each role sets its own temp SPT_HOME, so each broker socket name is home-tagged
# and neither can collide with the fleet daemon's.
export SPT_TWO_HOST=1 SPT_TWO_HOST_SECRET=rig-ladder-w3 SPT_TWO_HOST_PEER_IP=127.0.0.1 \
       SPT_TWO_HOST_WAIT_SECS=${WAIT:-180} \
       SPT_TWO_HOST_PORT_A=7460 SPT_TWO_HOST_PORT_B=7470 SPT_TWO_HOST_PORT_C=7462

date -u +%FT%TZ > "$OUT/started"
echo "procs-before: $(ps -W 2>/dev/null | grep -ci 'twohost' || true)" | tee "$OUT/procs.before"
# Build once so the two role processes never race cargo's build lock.
cargo nextest run -p spt-daemon --test "$TESTBIN" --no-run > "$OUT/build.raw" 2>&1
echo $? > "$OUT/build.exit"
[ "$(cat "$OUT/build.exit")" = "0" ] || exit 5

SPT_TWO_HOST_ROLE=b cargo nextest run -p spt-daemon --test "$TESTBIN" --no-fail-fast --no-capture \
  > "$OUT/b.raw" 2>&1 &
BPID=$!
echo "$BPID" > "$OUT/b.pid"
sleep 10
SPT_TWO_HOST_ROLE=a cargo nextest run -p spt-daemon --test "$TESTBIN" --no-fail-fast --no-capture \
  > "$OUT/a.raw" 2>&1
echo $? > "$OUT/a.exit"
wait "$BPID"
echo $? > "$OUT/b.exit"
date -u +%FT%TZ > "$OUT/finished"
echo "== $LABEL bin=$TESTBIN a.exit=$(cat "$OUT/a.exit") b.exit=$(cat "$OUT/b.exit") Summaries a=$(grep -c Summary "$OUT/a.raw") b=$(grep -c Summary "$OUT/b.raw")"
grep -E 'PASS|FAIL|panicked at' "$OUT/a.raw" | sed 's/^/A: /'
grep -E 'PASS|FAIL|panicked at' "$OUT/b.raw" | sed 's/^/B: /'
echo "-- barrier + signal witnesses (A raw):"
grep -nE 'ladder-done sent|published its drive session id|published its B-2 ticker session id' "$OUT/a.raw"
echo "-- barrier witness (B raw):"
grep -nE 'ladder-done sent by A|ladder complete' "$OUT/b.raw"
