#!/bin/bash
# =============================================================================
# FIELD DRIVER v5 — repaired candidate 53d625cd. FOR SOURCE REVIEW ONLY.
# NOT RUN. NO BUILD GRANT. NO FIELD GRANT. NO ELEVATION GRANT.
# todlando 2026-09-12.
#
# v4 was rejected on ten defects (doyle), on two MEASURED driver-control failures
# (hertz, stub arms), and on doyle's corrections to those findings. v5 is written
# against all of them. Where v4 stated something I had not read, v5 cites the file
# and line I read it in.
#
# WHAT CHANGED, and the defect each change answers:
#
# D1..D10 = doyle's ten. F1..F10 = hertz's source review. C = doyle's corrections.
#
#  D1/F1/C  THREE SEPARATE RESOURCE STATES, each marked BEFORE the dispatch that
#           could create it, each persisted as a FILE so a SIGKILL still leaves the
#           marker: pool_acquired, listener_may_exist, fw_mutation_may_have_occurred.
#           Cleanup acts only on states this run actually marked. hertz MEASURED v4
#           dispatching two product commands and a pool-release after a capacity
#           failure that created nothing; none of those can be reached here.
#           Per C: mutation-may-have-occurred is marked BEFORE the elevated setup is
#           requested, not after it succeeds — a REFUSED setup can leave rules behind.
#  D1       The ORIGINAL failure is preserved: cleanup never overwrites the exit code
#           or the first recorded failure, and cleanup's own failures go to their own
#           file (cleanup-failures.txt) so they cannot be read as the finding.
#  D2/C     NO LINE CLAIMS ELEVATION. The driver ASSERTS it is unelevated (S0a) and
#           refuses to continue if it is. Every elevated action is an explicit HANDOFF
#           to liam: a request file with a nonce, then a receipt, and then the receipt
#           is VERIFIED BY MY OWN CENSUS. A receipt is a claim; the census is evidence.
#  D3       CI axis is spt-bs-core (the CODE repo), job-level, and its exit is GATED.
#           `gh run list` REJECTS --json jobs, and `gh run view --json status` freezes,
#           so the list carries status/conclusion and any non-terminal run is then read
#           with `view --json jobs`. Refreshed after the build as well as before it.
#  D4       Fail closed everywhere. Every producer's exit is read in a guarded branch.
#           A git failure can no longer read as a clean tree: the exit is checked
#           BEFORE the emptiness of its output is interpreted.
#  D5/C     The seed is bound to ITS OWN keygen invocation. Any inherited seed is
#           explicitly discarded; exactly one public_hex and one seed_hex are parsed
#           from that invocation; the seed is exported from what was parsed, so the
#           signer's key IS the generated key by construction. The value is never
#           echoed, never recorded, and lives only under a 0700 dir that cleanup reaps.
#  D6       THREE-WAY provenance: the executable's measured sha256, the staged
#           artifact's measured sha256, and the artifact_sha256 inside the SIGNED
#           metadata must all be equal.
#  D7       Every trial enforces its ARM's pair state before AND after, the expected
#           PORT and BINDER (listener path == the built executable), a successful
#           listener stop with the per-arm stop signature, and a VALID CPU capture.
#  D8       THE VERDICT STRINGS ARE THE PRODUCT'S, READ AT THIS SHA. v4 matched
#           LAN_FIREWALL_VERIFIED and "LAN admission verified"; NEITHER EXISTS in
#           crates/. See the CONTRACT block below for what does.
#  D9/F8    D1 runs on setup REJECTION too, BEFORE any teardown is requested, and a
#           failed D1 can no longer finish at exit 0 calling the run complete.
#  D10      A pre-existing evidence dir or isolated home is REJECTED, never truncated.
#  F2/C     Signals terminate normal execution and enter state-aware cleanup EXACTLY
#           ONCE. No trial resumes after a signal. SIGKILL remains a residual and is
#           named as one, with the state markers on disk as the recovery instruction.
#  F3       The 5470 field comparison brackets the ELEVATED actions too, and a FINAL
#           post-cleanup comparison runs. v4 bracketed only the low-risk population.
#  F4/F5    The evidence dir is per-run and timestamped, so no assertion can be
#           satisfied by a PRIOR run's row and no rerun destroys the record it should
#           be compared against. Nothing is truncated.
#  F6       diff is read as 0 same / 1 changed / >=2 INSTRUMENT FAILURE. An unreadable
#           snapshot must not be announced as "5470 CHANGED".
#  F7       The capacity floor is read immediately before EVERY producer, and the hard
#           stop is evaluated, not just the admission floor.
#  F9       refusal faces are COUNTED, ALL of them reported, and the verdict taken by a
#           written-down precedence — not by whichever grep happens to run last.
#  F10/C    Instruments live in a separate dir from results, AND every instrument's
#           sha256 is written into the evidence dir, because placement is not provenance.
#  hertz Q3 Occurrences are counted with grep -o, not grep -c: two subject records on
#           one line would count as one line and defeat the >1 guard.
#  C        [ -f ] on a file run_cmd already created cannot fail, and -s is NOT proof of
#           execution. Launch/capture failures get their OWN status; an empty stderr is
#           classified as a MISSING-ROW OUTCOME, which is a measurement, not an error.
#
# ---------------------------------------------------------------------------
# PRODUCT CONTRACT, read at 53d625cd. Nothing below is remembered or guessed.
#
#   serveverb.rs:180-187   Lan{bootstrap:false,stop:false} builds LanStatus. A timed
#                          call without --bootstrap QUERIES A STOPPED LISTENER (v3's
#                          withdrawn command).
#   serveverb.rs:233-249   The LanUp arm prints LAN_BOOTSTRAP_UP, the sha256 anchors
#                          and LAN-EXPOSED, calls report_lan_admission, and RETURNS 0
#                          UNCONDITIONALLY. report_lan_admission returns unit, and
#                          reconcile_lan_firewall's i32 is DISCARDED at :371 and :387.
#                          => `serve lan --bootstrap` EXITS 0 EVEN WHEN UNVERIFIED.
#                          So a zero exit is NECESSARY BUT NOT SUFFICIENT (doyle): a
#                          nonzero rc is a real control error (:170,:192,:198) and is
#                          never accepted, while a zero carries no admission
#                          information on its own and is checked alongside the verdict
#                          line and the pair census.
#   serveverb.rs:297-302   print_lan_admission -> LAN_FIREWALL_RECONCILED (stdout).
#                          THE positive admission verdict.
#   serveverb.rs:311       lan_firewall_warning -> LAN_FIREWALL_UNVERIFIED (stderr)
#   serveverb.rs:318       lan_cleanup_warning  -> LAN_FIREWALL_CLEANUP_UNVERIFIED
#   serveverb.rs:331       LAN_FIREWALL_MUTATION_DISABLED — the opt-out refusing a
#                          mutation. Its PRESENCE in a trial proves verify() did not
#                          return Ok(true) (the Ok(true) arm returns at :357 before
#                          request_lan_firewall is reached).
#   serveverb.rs:341/345   LAN_FIREWALL_REPAIR_REQUESTED / _ELEVATION_UNAVAILABLE.
#                          "Launching it is not proof of admission or cleanup" — the
#                          product says so itself; treated as neither.
#   serveverb.rs:379       LAN_FIREWALL_CLEAN — is_clean() Ok(true) on a stop.
#   lanhost.rs:81          LAN_BOOTSTRAP_ALREADY_UP. In a trial this means THE PREVIOUS
#                          STOP FAILED and the wall measures a different path => VOID.
#   serveverb.rs:376-391   report_lan_cleanup: is_clean Ok(false), UNELEVATED, goes to
#                          request_lan_firewall, which the opt-out REFUSES — so THE
#                          PAIR IS RETAINED. That is what makes Arm B repeatable, and
#                          the retention is EVIDENCED by MUTATION_DISABLED +
#                          CLEANUP_UNVERIFIED together, then measured by census.
#   bootstrap_firewall.rs:19-25   mutation_permitted errors when SPT_INSTALL_NO_FIREWALL
#                          is set. It gates ONLY request_lan_firewall (serveverb:330)
#                          and reconcile_lan_firewall (:486). verify() :29-37 is NOT
#                          gated, so the verify-query leg still runs: listener up,
#                          exactly one verify-query, no elevation, no reconcile.
#   bootstrap_firewall.rs:99-109  THE SUBJECT ROW, on stderr:
#                          bootstrap-firewall leg=<leg> program=<p> wall_ms=<n> outcome=<o>
#                          The wall is measured INSIDE the process around the child,
#                          the same boundary the 3000 ms budget is enforced at
#                          (:136-188). NOT comparable with a Measure-Command wall.
#   bootstrap_firewall.rs:120-126 outcome(): killed beats failed; killed and failed are
#                          DIFFERENT findings.
#   windows.rs:676/801/889 The only three legs: verify-query, reconcile-write, cleanup.
#                          A trial must show exactly ONE verify-query and no others.
#   windows.rs:713-756     decide() order: duplicate-name hygiene, THEN
#                          pair_satisfied_by (:723) -> Ok(false), THEN source store
#                          (:731), THEN LAN scope (:745), THEN enforcement (:749).
#                          BECAUSE pair_satisfied_by IS CHECKED FIRST, reaching the
#                          enforcement arm PROVES the pair matched. That is the
#                          representation-accepted discriminator, and the reason it is.
#   windows.rs:817         mismatch_message is reachable ONLY from reconcile()'s
#                          post-write re-verification. An UNELEVATED trial with a
#                          mismatched pair gets decide() Ok(false), which :362 renders
#                          as the GENERIC "owned admission is absent or does not match
#                          the listener" — THE SAME STRING ARM A PRODUCES WITH NO PAIR.
#                          So ABSENT and MISSPELLED are indistinguishable at the trial's
#                          product surface, and THE CENSUS IS WHAT SUPPLIES THE ARM.
#                          This corrects my own registered outcome table.
#   windows.rs:816         reconcile() re-verifies after writing, so
#                          LAN_FIREWALL_RECONCILED from the ELEVATED setup DOES imply
#                          verify() returned Ok(true) at that instant.
#   windows.rs:675-680 / bootstrap_firewall.rs:136-188
#                          snapshot() hands stdout straight to serde_json; run_bounded
#                          pipes with a 1 MiB cap and no tee. The product's
#                          failure-time matcher input is UNRECOVERABLE at this sha.
#                          D1 is out-of-band and bounds host spellings only.
#   xtask/src/main.rs:2204-2218  debug-keygen prints, one each:
#                          "key_id:     <id>" / "public_hex: <hex>" / "seed_hex:   <hex>"
#   xtask/src/main.rs:2708-2712  debug-rollout derives its signing identity FROM
#                          SPT_DEBUG_RELEASE_SEED. :2717 panics "seed is hex" on a bad
#                          one — where A7's S3 died.
#   xtask/src/main.rs:2504 DEBUG_ROLLOUT_STAGED version=.. channel=.. platforms=.. stage_dir=..
#   xtask/src/main.rs:2295 DEBUG_MARKED_APPLIED version=.. releases=..
#   relcache.rs:35/39/266  The staged set is <stage>/release.json (a SignedUpdateSet
#                          with metadata_json + signature_hex) and
#                          <stage>/artifacts/<platform>.bin.
#   xtask/src/main.rs:2738-2746  --build-current builds with
#                          `cargo build --release -p spt --bin spt` at the workspace
#                          root and takes target/release/spt.exe. A CARGO PRODUCER
#                          RUNS INSIDE THIS VERB, so the capacity floor precedes it.
#
# NO `set -e`: it can exit before a failure is RECORDED and before state-aware
# cleanup runs. Every command's exit is captured immediately in a guarded branch.
# =============================================================================

