#!/bin/bash
# =============================================================================
# D2 DRIVER — #297 bounded out-of-band capture, run BY THE EXISTING FIELD DRIVER.
# hertz 2026-09-13. FOR SOURCE REVIEW. NOT RUN IN THE FIELD.
# NO BUILD GRANT. NO FIELD GRANT. NO ELEVATION GRANT. NO RESIDUAL-PID GRANT.
#
# PROVENANCE: this is the FROZEN r10 driver, staged-r10-queue-guard.sh, sha256
# a78f4ba6ed5491ccb38d26f8a3fe4f1a7a9f23296d85a133511b1bf9396d1fbf (todlando; frozen by
# doyle Y2B7UUAS, R10-FROZEN.sha256 re-verified here), with the r10 WORKLOAD REMOVED and the
# #297 D2 capture points ADDED. The exact diff against that file is the deliverable beside
# this one. Every retained block is retained BYTE-FOR-BYTE, so the diff shows only what D2
# changed. r10 is the base and not v9 (a9510e1e) deliberately: v9 predates the accepted
# binder-path, classifier, cleanup-exit and queue-guard repairs, and starting from it would
# have silently reintroduced four defects that were already paid for.
#
# WHY THIS FILE AND NOT A WRAPPER (doyle, 2026-09-13). I first built a separate wrapper that
# sequenced the capture points beside this driver, and exercised the wrapper until it went
# green. That was a parallel orchestrator standing next to machinery that already had
# handoff, state-marking and exactly-once cleanup — a weaker copy of a stricter check, which
# is worse than no copy because it arrives carrying evidence. The wrapper and its receipts
# are PRESERVED as superseded evidence (d2_wrapper.ps1, d2_wrapper_check.ps1,
# receipt-wrapper-check-wps51.txt); they are kept, not tended, and nothing here calls them.
#
# WHAT WAS REMOVED — the BUILD AND TIMING WORKLOAD, each named with its reason, because a
# silently dropped gate is a defect:
#   - debug-keygen / debug-pin / debug-rollout --build-current / debug-mark-applied, the
#     subject_boundary pair that bracketed the producer, and the THREE-WAY PROVENANCE check.
#     D2 reuses the executable r10 already built and receipted; there is no new artifact to
#     sign, stage or agree with. The executable is instead PINNED BY EXACT HASH (S1), and
#     that hash is stated in the elevated request as well, because a clean source tree does
#     not identify reused executable bytes.
#   - pool-claim / pool-release. Nothing here runs cargo, so no build pool is claimed;
#     claiming one would write a lane identity this run does not have.
#   - capacity_gate. It exists ahead of PRODUCERS (F7). With no producer, a disk floor gates
#     nothing.
#   - cpubracket.ps1, trial(), both arms, expect_pair's a/b vocabulary, completion_verdict
#     and populated_timing_report. There is no timed workload: the pair is created once,
#     read three times, and torn down. Two of r10's three "what a green establishes" ceiling
#     clauses went with them, because they were about trials and timings this run never
#     takes.
#
# WHAT WAS KEPT, AND WHY IT IS NOT WORKLOAD:
#   - THE STATUS-FILTERED CI AXIS and the ANCESTRY-AUTHENTICATED BOX CENSUS, at preflight and
#     again immediately before the elevated leg. This box is shared with a self-hosted
#     runner and a merge-push re-occupies it; admission to a shared host is not a property of
#     the workload, and the readings are POINT-IN-TIME (R10-FROZEN says so).
#   - the 5470 GUARD IN FULL. This run mutates the host firewall through a handoff, so
#     preserving the production port is a safety property of the mutation.
#   - the binder-path canonical comparison, the classifier face_report, the r8 cleanup-exit
#     handler, exactly-once state-aware cleanup, signal handling and the handoff mechanics.
#
# WHAT WAS ADDED:
#   t1  the ONLY elevated read the design has, RIDING THE seq-001 SETUP REQUEST. One nonce is
#       one execution: an elevated read cannot be added after the leg returns without a
#       second handoff and a second authorization. If it does not run, t1 is UNAVAILABLE — a
#       LABELLED EVIDENCE GAP, never a licence to report the capture contract satisfied.
#   t2  at the outcome of the setup, beside D1, BEFORE any teardown is requested — so the
#       state at a refusal is captured while it still exists.
#   t3  immediately before the teardown request is written, with the manifest hashed first.
#   TWO BUDGETS, ENFORCED AND SEPARATE (plan §4): a 300 s EXPERIMENTAL budget and a 180 s
#       CLEANUP REPORTING deadline. The experimental deadline ENDS ACTIVITY AND STARTS
#       CLEANUP — it exits through the EXIT trap, which is the only way cleanup is ever
#       entered, so a truncated run tears down exactly like a complete one. The reporting
#       deadline expiring means THE REPORT IS DUE, never that the host is tidy: cleanup stays
#       PENDING while a residual-identity authorization is outstanding.
#   RESIDUAL IDENTITY reporting (plan §6): pid + creation time + executable path + command
#       line, read fresh, with the enumeration's own positive control so a dead process
#       table cannot read as a tidy host. This driver REPORTS AND STOPS. It kills nothing:
#       the r10 pid authorization was pid-specific and is SPENT, and a fresh pid-naming
#       authorization is a STOP, not a step.
#   A RUN LEDGER carrying the four exits separately and the two verdicts.
#
# THE EXITS STAY SEPARATE, at every point (plan §5.0). The elevated setup's native exit and
# each capture's native exit are independent values in their own files. Neither is inferred
# from, overwritten by, or substituted for the other. d2_capture.ps1 exits only 0 (a document
# was written — a document full of DENIED states is still a capture), 2 (could not write) or
# 3 (arguments rejected). NO PROPERTY STATE IS EVER AN EXIT CODE, and this driver's own exit
# is likewise not a statement that the run was green: the verdicts live in the ledger.
#
# VALIDATION DECIDES WHETHER AN OBSERVATION WAS MADE, NEVER WHETHER ITS VALUE IS THE WANTED
# ONE (doyle, 2026-09-13). Legitimate null, empty-string, empty-array and ABSENT all pass. A
# DENIED or ERROR outcome is a QUERY FAILURE THAT WAS OBSERVED — counted, reported, and
# distinct from a MISSING REQUIRED OBSERVATION, which is the only thing that makes a document
# incomplete. Nothing here requires EnforcementStatus to be [1]; refusing [5, 20] would
# refuse the evidence this capture exists to collect.
#
# ---------------------------------------------------------------------------
# PRODUCT CONTRACT, read at 85f84d73 and unchanged here. Only the lines this driver still
# READS are kept; the build-chain lines went with the build chain.
#
#   serveverb.rs:233-249   The LanUp arm returns 0 UNCONDITIONALLY, so a zero exit carries no
#                          admission information on its own, while a nonzero IS a real
#                          control error (:170,:192,:198) and is never accepted.
#   serveverb.rs:297-302   print_lan_admission -> LAN_FIREWALL_RECONCILED (stdout). THE
#                          positive admission verdict.
#   serveverb.rs:311/318   LAN_FIREWALL_UNVERIFIED / LAN_FIREWALL_CLEANUP_UNVERIFIED (stderr)
#   serveverb.rs:331       LAN_FIREWALL_MUTATION_DISABLED — the opt-out refusing a mutation.
#   serveverb.rs:379       LAN_FIREWALL_CLEAN — is_clean() Ok(true) on a stop.
#   serveverb.rs:376-391   report_lan_cleanup: an UNELEVATED cleanup goes to
#                          request_lan_firewall, which the opt-out REFUSES — so an unelevated
#                          opt-out stop RETAINS the pair. That is what keeps the pair alive
#                          between t2 and t3.
#   serveverb.rs:191       serve reaches the broker through ensure_running, so the firewall
#                          teardown must stay AHEAD of the daemon stop or the teardown spawns
#                          a fresh daemon.
#   windows.rs:713-756     decide() checks pair_satisfied_by (:723) FIRST, so reaching the
#                          enforcement arm PROVES the pair matched.
#   windows.rs:816-817     reconcile() re-verifies after writing: RECONCILED from the ELEVATED
#                          setup does imply verify() Ok(true) at that instant, and
#                          mismatch_message is reachable only from that re-verification.
#   windows.rs:11-30       THE OWNED NAMES ARE CONSTANTS: spt-core-bootstrap-inbound-tcp and
#                          -lan, under group "spt-core bootstrap TCP". A production pair on
#                          5470 carries THE SAME NAMES, so a query by name can return more
#                          than one object. That is why the capture preserves every match
#                          with its own match_index and marks ambiguity instead of taking
#                          items[0].
#   bootstrap_firewall.rs:19-25  SPT_INSTALL_NO_FIREWALL gates request_lan_firewall and
#                          reconcile_lan_firewall only; verify() is NOT gated.
#
# 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/909af448-f4ab-4fa1-ba30-02e38b275a11/scratchpad/bundle-r5'
BIN="$SP/fp-bin"                  # INSTRUMENTS — never written to by a run
RUN_ROOT="$SP/fp-run"             # one timestamped subdir per run
# ---- THE PROVISIONED RIG (doyle W4C2QFLE) -----------------------------------
# THE HOME IS NO LONGER THIS DRIVER'S TO CREATE. The LAN-bootstrap set gate refuses a fresh
# home BEFORE any firewall admission is attempted (lanhost.rs:184-213 -> LanRefused ->
# serveverb.rs:260; report_lan_admission, which is what reaches the firewall, sits only on the
# Ok arm at :247), so a run whose home was empty could never create the pair it exists to
# measure. Provisioning is therefore a SEPARATE MUTATING PHASE with its own grant -- see
# provision-rig.sh -- and this driver only ever VERIFIES and CONSUMES what that phase produced.
#
# ONE DISPOSABLE EXECUTABLE PATH FOR EVERY ROLE (todlando's constraint), and it is structural
# rather than a convention to remember: the daemon is spawned from std::env::current_exe()
# (daemon.rs:874) and the brain from that supervisor, so invoking ONLY $EXE makes the CLI, the
# supervisor and the brain the same path by construction.
#
# AN EMPTY PIN IS NOT A MISSING SETTING. It is this run stating that it has no provisioned rig,
# exactly as TEARDOWN_B64_SHA256 states it has no authorized removal command.
RIG_ROOT=''                       # <run-root>/rig, written by provision-rig.sh. UNPINNED here.
H="$RIG_ROOT/home"                # the PROVISIONED isolated SPT_HOME: identity/ (the rig trust
                                  # key), releases/ (the staged set AND the applied record).
                                  # PRIOR HOMES ARE STILL NEVER REUSED OR CLEARED: fp-home-d2
                                  # and fp-home-d2-a2 belong to retained runs and are preserved
                                  # as their evidence. A rig is ONE ATTEMPT -- S0b consumes this
                                  # one atomically and a second run gets a refusal, not a reuse.
EXE="$RIG_ROOT/bin/spt.exe"       # A COPY of the subject, taken by provisioning and hashed
                                  # there. NEVER the worktree build itself and NEVER the fleet
                                  # installation: `update apply` replaces the executable it is
                                  # running, so either of those would be overwritten by the very
                                  # step that makes the gate passable. The copy is what makes
                                  # the apply disposable. Its sha is UNCHANGED from the subject
                                  # r10 built -- a copy that does not hash to EXE_SHA is a
                                  # different subject and S0b refuses it.
EXE_SHA='72d309011415b419aabfdb0b4065df1183bfd0069a9f95b5779da62e43349b10'
# THE CAPTURE SCRIPT IS A SUBJECT TOO (doyle LIRX7EUS). The elevated leg runs BOTH the product
# and this script, and every document this run reasons about is whatever THIS file produced.
# An acknowledgment that measures only the executable proves the leg can see one of the two.
# INTEGRATED 2026-09-13 (doyle W4C2QFLE): the capture successor. Its EXIT CONTRACT is five
# values, not three, and every record line below that names them says all five -- a 4 or a 5
# reaching the ledger as an unlabelled nonzero is the coupled defect this integration closes.
#   predecessor chain, every link hash-verified in history/:
#   a0e7afbe -> af29bbb3 -> 010666e7 -> 69b8506a   (all PRESERVED; none replaced)
CAPTURE_SHA='69b8506ac932841223996e7d5ad5ab03a51662ce4eacc6da77dad458a03f620c'
PORT=29470                        # never 5470
GUARD_PORT=5470                   # the production port this run must not disturb
SUBJECT_SHA='85f84d738fa702f35c83910f314aae17849d125c'
SUBJECT_BLOB='848a23fe18e5ca819774f9881ef13504221992f3'
# The owned pair's names are PRODUCT CONSTANTS (windows.rs:11-19), not a choice of this rig.
RULE_TAILNET='spt-core-bootstrap-inbound-tcp'
RULE_LAN='spt-core-bootstrap-inbound-tcp-lan'
# POSITIVE CONTROL: a standing rule, read-only, same property set, same route, same process.
# A property ABSENT on BOTH it and the pair is an INSTRUMENT LIMIT, not a finding about the
# pair. It is a knob because it names a rule on THIS host; the capture records whether it was
# actually present, and a control that was NOT present makes the pair's absences unreadable —
# reported by d2_validate as sound=false, never assumed either way.
# POSITIVE CONTROL, ACCEPTED BY NAME 2026-09-13 (doyle). Tailscale-In was a CANDIDATE and is
# MEASURED UNUSABLE: it is a DisplayName, not a rule Name, and TWO rules answer to it -- this
# capture addresses every rule by -Name, so by that route the store returned nothing, and even
# by DisplayName an ambiguous control identifies no object. Replaced by the guard rule's own
# Name, measured through this very capture: found=True matched_count=1 ambiguous=False
# query_outcome=OK, all seven filter groups one match each, every property observed.
# IT IS THE 5470 GUARD RULE (DisplayName 'spt lan-bootstrap 5470'), so it is READ ONLY here --
# the same rule GUARD_PORT exists to protect. Nothing in this run writes it.
CONTROL_RULE='{FF36EE51-2837-46D8-9AB8-2441D9070633}'
ABSENT_CONTROL='spt-core-bootstrap-inbound-tcp-d2-absent-control'
PREP_BUDGET_S=600                 # doyle 2026-09-13: PREPARATION IS BOUNDED SEPARATELY and
                                  # spends no experimental time. The read-only preflight and the
                                  # executor's hash-verified PREPARED/NOT_STARTED acknowledgment
                                  # run under THIS bound; the experimental window does not exist
                                  # yet while they do.
EXP_BUDGET_S=300                  # plan §4: experimental total, from GO -- NOT from run start
CLEANUP_REPORT_S=180              # plan §4: cleanup REPORTING deadline, from the end of activity
HANDOFF_WAIT_S=900                # bounded wait for a liam receipt; narrowed at the point of
                                  # waiting to what remains of the experimental budget
CLEANUP_HANDOFF_WAIT_S=300        # likewise narrowed to what remains of the reporting deadline
# ---- F5 r2.2 BOUNDS (doyle CT6GS2Y6 / O2VBV5LC / B3CMWRQI) ------------------
# Three constants the predecessor did not have. Each answers a defect the 20260913T071131Z
# run exhibited, and NONE of them is a duration estimate:
#   LEDGER_RESERVE_S  the report cannot be starved by the work before it. Every cleanup step
#                     is bounded by WORK_DEADLINE = REPORT_DEADLINE - this; the ledger owns
#                     the remainder ALONE and emits without waiting for any child.
#   KILL_GRACE_S      `timeout -k N` TERMs at the bound and KILLs N seconds later, so a bound
#                     of `deadline - now` overruns its own deadline by N. Every bound
#                     subtracts it, so TERM+KILL completes BY the deadline.
#   HANDOFF_CAP_S     a POLICY ALLOCATION of the activity window -- how much of the 300s this
#                     run will spend waiting on another agent. 94s and 134s are two samples,
#                     not a distribution, and nothing here is derived from them.
LEDGER_RESERVE_S=30
KILL_GRACE_S=5
HANDOFF_CAP_S=120
# THE TEARDOWN COMMAND IS PINNED, NEVER COMPOSED (doyle 2026-09-13). The removal this run may
# need is the PRODUCT'S OWN rendered cleanup command, which only the shipped binary can emit.
# Until it has been emitted, decoded, reviewed and pinned here, cleanup REFUSES to dispatch any
# teardown and reports PENDING/review. An empty pin is not a missing setting: it is this run
# stating that it has no authorized command to hand an elevated leg.
PRESERVED_D2='C:/Users/decid/Documents/projects/spt-core/.spt/preserved/hertz-fp-driver-review/d2'
TEARDOWN_COMMAND_FILE="$PRESERVED_D2/teardown-command.pinned"  # the emitted literal, byte for
                                  # byte. IT LIVES WITH THE PRESERVED REVIEW, NOT IN THE
                                  # SCRATCHPAD: a reviewed pin that a session teardown can
                                  # delete is not a pin, and the review that admitted it is
                                  # the only reason it may be dispatched at all.
# PINNED 2026-09-13 (doyle F3VCR5KO): the emitted payload is ACCEPTED as the reviewed
# RULE-REMOVAL CANDIDATE. Acceptance is not permission to execute it -- it is what would make a
# dispatch under a future grant legitimate at all.
TEARDOWN_B64_FILE="$PRESERVED_D2/d3/decoded-todlando/d3-payload.b64"
                                  # THE REVIEWED PAYLOAD ITSELF, at its permanent path. The
                                  # authority is doyle's pin below, not this driver's opinion.
TEARDOWN_B64_SHA256='416280dbece2601203c74c3f8e2c46e13009125fa5870166894e079329fb1d43'
# WHY TWO FILES AND ONE PIN. The bytes dispatched to an elevated leg must be the PRODUCT'S OWN
# emitted line, never one this driver assembles; the bytes REVIEWED are the base64 payload inside
# it. So the literal is kept verbatim in TEARDOWN_COMMAND_FILE and the check is that the payload
# INSIDE that literal is byte-for-byte the reviewed file, which in turn hashes to the pin above.
# Nothing is composed, and nothing unreviewed can ride along inside a literal that merely looks
# right.
RULE_PROBE="$PRESERVED_D2/rule-probe.ps1"
RULE_PROBE_SHA256='be016198d860076c58257953bf2342fc35fea54550e373aae7e0f2b60132bcee'
                                  # STALE PIN, CAUGHT BY doyle 2026-09-13: this still named the
                                  # probe as it was BEFORE its argument transport was corrected,
                                  # so removal_check would have refused the shipped probe as
                                  # UNPINNED at run time and no removal could ever be confirmed.
                                  # The controls did not catch it because the harness recomputed
                                  # this value instead of reading the driver's own.
                                  # THE INDEPENDENT POST-REMOVAL CHECK. The product reporting its
                                  # own success is the claim under test, and the census counts
                                  # ActiveStore rules by GROUP and PORT -- neither can say which
                                  # owned NAME is gone, nor anything at all about PersistentStore.
                                  # This probe addresses each name by InstanceID in each store.
                                  # It is evidence, so it is pinned like any other instrument.
TEARDOWN_PIN_STATE=UNCHECKED      # set by teardown_pin_verify; reported whatever it says
CI_REPO='BigscreenVR/spt-bs-core' # the CODE repo (D3). Issues live elsewhere.
PREP_EPOCH=$(date +%s)            # the PREPARATION clock starts at process start
PREP_DEADLINE=$((PREP_EPOCH + PREP_BUDGET_S))   # the instant preparation is over; every
                                  # bounded preflight probe runs under THIS one, so a
                                  # pre-GO step cannot be handed a window that has not opened
RUN_EPOCH=''                      # THE EXPERIMENTAL CLOCK DOES NOT EXIST UNTIL GO, and an unset
                                  # clock is an UNSTARTED experiment: every activity step refuses
                                  # while it is empty. MEASURED REASON (run 20260913T041410Z):
                                  # that run charged preparation AND the elevated operator's
                                  # reading time to the experiment -- handoff_interval alone was
                                  # 04:17:02Z..04:19:16Z, 134s of a 300s window -- and it reached
                                  # neither t1 nor t2. Separating the clocks is that measurement's
                                  # correction, not a preference.
GO_UTC=''                         # stamped by go(); the instant the experimental window opened
PREPARED_ACK=''                   # the executor's verified PREPARED/NOT_STARTED receipt path

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=''
# D2 state. Every value below is REPORTED, and each one starts at the reading that assumes
# the least: an unread exit is not a zero one, and an uncaptured point is a gap.
D2_T1=UNAVAILABLE
D2_T2=NOT_RUN
D2_T3=NOT_RUN
D2_T1_VALID=NOT_VALIDATED
D2_T2_VALID=NOT_VALIDATED
D2_T3_VALID=NOT_VALIDATED
D2_T1_QF=0                       # query failures among the REQUIRED observations at each point:
D2_T2_QF=0                       # observed and recorded, never counted as successful ones
D2_T3_QF=0
VALIDATE_QF=0
SETUP_RC=255
TEARDOWN_RC=255
# THE SETUP COMMAND'S OWN BOUNDS, stamped INSIDE the elevated leg and read back from the
# files that leg was asked to write. They are not this driver's clock: it never runs the
# command, so it cannot time it. UNRECORDED until the leg answers.
SETUP_START_UTC=UNRECORDED
SETUP_END_UTC=UNRECORDED
SETUP_EXIT_FILE=ABSENT           # the exit the leg preserved BEFORE t1 ran; a cross-check on
                                 # the receipt's exit= claim, never a substitute for it
