#!/usr/bin/env bash
# Fourth-cell diagnosis matrix (doyle 16:22Z + deployah's addendum): THREE shas
# x N=5, same cell, same invocation. Counts LIVE presence per run and keeps each
# listener stdout. Standing driver form: sentinel first, integer overwrites,
# reader refuses anything but a bare integer, stale outdir REFUSES.
set -u
GW=$1; OUT=$GW/.spt-ioev-matrix
CELL='binary(io_events_undriven_kinds_e2e)'
FN=relay_backlog_and_live_deliveries_stamp_once_even_after_hook_poll
mkdir "$OUT" 2>/dev/null || { echo "REFUSE: outdir exists"; exit 4; }
cd "$GW" || exit 9
unset OWL_SESSION_ID SPT_AGENT_ID SPT_ENDPOINT_ID SPT_HOME SPT_API_TOKEN

for SHA in fd296557 2f422990 4be9e5c9; do
  echo "VOID:unfinished" > "$OUT/$SHA.checkout"
  git checkout --detach "$SHA" > "$OUT/$SHA.checkout.raw" 2>&1
  echo $? > "$OUT/$SHA.checkout"
  [ "$(cat "$OUT/$SHA.checkout")" = "0" ] || { echo "checkout $SHA FAILED"; continue; }
  echo "sha=$(git rev-parse HEAD)" > "$OUT/$SHA.head"
  powershell -NoProfile -ExecutionPolicy Bypass -File .spt-holders.ps1 > "$OUT/$SHA.holders" 2>&1
  grep -q "holders-remaining: 0" "$OUT/$SHA.holders" || { echo "REFUSE: holders remain at $SHA"; exit 5; }
  for N in 1 2 3 4 5; do
    echo "VOID:unfinished" > "$OUT/$SHA.$N.exit"
    cargo nextest run -p spt --no-fail-fast -E "test($FN)" --test-threads=1 \
      --failure-output immediate-final --success-output final \
      > "$OUT/$SHA.$N.raw" 2>&1
    echo $? > "$OUT/$SHA.$N.exit"
  done
done

{
  for SHA in fd296557 2f422990 4be9e5c9; do
    for N in 1 2 3 4 5; do
      e=$(cat "$OUT/$SHA.$N.exit" 2>/dev/null)
      r="$OUT/$SHA.$N.raw"
      case "$e" in ''|*[!0-9]*) echo "$SHA run$N: EXIT=VOID($e) -- REFUSED";  continue;; esac
      # The cell's own words: it prints the LIVE assert's message on failure.
      live=$(grep -c 'live message reached the receiver' "$r")
      back=$(grep -c 'backlog reached the receiver' "$r")
      pass=$(grep -oE '^ *PASS .*' "$r" | sed 's/.*) //' | sort -u | wc -l)
      fail=$(grep -oE '^ *FAIL .*' "$r" | sed 's/.*) //' | sort -u | wc -l)
      sums=$(grep -c 'Summary' "$r")
      echo "$SHA run$N: exit=$e PASS=$pass FAIL=$fail Summary-lines=$sums live-assert-fired=$live backlog-assert-fired=$back"
    done
  done
} > "$OUT/matrix.txt"
git checkout - > /dev/null 2>&1
echo "MATRIX-DONE"
