#!/usr/bin/env bash
# W6 gate rig: isolated worktree at the PR head, own pool, targeted legs + compile gate.
set -uo pipefail
ROOT=/c/Users/decid/Documents/projects/spt-core
SHA=0cb81a8e
RIG="$ROOT/.worktrees/gate-w6-$SHA"
cd "$ROOT" || exit 1

echo "=== WRITER CENSUS (pre-gate) ==="
for img in cargo.exe rustc.exe Runner.Worker.exe; do
  printf '%s: ' "$img"; tasklist //FI "IMAGENAME eq $img" //FO CSV //NH 2>/dev/null | grep -c "$img"
done

[ -d "$RIG" ] || git worktree add --detach "$RIG" "$SHA" || exit 1
cd "$RIG" || exit 1
echo "=== RIG SUBJECT ==="
git rev-parse HEAD

echo "=== POOL CLAIM ==="
cargo run -q -p xtask -- pool-claim --pool "$RIG/target" --label "gate-w6-$SHA" 2>&1 | tail -3
echo "claim_rc=$?"

echo "=== LEG 1: compile gate (check --workspace --all-targets) ==="
CARGO_TARGET_DIR="$RIG/target" cargo check --workspace --all-targets 2>&1 | tail -12
echo "check_rc=${PIPESTATUS[0]}"

echo "=== LEG 2: spt-runtime lib units (changelog render + destination judge) ==="
CARGO_TARGET_DIR="$RIG/target" cargo test -p spt-runtime --lib 2>&1 | tail -12
echo "runtime_rc=${PIPESTATUS[0]}"

echo "=== LEG 3: webserve_e2e (CSP + changelog served) ==="
CARGO_TARGET_DIR="$RIG/target" cargo test -p spt-daemon --test webserve_e2e 2>&1 | tail -12
echo "webserve_rc=${PIPESTATUS[0]}"

echo "=== LEG 4: traceable-reqs ==="
traceable-reqs check 2>&1 | tail -6
echo "treqs_rc=${PIPESTATUS[0]}"

echo "=== WRITER CENSUS (post-gate) ==="
for img in cargo.exe rustc.exe Runner.Worker.exe; do
  printf '%s: ' "$img"; tasklist //FI "IMAGENAME eq $img" //FO CSV //NH 2>/dev/null | grep -c "$img"
done
echo "DONE"