# THE ELEVATED CAPTURE'S OWN BOUNDS, likewise stamped inside the leg. A document utc plus an
# exit file is ONE instant and a file mtime; these are two stamps taken around the command.
T1_START_UTC=UNRECORDED
T1_END_UTC=UNRECORDED
# THE HANDOFF'S BOUNDS -- a DIFFERENT interval, this driver's own: when it wrote the request
# and when it verified the receipt. It opens before the command exists and closes after the
# command has finished, so it is never the command's creation record.
HANDOFF_REQUEST_UTC=UNRECORDED
HANDOFF_RECEIPT_UTC=UNRECORDED
TS_ORDER=UNMEASURED              # the six stamps above compared with the calendar, not assumed
PRE_SETUP_ABSENCE=UNRECORDED
RESIDUE_COUNT=UNMEASURED
RESIDUE_LIVE=0                   # tracked identities re-queried and still running
RESIDUE_GONE=0                   # tracked identities measured absent (or pid-reused)
RESIDUE_UNREADABLE=0             # attribution missing or unreadable: NEVER read as clean
IDENT_CAPTURE_RC=1               # the capture command's own exit; 1 until it has run
CAPTURE_USABLE=no                # a capture supports CLEAR only when proven complete
CAPTURE_INTEGRITY=''             # why it is or is not usable, in words
DAEMON_STOP_REFUSED=0            # IR-122's expected refusal, recorded with its native exit
DAEMON_STOP_RC=NOT_RUN           # the refused command's OWN exit, preserved in every case
LISTENER_STATE=UNMEASURED        # unread is read as LIVE: an unread port is not an empty one
CAPTURE_CONTRACT=NOT_SATISFIED    # earned, never defaulted to satisfied
CLEANUP_VERDICT=PENDING           # PENDING until VERIFIED is measured; a clock never earns it
EXPERIMENTAL_ENDED=''
# ---- 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
}
# ---- binder identity: complete normalised path comparison (r2) --------------
# Replaces the grep substring test at the trial's binder check. Lifted VERBATIM from
# v9-exercises/binder-path/binder-path-r2.sh and fenced below, so the copy can be
# diffed against the file the fixtures actually exercise. binder-path-fixtures-r2.sh
# asserts the two are identical line for line: an inlined copy that quietly drifts
# from its tested original is a comparator nobody has tested.
# BINDER-PATH-BEGIN
binder_path_canon() {
  local p="$1" drive rest
  p="${p%$'\r'}"
  p="${p#"${p%%[![:space:]]*}"}"
  p="${p%"${p##*[![:space:]]}"}"
  [ -z "$p" ] && { printf 'empty'; return 1; }

  # Refuse the rooted-but-not-drive forms BEFORE any separator rewriting, because rewriting
  # is exactly what would disguise them as something supported.
  case "$p" in
    '\\'*|'//'*)   printf 'unc-or-extended'; return 1 ;;
  esac
  if [[ "$p" =~ ^/([A-Za-z])/(.*)$ ]]; then            # MSYS drive path: /c/dir/file
    drive="${BASH_REMATCH[1]}"; rest="${BASH_REMATCH[2]}"
  elif [[ "$p" =~ ^([A-Za-z]):[\\/](.*)$ ]]; then      # drive-absolute: C:\dir or C:/dir
    drive="${BASH_REMATCH[1]}"; rest="${BASH_REMATCH[2]}"
  elif [[ "$p" =~ ^[A-Za-z]:. ]]; then
    printf 'drive-relative'; return 1                  # C:file -- depends on a per-drive cwd
  elif [[ "$p" == /* || "$p" == '\'* ]]; then
    printf 'root-relative'; return 1                   # \dir\file -- depends on current drive
  else
    printf 'not-absolute'; return 1
  fi

  rest="${rest//\//\\}"                                 # separators, inside the path only
  while [[ "$rest" == *'\\'* ]]; do rest="${rest//\\\\/\\}"; done
  rest="${rest%\\}"
  printf '%s:\\%s' "$drive" "$rest" | tr '[:upper:]' '[:lower:]'
  return 0
}

# The Path value runs from the field to end of line. The field must be the whole key at the
# start of the line, optionally indented -- not any text containing "Path=".
binder_path_field() {
  local line="$1" rest
  [[ "$line" =~ ^[[:space:]]*Path=(.*)$ ]] || return 1
  rest="${BASH_REMATCH[1]}"
  rest="${rest%$'\r'}"
  rest="${rest%"${rest##*[![:space:]]}"}"
  rest="${rest#"${rest%%[![:space:]]*}"}"
  [ -z "$rest" ] && return 2
  printf '%s' "$rest"
}

binder_path_verdict() {
  local cap="$1" want="$2"
  if [ ! -r "$cap" ]; then
    echo "VERDICT VOID-CAPTURE-UNREADABLE got=[<no file>] want=[$want]"; return 2
  fi
  local found=() line f rc
  while IFS= read -r line || [ -n "$line" ]; do
    f=$(binder_path_field "$line"); rc=$?
    if [ "$rc" -eq 2 ]; then
      echo "VERDICT VOID-FIELD-EMPTY got=[$line] want=[$want]"; return 2
    fi
    [ "$rc" -eq 0 ] && found+=("$f")
  done < "$cap"

  if [ "${#found[@]}" -eq 0 ]; then
    echo "VERDICT VOID-NO-PATH-FIELD got=[<none>] want=[$want]"; return 2
  fi

  local n_want reason
  n_want=$(binder_path_canon "$want") || {
    reason="$n_want"
    echo "VERDICT VOID-CONFIGURED-PATH-UNSUPPORTED($reason) got=[${found[0]}] want=[$want]"; return 2
  }

  local first="" g n_g
  for g in "${found[@]}"; do
    n_g=$(binder_path_canon "$g") || {
      reason="$n_g"
      echo "VERDICT VOID-CAPTURE-PATH-UNSUPPORTED($reason) got=[$g] want=[$want]"; return 2
    }
    if [ -z "$first" ]; then first="$n_g"
    elif [ "$n_g" != "$first" ]; then
      echo "VERDICT VOID-CONFLICTING-PATHS got=[${found[*]}] want=[$want]"; return 2
    fi
  done

  if [ "$first" = "$n_want" ]; then
    echo "VERDICT SAME got=[${found[0]}] want=[$want]"; return 0
  fi
  echo "VERDICT DIFFERENT got=[${found[0]}] want=[$want]"; return 1
}
# BINDER-PATH-END

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
  bounded "portfields_${GUARD_PORT}_$1" "$(cur_deadline)" "$R/.guard.out" "$R/.guard.err" -- \
    pwsh -NoProfile -File "$BIN/portfields.ps1" -Tag "$1" -OutDir "$R" -Port "$GUARD_PORT"
  local rc=$?
  cat "$R/.guard.out" "$R/.guard.err" >> "$R/portfields.log" 2>/dev/null
  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"
  # v8: THE COMMAND IS COMPOSED HERE, AFTER the capture paths exist. A caller cannot
  # name them in its argument: the argument is expanded at the CALL, before this
  # function has run, so HO_OUT/HO_ERR would be the empty initialisers on the first
  # handoff and the PREVIOUS handoff's paths on every later one. Callers therefore
  # supply no redirection at all, and this refuses one if they try, so run_exactly
  # and the declared redirect_* paths cannot disagree.
  case "$3" in
    *">"*) die "handoff_request got a redirect in its command text: [$3]. Capture paths are composed here, after allocation; callers pass the bare command." ;;
  esac
  local cmd_exact="$3 > \"$HO_OUT\" 2> \"$HO_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"
    # THE AUDIENCE IS PART OF THE REQUEST (doyle XS5VAWJQ). A request that says "elevation:
    # REQUIRED" is addressed to the elevated executor. An AUTHORIZATION is not an action and is
    # not the executor's to give: readiness comes from whoever would run the leg, authorization
    # comes from the DRI, and stamping both with the same header made them one channel.
    case "${4:-executor}" in
      doyle)
        echo "audience: doyle (the DRI) — THE ELEVATED EXECUTOR MUST NOT ANSWER THIS REQUEST"
        echo "elevation: NOT_REQUIRED — this is an authorization, not an action; nothing is run to answer it"
        ;;
      *)
        echo "audience: the elevated executor"
        echo "elevation: REQUIRED — the trial driver is unelevated by assertion (S0a) and will not run this itself"
        ;;
    esac
    echo "run_exactly:"
    echo "$cmd_exact"
    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"
}

# PREPARATION (600 s, from process start). Read-only preflight and the executor's
#   hash-verified PREPARED/NOT_STARTED acknowledgment. NO EXPERIMENTAL TIME IS SPENT
#   HERE: the experimental clock does not start until go(), and every activity step
#   refuses while it is unstarted. Overrunning preparation is a REFUSAL TO START, never
#   a truncated experiment -- nothing has been created yet, so there is nothing to
#   truncate and nothing to tear down.
# ---- THREE BUDGETS, ENFORCED AND SEPARATE (plan §4; doyle 2026-09-13) --------
# The EXPERIMENTAL budget bounds ACTIVITY. The CLEANUP budget bounds the REPORT. They are
# different clocks measuring different obligations, and the second one starts where the
# first one ends:
#
#   EXPERIMENTAL (300 s, FROM GO -- not from run start). Reaching it ENDS ACTIVITY AND
#   STARTS CLEANUP.
#   IT NEVER SKIPS CLEANUP -- the deadline exits through the EXIT trap, which is the only
#   way cleanup is ever entered, so a truncated run tears down exactly like a complete one.
#   A phase cut short is REPORTED AS TRUNCATED, naming the phase; a truncated phase's
#   absence of a field is "NOT CAPTURED", never "not present".
#
#   CLEANUP REPORTING (180 s, from the end of activity). Reaching it means THE REPORT IS
#   DUE. It does NOT mean the host is tidy and it never converts PENDING into VERIFIED:
#   while a residual-identity authorization is outstanding, cleanup stays PENDING and the
#   identities are reported for the next consumer to act on.
CLEANUP_EPOCH=0
# THE DEADLINE INSTANTS. A remaining-seconds helper answers 'how long may this step run';
# an INSTANT answers 'by when must it be over', and only the second can be handed to a
# sequence of queries without each one silently re-granting itself the rest of the budget.
EXP_DEADLINE=0                   # RUN_EPOCH + EXP_BUDGET_S,  set at go()
REPORT_DEADLINE=0                # CLEANUP_EPOCH + CLEANUP_REPORT_S, set at end_experimental()
WORK_DEADLINE=0                  # REPORT_DEADLINE - LEDGER_RESERVE_S, same place
SETUP_COMPLETION=UNPROVEN        # R6: proven only by a run-bound receipt with terminal fields
CLEANUP_STOP_STATE=NOT_REACHED   # which gate outcome step 1 took (IR-124)
TEARDOWN_DISPATCH=NOT_REACHED    # whether a teardown command was dispatched, and why not
REMOVAL_CHECK=NOT_REACHED        # the INDEPENDENT reading, by name and by store
REMOVAL_PRE=NOT_REACHED          # the same reading taken BEFORE any teardown was asked for
DAEMON_STOP_STATE=NOT_REACHED    # which gate outcome the daemon stop took, reported either way
# ---- THE PINNED REMOVAL INSTRUMENT, VERIFIED TWICE (doyle 2026-09-13) --------
# Once BEFORE GO -- a run that cannot remove what it is about to create must never open the
# window -- and again immediately BEFORE USE, because the file can change in between and the
# first reading would then be about bytes nobody is dispatching. Each call names its context so
# the two readings cannot be mistaken for one another in the ledger.
#
# WHAT THE INSTRUMENT IS, read from the decoded payload: it removes the two OWNED rules from
# PersistentStore after asserting each rule's group and TCP protocol, then re-reads BOTH stores
# and throws if anything remains. IT STOPS NO LISTENER AND REMOVES NO PROCESS. The listener and
# process disposition stays exactly where it was -- a separate, observation-gated question that
# this command neither answers nor affects.
teardown_pin_verify() { # CONTEXT -> 0 when the reviewed instrument is present and intact
  local ctx="$1" sha b64
  TEARDOWN_PIN_STATE=UNCHECKED
  if [ -z "$TEARDOWN_B64_SHA256" ]; then
    TEARDOWN_PIN_STATE=UNPINNED
    record "TEARDOWN_PIN($ctx)=UNPINNED - no reviewed pin is configured. An empty pin is this run saying it has no authorized command to hand an elevated leg."
    return 1
  fi
  if [ ! -f "$TEARDOWN_B64_FILE" ]; then
    TEARDOWN_PIN_STATE=MISSING_REVIEWED_PAYLOAD
    record "TEARDOWN_PIN($ctx)=MISSING_REVIEWED_PAYLOAD [$TEARDOWN_B64_FILE] - the reviewed bytes are not where the pin says they live."
    return 1
  fi
  if [ ! -f "$TEARDOWN_COMMAND_FILE" ]; then
    TEARDOWN_PIN_STATE=MISSING_COMMAND_LITERAL
    record "TEARDOWN_PIN($ctx)=MISSING_COMMAND_LITERAL [$TEARDOWN_COMMAND_FILE] - the product's emitted line is absent, and this driver does not compose one."
    return 1
  fi
  sha=$(sha256sum "$TEARDOWN_B64_FILE" | cut -d' ' -f1)
  if [ "$sha" != "$TEARDOWN_B64_SHA256" ]; then
    TEARDOWN_PIN_STATE=REVIEWED_PAYLOAD_HASH_MISMATCH
    record "TEARDOWN_PIN($ctx)=REVIEWED_PAYLOAD_HASH_MISMATCH measured=$sha pinned=$TEARDOWN_B64_SHA256 - different bytes are a different command."
    return 1
  fi
  b64=$(sed -n 's/.*-EncodedCommand \([A-Za-z0-9+/=]*\).*/\1/p' "$TEARDOWN_COMMAND_FILE")
  if [ -z "$b64" ]; then
    TEARDOWN_PIN_STATE=LITERAL_CARRIES_NO_ENCODEDCOMMAND
    record "TEARDOWN_PIN($ctx)=LITERAL_CARRIES_NO_ENCODEDCOMMAND - the literal is not the shape the reviewed payload rides in; REFUSED rather than guessed at."
    return 1
  fi
  if ! printf '%s' "$b64" | cmp -s - "$TEARDOWN_B64_FILE"; then
    TEARDOWN_PIN_STATE=LITERAL_PAYLOAD_DIFFERS_FROM_REVIEWED
    record "TEARDOWN_PIN($ctx)=LITERAL_PAYLOAD_DIFFERS_FROM_REVIEWED - what was reviewed is not what would be dispatched: REFUSED."
    return 1
  fi
  TEARDOWN_PIN_STATE=VERIFIED
  record "TEARDOWN_PIN($ctx)=VERIFIED reviewed_b64_sha256=$sha - the dispatchable literal carries the reviewed payload byte for byte"
  return 0
}
# ---- THE INDEPENDENT POST-REMOVAL READING (doyle 2026-09-13) -----------------
# It answers one question the product's verdict and the group/port census cannot: is EACH owned
# NAME gone from EACH store. Its outcomes are named separately because they are different facts
# and they are not equally bad:
#
#   CONFIRMED           both names absent in both stores, with both per-store controls alive
#   PARTIAL             some absent, some present -- a removal that took one rule and not the
#                       other. THE SUCCESSFUL HALF IS NOT A SUCCESS: what remains is admission
#                       that is still open, and no retry is issued.
#   ACTIVESTORE_RESIDUE PersistentStore clean, ActiveStore still holding an owned name. The
#                       persistent rule is gone and the LIVE one is not, so the host is still
#                       admitting on it. Named on its own because a reader who sees "removed
#                       from the store it was written to" would otherwise call this clean.
#   FAILED              every owned name still present
#   UNREADABLE_*        the probe did not run, is not the pinned probe, its controls are dead,
#                       or it returned fewer readings than names x stores. An instrument that
#                       could not look is NOT a host that is clean.
#
# EVERY OUTCOME EXCEPT CONFIRMED IS PENDING/review at the call site. None of them dispatches
# anything: this function reads, and the run reports.
removal_check() { # TAG -> sets REMOVAL_CHECK
  # TAGGED, because this now runs TWICE and the two readings are different facts: one BEFORE any
  # teardown is asked for (is there anything to remove at all?) and one AFTER (did the removal
  # happen?). A single un-tagged transcript would let a reader take one for the other.
  local tag="${1:-post}" out rc absent present unread readings ctl_stores ctl_ok active_present persist_present psha
  REMOVAL_CHECK=UNREADABLE
  out="$R/rule-probe-$tag.out"
  if [ ! -f "$RULE_PROBE" ]; then
    REMOVAL_CHECK=UNREADABLE_NO_PROBE
    record "REMOVAL_CHECK=UNREADABLE_NO_PROBE [$RULE_PROBE] - the independent probe is absent; this run cannot confirm removal itself."
    return
  fi
  psha=$(sha256sum "$RULE_PROBE" | cut -d' ' -f1)
  if [ "$psha" != "$RULE_PROBE_SHA256" ]; then
    REMOVAL_CHECK=UNREADABLE_PROBE_UNPINNED
    record "REMOVAL_CHECK=UNREADABLE_PROBE_UNPINNED measured=$psha pinned=$RULE_PROBE_SHA256 - evidence from an unpinned instrument is not evidence."
    return
  fi
  # ONE DELIMITED TOKEN, AND THE PROBE IS TOLD HOW MANY TO EXPECT. Measured 2026-09-13:
  # powershell.exe -File collapses `-Names "a","b"` into the single string "a,b", and
  # `-Names "a" "b"` binds "b" to the NEXT parameter instead. Both forms silently delivered ONE
  # name. The probe now parses the token itself and REFUSES (exit 7) when the parsed count is
  # not the expected one, so a binding regression is a refusal rather than a smaller sample.
  pwsh -NoProfile -File "$RULE_PROBE" -NamesCsv "$RULE_TAILNET,$RULE_LAN" -ExpectNames 2 -ControlName "$CONTROL_RULE" > "$out" 2>&1
  rc=$?
  exits "rule_probe_${tag}_EXIT=$rc"
  if [ "$rc" -ne 0 ]; then
    REMOVAL_CHECK=UNREADABLE_PROBE_EXIT_$rc
    record "REMOVAL_CHECK=UNREADABLE probe_exit=$rc - see $out. A failed probe is not an absent rule."
    return
  fi
  ctl_stores=$(grep -c '^RULEPROBE_CONTROL_OK ' "$out" 2>/dev/null)
  ctl_ok=$(grep -c '^RULEPROBE_CONTROL_OK .* ok=True$' "$out" 2>/dev/null)
  readings=$(grep -c '^RULEPROBE store=' "$out" 2>/dev/null)
  absent=$(grep -c '^RULEPROBE store=.* state=ABSENT' "$out" 2>/dev/null)
  present=$(grep -c '^RULEPROBE store=.* state=PRESENT' "$out" 2>/dev/null)
  unread=$(grep -c '^RULEPROBE store=.* state=UNREADABLE' "$out" 2>/dev/null)
  active_present=$(grep -c '^RULEPROBE store=ActiveStore .* state=PRESENT' "$out" 2>/dev/null)
  persist_present=$(grep -c '^RULEPROBE store=PersistentStore .* state=PRESENT' "$out" 2>/dev/null)
  # grep -c prints 0 and EXITS 1 on no match. An `|| echo 0` after it appends a SECOND line, so
  # the variable holds two lines of zero instead of one and every numeric test below errors
  # out -- measured by control d1, which read PARTIAL where the answer was UNREADABLE_CONTROLS.
  record "REMOVAL_PROBE($tag) readings=$readings absent=$absent present=$present unreadable=$unread active_present=$active_present persistent_present=$persist_present controls=$ctl_ok/$ctl_stores"
  if [ "$ctl_stores" -lt 2 ] || [ "$ctl_ok" -ne "$ctl_stores" ]; then
    REMOVAL_CHECK=UNREADABLE_CONTROLS
    record "REMOVAL_CHECK=UNREADABLE_CONTROLS - a store whose positive/negative control did not hold cannot report absence: a dead predicate reads every name as gone."
    return
  fi
  if [ "$readings" -ne 4 ]; then
    REMOVAL_CHECK=UNREADABLE_INCOMPLETE
    record "REMOVAL_CHECK=UNREADABLE_INCOMPLETE readings=$readings expected=4 (2 names x 2 stores) - a missing reading is a gap, never an absence."
    return
  fi
  if [ "$unread" -ne 0 ]; then
    REMOVAL_CHECK=UNREADABLE_STATE
    record "REMOVAL_CHECK=UNREADABLE_STATE unreadable=$unread - at least one name could not be resolved either way."
    return
  fi
  if [ "$present" -eq 0 ]; then
    REMOVAL_CHECK=CONFIRMED
    record "REMOVAL_CHECK=CONFIRMED - both owned names measured ABSENT in BOTH stores by this run's own instrument, with each store's controls alive in the same sample."
    return
  fi
  if [ "$persist_present" -eq 0 ] && [ "$active_present" -gt 0 ]; then
    REMOVAL_CHECK=ACTIVESTORE_RESIDUE
    record "REMOVAL_CHECK=ACTIVESTORE_RESIDUE active_present=$active_present - the persistent rule is gone and a rule of that name is still in the LIVE store. Whether anything is being admitted through it is NOT established here (this reads names, not effective admission): PENDING/review, and nothing is retried."
    return
  fi
  if [ "$absent" -gt 0 ]; then
    REMOVAL_CHECK=PARTIAL
    record "REMOVAL_CHECK=PARTIAL absent=$absent present=$present - one owned name is absent and another is present. Read with the pre-teardown state and the remover's exit, that is a half-removal; on its own it does not establish that THIS invocation removed anything. Either way it is not a success: PENDING/review, and NO second dispatch is issued."
    return
  fi
  REMOVAL_CHECK=FAILED
  record "REMOVAL_CHECK=FAILED present=$present - every owned name is still there. The instrument ran and removed nothing: PENDING/review."
}
# AN UNSTARTED CLOCK IS NOT A FULL BUDGET. Before go() there is no experimental window at
# all, and a caller asking how much of it remains is asking about something that does not
# exist yet. Echoing EXP_BUDGET_S there would hand an activity step a full window it was
# never granted -- exactly the confusion go() exists to prevent.
exp_left() {
  [ -z "$RUN_EPOCH" ] && { echo UNSTARTED; return; }
  local now used left
  now=$(date +%s); used=$((now - RUN_EPOCH)); left=$((EXP_BUDGET_S - used))
  [ "$left" -lt 0 ] && left=0
  echo "$left"
}
# ---- bounded(): the ONLY enforced bound, and it MEASURES what it stopped -----
# THE PREDECESSOR ENFORCED NOTHING EXCEPT THE CAPTURES. deadline_check fired at two sites in
# the whole 20260913T071131Z run, and 271 of the 300 seconds ran with no budget read at all:
# a budget checked BETWEEN steps bounds a sequence, not a process.
#
# FOUR THINGS, NOT ONE, and each is a correction doyle made to my first proposal:
#   1. the bound subtracts KILL_GRACE_S, so TERM-then-KILL completes BY the deadline rather
#      than five seconds past it, and a step that cannot cover the grace is NOT STARTED;
#   2. the child is REGISTERED BEFORE it can finish, and the register distinguishes the msys
#      WRAPPER from the NATIVE child -- they are different processes with different pids, and
#      the one bash hands back is the wrapper while the one that may survive is the child;
#   3. on expiry the driver MEASURES what stopped instead of assuming it. `timeout` sends TERM
#      to a native Windows process that owes it no POSIX answer, and that process's descendants
#      are in no job object the kill reaches. A read-only command still leaves a process;
#   4. whatever the killed step wrote is PRESERVED under a name that says it is unverified.
#      An expired bound says the COMPLETION is unverified; it says nothing about the disk.
#
# NOTHING HERE KILLS ANYTHING THIS DRIVER DID NOT SPAWN, and nothing here acquires an
# authority over an elevated leg. Stopping a wait and stopping an operation are different acts.
BOUNDED_STATE=NOT_REACHED         # the outcome of the most recent bounded() call
LAUNCH_SEQ=0
launch_file() { echo "$R/launched-identities.txt"; }
# The WINPID behind an msys pid. `ps` is an msys builtin-class probe over msys's own table:
# it costs no CIM query and it is the only place the mapping exists. An unmappable pid is
# recorded as UNREADABLE -- never as 'the wrapper had no child'.
winpid_of() { # MSYS_PID -> WINPID | UNREADABLE
  local p="$1" w
  w=$(ps -p "$p" 2>/dev/null | awk -v p="$p" '$1==p {print $4}' | head -1)
  case "$w" in (''|*[!0-9]*) echo UNREADABLE ;; (*) echo "$w" ;; esac
}
# ONE bounded CIM query for the children of a live wrapper. It runs WHILE the wrapper is alive
# because that is the only moment the parent link exists: after `timeout` returns, a survivor
# has no edge back to anything this run can name.
register_launched() { # LABEL MSYS_PID DEADLINE
  local label="$1" mpid="$2" dl="$3" lf; lf=$(launch_file)
  LAUNCH_SEQ=$((LAUNCH_SEQ + 1))
  local wp; wp=$(winpid_of "$mpid")
  local now; now=$(date -u +%Y-%m-%dT%H:%M:%SZ)
  echo "LAUNCHED seq=$LAUNCH_SEQ label=$label kind=wrapper msys_pid=$mpid winpid=$wp launched=$now" >> "$lf"
  if [ "$wp" = UNREADABLE ]; then
    echo "LAUNCHED seq=$LAUNCH_SEQ label=$label kind=native state=ATTRIBUTION_INCOMPLETE reason=wrapper-winpid-unreadable" >> "$lf"
    record "  LAUNCH($label) the wrapper's WINPID could not be read: the native child is ATTRIBUTION_INCOMPLETE, which is NOT a statement that it is gone"
    return 0
  fi
  local q_left=$(( dl - $(date +%s) ))
  [ "$q_left" -gt 3 ] || {
    echo "LAUNCHED seq=$LAUNCH_SEQ label=$label kind=native state=ATTRIBUTION_INCOMPLETE reason=no-budget-for-descendant-query" >> "$lf"
    return 0
  }
  [ "$q_left" -gt 10 ] && q_left=10
  SPT_D2_WP="$wp" timeout -k 2 "$q_left" pwsh -NoProfile -Command '
    $p = [int]$env:SPT_D2_WP
    try { $kids = @(Get-CimInstance Win32_Process -Filter "ParentProcessId=$p" -ErrorAction Stop) }
    catch { "QUERY=UNREADABLE reason=enumeration-failed"; exit 0 }
    if ($kids.Count -eq 0) { "QUERY=NO_CHILD"; exit 0 }
    foreach ($k in $kids) {
      $c = try { $k.CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") } catch { "UNREADABLE" }
      "CHILD pid=$($k.ProcessId) created=$c exe=[$($k.ExecutablePath)]"
    }
  ' > "$R/.launch-q.$LAUNCH_SEQ" 2>&1
  local qrc=$?
  if [ "$qrc" -ne 0 ] || grep -q '^QUERY=UNREADABLE' "$R/.launch-q.$LAUNCH_SEQ" 2>/dev/null; then
    echo "LAUNCHED seq=$LAUNCH_SEQ label=$label kind=native state=ATTRIBUTION_INCOMPLETE reason=descendant-query-unreadable(rc=$qrc)" >> "$lf"
    return 0
  fi
  if grep -q '^QUERY=NO_CHILD' "$R/.launch-q.$LAUNCH_SEQ" 2>/dev/null; then
    # A CHILD THAT EXITED BEFORE REGISTRATION IS NOT CONFIRMED GONE (doyle B3CMWRQI). An
    # absence at the moment of registration is the absence of a READING, not a reading of an
    # absence; only a registered pid re-queried and measured absent is the second thing.
    echo "LAUNCHED seq=$LAUNCH_SEQ label=$label kind=native state=ATTRIBUTION_INCOMPLETE reason=no-child-at-registration wrapper_winpid=$wp" >> "$lf"
    return 0
  fi
  while IFS= read -r line; do
    case "$line" in
      CHILD\ *) echo "LAUNCHED seq=$LAUNCH_SEQ label=$label kind=native ${line#CHILD } parent_winpid=$wp" >> "$lf" ;;
    esac
  done < "$R/.launch-q.$LAUNCH_SEQ"
  return 0
}
# What actually stopped. Re-queries THIS call's registered native rows by pid AND creation
# instant -- pid reuse on this box is measured, so a pid answering with a different creation
# time is a DIFFERENT process and ours is gone.
measure_termination() { # LABEL SEQ DEADLINE -> sets TERMINATION
  local label="$1" seq="$2" dl="$3" lf; lf=$(launch_file)
  TERMINATION=UNREADABLE
  local rows; rows=$(grep "^LAUNCHED seq=$seq .* kind=native pid=" "$lf" 2>/dev/null)
  if [ -z "$rows" ]; then
    TERMINATION=ATTRIBUTION_INCOMPLETE
    record "  TERMINATION($label)=ATTRIBUTION_INCOMPLETE — no native identity was registered for this launch, so nothing can be re-queried. This is NOT 'confirmed gone'."
    return
  fi
  local q_left=$(( dl - $(date +%s) ))
  if [ "$q_left" -le 3 ]; then
    TERMINATION=UNREADABLE
    record "  TERMINATION($label)=UNREADABLE — no budget remained to re-query the registered identities. UNREADABLE is never CLEAR."
    return
  fi
  [ "$q_left" -gt 10 ] && q_left=10
  local live=0 gone=0 unread=0 p c now_c
  while IFS= read -r r; do
    p=$(echo "$r" | sed -n 's/.*[ ]pid=\([0-9]*\).*/\1/p')
    c=$(echo "$r" | sed -n 's/.*[ ]created=\([^ ]*\).*/\1/p')
    [ -n "$p" ] || continue
    now_c=$(SPT_D2_P="$p" timeout -k 2 "$q_left" pwsh -NoProfile -Command '
      $p = [int]$env:SPT_D2_P
      try { $x = @(Get-CimInstance Win32_Process -Filter "ProcessId=$p" -ErrorAction Stop) }
      catch { "UNREADABLE"; exit 0 }
      if ($x.Count -eq 0) { "GONE"; exit 0 }
      try { $x[0].CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") } catch { "UNREADABLE" }
    ' 2>/dev/null | tr -d ' \r\n')
    case "$now_c" in
      GONE)       gone=$((gone + 1)) ;;
      UNREADABLE|'') unread=$((unread + 1)) ;;
      "$c")       live=$((live + 1)); record "  TERMINATION($label) SURVIVING pid=$p created=$c — the bound expired and this process did not" ;;
      *)          gone=$((gone + 1)) ;;   # same pid, different creation instant: reuse, ours is gone
    esac
  done <<EOF_ROWS
$rows
EOF_ROWS
  if [ "$live" -gt 0 ]; then TERMINATION=SURVIVING
  elif [ "$unread" -gt 0 ]; then TERMINATION=UNREADABLE
  else TERMINATION=CONFIRMED_GONE
  fi
  record "  TERMINATION($label)=$TERMINATION surviving=$live gone=$gone unreadable=$unread (measured by pid PLUS creation instant, never by pid alone)"
}
# PRESERVE WHATEVER AN EXPIRED STEP WROTE. Completion unverified is not an absent document:
# a write can have finished, half-finished, or not started, and only inspection tells them apart.
preserve_unverified() { # LABEL PATH...
  local label="$1"; shift
  local f sz sha
  for f in "$@"; do
    [ -e "$f" ] || { record "  UNVERIFIED($label) $f ABSENT at the moment of preservation — recorded, not concluded from"; continue; }
    sz=$(wc -c < "$f" 2>/dev/null | tr -d ' ')
    sha=$(sha256sum "$f" 2>/dev/null | cut -d' ' -f1)
    cp -p "$f" "$f.unverified" 2>/dev/null \
      && record "  UNVERIFIED($label) $f preserved as $f.unverified bytes=$sz sha256=$sha — completion is UNVERIFIED; the artifact state is a fact to be INSPECTED, not inferred" \
      || record "  UNVERIFIED($label) $f could NOT be preserved (bytes=$sz sha256=$sha) — the original is left exactly where it is and nothing is deleted"
  done
}
# THE OUTPUT PATHS ARE PARAMETERS, NOT A REDIRECTION AT THE CALL SITE (r10's defect, and it
# cost IR-123 an unpassable gate): `record` TEES TO STDOUT, so `bounded ... > file` would file
# this function's own log lines into the subject's output. run_cmd already takes OUT and ERR
# for exactly this reason, and this helper keeps the same shape.
# WHICH DEADLINE A STEP IS UNDER IS A PROPERTY OF THE PHASE, NOT OF THE CALL SITE. One
# helper answers it, so a probe called from preparation, from the window and from cleanup
# cannot silently re-grant itself the wrong budget -- which is exactly what a remaining-seconds
# reading does when the clock it reads has not started.
cur_deadline() {
  if [ -z "$RUN_EPOCH" ]; then echo "$PREP_DEADLINE"
  elif [ "$CLEANUP_EPOCH" -eq 0 ]; then echo "$EXP_DEADLINE"
  else echo "$WORK_DEADLINE"; fi
}
bounded() { # LABEL DEADLINE_EPOCH OUT ERR -- COMMAND...
  local label="$1" dl="$2" out="$3" err="$4"; shift 4
  if [ "$1" = '--' ]; then shift; else
    record "HARNESS_BUG bounded '$label' called without --"; exits "${label}_HARNESS=bad-call"; BOUNDED_STATE=HARNESS_BUG; return 90
  fi
  if ! : > "$out" 2>/dev/null || ! : > "$err" 2>/dev/null; then
    record "CAPTURE_SETUP_FAILED $label out=$out err=$err"; exits "${label}_CAPTURE=SETUP_FAILED"; BOUNDED_STATE=SETUP_FAILED; return 91
  fi
  BOUNDED_STATE=NOT_REACHED
  TERMINATION=NOT_MEASURED
  case "$dl" in (''|*[!0-9]*) dl=0 ;; esac
  local now left; now=$(date +%s); left=$(( dl - now - KILL_GRACE_S ))
  if [ "$dl" -le 0 ] || [ "$left" -lt 1 ]; then
    BOUNDED_STATE=NOT_STARTED
    exits "${label}_BOUND=NOT_STARTED"
    record "BOUND_NOT_STARTED $label — ${left}s would remain after the ${KILL_GRACE_S}s escalation reserve. The step is NOT RUN."
    record "  TRUNCATED phase=$label got 0s. What it would have observed is NOT CAPTURED, which is not the statement 'not present'."
    return 125
  fi
  stamp "${label}_START bound=${left}s deadline_epoch=$dl"
  timeout -k "$KILL_GRACE_S" "$left" "$@" > "$out" 2> "$err" &
  local mpid=$!
  local myseq
  register_launched "$label" "$mpid" "$dl"
  myseq="$LAUNCH_SEQ"
  wait "$mpid"; local rc=$?
  stamp "${label}_END rc=$rc"
  exits "${label}_EXIT=$rc"
  if [ "$rc" -eq 124 ] || [ "$rc" -eq 137 ]; then
    BOUNDED_STATE=EXPIRED
    record "BOUND_EXPIRED $label after ${left}s (killer rc=$rc). The bound stopped THIS DRIVER'S WAIT and attempted to stop the operation; what actually stopped is measured below."
    measure_termination "$label" "$myseq" "$dl"
    return 124
  fi
  BOUNDED_STATE=RAN
  return $rc
}
cleanup_left() {
  [ "$CLEANUP_EPOCH" -eq 0 ] && { echo "$CLEANUP_REPORT_S"; return; }
  local now used left
  now=$(date +%s); used=$((now - CLEANUP_EPOCH)); left=$((CLEANUP_REPORT_S - used))
  [ "$left" -lt 0 ] && left=0
  echo "$left"
}
prep_left() {
  local now used left
  now=$(date +%s); used=$((now - PREP_EPOCH)); left=$((PREP_BUDGET_S - used))
  [ "$left" -lt 0 ] && left=0
  echo "$left"
}
prep_check() { # LABEL - called before each PREPARATION step
  [ -n "$RUN_EPOCH" ] && die "prep_check '$1' ran AFTER GO: a preparation step cannot be charged to the experimental window, and a sequence that reaches one here is mis-ordered."
  local left; left=$(prep_left)
  if [ "$left" -gt 0 ]; then
    record "PREP_BUDGET before '$1': ${left}s of ${PREP_BUDGET_S}s remain"
    return 0
  fi
  # A PREPARATION OVERRUN IS A REFUSAL TO START, NOT A TRUNCATED RUN. Nothing has been
  # dispatched, so there is no residue to report and no verdict to weaken: the honest
  # outcome is that the experiment never opened.
  record "PREP_DEADLINE reached before '$1' - the experimental window is NEVER OPENED. Nothing was created, so nothing is torn down and no capture is missing: this run did not start."
  set_original 8 "preparation deadline (${PREP_BUDGET_S}s) reached before $1; GO never given"
  exit 8
}
# GO - THE ONE PLACE THE EXPERIMENTAL CLOCK EVER STARTS (doyle 2026-09-13). It is a
# separate act from preparation on purpose: the 300s window pays for THIS RUN'S ACTIVITY,
# and it must not already be running while an elevated operator reads a request. MEASURED
# REASON: run 20260913T041410Z spent 134s of its 300s at the setup handoff and reached
# neither t1 nor t2.
go() { # WHY
  [ -n "$RUN_EPOCH" ] && { record "GO ignored - the experimental window is already open (opened $GO_UTC)"; return 0; }
  RUN_EPOCH=$(date +%s)
  EXP_DEADLINE=$((RUN_EPOCH + EXP_BUDGET_S))
  GO_UTC=$(date -u +%Y-%m-%dT%H:%M:%SZ)
  stamp "experimental_GO why=$1"
  record "GO ($1) at $GO_UTC - the ${EXP_BUDGET_S}s experimental window OPENS NOW, after $((RUN_EPOCH - PREP_EPOCH))s of preparation of the ${PREP_BUDGET_S}s allowed"
}
end_experimental() { # WHY — idempotent: the reporting clock starts exactly once
  [ -n "$EXPERIMENTAL_ENDED" ] && return 0
  EXPERIMENTAL_ENDED="$1"
  CLEANUP_EPOCH=$(date +%s)
  REPORT_DEADLINE=$((CLEANUP_EPOCH + CLEANUP_REPORT_S))
  WORK_DEADLINE=$((REPORT_DEADLINE - LEDGER_RESERVE_S))
  record "REPORTING_DEADLINES report_due=$REPORT_DEADLINE work_until=$WORK_DEADLINE (${LEDGER_RESERVE_S}s is RESERVED for the ledger and is not available to the work above it)"
  stamp "experimental_END why=$1"
  if [ -n "$RUN_EPOCH" ]; then
    record "EXPERIMENTAL_END ($1) at $((CLEANUP_EPOCH - RUN_EPOCH))s of the ${EXP_BUDGET_S}s budget; the ${CLEANUP_REPORT_S}s cleanup REPORTING deadline starts now"
  else
    # Reached without GO: the run ended during preparation. Saying '0s of 300s' would
    # report a window that never opened as one that opened and went unused.
    record "EXPERIMENTAL_END ($1) with the experimental window NEVER OPENED (no GO was given); the ${CLEANUP_REPORT_S}s cleanup REPORTING deadline starts now"
  fi
}
deadline_check() { # ACTIVITY-ONLY. LABEL — called before each activity step
  [ -z "$RUN_EPOCH" ] && die "activity step '$1' was reached with NO GO: the experimental window has not been opened, so this step has no budget to run under. A step that ran here would spend a window nobody granted."
  local left; left=$(exp_left)
  if [ "$left" -gt 0 ]; then
    record "BUDGET before '$1': ${left}s of ${EXP_BUDGET_S}s remain"
    return 0
  fi
  record "EXPERIMENTAL_DEADLINE reached before '$1' — activity ENDS HERE and cleanup begins; the deadline does not skip it"
  record "  TRUNCATED phase=$1 got 0s. Whatever this phase would have captured is NOT CAPTURED, which is not the same statement as 'not present'."
  end_experimental "experimental deadline before $1"
  set_original 7 "experimental deadline (${EXP_BUDGET_S}s) reached before $1"
  exit 7
}

