#!/usr/bin/env bash
# beagle-test: tiered test runner for beagle.
#
# Replaces direct `raco test beagle-test/tests/`. Reads tier classifications
# from beagle-test/tiers.rktd; ordinary runs use hosted active + demoted tiers.
# Native Core evidence is an explicit blocking `--include-native` route.
#
# Usage:
#   bin/beagle-test                         # active tier only (fast loop)
#   bin/beagle-test --full                  # active + demoted tiers
#   bin/beagle-test --include-gated         # also run gated tier (needs env vars)
#   bin/beagle-test --include-native        # also run blocking Native Core tier
#   bin/beagle-test --changed               # only what the change can affect
#   bin/beagle-test --explain-selection     # print that selection, run nothing
#
# --changed is the DEV LOOP. It reads the changed file set from git (working
# tree plus every commit since the merge base with main), maps each path
# through bin/_beagle-test-selection, and runs only the phases and suites that
# change can affect. A path the table does not recognize -- the checker, the
# type system, the reader, the stdlib tables, shared lowering, anything new --
# selects the full sweep, so narrowing is an allowlist and never an accident.
#
# The RELEASE GATE is the plain command with no flag. It is unchanged, it is
# still the default, and a narrowed run is not a substitute for it.
#
# Exit status is a CLASSIFICATION, not just a pass/fail bit:
#
#   0    every phase ran and passed.
#   1    a phase ran to completion and found a defect. GATING: fix the code.
#   124  a deadline was exceeded and the work was killed unfinished — either a
#        whole phase, or a test unit inside the tier runner. DIAGNOSTIC, NOT
#        GATING: the run proved nothing about the code, most often because the
#        machine was loaded. It is not a pass either — re-run it. Never read a
#        124 as "your work is bad".
#   2    harness or supervisor contract failure.
#
# A COMPLETED FAILURE OUTRANKS A BREACH, at every level. If anything ran to
# completion and failed, the exit status is 1, whatever else timed out
# alongside it. A diagnostic never masks evidence the gate actually obtained.
#
# The last line of output is a single greppable verdict:
#   beagle-test: VERDICT=PASS|FAIL|DIAGNOSTIC gating=yes|no phase=... exit=N load=...
#
# Demoted failures DO NOT affect exit code (advisory only).
#
# IMPORTANT: use this script, not `raco test` directly, during iteration.
# `raco test` bypasses tier logic and will block on demoted failures.

set -uo pipefail

source "$(dirname "$0")/_beagle-cold-authority"

# --explain-selection runs no test, so it takes no gate lock and needs no
# Racket. It exists so a human can read WHY a suite would be selected or
# skipped without paying for a gate run to find out.
if [[ " $* " == *" --explain-selection "* ]]; then
    source "$(dirname "$0")/_beagle-test-selection"
    beagle_selection_explain_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
    beagle_selection_compute "$beagle_selection_explain_root"
    beagle_selection_report "$beagle_selection_explain_root"
    exit 0
fi

if [[ "${BEAGLE_TEST_LOCKED:-0}" != 1 ]]; then
    BEAGLE_TEST_LOCK="${TMPDIR:-/tmp}/beagle-gate.lock"
    if ! flock -n "$BEAGLE_TEST_LOCK" -c ':'; then
        echo "beagle-test: waiting for concurrent gate to finish" >&2
    fi
    exec env BEAGLE_TEST_LOCKED=1 flock "$BEAGLE_TEST_LOCK" "$0" "$@"
fi

source "$(dirname "$0")/_beagle-racket"

BEAGLE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BEAGLE_TEST_BUN="$(command -v bun 2>/dev/null || true)"

# --changed is consumed here; everything else is forwarded to the tier runner
# untouched, so the runner keeps seeing exactly the argv it always saw.
BEAGLE_TEST_SELECT_CHANGED=0
BEAGLE_TEST_INCLUDE_NATIVE=0
beagle_test_forward_args=()
for beagle_test_arg in "$@"; do
    if [[ "$beagle_test_arg" == "--changed" ]]; then
        BEAGLE_TEST_SELECT_CHANGED=1
    elif [[ "$beagle_test_arg" == "--include-native" ]]; then
        BEAGLE_TEST_INCLUDE_NATIVE=1
        beagle_test_forward_args+=("$beagle_test_arg")
    else
        beagle_test_forward_args+=("$beagle_test_arg")
    fi
done
set -- "${beagle_test_forward_args[@]+"${beagle_test_forward_args[@]}"}"

# The parity driver runs this exact control path against a tiny hermetic gate
# tree.  The override is deliberately double-keyed and test-only; ordinary and
# fact-shadow invocations continue to resolve every command from this checkout.
if [[ -n "${BEAGLE_GATE_FACT_TEST_ROOT:-}" ]]; then
    if [[ "${BEAGLE_GATE_FACT_TEST_MODE:-0}" != 1 ]]; then
        echo "beagle-test: BEAGLE_GATE_FACT_TEST_ROOT requires BEAGLE_GATE_FACT_TEST_MODE=1" >&2
        exit 2
    fi
    BEAGLE_ROOT="$(cd "$BEAGLE_GATE_FACT_TEST_ROOT" && pwd)"