# ---- configuration ---------------------------------------------------------
W='C:/Users/decid/Documents/projects/spt-core/.worktrees/304-w2-repr'
SP='C:/Users/decid/AppData/Local/Temp/claude/C--Users-decid-Documents-projects-spt-core/291081e5-a375-43ea-81a8-f0e1b7e15a41/scratchpad'
BIN="$SP/fp-bin"                  # INSTRUMENTS — never written to by a run
RUN_ROOT="$SP/fp-run"             # one timestamped subdir per run
H="$SP/fp-home"                   # isolated SPT_HOME, this experiment only
EXE="$W/target/release/spt.exe"   # RELEASE, built by debug-rollout --build-current
PORT=29470                        # never 5470
GUARD_PORT=5470                   # the production port this run must not disturb
TRIPLE='x86_64-pc-windows-msvc'
LANE='fp-53d625cd'
KEY_ID='fp-debug-2026'
SUBJECT_SHA='53d625cd0bd88a04815efdf6c8209a3096bf53e8'
SUBJECT_BLOB='c28874ef6823a7bb522168514ac81c16ddd427d5'
FLOOR_GIB=96                      # producer-admission floor
HARD_STOP_GIB=32                  # below this a resource red is an UNTESTED lane
HANDOFF_WAIT_S=900                # bounded wait for a liam receipt in the normal flow
CLEANUP_HANDOFF_WAIT_S=300        # separate, shorter bound inside cleanup, so a missing
                                  # receipt cannot hold the independent teardown steps open
CI_REPO='BigscreenVR/spt-bs-core' # the CODE repo (D3). Issues live elsewhere.

ORIGINAL_RC=0                     # the FIRST failure's code; cleanup never changes it
ORIGINAL_WHY=''
ABORT=0
CLEANUP_ENTERED=0
CLEANUP_FAILURES=0
D1_OK=unknown
HANDOFF_SEQ=0
HO_SEQ=''; HO_NONCE=''; HO_RECEIPT=''; HO_OUT=''; HO_ERR=''

# ---- evidence dir: per-run, never reused, never truncated (F4/F5/D10) -------
RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)"
R="$RUN_ROOT/$RUN_ID"
if [ -e "$R" ]; then
  echo "REFUSED: evidence dir $R already exists. A run never truncates prior evidence (D10)." >&2
  exit 64
fi
mkdir -p "$R" || { echo "REFUSED: cannot create evidence dir $R" >&2; exit 64; }
ST="$R/state"; mkdir -p "$ST"
mkdir -p "$R/handoff"
SECRET="$R/.secret"; mkdir -p "$SECRET"; chmod 700 "$SECRET" 2>/dev/null

stamp()  { echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) $1" >> "$R/timeline.txt"; }
record() { echo "$1" | tee -a "$R/findings.txt"; }
exits()  { echo "$1" >> "$R/exits.txt"; }
cfail()  { echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) $1" >> "$R/cleanup-failures.txt"; CLEANUP_FAILURES=$((CLEANUP_FAILURES + 1)); }

# The first failure owns the exit code and the verdict. Later noise cannot replace it.
set_original() {
  if [ "$ORIGINAL_RC" -eq 0 ]; then ORIGINAL_RC="$1"; ORIGINAL_WHY="$2"; fi
}

# ---- resource state: marked BEFORE the dispatch that could create it -------
# On disk, so a SIGKILL or a power loss still leaves the marker for whoever cleans up.
mark_state() { echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) $2" > "$ST/$1"; record "STATE_MARKED $1 — $2"; }
has_state()  { [ -f "$ST/$1" ]; }

# ---- run_cmd: launch, capture and product-exit are THREE different answers -
# Pre-creating the capture files answers "can I capture at all". rc 126/127 answers
# "did it launch". Everything else is the product's own exit. An EMPTY capture is
# neither of those — it is a missing-row OUTCOME, classified where rows are counted.
run_cmd() {
  local tag="$1" out="$2" err="$3"; shift 3
  [ "$1" = '--' ] && shift || { record "HARNESS_BUG run_cmd $tag called without --"; exits "${tag}_HARNESS=bad-call"; return 90; }
  if ! : > "$out" 2>/dev/null; then
    exits "${tag}_CAPTURE=SETUP_FAILED_STDOUT"; record "CAPTURE_SETUP_FAILED $tag stdout=$out"; return 91
  fi
  if ! : > "$err" 2>/dev/null; then
    exits "${tag}_CAPTURE=SETUP_FAILED_STDERR"; record "CAPTURE_SETUP_FAILED $tag stderr=$err"; return 91
  fi
  stamp "${tag}_START"
  "$@" > "$out" 2> "$err"
  local rc=$?
  case "$rc" in
    127) exits "${tag}_LAUNCH=NOT_FOUND";     record "NOT_LAUNCHED $tag — command not found (rc 127), NOT a product exit" ;;
    126) exits "${tag}_LAUNCH=NOT_EXECUTABLE"; record "NOT_LAUNCHED $tag — not executable (rc 126), NOT a product exit" ;;
    *)   exits "${tag}_LAUNCH=OK" ;;
  esac
  exits "${tag}_EXIT=$rc"
  stamp "${tag}_END rc=$rc"
  return $rc
}

die() {
  set_original 1 "$1"
  record "HALT: $1"
  exit 1
}
void() {
  set_original 2 "VOID: $1"
  record "VOID: $1 — investigation stops here; no further trial runs"
  exit 2
}

# ---- 5470 preservation: FIELDS, and diff's three distinct answers (F3/F6) --
guard_snapshot() { # TAG
  pwsh -NoProfile -File "$BIN/portfields.ps1" -Tag "$1" -OutDir "$R" -Port "$GUARD_PORT" >> "$R/portfields.log" 2>&1
  local rc=$?
  exits "portfields_${GUARD_PORT}_$1_EXIT=$rc"
  if [ "$rc" -ne 0 ]; then return 1; fi
  grep -q "tag=$1 .* valid=YES" "$R/portfields.log" || return 1
  return 0
}
guard_baseline_taken=0
guard_assert() { # TAG — compares against the baseline and classifies diff's exit
  local tag="$1"
  if [ "$guard_baseline_taken" -ne 1 ]; then
    record "GUARD_ASSERT_SKIPPED $tag — no baseline was taken; nothing to compare against"
    return 2
  fi
  if ! guard_snapshot "$tag"; then
    record "GUARD_SNAPSHOT_FAILED $tag — instrument failure, NOT a statement about $GUARD_PORT"
    return 2
  fi
  local a="$R/portfields-$GUARD_PORT-guard-baseline.txt"
  local b="$R/portfields-$GUARD_PORT-$tag.txt"
  diff -u "$a" "$b" > "$R/guard-$tag.diff" 2>&1
  local drc=$?
  case "$drc" in
    0) record "GUARD_UNCHANGED $tag — $GUARD_PORT rule fields and listener identity identical"; return 0 ;;
    1) record "GUARD_CHANGED $tag — $GUARD_PORT fields or listener identity DIFFER; see guard-$tag.diff"; return 1 ;;
    *) record "GUARD_INSTRUMENT_FAILED $tag — diff exit $drc (unreadable snapshot); this says NOTHING about $GUARD_PORT"; return 2 ;;
  esac
}