# ---- the D2 capture point --------------------------------------------------
# THE ARGUMENT FORM IS MEASURED, NOT ASSUMED (control receipt, 2026-09-13). MEASURED ON THIS
# BOX, FOR THIS INVOCATION SHAPE -- a [string[]] parameter reached from bash through
# powershell.exe -- and the finding is scoped to exactly that; it is not a claim that -File
# is broken in general:
#   -File <script> -RuleName a,b   bound ONE element "a,b". The capture would then query a
#                                  name that cannot exist and record NO_RULE for both halves
#                                  of a pair that is present.
#   -File <script> -RuleName a b   failed binding outright ("A positional parameter cannot be
#                                  found"), exit 1.
#   -Command "& '<script>' -RuleName @('a','b'); exit $LASTEXITCODE"   delivered TWO elements.
# The trailing `exit $LASTEXITCODE` is load-bearing in the same measured way: without it a
# script exit of 2 arrived as 1, laundering the one exit that is this instrument's entire
# failure report.
#
# THE EXIT GOES TO ITS OWN FILE. It is never mixed with, inferred from or overwritten by the
# setup's exit, and no property state is ever encoded into it (plan §5.0).
#
# THE CAPTURE IS BOUNDED, AND A HANG IS ITS OWN OUTCOME (doyle, 2026-09-13). A budget checked
# BETWEEN steps bounds a sequence, not a process: a capture that never returns would sit
# inside one step while both deadlines pass unread. So each point runs under an explicit
# bound and a hang is recorded as CAPTURE_TIMEOUT -- which is neither a written document nor
# a write failure, and must never be read as either. The bound is passed in by the caller
# because the two clocks are different: the experimental budget pays for t1 and t2, and what
# remains of the REPORTING deadline pays for t3.
d2_capture_at() { # POINT BOUND_SECONDS
  local point="$1" bound="$2"
  local out="$R/d2-$point.json" exf="$R/d2-$point.exit"
  case "$bound" in (''|*[!0-9]*) bound=0 ;; esac
  if [ "$bound" -le 0 ]; then
    echo "NO_BUDGET" > "$exf"
    record "D2($point) NOT RUN — no budget remained to run it under a bound. NOT CAPTURED is not 'not present'."
    return 1
  fi
  [ "$bound" -gt 180 ] && bound=180   # plan §4 gives the capture phase 180s; no point may exceed it
  local cmd="& '$BIN/d2_capture.ps1' -CapturePoint '$point' -RuleName @('$RULE_TAILNET','$RULE_LAN')"
  cmd="$cmd -Port $PORT -IsolatedHome '$H' -RunId '$RUN_ID' -OutPath '$out'"
  cmd="$cmd -ControlRuleName '$CONTROL_RULE' -AbsentControlName '$ABSENT_CONTROL'"
  cmd="$cmd -PreSetupAbsence '$PRE_SETUP_ABSENCE' -SetupIntervalStart '$SETUP_START_UTC' -SetupIntervalEnd '$SETUP_END_UTC'"
  cmd="$cmd; exit \$LASTEXITCODE"
  # THE DEADLINE, NOT A DURATION. The point's own 180s cap (plan §4) stays and becomes the
  # earlier of two instants; bounded() subtracts the escalation reserve from whichever wins,
  # so TERM-then-KILL completes BY the deadline instead of five seconds past it.
  local dl cap; dl=$(cur_deadline); cap=$(( $(date +%s) + bound ))
  [ "$cap" -lt "$dl" ] && dl="$cap"
  bounded "d2_${point}_capture" "$dl" "$R/d2-$point-capture.out" "$R/d2-$point-capture.err" -- \
    powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "$cmd"
  local rc=$?
  if [ "$rc" -eq 125 ]; then
    echo "NO_BUDGET" > "$exf"
    record "D2($point) NOT RUN — the remaining budget could not cover the ${KILL_GRACE_S}s escalation reserve. NOT CAPTURED is not 'not present'."
    return 1
  fi
  if [ "$rc" -eq 124 ] || [ "$rc" -eq 137 ]; then
    echo "TIMEOUT" > "$exf"
    # COMPLETION UNVERIFIED IS NOT AN ABSENT DOCUMENT (doyle O2VBV5LC). The serialize, the
    # JSON write and the base64 write are separate stages in 69b8506a; an expired bound can
    # land anywhere among them, so the artifact state is INSPECTED, never inferred from the
    # expiry. Both paths are preserved under names that say so, and neither is read here.
    preserve_unverified "d2_${point}_capture" "$out" "$out.b64"
    record "D2($point) CAPTURE_COMPLETION=UNVERIFIED after the bound expired (killer rc=$rc). The OBSERVATION was not completed; what is on disk at $out is a separate question, preserved above and not answered here."
    # THE SURVIVOR IS FOUND BY ITS REGISTERED IDENTITY, NOT BY A STRING. The predecessor said a
    # survivor "carries -IsolatedHome on its command line, so BY CONSTRUCTION it is counted" --
    # that predicate is exactly the one the r10 residuals defeated (they ran `daemon run
    # --detached` and `daemon brain`, neither carrying the home). bounded() registered this
    # child's pid and creation instant at launch, and cleanup re-queries THAT.
    record "  D2($point) TERMINATION=$TERMINATION (measured, not assumed; see launched-identities.txt). A SURVIVING or UNREADABLE outcome blocks CLEANUP=VERIFIED."
    return 124
  fi
  echo "$rc" > "$exf"
  stamp "d2_${point}_END rc=$rc"
  exits "d2_${point}_capture_EXIT=$rc"
  # THE EXIT CONTRACT OF 69b8506a, ALL FIVE VALUES (the coupled change this integration owed;
  # the predecessor's line knew only 0/2/3, so a 4 or a 5 reached the ledger as an unlabelled
  # nonzero). NEITHER 2 NOR ANY OTHER CODE ASSERTS THE ARTIFACT STATE: exit 2 names the STAGE
  # that failed (D2_WRITE_FAILED_JSON / D2_WRITE_FAILED_B64) and the file may be absent,
  # partial, or a pre-existing one -- that requires inspection.
  record "D2($point) native_exit=$rc out=d2-$point.json (0=written AND read back and verified; 2=SERIALIZATION or a WRITE failed, stage named, artifact state NOT asserted; 3=arguments rejected; 4=written, receipt digest not takeable, NONZERO ON PURPOSE; 5=written, read-back digest disagrees with the bytes written. A document full of DENIED states IS a capture.)"
  # A ZERO IS NOT A CAPTURE. Measured on this box: `-Command "& '<path>' ...; exit $LASTEXITCODE"`
  # with a path PowerShell cannot resolve prints CommandNotFoundException and still hands the
  # caller EXIT 0 -- a clean zero from a command that never ran. So the document's existence is
  # asserted here rather than deduced from the exit, and validation decides the rest.
  if [ "$rc" -eq 0 ] && [ ! -f "$out" ]; then
    record "  D2($point) CLAIMED_OK_WITHOUT_DOCUMENT — exit 0 and no file at $out. A zero from a command that never ran looks exactly like this; the point is NOT CAPTURED."
  fi
  return $rc
}

# VALIDATION DECIDES WHETHER THE OBSERVATION WAS MADE. It never decides whether a value is
# the wanted one: [5, 20] is accepted exactly as [1] would be, and null, "" , [] and ABSENT
# are four legitimate observations. Only a MISSING REQUIRED OBSERVATION makes a document
# incomplete; a DENIED or ERROR outcome is a QUERY FAILURE THAT WAS OBSERVED and is counted
# and reported beside it. Exit 2 is an unreadable document -- an instrument failure, not a
# finding about the host.
# IT SETS A GLOBAL AND ECHOES NOTHING (r10's handoff_request precedent, and the second half
# of the defect the control caught): `record` TEES TO STDOUT, so any helper that logs and then
# echoes a value hands its caller the log as well as the value. VALIDATE_RESULT is read by the
# caller on the next line.
VALIDATE_RESULT=NOT_VALIDATED
d2_validate_at() { # POINT -> sets VALIDATE_RESULT; returns nothing on stdout
  # TWO STATEMENTS ON PURPOSE (r10's v7 lesson, which I re-broke and the control caught): a
  # single `local` expands EVERY right-hand side before assigning any name in it, so
  # `local point="$1" doc="$R/d2-$point.json"` builds the path from an UNSET point and every
  # document reads as NO_DOCUMENT -- three captures on disk, all reported as absent.
  local point="$1"
  local doc="$R/d2-$point.json"
  if [ ! -f "$doc" ]; then
    record "D2_VALIDATE($point) NO_DOCUMENT at $doc — nothing to validate, and nothing may be concluded from its absence beyond 'not captured'"
    VALIDATE_RESULT=NO_DOCUMENT; return
  fi
  python "$BIN/d2_validate.py" --doc "$doc" --point "$point" --run "$RUN_ID" \
    > "$R/d2-$point-validate.out" 2>&1
  local rc=$?
  exits "d2_${point}_validate_EXIT=$rc"
  while IFS= read -r line; do record "  D2_VALIDATE($point) $line"; done < "$R/d2-$point-validate.out"
  case "$rc" in
    0) VALIDATE_RESULT=COMPLETE ;;
    1) VALIDATE_RESULT=INCOMPLETE ;;
    *) VALIDATE_RESULT=UNREADABLE ;;
  esac
  # A DENIED OR ERROR OUTCOME IS A VALID OBSERVATION AND STILL NOT A SUCCESSFUL ONE (doyle,
  # 2026-09-13). Validation's job ends at "the observation was MADE", so it exits 0 on a captured
  # refusal -- correctly. The count is carried out here as its OWN number so the CONTRACT can
  # refuse a document that validates, and so neither statement can hide the other.
  VALIDATE_QF=0
  local dn er
  dn=$(awk '/^D2VALIDATE point=/{for(i=1;i<=NF;i++) if ($i ~ /^denied=/) {sub("denied=","",$i); print $i; exit}}' "$R/d2-$point-validate.out" | head -1)
  er=$(awk '/^D2VALIDATE point=/{for(i=1;i<=NF;i++) if ($i ~ /^error=/) {sub("error=","",$i); print $i; exit}}' "$R/d2-$point-validate.out" | head -1)
  case "$dn" in (''|*[!0-9]*) dn=0 ;; esac
  case "$er" in (''|*[!0-9]*) er=0 ;; esac
  VALIDATE_QF=$((dn + er))
  if [ "$VALIDATE_QF" -gt 0 ]; then
    record "  D2_VALIDATE($point) QUERY_FAILURES=$VALIDATE_QF (denied=$dn error=$er) -- observed and recorded, and NOT successful observations: this point cannot satisfy the capture contract"
  fi
}

