set +e
TGT=~/actions-runner/_work/spt-core/spt-core/target
KEY=controller_writer_reorder_consumer_view_stays_monotonic_and_session_live
GUARD=re_serve_resets_resume_cursor_after_a_pre_attached_consume
cd ~/actions-runner/_work/spt-core/spt-core
rm -rf /tmp/p1cv /tmp/p1cvr
git worktree add -f --detach /tmp/p1cv bdb51c2 >/dev/null 2>&1 || { echo WT-FAIL; exit 1; }
cd /tmp/p1cv; echo "HEAD=$(git rev-parse --short HEAD)"
CARGO_TARGET_DIR=$TGT timeout 300 cargo test -p spt-daemon --test broker --no-run >/tmp/fb.log 2>&1 || { echo BUILD-FAIL; tail -6 /tmp/fb.log; exit 1; }
echo "== KEYSTONE forkpty 5x =="
kp=0; for i in 1 2 3 4 5; do
  CARGO_TARGET_DIR=$TGT timeout 60 cargo test -p spt-daemon --test broker $KEY -- --exact 2>&1 | grep -q "test result: ok" && { kp=$((kp+1)); echo "key $i: PASS"; } || echo "key $i: FAIL"
done
echo "== GUARD green-normal 5x =="
gp=0; for i in 1 2 3 4 5; do
  CARGO_TARGET_DIR=$TGT timeout 60 cargo test -p spt-daemon --test broker $GUARD -- --exact 2>&1 | grep -q "test result: ok" && { gp=$((gp+1)); echo "guard $i: PASS"; } || echo "guard $i: FAIL"
done
echo "KEY_PASS=$kp/5 GUARD_PASS=$gp/5"
cd ~/actions-runner/_work/spt-core/spt-core && git worktree remove --force /tmp/p1cv 2>/dev/null
echo "== GUARD revert-to-RED (disable subscribe_with reset) =="
git worktree add -f --detach /tmp/p1cvr bdb51c2 >/dev/null 2>&1
cd /tmp/p1cvr
sed -i 's|self.session_cursors.insert(session_id, from_seq);|/* REVERT-TEST */|' crates/spt-daemon/src/brain.rs
echo "patched lines: $(grep -c 'REVERT-TEST' crates/spt-daemon/src/brain.rs)"
rr=0; for i in 1 2 3; do
  CARGO_TARGET_DIR=$TGT timeout 90 cargo test -p spt-daemon --test broker $GUARD -- --exact 2>&1 | grep -q "test result: ok" && echo "revert $i: PASS(BAD)" || { rr=$((rr+1)); echo "revert $i: FAIL(RED-good)"; }
done
echo "REVERT_RED=$rr/3 (want 3/3 = deterministic RED on revert)"
cd ~/actions-runner/_work/spt-core/spt-core && git worktree remove --force /tmp/p1cvr 2>/dev/null; git worktree prune
echo "FINAL-DONE"