# ---- liam handoff: a receipt is a claim; my own census is the evidence (D2) -
# The driver NEVER elevates. It writes exactly what it needs run, waits for a
# receipt carrying its nonce, and then MEASURES. If the measurement disagrees with
# the receipt, the measurement wins and the run halts.
# THE RETURN CHANNEL CARRIES NO LOG OUTPUT, AND NO STATE IS ALLOCATED IN A SUBSHELL.
# v5 defect (doyle): this was called as spec=$(handoff_request ...) while `record` tees to
# stdout, so the captured spec contained the log line as well as the value, and the
# HANDOFF_SEQ increment happened in the command-substitution subshell and was lost --
# every request would have been seq 001. Fixed by removing the substitution entirely:
# this sets PARENT globals and returns nothing on stdout.
#   HO_SEQ  HO_NONCE  HO_RECEIPT  HO_OUT  HO_ERR
handoff_request() { # NAME  DESCRIPTION  COMMAND-TEXT
  HANDOFF_SEQ=$((HANDOFF_SEQ + 1))
  local seq; seq=$(printf '%03d' "$HANDOFF_SEQ")
  local nonce="$RUN_ID-$seq-$$"
  local req="$R/handoff/$seq-$1-request.txt"
  HO_SEQ="$seq"
  HO_NONCE="$nonce"
  HO_RECEIPT="$R/handoff/$seq-$1-receipt.txt"
  HO_OUT="$R/handoff/$seq-$1-command.out"
  HO_ERR="$R/handoff/$seq-$1-command.err"
  {
    echo "HANDOFF_REQUEST $1"
    echo "nonce: $nonce"
    echo "run: $RUN_ID"
    echo "requested_utc: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
    echo "for: $2"
    echo "elevation: REQUIRED — the trial driver is unelevated by assertion (S0a) and will not run this itself"
    echo "run_exactly:"
    echo "$3"
    echo "receipt_file: $HO_RECEIPT"
    echo "redirect_stdout_to: $HO_OUT"
    echo "redirect_stderr_to: $HO_ERR"
    echo "receipt_must_contain a line EXACTLY: nonce: $nonce"
    echo "receipt_must_also_contain: a line 'exit=<N>' giving the command's ACTUAL exit status."
    echo "  A zero exit is a NECESSARY condition for accepting this action (doyle): a nonzero"
    echo "  control error is never accepted, and a zero exit is never sufficient on its own --"
    echo "  the verdict line and the pair census are checked too, by me, afterwards."
  } > "$req"
  record "HANDOFF_REQUESTED $1 seq=$seq nonce=$nonce req=$req"
  return 0
}
# CONTEXT decides what a signal means here (doyle's v5 blocker 5): in the NORMAL flow a
# signal must stop us waiting, but the AUTHORIZED TEARDOWN is the one thing that still
# needs to complete after a signal -- otherwise a Ctrl-C guarantees rules are left behind,
# which is the opposite of what signal handling is for. So:
#   context=trial    ABORT stops the wait (and no trial resumes: trial() calls
#                    abort_check, and cleanup is terminal -- it never returns to the flow)
#   context=cleanup  ABORT does NOT stop the wait. Waiting for a teardown receipt is not
#                    resuming work; it is finishing the only obligation left. The wait is
#                    separately bounded by CLEANUP_HANDOFF_WAIT_S so it cannot hold the
#                    remaining independent teardown steps open indefinitely.
handoff_await() { # CONTEXT(trial|cleanup)
  local context="$1"
  local rf="$HO_RECEIPT" nonce="$HO_NONCE"
  local limit="$HANDOFF_WAIT_S"
  [ "$context" = cleanup ] && limit="$CLEANUP_HANDOFF_WAIT_S"
  local waited=0
  while [ "$waited" -lt "$limit" ]; do
    if [ -f "$rf" ]; then
      # EXACT, WHOLE-LINE nonce match. An unanchored substring match would accept a
      # receipt that merely quotes the nonce inside other text.
      local nmatch; nmatch=$(grep -c "^nonce: $nonce\$" "$rf" 2>/dev/null)
      case "$nmatch" in (''|*[!0-9]*) nmatch=0 ;; esac
      if [ "$nmatch" -eq 1 ]; then
        record "HANDOFF_RECEIPT_PRESENT $rf (exactly one exact nonce line) — a CLAIM; the census below is the verification"
        return 0
      fi
      record "HANDOFF_RECEIPT_REJECTED $rf — expected exactly one line 'nonce: $nonce', found $nmatch"
      return 1
    fi
    if [ "$ABORT" -eq 1 ] && [ "$context" != cleanup ]; then
      record "HANDOFF_WAIT_ABORTED (signal) — not waiting further in the $context flow"
      return 1
    fi
    sleep 5
    waited=$((waited + 5))
  done
  record "HANDOFF_TIMEOUT after ${limit}s with no receipt at $rf (context=$context)"
  return 1
}
# The exit status of a command this driver did not run. It comes back in the receipt,
# and it is a NECESSARY condition, never a sufficient one: an absent or unparseable
# exit is treated as a failure, because an unread exit is not a zero one.
# EXACTLY ONE COMPLETE RECORD, OR 255. v5 took the FIRST substring matching exit=, so a
# receipt carrying two exit records, or the text 'exit=0' inside a sentence, would have
# been accepted (doyle). The record must be a WHOLE LINE and must occur exactly once;
# anything else is malformed and counts as 255, because an unread exit is not a zero one.
handoff_exit() { # (reads HO_RECEIPT)
  local rf="$HO_RECEIPT"
  local c; c=$(grep -c '^exit=[0-9][0-9]*$' "$rf" 2>/dev/null)
  case "$c" in (''|*[!0-9]*) c=0 ;; esac
  if [ "$c" -ne 1 ]; then echo 255; return; fi
  local n; n=$(grep '^exit=[0-9][0-9]*$' "$rf" | head -1 | cut -d= -f2)
  case "$n" in (''|*[!0-9]*) echo 255; return ;; esac
  echo "$n"
}

# ---- state-aware cleanup, entered EXACTLY ONCE (D1/F1/F2/C) ----------------
# EVERY STEP RUNS. NO STEP IS SKIPPED BECAUSE AN EARLIER ONE FAILED, and no check in
# here may terminate the function (doyle's v5 blocker 4). The rule is structural: inside
# cleanup, failures go to cfail() and a counter, never to die() or void(); guard_assert is
# called for its RECORDED STATUS and its return value is not allowed to decide control
# flow here.
#
# MEASURED, because the blocker named a mechanism I could not reproduce: guard_assert as
# written has no exit path at all — every arm ends in `return 0|1|2`, and nothing else
# reachable from cleanup calls die or exit. So a guard_assert cannot today skip the daemon
# shutdown or the pool release. The REQUIREMENT is right even though that path is not
# present, so it is now enforced by construction rather than left to inspection, and the
# real ordering hazard adjacent to it IS fixed: in v5 the teardown handoff could block for
# up to 900s ahead of the daemon stop and pool release, so those independent steps waited
# on a receipt that might never come. The cleanup wait is now separately bounded by
# CLEANUP_HANDOFF_WAIT_S, and a missing receipt leaves the state marker set and proceeds.
#
# The firewall teardown must stay AHEAD of the daemon stop: `serve lan --stop` reaches the
# broker through ensure_running (serveverb.rs:191), so stopping the daemon first would
# make the teardown spawn a fresh one. The order is a dependency, not a preference.
cleanup() {
  [ "$CLEANUP_ENTERED" -eq 1 ] && return 0
  CLEANUP_ENTERED=1
  record "CLEANUP_BEGIN states=[$(ls "$ST" 2>/dev/null | tr '\n' ' ')]"

  # 1. The listener. AUTHORITY: mine — unelevated, opt-out set, so the pair cannot
  #    be removed by it (bootstrap_firewall.rs:19-25 gating serveverb.rs:330).
  if has_state listener_may_exist; then
    run_cmd cleanup_stop "$R/cleanup-stop.out" "$R/cleanup-stop.err" -- \
      env SPT_INSTALL_NO_FIREWALL=1 SPT_HOME="$H" "$EXE" serve lan --stop
    [ $? -eq 0 ] || cfail "unelevated opt-out stop returned nonzero; see cleanup-stop.err"
  else
    record "CLEANUP_SKIP listener — no listener_may_exist state was ever marked"
  fi

  # 2. Host firewall. AUTHORITY: NOT mine. Resource state and cleanup authority are
  #    different questions (C): the state says something may need removing, and the
  #    handoff is the only way this driver can ask for it.
  if has_state fw_mutation_may_have_occurred; then
    guard_assert cleanup-pre-teardown     # status recorded; it cannot exit (see note above)
    handoff_request teardown \
      "remove bootstrap-owned TCP admission created or possibly created by this run" \
      "env -u SPT_INSTALL_NO_FIREWALL SPT_HOME=$H $EXE serve lan --stop"
    # context=cleanup: a signal must NOT stop us waiting for the teardown receipt.
    if handoff_await cleanup; then
      # FOUR CONDITIONS, ALL REQUIRED, before anything is called verified (doyle's v5
      # blocker 3). v5 declared TEARDOWN_VERIFIED on the census GREP alone — it read
      # neither the receipt's exit nor the census command's own exit, so a failed census
      # or a nonzero teardown could have been announced as a verified teardown.
      local t_rc; t_rc=$(handoff_exit)
      exits "cleanup_teardown_receipt_EXIT=$t_rc"
      pwsh -NoProfile -File "$BIN/census.ps1" -Tag cleanup-teardown-post -OutDir "$R" >> "$R/census.log" 2>&1
      local c_rc=$?
      exits "census_cleanup_teardown_post_EXIT=$c_rc"
      local verdict=0 absent=0 valid=0
      grep -q 'LAN_FIREWALL_CLEAN' "$HO_OUT" 2>/dev/null && verdict=1
      grep -q 'tag=cleanup-teardown-post .* subj_group=0 subj_29470=0' "$R/census.log" && absent=1
      grep -q 'tag=cleanup-teardown-post .* valid=YES' "$R/census.log" && valid=1
      record "TEARDOWN_CHECK receipt_exit=$t_rc census_exit=$c_rc clean_verdict=$verdict named_rules_absent=$absent census_valid=$valid"
      if [ "$t_rc" -eq 0 ] && [ "$c_rc" -eq 0 ] && [ "$verdict" -eq 1 ] && [ "$absent" -eq 1 ] && [ "$valid" -eq 1 ]; then
        record "TEARDOWN_VERIFIED — zero teardown exit AND a successful census AND the product's own LAN_FIREWALL_CLEAN verdict AND the owned named rules measured ABSENT"
      else
        cfail "TEARDOWN NOT VERIFIED (receipt_exit=$t_rc census_exit=$c_rc clean_verdict=$verdict absent=$absent census_valid=$valid). Owned rules MAY REMAIN. The state marker is left set deliberately."
      fi
    else
      cfail "no verified teardown receipt; bootstrap-owned rules MAY REMAIN. State markers left in $ST deliberately."
    fi
  else
    record "CLEANUP_SKIP firewall — no fw_mutation_may_have_occurred state was ever marked"
  fi

  # 3. Isolated daemon. OWL_SESSION_ID IS LEFT INTACT: clearing it bypasses a refusal
  #    guard doyle has not approved. A refusal is REPORTED; nothing is force-reaped.
  if has_state daemon_may_run; then
    run_cmd rig_daemon_stop "$R/rig-daemon-stop.out" "$R/rig-daemon-stop.err" -- \
      env SPT_HOME="$H" "$EXE" daemon stop
    if [ $? -ne 0 ]; then
      cfail "isolated daemon stop refused or errored — REPORTED, not forced. See rig-daemon-stop.err"
    fi
  else
    record "CLEANUP_SKIP daemon — no daemon_may_run state was ever marked"
  fi

  # 4. The build pool. Released only if THIS run claimed it.
  if has_state pool_acquired; then
    ( cd "$W" && cargo run -p xtask -- pool-release --pool "$W/target" ) > "$R/pool-release.out" 2>&1
    local prc=$?
    exits "pool_release_EXIT=$prc"
    [ "$prc" -eq 0 ] || cfail "pool-release exit $prc; the pool may still read as claimed"
  else
    record "CLEANUP_SKIP pool — no pool_acquired state was ever marked"
  fi

  # 5. The secret dir never outlives the run.
  rm -rf "$SECRET" 2>/dev/null || cfail "could not remove $SECRET"

  # 6. FINAL 5470 comparison — the one v4 never took (F3).
  guard_assert final-post-cleanup
  record "CLEANUP_END steps_failed=$CLEANUP_FAILURES original_rc=$ORIGINAL_RC original_why=[$ORIGINAL_WHY]"
  if [ "$CLEANUP_FAILURES" -gt 0 ]; then
    record "CLEANUP_HAD_FAILURES=$CLEANUP_FAILURES — every step still RAN; see cleanup-failures.txt."
    record "  These are REPORTED SEPARATELY and do NOT replace the original finding, and they do not"
    record "  change the exit code: the first failure owns that (original_rc=$ORIGINAL_RC)."
  fi
}