fi

BEAGLE_GATE_FACT_OBSERVATION_DIR="${BEAGLE_GATE_FACT_OBSERVATION_DIR:-}"
if [[ -n "$BEAGLE_GATE_FACT_OBSERVATION_DIR" ]]; then
    if ! mkdir -p "$BEAGLE_GATE_FACT_OBSERVATION_DIR"; then
        echo "beagle-test: fact observation directory is unavailable: $BEAGLE_GATE_FACT_OBSERVATION_DIR" >&2
    fi
    export BEAGLE_GATE_FACT_UNIT_OBSERVATIONS="$BEAGLE_GATE_FACT_OBSERVATION_DIR/tier-units.rktd"
fi

# Each phase has its own deadline and log. run-bounded.rkt is the accountable
# process supervisor: it owns the phase subtree, publishes START/END/TIMEOUT
# progress, and reaps descendants before returning.
BEAGLE_TEST_SUPERVISOR="$BEAGLE_ROOT/native-core/bin/run-bounded.rkt"
BEAGLE_TEST_LOG_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/beagle-test-phase.XXXXXX")"
BEAGLE_TEST_KEEP_LOGS=0
BEAGLE_TEST_SHARD_PIDS=()

# Exit-status contract, and the whole point of it: a deadline breach is a
# statement about the MACHINE, a non-zero child status is a statement about the
# CODE. Collapsing the first into the second is what taught lane owners their
# correct work was bad. These two verdicts never share a status again.
BEAGLE_TEST_STATUS_DEFECT=1     # a phase finished and found something wrong
BEAGLE_TEST_STATUS_DIAGNOSTIC=124   # a phase never finished; it proved nothing
BEAGLE_TEST_CORES="$(nproc 2>/dev/null || printf 'unknown')"
BEAGLE_TEST_VERDICT_PHASE=""
BEAGLE_TEST_PHASE_RAN=0

# Phase deadlines, in seconds. Both the predeclared fact claims and the enforced
# supervisor bound read THIS table: a claim that disagrees with the bound it
# claims to describe is not a claim, and the two used to drift (consumer-smoke
# was predeclared at 100s while 180s was enforced).
#
# What a deadline is FOR: catching a HANG. It is not a speed limit, and setting
# it below what the work honestly costs does not make the work faster — it just
# manufactures false failures and strands correct lanes, which is exactly what
# happened here. So each bound below sits above the slowest honest run measured
# on this machine, with the headroom stated.
#
# The 2-3 minute verification law is enforced somewhere else, on purpose: by the
# NAMED SPEED DEFECTS in docs and in the commit that set these numbers, not by a
# deadline that lies. Two phases are over the line today and are recorded as
# defects to fix, not blessed:
#   tier-runner    406s honest  — floored by ONE test, wasm-materializer.rkt
#                                 #core-publication-preserv-db27b4 at 404s, so
#                                 no amount of sharding brings it under 3 min.
#   consumer-smoke 308s honest on a cold cache miss (11-20s when the native
#                                 caches are prepared) — bimodal, and every lane
#                                 that changes the source closure pays the slow
#                                 side.
declare -A BEAGLE_TEST_PHASE_DEADLINE=(
    # Fresh-cache scope work completes around 139-150s and can reach its final
    # immutable-checkout probe near 180s. 360s keeps the hang detector above 2x
    # the observed legitimate path.
    [racket-scope]=360
    # honest 1s. A 30s floor: process startup alone can eat a small budget.
    [checkout-first]=30
    # honest <1s. Same floor reasoning, smaller work.
    [qualified-ref-scaffold]=15
    # Many isolated Babashka admissions plus sealed dispatch/publication probes;
    # 120s admits cold startup while remaining a useful hang detector.
    [hosted-preflight-routing]=120
    # One public check/build/AST route plus the exact TypeScript projection.
    # The parser-first landing currently forbids timing this new phase, so this
    # is an explicit first-run hang ceiling, to be priced from the first
    # permitted full-route observation before release.
    [typescript-foreign-interface-v1-public-route]=600
    # honest 2s once the typed planner and Rust supervisor are cached; 240s
    # admits a cold compiler/supervisor build without turning slowness into a
    # false product verdict.
    [byte-stable-emit]=240
    # honest 11-20s prepared, 308s on a cold miss (load 7.1). ~2x the miss case.
    [consumer-smoke]=600
    # honest 406s (load 6.4-8.0), 16 shards. ~2.2x.
    [tier-runner]=900
    # The narrowed counterpart of tier-runner. A selection is a SUBSET of what
    # tier-runner runs, so it can never honestly cost more; it keeps the same
    # bound rather than a tighter one because the worst legal selection is a
    # change to the one multi-minute suite itself.
    [tier-selected]=900
    # Not a gate phase: the opt-in probe below deliberately breaches this.
    [synthetic-timeout]=1
)

beagle_test_deadline() {
    local phase="$1"
    if [[ -z "${BEAGLE_TEST_PHASE_DEADLINE[$phase]+set}" ]]; then
        echo "beagle-test: no deadline is declared for phase $phase" >&2
        exit 2
    fi
    printf '%s' "${BEAGLE_TEST_PHASE_DEADLINE[$phase]}"
}