# ---- run-bound process identity, captured WHILE THE PROCESSES ARE LIVE ----------
# Cleanup can only re-query an identity somebody wrote down. This is where it is written
# down, immediately after the elevated leg that starts the daemon, and it is the ONLY basis
# on which cleanup later says a process of this run is gone.
#
# WHY NOT A COMMAND-LINE MATCH (doyle, 2026-09-13): r10's actual survivors ran
# `daemon run --detached` and `daemon brain --generation 0 --start-reason cold` -- neither
# carries the isolated home, so a home-string predicate reports a confident CLEAR over exactly
# the processes that were left behind. The pid FILE names the supervisor, the process TABLE
# gives it a creation time, an executable path and a command line, and the parent relationship
# gives the brain. Those are what get re-queried.
#
# It records, and records nothing it could not read. A missing pid file, a non-numeric pid, an
# unreadable table: each is written as IDENT_PROBE=UNREADABLE with its reason, and cleanup reads
# that as UNREADABLE rather than as an empty list.
capture_run_identities() { # WHEN
  local when="$1"
  bounded "identity_capture_$when" "$(cur_deadline)" "$R/run-identities.txt" "$R/run-identities.err" -- \
    env SPT_D2_HOME="$H" pwsh -NoProfile -Command '
    $h = $env:SPT_D2_HOME
    $pidFile = Join-Path $h "daemon.pid"
    if (-not (Test-Path $pidFile)) { "IDENT_PROBE=UNREADABLE reason=no-pid-file"; exit 0 }
    $sp = (Get-Content -Raw $pidFile).Trim()
    if ($sp -notmatch "^[0-9]+$") { "IDENT_PROBE=UNREADABLE reason=pid-file-not-numeric"; exit 0 }
    try { $all = @(Get-CimInstance Win32_Process -ErrorAction Stop) }
    catch { "IDENT_PROBE=UNREADABLE reason=enumeration-failed"; exit 0 }
    if ($all.Count -eq 0) { "IDENT_PROBE=UNREADABLE reason=empty-enumeration-is-not-an-empty-host"; exit 0 }
    "IDENT_ENUM total=$($all.Count) supervisor_pid_from_file=$sp"
    $target = [int]$sp
    $sup = @($all | Where-Object { $_.ProcessId -eq $target })
    if ($sup.Count -eq 0) { "IDENT_PROBE=UNREADABLE reason=supervisor-pid-$sp-not-in-process-table"; exit 0 }
    $rows = @($sup[0]) + @($all | Where-Object { $_.ParentProcessId -eq $target })
    $i = 0
    foreach ($p in $rows) {
      $role = if ($i -eq 0) { "supervisor" } else { "brain" }
      $c = try { $p.CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") } catch { "UNREADABLE" }
      "IDENT role=$role pid=$($p.ProcessId) created=$c exe=[$($p.ExecutablePath)] cmd=[$($p.CommandLine)]"
      $i++
    }
    "IDENT_PROBE=OK tracked=$($rows.Count)"
  '
  local rc=$?
  IDENT_CAPTURE_RC=$rc
  # A BOUND THAT EXPIRED HERE IS THE WORST ONE TO MISREAD: cleanup can only re-query an
  # identity somebody wrote down, so an expired identity capture makes the run's residue
  # UNREADABLE -- which is never CLEAR -- rather than making the host empty.
  cat "$R/run-identities.err" >> "$R/run-identities.txt" 2>/dev/null
  while IFS= read -r line; do record "  IDENTITY($when) $line"; done < "$R/run-identities.txt"
  local n
  n=$(grep -c '^IDENT role=' "$R/run-identities.txt" 2>/dev/null)
  case "$n" in (''|*[!0-9]*) n=0 ;; esac
  if [ "$n" -eq 0 ]; then
    record "  IDENTITY($when) NO PROCESS TRACKED. Cleanup will read this as UNREADABLE, never as clean: an identity nobody captured cannot later be shown to be gone."
  else
    record "  IDENTITY($when) $n process identities recorded (supervisor from daemon.pid plus its children). These, re-queried fresh, are what decide the cleanup verdict."
  fi
  return 0
}
# ---- is the captured identity set USABLE AS EVIDENCE OF ABSENCE? ---------------
# (doyle's second admission blocker, 2026-09-13.) Re-querying the rows we happen to have only
# proves something about the rows we happen to have. A capture INTERRUPTED after the supervisor
# row leaves one plausible-looking record; that pid is later absent, every tracked identity then
# reads GONE, and cleanup declares CLEAR while an UNRECORDED BRAIN is still running. The gap is
# not in the re-query, it is in trusting a partial capture.
#
# So a capture may support CLEAR only when ALL of these hold, and each is checked, not assumed:
#   the capture command exited 0;
#   EXACTLY ONE completion marker `IDENT_PROBE=OK tracked=N` is present;
#   N equals the number of IDENT rows actually written;
#   every row carries a numeric pid, a READABLE creation timestamp, a non-empty executable and a
#     non-empty command line.
# Anything else is UNREADABLE -- INCLUDING the case where every recorded pid is now absent.
ts_readable() { # a timestamp we can COMPARE -- parsed, not merely shaped
  # SHAPE IS NOT VALIDITY (doyle, 2026-09-13). "2026-02-30T00:00:00.000Z" matches every character
  # class an ISO-8601 pattern asks for and names a day that does not exist, so a pattern test would
  # let an impossible date establish pid reuse. This PARSES the value with the calendar and treats
  # a parse failure as unreadable. The empty string is rejected first, because `date -d ""` is
  # accepted as "now" and would otherwise pass.
  [ -n "$1" ] || return 1
  case "$1" in [0-9][0-9][0-9][0-9]-*) ;; *) return 1 ;; esac
  date -u -d "$1" +%s >/dev/null 2>&1
}
capture_is_complete() { # -> 0 when the recorded set may support a CLEAR verdict
  local f="$R/run-identities.txt"
  CAPTURE_INTEGRITY="unset"
  [ -f "$f" ] || { CAPTURE_INTEGRITY="no capture file"; return 1; }
  if [ "${IDENT_CAPTURE_RC:-1}" -ne 0 ]; then CAPTURE_INTEGRITY="the capture command exited ${IDENT_CAPTURE_RC:-unknown}"; return 1; fi
  local marks rows tracked
  marks=$(grep -c '^IDENT_PROBE=OK tracked=' "$f"); case "$marks" in (''|*[!0-9]*) marks=0 ;; esac
  rows=$(grep -c '^IDENT role=' "$f"); case "$rows" in (''|*[!0-9]*) rows=0 ;; esac
  if [ "$marks" -ne 1 ]; then CAPTURE_INTEGRITY="expected exactly one IDENT_PROBE=OK completion marker, found $marks"; return 1; fi
  tracked=$(sed -n 's/^IDENT_PROBE=OK tracked=\([0-9][0-9]*\).*/\1/p' "$f" | tail -1)
  case "$tracked" in (''|*[!0-9]*) CAPTURE_INTEGRITY="the completion marker carries no readable count"; return 1 ;; esac
  if [ "$rows" -ne "$tracked" ]; then CAPTURE_INTEGRITY="the capture says it tracked $tracked processes but wrote $rows rows"; return 1; fi
  if [ "$rows" -eq 0 ]; then CAPTURE_INTEGRITY="no identity rows were written"; return 1; fi
  local line lpid lcreated lexe lcmd
  while IFS= read -r line; do
    lpid=$(printf '%s' "$line" | sed -n 's/^IDENT .* pid=\([0-9][0-9]*\) .*/\1/p')
    lcreated=$(printf '%s' "$line" | sed -n 's/^IDENT .* created=\([^ ]*\) .*/\1/p')
    lexe=$(printf '%s' "$line" | sed -n 's/^IDENT .* exe=\[\(.*\)\] cmd=\[.*\]$/\1/p')
    lcmd=$(printf '%s' "$line" | sed -n 's/^IDENT .* cmd=\[\(.*\)\]$/\1/p')
    [ -n "$lpid" ] || { CAPTURE_INTEGRITY="a row carries no numeric pid"; return 1; }
    ts_readable "$lcreated" || { CAPTURE_INTEGRITY="pid $lpid has an unreadable creation timestamp [$lcreated]"; return 1; }
    [ -n "$lexe" ] || { CAPTURE_INTEGRITY="pid $lpid has an empty executable path"; return 1; }
    [ -n "$lcmd" ] || { CAPTURE_INTEGRITY="pid $lpid has an empty command line"; return 1; }
  done < <(grep '^IDENT role=' "$f")
  CAPTURE_INTEGRITY="complete: $rows rows, marker count $tracked, all fields readable"
  return 0
}
# ---- 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. 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, so those independent steps waited on a receipt that might never come.
# The cleanup wait is now bounded by WHAT REMAINS OF THE REPORTING DEADLINE, and a missing
# receipt leaves the state marker set and proceeds.
#
# D2 ADDS THREE OBLIGATIONS HERE, all of them before or around the teardown:
#   t3, captured IMMEDIATELY BEFORE THE TEARDOWN REQUEST IS WRITTEN — the last look at a
#      pair that is about to stop existing;
#   the MANIFEST, hashed BEFORE teardown, so the documents are pinned while their subject
#      is still there to re-read;
#   RESIDUAL IDENTITY, reported when the teardown could not be verified or a daemon
#      remains: pid + creation time + executable path + command line, read fresh. This
#      driver REPORTS and STOPS. It kills nothing: the r10 pid authorization was
#      pid-specific and is SPENT, and a fresh pid-naming authorization is a STOP, not a
#      step (plan §6).
#
# 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.
# ---- RESIDUE, MEASURED AS ITS OWN ACT (doyle 2026-09-13) -------------------
# Extracted from cleanup() unchanged in substance so it can be called TWICE: once as the GATE
# before anything is stopped, and once as the VERDICT after cleanup has run. The scan is a
# MEASUREMENT and never complains; only the verdict pass raises a cleanup failure, because a
# LIVE process before the stop is the reason to stop, while a LIVE process after it is a
# finding. Each pass writes its own evidence file, so neither overwrites the other's record.
#   tag      names the pass and its evidence file (residue-<tag>.txt)
#   verdict  yes|no -- whether this pass may raise cleanup failures
residue_scan() { # TAG VERDICT
  local tag="$1" verdict="$2"
  record "RESIDUE_SCAN($tag) begins; verdict_mode=$verdict"
RESIDUE_LIVE=0; RESIDUE_UNREADABLE=0; RESIDUE_GONE=0
if has_state daemon_may_run || has_state listener_may_exist; then
  if [ ! -f "$R/run-identities.txt" ]; then
    RESIDUE_UNREADABLE=1
    cfail "no run-bound identities were ever captured, so nothing can be re-queried: residual state is UNREADABLE, which is NOT clean. Whatever this run started is unattributed."
  elif ! grep -q '^IDENT role=' "$R/run-identities.txt"; then
    RESIDUE_UNREADABLE=1
    record "  $(grep '^IDENT_PROBE=' "$R/run-identities.txt" | tail -1)"
    cfail "identity capture produced no tracked process (see run-identities.txt): residual state is UNREADABLE, never CLEAR."
  else
    # THE GATE FIRST. Its verdict is independent of what the re-query finds: an incomplete
    # capture cannot support CLEAR even if every pid it did record is now absent.
    CAPTURE_USABLE=no
    if capture_is_complete; then
      CAPTURE_USABLE=yes
      record "  IDENTITY_CAPTURE_INTEGRITY=OK ($CAPTURE_INTEGRITY)"
    else
      record "  IDENTITY_CAPTURE_INTEGRITY=INCOMPLETE ($CAPTURE_INTEGRITY)"
      record "  An incomplete capture cannot show that a process is gone -- only that a row we"
      record "  happen to hold is gone. Whatever this run started that was never recorded is"
      record "  UNATTRIBUTED, so the residual state is UNREADABLE no matter what follows."
    fi
    : > "$R/residue-$tag.txt"
    while IFS= read -r ident; do
      local ipid irole icreated iexe icmd out
      irole=$(printf '%s' "$ident" | sed -n 's/^IDENT role=\([^ ]*\) .*/\1/p')
      ipid=$(printf '%s' "$ident" | sed -n 's/^IDENT .* pid=\([0-9][0-9]*\) .*/\1/p')
      icreated=$(printf '%s' "$ident" | sed -n 's/^IDENT .* created=\([^ ]*\) .*/\1/p')
      iexe=$(printf '%s' "$ident" | sed -n 's/^IDENT .* exe=\[\(.*\)\] cmd=\[.*\]$/\1/p')
      icmd=$(printf '%s' "$ident" | sed -n 's/^IDENT .* cmd=\[\(.*\)\]$/\1/p')
      if [ -z "$ipid" ]; then
        RESIDUE_UNREADABLE=$((RESIDUE_UNREADABLE + 1))
        echo "RECHECK role=$irole state=UNREADABLE reason=unparseable-identity-line" >> "$R/residue-$tag.txt"
        continue
      fi
      out=$(SPT_D2_PID="$ipid" pwsh -NoProfile -Command '
        $target = [int]$env:SPT_D2_PID
        try { $all = @(Get-CimInstance Win32_Process -ErrorAction Stop) }
        catch { "PROC=UNREADABLE reason=enumeration-failed"; exit 0 }
        if ($all.Count -eq 0) { "PROC=UNREADABLE reason=empty-enumeration-is-not-an-empty-host"; exit 0 }
        $p = @($all | Where-Object { $_.ProcessId -eq $target })
        if ($p.Count -eq 0) { "PROC=ABSENT pid=$target enum_total=$($all.Count)"; exit 0 }
        $q = $p[0]
        $c = try { $q.CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") } catch { "UNREADABLE" }
        "PROC=PRESENT pid=$($q.ProcessId) created=$c exe=[$($q.ExecutablePath)] cmd=[$($q.CommandLine)]"
      ' 2>&1 | tr -d '\r' | grep '^PROC=' | tail -1)
      case "$out" in
        PROC=ABSENT*)
          RESIDUE_GONE=$((RESIDUE_GONE + 1))
          echo "RECHECK role=$irole pid=$ipid state=GONE (the tracked identity is no longer in the process table)" >> "$R/residue-$tag.txt" ;;
        PROC=PRESENT*)
          local ncreated nexe ncmd
          ncreated=$(printf '%s' "$out" | sed -n 's/^PROC=PRESENT .* created=\([^ ]*\) .*/\1/p')
          nexe=$(printf '%s' "$out" | sed -n 's/^PROC=PRESENT .* exe=\[\(.*\)\] cmd=\[.*\]$/\1/p')
          ncmd=$(printf '%s' "$out" | sed -n 's/^PROC=PRESENT .* cmd=\[\(.*\)\]$/\1/p')
          # WHAT ESTABLISHES WHAT (doyle, 2026-09-13). Only a READABLE creation time that
          # DIFFERS establishes pid reuse -- i.e. that our process is gone and this pid now
          # belongs to a stranger. An unreadable creation time on either side establishes
          # NOTHING and stays UNREADABLE. A path or command-line mismatch ALONE does not make
          # our process gone: pid plus creation instant is the identity, so that case is
          # reported as LIVE with the mismatch named, never as GONE.
          if ! ts_readable "$ncreated" || ! ts_readable "$icreated"; then
            RESIDUE_UNREADABLE=$((RESIDUE_UNREADABLE + 1))
            echo "RECHECK role=$irole pid=$ipid state=UNREADABLE reason=creation-time-not-a-readable-timestamp (recorded=[$icreated] now=[$ncreated]); an empty or malformed value establishes NEITHER reuse NOR survival" >> "$R/residue-$tag.txt"
          elif [ "$ncreated" != "$icreated" ]; then
            RESIDUE_GONE=$((RESIDUE_GONE + 1))
            echo "RECHECK role=$irole pid=$ipid state=GONE-PID-REUSED (creation time differs: recorded=[$icreated] now=[$ncreated]; the pid answers, OURS is gone, and a bare pid match would have called this stranger residue: exe=[$nexe] cmd=[$ncmd])" >> "$R/residue-$tag.txt"
          elif [ "$nexe" = "$iexe" ] && [ "$ncmd" = "$icmd" ]; then
            RESIDUE_LIVE=$((RESIDUE_LIVE + 1))
            echo "RESIDUE role=$irole pid=$ipid created=$icreated exe=[$iexe] cmd=[$icmd] state=LIVE" >> "$R/residue-$tag.txt"
          else
            RESIDUE_LIVE=$((RESIDUE_LIVE + 1))
            echo "RESIDUE role=$irole pid=$ipid created=$icreated state=LIVE-FIELD-MISMATCH (same pid and same creation instant, so this IS our process and it is still running; the differing read is reported rather than resolved: exe recorded=[$iexe] now=[$nexe]; cmd recorded=[$icmd] now=[$ncmd])" >> "$R/residue-$tag.txt"
          fi ;;
        *)
          RESIDUE_UNREADABLE=$((RESIDUE_UNREADABLE + 1))
          echo "RECHECK role=$irole pid=$ipid state=UNREADABLE [$out]" >> "$R/residue-$tag.txt" ;;
      esac
    done < <(grep '^IDENT role=' "$R/run-identities.txt")
    while IFS= read -r line; do record "  $line"; done < "$R/residue-$tag.txt"
    record "  RESIDUE_SUMMARY($tag) live=$RESIDUE_LIVE gone=$RESIDUE_GONE unreadable=$RESIDUE_UNREADABLE (tracked identities re-queried fresh; LIVE and UNREADABLE are different facts and both refuse a clean verdict)"
    if [ "$verdict" = yes ] && [ "$RESIDUE_LIVE" -gt 0 ]; then
      cfail "$RESIDUE_LIVE tracked process(es) of THIS run are still LIVE, identified above by pid + creation time + executable + command line. A fresh pid-naming authorization is REQUIRED and is a STOP, not a step: this driver reports them and acts on none."
    fi
    if [ "$verdict" = yes ] && [ "$RESIDUE_UNREADABLE" -gt 0 ]; then
      cfail "$RESIDUE_UNREADABLE tracked identity/identities could not be re-queried. UNREADABLE is not CLEAR: this run cannot state that its processes are gone."
    fi
    if [ "$CAPTURE_USABLE" != yes ]; then
      RESIDUE_UNREADABLE=$((RESIDUE_UNREADABLE + 1))
      if [ "$verdict" = yes ]; then
        cfail "the identity capture was INCOMPLETE ($CAPTURE_INTEGRITY), so the recorded rows cannot support a clean verdict: residual state is UNREADABLE. An interrupted capture that omitted a child would otherwise read as CLEAR once its one recorded pid went away."
      fi
    fi
  fi
  # SUPPLEMENTARY, AND KNOWN-INCOMPLETE ON ITS OWN. Evidence beside the identity verdict, never
  # the verdict: a process running the pinned executable may belong to another lane using the
  # same worktree, and attributing it here would manufacture residue. It is kept because if
  # identity capture came back UNREADABLE, this list is the actionable one.
  SPT_D2_EXE="$EXE" pwsh -NoProfile -Command '
    $exe = $env:SPT_D2_EXE
    try { $all = @(Get-CimInstance Win32_Process -ErrorAction Stop) }
    catch { "SUBJECT_EXE_PROBE=UNREADABLE reason=enumeration-failed"; exit 0 }
    if ($all.Count -eq 0) { "SUBJECT_EXE_PROBE=UNREADABLE reason=empty-enumeration"; exit 0 }
    $hit = @($all | Where-Object { $_.ExecutablePath -and $_.ExecutablePath -eq $exe })
    foreach ($p in $hit) { "SUBJECT_EXE pid=$($p.ProcessId) cmd=[$($p.CommandLine)]" }
    "SUBJECT_EXE_PROBE=OK running_the_pinned_executable=$($hit.Count) enum_total=$($all.Count)"
  ' > "$R/subject-exe-processes.txt" 2>&1
  while IFS= read -r line; do record "  $line"; done < "$R/subject-exe-processes.txt"
  record "  NOTE: that line is EVIDENCE, not attribution -- another lane may run the same executable. The verdict is decided by the tracked identities above."
else
  record "CLEANUP_SKIP residue — neither a daemon nor a listener state was ever marked, so no process of this run was ever dispatched"
fi
}