on_signal() { # SIG
  # Normal execution TERMINATES here (C). No trial resumes after this.
  ABORT=1
  set_original 130 "signal $1"
  record "SIGNAL $1 — normal execution terminated; entering state-aware cleanup once; NO trial will resume"
  cleanup
  exit 130
}
trap 'on_signal INT'  INT
trap 'on_signal TERM' TERM
trap 'on_signal HUP'  HUP
trap cleanup EXIT
# RESIDUAL, named rather than papered over: SIGKILL and power loss run nothing. The
# state markers in $ST are the recovery instruction — read them and the last
# portfields snapshot BEFORE anything else touches this box.

abort_check() { [ "$ABORT" -eq 0 ] || void "aborted by signal before this step"; }

# ---- capacity, before EVERY producer (F7) ----------------------------------
capacity_gate() { # LABEL
  local label="$1" out="$R/capacity-$1.out"
  pwsh -NoProfile -Command '$d=Get-PSDrive C; "FREE_GIB={0:N2}" -f ($d.Free/1GB)' > "$out" 2>&1
  local rc=$?
  exits "capacity_${label}_EXIT=$rc"
  [ "$rc" -eq 0 ] || die "capacity probe for '$label' exited $rc — a producer must not start on an unmeasured disk"
  local free; free=$(sed -n 's/^FREE_GIB=//p' "$out" | tr -d ',')
  [ -n "$free" ] || die "capacity probe for '$label' produced no FREE_GIB row"
  case "$free" in (*[!0-9.]*) die "capacity probe for '$label' produced a non-numeric FREE_GIB: '$free'" ;; esac
  if awk -v f="$free" -v s="$HARD_STOP_GIB" 'BEGIN{exit !(f+0 < s)}'; then
    die "free ${free} GiB is below the ${HARD_STOP_GIB} GiB HARD STOP before '$label' — a resource red here is an UNTESTED lane, not a product result"
  fi
  if awk -v f="$free" -v s="$FLOOR_GIB" 'BEGIN{exit !(f+0 < s)}'; then
    die "free ${free} GiB is below the ${FLOOR_GIB} GiB producer-admission floor before '$label'"
  fi
  record "CAPACITY ok before '$label': free=${free} GiB (GiB = /1073741824, not decimal GB) floor=${FLOOR_GIB} hard_stop=${HARD_STOP_GIB}"
}

# ---- CI axis, on the CODE repo, job-level, exit gated (D3) -----------------
ci_gate() { # TAG
  local tag="$1" lf="$R/ci-$1-list.json"
  # `gh run list` REJECTS --json jobs; `gh run view --json status` freezes. Hence the
  # two-step: list carries status/conclusion, then view carries jobs.
  gh run list --repo "$CI_REPO" --limit 10 --json databaseId,headSha,status,conclusion,workflowName > "$lf" 2>"$R/ci-$1-list.err"
  local rc=$?
  exits "ci_${tag}_list_EXIT=$rc"
  [ "$rc" -eq 0 ] || die "CI query for '$tag' against $CI_REPO exited $rc — an unread CI axis is not a free box"
  local live
  live=$(python -c 'import json,sys; d=json.load(open(sys.argv[1],encoding="utf-8")); print(" ".join(str(r["databaseId"]) for r in d if r.get("status") not in ("completed",)))' "$lf" 2>"$R/ci-$1-parse.err")
  local prc=$?
  exits "ci_${tag}_parse_EXIT=$prc"
  [ "$prc" -eq 0 ] || die "could not parse the CI listing for '$tag' — see ci-$1-parse.err"
  if [ -n "$live" ]; then
    local id
    for id in $live; do
      gh run view "$id" --repo "$CI_REPO" --json jobs > "$R/ci-$tag-run-$id-jobs.json" 2>>"$R/ci-$1-view.err"
      exits "ci_${tag}_view_${id}_EXIT=$?"
    done
    die "CI on $CI_REPO has non-terminal run(s) [$live] at '$tag' — per-job detail captured; the box is not free and a merge-push re-occupies the runner"
  fi
  record "CI_AXIS ok at '$tag': no non-terminal runs on $CI_REPO"
}

# ---- what the box census is allowed to permit, written down (doyle) --------
# The census no longer excludes anything by name; it RESOLVES each build-class process
# to its command line and parent chain and classifies it. The gate is here, in the
# driver, so the decision is auditable instead of buried in an instrument's filter:
#   cargo_build      > 0  HALT. A producer's CPU would land inside the measured walls.
#   runner_descended > 0  HALT. The self-hosted runner is building on this box.
#   shim_unresolved  > 0  HALT, FAIL CLOSED. A build-class name whose command line does
#                         not resolve to a producer is not evidence of a quiet box.
#   analyzer         > 0  RECORDED, NOT GATED, and the reason is stated: rust-analyzer
#                         is a long-lived IDE service that is never absent on this
#                         workstation, it is NAMED in the evidence with its command
#                         line, and its adjacent load is exactly what the per-trial CPU
#                         bracket measures. Gating on it would make the gate unpassable
#                         and would not make any wall more comparable.
box_gate() { # RUNNER_CENSUS_FILE  LABEL
  local f="$1" label="$2" row; row=$(grep 'RUNNER_CENSUS ' "$f" | tail -1)
  [ -n "$row" ] || die "no RUNNER_CENSUS row at '$label'"
  local v
  for field in cargo_build runner_descended shim_unresolved; do
    v=$(echo "$row" | sed -n "s/.*[ ]$field=\([0-9]*\).*/\1/p")
    case "$v" in (''|*[!0-9]*) die "could not read $field from the runner census at '$label'" ;; esac
    [ "$v" -eq 0 ] || die "$field=$v at '$label' — see the CANDIDATE rows for the command line and parent chain of each"
  done
  local an; an=$(echo "$row" | sed -n 's/.*[ ]analyzer=\([0-9]*\).*/\1/p')
  record "BOX_GATE ok at '$label': cargo_build=0 runner_descended=0 shim_unresolved=0; analyzer=$an RECORDED AND NOT GATED (see the note above this function)"
}