# The supervisor multiplies every deadline by BEAGLE_DEADLINE_SCALE. Reporting
# the unscaled number next to an observed wall the reader can see is smaller
# would be its own small lie, so say what was actually enforced.
beagle_test_effective_deadline() {
    local deadline="$1" scale="${BEAGLE_DEADLINE_SCALE:-}"
    if [[ -z "$scale" || "$scale" == 1 ]]; then
        printf '%ss' "$deadline"
    else
        printf '%ss (declared %ss x BEAGLE_DEADLINE_SCALE=%s)' \
            "$(awk -v d="$deadline" -v s="$scale" 'BEGIN{printf "%g", d*s}')" \
            "$deadline" "$scale"
    fi
}

# Every timing this gate prints carries the machine load beside it, so a reader
# can see WHY a phase ran long instead of guessing.
beagle_test_load() {
    local one_minute
    if read -r one_minute _ </proc/loadavg 2>/dev/null; then
        printf '%s' "$one_minute"
    else
        printf 'unknown'
    fi
}

beagle_test_stop_shards() {
    local pid
    for pid in "${BEAGLE_TEST_SHARD_PIDS[@]:-}"; do
        if kill -0 "$pid" 2>/dev/null; then
            kill -TERM "$pid" 2>/dev/null || true
        fi
    done
    for pid in "${BEAGLE_TEST_SHARD_PIDS[@]:-}"; do
        wait "$pid" 2>/dev/null || true
    done
    BEAGLE_TEST_SHARD_PIDS=()
}

# The banners exist because the distinction has to survive a reader who scrolled
# past thousands of lines of phase output and looked at the last screen.
beagle_test_rule() {
    echo "==================================================================" >&2
}

beagle_test_diagnostic_banner() {
    local label="$1" deadline="$2" wall="$3" load_start="$4" load_end="$5" log="$6"
    beagle_test_rule
    {
        echo "beagle-test: DIAGNOSTIC -- NOT A PRODUCT FAILURE"
        echo "  phase           $label"
        echo "  outcome         deadline exceeded; the phase was killed unfinished"
        echo "  deadline        $(beagle_test_effective_deadline "$deadline")"
        echo "  observed wall   ${wall}s"
        echo "  machine load    ${load_start} at start -> ${load_end} at breach" \
             "(${BEAGLE_TEST_CORES} cores)"
        echo "  exit status     $BEAGLE_TEST_STATUS_DIAGNOSTIC (diagnostic);" \
             "$BEAGLE_TEST_STATUS_DEFECT is reserved for a product defect"
        echo
        echo "  An unfinished phase is UNPROVEN, not disproven. This run is NOT"
        echo "  evidence of a defect in the code under test, and it is not a pass"
        echo "  either. Do not abandon the work. Re-run when the machine is"
        echo "  quieter; if the phase is honestly this slow, that is a speed"
        echo "  defect in the phase, to be fixed rather than budgeted around."
        echo "  phase log       $log"
    } >&2
    beagle_test_rule
}

# The phase ran to completion; a test UNIT inside it was killed at its own
# deadline. Same classification, different subject, so it says so plainly
# instead of claiming the phase was killed.
beagle_test_unit_diagnostic_banner() {
    local label="$1" wall="$2" load_start="$3" load_end="$4" log="$5"
    beagle_test_rule
    {
        echo "beagle-test: DIAGNOSTIC -- NOT A PRODUCT FAILURE"
        echo "  phase           $label"
        echo "  outcome         the phase finished; one or more test UNITS were"
        echo "                  killed at their own deadline and never finished"
        echo "  observed wall   ${wall}s"
        echo "  machine load    ${load_start} at start -> ${load_end} at end" \
             "(${BEAGLE_TEST_CORES} cores)"
        echo "  exit status     $BEAGLE_TEST_STATUS_DIAGNOSTIC (diagnostic);" \
             "$BEAGLE_TEST_STATUS_DEFECT is reserved for a product defect"
        echo
        echo "  No active unit FAILED. A unit that ran out of time is UNPROVEN,"
        echo "  not disproven, and a completed failure would have outranked it."
        echo "  The units are named under ACTIVE DIAGNOSTIC DETAIL above."
        echo "  phase log       $log"
    } >&2
    beagle_test_rule
}

beagle_test_defect_banner() {
    local label="$1" status="$2" wall="$3" load_start="$4" load_end="$5" log="$6"
    beagle_test_rule
    {
        echo "beagle-test: PRODUCT FAILURE -- the gate found a real defect"
        echo "  phase           $label"
        echo "  outcome         the phase RAN TO COMPLETION and reported failure"
        echo "  exit status     $status"
        echo "  observed wall   ${wall}s"
        echo "  machine load    ${load_start} at start -> ${load_end} at end" \
             "(${BEAGLE_TEST_CORES} cores)"
        echo "  phase log       $log"
    } >&2
    beagle_test_rule
}