cleanup() {
  # THE INCOMING NATIVE STATUS, CAPTURED FIRST AND BEFORE ANYTHING ELSE (r8, doyle).
  # ORIGINAL_RC being zero is NOT proof the process was exiting zero: a path could exit
  # nonzero without ever calling set_original, and raising that to 6 would replace a
  # real failure with a cleanup complaint.
  # WRITTEN ON ONE LINE ON PURPOSE: `local incoming` first and `incoming=$?` after would
  # read local's OWN success, which is always 0. The expansion has to happen in the same
  # command that declares it.
  local incoming=$?
  [ "$CLEANUP_ENTERED" -eq 1 ] && return 0
  CLEANUP_ENTERED=1
  # Whatever brought us here — a completed sequence, a die, a signal or the experimental
  # deadline — ACTIVITY IS OVER NOW, and the reporting clock starts here if it has not.
  end_experimental "cleanup entered"
  record "CLEANUP_BEGIN states=[$(ls "$ST" 2>/dev/null | tr '\n' ' ')] reporting_deadline=${CLEANUP_REPORT_S}s"

  # R6 — IS SOMEONE ELSE STILL ACTING ON THIS HOST? (doyle O2VBV5LC.) This is a different
  # question from the marker/measurement gates below, which ask "is there something to stop".
  # A measurement taken while an elevated leg is mid-reconcile can read LIVE or GONE for
  # reasons that have nothing to do with what this run left behind, and dispatching a removal
  # while a setup may still be writing is two elevated commands mutating one rule store with
  # no ordering between them. So: while the setup is OUTSTANDING, EVERY cleanup mutation is
  # withheld -- the listener stop, the rule teardown and the daemon stop alike.
  #
  # PROOF OF COMPLETION IS THE RECEIPT'S TERMINAL FIELDS, NOT ITS PRESENCE. A NONZERO native
  # exit is a COMPLETED outcome (doyle B3CMWRQI): the test is whether the leg FINISHED, not
  # whether it succeeded, and treating a refusal as outstanding would withhold cleanup from
  # exactly the runs that most need it. Only an UNREAD exit (255: absent, malformed, or more
  # than one record) fails this, because an unread exit is not a zero one.
  #
  # THE READ HAPPENS ONCE AND NEVER WAITS. A receipt that arrived late is evidence to read,
  # never a reason to spend reporting budget waiting for one.
  SETUP_OUTSTANDING=no
  # THE TWO ABSENCES ARE DIFFERENT QUESTIONS, AND r2 COLLAPSED THEM (doyle 5N5TZOBG; measured in
  # group G). "No setup was ever dispatched" is a statement about the MARKER. An unassigned
  # SETUP_RECEIPT path is a statement about THIS DRIVER'S OWN BOOKKEEPING, and while the marker
  # is set it is the absence of a reading about a leg that may be running — never evidence that
  # nothing was dispatched. The driver marks fw_mutation_may_have_occurred BEFORE the dispatch and
  # assigns SETUP_RECEIPT AFTER handoff_request has already written the request to disk, so a
  # signal in between lands in exactly that state, with the request file sitting there as evidence
  # that the dispatch DID happen.
  #
  # THE GUARANTEE IS HERE, NOT IN THE ORDER OF TWO ASSIGNMENTS (doyle's ruling). Moving the
  # assignment earlier would narrow the window and would not close it: any dispatch-then-record
  # sequence has one, and a window narrowed by rearrangement is not a safety property.
  if ! has_state fw_mutation_may_have_occurred; then
    SETUP_COMPLETION=NOT_REQUESTED
    record "R6 setup_completion=NOT_REQUESTED — the mutation marker was never set, so no elevated setup was ever dispatched: nothing is outstanding and the gates below decide on their own measurements"
  elif [ -z "${SETUP_RECEIPT:-}" ]; then
    SETUP_COMPLETION="UNPROVEN: no-receipt-path-assigned"
    SETUP_OUTSTANDING=yes
    record "R6 setup_completion=UNPROVEN missing: no-receipt-path-assigned — the mutation marker IS set and this run holds no receipt path to read, which happens when it was interrupted between writing the request and recording where the answer will arrive. A DISPATCH CANNOT BE DISPROVED HERE, so the leg is treated as OUTSTANDING and every cleanup mutation is withheld. The cost of being wrong this way is a PENDING report; the cost of being wrong the other way is an autostarting stop racing a leg that may still be starting processes, which is IR-124."
  else
    local r6_missing='' r6_nonce r6_exit
    [ -f "$SETUP_RECEIPT" ] || r6_missing="$r6_missing no-receipt-file"
    r6_nonce=$(grep -c "^nonce: $SETUP_NONCE\$" "$SETUP_RECEIPT" 2>/dev/null)
    case "$r6_nonce" in (''|*[!0-9]*) r6_nonce=0 ;; esac
    [ "$r6_nonce" -eq 1 ] || r6_missing="$r6_missing nonce-lines=$r6_nonce"
    r6_exit=$(HO_RECEIPT="$SETUP_RECEIPT" handoff_exit)
    [ "$r6_exit" = 255 ] && r6_missing="$r6_missing exit-record-unread"
    case "$SETUP_END_UTC" in
      ABSENT|UNPARSEABLE|'') r6_missing="$r6_missing setup-return-stamp=$SETUP_END_UTC" ;;
    esac
    [ "$TS_ORDER" = OK ] || r6_missing="$r6_missing timestamp_order=$TS_ORDER"
    if [ -n "$r6_missing" ]; then
      SETUP_COMPLETION="UNPROVEN:$r6_missing"
      SETUP_OUTSTANDING=yes
      record "R6 setup_completion=UNPROVEN missing:$r6_missing — the leg cannot be shown to have finished. UNPROVEN IS TREATED AS OUTSTANDING: a leg that finished without writing a terminal field is indistinguishable from one still running, and the cost of being wrong this way is a PENDING report."
    else
      SETUP_COMPLETION=PROVEN
      record "R6 setup_completion=PROVEN nonce=$SETUP_NONCE exit=$r6_exit (a nonzero exit is a COMPLETED outcome) setup_return=$SETUP_END_UTC timestamp_order=$TS_ORDER"
    fi
  fi

  # 1. THE LISTENER -- MEASURED BEFORE IT IS TOUCHED (doyle 2026-09-13; IR-124).
  #    The predecessor ran `serve lan --stop` on has_state listener_may_exist ALONE. That marker
  #    is set BEFORE the setup is dispatched, deliberately, so that a REFUSED setup still tears
  #    down -- which means it is a statement about what this run INTENDED, never about what the
  #    host holds. In run 20260913T041410Z the setup was DECLINED, nothing was ever started, and
  #    the stop ran anyway; because `serve lan --stop` reaches the broker through ensure_running
  #    (serveverb.rs:191) it CREATED exactly what cleanup exists to remove -- supervisor 45944 at
  #    04:19:18.031Z and brain 22524 at 04:19:19.769Z, both the pinned executable. That is IR-124.
  #
  #    THE MARKER NOW DECIDES WHETHER THE QUESTION IS ASKED. THE MEASUREMENT DECIDES WHETHER THE
  #    COMMAND RUNS. Three outcomes, and only the first runs an autostarting command:
  #      LIVE       -- our process is measured running: stop it, that is what the command is for.
  #      GONE       -- every tracked identity is measured absent: NO COMMAND. There is nothing to
  #                    stop, and issuing one here is how the residue was manufactured.
  #      UNREADABLE -- attribution could not be established: PENDING/review, NO COMMAND. An
  #                    unreadable host is not an empty one, and it is not a licence to act either.
  residue_scan pre-stop no
  if [ "$SETUP_OUTSTANDING" = yes ]; then
    CLEANUP_STOP_STATE=WITHHELD_OUTSTANDING_SETUP
    CLEANUP_VERDICT=PENDING
    record "CLEANUP_STOP_WITHHELD setup=$SETUP_COMPLETION — the elevated setup cannot be shown to have finished. NO stop is issued: the stop verb is the AUTOSTARTING one of IR-124, and racing it against a leg that may still be starting processes is how residue gets manufactured. Disposition PENDING/review."
    cfail "listener stop withheld: the setup is outstanding ($SETUP_COMPLETION). This is a REFUSAL TO ACT, not a failed action."
  elif ! has_state listener_may_exist; then
    record "CLEANUP_SKIP listener - no listener_may_exist state was ever marked"
    CLEANUP_STOP_STATE=NOT_MARKED
  elif [ "$RESIDUE_LIVE" -gt 0 ]; then
    CLEANUP_STOP_STATE=ADMITTED
    record "CLEANUP_STOP_ADMITTED - $RESIDUE_LIVE tracked process(es) measured LIVE by pid + creation time; the stop has something to stop"
    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"
  elif [ "$RESIDUE_UNREADABLE" -gt 0 ]; then
    CLEANUP_STOP_STATE=WITHHELD_UNREADABLE
    record "CLEANUP_STOP_WITHHELD residue=UNREADABLE ($RESIDUE_UNREADABLE identity/identities) - NO autostarting stop is issued on an unreadable measurement. Disposition PENDING/review: this run can neither say the listener is gone nor act as though it is present."
  else
    CLEANUP_STOP_STATE=NOT_NEEDED
    record "CLEANUP_STOP_NOT_NEEDED - listener_may_exist was marked, but every tracked identity measured GONE (live=0 unreadable=0). NO COMMAND IS ISSUED: running one here is what IR-124 records."
  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
    # t3 FIRST: the pair is about to be removed, and after the request is written there is
    # no second chance to look at it. This is the last capture point the design has.
    d2_capture_at t3 "$(cleanup_left)"
    D2_T3=$(tr -d ' 
' < "$R/d2-t3.exit" 2>/dev/null || echo UNRECORDED)
    d2_validate_at t3; D2_T3_VALID="$VALIDATE_RESULT"; D2_T3_QF="$VALIDATE_QF"
    # THE MANIFEST IS TAKEN BEFORE THE TEARDOWN, over whatever documents exist. Hashing
    # after the subject is gone would pin bytes nobody could re-derive.
    ( cd "$R" && sha256sum d2-t1.json d2-t2.json d2-t3.json d2-t1.json.b64 d2-t2.json.b64 d2-t3.json.b64 \
        2>"$R/manifest.err" > "$R/MANIFEST.sha256" )
    record "D2_MANIFEST written before teardown ($(grep -c . "$R/MANIFEST.sha256" 2>/dev/null) documents hashed; any absent point is named in manifest.err and stays a labelled gap)"
    guard_assert cleanup-pre-teardown     # status recorded; it cannot exit (see note above)
    # THE TEARDOWN COMMAND IS NOT THIS DRIVER'S TO COMPOSE (doyle 2026-09-13).
    # The predecessor handed the elevated leg `serve lan --stop` -- the autostarting verb of
    # IR-124, which reaches the broker through ensure_running and can create what it was sent to
    # remove. Its replacement is the product's OWN rendered cleanup command
    # (bootstrap_firewall::cleanup_command, emitted on stderr inside the
    # LAN_FIREWALL_CLEANUP_UNVERIFIED line), whose composed source contains no New-, Set- or
    # Start- cmdlet and contacts no daemon. THAT LITERAL DOES NOT EXIST YET: it must be emitted
    # by the shipped binary, decoded, reviewed and PINNED before anything may dispatch it.
    #
    # A HAND-RECONSTRUCTED SCRIPT IS REFUSED, NOT SUBSTITUTED. Composing the payload here from
    # the source constants would produce a command that LOOKS like the product's and is not one,
    # and the elevated leg cannot tell them apart. While TEARDOWN_COMMAND_SHA256 is empty this
    # driver asks for NO teardown and says so: PENDING/review is an honest verdict, a fabricated
    # command is not.
    # NOTHING IS REMOVED ON A MARKER ALONE (doyle GUS4EENB). fw_mutation_may_have_occurred is
    # set BEFORE the setup is dispatched, deliberately, so that a REFUSED setup still tears
    # down. It is therefore a statement about what this run INTENDED, never about what the host
    # holds -- the same confusion that made IR-124: in run 20260913T041410Z the setup was
    # DECLINED, nothing was ever created, and the marker still drove a command.
    #
    # THE MARKER DECIDES WHETHER THE QUESTION IS ASKED. THE MEASUREMENT DECIDES WHETHER A
    # COMMAND IS REQUESTED. Same shape as the listener gate above, and the same three answers:
    #   ABSENT (CONFIRMED)  -- there is nothing to remove: NO dispatch. The disposition is
    #                          NOTHING_TO_REMOVE, which is a measurement, not a removal.
    #   UNREADABLE          -- attribution could not be established: NO dispatch, PENDING/review.
    #                          An unreadable host is not an empty one and is not a licence either.
    #   anything present    -- there IS something to remove: verify the pin and dispatch.
    removal_check pre-teardown
    REMOVAL_PRE="$REMOVAL_CHECK"
    if [ "$SETUP_OUTSTANDING" = yes ]; then
      TEARDOWN_DISPATCH=WITHHELD_OUTSTANDING_SETUP
      CLEANUP_VERDICT=PENDING
      record "TEARDOWN_WITHHELD setup=$SETUP_COMPLETION nonce=$SETUP_NONCE rules=$RULE_TAILNET,$RULE_LAN — NO removal is requested while the setup may still be writing to the same store. The pre-teardown reading above is recorded as taken, and it is NOT read as a final state: a store being mutated concurrently has no final state to read."
      cfail "teardown withheld: the setup is outstanding ($SETUP_COMPLETION). Owned rules MAY REMAIN and their removal is PENDING/review."
    elif [ "$REMOVAL_PRE" = CONFIRMED ]; then
      TEARDOWN_DISPATCH=NOT_NEEDED_MEASURED_ABSENT
      CLEANUP_VERDICT=NOTHING_TO_REMOVE
      record "TEARDOWN_NOT_NEEDED - both owned names measured ABSENT in both stores before any teardown was asked for, with each store's controls alive in the same sample. NO command is dispatched: asking an elevated leg to remove what is not there is how residue gets manufactured."
    elif [ "${REMOVAL_PRE#UNREADABLE}" != "$REMOVAL_PRE" ]; then
      TEARDOWN_DISPATCH=WITHHELD_UNREADABLE_STATE
      CLEANUP_VERDICT=PENDING
      record "TEARDOWN_WITHHELD state=$REMOVAL_PRE - the owned rules could not be read either way before teardown. NO command is dispatched and nothing is spawned; disposition PENDING/review."
      cfail "teardown withheld: the pre-teardown reading was $REMOVAL_PRE. This is a REFUSAL TO ACT on an unreadable measurement, not a failed action."
    # VERIFIED A SECOND TIME, IMMEDIATELY BEFORE USE (doyle 2026-09-13). The pre-GO reading
    # was about the file as it stood then; these are the bytes about to be handed to an
    # elevated leg, and only a reading taken here can speak for them.
    elif ! teardown_pin_verify pre-dispatch; then
      TEARDOWN_DISPATCH="WITHHELD_$TEARDOWN_PIN_STATE"
      CLEANUP_VERDICT=PENDING
      record "TEARDOWN_WITHHELD state=$TEARDOWN_PIN_STATE - NO teardown is requested and NO command is reconstructed or substituted. Bootstrap-owned rules MAY REMAIN and their removal is PENDING/review; the state markers in $ST are left set deliberately."
      cfail "teardown not dispatched (state=$TEARDOWN_PIN_STATE). This is a REFUSAL TO ACT, not a failed action, and a missing instrument is never replaced by a composed one."
    else
      TEARDOWN_DISPATCH=DISPATCHED
      record "TEARDOWN_COMMAND_PINNED reviewed_b64_sha256=$TEARDOWN_B64_SHA256 - dispatching the product-emitted literal VERBATIM, exactly as the binary rendered it (never re-wrapped, re-typed or re-encoded). It removes OWNED RULES ONLY: it stops no listener and removes no process."
      handoff_request teardown \
        "remove bootstrap-owned TCP admission created or possibly created by this run, using the PRODUCT-EMITTED cleanup command below VERBATIM. It removes rules only -- do not stop any listener and do not kill any process on the strength of this request." \
        "$(cat "$TEARDOWN_COMMAND_FILE")"
    fi
    if [ "$TEARDOWN_DISPATCH" = DISPATCHED ]; then
    # The wait is bounded by WHAT IS LEFT OF THE REPORTING DEADLINE, not by a fixed 300s:
    # the report is due at the deadline whether or not liam has answered.
    CLEANUP_HANDOFF_WAIT_S=$(cleanup_left)
    record "CLEANUP_HANDOFF_WAIT bounded to ${CLEANUP_HANDOFF_WAIT_S}s — what remains of the reporting deadline"
    # 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)
      TEARDOWN_RC="$t_rc"
      exits "cleanup_teardown_receipt_EXIT=$t_rc"
      bounded census_cleanup_teardown_post "$(cur_deadline)" "$R/.census.out" "$R/.census.err" -- \
        pwsh -NoProfile -File "$BIN/census.ps1" -Tag cleanup-teardown-post -OutDir "$R"
      local c_rc=$?
      cat "$R/.census.out" "$R/.census.err" >> "$R/census.log" 2>/dev/null
      # THE REVIEWED REMOVER SUCCEEDS SILENTLY (doyle 2026-09-13). The previous conjunction
      # required the product's LAN_FIREWALL_CLEAN line, which belonged to the `serve lan --stop`
      # verb this integration replaced. The reviewed payload prints NOTHING on success -- it
      # removes, re-reads both stores, and throws if anything remains -- so requiring that marker
      # made a successful removal unverifiable and every clean run PENDING. Removed rather than
      # manufactured: a marker this driver invents would prove only that the driver can write it.
      # WHAT REMAINS REQUIRED is what can actually be measured: the remover's own native exit, a
      # census that succeeded, and the independent per-name, per-store absence reading.
      local absent=0 valid=0
      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
      # INDEPENDENT POST-REMOVAL CHECK (doyle 2026-09-13). Everything above is either the
      # product's own verdict -- the claim under test -- or a census that counts ActiveStore
      # rules by GROUP and PORT. Neither can say WHICH owned name is gone, and neither reads
      # PersistentStore at all, so a removal that took one rule and failed on the other, or that
      # emptied PersistentStore while leaving ActiveStore residue, could pass both. This probe
      # addresses each owned name by InstanceID in EACH store and is the reading that decides.
      removal_check post-teardown
      record "TEARDOWN_CHECK receipt_exit=$t_rc census_exit=$c_rc named_rules_absent=$absent census_valid=$valid independent_removal=$REMOVAL_CHECK (the remover succeeds SILENTLY; there is no success marker to require)"
      if [ "$t_rc" -eq 0 ] && [ "$c_rc" -eq 0 ] && [ "$absent" -eq 1 ] && [ "$valid" -eq 1 ] && [ "$REMOVAL_CHECK" = CONFIRMED ]; then
        record "TEARDOWN_VERIFIED — zero remover exit AND a successful census AND the owned named rules measured ABSENT by an INDEPENDENT per-name, per-store probe"
        CLEANUP_VERDICT=VERIFIED
      else
        CLEANUP_VERDICT=PENDING
        cfail "TEARDOWN NOT VERIFIED (receipt_exit=$t_rc census_exit=$c_rc absent=$absent census_valid=$valid independent_removal=$REMOVAL_CHECK). Owned rules MAY REMAIN; removal is PENDING/review and is NOT retried. 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
    fi
  else
    record "CLEANUP_SKIP firewall — no fw_mutation_may_have_occurred state was ever marked"
    record "  CLEANUP=VERIFIED is not available on this path either: nothing was created, so there is nothing whose removal could be measured. The verdict below says which of the two it is."
  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.
  #    DAEMON_STOP_REFUSED is EXPECTED here (IR-122): the rig's isolated-daemon stop is
  #    structurally unrunnable from an spt-hosted session, and that refusal is reported,
  #    never worked around.
  # THE SAME GATE AS THE LISTENER (doyle 2026-09-13). daemon_may_run is marked BEFORE the setup
  # is dispatched, so it says what this run INTENDED, not what the host holds. The marker decides
  # whether the question is asked; a FRESH measurement decides whether the command runs.
  #   attributed LIVE -- a tracked identity of this run is measured running: the reviewed stop path
  #                      may be entered, because there is something to stop.
  #   measured ABSENT -- nothing of this run is running: SKIP. No command.
  #   UNREADABLE      -- attribution could not be established: PENDING/review, and no action.
  # THIS IS NOT A CLAIM THAT `daemon stop` SPAWNS ANYTHING. Nothing here measures that, and the
  # gating mismatch alone would not establish it. The reason for the gate is narrower and enough:
  # acting on a marker that was never a measurement is not justified by the marker.
  if has_state daemon_may_run; then
    residue_scan pre-daemon-stop no
    if [ "$SETUP_OUTSTANDING" = yes ]; then
      DAEMON_STOP_STATE=WITHHELD_OUTSTANDING_SETUP
      CLEANUP_VERDICT=PENDING
      record "DAEMON_STOP_WITHHELD setup=$SETUP_COMPLETION — the elevated leg dispatches through the daemon (ensure_running, serveverb.rs:191), so stopping it while that leg may still be acting races the processes it is starting. NO command is issued; disposition PENDING/review."
      cfail "daemon stop withheld: the setup is outstanding ($SETUP_COMPLETION)."
    elif [ "$RESIDUE_LIVE" -gt 0 ]; then
      DAEMON_STOP_STATE=ADMITTED
      record "DAEMON_STOP_ADMITTED - $RESIDUE_LIVE tracked identity/identities measured LIVE by pid + creation time; the stop has something to stop"
    elif [ "$RESIDUE_UNREADABLE" -gt 0 ]; then
      DAEMON_STOP_STATE=WITHHELD_UNREADABLE
      CLEANUP_VERDICT=PENDING
      record "DAEMON_STOP_WITHHELD residue=UNREADABLE ($RESIDUE_UNREADABLE identity/identities) - NO stop is issued on an unreadable measurement. Disposition PENDING/review."
    else
      DAEMON_STOP_STATE=NOT_NEEDED
      record "DAEMON_STOP_NOT_NEEDED - daemon_may_run was marked, but every tracked identity measured GONE (live=0 unreadable=0). NO COMMAND IS ISSUED."
    fi
  fi
  if [ "${DAEMON_STOP_STATE:-NOT_REACHED}" = ADMITTED ]; then
    run_cmd rig_daemon_stop "$R/rig-daemon-stop.out" "$R/rig-daemon-stop.err" -- \
      env SPT_HOME="$H" "$EXE" daemon stop
    DAEMON_STOP_RC=$?
    # THE REFUSED COMMAND'S NATIVE EXIT IS PRESERVED IN EVERY CASE (doyle, 2026-09-13) --
    # in exits.txt, here, and in the ledger. A refusal reported without its own exit is a
    # story about a command rather than a record of one.
    record "RIG_DAEMON_STOP native_exit=$DAEMON_STOP_RC (preserved verbatim; see rig-daemon-stop.err)"
    if [ "$DAEMON_STOP_RC" -ne 0 ]; then
      # REPORTED, NOT FORCED, and NOT BY ITSELF A CLEANUP FAILURE (D2 change, measured):
      # IR-122 makes this refusal STRUCTURAL from an spt-hosted session -- it fires on the
      # caller's OWL_SESSION_ID whatever SPT_HOME is targeted. r10 counted it as a cleanup
      # failure, which under the r8 exit rule would raise EVERY D2 run to exit 6 and empty
      # that code of meaning. What decides whether it MATTERS is the residue measurement
      # immediately below: a refusal that left no process associated with this home left
      # nothing behind, and a refusal that left one is reported as an identity with the
      # verdict PENDING. The refusal is on the record either way.
      record "DAEMON_STOP_REFUSED (expected, IR-122) — reported, never worked around. Whether anything REMAINS is decided by the residual-identity measurement below, not by this exit."
      DAEMON_STOP_REFUSED=1
    fi
  elif ! has_state daemon_may_run; then
    DAEMON_STOP_STATE=NOT_MARKED
    record "CLEANUP_SKIP daemon — no daemon_may_run state was ever marked"
  fi

  # 4. RESIDUAL IDENTITY -- RUN-BOUND, NOT STRING-MATCHED (doyle's admission blocker,
  #    2026-09-13). The previous predicate matched a process whose COMMAND LINE contained the
  #    isolated home. THE RESIDUALS WE ACTUALLY MET DO NOT: r10's survivors ran
  #    `daemon run --detached` and `daemon brain --generation 0 --start-reason cold`, neither of
  #    which carries the home string, so that probe could have printed a confident CLEAR over
  #    exactly the two processes this cleanup exists to find. A NONEMPTY ENUMERATION VALIDATES
  #    THAT THE TABLE WAS READ; IT SAYS NOTHING ABOUT WHETHER THE PREDICATE CAN MATCH.
  #
  #    What decides now is IDENTITY CAPTURED WHILE THE PROCESSES WERE LIVE (S9a): the supervisor
  #    named by <isolated-home>/daemon.pid with its creation time, executable path and command
  #    line, plus every child whose parent is that supervisor. Cleanup RE-QUERIES those exact
  #    identities, fresh, and compares all three fields -- a bare pid match is unsound because
  #    pid reuse on this box is measured, so a pid that answers with a different creation time
  #    is a DIFFERENT process and ours is GONE.
  #
  #    MISSING OR UNREADABLE ATTRIBUTION IS 'UNREADABLE', NEVER 'CLEAR'. If the identities were
  #    never captured, or the table cannot be read now, this run cannot say the box is tidy.
  #    NOTHING IS KILLED HERE. The r10 authorization was pid-specific and is SPENT; a fresh
  #    pid-naming authorization is a STOP, not a step.
  residue_scan post-cleanup yes
  # RESIDUE_COUNT keeps its ledger meaning: how many of OUR processes are still alive. An
  # unreadable attribution makes the count itself unmeasured rather than zero.
  RESIDUE_COUNT="$RESIDUE_LIVE"
  [ "$RESIDUE_UNREADABLE" -gt 0 ] && RESIDUE_COUNT=UNMEASURED

  # 4b. LISTENER ABSENCE, MEASURED FRESH (doyle's cleanup ruling, 2026-09-13). Rule removal is
  #     not the whole of cleanup: a structural stop refusal may be reported separately ONLY IF
  #     fresh checks establish that the isolated processes are GONE -- which means the residue
  #     count above AND a listener that is no longer bound. UNMEASURED counts as live, because
  #     an unread port is not an empty one.
  if port_at cleanup-post-listener; then
    if grep "tag=cleanup-post-listener " "$R/portfields.log" | tail -1 | grep -q 'listener_state=NONE'; then
      LISTENER_STATE=ABSENT
    else
      LISTENER_STATE=PRESENT
    fi
  else
    LISTENER_STATE=UNMEASURED
  fi
  record "LISTENER_AFTER_CLEANUP=$LISTENER_STATE on port $PORT (UNMEASURED is read as live: an unread port is not an empty one)"
  case "$LISTENER_STATE" in
    ABSENT)  : ;;
    PRESENT) cfail "a listener is STILL BOUND on port $PORT after cleanup -- the isolated processes are not gone, so cleanup is PENDING and this run does not end zero" ;;
    *)       cfail "the listener state on port $PORT could not be measured after cleanup -- unreadable residual state is PENDING, never clean" ;;
  esac

  # 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

  # 7. THE VERDICTS, and the reporting deadline read as what it is.
  #    A DEADLINE NEVER EARNS 'VERIFIED'. Running out of reporting time means the report is
  #    due; it says nothing about the host, so the verdict below is decided by measurement
  #    and the clock is reported beside it.
  local left; left=$(cleanup_left)
  # THREE FRESH FACTS ARE REQUIRED FOR VERIFIED, and identity reporting is not one of them
  # (doyle, 2026-09-13): the owned rules measured ABSENT (the teardown check above), no
  # residual process associated with this home, and no listener still bound. Live OR
  # UNREADABLE residual state is PENDING, and PENDING never ends at zero -- each of those
  # branches has already written a cleanup failure, which the r8 handler turns into exit 6.
  # NOTHING_TO_REMOVE IS A TERMINAL MEASURED STATE, NOT A WEAK 'VERIFIED' (doyle GUS4EENB).
  # A run whose setup was declined created nothing, so no removal could be measured and VERIFIED
  # is not available to it -- but neither is PENDING/review the truth, because there is nothing
  # outstanding. It still has to clear the SAME two other facts: no residual process of this
  # home, and no listener still bound. Either of those forces PENDING exactly as before.
  if { [ "$CLEANUP_VERDICT" != VERIFIED ] && [ "$CLEANUP_VERDICT" != NOTHING_TO_REMOVE ]; } \
     || [ "$RESIDUE_COUNT" != 0 ] || [ "${LISTENER_STATE:-UNMEASURED}" != ABSENT ]; then
    CLEANUP_VERDICT=PENDING
  fi
  if [ "$left" -le 0 ]; then
    record "CLEANUP_REPORT_DEADLINE expired (${CLEANUP_REPORT_S}s) — THE REPORT IS DUE. That is not a statement that the host is tidy."
  else
    record "CLEANUP_REPORT_WINDOW ${left}s of ${CLEANUP_REPORT_S}s remained when the report was written"
  fi
  # THE DEFERRED VALIDATIONS LAND HERE, on the reporting clock, bounded by WORK_DEADLINE like
  # everything else in this phase. t3's was always here; t1's and t2's join it.
  d2_validate_at t1; D2_T1_VALID="$VALIDATE_RESULT"; D2_T1_QF="$VALIDATE_QF"
  d2_validate_at t2; D2_T2_VALID="$VALIDATE_RESULT"; D2_T2_QF="$VALIDATE_QF"
  # EVERY LAUNCHED IDENTITY THIS RUN COULD NOT ACCOUNT FOR, PRINTED AS A LINE RATHER THAN
  # WAITED ON (doyle B3CMWRQI). The ledger owns the reserved interval and must emit on time;
  # an un-reaped child is reported as OUTSTANDING, which is a line to print.
  if [ -f "$(launch_file)" ]; then
    local out_n; out_n=$(grep -c 'state=ATTRIBUTION_INCOMPLETE' "$(launch_file)" 2>/dev/null)
    case "$out_n" in (''|*[!0-9]*) out_n=0 ;; esac
    record "LAUNCHED_IDENTITIES $(grep -c '^LAUNCHED ' "$(launch_file)" 2>/dev/null) rows, of which $out_n are ATTRIBUTION_INCOMPLETE — see launched-identities.txt. An incomplete attribution is NOT a process measured absent."
  else
    record "LAUNCHED_IDENTITIES none recorded — no bounded child was ever launched, or the register could not be written"
  fi
  d2_ledger
  emit_ceiling summary
  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: the first"
    record "  failure still owns the verdict (original_rc=$ORIGINAL_RC, incoming status $incoming)."
    # A CLEANUP FAILURE AFTER AN OTHERWISE SUCCESSFUL RUN NOW EXITS 6 (doyle's ruling,
    # r8). This EXPLICITLY SUPERSEDES the previous design, which recorded the failures
    # and left the status alone: a run that could not verify its own teardown was
    # reporting success to whatever reads the exit code, which is a green that means the
    # opposite of what it says. Cleanup gates must pass for green.
    #
    # IT ONLY EVER REPLACES A ZERO, and BOTH conditions are required. An existing
    # nonzero status is preserved whether it came from set_original (die, void, signal)
    # or from a path that exited nonzero without setting it -- the incoming status is
    # checked in its own right precisely so that second kind cannot be overwritten.
    if [ "$incoming" -eq 0 ] && [ "$ORIGINAL_RC" -eq 0 ]; then
      record "  EXIT RAISED TO 6: the run was otherwise successful but its teardown could not be verified. A zero here would have said the box was left clean when that is exactly what failed."
      exit 6
    fi
    record "  EXIT PRESERVED at $incoming (original_rc=$ORIGINAL_RC): the earlier finding owns the status; the cleanup failures are reported beside it, never in place of it."
  fi
}