# ===========================================================================
# S0a  THE DRIVER MUST NOT BE ELEVATED — asserted, not commented (D2)
# ===========================================================================
elev=$(pwsh -NoProfile -Command '([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)' 2>"$R/s0a-elev.err")
erc=$?
exits "s0a_elev_EXIT=$erc"
[ "$erc" -eq 0 ] || die "could not determine this process's elevation; refusing to continue (an unmeasured privilege is not an unelevated one)"
record "ELEVATION self=$elev (expect False)"
[ "$elev" = 'False' ] || die "this driver is ELEVATED. The trial driver must remain unelevated; elevated work goes to liam by handoff."

# ===========================================================================
# S0b  PRE-EXISTING STATE IS REJECTED, NEVER TRUNCATED (D10)
# ===========================================================================
if [ -e "$H" ]; then
  die "isolated home $H already exists. A prior run's home would make provenance unreadable; MOVE it, do not let this run truncate it (D10)."
fi

# ===========================================================================
# S0c  INSTRUMENTS: present, and HASHED INTO THE EVIDENCE (F10 + C)
# ===========================================================================
for inst in census.ps1 cpubracket.ps1 runner-census.ps1 portfields.ps1 d1_render.py; do
  [ -f "$BIN/$inst" ] || die "instrument $BIN/$inst is missing — the five dependencies must all exist before any runnable claim"
done
sha256sum "$BIN"/census.ps1 "$BIN"/cpubracket.ps1 "$BIN"/runner-census.ps1 "$BIN"/portfields.ps1 "$BIN"/d1_render.py \
  > "$R/INSTRUMENTS.sha256" 2>"$R/instruments.err"
irc=$?
exits "instruments_sha_EXIT=$irc"
[ "$irc" -eq 0 ] || die "could not hash the instruments — directory placement is not provenance (C); the hashes must ride the evidence"
record "INSTRUMENTS hashed into INSTRUMENTS.sha256 (5 files; portfields.ps1 is the renamed preserve5470 dependency, parameterised by port)"
# SCOPE OF PRIOR INSTRUMENT EXERCISE, recorded accurately (doyle 2026-09-12):
# d1_render.py was exercised by LIVE LOCAL EXECUTION against the pinned blob plus three
# negative controls (one of which found a real substring-counting defect in it), and
# portfields.ps1 and runner-census.ps1 were exercised by LIVE READ-ONLY HOST PROBES --
# not source-only self-tests. Those probes read the firewall rule store, the listening
# sockets and the process table; they invoked no product command, changed no host state
# and touched no firewall rule. The corrections made AFTER those probes -- the
# provider-success-versus-empty-population split in portfields.ps1, and the removal of
# name-based exclusion in runner-census.ps1 -- are UNEXERCISED, by instruction.
record "INSTRUMENT_EXERCISE_SCOPE: d1_render live-executed with controls; portfields/runner-census exercised by live READ-ONLY host probes; all post-correction changes UNEXERCISED (no live probes authorized)"

# ===========================================================================
# S0d  CAPACITY AND BOX, BEFORE ANY PRODUCER
# ===========================================================================
capacity_gate preflight
ci_gate preflight
pwsh -NoProfile -File "$BIN/runner-census.ps1" -Tag preflight > "$R/s0-runner.txt" 2>&1
rrc=$?
exits "s0_runner_EXIT=$rrc"
[ "$rrc" -eq 0 ] || die "runner census exited $rrc — its numbers mean nothing (its own positive control failed)"
grep -q 'valid=YES' "$R/s0-runner.txt" || die "runner census invalid (self_seen false or empty table) — a clean zero from a dead enumeration is not a quiet box"
grep -q 'RUNNER_WORKER=ABSENT' "$R/s0-runner.txt" || die "Runner.Worker.exe present — the box is not free"
box_gate "$R/s0-runner.txt" preflight

# ===========================================================================
# S0e  SUBJECT IDENTITY — exit read BEFORE emptiness is interpreted (D4)
# ===========================================================================
head_sha=$(git -C "$W" rev-parse HEAD 2>"$R/s0e-head.err"); grc=$?
exits "s0e_head_EXIT=$grc"
[ "$grc" -eq 0 ] || die "git rev-parse HEAD exited $grc — see s0e-head.err"
[ "$head_sha" = "$SUBJECT_SHA" ] || die "W is at $head_sha, not the subject $SUBJECT_SHA"
# A git FAILURE must not read as a clean tree: check the exit, THEN the emptiness.
dirty=$(git -C "$W" status --porcelain 2>"$R/s0e-status.err"); grc=$?
exits "s0e_status_EXIT=$grc"
[ "$grc" -eq 0 ] || die "git status exited $grc — an errored status is NOT an empty one (D4)"
[ -z "$dirty" ] || die "W is dirty; a dirty tree fabricates provenance"
blob=$(git -C "$W" rev-parse "HEAD:crates/spt-daemon/src/bootstrap_firewall/windows.rs" 2>"$R/s0e-blob.err"); grc=$?
exits "s0e_blob_EXIT=$grc"
[ "$grc" -eq 0 ] || die "git rev-parse of the subject blob exited $grc"
[ "$blob" = "$SUBJECT_BLOB" ] || die "windows.rs blob $blob != $SUBJECT_BLOB"
record "SUBJECT sha=$head_sha clean blob=$blob"

# ===========================================================================
# S0f  5470 BASELINE — taken BEFORE anything can disturb it (F1/F3)
# ===========================================================================
guard_snapshot guard-baseline || die "could not take the $GUARD_PORT baseline; without it no later claim about $GUARD_PORT is supportable"
guard_baseline_taken=1
record "GUARD_BASELINE taken for port $GUARD_PORT"

# ===========================================================================
# S1  POOL — state marked BEFORE the dispatch that acquires it (C)
# ===========================================================================
abort_check
capacity_gate pool-claim
export CARGO_BUILD_JOBS=2
mark_state pool_acquired "pool-claim is about to be dispatched for $W/target label=$LANE; it may be claimed from this moment whether or not the verb succeeds"
( cd "$W" && cargo run -p xtask -- pool-claim --pool "$W/target" --label "$LANE" ) > "$R/s1-pool.out" 2>&1
prc=$?
exits "s1_pool_EXIT=$prc"
[ "$prc" -eq 0 ] || die "pool-claim exited $prc — see s1-pool.out"
# Lane-identity enforcement lives in the BUILD, never in pool-claim (IR-42). A
# SPT_POOL_FOREIGN or lane-identity refusal appears at the first build and is a HALT;
# it is never predicted from the claim verb.
record "POOL claimed (claim is last-writer-wins by construction; enforcement speaks at the next build)"

# ===========================================================================
# S2  KEY — the seed is bound to ITS OWN keygen invocation (D5/C)
# ===========================================================================
abort_check
# Any inherited seed is DISCARDED: validating an inherited seed and then signing with
# a different generated key is exactly the defect doyle named.
if [ -n "${SPT_DEBUG_RELEASE_SEED:-}" ]; then
  record "INHERITED SPT_DEBUG_RELEASE_SEED present and DISCARDED — this run signs only with the key it generates"
fi
unset SPT_DEBUG_RELEASE_SEED
capacity_gate keygen
mkdir -p "$H"
run_cmd s2_keygen "$SECRET/keygen.out" "$R/s2-keygen.err" -- \
  env -C "$W" cargo run -p xtask -- debug-keygen "$KEY_ID"
krc=$?
[ "$krc" -eq 0 ] || die "debug-keygen exited $krc — see s2-keygen.err"
# EXACTLY ONE of each, counted as OCCURRENCES.
n_pub=$(grep -o '^public_hex:' "$SECRET/keygen.out" | wc -l | tr -d ' ')
n_seed=$(grep -o '^seed_hex:' "$SECRET/keygen.out" | wc -l | tr -d ' ')
[ "$n_pub" = '1' ]  || die "expected exactly one public_hex line from THIS keygen invocation, got $n_pub"
[ "$n_seed" = '1' ] || die "expected exactly one seed_hex line from THIS keygen invocation, got $n_seed"
pub=$(sed -n 's/^public_hex: *//p' "$SECRET/keygen.out" | tr -d ' \r')
seed=$(sed -n 's/^seed_hex: *//p' "$SECRET/keygen.out" | tr -d ' \r')
case "$pub"  in (''|*[!0-9a-f]*) die "parsed public_hex is not lowercase hex" ;; esac
case "$seed" in (''|*[!0-9a-f]*) die "parsed seed_hex is not lowercase hex (xtask/src/main.rs:2717 panics 'seed is hex' on this)" ;; esac
[ "${#pub}" -eq 64 ]  || die "parsed public_hex is ${#pub} chars, expected 64"
[ "${#seed}" -eq 64 ] || die "parsed seed_hex is ${#seed} chars, expected 64"
# RELATIONSHIP, within the one invocation: xtask prints the same public key twice —
# once as public_hex and once inside the debug-pin instruction it tells you to run
# (xtask/src/main.rs:2208 and :2214-2216). They must agree, or the parse is reading
# two different keys.
pub_echo=$(grep -o 'debug-pin --key-id [^ ]* --public-key [0-9a-f]*' "$SECRET/keygen.out" | sed -n 's/.*--public-key //p' | tr -d ' \r')
[ "$pub_echo" = "$pub" ] || die "the keygen output's two public-key occurrences disagree ($pub vs $pub_echo) — refusing to pin a key the invocation does not agree on"
# BY CONSTRUCTION the signer now uses THIS invocation's seed. The value is exported
# and never recorded, printed or expanded into any capture.
export SPT_DEBUG_RELEASE_SEED="$seed"
record "SEED bound to this keygen invocation: shape=64hex (value never recorded), pinned public=$pub"
record "  CEILING, stated: the seed/public relationship is established BY CONSTRUCTION (one invocation, both values parsed from it, two occurrences agreeing) and CONFIRMED LATER BY REFUSAL — a set signed by a key other than the pinned one fails verification at apply/serve time by name. There is no verb at this sha that re-derives a public key from a seed for an independent check."
seed=''