# One greppable terminal line. A caller that reads nothing else can branch on it.
beagle_test_emit_verdict() {
    local status="$1"
    [[ "$BEAGLE_TEST_PHASE_RAN" == 1 ]] || return 0
    case "$status" in
        0)
            echo "beagle-test: VERDICT=PASS exit=0 load=$(beagle_test_load)" >&2
            ;;
        "$BEAGLE_TEST_STATUS_DIAGNOSTIC")
            echo "beagle-test: VERDICT=DIAGNOSTIC gating=no" \
                 "phase=${BEAGLE_TEST_VERDICT_PHASE:-unknown}" \
                 "reason=deadline-exceeded exit=$status load=$(beagle_test_load)" >&2
            ;;
        *)
            echo "beagle-test: VERDICT=FAIL gating=yes" \
                 "phase=${BEAGLE_TEST_VERDICT_PHASE:-unknown}" \
                 "reason=product-defect exit=$status load=$(beagle_test_load)" >&2
            ;;
    esac
}

beagle_test_cleanup() {
    local status=$?
    beagle_test_stop_shards
    if [[ "$BEAGLE_TEST_KEEP_LOGS" == 1 ]]; then
        echo "beagle-test: preserved phase logs at $BEAGLE_TEST_LOG_ROOT" >&2
    else
        rm -rf -- "${BEAGLE_TEST_LOG_ROOT:?}"
    fi
    beagle_test_emit_verdict "$status"
    exit "$status"
}
trap beagle_test_cleanup EXIT

beagle_test_slug() {
    printf '%s' "$1" | tr '[:upper:] /' '[:lower:]__' | tr -cd '[:alnum:]_-'
}

# These files are raw observations at the old gate boundaries, not admitted
# facts.  Observation failure is visible to the shadow maintainer but never
# suppresses or reclassifies the authoritative command that follows.
beagle_test_fact_write_claim() {
    [[ -n "$BEAGLE_GATE_FACT_OBSERVATION_DIR" ]] || return 0
    local label="$1"
    local deadline="$2"
    local slug="$3"
    shift 3
    local digest target temporary
    digest="$(printf '%s\0' "$@" | sha256sum | cut -d' ' -f1)"
    target="$BEAGLE_GATE_FACT_OBSERVATION_DIR/phase-$slug.claim"
    temporary="$(mktemp "$BEAGLE_GATE_FACT_OBSERVATION_DIR/.phase-claim.XXXXXX")" || return 1
    if printf '%s\n' \
        'beagle-gate-phase-claim-v1' \
        "label=$label" \
        "deadline-seconds=$deadline" \
        "command-sha256=$digest" >"$temporary" &&
       mv -f "$temporary" "$target"; then
        return 0
    fi
    rm -f -- "$temporary"
    return 1
}

beagle_test_fact_write_observation() {
    [[ -n "$BEAGLE_GATE_FACT_OBSERVATION_DIR" ]] || return 0
    local label="$1"
    local slug="$2"
    local status="$3"
    local log="$4"
    local receipt="$5"
    local completion log_digest receipt_digest target temporary
    if [[ "$status" -eq 124 ]]; then
        completion="timeout"
    else
        completion="exit"
    fi
    if [[ -f "$log" ]]; then
        log_digest="$(sha256sum "$log" | cut -d' ' -f1)"
    else
        log_digest=missing
    fi
    if [[ -f "$receipt" ]]; then
        receipt_digest="$(sha256sum "$receipt" | cut -d' ' -f1)"
    else
        receipt_digest=missing
    fi
    target="$BEAGLE_GATE_FACT_OBSERVATION_DIR/phase-$slug.observation"
    temporary="$(mktemp "$BEAGLE_GATE_FACT_OBSERVATION_DIR/.phase-observation.XXXXXX")" || return 1
    if printf '%s\n' \
        'beagle-gate-phase-observation-v1' \
        "label=$label" \
        "completion=$completion" \
        "exit-code=$status" \
        "log-sha256=$log_digest" \
        "receipt-sha256=$receipt_digest" >"$temporary" &&
       mv -f "$temporary" "$target"; then
        return 0
    fi
    rm -f -- "$temporary"
    return 1
}

beagle_test_fact_write_shard_receipt() {
    [[ -n "$BEAGLE_GATE_FACT_OBSERVATION_DIR" ]] || return 0
    local workers="$1"
    local worker_root="$2"
    local target="$3"
    local temporary i value
    temporary="$(mktemp "$BEAGLE_GATE_FACT_OBSERVATION_DIR/.tier-receipt.XXXXXX")" || return 1
    {
        printf '%s\n' 'beagle-tier-shard-receipts-v1' "workers=$workers"
        for ((i = 0; i < workers; i++)); do
            if [[ -f "$worker_root/worker-$i.receipt" ]]; then
                value="$(<"$worker_root/worker-$i.receipt")"
            else
                value=missing
            fi
            printf 'worker-%s=%s\n' "$i" "$value"
        done
    } >"$temporary"
    if mv -f "$temporary" "$target"; then
        return 0
    fi
    rm -f -- "$temporary"
    return 1
}