# ---- the run ledger --------------------------------------------------------
# THE VERDICTS LIVE HERE, NOT IN THE EXIT CODE. This driver's zero says the sequence ran and
# the ledger was written; it is never a statement that the capture contract was satisfied,
# exactly as a capture's property states never live in its exit code.
#
# THE FOUR EXITS ARE FOUR SEPARATE VALUES. The elevated setup's exit and each capture's exit
# are reported side by side and none is inferred from another (plan §5.0).
#
# THE CAPTURE CONTRACT IS EARNED. It requires all three points captured and validated
# COMPLETE, with sound controls. t1 UNAVAILABLE is a LABELLED EVIDENCE GAP: the run then
# collected a smaller set, says so, and no downstream conclusion may rest on the missing
# observation.
d2_ledger() {
  local lf="$R/d2-ledger.txt"
  local t1v="$D2_T1_VALID" t2v="$D2_T2_VALID" t3v="$D2_T3_VALID"
  CAPTURE_CONTRACT=NOT_SATISFIED
  # THE CONTRACT REQUIRES SUCCESSFUL OBSERVATIONS, not merely made ones (doyle, 2026-09-13).
  # A DENIED document is a VALID record of a query failure and still has not delivered what the
  # plan asks for, so any query failure among the required observations refuses the contract even
  # where validation is COMPLETE. The two statements stay separate and both are printed.
  local qf=$(( ${D2_T1_QF:-0} + ${D2_T2_QF:-0} + ${D2_T3_QF:-0} ))
  if [ "$D2_T1" = 0 ] && [ "$D2_T2" = 0 ] && [ "$D2_T3" = 0 ] \
     && [ "$t1v" = COMPLETE ] && [ "$t2v" = COMPLETE ] && [ "$t3v" = COMPLETE ] \
     && [ "$qf" -eq 0 ]; then
    CAPTURE_CONTRACT=SATISFIED
  fi
  {
    echo "D2 RUN LEDGER — run=$RUN_ID"
    echo "  this file reports; it does not congratulate. The driver's own exit means the"
    echo "  sequence ran and this ledger was written, never that the run was green."
    echo "EXITS, four separate values, none inferred from another:"
    echo "  setup_elevated_exit=$SETUP_RC"
    echo "  d2_t1_exit=$D2_T1   (UNAVAILABLE = the elevated capture never ran: a labelled evidence gap)"
    echo "  d2_t2_exit=$D2_T2"
    echo "  d2_t3_exit=$D2_T3"
    echo "  teardown_exit=$TEARDOWN_RC"
    echo "VALIDATION, whether each observation was MADE (never whether its value was wanted):"
    echo "  t1=$t1v  t2=$t2v  t3=$t3v"
    echo "QUERY FAILURES among the required observations -- observed, recorded, and NOT successful:"
    echo "  t1=${D2_T1_QF:-0}  t2=${D2_T2_QF:-0}  t3=${D2_T3_QF:-0}  (any nonzero refuses the contract, however valid the document is)"
    echo "IDENTITY the records bind to (never InstanceID):"
    echo "  run=$RUN_ID"
    echo "  pre_setup_absence=$PRE_SETUP_ABSENCE"
    echo "  setup_interval=[$SETUP_START_UTC .. $SETUP_END_UTC] (the COMMAND's own bounds, stamped INSIDE the elevated leg)"
    echo "  t1_interval=[$T1_START_UTC .. $T1_END_UTC] (the elevated capture's own two stamps, same leg)"
    echo "  handoff_interval=[$HANDOFF_REQUEST_UTC .. $HANDOFF_RECEIPT_UTC] (this driver's request-write and receipt-verify -- a DIFFERENT interval, never the command's)"
    echo "  timestamp_order=$TS_ORDER (the six stamps compared with the calendar; UNMEASURED = at least one is a gap)"
    echo "  setup_exit_preserved_by_leg=$SETUP_EXIT_FILE (written before t1 ran; the receipt's exit= above stays the declared channel)"
    echo "  rule_names=$RULE_TAILNET,$RULE_LAN  port=$PORT  isolated_home=$H"
    echo "VERDICTS:"
    echo "  CAPTURE_CONTRACT=$CAPTURE_CONTRACT"
    # UNMEASURED IS KEPT DISTINCT FROM LIVE (doyle, 2026-09-13). Both refuse verification and
    # both end nonzero, but they are different facts and a reader must not have to guess which
    # one happened: LIVE is a process or a listener we SAW, UNREADABLE is a measurement we could
    # not make. Collapsing them would let an instrument failure be reported as a dirty host, or
    # a dirty host as an instrument failure.
    local residual=CLEAR
    if [ "${RESIDUE_COUNT:-UNMEASURED}" != 0 ] && [ "${RESIDUE_COUNT:-UNMEASURED}" != UNMEASURED ]; then residual=LIVE
    elif [ "${LISTENER_STATE:-UNMEASURED}" = PRESENT ]; then residual=LIVE
    elif [ "${RESIDUE_COUNT:-UNMEASURED}" = UNMEASURED ] || [ "${LISTENER_STATE:-UNMEASURED}" != ABSENT ]; then residual=UNREADABLE
    fi
    echo "  residual_state=$residual (CLEAR = measured gone; LIVE = seen; UNREADABLE = not measurable, and NOT the same claim)"
    echo "  tracked_process_identities: live=${RESIDUE_LIVE:-0} gone=${RESIDUE_GONE:-0} unreadable=${RESIDUE_UNREADABLE:-0} (re-queried by pid + creation time + executable + command line)"
    echo "  identity_capture=${CAPTURE_USABLE:-not-attempted} (${CAPTURE_INTEGRITY:-no capture was needed}) -- an incomplete capture can never support CLEAR"
    echo "  cleanup_stop_gate=${CLEANUP_STOP_STATE} daemon_stop_gate=${DAEMON_STOP_STATE:-NOT_REACHED} teardown_dispatch=${TEARDOWN_DISPATCH} removal_pre=${REMOVAL_PRE:-NOT_REACHED} removal_post=${REMOVAL_CHECK:-NOT_REACHED}"
    echo "  rig_daemon_stop_exit=${DAEMON_STOP_RC:-NOT_RUN}  listener_after_cleanup=${LISTENER_STATE:-UNMEASURED}"
    echo "  CLEANUP=$CLEANUP_VERDICT  residue=${RESIDUE_COUNT:-UNMEASURED}  daemon_stop_refused=${DAEMON_STOP_REFUSED:-0} (IR-122: expected from an spt-hosted session; the residue count is what decides whether anything remains)"
    echo "  experimental_ended=[$EXPERIMENTAL_ENDED]"
    [ "$D2_T1" = UNAVAILABLE ] && echo "  D2_T1=UNAVAILABLE — the seq-001 request named the elevated capture and it did not run. The contract is NOT satisfied and no conclusion may rest on that observation."
    [ "$CLEANUP_VERDICT" = PENDING ] && echo "  CLEANUP=PENDING — residual identities above are the actionable record. A fresh pid-naming authorization is a STOP, not a step."
  } > "$lf"
  while IFS= read -r line; do record "LEDGER $line"; done < "$lf"
}
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"; }

# ---- CI axis, on the CODE repo, job-level, exit gated (D3) -----------------
# THE ACTIVE STATUSES, asked for BY NAME (r9). The previous gate listed the latest 10 runs
# and filtered them for non-terminal status, which can only ever see an active run that is
# also RECENT. A run queued behind 40 newer completed ones is invisible to it, and the gate
# reported "no non-terminal runs" -- a clean zero over a window that never contained the
# answer. Admission must not depend on active jobs being recent.
# Values are gh's own (gh 2.89.0, `gh run list --help`): queued, in_progress, requested,
# waiting and pending are the non-terminal set; completed and the conclusion values are not
# statuses a run can still be occupying the box in.
# action_required is NOT here (doyle, r10). It is a CONCLUSION, not a status a run is still
# occupying the box in, so blocking on it would let a historical completed run refuse
# admission indefinitely -- a gate that can never clear. The five non-terminal statuses
# already cover a run waiting on approval.
CI_ACTIVE_STATUSES='queued in_progress requested waiting pending'
CI_STATUS_LIMIT=100

ci_scan_file() { # FILE -> echoes ids; rc 0 = read, 2 = unreadable
  # PURE over a file, so the decision can be exercised without a network call.
  local f="$1" out
  out=$(python -c 'import json,sys
d = json.load(open(sys.argv[1], encoding="utf-8"))
if not isinstance(d, list): raise SystemExit("not a JSON array")
for r in d:
    if "databaseId" not in r: raise SystemExit("row without databaseId")
print(" ".join(str(r["databaseId"]) for r in d))' "$f" 2>/dev/null) || return 2
  echo "$out"
}

ci_gate() { # TAG
  local tag="$1" st lf rc ids n live=''
  # ONE QUERY PER ACTIVE STATUS. A status-filtered listing is not bounded by recency, so an
  # old queued run appears in it; the previous recency-bounded form could not ask the
  # question at all.
  for st in $CI_ACTIVE_STATUSES; do
    lf="$R/ci-$tag-$st.json"
    gh run list --repo "$CI_REPO" --status "$st" --limit "$CI_STATUS_LIMIT" --json databaseId,headSha,status,workflowName > "$lf" 2>"$R/ci-$tag-$st.err"
    rc=$?
    exits "ci_${tag}_${st}_EXIT=$rc"
    [ "$rc" -eq 0 ] || die "CI '$st' query for '$tag' against $CI_REPO exited $rc — an unread CI axis is not a free box, and a status this gate cannot ask about is not a status with no runs"
    ids=$(ci_scan_file "$lf"); local prc=$?
    exits "ci_${tag}_${st}_parse_EXIT=$prc"
    [ "$prc" -eq 0 ] || die "could not parse the CI '$st' listing for '$tag' — an unparsed answer is not an empty one"
    n=$(printf '%s' "$ids" | wc -w | tr -d ' ')
    record "CI_STATUS '$tag' status=$st count=$n limit=$CI_STATUS_LIMIT"
    # A FULL PAGE MAY BE A TRUNCATED PAGE. Refusing here is the fail-closed answer: an
    # unread remainder is not an empty remainder, and this gate exists to say the box is
    # free only when it has actually seen that it is.
    [ "$n" -lt "$CI_STATUS_LIMIT" ] || die "the CI '$st' query returned a FULL page ($n == limit $CI_STATUS_LIMIT) for '$tag' — the answer may be truncated and the unread remainder cannot be assumed empty"
    live="$live $ids"
  done
  live=$(printf '%s' "$live" | tr -s ' ' | sed 's/^ //;s/ $//')
  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-$tag-view.err"
      exits "ci_${tag}_view_${id}_EXIT=$?"
    done
    die "CI on $CI_REPO has active 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': every active status queried BY NAME ($CI_ACTIVE_STATUSES) returned zero runs on $CI_REPO — not merely zero among the most recent"
}

# ---- 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 competes for this box, and this run mutates
#                         the host firewall while it is here.
#   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. Gating on it would make the gate unpassable.
#   D2 CORRECTION, by replacement rather than carried forward: r10 justified the analyzer
#   exemption by saying its adjacent load 'is exactly what the per-trial CPU bracket
#   measures'. THERE IS NO CPU BRACKET AND NO WALL HERE. The remaining reason stands on
#   its own -- the exemption is about a service that is always present, not about a
#   measurement this run no longer takes.
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)"
}

emit_ceiling() { # WHEN
  # EVIDENCE CEILING. r10's revision 3 is preserved in that driver; this is its D2 form,
  # because two of its three "what a green establishes" clauses were about TRIALS AND
  # TIMINGS THAT NO LONGER EXIST HERE, and carrying them forward would have claimed
  # measurements this run never takes.
  record "CEILING($1) REACHABILITY=NOT_TESTED"
  record "CEILING($1)   After an uncatchable termination, only output and artifacts ACTUALLY PRESERVED may be cited; neither this initial print nor state-marker persistence is guaranteed."
  record "CEILING($1)   This rig makes NO connection attempt, from this box or any other. Rule shape is not arrival: LAN_FIREWALL_RECONCILED means verify() returned Ok(true) over the rule store at that instant, and the product states the converse itself in LAN_FIREWALL_UNVERIFIED -- 'this does not prove the listener unreachable' (serveverb.rs:310-315)."
  record "CEILING($1)   A COMPLETE D2 RUN ESTABLISHES EXACTLY ONE THING: WHAT THE PROVIDER RETURNED, for the named properties of a NEWLY CREATED pair, at three recorded instants, each value with its type, cardinality and its own query interval. It NAMES a disagreement; it never explains one."
  record "CEILING($1)   IT SAYS NOTHING ABOUT THE r10 INSTANCES. Those were torn down and measured absent. This is a NEW pair with its own provenance: a matching [5, 20] would not prove the r10 instances carried the same cause, and a different result would not refute the r10 observation."
  record "CEILING($1)   Every host-facing path of the capture has met a STUB and never a real provider. What is exercised is that it reads, encodes, writes and reports correctly GIVEN A PROVIDER THAT BEHAVES AS THE STUB DOES. A real provider may differ in exactly the ways this investigation is about, and the DENIED path in particular has never been produced by an actual access denial."
  record "CEILING($1)   A SUCCESSFUL EMPTY RESULT IS AN EMPTY RESULT, and its completeness is UNPROVEN wherever the provider can silently filter. Emptiness licenses no claim that nothing exists."
  record "CEILING($1)   It establishes NONE of: remote connectivity; ACL disposition; end-to-end #297 acceptance. TWO-HOST ACCEPTANCE REMAINS OUTSTANDING with its own plan and its own execution grant."
}

emit_ceiling pre-preflight
# ===========================================================================
# 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  THE PROVISIONED RIG IS VERIFIED AND CONSUMED — NEVER PROVISIONED HERE
# ===========================================================================
# PREPARATION VERIFIES; IT DOES NOT PROVISION (doyle W4C2QFLE). Everything in this section is
# READ-ONLY over the rig except one atomic marker, and that marker is the consumption.
#
# THE PRODUCT'S GATES DO NOT REJECT EVERY UNRELATED OR PREVIOUSLY USED HOME, and I said
# otherwise in the first proposal — doyle corrected it. A home that happens to carry a matching
# applied set would satisfy the conjuncts perfectly well. So exclusive creation, provenance and
# one-attempt consumption are THE RIG'S OWN obligations, enforced here and in provision-rig.sh,
# and never inferred from the product refusing something.
if [ -z "$RIG_ROOT" ]; then
  die "no provisioned rig is pinned (RIG_ROOT is empty). This driver does not create one: provisioning is a separate mutating phase with its own grant, and a run that provisioned its own subject could not tell a prepared home from one it repaired to make a check pass."
fi
[ -d "$RIG_ROOT" ] || die "the pinned rig root does not exist: $RIG_ROOT"
[ -d "$H" ]        || die "the pinned rig has no home at $H"
[ -f "$EXE" ]      || die "the pinned rig has no executable at $EXE"
PROVENANCE="$H/provenance.json"
[ -f "$PROVENANCE" ] || die "no provenance record at $PROVENANCE. An intentionally provisioned home is a MEASURABLE property, not an assertion: without the record this home is indistinguishable from a leftover."
# ONE ATTEMPT, CONSUMED ATOMICALLY. mkdir either creates the directory or fails because it is
# already there; a test-then-create would leave a window in which two runs both read 'absent'.
# A CONSUMED RIG IS NEVER CLEARED AND NEVER REUSED: the refusal is the point, and the evidence
# of the previous attempt -- successful or failed -- stays exactly where it is.
if ! mkdir "$H/.consumed" 2>/dev/null; then
  die "this provisioned rig has ALREADY BEEN CONSUMED (see $H/.consumed). A rig is one attempt: provision a new one rather than reusing or clearing this, whose contents are the previous attempt's evidence."
fi
{ echo "run_id=$RUN_ID"; echo "consumed_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)"; echo "driver=$0"; } > "$H/.consumed/run.txt" 2>/dev/null
record "RIG_CONSUMED $H/.consumed created by run $RUN_ID — exclusive creation, so a second run refuses rather than sharing this subject"
# PROVENANCE FIELDS, read as plain strings. The rig does NOT parse the product's cache files:
# what the applied state is was measured by provisioning, with the product's own output kept
# beside this record, and re-deriving it here from internals would be a second, weaker reading.
prov_field() { # KEY -> value | ''
  sed -n 's/.*"'"$1"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$PROVENANCE" | head -1
}
P_RUN=$(prov_field rig_id);          P_EXE=$(prov_field rig_exe)
P_SHA=$(prov_field rig_exe_sha256);  P_HOME=$(prov_field home)
P_VER=$(prov_field applied_version); P_KEY=$(prov_field trust_key_id)
P_EVID=$(prov_field applied_evidence)
record "RIG_PROVENANCE rig_id=$P_RUN exe=$P_EXE sha256=$P_SHA home=$P_HOME applied_version=$P_VER trust_key_id=$P_KEY evidence=$P_EVID"
for f in P_RUN P_EXE P_SHA P_HOME P_VER P_EVID; do
  eval "v=\$$f"
  [ -n "$v" ] || die "the provenance record is missing $f. An incomplete provenance record does not establish that this home was prepared for anything."
done
# THE BYTES, MEASURED HERE AND NOT TAKEN FROM THE RECORD. A provenance file that says what the
# sha is proves only what provisioning believed; this is the reading that binds the subject.
RIG_EXE_SHA_NOW=$(sha256sum "$EXE" 2>/dev/null | cut -d' ' -f1)
[ -n "$RIG_EXE_SHA_NOW" ] || die "could not hash $EXE — an unmeasured executable is not the subject"
[ "$RIG_EXE_SHA_NOW" = "$EXE_SHA" ] || die "the rig executable hashes to $RIG_EXE_SHA_NOW and the pinned subject is $EXE_SHA. Different bytes are a different subject."
[ "$P_SHA" = "$EXE_SHA" ] || die "the provenance record names $P_SHA and this run's subject is $EXE_SHA: this rig was provisioned for a different binary."
# THE PATHS, COMPARED CANONICALLY with the same r2 comparison the binder check uses. A string
# comparison would accept two spellings of one path and reject one path spelt two ways.
rig_canon=$(binder_path_canon "$EXE") || die "could not canonicalise $EXE"
prov_canon=$(binder_path_canon "$P_EXE") || die "could not canonicalise the provenance path $P_EXE"
[ "$rig_canon" = "$prov_canon" ] || die "the provisioned executable ($P_EXE) is not the one this run would invoke ($EXE)"
home_canon=$(binder_path_canon "$H") || die "could not canonicalise $H"
prov_home=$(binder_path_canon "$P_HOME") || die "could not canonicalise the provenance home $P_HOME"
[ "$home_canon" = "$prov_home" ] || die "the provenance record belongs to a different home ($P_HOME): this rig is not this run's"
# THE APPLIED STATE'S EVIDENCE. Provisioning verified a genuine Applied state with the product's
# own output; PREP requires that evidence to EXIST and to name the same version. It is not
# re-derived from the release cache here: a second, weaker reading of the same fact would add no
# assurance and would put the rig in the business of parsing product internals.
[ -f "$P_EVID" ] || die "the applied-state evidence named by the provenance record is absent ($P_EVID). A recorded version with no evidence beside it is a claim, not a measurement."
grep -q "$P_VER" "$P_EVID" || die "the applied-state evidence does not mention version $P_VER"
record "RIG_VERIFIED exe_sha256=$RIG_EXE_SHA_NOW (measured here) canonical_path=$rig_canon applied_version=$P_VER evidence=$P_EVID"
record "  BINDER EQUALITY IS NOT CHECKED HERE (doyle W4C2QFLE): whether the LISTENER is this executable is a POST-SETUP question, and there is no listener yet. It is measured at setup-post-listener, where it has a subject."

# ===========================================================================
# S0c  INSTRUMENTS: present, and HASHED INTO THE EVIDENCE (F10 + C)
# ===========================================================================
# THE SET CHANGED WITH THE WORKLOAD. cpubracket.ps1 is gone with the timed trials it
# bracketed; d2_capture.ps1 and d2_validate.py are new. runner-census.ps1 STAYS: shared-host
# admission is not workload, and its ancestry-authenticated census is what makes box_gate a
# measurement instead of a name filter.
for inst in census.ps1 runner-census.ps1 portfields.ps1 d1_render.py d2_capture.ps1 d2_validate.py; do
  [ -f "$BIN/$inst" ] || die "instrument $BIN/$inst is missing — the six dependencies must all exist before any runnable claim"
done
sha256sum "$BIN"/census.ps1 "$BIN"/runner-census.ps1 "$BIN"/portfields.ps1 "$BIN"/d1_render.py \
          "$BIN"/d2_capture.ps1 "$BIN"/d2_validate.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 (6 files)"
# SCOPE OF PRIOR INSTRUMENT EXERCISE, recorded accurately (doyle 2026-09-12, extended
# 2026-09-13 for the two D2 instruments):
# d1_render.py was exercised by LIVE LOCAL EXECUTION against blob c28874ef plus three
# negative controls, and RENDER-ONLY against this subject 848a23fe (pre-check exact, b64
# 8dc3b4b2). portfields.ps1 and runner-census.ps1 were exercised by LIVE READ-ONLY HOST
# PROBES; their post-correction changes are UNEXERCISED, by instruction.
# d2_capture.ps1 was exercised at TWO LEVELS AGAINST STUBS ONLY: a leaf serializer check
# (12/12 on Desktop 5.1 AND Core 7, with a deliberate red control failing as required) and a
# document check (41/41 on Desktop 5.1), both receipted in the D2 control receipt. EVERY
# HOST-FACING PATH HAS MET A STUB AND NEVER A REAL PROVIDER, and its DENIED path has never
# been produced by an actual access denial -- Test-Denied matches on error text, which is the
# weakest part of the instrument.
# d2_validate.py was exercised by the actual-sequence control against synthetic documents,
# including the red arms it exists for: a missing required observation, an observed DENIED
# query, and an unreadable document.
record "INSTRUMENT_EXERCISE_SCOPE: d1_render live-executed with controls against c28874ef and RENDER-ONLY against 848a23fe; portfields/runner-census live READ-ONLY host probes; d2_capture STUB-ONLY at leaf and document level (12/12 both editions, 41/41 documents, red controls firing) with NO host-facing path ever exercised against a real provider; d2_validate exercised against synthetic documents including missing-observation, DENIED and unreadable arms"