abort_check
capacity_gate pin
run_cmd s2_pin "$R/s2-pin.out" "$R/s2-pin.err" -- \
  env -C "$W" cargo run -p xtask -- debug-pin --key-id "$KEY_ID" --public-key "$pub" --home "$H"
[ $? -eq 0 ] || die "debug-pin exited nonzero — see s2-pin.err"

# ===========================================================================
# S3  BUILD AND STAGE. A cargo producer runs INSIDE this verb (main.rs:2738).
# ===========================================================================
abort_check
capacity_gate rollout-build
run_cmd s3_rollout "$R/s3-rollout.out" "$R/s3-rollout.err" -- \
  env -C "$W" cargo run -p xtask -- debug-rollout --key-id "$KEY_ID" \
    --product-version 0.69.0-fp --channel debug --version 1 --build-current \
    --stage-dir "$H/releases" --state "$W/target/fp-rollout-state.json"
rrc=$?
[ "$rrc" -eq 0 ] || die "S3 rollout exited $rrc — see s3-rollout.err (this is where A7 died, on 'seed is hex')"
grep -q 'DEBUG_ROLLOUT_STAGED version=1' "$R/s3-rollout.out" || die "S3 printed no DEBUG_ROLLOUT_STAGED row"

abort_check
capacity_gate mark-applied
run_cmd s4_applied "$R/s4-applied.out" "$R/s4-applied.err" -- \
  env -C "$W" cargo run -p xtask -- debug-mark-applied --version 1 --home "$H"
[ $? -eq 0 ] || die "debug-mark-applied exited nonzero — see s4-applied.err"
grep -q 'DEBUG_MARKED_APPLIED version=1' "$R/s4-applied.out" || die "S4 printed no DEBUG_MARKED_APPLIED row"

# ===========================================================================
# S5  THREE-WAY PROVENANCE (D6): executable, staged artifact, SIGNED metadata
# ===========================================================================
[ -f "$EXE" ] || die "no release binary at $EXE"
staged="$H/releases/artifacts/$TRIPLE.bin"
rel="$H/releases/release.json"
[ -f "$staged" ] || die "no staged artifact at $staged (relcache.rs:266 writes artifacts/<platform>.bin)"
[ -f "$rel" ]    || die "no staged signed set at $rel (relcache.rs:35)"
{ sha256sum "$EXE"; sha256sum "$staged"; stat -c '%s bytes  mtime=%y  path=%n' "$EXE"; } > "$R/s5-provenance.out" 2>&1
exits "s5_prov_EXIT=$?"
exe_sha=$(sha256sum "$EXE" | awk '{print $1}')
stg_sha=$(sha256sum "$staged" | awk '{print $1}')
meta_sha=$(python -c 'import json,sys; d=json.load(open(sys.argv[1],encoding="utf-8")); m=json.loads(d["metadata_json"]); print(m["artifacts"][sys.argv[2]]["artifact_sha256"])' "$rel" "$TRIPLE" 2>"$R/s5-meta.err")
mrc=$?
exits "s5_meta_parse_EXIT=$mrc"
[ "$mrc" -eq 0 ] || die "could not read artifact_sha256 out of the SIGNED metadata — see s5-meta.err"
[ -n "$exe_sha" ] && [ -n "$stg_sha" ] && [ -n "$meta_sha" ] || die "one of the three provenance hashes is empty; a three-way check needs three measured values"
record "PROVENANCE exe=$exe_sha staged=$stg_sha signed_metadata=$meta_sha"
[ "$exe_sha" = "$stg_sha" ]  || die "THREE-WAY PROVENANCE FAILED: the executable and the staged artifact differ"
[ "$exe_sha" = "$meta_sha" ] || die "THREE-WAY PROVENANCE FAILED: the executable does not match the artifact_sha256 inside the signed metadata"
record "PROVENANCE_THREE_WAY_OK — executable == staged artifact == signed metadata artifact_sha256"

# ===========================================================================
# S6  BOX REFRESHED AFTER THE BUILD, BEFORE ARM A — both axes (D3)
# ===========================================================================
abort_check
ci_gate post-build
pwsh -NoProfile -File "$BIN/runner-census.ps1" -Tag post-build > "$R/s6-runner.txt" 2>&1
src=$?
exits "s6_runner_EXIT=$src"
[ "$src" -eq 0 ] || die "post-build runner census exited $src"
grep -q 'valid=YES' "$R/s6-runner.txt" || die "post-build runner census invalid"
grep -q 'RUNNER_WORKER=ABSENT' "$R/s6-runner.txt" || die "the runner re-occupied the box during the build (a merge-push starts a post-merge run on this box)"
box_gate "$R/s6-runner.txt" post-build
guard_assert post-build

# ===========================================================================
# CENSUS AND BRACKET HELPERS — every call's exit and validity enforced (F-a)
# ===========================================================================
census_at() { # TAG
  pwsh -NoProfile -File "$BIN/census.ps1" -Tag "$1" -OutDir "$R" >> "$R/census.log" 2>&1
  local rc=$?
  exits "census_$1_EXIT=$rc"
  [ "$rc" -eq 0 ] || return 1
  grep -q "tag=$1 .* valid=YES" "$R/census.log" || return 1
  return 0
}
census_row() { # TAG -> the row, or empty
  grep "tag=$1 " "$R/census.log" | tail -1
}
cpu_at() { # TAG — a bracket that did not produce a numeric total is NOT a valid capture (D7)
  pwsh -NoProfile -File "$BIN/cpubracket.ps1" -Tag "$1" >> "$R/cpu-brackets.txt" 2>&1
  local rc=$?
  exits "cpu_$1_EXIT=$rc"
  [ "$rc" -eq 0 ] || return 1
  local row; row=$(grep "tag=$1 " "$R/cpu-brackets.txt" | tail -1)
  [ -n "$row" ] || return 1
  local tot; tot=$(echo "$row" | sed -n 's/.*total_cpus_3s=\([0-9.]*\).*/\1/p')
  case "$tot" in (''|*[!0-9.]*) return 1 ;; esac
  return 0
}
port_at() { # TAG — the trial port's rules and listener identity
  pwsh -NoProfile -File "$BIN/portfields.ps1" -Tag "$1" -OutDir "$R" -Port "$PORT" >> "$R/portfields.log" 2>&1
  local rc=$?
  exits "portfields_${PORT}_$1_EXIT=$rc"
  [ "$rc" -eq 0 ] || return 1
  grep -q "tag=$1 .* valid=YES" "$R/portfields.log" || return 1
  return 0
}

# The arm's expected pair state, enforced before AND after every trial (D7).
expect_pair() { # ARM TAG  -> 0 when the census row matches the arm's precondition
  local arm="$1" tag="$2" row; row=$(census_row "$tag")
  [ -n "$row" ] || return 1
  case "$arm" in
    a) echo "$row" | grep -q 'subj_group=0 subj_29470=0' ;;
    b) echo "$row" | grep -q 'subj_group=2 subj_29470=2' ;;
    *) return 1 ;;
  esac
}