run_beagle_test_phase() {
    local label="$1"
    local deadline
    deadline="$(beagle_test_deadline "$1")"
    shift 1
    local slug log receipt status tee_status
    local load_start load_end started wall
    local -a pipeline_status
    slug="$(beagle_test_slug "$label")"
    log="$BEAGLE_TEST_LOG_ROOT/$slug.log"
    receipt="$BEAGLE_TEST_LOG_ROOT/$slug.receipt"

    if ! beagle_test_fact_write_claim "$label" "$deadline" "$slug" "$@"; then
        echo "beagle-test: fact claim observation write failed for $label" >&2
    fi

    BEAGLE_TEST_PHASE_RAN=1
    BEAGLE_TEST_VERDICT_PHASE="$label"
    load_start="$(beagle_test_load)"
    started=$SECONDS
    echo "beagle-test: phase $label START deadline=${deadline}s load=${load_start}/${BEAGLE_TEST_CORES} log=$log receipt=$receipt" >&2
    set +e
    BEAGLE_BOUNDED_COMPLETION_RECEIPT="$receipt" \
        "$RACKET" "$BEAGLE_TEST_SUPERVISOR" "$deadline" 5 -- "$@" 2>&1 |
        tee "$log"
    pipeline_status=("${PIPESTATUS[@]}")
    status="${pipeline_status[0]}"
    tee_status="${pipeline_status[1]}"
    set -e
    wall=$((SECONDS - started))
    load_end="$(beagle_test_load)"

    if [[ "$tee_status" -ne 0 ]]; then
        status="$tee_status"
    fi
    if [[ "$status" -eq "$BEAGLE_TEST_STATUS_DIAGNOSTIC" ]]; then
        BEAGLE_TEST_KEEP_LOGS=1
        echo "beagle-test: phase $label TIMEOUT status=$status wall=${wall}s load=${load_end}/${BEAGLE_TEST_CORES}; stopping gate" >&2
        beagle_test_diagnostic_banner \
            "$label" "$deadline" "$wall" "$load_start" "$load_end" "$log"
    elif [[ "$status" -ne 0 ]]; then
        BEAGLE_TEST_KEEP_LOGS=1
        echo "beagle-test: phase $label FAILED status=$status wall=${wall}s load=${load_end}/${BEAGLE_TEST_CORES}; stopping gate" >&2
        beagle_test_defect_banner \
            "$label" "$status" "$wall" "$load_start" "$load_end" "$log"
    else
        echo "beagle-test: phase $label END status=0 wall=${wall}s load=${load_end}/${BEAGLE_TEST_CORES}" >&2
        BEAGLE_TEST_VERDICT_PHASE=""
    fi
    if ! beagle_test_fact_write_observation "$label" "$slug" "$status" "$log" "$receipt"; then
        echo "beagle-test: fact result observation write failed for $label" >&2
    fi
    return "$status"
}