# ===========================================================================
# S0d  SHARED-HOST EXECUTION ADMISSION, BEFORE THE DIAGNOSTIC STARTS
# ===========================================================================
# CAPACITY IS GONE WITH THE PRODUCER (doyle, 2026-09-13): a disk floor gates a build, and
# nothing here builds. ADMISSION IS NOT GONE. This box is shared -- it hosts the self-hosted
# runner, and a merge-push RE-OCCUPIES it minutes after a golden -- so the status-filtered CI
# axis and the ancestry-authenticated process census both still run before anything of this
# run's touches the host. They are kept exactly as r10 left them, queue guard and all.
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  THE EXECUTABLE IS PINNED BY HASH. NOTHING IS BUILT.
# ===========================================================================
# This replaces r10's pool claim, keygen, pin, rollout --build-current, mark-applied and
# three-way provenance. D2 reuses the executable that run already built and receipted, so
# there is no new artifact to sign, stage or agree with -- but there is still a subject to
# identify, and A CLEAN SOURCE TREE DOES NOT IDENTIFY REUSED EXECUTABLE BYTES (doyle,
# 2026-09-13). S0e establishes that the tree is the subject source; this establishes that
# the file about to create the pair is the executable r10 measured. Both, or neither means
# anything.
#
# The hash is ALSO stated in the elevated request (S8), because liam runs that command in a
# leg this driver cannot observe: a pair written by a different binary is a different
# subject, and the person running it is told the value to refuse on.
[ -f "$EXE" ] || die "no executable at $EXE. Nothing here builds one: D2 reuses r10's, and its absence is a STOP, not a reason to produce a new one."
exe_sha=$(sha256sum "$EXE" 2>"$R/s1-exe.err" | awk '{print $1}')
esrc=$?
exits "s1_exe_sha_EXIT=$esrc"
[ "$esrc" -eq 0 ] || die "could not hash $EXE — an unmeasured executable is not the pinned one"
[ -n "$exe_sha" ] || die "the executable hash came back empty; an empty measurement is not a match"
record "EXECUTABLE sha256=$exe_sha path=$EXE"
if [ "$exe_sha" != "$EXE_SHA" ]; then
  die "EXECUTABLE IDENTITY FAILED: $exe_sha != the pinned $EXE_SHA. This is not the executable r10 built and receipted, and a capture of a pair written by a different binary describes a different subject. REFUSING — the fix is to restore the pinned artifact, never to rebuild one here."
fi
record "EXECUTABLE_PINNED — bytes equal the r10 setup receipt's subject ($EXE_SHA); no build ran, and none is authorized"
{ sha256sum "$EXE"; stat -c '%s bytes  mtime=%y  path=%n' "$EXE"; } > "$R/s1-executable.out" 2>&1
exits "s1_exe_record_EXIT=$?"
# ===========================================================================
# S6  ADMISSION REFRESHED IMMEDIATELY BEFORE THE DIAGNOSTIC — both axes (D3)
# ===========================================================================
# r10 refreshed here because a BUILD had just run and a merge-push starts a post-merge run
# on this box's runner. There is no build now, but the refresh is kept and the reason is
# unchanged and independent of the workload: THE VOLATILE ADMISSION READINGS ARE
# POINT-IN-TIME (R10-FROZEN), and the runner can occupy this box between the preflight and
# the elevated leg whatever this driver is doing in between.
abort_check
ci_gate pre-diagnostic
pwsh -NoProfile -File "$BIN/runner-census.ps1" -Tag pre-diagnostic > "$R/s6-runner.txt" 2>&1
src=$?
exits "s6_runner_EXIT=$src"
[ "$src" -eq 0 ] || die "pre-diagnostic runner census exited $src"
grep -q 'valid=YES' "$R/s6-runner.txt" || die "pre-diagnostic runner census invalid"
grep -q 'RUNNER_WORKER=ABSENT' "$R/s6-runner.txt" || die "the runner re-occupied the box (a merge-push starts a post-merge run on this box)"
box_gate "$R/s6-runner.txt" pre-diagnostic
guard_assert pre-diagnostic
# ===========================================================================
# CENSUS AND BRACKET HELPERS — every call's exit and validity enforced (F-a)
# ===========================================================================
census_at() { # TAG
  bounded "census_$1" "$(cur_deadline)" "$R/.census.out" "$R/.census.err" -- \
    pwsh -NoProfile -File "$BIN/census.ps1" -Tag "$1" -OutDir "$R"
  local rc=$?
  cat "$R/.census.out" "$R/.census.err" >> "$R/census.log" 2>/dev/null
  [ "$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
}
port_at() { # TAG — the trial port's rules and listener identity
  bounded "portfields_${PORT}_$1" "$(cur_deadline)" "$R/.probe.out" "$R/.probe.err" -- \
    pwsh -NoProfile -File "$BIN/portfields.ps1" -Tag "$1" -OutDir "$R" -Port "$PORT"
  local rc=$?
  # THE PROBE'S OWN OUTPUT STILL REACHES THE LOG. bounded() takes OUT and ERR as parameters
  # because `record` tees to stdout; the log this rig greps is assembled here instead.
  cat "$R/.probe.out" "$R/.probe.err" >> "$R/portfields.log" 2>/dev/null
  [ "$rc" -eq 0 ] || return 1
  grep -q "tag=$1 .* valid=YES" "$R/portfields.log" || return 1
  return 0
}

# ===========================================================================
# 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 CONTEXT
  local fo="$1" fe="$2" px="$3" ctx="${4:-undeclared}"
  local c_recon c_unver c_mismatch c_afterwrite c_src c_nolan c_enf c_reprfault 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 codes are'                          | wc -l | tr -d ' ')
  c_reprfault=$( cat "$fo" "$fe" 2>/dev/null | grep -o 'ENFORCEMENT_REPRESENTATION_FAULT'                          | 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 representation_fault=$c_reprfault mutation_disabled=$c_disabled clean=$c_clean cleanup_unverified=$c_cleanunver already_up=$c_already repair_requested=$c_repair elevation_unavailable=$c_elevun"
  # CLEAN IS BOUND TO ITS INVOCATION, NOT TO THE TOKEN (r6). LAN_FIREWALL_CLEAN has TWO
  # print sites -- serveverb.rs:379 on the stop path and :530 inside
  # reconcile_lan_firewall -- so a count on its own cannot say which one ran. The
  # context the caller declares is what narrows it, and an undeclared context stays
  # UNATTRIBUTABLE rather than defaulting to the flattering reading.
  if [ "$c_clean" -gt 0 ]; then
    case "$ctx" in
      stop)      record "$px CLEAN_ATTRIBUTION ctx=stop site=serveverb.rs:379 (the stop path; :530 is not reached by a stop)" ;;
      bootstrap) record "$px CLEAN_ATTRIBUTION ctx=bootstrap site=serveverb.rs:530 (inside reconcile_lan_firewall) -- NOT stop-path cleanliness" ;;
      *)         record "$px CLEAN_ATTRIBUTION ctx=undeclared site=UNATTRIBUTABLE -- :379 and :530 both print this token" ;;
    esac
  fi
  # CAUSE AND WRAPPER ARE SEPARATE AXES (r6). They used to share one precedence chain,
  # so an after-write wrapper ERASED the cause underneath it, and a transport fault and
  # a code refusal inside a wrapper were reported as the same thing. The cause is now
  # computed on its own, the wrapper on its own, and the face carries both as
  # wrapper/cause. Every count above is reported whatever the face says.
  # THREE STATES UNDER ONE WRAPPER, never two (doyle; field plan f1c400f9 §§1,4):
  #   ONLY the specific enforcement-code refusal establishes that decide() passed
  #   pair_satisfied_by -- the check order puts pair_satisfied_by first, so reaching
  #   the enforcement arm requires it to have matched. That is what makes it the
  #   representation-ACCEPTED discriminator.
  #   A REPRESENTATION FAULT ESTABLISHES NO SUCH THING: the query failed, so decide()'s
  #   verdict is NOT IN EVIDENCE at all -- neither representation-accepted nor
  #   pair-absent. It must never be grouped with the enforcement refusal.
  #   A generic UNVERIFIED establishes ONLY that verify() did not return Ok(true).
  local cause=none wrapper=none
  if   [ "$c_reprfault" -gt 0 ]; then cause=representation-fault  # the QUERY could not transport the codes: NO decide() verdict is in evidence
  elif [ "$c_enf"       -gt 0 ]; then cause=enforcement           # past pair_satisfied_by (:797) => the codes were READ and REFUSED
  elif [ "$c_src"       -gt 0 ]; then cause=source-store          # also past pair_satisfied_by => representation accepted, persistence refused
  elif [ "$c_nolan"     -gt 0 ]; then cause=no-lan-scope          # tailnet half checked; host cannot carry the LAN half
  fi
  # WHEN BOTH A FAULT AND A CODE REFUSAL APPEAR, the fault is selected. That is
  # CONSERVATIVE REPORTING PRECEDENCE AND NOTHING MORE. Finding both texts in one
  # combined capture does NOT establish that the transport failed before any verdict
  # was reached: the capture carries no ordering, the two lines may come from
  # different invocations, and an earlier revision of this comment asserted a
  # chronology the evidence cannot supply. The fault is preferred because it is the
  # weaker claim -- it asserts no decide() verdict at all -- not because it happened
  # first. BOTH COUNTS RIDE THE FACE_COUNTS LINE and the mixed case is named there.
  if   [ "$c_mismatch"   -gt 0 ]; then wrapper=mismatch-after-write   # reconcile wrote, then verify disagreed (windows.rs:892)
  elif [ "$c_afterwrite" -gt 0 ]; then wrapper=unverified-after-write # writes landed, observation cut short: NOT a refused write
  fi
  local face=none
  if   [ "$wrapper" != none ] && [ "$cause" != none ]; then face="$wrapper/$cause"
  elif [ "$wrapper" != none ];                        then face="$wrapper"
  elif [ "$cause"   != none ];                        then face="$cause"
  elif [ "$c_recon" -gt 0 ];                          then face=reconciled
  elif [ "$c_unver" -gt 0 ];                          then face=unverified-generic
  fi
  # WHAT unverified-generic PROVES, stated no more strongly than it can be (r6). It used
  # to read "decide() Ok(false): ABSENT or MISSPELLED". It cannot carry that: the same
  # LAN_FIREWALL_UNVERIFIED line carries ANY reason serveverb.rs:310-315 interpolates,
  # a transport fault included, and any reason this classifier does not recognise. It
  # means only that the run was not verified and that no recognised cause was present.
  if [ "$face" = unverified-generic ]; then
    record "$px UNVERIFIED_GENERIC_CEILING: no recognised cause matched. It establishes ONLY that verify() did not return Ok(true). It does NOT prove the pair was absent or misspelled -- that gloss was the OLD driver's reading and is the defect this revision removes. Read the reason text in the capture and the census row."
  fi
  if [ "$cause" = representation-fault ]; then
    record "$px REPRESENTATION_FAULT_CEILING: the query could not transport the codes, so decide()'s verdict is NOT IN EVIDENCE -- this is neither representation-accepted nor pair-absent, and it must not be read as either."
    if [ "$c_enf" -gt 0 ]; then
      record "$px MIXED_CAUSE: this capture carries BOTH a representation fault ($c_reprfault) and a code refusal ($c_enf). The face names the fault by CONSERVATIVE REPORTING PRECEDENCE, not by any evidence of order -- the capture carries no chronology and the two may come from different invocations. Read both counts."
    fi
  fi
  record "$px FACE=$face wrapper=$wrapper cause=$cause ctx=$ctx"
  echo "$face"
}

# ===========================================================================
# D1 — out-of-band QUERY capture. SERIALIZED, never inside a timed trial.
# ===========================================================================
d1_capture() { # TAG
  local tag="$1"
  D1_OK=no
  # THE RENDER TOUCHES NO HOST AND STILL CANNOT MOVE (doyle CT6GS2Y6). Its output IS the
  # command the post-mutation snapshot runs, two lines below, and the A2.1 pre-check on its
  # stdout gates that snapshot. Host-free is not the test for deferral; ordering is.
  bounded "d1_${tag}_render" "$(cur_deadline)" "$R/d1-$tag-render.out" "$R/d1-$tag-render.err" -- \
    python "$BIN/d1_render.py" --repo "$W" --blob "$SUBJECT_BLOB" --out "$R/d1-$tag.b64"
  local rc=$?
  cat "$R/d1-$tag-render.err" >> "$R/d1-$tag-render.out" 2>/dev/null
  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; }
  bounded "d1_${tag}_exec" "$(cur_deadline)" "$R/d1-$tag-snapshot.json" "$R/d1-$tag-snapshot.err" -- \
    powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand "$(cat "$R/d1-$tag.b64")"
  local prc=$?
  if [ "$prc" -eq 124 ]; then
    # COMPLETION UNVERIFIED, NOT AN ABSENT SNAPSHOT. The partial is preserved and left unread.
    preserve_unverified "d1_${tag}_exec" "$R/d1-$tag-snapshot.json"
    record "D1_FAILED($tag) the out-of-band capture did not complete within its bound; its partial output is PRESERVED UNREAD and this run makes no claim about what it contains"
    return 1
  fi
  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:748 and run_bounded :136-188 keep nothing). It bounds the host"
  record "  spellings present AROUND the call."
  record "  r5 CORRECTION: the earlier note said the QUERY const is byte-identical at 53d625cd and"
  record "  921aa68f, so D1 could not discriminate the candidate from the registration sha. That was"
  record "  measured and true of THOSE shas; it is NOT true of this subject. 85f84d73 carries the"
  record "  REPAIRED query (raw CIM accessor), so the const differs from 53d625cd by construction."
  return 0
}

# ===========================================================================
# PAIR STATE — the census row read as a state, not as an arm precondition
# ===========================================================================
# r10's expect_pair asked "does the census match ARM a or ARM b". There are no arms here:
# the pair is created once, read three times and torn down. The same row is read for the
# same two facts, under names that say what they are.
pair_state() { # TAG -> echoes absent|present|other
  local row; row=$(census_row "$1")
  [ -n "$row" ] && echo "$row" | grep -q 'subj_group=0 subj_29470=0' && { echo absent; return; }
  [ -n "$row" ] && echo "$row" | grep -q 'subj_group=2 subj_29470=2' && { echo present; return; }
  echo other
}

# ===========================================================================
# S7  PRE-SETUP ABSENCE — one of the five parts the records bind to (plan §3)
# ===========================================================================
# InstanceID MUST NOT be assumed unique across deletion and recreation, so no record binds
# to it. Records bind to the RUN, this MEASURED ABSENCE, the STORE, the NAME and the SETUP
# INTERVAL. This step is where the absence is measured, and the string it produces rides
# into every captured record.
abort_check
prep_check pre-setup-absence
census_at pre-setup-absence || die "the pre-setup census is invalid; its zeros would be meaningless and every later record would bind to a fabricated absence"
ps_state=$(pair_state pre-setup-absence)
[ "$ps_state" = absent ] || die "an owned pair is already present before setup (state=$ps_state, row=[$(census_row pre-setup-absence)]). This run cannot tell its own pair from a pre-existing one, and no capture may be attributed to a pair it did not create."
PRE_SETUP_ABSENCE="census(pre-setup-absence) $(census_row pre-setup-absence)"
record "PRE_SETUP_ABSENCE measured: both owned names absent — [$PRE_SETUP_ABSENCE]"

# ===========================================================================
# S8  SETUP — ONE elevated action, by HANDOFF (D2). Never run by this driver.
#     THE ELEVATED CAPTURE RIDES THIS REQUEST. One nonce is one execution.
# ===========================================================================
# ===========================================================================
# S7b PREPARED / NOT_STARTED -- the acknowledgment that opens the window
# ===========================================================================
# WHY THIS IS A SEPARATE ACT (doyle 2026-09-13). Everything above is read-only preparation and
# is paid for out of PREP_BUDGET_S. The experimental window pays for ACTIVITY, and run
# 20260913T041410Z showed what happens when the two share a clock: 134s of its 300s went to an
# elevated operator reading a request, and t1 and t2 were never reached. So the executor is
# asked to acknowledge -- BEFORE ANY ACTIVITY IS DISPATCHED -- that it is prepared and has
# started nothing. GO follows the acknowledgment; the 300s starts there.
#
# HASH-VERIFIED, AND THE HASH IS THE EXECUTOR'S OWN MEASUREMENT. The receipt must carry the
# sha256 of the pinned executable as the EXECUTOR measured it. An acknowledgment that merely
# says PREPARED proves the request was answered; one that carries the subject's hash proves the
# answering leg can see the subject this run is about. It also front-loads the identity check
# into preparation, where a mismatch costs no experimental time.
prep_check prepared-acknowledgment
handoff_request prepare \
  "ACKNOWLEDGE ONLY -- RUN NOTHING. Confirm you are prepared to execute the setup leg and that you have started nothing yet, and report the sha256 of BOTH subjects this leg would run, AS YOU MEASURE THEM NOW: the pinned executable and the capture script." \
  "ACKNOWLEDGEMENT ONLY. Do not run the product. Reply in the receipt with these four tokens, EACH ON A LINE OF ITS OWN AND NOTHING ELSE ON THAT LINE: PREPARED, NOT_STARTED, then executable_sha256= followed by the sha256 you measure of $EXE, then capture_sha256= followed by the sha256 you measure of $BIN/d2_capture.ps1. If you are NOT prepared, say so in words -- do not write NOT_PREPARED on a line by itself and expect it to read as a refusal. NOTE ON PHRASING: this text carries no angle brackets deliberately. handoff_request refuses any command text containing a redirect character, because capture paths are composed inside it; a bracketed placeholder was refused by that guard on the first live PREP (run 20260913T070453Z), before any request was written."
PREPARED_ACK="$HO_RECEIPT"
# BOUNDED BY WHAT IS LEFT OF PREPARATION (doyle 2026-09-13). HANDOFF_WAIT_S is 900s and the whole
# preparation budget is 600s, so an unbounded-by-prep wait could sit past the deadline and then
# open a window the budget had already closed. Same narrowing the cleanup wait already does.
HANDOFF_WAIT_S=$(prep_left)
record "PREP_HANDOFF_WAIT bounded to ${HANDOFF_WAIT_S}s — what remains of the preparation budget"
# NOT `if ! handoff_await trial`: that exact line is the anchor of an assembly-time correction
# applied to the RETAINED setup wait, and the assembler asserts it appears exactly once. Same
# call, same context, written so the anchor stays unique -- the rig refused this and was right.
handoff_await trial || die "no PREPARED/NOT_STARTED acknowledgment within the preparation budget. The experimental window is NEVER OPENED: nothing was dispatched, nothing was created, and there is nothing to tear down."
ack_missing=''
# EXACT WHOLE-LINE TOKENS (doyle K4QDUUVV). A substring search for PREPARED is satisfied by
# NOT_PREPARED, and one for GO_AUTHORIZED by NOT_GO_AUTHORIZED -- so a receipt that REFUSES would
# have read as a receipt that agrees, which is the worst direction for this particular mistake.
# Matching is whole-line and the hash fields are matched entire, so a truncated or prefixed hash
# cannot satisfy one either. CR IS STRIPPED FIRST: the receipt is written by a Windows elevated
# leg, so its lines end CRLF, and a whole-line match against a line ending in \r matches nothing --
# the tightening would otherwise have refused every honest receipt.
ack_line() { tr -d '\r' < "$1" 2>/dev/null | grep -qx -F -- "$2"; }
ack_line "$PREPARED_ACK" "PREPARED"    || ack_missing="$ack_missing PREPARED"
ack_line "$PREPARED_ACK" "NOT_STARTED" || ack_missing="$ack_missing NOT_STARTED"
ack_line "$PREPARED_ACK" "executable_sha256=$EXE_SHA" || ack_missing="$ack_missing executable_sha256=$EXE_SHA"
# BOTH SUBJECTS, NOT ONE (doyle LIRX7EUS). The leg runs the product AND the capture script, and the
# documents this run reasons about are whatever the capture script produced. An acknowledgment that
# measured only the executable proved the leg could see half of what it is about to run.
ack_line "$PREPARED_ACK" "capture_sha256=$CAPTURE_SHA" || ack_missing="$ack_missing capture_sha256=$CAPTURE_SHA"
if [ -n "$ack_missing" ]; then
  record "PREPARED_ACK_CONTENTS: [$(tr -d '\r' < "$PREPARED_ACK" 2>/dev/null | tr "\n" " ")]"
  die "the acknowledgment is missing:$ack_missing. An unverified acknowledgment opens no window -- a receipt that cannot state the subject it measured is not evidence that the executor is looking at this run."
fi
record "PREPARED_ACK_VERIFIED - the executor reports PREPARED and NOT_STARTED and measured BOTH subjects: executable $EXE_SHA and capture script $CAPTURE_SHA"
record "PREPARED_IS_NOT_AUTHORIZATION - readiness says the leg CAN act; it does not say this run MAY. The window stays shut until a separate, run-bound GO authorization is verified below."

# READINESS IS NOT AUTHORIZATION (doyle LIRX7EUS). The predecessor ran PREPARED and then called
# go() on the next line: verifying that the executor was READY opened the experimental window by
# itself, so a leg that answered a preparation question had, without being asked, started a 300s
# clock on the host. THE TWO ARE NOW SEPARATE ACTS. This second request asks for an AUTHORIZATION,
# it carries its own nonce, and the receipt must quote that nonce back -- so an authorization is
# bound to THIS run and THIS request and cannot be a stale or reused token from another.
prep_check go-authorization
handoff_request go-authorization \
  "AUTHORIZE ONLY -- RUN NOTHING. FOR THE DRI, NOT FOR THE ELEVATED EXECUTOR: readiness has already been acknowledged by the leg that would run this, and that acknowledgment is not this decision. Authorize the experimental window to OPEN for this run, knowing the 300s activity clock starts when it does." \
  "AUTHORIZATION ONLY. Nothing is run to answer this. Reply in the receipt with THREE things: the token GO_AUTHORIZED on a line of its own and nothing else on that line; the line authorizer=doyle, likewise alone on its line; and the nonce of THIS request quoted exactly (anywhere). To WITHHOLD authorization, say so in words -- there is no negative token this check reads." \
  doyle
GO_ACK="$HO_RECEIPT"; GO_ACK_NONCE="$HO_NONCE"
HANDOFF_WAIT_S=$(prep_left)
record "PREP_HANDOFF_WAIT bounded to ${HANDOFF_WAIT_S}s — what remains of the preparation budget"
handoff_await trial || die "no GO authorization within the preparation budget. The experimental window is NEVER OPENED: readiness alone does not open it, nothing was dispatched, and there is nothing to tear down."
go_missing=''
ack_line "$GO_ACK" "GO_AUTHORIZED" || go_missing="$go_missing GO_AUTHORIZED"
# THE AUTHORIZER IS NAMED, AND THAT IS A ROUTING CHECK, NOT AUTHENTICATION (doyle XS5VAWJQ).
# It establishes that the receipt answering this request claims to be the DRI's decision rather
# than the executor's; it cannot establish WHO wrote the file, and nothing here should be read as
# if it could. The operational authorization is doyle's own run-and-nonce-bound message; this
# receipt RECORDS that decision and does not create it.
ack_line "$GO_ACK" "authorizer=doyle" || go_missing="$go_missing authorizer=doyle"
# THE NONCE KEEPS ITS SUBSTRING MATCH, deliberately: it is quoted inside a line the executor
# writes in its own words ("nonce: <value>"), and it is a run-scoped value that nothing else on
# the receipt can accidentally contain.
grep -q -F -- "$GO_ACK_NONCE" "$GO_ACK" 2>/dev/null || go_missing="$go_missing nonce=$GO_ACK_NONCE"
if [ -n "$go_missing" ]; then
  record "GO_ACK_CONTENTS: [$(tr -d '\r' < "$GO_ACK" 2>/dev/null | tr "\n" " ")]"
  die "the GO authorization is missing:$go_missing. An authorization that cannot quote the nonce of the request it answers is not bound to this run, and this window does not open on it."