# ===========================================================================
# REFUSAL FACES — all counted, all reported, precedence WRITTEN DOWN (F9)
# ===========================================================================
# Exclusive by deliberate precedence, not by which grep ran last. The strings are the
# product's, at this sha; the comment after each names what reaching it PROVES.
face_report() { # FILE_OUT FILE_ERR PREFIX
  local fo="$1" fe="$2" px="$3"
  local c_recon c_unver c_mismatch c_afterwrite c_src c_nolan c_enf c_disabled c_clean c_cleanunver c_already c_repair c_elevun
  c_recon=$(     cat "$fo" "$fe" 2>/dev/null | grep -o 'LAN_FIREWALL_RECONCILED'                                  | wc -l | tr -d ' ')
  c_unver=$(     cat "$fo" "$fe" 2>/dev/null | grep -o 'LAN_FIREWALL_UNVERIFIED'                                  | wc -l | tr -d ' ')
  c_mismatch=$(  cat "$fo" "$fe" 2>/dev/null | grep -o 'observed rules do not match the admission pair'           | wc -l | tr -d ' ')
  c_afterwrite=$(cat "$fo" "$fe" 2>/dev/null | grep -o 'admission pair was WRITTEN and then could not be verified' | wc -l | tr -d ' ')
  c_src=$(       cat "$fo" "$fe" 2>/dev/null | grep -o 'its source store is'                                      | wc -l | tr -d ' ')
  c_nolan=$(     cat "$fo" "$fe" 2>/dev/null | grep -o 'no connected IPv4 interface'                               | wc -l | tr -d ' ')
  c_enf=$(       cat "$fo" "$fe" 2>/dev/null | grep -o 'ActiveStore enforcement is'                                | wc -l | tr -d ' ')
  c_disabled=$(  cat "$fo" "$fe" 2>/dev/null | grep -o 'LAN_FIREWALL_MUTATION_DISABLED'                            | wc -l | tr -d ' ')
  c_clean=$(     cat "$fo" "$fe" 2>/dev/null | grep -o 'LAN_FIREWALL_CLEAN'                                        | wc -l | tr -d ' ')
  c_cleanunver=$(cat "$fo" "$fe" 2>/dev/null | grep -o 'LAN_FIREWALL_CLEANUP_UNVERIFIED'                           | wc -l | tr -d ' ')
  c_already=$(   cat "$fo" "$fe" 2>/dev/null | grep -o 'LAN_BOOTSTRAP_ALREADY_UP'                                  | wc -l | tr -d ' ')
  c_repair=$(    cat "$fo" "$fe" 2>/dev/null | grep -o 'LAN_FIREWALL_REPAIR_REQUESTED'                             | wc -l | tr -d ' ')
  c_elevun=$(    cat "$fo" "$fe" 2>/dev/null | grep -o 'LAN_FIREWALL_ELEVATION_UNAVAILABLE'                        | wc -l | tr -d ' ')
  # LAN_FIREWALL_CLEANUP_UNVERIFIED contains LAN_FIREWALL_CLEAN as a substring, so the
  # bare CLEAN count is corrected rather than reported as two separate faces.
  c_clean=$((c_clean - c_cleanunver))
  record "$px FACE_COUNTS reconciled=$c_recon unverified=$c_unver mismatch_written=$c_mismatch unverified_after_write=$c_afterwrite source_store=$c_src no_lan_scope=$c_nolan enforcement=$c_enf mutation_disabled=$c_disabled clean=$c_clean cleanup_unverified=$c_cleanunver already_up=$c_already repair_requested=$c_repair elevation_unavailable=$c_elevun"
  # PRECEDENCE, most specific first. Each line says what it PROVES, not what it hints.
  local face=none
  if   [ "$c_mismatch"   -gt 0 ]; then face=mismatch-after-write   # reconcile wrote, then verify disagreed: representation NOT accepted (windows.rs:817)
  elif [ "$c_afterwrite" -gt 0 ]; then face=unverified-after-write  # writes landed, observation cut short: NOT a refused write
  elif [ "$c_enf"        -gt 0 ]; then face=enforcement             # decide() got past pair_satisfied_by (:723) => REPRESENTATION ACCEPTED
  elif [ "$c_src"        -gt 0 ]; then face=source-store            # also past pair_satisfied_by => representation accepted, persistence refused
  elif [ "$c_nolan"      -gt 0 ]; then face=no-lan-scope            # tailnet half checked; host cannot carry the LAN half
  elif [ "$c_recon"      -gt 0 ]; then face=reconciled              # verify() Ok(true)
  elif [ "$c_unver"      -gt 0 ]; then face=unverified-generic      # decide() Ok(false): ABSENT **or** MISSPELLED — the census supplies which
  else face=none
  fi
  record "$px FACE=$face"
  echo "$face"
}

# ===========================================================================
# TRIAL
# ===========================================================================
trial() { # ARM N
  abort_check
  local arm="$1" n="$2" id="$arm-$n"
  local outf="$R/$id.out" errf="$R/$id.err"
  local soutf="$R/$id.stop.out" serrf="$R/$id.stop.err"

  census_at "$id-pre"  || void "pre-census $id invalid (a control failed) — its numbers mean nothing"
  expect_pair "$arm" "$id-pre" || void "ARM $arm precondition not met before trial $n: census row [$(census_row "$id-pre")]"
  port_at "$id-pre"    || void "pre portfields $id invalid"
  cpu_at  "$id-pre"    || void "pre CPU bracket $id produced no valid capture (D7)"

  # THE TIMED INVOCATION. Unelevated, opt-out set: listener up, exactly one
  # verify-query, no elevation, no reconcile. The wall is the PRODUCT's own.
  mark_state listener_may_exist "about to dispatch serve lan --bootstrap for trial $id on port $PORT"
  mark_state daemon_may_run "serve dispatches through the daemon (ensure_running, serveverb.rs:191)"
  run_cmd "${id}_serve" "$outf" "$errf" -- \
    env SPT_INSTALL_NO_FIREWALL=1 SPT_HOME="$H" "$EXE" serve lan --bootstrap --port "$PORT"
  local serve_rc=$?
  # A NONZERO EXIT IS A CONTROL ERROR AND IS NEVER ACCEPTED (doyle). The LanUp arm
  # returns 0 unconditionally (serveverb.rs:233-249), so a nonzero cannot be an
  # admission refusal — it is a path, daemon or control failure (:170, :192, :198),
  # which means this trial never measured the verify-query leg at all.
  if [ "$serve_rc" -ne 0 ]; then
    void "$id: serve lan --bootstrap exited $serve_rc, which on this path can only be a path/daemon/control error, not a verdict. This trial is not a measurement."
  fi

  # ALREADY_UP means the PREVIOUS stop failed and this wall measures a different path.
  if grep -q 'LAN_BOOTSTRAP_ALREADY_UP' "$outf"; then
    void "$id printed LAN_BOOTSTRAP_ALREADY_UP — the previous stop did not take, so this wall is not a cold verify-query"
  fi
  # EXPECTED PORT AND BINDER (D7), while the listener is up.
  port_at "$id-up" || void "portfields on port $PORT during trial $id is invalid"
  local lrow; lrow=$(grep "tag=$id-up " "$R/portfields.log" | tail -1)
  echo "$lrow" | grep -q 'listener_state=READ' || void "$id: no listener READ on port $PORT after --bootstrap; the expected port is not bound"
  if ! grep -q "Path=$EXE" "$R/portfields-$PORT-$id-up.txt"; then
    void "$id: the listener on port $PORT is not the built executable ($EXE) — wrong binder, so the trial measures another process"
  fi

  run_cmd "${id}_stop" "$soutf" "$serrf" -- \
    env SPT_INSTALL_NO_FIREWALL=1 SPT_HOME="$H" "$EXE" serve lan --stop
  local stop_rc=$?
  # The LanStopped arm also returns 0 (serveverb.rs:250-258), so a nonzero here is
  # likewise a control error. Fail closed: the arm's next trial depends on this stop
  # having actually happened, and the measured assertions below are run anyway so the
  # evidence of WHAT state was left behind is captured before the void.
  if [ "$stop_rc" -ne 0 ]; then
    record "  STOP_CONTROL_ERROR $id: serve lan --stop exited $stop_rc (a control error, not a verdict)"
  fi

  cpu_at  "$id-post" || void "post CPU bracket $id produced no valid capture"
  census_at "$id-post" || void "post-census $id invalid"
  port_at "$id-post" || void "post portfields $id invalid"
  # A SUCCESSFUL LISTENER STOP, measured rather than assumed (D7).
  grep "tag=$id-post " "$R/portfields.log" | tail -1 | grep -q 'listener_state=NONE' \
    || void "$id: a listener is still bound on port $PORT after --stop; the stop did not take"
  # THE ARM'S PAIR STATE AFTER, not just before (D7). For arm b this is the RETENTION
  # that makes the next trial repeatable (report_lan_cleanup, serveverb.rs:376-391).
  expect_pair "$arm" "$id-post" \
    || void "ARM $arm pair state changed across trial $n: post census [$(census_row "$id-post")]"
  guard_assert "$id-post"
  case $? in
    0) : ;;
    1) die "port $GUARD_PORT fields changed during trial $id — this run must not disturb the production port" ;;
    *) die "the $GUARD_PORT comparison instrument failed during trial $id; the preservation claim is unsupportable" ;;
  esac
  # The stop's control error is voided HERE, after the post-state has been captured, so
  # the evidence of what the failed teardown left behind survives the void.
  if [ "$stop_rc" -ne 0 ]; then
    void "$id: the stop exited $stop_rc. The post-trial state above is recorded, but the next trial in this arm cannot rely on a teardown that reported a control error."
  fi

  # THE SUBJECT ROW. grep -o counts OCCURRENCES: two records on one line must not
  # count as one (hertz Q3). grep exits nonzero on zero matches, so the status is
  # dropped deliberately and the COUNT is then asserted numeric.
  local rows; rows=$(grep -o 'leg=verify-query' "$errf" 2>/dev/null | wc -l | tr -d ' ')
  case "$rows" in (''|*[!0-9]*) void "$id: subject-row count is not numeric: '$rows'" ;; esac
  # An EMPTY capture is a MISSING-ROW OUTCOME — a measurement, not a launch failure (C).
  # Launch failures were already classified by run_cmd and carry their own status.
  if [ "$rows" -eq 0 ]; then
    void "$id: subject row ABSENT — the measured path was not reached. (Launch status for this tag is in exits.txt; an empty capture is a missing-row outcome, not evidence the command never ran.)"
  fi
  if [ "$rows" -gt 1 ]; then
    void "$id: $rows subject rows; multiple rows are NOT interchangeable observations"
  fi
  # No other leg may appear in a trial (windows.rs 676/801/889).
  local other; other=$(grep -o 'leg=reconcile-write\|leg=cleanup' "$errf" 2>/dev/null | wc -l | tr -d ' ')
  [ "$other" = '0' ] || void "$id: $other non-verify legs appeared in a trial that must only verify"

  local row; row=$(grep 'leg=verify-query' "$errf" | head -1)
  local wall; wall=$(echo "$row" | sed -n 's/.*wall_ms=\([0-9]*\).*/\1/p')
  local outcome; outcome=$(echo "$row" | sed -n 's/.*outcome=\([a-z]*\).*/\1/p')
  case "$outcome" in
    completed) : ;;   # a measurement; three are needed for a SUCCESSFUL arm
    failed)    : ;;   # a measurement OF failed (non-deadline Err); does not count
    killed)    : ;;   # a measurement OF killed; IS the populated arm's failure verdict
    *) void "$id: unrecognised outcome field in the subject row: [$row]" ;;
  esac
  record "TRIAL $id serve_rc=$serve_rc stop_rc=$stop_rc wall_ms=$wall outcome=$outcome row=[$row]"
  record "  NOTE on rc: a zero is NECESSARY BUT NOT SUFFICIENT. serveverb.rs:233-249 returns 0 unconditionally on LanUp, so a zero says nothing about admission; a NONZERO is a real control error and disqualifies the trial."
  if [ "$outcome" != completed ]; then
    record "  non-completed outcome RECORDED IN PLACE and NOT re-rolled; all three scheduled attempts stand as run"
    record "  error text: $(tr '\n' ' ' < "$errf" | cut -c1-400)"
  fi
  face_report "$outf" "$errf" "TRIAL $id" > /dev/null
  # The per-arm stop signature (D7).
  case "$arm" in
    a) grep -q 'LAN_FIREWALL_CLEAN' "$soutf" \
         || record "  STOP_SIGNATURE_UNEXPECTED arm a: no LAN_FIREWALL_CLEAN on the stop with no pair present" ;;
    b) if grep -q 'LAN_FIREWALL_MUTATION_DISABLED' "$serrf" && grep -q 'LAN_FIREWALL_CLEANUP_UNVERIFIED' "$serrf"; then
         record "  STOP_SIGNATURE arm b as designed: the opt-out refused the removal, so THE PAIR IS RETAINED (census above confirms it)"
       else
         record "  STOP_SIGNATURE_UNEXPECTED arm b: retention is supposed to show as MUTATION_DISABLED + CLEANUP_UNVERIFIED together"
       fi ;;
  esac
}