run_beagle_test_shards() {
    local deadline
    deadline="$(beagle_test_deadline tier-runner)"
    local runner="$BEAGLE_ROOT/beagle-lib/private/tier-runner.rkt"
    local worker_root="$BEAGLE_TEST_LOG_ROOT/tier-workers"
    local workers count_status i pid completed_pid status receipt expected
    local aggregate_log aggregate_receipt merge_status tee_status terminal_status started_seconds wall_seconds
    local load_start load_end
    local -a live next_live pipeline_status
    local -A worker_by_pid

    aggregate_log="$BEAGLE_TEST_LOG_ROOT/tier-runner.log"
    aggregate_receipt="$BEAGLE_TEST_LOG_ROOT/tier-runner.receipt"
    if ! beagle_test_fact_write_claim "tier-runner" "$deadline" "tier-runner" "$runner" "$@"; then
        echo "beagle-test: fact claim observation write failed for tier-runner" >&2
    fi
    mkdir -p "$worker_root"
    set +e
    workers="$("$RACKET" "$runner" "$@" --print-worker-count)"
    count_status=$?
    set -e
    if [[ "$count_status" -ne 0 || ! "$workers" =~ ^[1-9][0-9]*$ ]]; then
        BEAGLE_TEST_KEEP_LOGS=1
        echo "beagle-test: tier-runner worker-count resolution failed" >&2
        beagle_test_fact_write_observation \
            "tier-runner" "tier-runner" 2 "$aggregate_log" "$aggregate_receipt" || true
        return 2
    fi

    BEAGLE_TEST_PHASE_RAN=1
    BEAGLE_TEST_VERDICT_PHASE="tier-runner"
    load_start="$(beagle_test_load)"
    started_seconds=$SECONDS
    echo "beagle-test: phase tier-runner START deadline=${deadline}s workers=$workers load=${load_start}/${BEAGLE_TEST_CORES}" >&2

    # The explicit Native tier's Wasm phases are separate processes that all start at once and
    # all need the same canonical fixtures. Cold, they used to race: one built
    # while the rest sat on the exclusive fixture lock, and a waiter that
    # outlasted the lock's delay failed with "timed out acquiring shared base
    # fixture lock" — contention reported as a product defect. Build them ONCE
    # here, before anything forks, so every worker hits a warm cache. This is
    # preparation, not a check: it asserts nothing, and a failure is left for
    # the phases themselves to report against their own assertions rather than
    # being reclassified into a gate verdict here.
    if [[ "$BEAGLE_TEST_INCLUDE_NATIVE" == 1 ]]; then
        local prepare_log="$BEAGLE_TEST_LOG_ROOT/tier-fixtures.log"
        local prepare_started=$SECONDS
        if BEAGLE_WASM_TEST_PREPARE_FIXTURES=1 \
            "$RACKET" "$BEAGLE_ROOT/beagle-test/tests/wasm-materializer.rkt" \
            >"$prepare_log" 2>&1; then
            echo "beagle-test: tier-runner shared Native fixtures prepared wall=$((SECONDS - prepare_started))s load=$(beagle_test_load)/${BEAGLE_TEST_CORES}" >&2
        else
            echo "beagle-test: tier-runner shared Native fixture preparation did not complete (status=$?); phases will build their own. log=$prepare_log" >&2
            BEAGLE_TEST_KEEP_LOGS=1
        fi
    fi
    for ((i = 0; i < workers; i++)); do
        local log="$worker_root/worker-$i.log"
        local result="$worker_root/worker-$i.rktd"
        local shard_receipt="$worker_root/worker-$i.receipt"
        rm -f "$result" "$shard_receipt"
        echo "beagle-test: shard tier-runner[$i/$workers] START deadline=${deadline}s log=$log receipt=$shard_receipt" >&2
        BEAGLE_BOUNDED_COMPLETION_RECEIPT="$shard_receipt" \
            "$RACKET" "$BEAGLE_TEST_SUPERVISOR" "$deadline" 5 -- \
            "$RACKET" "$runner" "$@" \
            --worker-shard "$i/$workers" --worker-result "$result" \
            >"$log" 2>&1 &
        pid=$!
        BEAGLE_TEST_SHARD_PIDS+=("$pid")
        live+=("$pid")
        worker_by_pid["$pid"]="$i"
    done

    terminal_status=0
    while ((${#live[@]} > 0)); do
        completed_pid=""
        set +e
        wait -n -p completed_pid "${live[@]}"
        status=$?
        set -e
        if [[ -z "$completed_pid" || -z "${worker_by_pid[$completed_pid]+set}" ]]; then
            terminal_status=2
            echo "beagle-test: shard supervisor wait contract failed" >&2
            break
        fi
        i="${worker_by_pid[$completed_pid]}"
        next_live=()
        for pid in "${live[@]}"; do
            [[ "$pid" == "$completed_pid" ]] || next_live+=("$pid")
        done
        live=("${next_live[@]}")

        receipt=""
        [[ -f "$worker_root/worker-$i.receipt" ]] && \
            receipt="$(<"$worker_root/worker-$i.receipt")"
        if [[ "$status" -eq 124 ]]; then
            expected="subtree-reaped-v0 timeout status=124"
        else
            expected="subtree-reaped-v0 exit status=$status"
        fi
        if [[ "$receipt" != "$expected" ]]; then
            echo "beagle-test: shard tier-runner[$i/$workers] receipt mismatch status=$status receipt=${receipt:-missing}" >&2
            status=2
        fi

        if [[ "$status" -eq 0 ]]; then
            echo "beagle-test: shard tier-runner[$i/$workers] END status=0" >&2
        elif [[ "$status" -eq 1 && -f "$worker_root/worker-$i.rktd" ]]; then
            echo "beagle-test: shard tier-runner[$i/$workers] END status=1 (test failure recorded for merge)" >&2
        elif [[ "$status" -eq "$BEAGLE_TEST_STATUS_DIAGNOSTIC" ]]; then
            echo "beagle-test: shard tier-runner[$i/$workers] TIMEOUT status=$status load=$(beagle_test_load)/${BEAGLE_TEST_CORES}" >&2
            terminal_status="$BEAGLE_TEST_STATUS_DIAGNOSTIC"
        else
            echo "beagle-test: shard tier-runner[$i/$workers] FAILED status=$status load=$(beagle_test_load)/${BEAGLE_TEST_CORES}" >&2
            # A shard that RAN TO COMPLETION and reported failure found a real
            # defect, so it outranks a sibling shard's deadline breach. A
            # diagnostic must never mask evidence the gate actually obtained;
            # the breach is still reported below, it just does not decide.
            terminal_status="$status"
        fi
    done

    if [[ "$terminal_status" -ne 0 ]]; then
        BEAGLE_TEST_KEEP_LOGS=1
        beagle_test_stop_shards
        for ((i = 0; i < workers; i++)); do
            if [[ ! -f "$worker_root/worker-$i.rktd" && -s "$worker_root/worker-$i.log" ]]; then
                sed "s/^/  [shard $i] /" "$worker_root/worker-$i.log" >&2
            fi
        done
        beagle_test_fact_write_shard_receipt \
            "$workers" "$worker_root" "$aggregate_receipt" || true
        wall_seconds=$((SECONDS - started_seconds))
        load_end="$(beagle_test_load)"
        if [[ "$terminal_status" -eq "$BEAGLE_TEST_STATUS_DIAGNOSTIC" ]]; then
            echo "beagle-test: phase tier-runner TIMEOUT status=$terminal_status wall=${wall_seconds}s load=${load_end}/${BEAGLE_TEST_CORES}; stopping gate" >&2
            beagle_test_diagnostic_banner "tier-runner" "$deadline" \
                "$wall_seconds" "$load_start" "$load_end" "$worker_root"
        else
            echo "beagle-test: phase tier-runner FAILED status=$terminal_status wall=${wall_seconds}s load=${load_end}/${BEAGLE_TEST_CORES}; stopping gate" >&2
            beagle_test_defect_banner "tier-runner" "$terminal_status" \
                "$wall_seconds" "$load_start" "$load_end" "$worker_root"
        fi
        beagle_test_fact_write_observation \
            "tier-runner" "tier-runner" "$terminal_status" "$aggregate_log" "$aggregate_receipt" || true
        return "$terminal_status"
    fi
    BEAGLE_TEST_SHARD_PIDS=()
    if ! beagle_test_fact_write_shard_receipt \
        "$workers" "$worker_root" "$aggregate_receipt"; then
        echo "beagle-test: fact shard receipt write failed for tier-runner" >&2
    fi

    set +e
    "$RACKET" "$runner" "$@" --merge-worker-results "$worker_root" 2>&1 |
        tee "$aggregate_log"
    pipeline_status=("${PIPESTATUS[@]}")
    merge_status="${pipeline_status[0]}"
    tee_status="${pipeline_status[1]}"
    set -e
    [[ "$tee_status" -eq 0 ]] || merge_status="$tee_status"
    wall_seconds=$((SECONDS - started_seconds))
    load_end="$(beagle_test_load)"
    if [[ "$merge_status" -eq 0 ]]; then
        echo "beagle-test: phase tier-runner END status=0 wall=${wall_seconds}s load=${load_end}/${BEAGLE_TEST_CORES}" >&2
        BEAGLE_TEST_VERDICT_PHASE=""
    elif [[ "$merge_status" -eq "$BEAGLE_TEST_STATUS_DIAGNOSTIC" ]]; then
        # Every shard completed, and the merge — the one place that sees all of
        # them — found that the only active non-passes were units killed at a
        # deadline. Nothing failed, so nothing here is a product verdict. Had
        # any unit actually failed, the merge would have exited 1 instead: a
        # completed failure outranks a breach.
        BEAGLE_TEST_KEEP_LOGS=1
        echo "beagle-test: phase tier-runner UNIT-TIMEOUT status=$merge_status wall=${wall_seconds}s load=${load_end}/${BEAGLE_TEST_CORES}; stopping gate" >&2
        beagle_test_unit_diagnostic_banner "tier-runner" \
            "$wall_seconds" "$load_start" "$load_end" "$aggregate_log"
    else
        BEAGLE_TEST_KEEP_LOGS=1
        echo "beagle-test: phase tier-runner FAILED status=$merge_status wall=${wall_seconds}s load=${load_end}/${BEAGLE_TEST_CORES}; stopping gate" >&2
        beagle_test_defect_banner "tier-runner" "$merge_status" \
            "$wall_seconds" "$load_start" "$load_end" "$aggregate_log"
    fi
    if ! beagle_test_fact_write_observation \
        "tier-runner" "tier-runner" "$merge_status" "$aggregate_log" "$aggregate_receipt"; then
        echo "beagle-test: fact result observation write failed for tier-runner" >&2
    fi
    return "$merge_status"
}

beagle_test_fact_write_declared_claims() {
    local runner="$BEAGLE_ROOT/beagle-lib/private/tier-runner.rkt"
    local phase
    [[ -n "$BEAGLE_TEST_BUN" ]] || {
        echo "beagle-test: Bun is required for JavaScript gate phases; enter the Beagle development shell" >&2
        return 1
    }
    for phase in \
        racket-scope \
        checkout-first \
        qualified-ref-scaffold \
        hosted-preflight-routing \
        typescript-foreign-interface-v1-public-route \
        consumer-smoke; do
        beagle_test_fact_write_claim \
            "$phase" "$(beagle_test_deadline "$phase")" "$phase" \
            "$BEAGLE_ROOT/bin/test/$phase/run.sh" || return 1
    done
    beagle_test_fact_write_claim \
        "byte-stable-emit" "$(beagle_test_deadline byte-stable-emit)" \
        "byte-stable-emit" "$BEAGLE_TEST_BUN" \
        "$BEAGLE_ROOT/bin/test/byte-stable-emit/run.mjs" "$RACKET" || return 1
    beagle_test_fact_write_claim \
        "tier-runner" "$(beagle_test_deadline tier-runner)" "tier-runner" \
        "$runner" "$@" || return 1
    "$RACKET" "$runner" "$@" \
        --write-fact-claims "$BEAGLE_GATE_FACT_OBSERVATION_DIR/tier-claims.rktd"
}

# Fact preparation needs the complete predeclared claim set before the old
# gate starts.  This mode derives that plan through the same tier expansion but
# executes no gate phase and is never used by an ordinary invocation.
if [[ "${BEAGLE_GATE_FACT_PLAN_ONLY:-0}" == 1 ]]; then
    if [[ -z "$BEAGLE_GATE_FACT_OBSERVATION_DIR" ]]; then
        echo "beagle-test: BEAGLE_GATE_FACT_PLAN_ONLY requires BEAGLE_GATE_FACT_OBSERVATION_DIR" >&2
        exit 2
    fi
    if ! beagle_test_fact_write_declared_claims "$@"; then
        echo "beagle-test: could not write the fact claim plan" >&2
        exit 2
    fi
    exit 0
fi

# A deterministic, opt-in probe for the release-bar timeout contract. It is
# not part of any normal tier; it leaves the child PID in the preserved log
# directory so a caller can prove that the supervisor reaped it.
if [[ "${BEAGLE_TEST_SYNTHETIC_TIMEOUT:-0}" == 1 ]]; then
    synthetic_pid_file="$BEAGLE_TEST_LOG_ROOT/synthetic-child.pid"
    BEAGLE_TEST_KEEP_LOGS=1
    run_beagle_test_phase "synthetic-timeout" \
        "$BASH" -c 'sleep 30 & child=$!; printf "%s\n" "$child" >"$1"; wait "$child"' \
        bash "$synthetic_pid_file" || exit $?
    exit 0
fi

# Canonical physical source is a precondition for every ordinary release or
# changed-input verdict. Check exactly the Beagle files changed from main; the
# formatter itself owns parsing, comment safety, and the nonzero drift status.
source "$BEAGLE_ROOT/bin/_beagle-canonical-format-check"
beagle_canonical_format_check "$BEAGLE_ROOT" "$BEAGLE_ROOT/bin/beagle-fmt" || exit $?

# --changed narrows the run to what the change can affect. The selection can
# still come back "full", and then this path runs exactly the sweep below.
if [[ "$BEAGLE_TEST_SELECT_CHANGED" == 1 ]]; then
    # This is deliberately before any selected phase: it names a declared
    # self-host/Racket twin that changed on one side, while parity is still
    # cheap to schedule rather than expensive to diagnose.  The checker only
    # knows explicit contracts; unpaired infrastructure remains admissible.
    "$BEAGLE_ROOT/bin/beagle-compiler-twin-drift" --strict || exit $?
    source "$BEAGLE_ROOT/bin/_beagle-test-selection"
    beagle_selection_compute "$BEAGLE_ROOT"
    beagle_selection_report "$BEAGLE_ROOT"
    if [[ "$BEAGLE_SELECTION_MODE" == narrow ]]; then
        for beagle_test_phase in "${BEAGLE_SELECTION_PHASES[@]}"; do
            case "$beagle_test_phase" in
                byte-stable-emit|typescript-foreign-interface-v1-public-route)
                    [[ -n "$BEAGLE_TEST_BUN" ]] || {
                        echo "beagle-test: Bun is required for JavaScript gate phases; enter the Beagle development shell" >&2
                        exit 2
                    }
                    ;;
            esac
            if [[ "$beagle_test_phase" == byte-stable-emit ]]; then
                run_beagle_test_phase "$beagle_test_phase" "$BEAGLE_TEST_BUN" \
                    "$BEAGLE_ROOT/bin/test/byte-stable-emit/run.mjs" "$RACKET" || exit $?
            else
                run_beagle_test_phase "$beagle_test_phase" \
                    "$BEAGLE_ROOT/bin/test/$beagle_test_phase/run.sh" || exit $?
            fi
        done
        BEAGLE_GATE_NO_CACHE="$BEAGLE_SELECTION_BYPASS_CACHE" \
        run_beagle_test_phase "tier-selected" \
            "$BEAGLE_ROOT/bin/_beagle-test-selected-units" \
            "${BEAGLE_SELECTION_SUITES[@]}" || exit $?
        echo "beagle-test: narrowed run complete." \
             "The release proof is the plain command: bin/beagle test" >&2
        exit 0
    fi
fi

# `exit $?` and not `exit 1`: this is the line that used to strand finished
# work. Collapsing the supervisor's 124 into 1 told a lane owner the code was
# broken when the only thing that had happened was that the box was busy.
run_beagle_test_phase "racket-scope" \
    "$BEAGLE_ROOT/bin/test/racket-scope/run.sh" || exit $?
run_beagle_test_phase "checkout-first" \
    "$BEAGLE_ROOT/bin/test/checkout-first/run.sh" || exit $?
run_beagle_test_phase "qualified-ref-scaffold" \
    "$BEAGLE_ROOT/bin/test/qualified-ref-scaffold/run.sh" || exit $?
run_beagle_test_phase "hosted-preflight-routing" \
    "$BEAGLE_ROOT/bin/test/hosted-preflight-routing/run.sh" || exit $?
[[ -n "$BEAGLE_TEST_BUN" ]] || {
    echo "beagle-test: Bun is required for JavaScript gate phases; enter the Beagle development shell" >&2
    exit 2
}
run_beagle_test_phase "typescript-foreign-interface-v1-public-route" \
    "$BEAGLE_ROOT/bin/test/typescript-foreign-interface-v1-public-route/run.sh" || exit $?
run_beagle_test_phase "byte-stable-emit" "$BEAGLE_TEST_BUN" \
    "$BEAGLE_ROOT/bin/test/byte-stable-emit/run.mjs" "$RACKET" || exit $?
run_beagle_test_phase "consumer-smoke" \
    "$BEAGLE_ROOT/bin/test/consumer-smoke/run.sh" || exit $?
run_beagle_test_shards "$@" || exit $?
