#!/usr/bin/env bash
# doyle's THREE decisive reads on twohost-b's a4 log (Q3 dropped: the resthost outcome is a WIRE
# record, RestRecord::Reply ndjson back to A, never logged at B — zero hits there says nothing).
# Run ONLY when the run is terminal; a partial in-progress log reads as absence.
set -u
REPO="C:/Users/decid/Documents/projects/spt-core"; D="$REPO/.spt/preserved/golden-272-r2-attempt4"
cd "$REPO" || exit 1
ST=$(gh run view 34262154550 --json status -q .status)
NT=$(gh run view 34262154550 --json jobs -q '[.jobs[]|select(.status!="completed")]|length')
echo "gate: status=$ST non_terminal=$NT"
[ "$ST" = "completed" ] && [ "$NT" = "0" ] || { echo "REFUSED: run not terminal."; exit 3; }

BID=$(gh run view 34262154550 --json jobs -q '.jobs[]|select(.name=="twohost-b")|.databaseId')
L="$D/a4-twohost-b-$BID.log"
gh api "repos/BigscreenVR/spt-bs-core/actions/jobs/$BID/logs" > "$L" 2>/dev/null
echo "twohost-b job $BID, bytes=$(stat -c %s "$L")"

# ANCHORS verified verbatim in a3's B log (450047 B) at lines 1045/1077/1089:
A1="A-3: A's setup suspend landed (B suspended)"      # (i) B stalls HERE => intent NOT Suspended => liveness derivation
A2="A-3: A's bare-id ROUTED wake landed (B active)"   # (ii) B stalls HERE => intent ALREADY Suspended before A-3
A3="toast: A's notify rendered via the shell template at B"

echo; echo "########## READ 1: which rig_wait did B panic on ##########"
# NOTE: the timeout/panic FORMAT is unverifiable from a passing log (a3 has zero timeout vocabulary),
# so capture BROADLY with context rather than pattern-matching a shape I have not seen.
grep -nE 'panicked at|FAILED|test result:|timed out|never |within [0-9]+' "$L" | head -20
echo "--- context around the first panic ---"
PL=$(grep -nE 'panicked at' "$L" | head -1 | cut -d: -f1)
[ -n "${PL:-}" ] && sed -n "$((PL-6)),$((PL+8))p" "$L" || echo "(no panic line found)"

echo; echo "########## READ 2: the discriminator — which anchor is present, which is missing ##########"
for A in "$A1" "$A2" "$A3"; do
  n=$(grep -cF "$A" "$L")
  if [ "$n" -gt 0 ]; then grep -nF "$A" "$L" | head -1 | sed 's/^/  PRESENT /'
  else echo "  ABSENT  ($n) $A"; fi
done
echo "--- last TWOHOST OK before the panic, with timestamp ---"
if [ -n "${PL:-}" ]; then awk -v n="$PL" 'NR<n && /TWOHOST OK/ {last=NR": "$0} END{print last}' "$L"
else grep -n 'TWOHOST OK' "$L" | tail -1; fi

echo; echo "########## READ 3: B's toast-rung timestamp vs A's 02:44:22.38Z ##########"
grep -nF "$A3" "$L" || echo "  (toast anchor absent — the rung did not complete at B)"
echo "--- a3 baseline for the same anchors: toast 00:56:31.024Z -> A-3 suspend 00:56:32.026Z = ~1.0 s ---"

echo; echo "########## criteria 5/6 FRESH at a4 (report even though the run is lost) ##########"
grep -nE 'served cell|served all|two_host_web_role_b|two_host_web_helper' "$L" | head -12