# ===========================================================================
# D1 — out-of-band QUERY capture. SERIALIZED, never inside a timed trial.
# ===========================================================================
d1_capture() { # TAG
  local tag="$1"
  D1_OK=no
  python "$BIN/d1_render.py" --repo "$W" --blob "$SUBJECT_BLOB" --out "$R/d1-$tag.b64" \
    > "$R/d1-$tag-render.out" 2>&1
  local rc=$?
  exits "d1_${tag}_render_EXIT=$rc"
  if [ "$rc" -ne 0 ]; then
    record "D1_FAILED($tag) render exit $rc — see d1-$tag-render.out. The capture is DISCARDED, not patched up."
    return 1
  fi
  grep -q 'PRECHECK Named-Rules=1 PersistentStore=0 Get-NetIPAddress=1 ActiveStore=2' "$R/d1-$tag-render.out" \
    || { record "D1_FAILED($tag) the render did not satisfy its own A2.1 pre-check; capture discarded"; return 1; }
  powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand "$(cat "$R/d1-$tag.b64")" \
    > "$R/d1-$tag-snapshot.json" 2> "$R/d1-$tag-snapshot.err"
  local prc=$?
  exits "d1_${tag}_exec_EXIT=$prc"
  if [ "$prc" -ne 0 ]; then
    record "D1_FAILED($tag) the out-of-band capture exited $prc — see d1-$tag-snapshot.err"
    return 1
  fi
  D1_OK=yes
  record "D1($tag) captured to d1-$tag-snapshot.json — a SEPARATE DIAGNOSTIC INVOCATION."
  record "  CEILING: it is NOT the product's failure-time snapshot and cannot say what any timed call saw"
  record "  (snapshot() windows.rs:675-680 and run_bounded :136-188 keep nothing). It bounds the host"
  record "  spellings present AROUND the call. It also cannot discriminate this candidate from the"
  record "  registration sha: the QUERY const is byte-identical at 53d625cd and 921aa68f (measured)."
  return 0
}

# ===========================================================================
# ARM A — owned pair ABSENT
# ===========================================================================
abort_check
census_at a-precondition || die "the Arm A precondition census is invalid; its zeros would be meaningless"
expect_pair a a-precondition || die "ARM A precondition not met: an owned pair is present. Row: [$(census_row a-precondition)]"
record "ARM_A precondition measured: owned pair ABSENT"
for n in 1 2 3; do trial a "$n"; done

# ===========================================================================
# ARM B SETUP — ONE elevated action, by HANDOFF (D2). Never run by this driver.
# ===========================================================================
abort_check
guard_assert pre-setup
case $? in
  0) : ;;
  1) die "port $GUARD_PORT already changed before the elevated setup" ;;
  *) die "the $GUARD_PORT instrument failed before the elevated setup" ;;
esac
# MARKED BEFORE THE DISPATCH (C): a REFUSED setup can still leave rules behind.
mark_state fw_mutation_may_have_occurred "an elevated reconcile is about to be REQUESTED; rules may exist from this moment even if the setup is refused"
handoff_request setup \
  "one elevated reconcile so Arm B has a bootstrap-OWNED pair written by the product itself (never a hand netsh, so the rules carry the shipped desired_specs shape)" \
  "env -u SPT_INSTALL_NO_FIREWALL SPT_HOME=$H $EXE serve lan --bootstrap --port $PORT > $HO_OUT 2> $HO_ERR"
SETUP_OUT="$HO_OUT"; SETUP_ERR="$HO_ERR"   # captured now: a later handoff rebinds HO_*
if ! handoff_await trial; then
  die "no verified setup receipt; Arm B cannot begin. State markers left for the authorized teardown."
fi
setup_rc=$(handoff_exit)
guard_assert post-setup
case $? in
  0) : ;;
  1) die "port $GUARD_PORT fields changed across the elevated setup — see guard-post-setup.diff" ;;
  *) die "the $GUARD_PORT instrument failed across the elevated setup" ;;
esac

census_at b-setup-post || die "the post-setup census is invalid"
setup_face=$(face_report "$SETUP_OUT" "$SETUP_ERR" "SETUP")
exits "b_setup_elev_EXIT=$setup_rc"
pair_written=no
census_row b-setup-post | grep -q 'subj_group=2 subj_29470=2' && pair_written=yes
record "ARM_B_SETUP rc=$setup_rc face=$setup_face pair_written=$pair_written row=[$(census_row b-setup-post)]"
# ACCEPTANCE — THREE CONDITIONS, ALL REQUIRED (doyle):
#   rc == 0          NECESSARY, NOT SUFFICIENT. A nonzero control error is never
#                    accepted. It is not sufficient because serveverb.rs:233-249
#                    returns 0 unconditionally on LanUp, so a zero carries no
#                    admission information by itself. An unread exit counts as 255.
#   face == reconciled   the product's own positive verdict. Here it DOES imply
#                    verify() Ok(true), because reconcile() re-verifies at
#                    windows.rs:816 and returns Err otherwise.
#   pair_written     the pair measured present by census. Absence of refusal text
#                    was never acceptance.
if [ "$setup_rc" -ne 0 ] || [ "$setup_face" != reconciled ] || [ "$pair_written" != yes ]; then
  record "ARM_B_SETUP_NOT_ACCEPTED rc=$setup_rc face=$setup_face pair_written=$pair_written"
  [ "$setup_rc" -eq 255 ] && record "  rc=255 means the receipt carried no parseable exit= line; an unread exit is not a zero one"
  case "$setup_face" in
    mismatch-after-write)
      record "  DIAGNOSTIC: the product WROTE the pair and then refused its own writes (windows.rs:817)."
      record "  That is A7's defect reproduced at the repaired candidate: representation NOT accepted in the field." ;;
    enforcement|source-store)
      record "  DIAGNOSTIC: an enforcement/persistence refusal. Spec matching passed FOR THAT INVOCATION and"
      record "  nothing more — it does NOT establish the registered successful-reconcile precondition for Arm B." ;;
    unverified-after-write)
      record "  DIAGNOSTIC: the writes landed and the observation was cut short. NOT a refused write." ;;
  esac
  # D9: D1 runs on REJECTION, BEFORE any teardown is requested.
  record "  D1 runs NOW, before any teardown, so the host state at the refusal is captured."
  d1_capture setup-rejection
  record "  POPULATED TRIALS HELD. No Arm B without a separately reviewed amendment."
  set_original 3 "Arm B setup not accepted (rc=$setup_rc face=$setup_face pair_written=$pair_written)"
  exit 3
fi

# Retain the pair for Arm B with an UNELEVATED opt-out stop. An elevated stop here
# would REMOVE it (report_lan_cleanup, serveverb.rs:376-391).
mark_state listener_may_exist "the setup left a listener up; an unelevated opt-out stop follows"
run_cmd b_setup_stop "$R/b-setup-stop.out" "$R/b-setup-stop.err" -- \
  env SPT_INSTALL_NO_FIREWALL=1 SPT_HOME="$H" "$EXE" serve lan --stop
[ $? -eq 0 ] || record "the retention stop returned nonzero; the census below is what decides"
census_at b-precondition || die "the Arm B precondition census is invalid"
expect_pair b b-precondition \
  || die "the opt-out stop did not retain the pair; Arm B's populated precondition is gone. Row: [$(census_row b-precondition)]"
record "ARM_B precondition measured: owned pair PRESENT and retained through an unelevated stop"

for n in 1 2 3; do trial b "$n"; done

# ===========================================================================
# D1 and the final verdict. A failed D1 CANNOT finish at exit 0 (F8).
# ===========================================================================
abort_check
d1_capture main
d1_rc=$?

if [ "$d1_rc" -ne 0 ]; then
  record "ALL ARMS RAN; D1 FAILED (D1_OK=$D1_OK). The completion statement covers THE ARMS ONLY."
  set_original 4 "arms complete, D1 failed"
  exit 4
fi
record "ALL ARMS COMPLETE and D1 captured (D1_OK=$D1_OK)"
exit 0
