#!/usr/bin/env bash
# ARM A — 15 isolated repeats of the sync cell at ed8ecd94 (doyle-authorized 2026-09-10 ~15:12Z).
# CONTROL for Arm B. NOT a failure-rate estimate.
set -u
ROOT="/c/Users/decid/Documents/projects/spt-core"
W="$ROOT/.worktrees/hertz-294-sync-stages"
OUT="$ROOT/.spt/preserved/deployah-294-armA-20260910"
SHA="ed8ecd94a8a610815d5c2d6b54d3ed0f9d789d56"
TEST='test(=two_tier_sync_lands_and_gate_refuses_server_side)'
mkdir -p "$OUT"

cd "$W" || exit 90
echo "$(git rev-parse HEAD)" > "$OUT/subject.sha"
[ "$(git rev-parse HEAD)" = "$SHA" ] || { echo "SUBJECT SHA MISMATCH" > "$OUT/ABORT"; exit 91; }

# Sequential takeover of hertz's released lane pool, claimed FROM this worktree.
{ echo "cwd=$W"; echo "cargo run -p xtask -- pool-claim --pool target --label deployah-armA"; } > "$OUT/claim.command"
cargo run -p xtask -- pool-claim --pool target --label deployah-armA > "$OUT/claim.log" 2>&1
echo "$?" > "$OUT/claim.exit"

# Build once so run 1 is not build-inflated. Defender's first-touch tax still lands on run 1.
cargo nextest run -p spt-daemon --test sync -E "$TEST" --no-run > "$OUT/build.log" 2>&1
echo "$?" > "$OUT/build.exit"

echo '{"arm":"A","sha":"'"$SHA"'","box":"hfenduleam","worktree":"'"$W"'","pool":"'"$W"'/target","repeats":15,"isolated":true,"started":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}' > "$OUT/RUN.json"

for i in $(seq -w 1 15); do
  S=$(date -u +%Y-%m-%dT%H:%M:%SZ)
  cargo nextest run -p spt-daemon --test sync -E "$TEST" \
      --test-threads=1 --success-output immediate --no-fail-fast \
      > "$OUT/run-$i.log" 2>&1
  RC=$?
  E=$(date -u +%Y-%m-%dT%H:%M:%SZ)
  echo "$RC" > "$OUT/run-$i.exit"
  grep -c '^ *Summary' "$OUT/run-$i.log" > "$OUT/run-$i.summary-count"
  grep -E '^IR294 ' "$OUT/run-$i.log" | sed 's/^IR294 //' > "$OUT/run-$i.events.jsonl"
  printf '{"run":"%s","started":"%s","ended":"%s","exit":%s}\n' "$i" "$S" "$E" "$RC" >> "$OUT/order.jsonl"
done

echo "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$OUT/finished.utc"