fi
record "GO_AUTHORIZED_VERIFIED nonce=$GO_ACK_NONCE authorizer=doyle - a separate, run-bound authorization from the DRI, distinct from the executor's readiness acknowledgment. The identity line is a routing and consistency check, not authentication: it records whose decision this receipt claims to carry."

# THE REMOVAL INSTRUMENT IS REQUIRED BEFORE THE WINDOW OPENS (doyle 2026-09-13).
# A run that cannot remove what it is about to create must never create it. The predecessor
# discovered its missing teardown at CLEANUP -- after the rules existed -- and could then only
# report PENDING and leave them for a human. Checking here costs no experimental time (this is
# still preparation) and turns that PENDING into a run that never started.
#
# THIS IS A PRECONDITION, NOT A PERMISSION. Verifying the instrument does not authorize its use
# any more than the PREPARED acknowledgment authorizes the setup; it establishes that the removal
# this run will owe is one it can actually hand over, pinned and reviewed.
if ! teardown_pin_verify pre-go; then
  die "the reviewed rule-removal instrument is not available (state=$TEARDOWN_PIN_STATE). The experimental window is NEVER OPENED: nothing is dispatched, nothing is created, and there is nothing to tear down. This is a refusal to start, not a failed run."
fi

# THE DEADLINE IS RE-READ IMMEDIATELY BEFORE THE WINDOW OPENS (doyle 2026-09-13). Every check
# above was taken when it ran; a receipt can arrive after the preparation budget has expired, and
# an authorization that is verified late must not open a window the budget had already closed.
# prep_check refuses with exit 8 -- a run that never started, with nothing to tear down.
prep_check window-open

# THE WINDOW OPENS HERE AND NOWHERE ELSE.
go "GO authorization verified (run-bound), both subject hashes measured by the executor, and the reviewed removal instrument verified"

abort_check
deadline_check elevated-setup
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"
mark_state daemon_may_run "serve dispatches through the daemon (ensure_running, serveverb.rs:191); the elevated leg may leave one running"
mark_state listener_may_exist "the elevated setup binds a listener on port $PORT"
# A TIMESTAMP THIS DRIVER DID NOT TAKE (D2 successor). The setup command and the elevated
# capture both run in a leg this driver never enters, so their bounds can only be stamped
# THERE and read back HERE. An absent file is a LABELLED GAP: it is never "now", and never
# the neighbouring stamp. A present value that the calendar cannot parse is UNPARSEABLE --
# a string, not a time -- because shape is not validity (ts_readable's rule).
leg_utc() { # PATH -> the stamp | ABSENT | UNPARSEABLE
  local f="$1" v
  [ -f "$f" ] || { echo ABSENT; return; }
  v=$(tr -d ' \r\n' < "$f")
  if ts_readable "$v"; then echo "$v"; else echo UNPARSEABLE; fi
}
leg_exit() { # PATH -> the exit | ABSENT | UNPARSEABLE   (an unread exit is not a zero one)
  local f="$1" v
  [ -f "$f" ] || { echo ABSENT; return; }
  v=$(tr -d ' \r\n' < "$f")
  case "$v" in (''|*[!0-9]*) echo UNPARSEABLE ;; (*) echo "$v" ;; esac
}
# THE HANDOFF'S BOUNDS ARE NOT THE COMMAND'S (doyle, 2026-09-13). f7b7773f stamped
# SETUP_START_UTC where this line stands -- at the moment the REQUEST WAS WRITTEN -- and
# SETUP_END_UTC at the moment the RECEIPT WAS VERIFIED, then labelled that pair "THE CREATION
# RECORD". It is not one: it opens before the command exists and closes after the command has
# finished, and it includes however long liam took to read the request and answer it. Both
# intervals are recorded here, each under a name that says whose clock took it.
HANDOFF_REQUEST_UTC="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
handoff_request setup \
  "create the owned pair with the product itself (never a hand netsh, so the rules carry the shipped desired_specs shape) AND take the t1 capture inside this same elevated leg" \
  "env -u SPT_INSTALL_NO_FIREWALL SPT_HOME=\"$H\" \"$EXE\" serve lan --bootstrap --port $PORT"
SETUP_OUT="$HO_OUT"; SETUP_ERR="$HO_ERR"   # captured now: a later handoff rebinds HO_*
# THE SETUP'S RECEIPT PATH AND NONCE, CAPTURED FOR R6. Cleanup has to ask whether THIS command
# finished before it may mutate anything, and a later handoff rebinds HO_RECEIPT/HO_NONCE.
SETUP_RECEIPT="$HO_RECEIPT"; SETUP_NONCE="$HO_NONCE"
# THE t1 RIDER, appended to the request this driver just wrote. It is NOT a second handoff
# and NOT a second nonce: one nonce is one execution, and an elevated read cannot be added
# after this leg returns without a second authorization. It costs one block in the request.
# ITS EXIT GOES TO ITS OWN FILE. A capture that fails inside a setup that succeeded must not
# read as a failed setup, and a setup that fails must not be masked by a capture that ran.
{
  echo ""
  echo "executable_identity_REQUIRED: sha256 $EXE_SHA"
  echo "  at $EXE — MEASURED by this driver immediately before this request (S1) and stated here"
  echo "  because a clean source tree does not identify reused executable BYTES. If the file at that"
  echo "  path does not hash to this value when you run it, REFUSE THE LEG and say so in the receipt:"
  echo "  a pair written by a different binary is a different subject."
  echo ""
  echo "elevated_leg_sequence: EIGHT STEPS, IN THIS ORDER, IN ONE LEG UNDER ONE NONCE."
  echo "  The two stamps around run_exactly are THE COMMAND'S OWN BOUNDS. The requested_utc line"
  echo "  above and the moment I verify this receipt are the HANDOFF's bounds. They are different"
  echo "  intervals — the handoff one opens before the command exists and closes after it has"
  echo "  finished — and neither may be reported as the other."
  echo "  1. stamp_utc_now_to (immediately BEFORE step 2, with nothing in between): $R/setup-start.utc"
  echo "  2. run_exactly (the command and the redirections named above)"
  echo "  3. PRESERVE ITS EXIT IN A VARIABLE THE INSTANT IT RETURNS, before running anything else:"
  echo "     every later command overwrites \$LASTEXITCODE / \$?, INCLUDING the stamp in step 4."
  echo "  4. stamp_utc_now_to (immediately AFTER step 2): $R/setup-return.utc"
  echo "  5. write_the_exit_preserved_in_step_3_to: $R/setup.exit"
  echo "     THIS HAPPENS BEFORE t1 RUNS. The capture must not be able to overwrite the setup's exit."
  echo "  6. stamp_utc_now_to (immediately BEFORE step 7): $R/d2-t1-start.utc"
  echo "  7. then_run_exactly (SECOND command, same elevated leg, same nonce):"
  echo "& '$BIN/d2_capture.ps1' -CapturePoint 't1' -RuleName @('$RULE_TAILNET','$RULE_LAN') -Port $PORT -IsolatedHome '$H' -RunId '$RUN_ID' -OutPath '$R/d2-t1.json' -ControlRuleName '$CONTROL_RULE' -AbsentControlName '$ABSENT_CONTROL' -PreSetupAbsence '$PRE_SETUP_ABSENCE' -SetupIntervalStart (Get-Content -Raw '$R/setup-start.utc').Trim() -SetupIntervalEnd (Get-Content -Raw '$R/setup-return.utc').Trim()"
  echo "     then_write_its_native_exit_to: $R/d2-t1.exit"
  echo "  8. stamp_utc_now_to (immediately AFTER step 7): $R/d2-t1-end.utc"
  echo ""
  echo "stamp_utc_now_to <path> means EXACTLY this, and nothing that merely resembles it:"
  echo "  powershell.exe -NoLogo -NoProfile -NonInteractive -Command \"[DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ') | Set-Content -NoNewline -Encoding ascii '<path>'\""
  echo "  A FILE MTIME IS NOT ONE OF THESE STAMPS. A document's own utc plus an exit file gives one"
  echo "  instant and a filesystem attribute, which is not a start and an end; steps 6 and 8 exist"
  echo "  because the capture's two bounds have to be TAKEN, not reconstructed afterwards."
  echo "  THE SETUP INTERVAL RIDES INTO THE CAPTURE FROM THOSE FILES (step 7 reads them), so the"
  echo "  interval recorded in every t1 document is the one THIS LEG measured. I cannot supply it:"
  echo "  when I write this request the command has not started."
  echo ""
  echo "  Run each command with powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"<the line>; exit \$LASTEXITCODE\"."
  echo "  MEASURED, and the reason the form is spelled out: -File binds -RuleName a,b as ONE element"
  echo "  \"a,b\" (a name that cannot exist, recording NO_RULE for a pair that is present), two bare"
  echo "  tokens fail binding, and without the trailing exit \$LASTEXITCODE a capture exit of 2 arrives as 1."
  echo "  THE TWO EXITS STAY SEPARATE: the setup's exit goes in this receipt's exit= line AND in the"
  echo "  step-5 file, the capture's exit goes in the step-7 file. Neither substitutes for the other."
  echo "  If this capture is not run, say so in the receipt: t1 is then UNAVAILABLE, which is a labelled"
  echo "  evidence gap. It is NOT a reason to withhold the setup's own result."
  echo "  Any step you did not run: say which one. A missing stamp is read here as a gap, never as a pass."
} >> "$R/handoff/$HO_SEQ-setup-request.txt"
record "HANDOFF_T1_RIDER appended to the seq-$HO_SEQ setup request — the only elevated read this design has; omission is a labelled gap, not a pass"
record "HANDOFF_REQUEST_UTC=$HANDOFF_REQUEST_UTC — a bound on THIS DRIVER's request, not on the command it asks for"
# The wait cannot outlive the experimental budget: the deadline ends activity, whoever is
# holding it up.
HANDOFF_WAIT_S=$(exp_left)
# THE CAP IS A POLICY ALLOCATION, NOT AN ESTIMATE (doyle CT6GS2Y6). It answers how much of the
# activity window this run will spend waiting on another agent, and it exists because one slow
# counterparty can otherwise consume the whole window and leave nothing for the observations the
# window exists to take -- run 20260913T041410Z spent 134s here and reached neither t1 nor t2.
# 94s and 134s are two samples, not a distribution, and no number here is derived from them.
if [ "$HANDOFF_WAIT_S" -gt "$HANDOFF_CAP_S" ]; then
  record "HANDOFF_CAP applied: ${HANDOFF_CAP_S}s of the ${HANDOFF_WAIT_S}s that remain — the rest of the window is RESERVED for the post-mutation observations, which cannot be taken anywhere else"
  HANDOFF_WAIT_S=$HANDOFF_CAP_S
fi
record "HANDOFF_WAIT bounded to ${HANDOFF_WAIT_S}s — the lesser of the cap and what remains of the experimental budget"
# CONTEXT NAME KEPT VERBATIM: 'trial' is handoff_await's name for THE NORMAL FLOW, as
# opposed to 'cleanup'. There are no trials here; renaming it would edit a function this
# change has no reason to touch, so the name stays and this line says what it means.
if ! handoff_await trial; then
  HANDOFF_RECEIPT_UTC="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  record "HANDOFF_INTERVAL request=$HANDOFF_REQUEST_UTC receipt=$HANDOFF_RECEIPT_UTC — the handoff's bounds. The setup command's own bounds were never returned."
  # THE WAIT STOPPED; THE COMMAND MAY NOT HAVE. This driver never entered that leg and has no
  # authority to stop it, asks for none, and does not re-ask: one nonce is one execution, so a
  # second request would be a second authorization rather than a retry. It also does NOT proceed
  # into the post-mutation set -- those readings would be recorded under names asserting they are
  # AFTER a setup that may still be writing, which is a falsified observation and worse than a
  # missing one. Activity ends here and cleanup is entered through the EXIT trap, where R6
  # withholds EVERY mutation while the command is outstanding.
  record "HANDOFF_CAP_EXPIRED nonce=$SETUP_NONCE receipt_awaited=$SETUP_RECEIPT — the wait ended, the command's disposition is UNKNOWN, and nothing was killed or re-requested"
  die "no verified setup receipt within the bounded wait. The elevated command may still be acting: state markers are left set, no cleanup mutation may run while it is outstanding (R6), and a REFUSED or UNANSWERED setup can still have left rules behind."
fi
HANDOFF_RECEIPT_UTC="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
SETUP_RC=$(handoff_exit)
exits "setup_elevated_EXIT=$SETUP_RC"
# THE LEG'S OWN MEASUREMENTS, read back from the files it was asked to write.
SETUP_START_UTC=$(leg_utc "$R/setup-start.utc")
SETUP_END_UTC=$(leg_utc "$R/setup-return.utc")
T1_START_UTC=$(leg_utc "$R/d2-t1-start.utc")
T1_END_UTC=$(leg_utc "$R/d2-t1-end.utc")
SETUP_EXIT_FILE=$(leg_exit "$R/setup.exit")
record "SETUP_INTERVAL start=$SETUP_START_UTC end=$SETUP_END_UTC — THE CREATION RECORD, and it is the ELEVATED LEG's measurement of its own command, not this driver's measurement of the handoff. No provider creation timestamp is claimed and no instant is invented between these bounds."
record "T1_INTERVAL start=$T1_START_UTC end=$T1_END_UTC — the elevated capture's own two stamps"
record "HANDOFF_INTERVAL request=$HANDOFF_REQUEST_UTC receipt=$HANDOFF_RECEIPT_UTC — SEPARATELY LABELLED. This is how long the handoff took, and it is not a bound on anything the leg ran."
# THE SETUP'S EXIT, TWICE, FROM TWO CHANNELS. The receipt's exit= line keeps its authority
# (SETUP_RC is unchanged); the step-5 file is the evidence that the value was preserved BEFORE
# the capture ran. A disagreement is reported, never resolved by preference: it means one of
# the two readings is of something else.
case "$SETUP_EXIT_FILE" in
  "$SETUP_RC")
    record "SETUP_EXIT_PRESERVED=$SETUP_EXIT_FILE — the leg's own file agrees with the receipt's exit=, and it was written before t1 ran" ;;
  ABSENT)
    record "SETUP_EXIT_PRESERVED=ABSENT — step 5 produced no file. The receipt's exit=$SETUP_RC is then the ONLY reading of the setup's exit, and nothing here shows it was captured before the capture command overwrote \$LASTEXITCODE." ;;
  UNPARSEABLE)
    record "SETUP_EXIT_PRESERVED=UNPARSEABLE — a step-5 file exists and carries no readable exit. An unread exit is not a zero one." ;;
  *)
    record "SETUP_EXIT_DISAGREES receipt=$SETUP_RC leg_file=$SETUP_EXIT_FILE — TWO CHANNELS, TWO ANSWERS. Neither is preferred here; the receipt's value continues to be used because that is the declared channel, and this line is the standing caveat on it." ;;
esac
# ORDERING IS ASSERTED, NOT ASSUMED. Six stamps taken in an order this driver REQUESTED are a
# claim about that order until they are compared. Parsed with the calendar (ts_readable's rule,
# GNU date -u -d) and compared as epochs; a gap or an unparseable value leaves the comparison
# UNMEASURED rather than passing it. Stamps one second apart or identical are expected: the
# resolution is one second, so the test is <=, and an out-of-order pair is a real violation.
TS_ORDER=UNMEASURED
if ts_readable "$HANDOFF_REQUEST_UTC" && ts_readable "$SETUP_START_UTC" && ts_readable "$SETUP_END_UTC" \
   && ts_readable "$T1_START_UTC" && ts_readable "$T1_END_UTC" && ts_readable "$HANDOFF_RECEIPT_UTC"; then
  ts_hq=$(date -u -d "$HANDOFF_REQUEST_UTC" +%s); ts_ss=$(date -u -d "$SETUP_START_UTC" +%s)
  ts_se=$(date -u -d "$SETUP_END_UTC" +%s);       ts_t1s=$(date -u -d "$T1_START_UTC" +%s)
  ts_t1e=$(date -u -d "$T1_END_UTC" +%s);         ts_hr=$(date -u -d "$HANDOFF_RECEIPT_UTC" +%s)
  if [ "$ts_hq" -le "$ts_ss" ] && [ "$ts_ss" -le "$ts_se" ] && [ "$ts_se" -le "$ts_t1s" ] \
     && [ "$ts_t1s" -le "$ts_t1e" ] && [ "$ts_t1e" -le "$ts_hr" ]; then
    TS_ORDER=OK
  else
    TS_ORDER=VIOLATED
  fi
fi
record "TIMESTAMP_ORDER=$TS_ORDER handoff_request=$HANDOFF_REQUEST_UTC <= setup_start=$SETUP_START_UTC <= setup_return=$SETUP_END_UTC <= t1_start=$T1_START_UTC <= t1_end=$T1_END_UTC <= handoff_receipt=$HANDOFF_RECEIPT_UTC"
[ "$TS_ORDER" = VIOLATED ] && record "  THE SEQUENCE THE REQUEST ASKED FOR DID NOT HAPPEN IN THAT ORDER. The stamps are kept as taken; nothing is reordered or discarded, and every interval above is read with this line beside it."
[ "$TS_ORDER" = UNMEASURED ] && record "  ORDER NOT MEASURED — at least one of the six stamps is missing or unparseable, so no ordering claim is made either way."
# t1's OWN exit, read from its OWN file. Absent file = the elevated capture never ran.
if [ -f "$R/d2-t1.exit" ]; then
  D2_T1=$(tr -d ' \r\n' < "$R/d2-t1.exit")
  case "$D2_T1" in (''|*[!0-9]*) D2_T1=UNPARSEABLE ;; esac
  exits "d2_t1_capture_EXIT=$D2_T1"
  record "D2(t1) native_exit=$D2_T1 — the ELEVATED capture, read from its own file, never from the setup's exit"
  # VALIDATION IS DEFERRED TO THE REPORTING WINDOW (doyle CT6GS2Y6, approved). It touches no
  # host, and its result is read at exactly three lines, all inside d2_ledger, which runs in
  # cleanup: no in-window decision consumes it, so charging it to the activity budget was the
  # category error F5 named. It runs beside the t3 validation that was always there.
else
  D2_T1=UNAVAILABLE
  record "D2_T1=UNAVAILABLE — the seq-001 request named the elevated capture and no exit file came back."
  record "  THIS IS A LABELLED EVIDENCE GAP, NOT A PASS. The run collected a smaller set: it proceeds with"
  record "  the unelevated points only, the capture contract is NOT satisfied, and no downstream conclusion"
  record "  may rest on the missing observation. A second elevated read would need a second handoff and a"
  record "  second authorization — one nonce is one execution."
fi

# ===========================================================================
# S9  WHAT THE SETUP DID — measured, then captured at t2 BEFORE any teardown
# ===========================================================================
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 setup-post || die "the post-setup census is invalid"
# THE FACE IS READ FROM A FILE, NOT FROM A COMMAND SUBSTITUTION (defect found by the D2
# control, and it is r10's, not mine): face_report calls `record`, which TEES TO STDOUT, so
# `face=$(face_report ...)` captures the whole log block ahead of the verdict and the value
# can never equal 'reconciled'. In r10 that made the Arm-B acceptance gate unpassable on the
# ACCEPTED path -- the path its stub cases never exercised, because the case that reached
# this line was a refusal that was expected to fail anyway. face_report is left BYTE-FOR-BYTE
# as r10 wrote it; the fix is here, at the call, and the tee'd copy is kept as evidence.
face_report "$SETUP_OUT" "$SETUP_ERR" "SETUP" bootstrap > "$R/setup-face.txt"
setup_face=$(tail -1 "$R/setup-face.txt" | tr -d ' 
')
pair=$(pair_state setup-post)
record "SETUP rc=$SETUP_RC face=$setup_face pair=$pair row=[$(census_row setup-post)]"
# THE OUTCOME IS DATA HERE, NOT A GATE. r10 held its populated arm unless the setup was
# ACCEPTED on three conditions, because a trial needs a pair the product agreed to. D2 wants
# the state AT THE REFUSAL just as much as the state at an acceptance -- that is the whole
# point of capturing it -- so the acceptance is RECORDED and the capture proceeds either way.
# What is not allowed is silence: which of the two happened is written down, and the pair's
# measured presence is what any later reading of these documents depends on.
if [ "$SETUP_RC" -ne 0 ] || [ "$setup_face" != reconciled ] || [ "$pair" != present ]; then
  record "SETUP_NOT_ACCEPTED rc=$SETUP_RC face=$setup_face pair=$pair — the capture below is of a REFUSING state, which is evidence, not a failure of this run"
  [ "$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)." ;;
    enforcement|source-store)
      record "  DIAGNOSTIC: an enforcement/persistence refusal. decide() got past pair_satisfied_by (:723), so the representation WAS accepted." ;;
    unverified-after-write)
      record "  DIAGNOSTIC: the writes landed and the observation was cut short. NOT a refused write." ;;
  esac
  [ "$pair" != present ] && record "  THE PAIR IS NOT MEASURED PRESENT (state=$pair). t2 and t3 will record what is actually there, which may be nothing; an empty capture of an absent pair is an observation of absence, never an observation of the pair."
else
  record "SETUP_ACCEPTED rc=0 face=reconciled pair=present — reconcile() re-verified after writing (windows.rs:816), so RECONCILED here does imply verify() Ok(true) at that instant"
fi
# THE LISTENER'S IDENTITY, using r10's canonical comparison: a capture of the wrong
# process's pair would be a capture of the wrong thing entirely.
if port_at setup-post-listener; then
  bp_out=$(binder_path_verdict "$R/portfields-$PORT-setup-post-listener.txt" "$EXE"); bp_rc=$?
  record "BINDER_CHECK setup-post-listener $bp_out"
  case "$bp_rc" in
    0) : ;;
    1) record "  BINDER DIFFERENT — the listener on port $PORT is not this executable. The captures below are still taken and still recorded: what they describe is the RULE STORE, and this line is the standing caveat on attributing the pair to this run's process." ;;
    *) record "  BINDER UNMEASURED — an instrument failure, NOT a finding about the binder" ;;
  esac
else
  record "PORT_FIELDS invalid at setup-post-listener — the binder identity is UNMEASURED, not confirmed"
fi

# ===========================================================================
# S9a  RUN-BOUND PROCESS IDENTITY — captured NOW, while the leg's processes are live
# ===========================================================================
# The elevated setup dispatches through the daemon (ensure_running, serveverb.rs:191), so if a
# supervisor and a brain exist at all, they exist now. Cleanup cannot re-query what was never
# recorded, and it must never fall back to guessing by command-line text: the r10 survivors'
# command lines contain nothing that identifies this run.
capture_run_identities post-setup
# ===========================================================================
# S10  t2 — at the outcome, BESIDE D1, BEFORE ANY TEARDOWN IS REQUESTED
# ===========================================================================
abort_check
deadline_check t2-capture
record "D1 and t2 run NOW, before any teardown is requested, so the state at this outcome is captured while it still exists."
d1_capture setup-outcome
d2_capture_at t2 "$(exp_left)"
D2_T2=$(tr -d ' 
' < "$R/d2-t2.exit" 2>/dev/null || echo UNRECORDED)
# t2's validation is DEFERRED with t1's — see the note at the t1 site. This is the 11s
# reporting tail that overran the window in run 20260913T071131Z.

# ===========================================================================
# S11  HAND BACK TO CLEANUP. t3, the manifest and the teardown live there.
# ===========================================================================
# The remaining sequence is CLEANUP'S, and it runs whether this line is reached or not:
#   t3 immediately before the teardown request is written, the manifest hashed before the
#   teardown, the teardown handoff, the residual-identity report and the ledger.
# Reaching this line is therefore NOT the end of the run, and exiting 0 here says only that
# the experimental sequence completed and the ledger will be written. THE VERDICTS ARE IN
# THE LEDGER: a run whose t1 never happened, whose documents were incomplete or whose
# teardown could not be verified reports exactly that, and cleanup raises the exit to 6 when
# an otherwise successful run could not verify its own teardown.
record "EXPERIMENTAL_SEQUENCE_COMPLETE — t1=$D2_T1 t2=$D2_T2; t3, the manifest and the teardown follow in cleanup"
end_experimental "sequence complete"
exit 0
