#!/usr/bin/env bash
# fmix — fast native Elixir test runner for cisco-cdr
# See docs/designs/2026-07-30-fmix-session-cache-v2.md for the v2 contract.
#
# Usage:
#   ./fmix test [--worktree <path>] [--session <id>] [--isolate] [--cache-base <N.N.N-stable>] [--no-auto-setup] [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>
#   ./fmix coverage --worktree <path> [--session <id>] [--no-auto-setup] --base <git-ref> -- <test paths>
#   ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
#   ./fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--dot-formatter <path>] [--check] -- <files...>
#   ./fmix setup [--worktree <path>] [--session <id>] [--rebuild-db|--cold-db|--from-zero]
#   ./fmix seed publish --worktree <path> [--session <id>] --cache-base <N.N.N-stable>
#   ./fmix cache explain --worktree <path> --cache-base <N.N.N-stable>
#   ./fmix cache verify [--key <16-hex-template-key>]
#   # seed publish is explicit clean-stable-only maintenance; cache explain is read-only
#   ./fmix doctor
#   ./fmix status
#   ./fmix timing [--limit N] [--worktree <path>]
#   ./fmix gc [--reap] [--yes]
#   ./fmix gc --artifacts-only [--json]  # bounded read-only inventory; no eviction
#   ./fmix self-test
#   ./fmix verify-push [--worktree <path>] [--cooldown-minutes <N>] [--require-receipt]
#   ./fmix hook install [--worktree <path>]
#   ./fmix runner <submit|status|logs|cancel|list|receipt|install-hooks|gc-worktree>
#

set -uo pipefail

# ---------------------------------------------------------------------------
# Constants & config
# ---------------------------------------------------------------------------
FMIX_VERSION="2.7.23"
FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
FMIX_OS="$(uname -s)"
FMIX_ARCH="$(uname -m)"
FMIX_SESSION_SCHEMA="1"
FMIX_TEMPLATE_SCHEMA="1"
FMIX_CONFIG_HOME="${FMIX_CONFIG_HOME:-${XDG_CONFIG_HOME:-${HOME}/.config}/calltelemetry}"
FMIX_LOCK_TIMEOUT="${FMIX_LOCK_TIMEOUT:-900}"   # 15 min template build wait
FMIX_INFRA_PROJECT="${FMIX_INFRA_PROJECT:-ct-infra}"
FMIX_INFRA_SCHEMA="1"
FMIX_ENSURE="${FMIX_ENSURE:-1}"
FMIX_ENSURE_TIMEOUT="${FMIX_ENSURE_TIMEOUT:-90}"

# Run-observability / telemetry state (restored with the subsystem).
FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_MAX_S="10"
FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S="${FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S:-2}"
FMIX_RESOURCE_SAMPLE_MAX_SAMPLES="${FMIX_RESOURCE_SAMPLE_MAX_SAMPLES:-14400}"
FMIX_RESOURCE_SAMPLE_MAX_SAMPLES_LIMIT="86400"
FMIX_RUN_CACHE_HOT="no"
FMIX_RUN_HOT_PATH="no"
FMIX_RUN_OBSERVABILITY_DEGRADED=0
FMIX_RUN_OBSERVABILITY_DIR=""
FMIX_RUN_OBSERVABILITY_ENABLED=0
FMIX_RUN_OBSERVABILITY_FINISHED=0
FMIX_RUN_OBSERVABILITY_LAUNCHER_PID=""
FMIX_RUN_OBSERVABILITY_PHASE="session"
FMIX_RUN_OBSERVABILITY_SAMPLER_PID=""
FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT="14400"
FMIX_RUN_OVERHEAD_S="0"
FMIX_RUN_TOTAL_S="0"
FMIX_TELEMETRY_TTL_HOURS="${FMIX_TELEMETRY_TTL_HOURS:-4}"
FMIX_TELEMETRY_TTL_MAX_HOURS="8760"
FMIX_LOCK_INIT_GRACE="${FMIX_LOCK_INIT_GRACE:-5}"
FMIX_LOCK_METADATA_TTL_DAYS="${FMIX_LOCK_METADATA_TTL_DAYS:-7}"
FMIX_WORKTREE_LOCK_TIMEOUT="${FMIX_WORKTREE_LOCK_TIMEOUT:-360}"
# Session overlays are large (roughly 0.5 GiB each), so four hours is the
# retention default for both automatic housekeeping and explicit GC. Preserve
# the day-based variables as compatibility fallbacks for existing operator
# config, but leave the modern overrides unset when they were not supplied so
# command-scoped legacy overrides continue to work.
FMIX_SESSION_TTL_DEFAULT="1"
FMIX_SESSION_TTL_DAYS="${FMIX_SESSION_TTL_DAYS-}"
FMIX_SESSION_TTL_HOURS="${FMIX_SESSION_TTL_HOURS-}"
FMIX_SESSION_TTL_DEFAULT_HOURS="4"
FMIX_SESSION_WARN_THRESHOLD="${FMIX_SESSION_WARN_THRESHOLD:-24}"
FMIX_COPY_MODE="${FMIX_COPY_MODE:-}"            # override: "full" to skip CoW
FMIX_HOST_TEST_LOCK="${FMIX_HOST_TEST_LOCK:-1}"  # default: serialize only CREATE/DROP DATABASE on this host
FMIX_HOST_LOCK_TIMEOUT="${FMIX_HOST_LOCK_TIMEOUT:-60}"
FMIX_DB_CREATE_ADMISSION="${FMIX_DB_CREATE_ADMISSION:-1}"
FMIX_DB_ADMISSION_TIMEOUT="${FMIX_DB_ADMISSION_TIMEOUT:-20}"
FMIX_DB_PRESSURE_MIN_AGE="${FMIX_DB_PRESSURE_MIN_AGE:-10}"
FMIX_DB_CREATE_TIMEOUT="${FMIX_DB_CREATE_TIMEOUT:-60}"
FMIX_DB_DROP_TIMEOUT="${FMIX_DB_DROP_TIMEOUT:-30}"
# Epoch 2 gives DB bases created before the clean-bootstrap publication gate a
# new content-addressed namespace. Their databases and index records remain
# untouched, but are no longer eligible sources because their cleanliness was
# never proved.
FMIX_DB_SCHEMA_EPOCH="2"
FMIX_STABLE_SEED_SCHEMA="1"
FMIX_STABLE_SEED_COMPAT_VERSION="v1"
FMIX_DEPENDENCY_ARTIFACT_SCHEMA="1"
FMIX_DEPENDENCY_LANE_VERSION="v1"
# REL-1244 intentionally replaces the historical 30-day *candidate* default
# with four hours. Explicit legacy day overrides still win when hours are
# absent. Neither this policy nor --yes releases artifact consumers for GC.
FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS="${FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS-}"
FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS="${FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS-}"
FMIX_TEMPLATE_TTL_HOURS="${FMIX_TEMPLATE_TTL_HOURS-}"
FMIX_ARTIFACT_TTL_DEFAULT_HOURS="4"
# Auto-expire batch bound for one preparation pass: pending retirement
# journals first, then fresh candidates, at most this many operations total.
FMIX_AUTO_EXPIRE_MAX_DEFAULT="3"
FMIX_AUTO_EXPIRE_MAX_LIMIT="10"
FMIX_MIGRATION_DELTA_LIMIT="${FMIX_MIGRATION_DELTA_LIMIT:-50}"
FMIX_COMPILE_HEARTBEAT="${FMIX_COMPILE_HEARTBEAT:-30}"
FMIX_COMPILE_TIMEOUT="${FMIX_COMPILE_TIMEOUT:-900}"
# An explicit setup is a deliberate cold build. Its no-output stall budget
# cancels only a compiler that has stopped producing output; the absolute
# ceiling is a last-resort bound against a wedged process, not a progress
# estimate. The 900s normal-compile cap never applies to setup.
FMIX_SETUP_COMPILE_TIMEOUT="${FMIX_SETUP_COMPILE_TIMEOUT:-7200}"
FMIX_SETUP_COMPILE_STALL_TIMEOUT="${FMIX_SETUP_COMPILE_STALL_TIMEOUT:-600}"
FMIX_DEPS_HEARTBEAT="${FMIX_DEPS_HEARTBEAT:-15}"
FMIX_DEPS_STALL_TIMEOUT="${FMIX_DEPS_STALL_TIMEOUT:-120}"
FMIX_DEPS_TIMEOUT="${FMIX_DEPS_TIMEOUT:-600}"
FMIX_ENV_FILE="${FMIX_ENV_FILE:-}"
FMIX_HEX_HOME="$FMIX_HOME/hex"
FMIX_MIGRATION_TIMEOUT="${FMIX_MIGRATION_TIMEOUT:-120}"
# Full from-scratch migration chain (API-2846 migrate-from-zero lane) is
# orders of magnitude longer than the bounded hot-lane delta replay above —
# it is expected to run once per machine per schema, not per agent, so a
# generous default is appropriate. Override for slower hosts.
FMIX_MIGRATE_FROM_ZERO_TIMEOUT="${FMIX_MIGRATE_FROM_ZERO_TIMEOUT:-1800}"
FMIX_STRUCTURE_LOAD_TIMEOUT="${FMIX_STRUCTURE_LOAD_TIMEOUT:-120}"
FMIX_STRUCTURE_LOAD_HEARTBEAT="${FMIX_STRUCTURE_LOAD_HEARTBEAT:-30}"

# Kernel locks are held by dedicated Python keeper processes. The FMix shell
# never owns the lock descriptor, so compiler children and detached daemons
# cannot inherit lock ownership. Indexed arrays keep this compatible with the
# Bash 3.2 shipped by older macOS hosts; associative arrays and `flock(1)` are
# intentionally not required.
FMIX_HELD_LOCK_NAMES=()
FMIX_HELD_LOCK_KEEPER_PIDS=()
FMIX_HELD_LOCK_TOKENS=()
# Parallel to FMIX_HELD_LOCK_NAMES: "exclusive" (default) or "shared" (read).
FMIX_HELD_LOCK_MODES=()
# Parallel to FMIX_HELD_LOCK_NAMES: 1 when this process published the
# directory-shaped legacy metadata record, 0 for a shared joiner that left
# the publisher's record untouched.
FMIX_HELD_LOCK_PUBLISHED=()
# Set by fmix_lock_mutate_gate when it escalated a shared hold and the caller
# must re-verify its warm decision before mutating (retry-once protocol).
FMIX_LOCK_GATE_RETRY=""
FMIX_LAST_LOCK_KEEPER_PID=""
FMIX_LOCK_STOP_PROBE_PIDS=()
FMIX_PENDING_LOCK_KEEPER_PID=""
FMIX_PENDING_LOCK_KEEPER_STATE=""

# Set by fmix_activate_session before any mutable artifact, stamp, or scratch
# database path is resolved.
FMIX_ACTIVE_SESSION_HASH=""
FMIX_ACTIVE_SESSION_ROOT=""
FMIX_ACTIVE_SESSION_SOURCE=""

# Shared-infra endpoints for a NATIVE host run. CRITICAL: do NOT inherit ambient
# DB_HOSTNAME/DB_PORT. ct-local-dev exports the shared infra as DOCKER-INTERNAL
# names (CT_SHARED_DB_HOST=host.docker.internal, CT_NATS_HOST=…) for containers;
# those do NOT resolve on the host (Postgrex :nxdomain). The host-side equivalent
# of the published port is ALWAYS localhost. Only an explicit FMIX_* override
# changes it (for genuinely remote infra).
DB_HOST="${FMIX_DB_HOST:-localhost}"
DB_PORT="${FMIX_DB_PORT:-5432}"
DB_USER="${FMIX_DB_USER:-calltelemetry}"
DB_PASSWORD="${FMIX_DB_PASSWORD:-calltelemetry_dev_password}"
NATS_PORT="${FMIX_NATS_PORT:-4222}"
FMIX_TAILNET_NATS_HOST="${FMIX_TAILNET_NATS_HOST:-nats-dev}"
# Upper bound, in seconds, for each JetStream round trip in the NATS probe.
FMIX_NATS_PROBE_TIMEOUT="${FMIX_NATS_PROBE_TIMEOUT:-3}"

# Bounded JetStream health probe. A TCP connect proves only that something
# listens on the port; a remote can accept TCP and still time out on JetStream,
# which is what breaks app boot (KV bucket creation). The probe speaks just
# enough NATS protocol to send two JetStream API requests on one inbox:
#   $JS.API.INFO                      the JetStream control plane answers
#   $JS.API.STREAM.INFO.KV_<probe>    the KV stream namespace answers
# A "stream not found" (err_code 10059) reply still proves the KV namespace
# answered; the bucket need not exist. Any silence past the bound is a failure.
# Usage: fmix_nats_jetstream_probe HOST PORT
# Sets FMIX_NATS_PROBE_DETAIL to "<ms>ms" on success or a reason on failure.
# Returns 0 when healthy, 1 otherwise.
fmix_nats_jetstream_probe() {
    local host="$1" port="$2" py
    FMIX_NATS_PROBE_DETAIL=""
    py="$(command -v python3 2>/dev/null || true)"
    [[ -n "$py" ]] || py="/usr/bin/python3"
    if [[ ! -x "$py" ]]; then
        FMIX_NATS_PROBE_DETAIL="no python3 available for the JetStream probe"
        return 1
    fi
    local out
    out="$("$py" -I -B - "$host" "$port" "$FMIX_NATS_PROBE_TIMEOUT" 2>/dev/null <<'FMIX_NATS_PROBE_PY'
import socket, sys, time, uuid, json

host, port, bound = sys.argv[1], int(sys.argv[2]), float(sys.argv[3])
started = time.monotonic()
deadline = started + bound


def fail(reason):
    print("fail " + reason)
    sys.exit(1)


def remaining():
    left = deadline - time.monotonic()
    if left <= 0:
        fail("no JetStream answer within %gs" % bound)
    return left


try:
    sock = socket.create_connection((host, port), timeout=remaining())
except socket.timeout:
    fail("tcp connect timed out")
except OSError as exc:
    fail("tcp connect failed (%s)" % (exc.strerror or type(exc).__name__))

buf = bytearray()


def fill(size):
    while len(buf) < size:
        sock.settimeout(remaining())
        try:
            chunk = sock.recv(65536)
        except socket.timeout:
            fail("no JetStream answer within %gs" % bound)
        if not chunk:
            fail("connection closed by server")
        buf.extend(chunk)


def readline():
    while b"\r\n" not in buf:
        fill(len(buf) + 1)
    line, _, rest = bytes(buf).partition(b"\r\n")
    buf[:] = rest
    return line


def readn(count):
    fill(count + 2)
    data = bytes(buf[:count])
    del buf[: count + 2]
    return data


try:
    if not readline().startswith(b"INFO "):
        fail("peer did not speak the NATS protocol")
    sock.sendall(b'CONNECT {"verbose":false,"pedantic":false,"headers":true,'
                 b'"no_responders":true,"protocol":1,"lang":"python",'
                 b'"version":"fmix-probe"}\r\nPING\r\n')
    while True:
        line = readline()
        if line == b"PONG":
            break
        if line.startswith(b"-ERR"):
            fail("server error " + line[4:].strip().decode("utf-8", "replace")[:120])
        if line == b"PING":
            sock.sendall(b"PONG\r\n")

    inbox = ("_INBOX.fmixprobe." + uuid.uuid4().hex).encode()
    sock.sendall(b"SUB " + inbox + b" 1\r\n")

    def request(subject):
        sock.sendall(b"PUB " + subject + b" " + inbox + b" 0\r\n\r\n")
        while True:
            line = readline()
            if line == b"PING":
                sock.sendall(b"PONG\r\n")
            elif line.startswith(b"-ERR"):
                fail("server error " + line[4:].strip().decode("utf-8", "replace")[:120])
            elif line.startswith(b"MSG "):
                return json.loads(readn(int(line.split()[-1])).decode("utf-8", "replace"))
            elif line.startswith(b"HMSG "):
                parts = line.split()
                header_len, total_len = int(parts[-2]), int(parts[-1])
                header = readn(total_len)[:header_len]
                if b" 503" in header.split(b"\r\n", 1)[0]:
                    fail("no JetStream responders (503): JetStream is not enabled")
            # +OK, INFO and other frames are ignored.

    info = request(b"$JS.API.INFO")
    if "error" in info:
        fail("JetStream API error: " + str(info["error"].get("description", "unknown"))[:120])

    kv = request(b"$JS.API.STREAM.INFO.KV_fmix-probe")
    kv_error = kv.get("error") or {}
    if "error" in kv and kv_error.get("err_code") != 10059:
        fail("KV namespace error: " + str(kv_error.get("description", "unknown"))[:120])
except socket.timeout:
    fail("no JetStream answer within %gs" % bound)
except (OSError, ValueError) as exc:
    fail("protocol error (%s)" % type(exc).__name__)

print("ok %dms" % int((time.monotonic() - started) * 1000))
FMIX_NATS_PROBE_PY
)" || true
    if [[ "$out" == ok\ * ]]; then
        FMIX_NATS_PROBE_DETAIL="${out#ok }"
        return 0
    fi
    FMIX_NATS_PROBE_DETAIL="${out#fail }"
    [[ -n "$FMIX_NATS_PROBE_DETAIL" ]] || FMIX_NATS_PROBE_DETAIL="probe produced no result"
    return 1
}

# Resolves NATS_HOST and records why in FMIX_NATS_HOST_REASON. Runs in the
# current shell (not a subshell) so the reason survives for the doctor.
#   1. An explicit FMIX_NATS_HOST always wins and is never probed.
#   2. CI, or FMIX_DISABLE_TAILNET_NATS=1, selects localhost without probing.
#   3. Otherwise the tailnet host must pass the JetStream probe.
#   4. If it fails or exceeds the bound, a local NATS that passes the same
#      probe is preferred. If neither passes, localhost remains the default so
#      the doctor reports the real state rather than a silent switch.
fmix_resolve_nats_host() {
    if [[ "${FMIX_NATS_HOST+set}" == "set" ]]; then
        NATS_HOST="$FMIX_NATS_HOST"
        FMIX_NATS_HOST_REASON="explicit FMIX_NATS_HOST override (not probed)"
        return 0
    fi
    if [[ "${GITHUB_ACTIONS:-}" == "true" || "${CI:-}" == "true" || "${FMIX_DISABLE_TAILNET_NATS:-}" == "1" ]]; then
        NATS_HOST="localhost"
        FMIX_NATS_HOST_REASON="CI or FMIX_DISABLE_TAILNET_NATS: localhost, tailnet not probed"
        return 0
    fi
    if fmix_nats_jetstream_probe "$FMIX_TAILNET_NATS_HOST" "$NATS_PORT"; then
        NATS_HOST="$FMIX_TAILNET_NATS_HOST"
        FMIX_NATS_HOST_REASON="tailnet $FMIX_TAILNET_NATS_HOST JetStream healthy ($FMIX_NATS_PROBE_DETAIL)"
        return 0
    fi
    local remote_detail="$FMIX_NATS_PROBE_DETAIL"
    if fmix_nats_jetstream_probe localhost "$NATS_PORT"; then
        NATS_HOST="localhost"
        FMIX_NATS_HOST_REASON="tailnet $FMIX_TAILNET_NATS_HOST unhealthy ($remote_detail); local localhost JetStream healthy ($FMIX_NATS_PROBE_DETAIL)"
        printf '[fmix] NATS: using localhost:%s; %s\n' "$NATS_PORT" "$FMIX_NATS_HOST_REASON" >&2
        return 0
    fi
    NATS_HOST="localhost"
    FMIX_NATS_HOST_REASON="tailnet $FMIX_TAILNET_NATS_HOST unhealthy ($remote_detail); local localhost also unhealthy ($FMIX_NATS_PROBE_DETAIL); defaulting to localhost"
    return 0
}
fmix_resolve_nats_host

# Fixed dev constant SECRET_KEY_BASE (64 hex chars — only used in test env)
SECRET_KEY_BASE="${FMIX_SECRET_KEY_BASE:-dev0000000000000000000000000000000000000000000000000000000000000001}"

# ---------------------------------------------------------------------------
# OS dispatch helpers — ALL OS-specific calls go through these functions.
# No inline uname checks outside this block.
# ---------------------------------------------------------------------------

fmix_realpath() {
    # Portable realpath: prefer system binary, fall back to python3
    if command -v realpath >/dev/null 2>&1; then
        realpath "$1"
    elif command -v /usr/bin/python3 >/dev/null 2>&1; then
        /usr/bin/python3 -I -B -c "import os, sys; print(os.path.realpath(sys.argv[1]))" "$1"
    elif command -v python3 >/dev/null 2>&1; then
        python3 -I -B -c "import os, sys; print(os.path.realpath(sys.argv[1]))" "$1"
    else
        # Last resort: resolve an existing directory through cd so the final
        # path component is canonical too. For files or non-existent paths,
        # preserve the historical parent-only behavior.
        local base dir
        if [[ -d "$1" ]]; then
            (cd "$1" && pwd -P)
            return
        fi
        base="$(basename "$1")"
        dir="$(dirname "$1")"
        echo "$(cd "$dir" && pwd -P)/$base"
    fi
}

fmix_prepare_home() {
    # macOS exposes /tmp through the /private/tmp symlink. Keep every FMix
    # artifact path in one canonical namespace before Mix computes relative
    # links between MIX_BUILD_PATH and MIX_DEPS_PATH; mixing the logical and
    # canonical prefixes produces links that resolve under /private/private/tmp.
    mkdir -p "$FMIX_HOME" || {
        fmix_error "Could not create FMIX_HOME: $FMIX_HOME"
        return 1
    }
    FMIX_HOME="$(fmix_realpath "$FMIX_HOME")" || return 1
    FMIX_HEX_HOME="$FMIX_HOME/hex"
    export FMIX_HOME
}

fmix_prepare_command_home() {
    fmix_prepare_home || return 1
    mkdir -p "$FMIX_HOME"/{templates,template-access,dependency-artifacts,dependency-artifact-access,sessions,worktrees,db-index,compile-stamps,dependency-stamps,locks,lock-kernel,lock-metadata,logs,quarantine} \
        || return 1
    fmix_prepare_session_state_root || return 1
    chmod 0700 "$FMIX_HOME" 2>/dev/null || true
}

fmix_prepare_home_readonly() {
    # Cache explain/verify are read-only. Canonicalize an existing home so the
    # same path-safety comparisons apply through aliases, but never create a
    # missing cache root as a side effect of inspection.
    if [[ ! -e "$FMIX_HOME" ]]; then
        if [[ -L "$FMIX_HOME" ]]; then
            fmix_error "FMIX_HOME is a dangling symlink: $FMIX_HOME"
            return 1
        fi
        return 0
    fi
    if [[ ! -d "$FMIX_HOME" ]]; then
        fmix_error "FMIX_HOME is not a directory: $FMIX_HOME"
        return 1
    fi
    FMIX_HOME="$(fmix_realpath "$FMIX_HOME")" || return 1
    FMIX_HEX_HOME="$FMIX_HOME/hex"
    export FMIX_HOME
}

fmix_real_directory_is_safe() {
    local path="$1"
    [[ -d "$path" && ! -L "$path" ]] || return 1
}

fmix_ensure_real_directory() {
    local path="$1"
    if [[ -e "$path" || -L "$path" ]]; then
        fmix_real_directory_is_safe "$path" || {
            fmix_error "FMix state path must be a real directory: $path"
            return 1
        }
        return 0
    fi
    # Another session may create the same structural ancestor after our
    # existence check. Treat that as success only after validating the winner;
    # all other creation failures still fail closed.
    if ! mkdir "$path" 2>/dev/null; then
        fmix_real_directory_is_safe "$path" || {
            fmix_error "Could not create FMix state directory: $path"
            return 1
        }
    fi
    fmix_real_directory_is_safe "$path" || {
        fmix_error "FMix state directory failed post-create validation: $path"
        return 1
    }
}

fmix_prepare_session_state_root() {
    fmix_real_directory_is_safe "$FMIX_HOME" || {
        fmix_error "FMIX_HOME must resolve to a real directory before session setup: $FMIX_HOME"
        return 1
    }
    fmix_ensure_real_directory "$FMIX_HOME/sessions" || return 1
    fmix_ensure_real_directory "$FMIX_HOME/sessions/v1"
}

fmix_create_session_root() {
    local host_hash="$1" session_hash="$2" worktree_hash="$3"
    local path="$FMIX_HOME/sessions/v1" component
    fmix_prepare_session_state_root || return 1
    for component in "$host_hash" "$session_hash" "$worktree_hash"; do
        path="$path/$component"
        fmix_ensure_real_directory "$path" || return 1
    done
    printf '%s\n' "$path"
}

fmix_python_bin() {
    if command -v /usr/bin/python3 >/dev/null 2>&1; then
        printf '/usr/bin/python3\n'
    else
        printf 'python3\n'
    fi
}

fmix_run_early_supervisor() {
    local py_bin bootstrap
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    IFS= read -r -d '' bootstrap <<'FMIX_EARLY_PY'
import os
import sys

runner = os.path.realpath(sys.argv[1])
arguments = sys.argv[2:]
try:
    with open(runner, "rb") as source_file:
        source = source_file.read(4 * 1024 * 1024 + 1)
except OSError:
    raise SystemExit(125)
if len(source) > 4 * 1024 * 1024:
    raise SystemExit(125)
start_marker = b"fmix_observability_supervisor_source() {\n    command cat <<'PY'\n"
end_marker = b"\nPY\n}\n\nfmix_run_embedded_supervisor()"
start = source.find(start_marker)
if start < 0 or source.find(start_marker, start + 1) >= 0:
    raise SystemExit(125)
start += len(start_marker)
end = source.find(end_marker, start)
if end < 0 or source.find(end_marker, end + 1) >= 0:
    raise SystemExit(125)
supervisor_source = source[start:end].decode("utf-8")
sys.argv = ["-c", runner, *arguments]
exec(compile(supervisor_source, runner + "::<observability-supervisor>", "exec"))
FMIX_EARLY_PY
    true
    FMIX_VERSION="$FMIX_VERSION" exec "$py_bin" -c "$bootstrap" "$0" "$@"
}

fmix_timing_help_requested() {
    # Mirror the timing parser's option arity. A value or forwarded argument
    # named --help must never become a side-effect-free help request.
    while (( $# > 0 )); do
        case "$1" in
            --json|--limit=*|--worktree=*) shift ;;
            --limit|--worktree) (( $# >= 2 )) || return 1; shift 2 ;;
            --help|-h) return 0 ;;
            *) return 1 ;;
        esac
    done
    return 1
}

fmix_readonly_entrypoint() {
    local arg
    case "${1:-}" in
        ""|help|--help|-h|version|--version|analyze) return 0 ;;
        timing)
            shift
            fmix_timing_help_requested "$@"
            return $? ;;
        gc)
            for arg in "$@"; do
                [[ "$arg" == "--artifacts-only" ]] && return 0
            done
            ;;
    esac
    case "${1:-}" in
        test|coverage|task|format|setup|seed|cache|ensure|doctor|status|timing|gc|install|self-test)
            [[ "${2:-}" == "--help" || "${2:-}" == "-h" ]] && return 0
            ;;
        verify-push|hook)
            [[ "${2:-}" == "--help" || "${2:-}" == "-h" ]] && return 0
            ;;
    esac
    return 1
}

if ! fmix_readonly_entrypoint "$@" && [[ "${BASH_SOURCE[0]}" == "$0" \
    && "${FMIX_OBSERVABILITY_WORKER:-0}" != "1" \
    && "${1:-}" != "--fmix-observability-worker" \
    && "${FMIX_RUN_ID:-}" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then
    fmix_run_early_supervisor "$@"
    exit $?
fi

fmix_stat_mtime() {
    # Returns seconds-since-epoch mtime for a file.  Portable BSD/GNU.
    local f="$1"
    if [[ "$FMIX_OS" == "Darwin" ]]; then
        stat -f '%m' "$f"
    else
        stat -c '%Y' "$f"
    fi
}

fmix_stat_device() {
    # Device id containing a path. Portable BSD/GNU.
    local f="$1"
    if [[ "$FMIX_OS" == "Darwin" ]]; then
        stat -f '%d' "$f"
    else
        stat -c '%d' "$f"
    fi
}

fmix_stat_identity() {
    # Identity stamp for lock-free CAS reads: the retirement engine's
    # identity() audit fields (device, inode, uid, mode, mtime, ctime) as one
    # comparable line. Fails on a missing or non-regular path.
    local f="$1"
    [[ -f "$f" && ! -L "$f" ]] || return 1
    if [[ "$FMIX_OS" == "Darwin" ]]; then
        stat -f '%d:%i:%u:%Lp:%m:%c' "$f"
    else
        stat -c '%d:%i:%u:%a:%Y:%Z' "$f"
    fi
}

fmix_cow_clone() {
    # CoW clone source_dir → dest_dir (dest must NOT exist).
    # Returns 0 on success, non-zero on failure.
    local src="$1" dst="$2"
    if [[ "$FMIX_COPY_MODE" == "full" ]]; then
        _fmix_full_copy "$src" "$dst"
        return $?
    fi
    if [[ "$FMIX_OS" == "Darwin" ]]; then
        # APFS clonefile via cp -c; fails loud on cross-volume (EXDEV)
        if cp -c -R "$src" "$dst" 2>/tmp/fmix_cow_err_$$; then
            return 0
        else
            local err
            err="$(cat /tmp/fmix_cow_err_$$)"
            rm -f /tmp/fmix_cow_err_$$
            if echo "$err" | grep -q "EXDEV\|cross-device"; then
                fmix_error "CoW clone failed: source ($src) and destination ($dst) are on different volumes.\nSet FMIX_COPY_MODE=full to use a slower full copy instead."
            else
                fmix_error "CoW clone failed: $err"
            fi
            return 1
        fi
    else
        # Linux: --reflink=auto (CoW on btrfs/XFS; silent full copy on ext4)
        local t0 t1
        t0=$(date +%s)
        if cp -R --reflink=auto "$src" "$dst" 2>/tmp/fmix_cow_err_$$; then
            t1=$(date +%s)
            local elapsed=$(( t1 - t0 ))
            if (( elapsed > 10 )); then
                echo "  [fmix] note: clone took ${elapsed}s — likely a full copy on non-CoW filesystem (normal on ext4)" >&2
            fi
            return 0
        else
            local err
            err="$(cat /tmp/fmix_cow_err_$$)"
            rm -f /tmp/fmix_cow_err_$$
            fmix_error "Clone failed: $err"
            return 1
        fi
    fi
    rm -f /tmp/fmix_cow_err_$$
}

_fmix_full_copy() {
    local src="$1" dst="$2"
    local t0 t1 copy_rc=0
    t0=$(date +%s)
    cp -R "$src" "$dst" || copy_rc=$?
    t1=$(date +%s)
    if (( copy_rc == 0 )); then
        echo "  [fmix] full copy completed in $(( t1 - t0 ))s (FMIX_COPY_MODE=full)" >&2
    else
        fmix_error "Full copy failed (rc=$copy_rc); destination is not a proven clone."
    fi
    return "$copy_rc"
}

fmix_heal_cmake_nif_caches() {
    # CMake-based NIFs (e.g. :crc32cer) bake an ABSOLUTE build path into
    # deps/<dep>/c_build/CMakeCache.txt. fmix CoW-clones deps/ across absolute
    # paths (worktree <-> template, and between separate ai-workspace checkouts),
    # so that cache goes stale and the next `mix compile` dies with
    # "current CMakeCache.txt directory is different than the directory ...".
    # Heal-before-compile: drop any c_build whose recorded build dir != its own
    # current path so cmake regenerates it here (a cheap NIF recompile). No-op
    # when the cache already matches, so warm builds pay nothing.
    local deps_dir="$1"
    [[ -d "$deps_dir" ]] || return 0
    local cache dep_dir recorded healed=0
    for cache in "$deps_dir"/*/c_build/CMakeCache.txt; do
        [[ -f "$cache" ]] || continue
        dep_dir="$(cd "$(dirname "$(dirname "$cache")")" && pwd)"
        recorded="$(sed -n 's/^# For build in directory: //p' "$cache" | head -1)"
        if [[ "$recorded" != "${dep_dir}/c_build" ]]; then
            rm -rf "${dep_dir}/c_build"
            healed=$(( healed + 1 ))
        fi
    done
    (( healed > 0 )) && fmix_info "Healed $healed stale CMake NIF cache(s) (path drift) in ${deps_dir}."
    return 0
}

fmix_heal_toolchain_stale_nifs() {
    # Native deps (e.g. :sippet) compile a NIF from c_src via elixir_make. Make
    # only rebuilds when SOURCES are newer than objects, so switching the
    # toolchain -- a different OTP in .tool-versions -- leaves the previously
    # built .o/.so in place and the BEAM keeps loading a NIF built against the
    # OLD ERTS. `mix deps.compile <dep> --force` does not help: it re-runs make,
    # which still considers the objects up to date.
    #
    # The symptom is silent and expensive: sippet's typed header parsers went
    # dead, changing parsed SIP header shapes, and an OTP A/B measured the wrong
    # binary entirely (cisco-cdr API-3051).
    #
    # Stamp the ABI that produced the native artifacts and drop them whenever it
    # changes. Warm runs on an unchanged toolchain pay a single string compare.
    local deps_dir="$1"
    [[ -d "$deps_dir" ]] || return 0

    local abi stamp previous
    abi="$(printf '%s' "${FMIX_TOOLCHAIN_IDENTITY:-}" | tr '\n' ' ')"
    [[ -n "${abi// /}" ]] || return 0
    stamp="${deps_dir}/.fmix-native-abi"

    previous=""
    [[ -f "$stamp" ]] && previous="$(cat "$stamp" 2>/dev/null)"

    if [[ "$previous" == "$abi" ]]; then
        return 0
    fi

    local purged=0 artifact
    while IFS= read -r artifact; do
        [[ -e "$artifact" ]] || continue
        rm -rf "$artifact"
        purged=$(( purged + 1 ))
    done < <(
        find "$deps_dir" -mindepth 2 -maxdepth 3 \
            \( -name '*.so' -o -name '*.o' -o -name '*.a' -o -name 'c_build' \) \
            2>/dev/null
    )

    printf '%s' "$abi" > "$stamp" 2>/dev/null || true

    if (( purged > 0 )); then
        if [[ -n "$previous" ]]; then
            fmix_info "Toolchain ABI changed; purged $purged stale native artifact(s) so NIFs rebuild against the active ERTS."
        else
            fmix_info "Recording native ABI stamp; purged $purged unstamped native artifact(s) in ${deps_dir}."
        fi
    fi
    return 0
}

fmix_native_deps_missing_so() {
    # Read-only. Print (one per line) every elixir_make dependency that ships
    # c_src + a Makefile but has no built NIF (.so/.dylib/.dll) anywhere under
    # its priv/. Such a dep leaves `on_load` failing at runtime (for example
    # "module Sippet.Parser is not available") while Mix still believes the dep
    # is compiled. Deps already proven to build no priv library carry a
    # .fmix-no-native-so sentinel and are skipped so a false positive costs
    # one rebuild attempt, not one per run.
    local deps_root="${1:-}" dep_dir
    [[ -d "$deps_root" ]] || return 0
    for dep_dir in "$deps_root"/*/; do
        dep_dir="${dep_dir%/}"
        [[ -d "$dep_dir/c_src" ]] || continue
        [[ -f "$dep_dir/Makefile" || -f "$dep_dir/c_src/Makefile" ]] || continue
        [[ -f "$dep_dir/mix.exs" ]] && grep -q elixir_make "$dep_dir/mix.exs" 2>/dev/null \
            || continue
        [[ -e "$dep_dir/.fmix-no-native-so" ]] && continue
        if [[ -d "$dep_dir/priv" ]] \
            && [[ -n "$(find -L "$dep_dir/priv" \( -name '*.so' -o -name '*.dylib' -o -name '*.dll' \) \
                -print -quit 2>/dev/null)" ]]; then
            continue
        fi
        basename "$dep_dir"
    done
}

fmix_repair_missing_native_deps() {
    # Post-install / post-heal verification: every native dep must have its NIF.
    # fmix_heal_toolchain_stale_nifs deletes .so/.o/c_build but Mix does not
    # re-run a dependency it already considers compiled, and donor clones /
    # dependency artifacts can carry a purged tree. Force `mix deps.compile
    # <dep> --force` for exactly the deps that lack their priv library; make
    # then rebuilds them because the objects are gone. Best-effort: failures
    # warn and the normal compile/test path surfaces the real error.
    local worktree="${1:-}" deps_root dep
    local -a missing=() build_env=()
    [[ -n "$worktree" ]] || return 0
    deps_root="$(fmix_session_deps_root "$worktree")" || return 0
    [[ -d "$deps_root" ]] || return 0
    while IFS= read -r dep; do
        [[ -n "$dep" ]] && missing+=("$dep")
    done < <(fmix_native_deps_missing_so "$deps_root")
    (( ${#missing[@]} > 0 )) || return 0

    fmix_warn "Native dependencies missing their NIF library: ${missing[*]}; rebuilding with mix deps.compile --force."
    [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
    [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
    if ! (
        cd "$worktree" || exit 1
        exec env \
            "${build_env[@]+"${build_env[@]}"}" \
            MIX_ENV=test \
            MEESEEKS_HTML5EVER_BUILD=0 \
            mix deps.compile "${missing[@]}" --force
    ); then
        fmix_warn "mix deps.compile --force failed for: ${missing[*]}"
    fi
    while IFS= read -r dep; do
        [[ -n "$dep" ]] || continue
        fmix_warn "Dependency $dep still has no priv NIF library after rebuild; assuming it builds none."
        : >"$deps_root/$dep/.fmix-no-native-so" 2>/dev/null || true
    done < <(fmix_native_deps_missing_so "$deps_root")
    return 0
}

fmix_psql() {
    # Portable psql: prefer local binary, fall back to docker exec
    # Sets PGPASSWORD for the call.
    if command -v psql >/dev/null 2>&1; then
        PGPASSWORD="$DB_PASSWORD" psql "$@"
    elif [[ "$FMIX_OS" == "Darwin" ]] && [[ -x /opt/homebrew/bin/psql ]]; then
        PGPASSWORD="$DB_PASSWORD" /opt/homebrew/bin/psql "$@"
    elif command -v docker >/dev/null 2>&1; then
        # Try docker exec fallback
        local container
        container="$(docker ps --format '{{.Names}}' 2>/dev/null | grep -E 'postgres|infra' | head -1)"
        if [[ -n "$container" ]]; then
            docker exec -i \
                -e PGPASSWORD="$DB_PASSWORD" \
                -e PGCONNECT_TIMEOUT="${PGCONNECT_TIMEOUT:-}" \
                -e PGOPTIONS="${PGOPTIONS:-}" \
                -e PGAPPNAME="${PGAPPNAME:-}" \
                "$container" psql "$@"
        else
            return 1
        fi
    else
        return 1
    fi
}

fmix_find_psql() {
    # Detect psql binary path, for reporting in doctor/self-test
    if command -v psql >/dev/null 2>&1; then
        command -v psql
    elif [[ "$FMIX_OS" == "Darwin" ]] && [[ -x /opt/homebrew/bin/psql ]]; then
        echo "/opt/homebrew/bin/psql"
    elif command -v docker >/dev/null 2>&1; then
        local container
        container="$(docker ps --format '{{.Names}}' 2>/dev/null | grep -E 'postgres|infra' | head -1)"
        if [[ -n "$container" ]]; then
            echo "docker:$container"
        else
            echo ""
        fi
    else
        echo ""
    fi
}

# ---------------------------------------------------------------------------
# Utility helpers
# ---------------------------------------------------------------------------

fmix_error() {
    echo "  [fmix ERROR] $*" >&2
}

fmix_prepend_toolchain_paths() {
    # Prefer the repo-aware asdf shims over ambient host managers. Keep the
    # caller's PATH as a final fallback for hosts whose active runtime is
    # already exact (for example a CI setup-beam install). Do not reorder
    # unrelated host tools: test/CI shims for git, psql, and other commands
    # must retain their caller-selected precedence.
    local entry remaining=""
    local -a path_entries=()
    IFS=':' read -r -a path_entries <<<"$PATH"
    for entry in "${path_entries[@]}"; do
        case "$entry" in
            "$HOME/.asdf/shims"|"$HOME/.asdf/bin") continue ;;
        esac
        if [[ -n "$remaining" ]]; then
            remaining="$remaining:$entry"
        else
            remaining="$entry"
        fi
    done
    PATH="$HOME/.asdf/shims:$HOME/.asdf/bin${remaining:+:$remaining}"
    export PATH
}

fmix_resolved_toolchain_identity() {
    # Print a stable ABI identity only when the ACTIVE executables exactly
    # match the cisco-cdr checkout's .tool-versions. Merely hashing that file is
    # insufficient: an ambient Mise/asdf/global shim can run a different ERTS
    # while writing into the same deps/ and _build/ directories.
    local worktree="$1"
    local versions="$worktree/.tool-versions"
    local wanted_otp wanted_elixir wanted_elixir_base wanted_compiled_otp
    local actual_otp_major actual_otp actual_erts actual_elixir actual_compiled_otp actual_mix
    local otp_root otp_version_file

    [[ -r "$versions" ]] || {
        fmix_error "Missing readable toolchain source of truth: $versions"
        return 1
    }
    wanted_otp="$(awk '$1 == "erlang" {print $2; exit}' "$versions")"
    wanted_elixir="$(awk '$1 == "elixir" {print $2; exit}' "$versions")"
    [[ "$wanted_otp" =~ ^[0-9]+\.[0-9]+([.][0-9]+)*$ ]] || {
        fmix_error ".tool-versions missing erlang or elixir pin: .tool-versions must pin a full Erlang/OTP version (got '${wanted_otp:-missing}')."
        return 1
    }
    [[ "$wanted_elixir" =~ ^[0-9]+\.[0-9]+([.][0-9]+)*-otp-[0-9]+$ ]] || {
        fmix_error ".tool-versions must pin Elixir with an OTP suffix (got '${wanted_elixir:-missing}')."
        return 1
    }
    wanted_elixir_base="${wanted_elixir%%-otp-*}"
    wanted_compiled_otp="${wanted_elixir##*-otp-}"

    local executable
    for executable in erl elixir mix; do
        command -v "$executable" >/dev/null 2>&1 || {
            fmix_error "$executable is unavailable for $worktree. Install the versions in .tool-versions."
            return 1
        }
    done

    # ONE erl spawn, not three. Each BEAM start is a full VM boot; measured on a
    # loaded host at 1.5s / 1.8s / 0.7s here, and this function runs on every
    # compile-fingerprint computation, i.e. every warm fmix invocation.
    #
    # Fields are NEWLINE-separated, one per line. `code:root_dir()` is an
    # operator-controlled filesystem path, so any PRINTABLE delimiter could occur
    # inside it: a path containing a literal `|` would truncate otp_root, make
    # OTP_VERSION unreadable, and produce a spurious mismatch refusal. A newline
    # cannot appear in a path, so the probe is read as a stream instead of split
    # on a character.
    local erl_probe
    erl_probe="$(
        cd "$worktree" &&
            erl -noshell -eval 'io:format("~s~n~s~n~s~n", [erlang:system_info(otp_release), code:root_dir(), erlang:system_info(version)]), halt().' 2>/dev/null
    )" || erl_probe=""
    actual_otp_major=""
    otp_root=""
    actual_erts=""
    if [[ -n "$erl_probe" ]]; then
        local -a erl_fields=()
        while IFS= read -r erl_field; do
            erl_fields+=("$erl_field")
        done <<< "$erl_probe"
        if (( ${#erl_fields[@]} >= 3 )); then
            actual_otp_major="${erl_fields[0]}"
            otp_root="${erl_fields[1]}"
            actual_erts="${erl_fields[2]}"
        fi
    fi
    # A probe that did not yield three non-empty fields means the VM could not be
    # queried; fail the identity rather than compiling against an unverified
    # toolchain.
    if [[ -z "$actual_otp_major" || -z "$otp_root" || -z "$actual_erts" ]]; then
        actual_otp_major=""
        otp_root=""
        actual_erts=""
    fi
    otp_version_file="$otp_root/releases/$actual_otp_major/OTP_VERSION"
    if [[ -r "$otp_version_file" ]]; then
        actual_otp="$(tr -d '[:space:]' <"$otp_version_file")"
    else
        actual_otp=""
    fi
    actual_elixir="$(
        cd "$worktree" &&
            elixir --version 2>/dev/null | awk '$1 == "Elixir" {print $2; exit}'
    )" || actual_elixir=""
    actual_compiled_otp="$(
        cd "$worktree" &&
            elixir --version 2>/dev/null |
                sed -nE 's/.*compiled with Erlang\/OTP ([0-9]+).*/\1/p' |
                head -1
    )" || actual_compiled_otp=""
    actual_mix="$(
        cd "$worktree" &&
            mix --version 2>/dev/null | sed -nE 's/^Mix ([0-9.]+).*/\1/p' | head -1
    )" || actual_mix=""

    if [[ "$actual_otp" != "$wanted_otp" ]] ||
        [[ "$actual_otp_major" != "${wanted_otp%%.*}" ]]; then
        fmix_error "Erlang/OTP mismatch: .tool-versions requires $wanted_otp, active runtime is ${actual_otp:-unknown} (release ${actual_otp_major:-unknown})."
        fmix_error "Refusing to read or write deps/_build. Run: cd $worktree && asdf install"
        return 1
    fi
    if [[ "$actual_elixir" != "$wanted_elixir_base" ]] ||
        [[ "$actual_compiled_otp" != "$wanted_compiled_otp" ]]; then
        fmix_error "Elixir mismatch: .tool-versions requires $wanted_elixir, active runtime is ${actual_elixir:-unknown}-otp-${actual_compiled_otp:-unknown}."
        fmix_error "Refusing to read or write deps/_build. Run: cd $worktree && asdf install"
        return 1
    fi
    if [[ "$actual_mix" != "$wanted_elixir_base" ]]; then
        fmix_error "Mix mismatch: expected $wanted_elixir_base with Elixir $wanted_elixir, active Mix is ${actual_mix:-unknown}."
        fmix_error "Refusing to read or write deps/_build."
        return 1
    fi

    printf 'otp=%s\n' "$actual_otp"
    printf 'erts=%s\n' "$actual_erts"
    printf 'elixir=%s-otp-%s\n' "$actual_elixir" "$actual_compiled_otp"
    printf 'mix=%s\n' "$actual_mix"
}

fmix_activate_toolchain() {
    local worktree="$1"
    fmix_prepend_toolchain_paths
    FMIX_TOOLCHAIN_IDENTITY="$(fmix_resolved_toolchain_identity "$worktree")" || {
        FMIX_TOOLCHAIN_IDENTITY=""
        return 1
    }
    export FMIX_TOOLCHAIN_IDENTITY
    fmix_info "Toolchain verified: $(printf '%s' "$FMIX_TOOLCHAIN_IDENTITY" | tr '\n' ' ')"
}

fmix_verify_toolchain() {
    fmix_activate_toolchain "$@"
}

fmix_info() {
    echo "  [fmix] $*" >&2
}

fmix_warn() {
    echo "  [fmix WARN] $*" >&2
}

fmix_hash_stdin() {
    if command -v shasum >/dev/null 2>&1; then
        shasum -a 256 | awk '{print $1}'
    elif command -v sha256sum >/dev/null 2>&1; then
        sha256sum | awk '{print $1}'
    else
        fmix_error "No SHA-256 tool found (need shasum or sha256sum). Install one and retry."
        return 1
    fi
}

fmix_hash_string() {
    printf '%s\n' "$1" | fmix_hash_stdin
}

fmix_hash_files() {
    if [[ -n "${FMIX_STAT_HASH_CACHE:-}" ]] && (( $# > 0 )); then
        local fmix_cached_hash_output=""
        if fmix_cached_hash_output="$(fmix_stat_hash_files_cached "$@")"; then
            printf '%s\n' "$fmix_cached_hash_output"
            return 0
        fi
    fi
    if command -v shasum >/dev/null 2>&1; then
        shasum -a 256 -- "$@"
    elif command -v sha256sum >/dev/null 2>&1; then
        sha256sum -- "$@"
    else
        fmix_error "No SHA-256 tool found. Install shasum or sha256sum."
        return 1
    fi
}

# --- Stat-validated content-hash cache (warm admission) ---------------------
# A cache line records path -> dev,ino,mtime_ns,ctime_ns,size -> sha256. A
# recorded digest is reused only when the whole stat tuple is unchanged;
# ctime cannot be preserved by userspace, so every write is re-hashed even
# when mtime and size are restored. The cache is an accelerator only: any
# anomaly (odd names, symlinks, special files, stat/read errors, a corrupt
# cache) falls back to the real full-hash path for the affected call, and the
# dirty/ignored/dependency guards deliberately keep hashing live content.
fmix_stat_hash_cache_path() {
    local worktree="$1"
    printf '%s.statcache\n' "$(fmix_compile_stamp_file "$worktree")"
}

fmix_stat_hash_cache_use() {
    local worktree="${1:-}" cache
    [[ -n "$worktree" ]] || return 1
    cache="$(fmix_stat_hash_cache_path "$worktree")" || return 1
    mkdir -p "$(dirname "$cache")" || return 1
    if [[ -n "${FMIX_STAT_HASH_CACHE:-}" ]]; then
        FMIX_STAT_HASH_CACHE_REFCOUNT=$(( ${FMIX_STAT_HASH_CACHE_REFCOUNT:-0} + 1 ))
        return 0
    fi
    FMIX_STAT_HASH_CACHE="$cache"
    FMIX_STAT_HASH_CACHE_REFCOUNT=1
    export FMIX_STAT_HASH_CACHE
    return 0
}

fmix_stat_hash_cache_done() {
    local fmix_cache_count="${FMIX_STAT_HASH_CACHE_REFCOUNT:-1}"
    fmix_cache_count=$(( fmix_cache_count - 1 ))
    if (( fmix_cache_count > 0 )); then
        FMIX_STAT_HASH_CACHE_REFCOUNT="$fmix_cache_count"
        return 0
    fi
    unset FMIX_STAT_HASH_CACHE FMIX_STAT_HASH_CACHE_REFCOUNT
    return 0
}

fmix_stat_hash_cache_seed() {
    # Replace the active cache with a decoded stat manifest (base64 + zlib of
    # the TSV cache format). Empty or undecodable input fails without touching
    # the cache; the caller then runs the ordinary full-hash path. Old stamps
    # without the field are an ordinary miss here, never an error.
    local fmix_manifest="${1:-}" py_bin cache tmp rc
    [[ -n "${FMIX_STAT_HASH_CACHE:-}" ]] || return 1
    [[ -n "$fmix_manifest" ]] || return 1
    cache="$FMIX_STAT_HASH_CACHE"
    tmp="$(mktemp)" || return 1
    printf '%s' "$fmix_manifest" >"$tmp"
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    "$py_bin" - "$tmp" "$cache" <<'PY'
import base64, os, sys, zlib

source, target = sys.argv[1], sys.argv[2]
try:
    with open(source, "rb") as handle:
        data = handle.read()
    raw = zlib.decompress(base64.b64decode(data))
except Exception:
    raise SystemExit(1)
if not raw or b"\0" in raw:
    raise SystemExit(1)
tmp = target + ".seed.%d" % os.getpid()
try:
    with open(tmp, "wb") as handle:
        handle.write(raw)
    os.replace(tmp, target)
except OSError:
    try:
        os.unlink(tmp)
    except OSError:
        pass
    raise SystemExit(1)
PY
    rc=$?
    rm -f "$tmp"
    (( rc == 0 )) || return 1
    return 0
}

fmix_stat_hash_cache_dump() {
    # Serialize the active cache as the stamp's stat manifest payload.
    local py_bin
    [[ -n "${FMIX_STAT_HASH_CACHE:-}" && -f "$FMIX_STAT_HASH_CACHE" ]] || return 0
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    "$py_bin" - "$FMIX_STAT_HASH_CACHE" <<'PY'
import base64, sys, zlib

try:
    with open(sys.argv[1], "rb") as handle:
        raw = handle.read()
except OSError:
    raise SystemExit(0)
if not raw:
    raise SystemExit(0)
sys.stdout.write(base64.b64encode(zlib.compress(raw, 6)).decode("ascii"))
PY
}

fmix_stat_hash_files_cached() {
    # Cached fmix_hash_files: byte-identical digest lines (matching the text
    # output of shasum/sha256sum) with recorded digests reused for stat-tuple
    # matches and only drifted entries read from disk. Exits non-zero without
    # printing anything so the caller can fall back to the real hash tools.
    local py_bin
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    "$py_bin" - "$FMIX_STAT_HASH_CACHE" "$@" <<'PY'
import hashlib, os, stat, sys

cache_path = sys.argv[1]
names = sys.argv[2:]

for name in names:
    if "\n" in name or "\\" in name or "\0" in name:
        raise SystemExit(42)

entries = {}
try:
    if os.path.isfile(cache_path):
        with open(cache_path, "r", encoding="utf-8", errors="surrogateescape") as handle:
            for line in handle:
                parts = line.rstrip("\n").split("\t")
                if len(parts) == 7:
                    entries[parts[0]] = parts[1:]
except OSError:
    raise SystemExit(43)


def hash_file(path):
    digest = hashlib.sha256()
    with open(path, "rb") as source:
        while True:
            chunk = source.read(1024 * 1024)
            if not chunk:
                break
            digest.update(chunk)
    return digest.hexdigest()


lines = []
fresh = {}
for name in names:
    try:
        key = os.path.normpath(os.path.abspath(name))
        st = os.lstat(name)
        if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode):
            raise SystemExit(42)
        tup = (
            str(st.st_dev),
            str(st.st_ino),
            str(st.st_mtime_ns),
            str(st.st_ctime_ns),
            str(st.st_size),
        )
        cached = entries.get(key)
        if cached is not None and tuple(cached[:5]) == tup and len(cached[5]) == 64:
            digest = cached[5]
        else:
            digest = hash_file(name)
            fresh[key] = tup + (digest,)
    except SystemExit:
        raise
    except OSError:
        raise SystemExit(42)
    lines.append(digest + "  " + name)

if fresh:
    entries.update(fresh)
    tmp = cache_path + ".tmp.%d" % os.getpid()
    try:
        with open(tmp, "w", encoding="utf-8", errors="surrogateescape") as handle:
            for key in sorted(entries):
                handle.write("\t".join([key] + list(entries[key])) + "\n")
        os.replace(tmp, cache_path)
    except OSError:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise SystemExit(43)

sys.stdout.write("".join(line + "\n" for line in lines))
PY
}

fmix_hash_file_batches() {
    local file
    local -a batch=()
    for file in "$@"; do
        batch+=("$file")
        if (( ${#batch[@]} >= 256 )); then
            fmix_hash_files "${batch[@]}" || return 1
            batch=()
        fi
    done
    if (( ${#batch[@]} > 0 )); then
        fmix_hash_files "${batch[@]}" || return 1
    fi
}

fmix_hash_paired_lines() {
    # Print "<prefix>:<rel>:<digest-line>" for each (rel, abs) pair while
    # batching the content hashes into as few hash processes as possible.
    # Output is byte-identical to interleaved printf + fmix_hash_files calls.
    local prefix="$1" line index=0 hash_out
    shift
    local -a pair_rels=() pair_abses=()
    while (( $# >= 2 )); do
        pair_rels+=("$1")
        pair_abses+=("$2")
        shift 2
    done
    (( ${#pair_abses[@]} > 0 )) || return 0
    hash_out="$(mktemp)" || return 1
    if ! fmix_hash_file_batches "${pair_abses[@]}" >"$hash_out"; then
        rm -f "$hash_out"
        return 1
    fi
    while IFS= read -r line; do
        printf '%s:%s:%s\n' "$prefix" "${pair_rels[$index]}" "$line"
        index=$((index + 1))
    done <"$hash_out"
    rm -f "$hash_out"
    return 0
}

fmix_hash_tracked_compile_inputs() {
    local root="$1" tracked_file="$2" py_bin
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    "$py_bin" - "$root" "$tracked_file" <<'PY'
import hashlib
import os
import stat as stat_module
import sys


root = os.fsencode(sys.argv[1])
tracked_file = sys.argv[2]
output = sys.stdout.buffer
error_output = sys.stderr.buffer

# Stat-validated digest reuse: recorded entries are used only when the full
# stat tuple (including ctime) still matches; anomalies simply hash fresh.
stat_cache_path = os.environ.get("FMIX_STAT_HASH_CACHE", "")
stat_cache_entries = {}
stat_cache_usable = bool(stat_cache_path)
if stat_cache_usable:
    try:
        with open(stat_cache_path, "r", encoding="utf-8", errors="surrogateescape") as handle:
            for line in handle:
                parts = line.rstrip("\n").split("\t")
                if len(parts) == 7:
                    stat_cache_entries[parts[0]] = parts[1:]
    except FileNotFoundError:
        pass
    except OSError:
        stat_cache_usable = False
stat_cache_fresh = {}


def iter_nul_records(stream):
    pending = bytearray()
    while True:
        chunk = stream.read(64 * 1024)
        if not chunk:
            break
        pending.extend(chunk)
        start = 0
        while True:
            try:
                end = pending.index(0, start)
            except ValueError:
                if start:
                    del pending[:start]
                break
            yield bytes(pending[start:end])
            start = end + 1
            if start == len(pending):
                pending.clear()
                break

    if pending:
        yield bytes(pending)


def report_error(message):
    error_output.write(b"  [fmix ERROR] " + message + b"\n")
    error_output.flush()


def hash_file(path):
    digest = hashlib.sha256()
    with open(path, "rb") as source:
        while True:
            chunk = source.read(1024 * 1024)
            if not chunk:
                break
            digest.update(chunk)
    return digest.hexdigest().encode("ascii")


def cached_hash_file(path):
    if not stat_cache_usable:
        return hash_file(path)
    try:
        key = os.path.normpath(os.path.abspath(os.fsdecode(path)))
        st = os.lstat(path)
    except OSError:
        return hash_file(path)
    if stat_module.S_ISLNK(st.st_mode) or not stat_module.S_ISREG(st.st_mode):
        return hash_file(path)
    tup = (
        str(st.st_dev),
        str(st.st_ino),
        str(st.st_mtime_ns),
        str(st.st_ctime_ns),
        str(st.st_size),
    )
    cached = stat_cache_entries.get(key)
    if cached is not None and tuple(cached[:5]) == tup and len(cached[5]) == 64:
        return cached[5].encode("ascii")
    digest = hash_file(path)
    stat_cache_fresh[key] = tup + (digest.decode("ascii"),)
    return digest


try:
    with open(tracked_file, "rb") as records:
        for entry in iter_nul_records(records):
            try:
                metadata, path = entry.split(b"\t", 1)
                mode = metadata.split(b" ", 1)[0]
            except ValueError:
                report_error(b"Malformed tracked compiler input record")
                raise SystemExit(1)

            if mode == b"160000":
                continue

            candidate = root + b"/" + path
            output.write(b"tracked:" + metadata + b":" + path + b":")
            if os.path.islink(candidate):
                output.flush()
                report_error(
                    b"Symlinked compiler input is unsupported: " + candidate
                )
                raise SystemExit(1)
            if os.path.isfile(candidate):
                try:
                    digest = cached_hash_file(candidate)
                except OSError:
                    output.flush()
                    report_error(b"Could not hash compiler input: " + candidate)
                    raise SystemExit(1)
                output.write(digest + b"\n")
            else:
                output.write(b"missing\n")
        output.flush()
except OSError:
    report_error(b"Could not read tracked compiler input records")
    raise SystemExit(1)

if stat_cache_usable and stat_cache_fresh:
    stat_cache_entries.update(stat_cache_fresh)
    stat_cache_tmp = stat_cache_path + ".tmp.%d" % os.getpid()
    try:
        with open(stat_cache_tmp, "w", encoding="utf-8", errors="surrogateescape") as handle:
            for key in sorted(stat_cache_entries):
                handle.write("\t".join([key] + list(stat_cache_entries[key])) + "\n")
        os.replace(stat_cache_tmp, stat_cache_path)
    except OSError:
        try:
            os.unlink(stat_cache_tmp)
        except OSError:
            pass
PY
}

fmix_now() {
    date -u +%Y-%m-%dT%H:%M:%SZ
}

fmix_epoch() {
    date +%s
}

# Wall-clock milliseconds for boundaries that must line up with in-VM
# System.os_time(:millisecond) marks; whole seconds cannot split mix_test.
fmix_epoch_ms() {
    if [[ -n "${EPOCHREALTIME:-}" ]]; then
        local t="${EPOCHREALTIME/[.,]/}"
        printf '%s\n' "${t:0:${#t}-3}"
    else
        python3 -c 'import time; print(int(time.time() * 1000))'
    fi
}

# Record the runner side of the boot timeline next to the harness artifacts.
# Analysis joins these with the VM's boot_timeline.json marks; absent outside
# FMIX_RUN_ID executions.
fmix_write_mix_boundaries() {
    local live="${FMIX_RUN_ARTIFACT_DIR:-}/live"
    [[ -n "${FMIX_RUN_ARTIFACT_DIR:-}" && -d "$live" && ! -L "$live" ]] || return 0
    printf '{"schema":"fmix-mix-boundaries.v1","clock":"os_time_ms","guard_pre_started_at":%s,"spawned_at":%s,"exited_at":%s,"guard_post_finished_at":%s,"boot_profile":%s,"fixture_profile":%s}\n' \
        "$1" "$2" "$3" "$4" "$5" "$6" > "$live/mix_boundaries.json" 2>/dev/null || true
}

fmix_run_id_is_valid() {
    local run_id="${1:-}"
    [[ "$run_id" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]
}

fmix_run_observability_purge() {
    local ttl_hours runs_root canonical_root now candidate basename canonical_candidate
    local candidate_mtime candidate_age ttl_seconds
    ttl_hours="$FMIX_TELEMETRY_TTL_HOURS"
    if [[ ! "$ttl_hours" =~ ^[0-9]+$ ]] \
        || (( ${#ttl_hours} > 4 )) \
        || (( 10#$ttl_hours > FMIX_TELEMETRY_TTL_MAX_HOURS )); then
        fmix_warn "FMIX_TELEMETRY_TTL_HOURS='$ttl_hours' must be an integer from 0 to $FMIX_TELEMETRY_TTL_MAX_HOURS; using 4."
        ttl_hours=4
    fi
    ttl_hours=$(( 10#$ttl_hours ))
    runs_root="$FMIX_HOME/telemetry/runs"
    [[ -d "$runs_root" && ! -L "$runs_root" ]] || return 0
    canonical_root="$(fmix_realpath "$runs_root" 2>/dev/null)" || return 0
    [[ -n "$canonical_root" && "$canonical_root" != "/" ]] || return 0
    now="$(fmix_epoch)"
    ttl_seconds=$(( ttl_hours * 3600 ))

    for candidate in "$runs_root"/*; do
        [[ -d "$candidate" && ! -L "$candidate" ]] || continue
        basename="$(basename "$candidate")"
        fmix_run_id_is_valid "$basename" || continue
        canonical_candidate="$(fmix_realpath "$candidate" 2>/dev/null)" || continue
        case "$canonical_candidate" in
            "$canonical_root"/*) ;;
            *) continue ;;
        esac
        if [[ -f "$canonical_candidate/snapshot.json" ]] \
            && grep -Eq '"state"[[:space:]]*:[[:space:]]*"running"' \
                "$canonical_candidate/snapshot.json" 2>/dev/null; then
            continue
        fi
        candidate_mtime="$(fmix_stat_mtime "$canonical_candidate" 2>/dev/null || echo "$now")"
        [[ "$candidate_mtime" =~ ^[0-9]+$ ]] || continue
        candidate_age=$(( now - candidate_mtime ))
        (( candidate_age >= ttl_seconds )) || continue
        rm -rf -- "$canonical_candidate"
    done
    return 0
}

fmix_run_observability_write_snapshot() {
    local action="$1" py_bin
    (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    FMIX_OBSERVABILITY_ACTION="$action" \
    FMIX_OBSERVABILITY_RUN_ID="$FMIX_RUN_ID" \
    FMIX_OBSERVABILITY_FMIX_VERSION="$FMIX_VERSION" \
    FMIX_OBSERVABILITY_LAUNCHER_PID="$FMIX_RUN_OBSERVABILITY_LAUNCHER_PID" \
    FMIX_OBSERVABILITY_STARTED_AT="$FMIX_RUN_STARTED_AT" \
    FMIX_OBSERVABILITY_COMMAND="$FMIX_RUN_CMD" \
    FMIX_OBSERVABILITY_PHASE="$FMIX_RUN_OBSERVABILITY_PHASE" \
    FMIX_OBSERVABILITY_EXIT_CODE="$FMIX_RUN_RC" \
    FMIX_OBSERVABILITY_PHASES="$FMIX_RUN_PHASES" \
    FMIX_OBSERVABILITY_TOTAL_S="$FMIX_RUN_TOTAL_S" \
    FMIX_OBSERVABILITY_WORKTREE="$FMIX_RUN_WORKTREE" \
    FMIX_OBSERVABILITY_TEMPLATE_KEY="$FMIX_RUN_TEMPLATE_KEY" \
    FMIX_OBSERVABILITY_DB="$FMIX_RUN_DB" \
    FMIX_OBSERVABILITY_CACHE_HOT="$FMIX_RUN_CACHE_HOT" \
    FMIX_OBSERVABILITY_HOT_PATH="$FMIX_RUN_HOT_PATH" \
    FMIX_OBSERVABILITY_OVERHEAD_S="$FMIX_RUN_OVERHEAD_S" \
    FMIX_OBSERVABILITY_COMPILE_OUTCOME="$FMIX_LAST_COMPILE_OUTCOME" \
    FMIX_OBSERVABILITY_COMPILE_FILES="${FMIX_LAST_COMPILE_FILES:-0}" \
    FMIX_OBSERVABILITY_COMPILE_SECONDS="${FMIX_LAST_COMPILE_SECONDS:-0}" \
    FMIX_OBSERVABILITY_ARTIFACTS_OUTCOME="$FMIX_LAST_ARTIFACTS_OUTCOME" \
    FMIX_OBSERVABILITY_SESSION_HASH="${FMIX_ACTIVE_SESSION_HASH:-}" \
    FMIX_OBSERVABILITY_SESSION_SOURCE="${FMIX_ACTIVE_SESSION_SOURCE:-}" \
    FMIX_OBSERVABILITY_SESSION_ROOT="${FMIX_ACTIVE_SESSION_ROOT:-}" \
    FMIX_OBSERVABILITY_DEGRADED="$FMIX_RUN_OBSERVABILITY_DEGRADED" \
    FMIX_OBSERVABILITY_SAMPLE_LIMIT="$FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT" \
    "$py_bin" - "$FMIX_RUN_OBSERVABILITY_DIR" <<'PY' 2>/dev/null
import datetime
import fcntl
import json
import os
import re
import stat
import sys

run_dir = sys.argv[1]
action = os.environ["FMIX_OBSERVABILITY_ACTION"]
snapshot_path = os.path.join(run_dir, "snapshot.json")
events_path = os.path.join(run_dir, "events.jsonl")
metrics_path = os.path.join(run_dir, "metrics.jsonl")
now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

if action == "begin":
    snapshot = {
        "version": "fmix-session.v1",
        "runId": os.environ["FMIX_OBSERVABILITY_RUN_ID"],
        "fmixVersion": os.environ["FMIX_OBSERVABILITY_FMIX_VERSION"],
        "launcherPid": int(os.environ["FMIX_OBSERVABILITY_LAUNCHER_PID"]),
        "state": "running",
        "phase": "session",
        "command": os.environ["FMIX_OBSERVABILITY_COMMAND"],
        "exitCode": None,
        "startedAt": os.environ["FMIX_OBSERVABILITY_STARTED_AT"],
        "updatedAt": now,
    }
else:
    with open(snapshot_path, encoding="utf-8") as fh:
        snapshot = json.load(fh)
    snapshot["updatedAt"] = now

if action == "phase":
    snapshot["phase"] = os.environ["FMIX_OBSERVABILITY_PHASE"]
elif action == "meta":
    snapshot["worktree"] = os.environ.get("FMIX_OBSERVABILITY_WORKTREE", "") or None
    snapshot["templateKey"] = os.environ.get("FMIX_OBSERVABILITY_TEMPLATE_KEY", "") or None
    snapshot["database"] = os.environ.get("FMIX_OBSERVABILITY_DB", "") or None
    snapshot["session"] = {
        "hash": os.environ.get("FMIX_OBSERVABILITY_SESSION_HASH", "") or None,
        "source": os.environ.get("FMIX_OBSERVABILITY_SESSION_SOURCE", "") or None,
        "root": os.environ.get("FMIX_OBSERVABILITY_SESSION_ROOT", "") or None,
    }
elif action == "finish":
    exit_code = int(os.environ.get("FMIX_OBSERVABILITY_EXIT_CODE", "0") or 0)
    if exit_code == 0:
        state = "completed"
    elif exit_code in (129, 130, 143):
        state = "cancelled"
    else:
        state = "failed"
    phases = {}
    for item in os.environ.get("FMIX_OBSERVABILITY_PHASES", "").split():
        if "=" not in item:
            continue
        name, value = item.split("=", 1)
        try:
            phases[name] = int(value)
        except ValueError:
            continue
    samples = []
    metrics_degraded = False
    if os.path.isfile(metrics_path):
        with open(metrics_path, encoding="utf-8") as fh:
            metric_lines = fh.readlines()
        for index, line in enumerate(metric_lines):
            try:
                metric = json.loads(line)
                cpu = metric["processCpuPercent"]
                rss = metric["processRssBytes"]
                host = metric.get("hostAvailableMemoryBytes")
                if metric.get("version") != "fmix-metric.v1":
                    raise ValueError("unexpected metric version")
                if metric.get("runId") != os.environ["FMIX_OBSERVABILITY_RUN_ID"]:
                    raise ValueError("unexpected metric run id")
                if not isinstance(cpu, (int, float)) or not isinstance(rss, (int, float)):
                    raise ValueError("non-numeric process metric")
                if cpu < 0 or rss < 0:
                    raise ValueError("negative process metric")
                if host is not None and (not isinstance(host, (int, float)) or host < 0):
                    raise ValueError("invalid host memory metric")
                samples.append(metric)
            except (json.JSONDecodeError, KeyError, TypeError, ValueError):
                is_truncated_last_line = index == len(metric_lines) - 1 and not line.endswith("\n")
                if not is_truncated_last_line:
                    metrics_degraded = True

    def nearest_rank(values, percentile):
        if not values:
            return None
        import math
        ordered = sorted(values)
        return ordered[max(0, math.ceil(percentile * len(ordered)) - 1)]

    cpu_values = [sample["processCpuPercent"] for sample in samples]
    rss_values = [sample["processRssBytes"] for sample in samples]
    host_values = [
        sample["hostAvailableMemoryBytes"]
        for sample in samples
        if sample.get("hostAvailableMemoryBytes") is not None
    ]
    resources = {
        "sampleCount": len(samples),
        "processCpuPercent": {
            "p50": nearest_rank(cpu_values, 0.50),
            "p95": nearest_rank(cpu_values, 0.95),
            "max": max(cpu_values) if cpu_values else None,
        },
        "processRssBytes": {
            "p50": nearest_rank(rss_values, 0.50),
            "p95": nearest_rank(rss_values, 0.95),
            "max": max(rss_values) if rss_values else None,
        },
        "hostAvailableMemoryBytes": {
            "min": min(host_values) if host_values else None,
        },
    }
    if os.path.isfile(os.path.join(run_dir, ".sampler-limit-reached")):
        resources["sampleLimit"] = int(os.environ["FMIX_OBSERVABILITY_SAMPLE_LIMIT"])
        resources["truncated"] = True
    snapshot.update(
        {
            "state": state,
            "phase": "terminal",
            "exitCode": exit_code,
            "finishedAt": now,
            "durationSeconds": int(os.environ.get("FMIX_OBSERVABILITY_TOTAL_S", "0") or 0),
            "phases": phases,
            "worktree": os.environ.get("FMIX_OBSERVABILITY_WORKTREE", "") or None,
            "templateKey": os.environ.get("FMIX_OBSERVABILITY_TEMPLATE_KEY", "") or None,
            "database": os.environ.get("FMIX_OBSERVABILITY_DB", "") or None,
            "cache": {
                "hot": os.environ.get("FMIX_OBSERVABILITY_CACHE_HOT") == "yes",
                "hotPath": os.environ.get("FMIX_OBSERVABILITY_HOT_PATH") == "yes",
                "overheadSeconds": int(os.environ.get("FMIX_OBSERVABILITY_OVERHEAD_S", "0") or 0),
            },
            "compile": {
                "outcome": os.environ.get("FMIX_OBSERVABILITY_COMPILE_OUTCOME", "") or None,
                "fileCount": int(os.environ.get("FMIX_OBSERVABILITY_COMPILE_FILES", "0") or 0),
                "seconds": int(os.environ.get("FMIX_OBSERVABILITY_COMPILE_SECONDS", "0") or 0),
            },
            "artifacts": {
                "outcome": os.environ.get("FMIX_OBSERVABILITY_ARTIFACTS_OUTCOME", "") or None,
            },
            "session": {
                "hash": os.environ.get("FMIX_OBSERVABILITY_SESSION_HASH", "") or None,
                "source": os.environ.get("FMIX_OBSERVABILITY_SESSION_SOURCE", "") or None,
                "root": os.environ.get("FMIX_OBSERVABILITY_SESSION_ROOT", "") or None,
            },
            "resources": resources,
            "telemetry": {
                "degraded": (
                    os.environ.get("FMIX_OBSERVABILITY_DEGRADED", "0") == "1"
                    or metrics_degraded
                ),
            },
        }
    )
elif action != "begin":
    raise SystemExit(2)

temporary_path = snapshot_path + ".tmp-" + str(os.getpid())
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
fd = os.open(temporary_path, flags, 0o600)
try:
    with os.fdopen(fd, "w", encoding="utf-8") as fh:
        json.dump(snapshot, fh, separators=(",", ":"))
        fh.write("\n")
        fh.flush()
        os.fsync(fh.fileno())
    os.chmod(temporary_path, 0o600)
    os.replace(temporary_path, snapshot_path)
finally:
    try:
        os.unlink(temporary_path)
    except FileNotFoundError:
        pass

event_type = {
    "begin": "run_started",
    "phase": "phase_changed",
    "finish": "run_finished",
}.get(action)
if event_type:
    sequence = 0
    event_fd = None
    if os.environ.get("FMIX_OBSERVABILITY_WORKER") == "1":
        if os.environ.get("FMIX_OBSERVABILITY_EVENTS_FD") != "8":
            raise SystemExit(2)
        event_fd = 8
        event_info = os.fstat(event_fd)
        event_flags = fcntl.fcntl(event_fd, fcntl.F_GETFL)
        expected_dev = int(os.environ["FMIX_OBSERVABILITY_EVENTS_DEV"])
        expected_ino = int(os.environ["FMIX_OBSERVABILITY_EVENTS_INODE"])
        if (
            not stat.S_ISREG(event_info.st_mode)
            or event_info.st_uid != os.geteuid()
            or stat.S_IMODE(event_info.st_mode) != 0o600
            or not event_flags & os.O_APPEND
            or (event_info.st_dev, event_info.st_ino) != (expected_dev, expected_ino)
        ):
            raise SystemExit(2)
        size = event_info.st_size
        event_bytes = os.pread(event_fd, size, 0) if size else b""
        event_lines = event_bytes.splitlines()
    elif os.path.isfile(events_path):
        with open(events_path, "rb") as fh:
            event_lines = fh.read().splitlines()
    else:
        event_lines = []
    for line in event_lines:
        try:
            sequence = max(sequence, int(json.loads(line).get("seq", 0)))
        except (json.JSONDecodeError, TypeError, ValueError):
            continue
    event = {
        "version": "fmix-event.v1",
        "runId": os.environ["FMIX_OBSERVABILITY_RUN_ID"],
        "seq": sequence + 1,
        "type": event_type,
        "timestamp": now,
        "phase": snapshot["phase"],
        "state": snapshot["state"],
    }
    if action == "finish":
        event["exitCode"] = snapshot["exitCode"]
    event_payload = json.dumps(event, separators=(",", ":")).encode() + b"\n"
    if event_fd is not None:
        os.write(event_fd, event_payload)
        os.fsync(event_fd)
    else:
        flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
        fd = os.open(events_path, flags, 0o600)
        try:
            os.write(fd, event_payload)
            os.fsync(fd)
        finally:
            os.close(fd)
        os.chmod(events_path, 0o600)
PY
    [[ $? -eq 0 ]] || return 1
}

fmix_run_observability_begin() {
    FMIX_RUN_OBSERVABILITY_DIR=""
    FMIX_RUN_OBSERVABILITY_ENABLED=0
    FMIX_RUN_OBSERVABILITY_FINISHED=0
    FMIX_RUN_OBSERVABILITY_DEGRADED=0
    FMIX_RUN_OBSERVABILITY_PHASE="session"
    FMIX_RUN_OBSERVABILITY_SAMPLER_PID=""
    FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT="14400"
    FMIX_RUN_OBSERVABILITY_LAUNCHER_PID="$$"
    fmix_run_id_is_valid "${FMIX_RUN_ID:-}" || return 0

    # The supervisor has already validated and created this run directory.
    # The reserved worker may publish nonterminal phase/meta state, but never
    # owns sampling, cancellation, or terminal evidence.
    if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
        FMIX_RUN_OBSERVABILITY_DIR="$FMIX_HOME/telemetry/runs/$FMIX_RUN_ID"
        FMIX_RUN_OBSERVABILITY_LAUNCHER_PID="${FMIX_OBSERVABILITY_SUPERVISOR_PID:-}"
        FMIX_RUN_OBSERVABILITY_ENABLED=1
        return 0
    fi

    local telemetry_root="$FMIX_HOME/telemetry" runs_root="$FMIX_HOME/telemetry/runs"
    local old_umask canonical_runs canonical_run
    old_umask="$(umask)"
    umask 077
    if ! fmix_ensure_real_directory "$telemetry_root" \
        || ! fmix_ensure_real_directory "$runs_root"; then
        umask "$old_umask"
        return 0
    fi
    chmod 0700 "$telemetry_root" "$runs_root" 2>/dev/null || true
    fmix_run_observability_purge
    FMIX_RUN_OBSERVABILITY_DIR="$runs_root/$FMIX_RUN_ID"
    if [[ -e "$FMIX_RUN_OBSERVABILITY_DIR" || -L "$FMIX_RUN_OBSERVABILITY_DIR" ]]; then
        if ! fmix_real_directory_is_safe "$FMIX_RUN_OBSERVABILITY_DIR"; then
            FMIX_RUN_OBSERVABILITY_DIR=""
            umask "$old_umask"
            return 0
        fi
    elif ! mkdir "$FMIX_RUN_OBSERVABILITY_DIR"; then
        FMIX_RUN_OBSERVABILITY_DIR=""
        umask "$old_umask"
        return 0
    fi
    canonical_runs="$(fmix_realpath "$runs_root" 2>/dev/null)" || canonical_runs=""
    canonical_run="$(fmix_realpath "$FMIX_RUN_OBSERVABILITY_DIR" 2>/dev/null)" || canonical_run=""
    if [[ -z "$canonical_runs" || "$canonical_runs" == "/" ]]; then
        FMIX_RUN_OBSERVABILITY_DIR=""
        umask "$old_umask"
        return 0
    fi
    case "$canonical_run" in
        "$canonical_runs"/*) ;;
        *)
            FMIX_RUN_OBSERVABILITY_DIR=""
            umask "$old_umask"
            return 0
            ;;
    esac
    FMIX_RUN_OBSERVABILITY_DIR="$canonical_run"
    chmod 0700 "$FMIX_RUN_OBSERVABILITY_DIR" 2>/dev/null || true
    FMIX_RUN_OBSERVABILITY_ENABLED=1
    if ! fmix_run_observability_write_snapshot begin; then
        FMIX_RUN_OBSERVABILITY_ENABLED=0
    fi
    umask "$old_umask"
    if (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )); then
        fmix_run_observability_start_sampler
    fi
    return 0
}

fmix_run_observability_start_sampler() {
    (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
    local interval="${FMIX_RESOURCE_SAMPLE_INTERVAL:-1}" max_samples py_bin
    if [[ ! "$interval" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
        FMIX_RUN_OBSERVABILITY_DEGRADED=1
        return 0
    fi
    max_samples="$FMIX_RESOURCE_SAMPLE_MAX_SAMPLES"
    if [[ ! "$max_samples" =~ ^[0-9]+$ ]] \
        || (( ${#max_samples} > 5 )) \
        || (( 10#$max_samples < 1 )) \
        || (( 10#$max_samples > FMIX_RESOURCE_SAMPLE_MAX_SAMPLES_LIMIT )); then
        fmix_warn "FMIX_RESOURCE_SAMPLE_MAX_SAMPLES='$max_samples' must be an integer from 1 to $FMIX_RESOURCE_SAMPLE_MAX_SAMPLES_LIMIT; using 14400."
        max_samples=14400
        FMIX_RUN_OBSERVABILITY_DEGRADED=1
    fi
    max_samples=$(( 10#$max_samples ))
    FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT="$max_samples"
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    rm -f "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-stop" \
        "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-error" \
        "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-done" \
        "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-limit-reached" \
        "$FMIX_RUN_OBSERVABILITY_DIR/metrics.jsonl"
    {
    env -i PATH="$PATH" FMIX_OBSERVABILITY_MAX_SAMPLES="$max_samples" \
        "$py_bin" - "$FMIX_RUN_OBSERVABILITY_DIR" "$$" "$interval" <<'PY' >/dev/null 2>&1
import datetime
import json
import math
import os
import re
import subprocess
import sys
import time

run_dir, root_pid_text, interval_text = sys.argv[1:4]
run_id = os.path.basename(run_dir)
metrics_path = os.path.join(run_dir, "metrics.jsonl")
stop_path = os.path.join(run_dir, ".sampler-stop")
error_path = os.path.join(run_dir, ".sampler-error")
done_path = os.path.join(run_dir, ".sampler-done")
limit_path = os.path.join(run_dir, ".sampler-limit-reached")


def write_private_marker(path):
    flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
    fd = os.open(path, flags, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as fh:
        fh.write("\n")
    os.chmod(path, 0o600)


def host_available_memory_bytes():
    try:
        if os.path.isfile("/proc/meminfo"):
            with open("/proc/meminfo", encoding="utf-8") as fh:
                for line in fh:
                    if line.startswith("MemAvailable:"):
                        return int(line.split()[1]) * 1024
        output = subprocess.run(
            ["/usr/bin/memory_pressure", "-Q"],
            capture_output=True,
            text=True,
            timeout=2,
            check=True,
            env={**os.environ, "LC_ALL": "C"},
        ).stdout
        total_match = re.search(r"system has ([0-9]+)", output)
        free_match = re.search(r"memory free percentage: ([0-9]+)%", output)
        if total_match and free_match:
            return int(total_match.group(1)) * int(free_match.group(1)) // 100
    except (FileNotFoundError, OSError, subprocess.SubprocessError, ValueError):
        pass
    return None


def process_tree_totals(root_pid):
    output = subprocess.run(
        ["ps", "-axo", "pid=,ppid=,%cpu=,rss="],
        capture_output=True,
        text=True,
        timeout=2,
        check=True,
        env={**os.environ, "LC_ALL": "C"},
    ).stdout
    rows = []
    for line in output.splitlines():
        fields = line.split()
        if len(fields) != 4:
            continue
        try:
            pid, ppid = int(fields[0]), int(fields[1])
            cpu, rss_kib = float(fields[2]), int(fields[3])
        except ValueError:
            continue
        rows.append((pid, ppid, max(0.0, cpu), max(0, rss_kib)))
    selected = {root_pid}
    changed = True
    while changed:
        changed = False
        for pid, ppid, _cpu, _rss in rows:
            if ppid in selected and pid not in selected:
                selected.add(pid)
                changed = True
    sampler_subtree = {os.getpid()}
    changed = True
    while changed:
        changed = False
        for pid, ppid, _cpu, _rss in rows:
            if ppid in sampler_subtree and pid not in sampler_subtree:
                sampler_subtree.add(pid)
                changed = True
    selected.difference_update(sampler_subtree)
    cpu_total = sum(cpu for pid, _ppid, cpu, _rss in rows if pid in selected)
    rss_total = sum(rss for pid, _ppid, _cpu, rss in rows if pid in selected) * 1024
    return round(cpu_total, 3), rss_total


try:
    root_pid = int(root_pid_text)
    interval = float(interval_text)
    max_samples = int(os.environ["FMIX_OBSERVABILITY_MAX_SAMPLES"])
    if interval <= 0:
        raise ValueError("sample interval must be positive")
    cadence_monotonic = time.monotonic
    cadence_sleep = time.sleep
    sequence = 0
    next_sample_at = cadence_monotonic()
    while not os.path.exists(stop_path):
        cpu_percent, rss_bytes = process_tree_totals(root_pid)
        sequence += 1
        metric = {
            "version": "fmix-metric.v1",
            "runId": run_id,
            "seq": sequence,
            "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z"),
            "processCpuPercent": cpu_percent,
            "processRssBytes": rss_bytes,
            "hostAvailableMemoryBytes": host_available_memory_bytes(),
        }
        flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
        fd = os.open(metrics_path, flags, 0o600)
        with os.fdopen(fd, "a", encoding="utf-8") as fh:
            fh.write(json.dumps(metric, separators=(",", ":")) + "\n")
            fh.flush()
        os.chmod(metrics_path, 0o600)
        if sequence >= max_samples:
            write_private_marker(limit_path)
            break
        next_sample_at += interval
        now = cadence_monotonic()
        if next_sample_at <= now:
            missed_ticks = math.floor((now - next_sample_at) / interval) + 1
            next_sample_at += missed_ticks * interval
        while not os.path.exists(stop_path) and cadence_monotonic() < next_sample_at:
            cadence_sleep(min(0.05, max(0.0, next_sample_at - cadence_monotonic())))
except Exception as exc:
    flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
    fd = os.open(error_path, flags, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as fh:
        fh.write(type(exc).__name__ + "\n")
    raise
finally:
    write_private_marker(done_path)
PY
    } &
    FMIX_RUN_OBSERVABILITY_SAMPLER_PID=$!
    return 0
}

fmix_run_observability_stop_sampler() {
    local sampler_pid="${FMIX_RUN_OBSERVABILITY_SAMPLER_PID:-}" timeout_s
    local poll_count=0 max_polls sampler_state=""
    [[ -n "$sampler_pid" ]] || return 0
    : >"$FMIX_RUN_OBSERVABILITY_DIR/.sampler-stop"
    chmod 0600 "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-stop" 2>/dev/null || true

    timeout_s="$FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S"
    if [[ ! "$timeout_s" =~ ^[0-9]+$ ]] \
        || (( ${#timeout_s} > 2 )) \
        || (( 10#$timeout_s < 1 )) \
        || (( 10#$timeout_s > FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_MAX_S )); then
        fmix_warn "FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S='$timeout_s' must be an integer from 1 to $FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_MAX_S; using 2."
        timeout_s=2
        FMIX_RUN_OBSERVABILITY_DEGRADED=1
    fi
    timeout_s=$(( 10#$timeout_s ))
    # Keep the configured grace window, but avoid spawning a sleep process for
    # every 50ms tick on macOS/hosted runners. A 200ms observation cadence is
    # sufficient for a cooperative sampler and leaves the escalation windows
    # explicitly bounded below.
    max_polls=$(( timeout_s * 5 ))
    while (( poll_count < max_polls )); do
        if ! kill -0 "$sampler_pid" 2>/dev/null; then
            sampler_state=""
            break
        fi
        sampler_state="running"
        sleep 0.2
        poll_count=$(( poll_count + 1 ))
    done

    if [[ -n "$sampler_state" ]]; then
        FMIX_RUN_OBSERVABILITY_DEGRADED=1
        kill -TERM "$sampler_pid" 2>/dev/null || true
        poll_count=0
        while (( poll_count < 2 )); do
            if ! kill -0 "$sampler_pid" 2>/dev/null; then
                sampler_state=""
                break
            fi
            sampler_state="running"
            sleep 0.05
            poll_count=$(( poll_count + 1 ))
        done
    fi

    # A successful KILL is followed by a short bounded liveness check and a
    # single zombie probe. This avoids an unbounded wait for an uninterruptible
    # sampler while keeping the normal child-reap path cheap on hosted runners.
    if [[ -n "$sampler_state" && "$sampler_state" != Z* ]]; then
        if kill -KILL "$sampler_pid" 2>/dev/null; then
            poll_count=0
            while (( poll_count < 2 )); do
                if ! kill -0 "$sampler_pid" 2>/dev/null; then
                    sampler_state=""
                    break
                fi
                sampler_state="running"
                sleep 0.05
                poll_count=$(( poll_count + 1 ))
            done
            if [[ -n "$sampler_state" && "$sampler_state" != Z* ]]; then
                sampler_state="$(ps -o stat= -p "$sampler_pid" 2>/dev/null || true)"
            fi
        fi
    fi
    if [[ -z "$sampler_state" || "$sampler_state" == Z* ]]; then
        # wait is immediate only after a bounded probe proves the child exited
        # or is a zombie; a still-running or uninterruptible sampler is never
        # awaited.
        wait "$sampler_pid" 2>/dev/null || FMIX_RUN_OBSERVABILITY_DEGRADED=1
    else
        FMIX_RUN_OBSERVABILITY_DEGRADED=1
    fi
    if [[ -f "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-error" ]]; then
        FMIX_RUN_OBSERVABILITY_DEGRADED=1
    fi
    rm -f "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-done"
    FMIX_RUN_OBSERVABILITY_SAMPLER_PID=""
    return 0
}

fmix_run_observability_send_update() {
    [[ "${FMIX_OBSERVABILITY_UPDATES_FD:-}" == "10" \
        && "${FMIX_OBSERVABILITY_UPDATES_ACK_FD:-}" == "11" ]] || return 1
    local previous_pipe_trap ack write_rc=0
    previous_pipe_trap="$(trap -p PIPE)"
    trap '' PIPE
    printf "$@" 2>/dev/null >&10 || write_rc=$?
    if [[ -n "$previous_pipe_trap" ]]; then
        eval "$previous_pipe_trap"
    else
        trap - PIPE
    fi
    if (( write_rc != 0 )); then
        exec 10>&- 11<&-
        FMIX_OBSERVABILITY_UPDATES_FD=""
        FMIX_OBSERVABILITY_UPDATES_ACK_FD=""
        return 1
    fi
    ack=""
    if ! IFS= read -r -n 1 -t 2 ack 2>/dev/null <&11 \
        || [[ "$ack" != "A" ]]; then
        exec 10>&- 11<&-
        FMIX_OBSERVABILITY_UPDATES_FD=""
        FMIX_OBSERVABILITY_UPDATES_ACK_FD=""
        return 1
    fi
    return 0
}

fmix_run_observability_phase() {
    (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
    FMIX_RUN_OBSERVABILITY_PHASE="$1"
    if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
        local LC_ALL=C
        if (( ${#FMIX_RUN_OBSERVABILITY_PHASE} < 1 \
            || ${#FMIX_RUN_OBSERVABILITY_PHASE} > 64 )) \
            || [[ ! "$FMIX_RUN_OBSERVABILITY_PHASE" =~ ^[A-Za-z0-9_.-]+$ ]] \
            || ! fmix_run_observability_send_update \
                'P\0%s\0' "$FMIX_RUN_OBSERVABILITY_PHASE"; then
            FMIX_RUN_OBSERVABILITY_DEGRADED=1
        fi
        return 0
    fi
    fmix_run_observability_write_snapshot phase || FMIX_RUN_OBSERVABILITY_DEGRADED=1
    return 0
}

fmix_run_observability_meta() {
    (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
    if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
        local LC_ALL=C value invalid=0
        for value in \
            "$FMIX_RUN_WORKTREE" \
            "$FMIX_RUN_TEMPLATE_KEY" \
            "$FMIX_RUN_DB" \
            "${FMIX_ACTIVE_SESSION_HASH:-}" \
            "${FMIX_ACTIVE_SESSION_SOURCE:-}" \
            "${FMIX_ACTIVE_SESSION_ROOT:-}"; do
            (( ${#value} <= 4096 )) || invalid=1
        done
        if (( invalid == 1 )) \
            || ! fmix_run_observability_send_update \
            'M\0%s\0%s\0%s\0%s\0%s\0%s\0' \
            "$FMIX_RUN_WORKTREE" \
            "$FMIX_RUN_TEMPLATE_KEY" \
            "$FMIX_RUN_DB" \
            "${FMIX_ACTIVE_SESSION_HASH:-}" \
            "${FMIX_ACTIVE_SESSION_SOURCE:-}" \
            "${FMIX_ACTIVE_SESSION_ROOT:-}"; then
            FMIX_RUN_OBSERVABILITY_DEGRADED=1
        fi
        return 0
    fi
    fmix_run_observability_write_snapshot meta || FMIX_RUN_OBSERVABILITY_DEGRADED=1
    return 0
}

fmix_run_observability_finish() {
    (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
    (( FMIX_RUN_OBSERVABILITY_FINISHED == 0 )) || return 0
    FMIX_RUN_OBSERVABILITY_FINISHED=1
    if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
        fmix_run_observability_write_handoff || FMIX_RUN_OBSERVABILITY_DEGRADED=1
        return 0
    fi
    fmix_run_observability_stop_sampler
    fmix_run_observability_write_snapshot finish || FMIX_RUN_OBSERVABILITY_DEGRADED=1
    return 0
}

fmix_run_observability_write_handoff() {
    local handoff_fd="${FMIX_OBSERVABILITY_HANDOFF_FD:-}" value field_limit
    local LC_ALL=C payload_bytes=0 field_index=0
    local -a fields
    [[ "$handoff_fd" == "9" && -p /dev/fd/9 ]] || return 1
    fields=(
        "fmix-terminal-handoff.v2" "$FMIX_RUN_ID" "$$"
        "${FMIX_RUN_RC:-0}" "$FMIX_RUN_PHASES" "${FMIX_RUN_TOTAL_S:-0}"
        "$FMIX_RUN_CACHE_HOT" "$FMIX_RUN_HOT_PATH" "${FMIX_RUN_OVERHEAD_S:-0}"
        "$FMIX_LAST_COMPILE_OUTCOME" "${FMIX_LAST_COMPILE_FILES:-0}"
        "${FMIX_LAST_COMPILE_SECONDS:-0}" "${FMIX_ACTIVE_SESSION_HASH:-}"
        "${FMIX_ACTIVE_SESSION_SOURCE:-}" "${FMIX_ACTIVE_SESSION_ROOT:-}"
        "$FMIX_RUN_WORKTREE" "$FMIX_RUN_TEMPLATE_KEY" "$FMIX_RUN_DB"
        "$FMIX_LAST_ARTIFACTS_OUTCOME" "$FMIX_RUN_OBSERVABILITY_DEGRADED"
    )
    for value in "${fields[@]}"; do
        field_limit=4096
        (( field_index == 4 )) && field_limit=8192
        (( ${#value} <= field_limit )) || return 1
        payload_bytes=$(( payload_bytes + ${#value} + 1 ))
        field_index=$(( field_index + 1 ))
    done
    (( payload_bytes <= 65536 )) || return 1
    printf '%s\0' "${fields[@]}" >&"$handoff_fd"
}

fmix_run_telemetry_exclude_observability_elapsed() {
    local started="$1" finished elapsed
    finished="$(fmix_epoch)"
    [[ "$started" =~ ^[0-9]+$ && "$finished" =~ ^[0-9]+$ ]] || return 0
    elapsed=$(( finished - started ))
    (( elapsed > 0 )) || return 0
    if [[ "$FMIX_RUN_T0" =~ ^[0-9]+$ ]]; then
        FMIX_RUN_T0=$(( FMIX_RUN_T0 + elapsed ))
    fi
    if [[ "$FMIX_RUN_PHASE_T0" =~ ^[0-9]+$ ]]; then
        FMIX_RUN_PHASE_T0=$(( FMIX_RUN_PHASE_T0 + elapsed ))
    fi
    return 0
}

# ---------------------------------------------------------------------------
# Run telemetry (phase timings + session identity)
# Written to $FMIX_HOME/logs/runs.jsonl on every test/setup/task finish.
# Human one-liner always on stderr; set FMIX_TIMING=1 for per-phase lines.
# ---------------------------------------------------------------------------

FMIX_RUN_CMD=""
FMIX_RUN_T0=""
FMIX_RUN_PHASE_T0=""
FMIX_RUN_PHASES=""          # "name=seconds name=seconds ..."
FMIX_RUN_STARTED_AT=""
FMIX_RUN_WORKTREE=""
FMIX_RUN_TEMPLATE_KEY=""
FMIX_RUN_DB=""
FMIX_RUN_RC=""
FMIX_LAST_COMPILE_OUTCOME=""  # stamp_hit | compiled | skipped | error
FMIX_LAST_COMPILE_FILES=""
FMIX_LAST_COMPILE_SECONDS=""
FMIX_LAST_COMPILE_LOG=""
FMIX_LAST_ARTIFACTS_OUTCOME=""  # clone | adopt | skip | seed | error
FMIX_LAST_ARTIFACTS_COMPILE_FAILURE=0
FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE=0

fmix_run_telemetry_begin() {
    local observability_started
    FMIX_RUN_CMD="${1:-unknown}"
    FMIX_RUN_T0="$(fmix_epoch)"
    FMIX_RUN_PHASE_T0="$FMIX_RUN_T0"
    FMIX_RUN_PHASES=""
    FMIX_RUN_STARTED_AT="$(fmix_now)"
    FMIX_RUN_WORKTREE=""
    FMIX_RUN_TEMPLATE_KEY=""
    FMIX_RUN_DB=""
    FMIX_RUN_RC=""
    FMIX_LAST_COMPILE_OUTCOME=""
    FMIX_LAST_COMPILE_FILES=""
    FMIX_LAST_COMPILE_SECONDS=""
    FMIX_LAST_COMPILE_LOG=""
    FMIX_LAST_ARTIFACTS_OUTCOME=""
    observability_started="$(fmix_epoch)"
    fmix_run_observability_begin
    fmix_run_telemetry_exclude_observability_elapsed "$observability_started"
}

fmix_run_telemetry_meta() {
    # fmix_run_telemetry_meta worktree=... template=... db=...
    local kv observability_started
    for kv in "$@"; do
        case "$kv" in
            worktree=*) FMIX_RUN_WORKTREE="${kv#worktree=}" ;;
            template=*) FMIX_RUN_TEMPLATE_KEY="${kv#template=}" ;;
            db=*) FMIX_RUN_DB="${kv#db=}" ;;
        esac
    done
    observability_started="$(fmix_epoch)"
    fmix_run_observability_meta
    fmix_run_telemetry_exclude_observability_elapsed "$observability_started"
}

fmix_run_telemetry_phase() {
    local name="$1"
    local now elapsed observability_started
    [[ -n "$FMIX_RUN_PHASE_T0" ]] || return 0
    now="$(fmix_epoch)"
    elapsed=$(( now - FMIX_RUN_PHASE_T0 ))
    (( elapsed < 0 )) && elapsed=0
    if [[ -n "$FMIX_RUN_PHASES" ]]; then
        FMIX_RUN_PHASES="${FMIX_RUN_PHASES} ${name}=${elapsed}"
    else
        FMIX_RUN_PHASES="${name}=${elapsed}"
    fi
    FMIX_RUN_PHASE_T0="$now"
    if [[ "${FMIX_TIMING:-0}" == "1" ]]; then
        fmix_info "timing phase ${name}: ${elapsed}s"
    fi
    observability_started="$(fmix_epoch)"
    fmix_run_observability_phase "$name"
    fmix_run_telemetry_exclude_observability_elapsed "$observability_started"
}

# Emit a bounded NDJSON phase-change record to FMIX_EVENT_FD.
#
# No-op unless FMIX_EVENT_FD names a numeric descriptor, so an ordinary run is
# unaffected. The write is guarded against a closed pipe, a missing descriptor,
# and SIGPIPE, and never leaks to stderr: a consumer that dies must not take
# the test run down with it.
fmix_emit_phase_change() {
    local phase="$1"
    local status="$2"
    local duration_ms="${3:-}"
    local fd="${FMIX_EVENT_FD:-}"
    [[ -n "$fd" && "$fd" =~ ^[0-9]+$ ]] || return 0

    local now_iso run_id rec
    now_iso="$(fmix_now 2>/dev/null || date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo "")"
    run_id="${FMIX_RUN_ID:-}"
    run_id="${run_id//\\/\\\\}"
    run_id="${run_id//\"/\\\"}"

    if [[ -n "$duration_ms" && "$duration_ms" =~ ^[0-9]+$ ]]; then
        rec="{\"schemaVersion\":\"1.0.0\",\"runId\":\"$run_id\",\"timestamp\":\"$now_iso\",\"event\":\"phase:change\",\"phase\":\"$phase\",\"status\":\"$status\",\"durationMs\":$duration_ms}"
    else
        rec="{\"schemaVersion\":\"1.0.0\",\"runId\":\"$run_id\",\"timestamp\":\"$now_iso\",\"event\":\"phase:change\",\"phase\":\"$phase\",\"status\":\"$status\"}"
    fi

    # Bounded <= 512 bytes NDJSON record to designated FD
    # Non-blocking and safe against closed pipe / missing descriptor / stderr leaks / SIGPIPE
    if (( ${#rec} <= 512 )); then
        { ( trap '' PIPE; printf '%s\n' "$rec" >&"$fd" ) 2>/dev/null; } >/dev/null 2>&1 || true
    fi
}

fmix_run_telemetry_jsonl_path() {
    printf '%s/logs/runs.jsonl\n' "$FMIX_HOME"
}

fmix_run_telemetry_finish() {
    local rc="${1:-0}"
    local total=0 now path py_bin
    FMIX_RUN_RC="$rc"
    [[ -n "$FMIX_RUN_T0" ]] || return 0
    now="$(fmix_epoch)"
    total=$(( now - FMIX_RUN_T0 ))
    (( total < 0 )) && total=0

    # cache_hot: compile/artifacts warm (independent of ExUnit duration).
    # hot_path: cache_hot AND runner overhead (excl. mix_test) within budget.
    # Default overhead budget 25s — reflects preflight+fingerprint+db+migrate
    # after 2.2.1 warm-path cuts; override with FMIX_HOT_PATH_BUDGET_S.
    local hot_path="no" cache_hot="no" hot_budget overhead=0 phase_pair pname pval
    hot_budget="$(fmix_uint_or_default "${FMIX_HOT_PATH_BUDGET_S:-25}" 25 FMIX_HOT_PATH_BUDGET_S)"
    case "${FMIX_LAST_COMPILE_OUTCOME:-}" in
        stamp_hit|stamp_hit_repaired|stamp_hit_after_deps|stamp_hit_quick|noop_compile)
            case "${FMIX_LAST_ARTIFACTS_OUTCOME:-}" in
                session_hit|adopt_stamps|adopt_compatible|adopt_migration_delta|dependency_reconcile|ready|stable_seed|donor_clone)
                    cache_hot="yes"
                    ;;
            esac
            ;;
        incremental)
            # A same-toolchain dependency change deliberately keeps the
            # proven application build and lets Mix compile only the affected
            # dependency/app delta. That is still a cache hit; a near-full
            # compile is classified separately as full_recompile.
            [[ "${FMIX_LAST_ARTIFACTS_OUTCOME:-}" == "dependency_reconcile" \
                || "${FMIX_LAST_ARTIFACTS_OUTCOME:-}" == "adopt_migration_delta" ]] \
                && cache_hot="yes"
            ;;
    esac
    if [[ -n "$FMIX_RUN_PHASES" ]]; then
        for phase_pair in $FMIX_RUN_PHASES; do
            pname="${phase_pair%%=*}"
            pval="${phase_pair#*=}"
            [[ "$pval" =~ ^[0-9]+$ ]] || continue
            case "$pname" in
                mix_test) ;; # exclude actual ExUnit wall time
                *) overhead=$(( overhead + pval )) ;;
            esac
        done
    fi
    if [[ "$cache_hot" == "yes" ]] && (( overhead <= hot_budget )); then
        hot_path="yes"
    fi

    FMIX_RUN_TOTAL_S="$total"
    FMIX_RUN_CACHE_HOT="$cache_hot"
    FMIX_RUN_HOT_PATH="$hot_path"
    FMIX_RUN_OVERHEAD_S="$overhead"
    fmix_run_observability_finish
    rc="$FMIX_RUN_RC"

    # Always emit a greppable one-liner — primary operator signal for cold vs warm.
    # Match with:  ... 2>&1 | grep -E 'timing total=|Finished in|failure'
    fmix_info "timing total=${total}s rc=${rc} cache_hot=${cache_hot} hot_path=${hot_path} overhead=${overhead}s cmd=${FMIX_RUN_CMD:-?} session=${FMIX_ACTIVE_SESSION_HASH:-none}(${FMIX_ACTIVE_SESSION_SOURCE:-?}) compile=${FMIX_LAST_COMPILE_OUTCOME:-?} files=${FMIX_LAST_COMPILE_FILES:-0} compile_s=${FMIX_LAST_COMPILE_SECONDS:-?} artifacts=${FMIX_LAST_ARTIFACTS_OUTCOME:-?} phases=[${FMIX_RUN_PHASES}]"

    path="$(fmix_run_telemetry_jsonl_path)"
    mkdir -p "$(dirname "$path")" 2>/dev/null || true
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    # Best-effort append; never fail the caller if logging breaks.
    FMIX_RUN_TOTAL_S="$total" \
    FMIX_RUN_STARTED_AT="$FMIX_RUN_STARTED_AT" \
    FMIX_RUN_CMD="$FMIX_RUN_CMD" \
    FMIX_RUN_RC="$FMIX_RUN_RC" \
    FMIX_RUN_WORKTREE="$FMIX_RUN_WORKTREE" \
    FMIX_RUN_TEMPLATE_KEY="$FMIX_RUN_TEMPLATE_KEY" \
    FMIX_RUN_DB="$FMIX_RUN_DB" \
    FMIX_RUN_PHASES="$FMIX_RUN_PHASES" \
    FMIX_RUN_HOT_PATH="$hot_path" \
    FMIX_RUN_CACHE_HOT="$cache_hot" \
    FMIX_RUN_OVERHEAD_S="$overhead" \
    FMIX_LAST_COMPILE_OUTCOME="$FMIX_LAST_COMPILE_OUTCOME" \
    FMIX_LAST_COMPILE_FILES="${FMIX_LAST_COMPILE_FILES:-0}" \
    FMIX_LAST_COMPILE_SECONDS="${FMIX_LAST_COMPILE_SECONDS:-0}" \
    FMIX_LAST_COMPILE_LOG="$FMIX_LAST_COMPILE_LOG" \
    FMIX_LAST_ARTIFACTS_OUTCOME="$FMIX_LAST_ARTIFACTS_OUTCOME" \
    FMIX_ACTIVE_SESSION_HASH="${FMIX_ACTIVE_SESSION_HASH:-}" \
    FMIX_ACTIVE_SESSION_SOURCE="${FMIX_ACTIVE_SESSION_SOURCE:-}" \
    FMIX_ACTIVE_SESSION_ROOT="${FMIX_ACTIVE_SESSION_ROOT:-}" \
    FMIX_VERSION="$FMIX_VERSION" \
    "$py_bin" - "$path" <<'PY' 2>/dev/null
import json, os, sys
path = sys.argv[1]
rec = {
    "ts": os.environ.get("FMIX_RUN_STARTED_AT", ""),
    "cmd": os.environ.get("FMIX_RUN_CMD", ""),
    "rc": int(os.environ.get("FMIX_RUN_RC", "0") or 0),
    "total_s": int(os.environ.get("FMIX_RUN_TOTAL_S", "0") or 0),
    "hot_path": os.environ.get("FMIX_RUN_HOT_PATH", "no") == "yes",
    "cache_hot": os.environ.get("FMIX_RUN_CACHE_HOT", "no") == "yes",
    "overhead_s": int(os.environ.get("FMIX_RUN_OVERHEAD_S", "0") or 0),
    "worktree": os.environ.get("FMIX_RUN_WORKTREE", ""),
    "session_hash": os.environ.get("FMIX_ACTIVE_SESSION_HASH", ""),
    "session_source": os.environ.get("FMIX_ACTIVE_SESSION_SOURCE", ""),
    "session_root": os.environ.get("FMIX_ACTIVE_SESSION_ROOT", ""),
    "template_key": os.environ.get("FMIX_RUN_TEMPLATE_KEY", ""),
    "db": os.environ.get("FMIX_RUN_DB", ""),
    "compile_outcome": os.environ.get("FMIX_LAST_COMPILE_OUTCOME", ""),
    "compile_files": int(os.environ.get("FMIX_LAST_COMPILE_FILES", "0") or 0),
    "compile_s": int(os.environ.get("FMIX_LAST_COMPILE_SECONDS", "0") or 0),
    "compile_log": os.environ.get("FMIX_LAST_COMPILE_LOG", ""),
    "artifacts_outcome": os.environ.get("FMIX_LAST_ARTIFACTS_OUTCOME", ""),
    "phases": {},
    "fmix_version": os.environ.get("FMIX_VERSION", ""),
    "pid": os.getpid(),
}
phases = os.environ.get("FMIX_RUN_PHASES", "").strip()
if phases:
    for part in phases.split():
        if "=" not in part:
            continue
        k, v = part.split("=", 1)
        try:
            rec["phases"][k] = int(v)
        except ValueError:
            rec["phases"][k] = v
with open(path, "a", encoding="utf-8") as fh:
    fh.write(json.dumps(rec, separators=(",", ":")) + "\n")
PY
    true
    true
}

fmix_iso_epoch() {
    local py_bin="python3"
    command -v /usr/bin/python3 >/dev/null 2>&1 && py_bin="/usr/bin/python3"
    "$py_bin" - "$1" <<'PY'
import datetime
import sys

try:
    value = datetime.datetime.fromisoformat(sys.argv[1].replace("Z", "+00:00"))
except (IndexError, ValueError):
    raise SystemExit(1)
print(int(value.timestamp()))
PY
}

fmix_uint_or_default() {
    local value="$1" default="$2" label="$3"
    if [[ "$value" =~ ^[0-9]+$ ]]; then
        printf '%s\n' "$value"
    else
        fmix_warn "$label='$value' is not a non-negative integer; using $default."
        printf '%s\n' "$default"
    fi
}

fmix_positive_uint_or_default() {
    local value="$1" default="$2" label="$3"
    if [[ "$value" =~ ^[1-9][0-9]*$ ]]; then
        printf '%s\n' "$value"
    else
        fmix_warn "$label='$value' is not a positive integer; using $default."
        printf '%s\n' "$default"
    fi
}

fmix_nonnegative_number_or_default() {
    local value="$1" default="$2" label="$3"
    if [[ "$value" =~ ^([0-9]+(\.[0-9]+)?|\.[0-9]+)$ ]]; then
        printf '%s\n' "$value"
    else
        fmix_warn "$label='$value' is not a valid non-negative number; using $default."
        printf '%s\n' "$default"
    fi
}

fmix_effective_session_ttl_days() {
    fmix_nonnegative_number_or_default \
        "${FMIX_SESSION_TTL_DAYS:-${FMIX_CACHE_TTL_DAYS:-$FMIX_SESSION_TTL_DEFAULT}}" \
        "$FMIX_SESSION_TTL_DEFAULT" FMIX_SESSION_TTL_DAYS
}

fmix_effective_session_ttl_hours() {
    local explicit_hours="${FMIX_SESSION_TTL_HOURS-}"
    local legacy_days="${FMIX_SESSION_TTL_DAYS:-${FMIX_CACHE_TTL_DAYS:-}}"
    local hours
    if [[ -n "$explicit_hours" ]]; then
        fmix_nonnegative_number_or_default \
            "$explicit_hours" "$FMIX_SESSION_TTL_DEFAULT_HOURS" FMIX_SESSION_TTL_HOURS
        return 0
    fi
    if [[ -n "$legacy_days" ]]; then
        hours="$(fmix_nonnegative_number_or_default \
            "$legacy_days" "$FMIX_SESSION_TTL_DEFAULT" FMIX_SESSION_TTL_DAYS)"
        fmix_session_ttl_hours_from_days "$hours"
        return 0
    fi
    printf '%s\n' "$FMIX_SESSION_TTL_DEFAULT_HOURS"
}

fmix_session_ttl_hours_from_days() {
    local days="$1" py_bin
    if [[ "$days" =~ ^[0-9]+$ ]]; then
        printf '%s\n' "$(( days * 24 ))"
        return 0
    fi
    py_bin="$(fmix_python_bin)"
    "$py_bin" -c 'import sys; print(float(sys.argv[1]) * 24)' \
        "$days" 2>/dev/null || printf '4\n'
}

fmix_session_ttl_seconds() {
    local ttl_hours="${1:-$(fmix_effective_session_ttl_hours)}" py_bin
    if [[ "$ttl_hours" =~ ^[0-9]+$ ]]; then
        printf '%s\n' "$(( ttl_hours * 3600 ))"
        return 0
    fi
    py_bin="$(fmix_python_bin)"
    "$py_bin" -c 'import sys; print(int(float(sys.argv[1]) * 3600))' \
        "$ttl_hours" 2>/dev/null || printf '14400\n'
}

fmix_control_psql() {
    # Catalog/readiness probes must not become the unbounded part of an
    # otherwise bounded operation. The timeout covers connection, lock, and SQL.
    local timeout="${1:-5}"
    shift
    timeout="$(fmix_positive_uint_or_default "$timeout" 5 "control query timeout")"
    local timeout_ms=$(( timeout * 1000 ))
    PGCONNECT_TIMEOUT="$timeout" \
        PGOPTIONS="${PGOPTIONS:-} -c statement_timeout=${timeout_ms} -c lock_timeout=${timeout_ms}" \
        fmix_psql "$@"
}

fmix_json_escape() {
    # Minimal JSON string escaping
    local py_bin
    py_bin="$(fmix_python_bin)"
    printf '%s' "$1" | "$py_bin" -c 'import json,sys; print(json.dumps(sys.stdin.read()))' 2>/dev/null \
        || printf '"%s"' "$(printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g')"
}

# ---------------------------------------------------------------------------
# Session-owned mutable state
# ---------------------------------------------------------------------------

fmix_host_identity() {
    {
        printf 'fmix-host-v1\n'
        printf 'hostname=%s\n' "$(hostname 2>/dev/null || printf unknown)"
        printf 'uid=%s\n' "$(id -u 2>/dev/null || printf unknown)"
        printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
    } | fmix_hash_stdin | cut -c1-16
}

# Super-hot default (2.2.0+): one worktree → one warm overlay.
# Thread/chat/run IDs must NOT mint cold sessions. True parallel Mix on one
# checkout opts in with a *stable* --session name (and optionally --isolate).
fmix_worktree_default_logical() {
    printf 'worktree:%s\n' "$(id -u 2>/dev/null || printf unknown)"
}

fmix_session_id_is_ephemeral() {
    local id="${1:-}"
    [[ -n "$id" ]] || return 1
    # UUIDs (with or without braces)
    [[ "$id" =~ ^\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}?$ ]] && return 0
    # Auto-bound harness prefixes
    case "$id" in
        codex:*|github:*|cursor:*|claude:*|thread:*|run:*) return 0 ;;
    esac
    # Pure hex blobs (session hashes, random tokens) — 16+ hex chars only
    [[ "$id" =~ ^[0-9a-fA-F]{16,}$ ]] && return 0
    # pid / timestamp flavored ids
    [[ "$id" =~ (^|[^a-zA-Z])(pid|PPID|ppid)[-_]?[0-9]+ ]] && return 0
    [[ "$id" =~ [0-9]{8}T[0-9]{6} ]] && return 0
    [[ "$id" =~ ^tmp-|^temp-|^rand-|^random-|^uuid- ]] && return 0
    return 1
}

fmix_session_force_enabled() {
    case "${FMIX_FORCE_SESSION:-0}" in
        1|true|TRUE|yes|YES|on|ON) return 0 ;;
    esac
    case "${FMIX_ISOLATE:-0}" in
        1|true|TRUE|yes|YES|on|ON) return 0 ;;
    esac
    return 1
}

fmix_thread_sessions_enabled() {
    case "${FMIX_THREAD_SESSIONS:-0}" in
        1|true|TRUE|yes|YES|on|ON) return 0 ;;
    esac
    return 1
}

fmix_in_ci_environment() {
    [[ "${GITHUB_ACTIONS:-}" == "true" || "${CI:-}" == "true" || "${CI:-}" == "1" ]]
}

fmix_resolve_to_worktree_default() {
    local reason="${1:-}"
    if [[ -n "$reason" ]]; then
        fmix_warn "Session identity remapped to worktree-default ($reason)."
        fmix_warn "Hot cache requires one overlay per checkout. Use a stable --session name only for true parallel Mix; ephemeral ids need FMIX_FORCE_SESSION=1."
    fi
    printf 'worktree-default\t%s\n' "$(fmix_worktree_default_logical)"
}

fmix_resolve_session_identity() {
    local requested="${1:-}"
    local candidate="" source=""

    if [[ -n "$requested" ]]; then
        candidate="$requested"
        source="explicit"
    elif [[ -n "${FMIX_SESSION_ID:-}" ]]; then
        candidate="$FMIX_SESSION_ID"
        source="environment"
    elif fmix_thread_sessions_enabled && [[ -n "${CODEX_THREAD_ID:-}" ]]; then
        # Opt-in only: default ignores CODEX_THREAD_ID (2.2.0 super-hot).
        candidate="codex:${CODEX_THREAD_ID}"
        source="codex-thread"
    elif [[ "${GITHUB_ACTIONS:-}" == "true" ]] && [[ -n "${GITHUB_RUN_ID:-}" ]]; then
        candidate="github:${GITHUB_RUN_ID}:${GITHUB_JOB:-job}:${GITHUB_RUN_ATTEMPT:-1}"
        source="github-actions"
    else
        # Ignore ambient CODEX_THREAD_ID / non-CI GITHUB_RUN_ID so agent
        # harnesses and re-runs share the warm worktree-default overlay.
        if [[ -n "${CODEX_THREAD_ID:-}" ]] && ! fmix_thread_sessions_enabled; then
            fmix_warn "Ignoring CODEX_THREAD_ID for session identity (set FMIX_THREAD_SESSIONS=1 to restore thread-scoped cold sessions)."
        fi
        fmix_resolve_to_worktree_default ""
        return 0
    fi

    # Ephemeral remap applies to user/agent-supplied ids only. Auto CI/thread
    # candidates are intentional namespaces and already gated above.
    case "$source" in
        explicit|environment)
            if fmix_session_id_is_ephemeral "$candidate" && ! fmix_session_force_enabled; then
                fmix_resolve_to_worktree_default "ephemeral ${source} id '${candidate}'"
                return 0
            fi
            ;;
    esac

    printf '%s\t%s\n' "$source" "$candidate"
}



fmix_session_meta_file() {
    [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]] || return 1
    printf '%s/meta.json\n' "$FMIX_ACTIVE_SESSION_ROOT"
}

fmix_create_or_touch_meta_json() {
    local worktree="$1" meta created lockfile_hash app_name ttl_days ttl_hours tmp
    meta="$(fmix_session_meta_file)" || return 1
    if [[ ! -f "$meta" ]] && fmix_lock_any_shared_held; then
        # Creating the session metadata record is a shared-state mutation.
        # Refreshing an existing record is timestamp-only access accounting
        # (see docs/fmix.md) and stays under the shared hold.
        fmix_lock_escalate_exclusive "session meta creation" || return 70
    fi

    ttl_days="$(fmix_effective_session_ttl_days)"
    ttl_hours="$(fmix_effective_session_ttl_hours)"

    created=""
    if [[ -f "$meta" ]]; then
        local py_bin
        py_bin="$(fmix_python_bin)"
        created="$("$py_bin" -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d.get("creation_time") or d.get("created_at") or "")' "$meta" 2>/dev/null)" || created=""
        if [[ -z "$created" ]]; then
            created="$(grep -o '"creation_time"[[:space:]]*:[[:space:]]*"[^"]*"' "$meta" 2>/dev/null \
                | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
            if [[ -z "$created" ]]; then
                created="$(grep -o '"created_at"[[:space:]]*:[[:space:]]*"[^"]*"' "$meta" 2>/dev/null \
                    | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
            fi
        fi
    fi
    [[ -n "${created:-}" ]] || created="$(fmix_now)"

    lockfile_hash=""
    if [[ -f "$worktree/mix.lock" ]]; then
        lockfile_hash="$(fmix_hash_files "$worktree/mix.lock" 2>/dev/null | awk '{print $1}')"
    fi

    app_name="cdrcisco"
    if [[ -f "$worktree/mix.exs" ]]; then
        local found_app
        found_app="$(grep -o 'app:[[:space:]]*:[a-zA-Z0-9_]*' "$worktree/mix.exs" 2>/dev/null | head -1 | sed 's/.*:\([a-zA-Z0-9_]*\)/\1/')"
        [[ -n "$found_app" ]] && app_name="$found_app"
    fi

    tmp="${meta}.tmp-$$-${RANDOM}"
    if ! cat >"$tmp" <<EOF
{
  "schema": "$FMIX_SESSION_SCHEMA",
  "session_id": "$FMIX_ACTIVE_SESSION_HASH",
  "session_hash": "$FMIX_ACTIVE_SESSION_HASH",
  "app_name": $(fmix_json_escape "$app_name"),
  "source": $(fmix_json_escape "$FMIX_ACTIVE_SESSION_SOURCE"),
  "worktree": $(fmix_json_escape "$worktree"),
  "deps_path": $(fmix_json_escape "$MIX_DEPS_PATH"),
  "build_path": $(fmix_json_escape "$MIX_BUILD_PATH"),
  "creation_time": "$created",
  "created_at": "$created",
  "last_accessed": "$(fmix_now)",
  "last_used": "$(fmix_now)",
  "ttl_days": $ttl_days,
  "ttl_hours": $ttl_hours,
  "lockfile_hash": $(fmix_json_escape "$lockfile_hash"),
  "status": "active"
}
EOF
    then
        rm -f "$tmp"
        return 1
    fi
    mv "$tmp" "$meta" || { rm -f "$tmp"; return 1; }
    chmod 0600 "$meta" 2>/dev/null || true
}

fmix_write_session_meta() {
    fmix_create_or_touch_meta_json "$1"
}

fmix_session_meta_is_expired() {
    # Call only while holding session-<expected_hash>. Re-read the canonical
    # metadata under lease so a touch or replacement after an earlier snapshot
    # cannot be deleted from stale evidence.
    local session_meta="$1" expected_hash="$2" ttl_seconds="$3"
    local path_hash current_last current_epoch
    [[ -f "$session_meta" ]] || return 1
    path_hash="$(fmix_session_hash_from_metadata_path "$session_meta")" || return 1
    [[ "$path_hash" == "$expected_hash" ]] || return 1
    fmix_session_metadata_identity_matches_path "$session_meta" || return 1
    current_last="$(grep -o '"last_accessed"[[:space:]]*:[[:space:]]*"[^"]*"' \
        "$session_meta" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
    [[ -n "$current_last" ]] || current_last="$(grep -o '"last_used"[[:space:]]*:[[:space:]]*"[^"]*"' \
        "$session_meta" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
    [[ -n "$current_last" ]] || current_last="$(grep -o '"last_accessed"[[:space:]]*:[[:space:]]*[0-9.]*' \
        "$session_meta" 2>/dev/null | head -1 | sed 's/.*:[[:space:]]*//')"
    [[ -n "$current_last" ]] || current_last="$(grep -o '"last_used"[[:space:]]*:[[:space:]]*[0-9.]*' \
        "$session_meta" 2>/dev/null | head -1 | sed 's/.*:[[:space:]]*//')"
    [[ -n "$current_last" ]] || return 1
    if [[ "$current_last" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
        current_epoch="${current_last%.*}"
    else
        current_epoch="$(fmix_iso_epoch "$current_last" 2>/dev/null)" || return 1
    fi
    [[ "$current_epoch" =~ ^[0-9]+$ ]] || return 1
    (( $(fmix_epoch) - current_epoch >= ttl_seconds ))
}

fmix_session_hash_from_metadata_path() {
    local metadata_path="$1" sessions_v1="$FMIX_HOME/sessions/v1" relative
    local host_component session_component worktree_component file_component extra
    [[ "$metadata_path" == "$sessions_v1/"* ]] || return 1
    relative="${metadata_path#"$sessions_v1/"}"
    IFS='/' read -r host_component session_component worktree_component \
        file_component extra <<<"$relative"
    [[ -n "$host_component" && "$session_component" =~ ^[0-9a-f]{16}$ \
        && -n "$worktree_component" && "$file_component" == "meta.json" \
        && -z "$extra" ]] || return 1
    [[ "$host_component" != "." && "$host_component" != ".." \
        && "$worktree_component" != "." && "$worktree_component" != ".." ]] \
        || return 1
    fmix_real_directory_is_safe "$sessions_v1/$host_component" || return 1
    fmix_real_directory_is_safe "$sessions_v1/$host_component/$session_component" || return 1
    fmix_real_directory_is_safe \
        "$sessions_v1/$host_component/$session_component/$worktree_component" || return 1
    [[ -f "$metadata_path" && ! -L "$metadata_path" ]] || return 1
    printf '%s\n' "$session_component"
}

fmix_session_metadata_identity_matches_path() {
    local metadata_path="$1" path_hash declared_hash declared_id hash_count id_count
    path_hash="$(fmix_session_hash_from_metadata_path "$metadata_path")" || return 1
    hash_count="$(grep -o '"session_hash"[[:space:]]*:' "$metadata_path" 2>/dev/null \
        | wc -l | tr -d ' ')"
    id_count="$(grep -o '"session_id"[[:space:]]*:' "$metadata_path" 2>/dev/null \
        | wc -l | tr -d ' ')"
    [[ "$hash_count" =~ ^[0-9]+$ && "$id_count" =~ ^[0-9]+$ \
        && "$hash_count" -le 1 && "$id_count" -le 1 ]] || return 1
    declared_hash="$(grep -o '"session_hash"[[:space:]]*:[[:space:]]*"[^"]*"' \
        "$metadata_path" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
    declared_id="$(grep -o '"session_id"[[:space:]]*:[[:space:]]*"[^"]*"' \
        "$metadata_path" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
    if grep -q '"session_hash"[[:space:]]*:' "$metadata_path" 2>/dev/null \
        && [[ -z "$declared_hash" ]]; then
        return 1
    fi
    if grep -q '"session_id"[[:space:]]*:' "$metadata_path" 2>/dev/null \
        && [[ -z "$declared_id" ]]; then
        return 1
    fi
    [[ -z "$declared_hash" || "$declared_hash" == "$path_hash" ]] \
        && [[ -z "$declared_id" || "$declared_id" == "$path_hash" ]]
}

fmix_validate_session_structure() {
    local filename="${1:-}" sessions_v1="$FMIX_HOME/sessions/v1"
    local symlink_output
    if ! fmix_real_directory_is_safe "$FMIX_HOME/sessions" \
        || ! fmix_real_directory_is_safe "$sessions_v1" \
        || [[ ! -r "$sessions_v1" || ! -x "$sessions_v1" ]]; then
        fmix_error "Session state root is missing, inaccessible, or not a real directory: $sessions_v1"
        return 1
    fi
    if ! symlink_output="$(find "$sessions_v1" -mindepth 1 -maxdepth 3 -type l 2>&1)"; then
        while IFS= read -r scan_line; do
            [[ -n "$scan_line" ]] \
                && fmix_error "Session structure validation: $scan_line"
        done <<<"$symlink_output"
        fmix_error "Bounded session structure validation failed."
        return 1
    fi
    if [[ -n "$filename" ]]; then
        local metadata_links
        if ! metadata_links="$(find "$sessions_v1" -mindepth 4 -maxdepth 4 \
            -name "$filename" -type l 2>&1)"; then
            while IFS= read -r scan_line; do
                [[ -n "$scan_line" ]] \
                    && fmix_error "Session metadata validation: $scan_line"
            done <<<"$metadata_links"
            fmix_error "Bounded session metadata validation failed."
            return 1
        fi
        [[ -n "$metadata_links" ]] && symlink_output+="${symlink_output:+$'\n'}$metadata_links"
    fi
    if [[ -n "$symlink_output" ]]; then
        fmix_error "Session state contains symlinked structural metadata: $(head -1 <<<"$symlink_output")"
        return 1
    fi
}

fmix_session_files() {
    local filename="$1"
    local sessions_v1="$FMIX_HOME/sessions/v1"
    local scan_output
    fmix_validate_session_structure "$filename" || return 1
    # Session-owned files live exactly at v1/<host>/<session>/<worktree>/.
    # Never recurse into deps/_build: those trees can contain hundreds of
    # thousands of directories and must not delay startup housekeeping.
    if ! scan_output="$(find "$sessions_v1" -mindepth 4 -maxdepth 4 \
        -name "$filename" -type f 2>&1)"; then
        while IFS= read -r scan_line; do
            [[ -n "$scan_line" ]] && fmix_error "Bounded session discovery: $scan_line"
        done <<<"$scan_output"
        fmix_error "Bounded session discovery failed."
        return 1
    fi
    [[ -n "$scan_output" ]] && printf '%s\n' "$scan_output"
    return 0
}

fmix_empty_session_dirs() {
    local sessions_v1="$FMIX_HOME/sessions/v1"
    local scan_output
    fmix_validate_session_structure || return 1
    # Prune only empty structural host/session/worktree directories. -maxdepth
    # keeps the scan out of deps/_build. -depth reports children before parents;
    # a parent emptied by this run is pruned on the next housekeeping pass.
    if ! scan_output="$(find "$sessions_v1" -mindepth 1 -maxdepth 3 -depth \
        -type d -empty 2>&1)"; then
        while IFS= read -r scan_line; do
            [[ -n "$scan_line" ]] && fmix_error "Empty-session discovery: $scan_line"
        done <<<"$scan_output"
        fmix_error "Empty-session discovery failed."
        return 1
    fi
    [[ -n "$scan_output" ]] && printf '%s\n' "$scan_output"
    return 0
}

fmix_session_metadata_references_hash() {
    local metadata_paths="$1" expected_hash="$2"
    local sessions_v1="$FMIX_HOME/sessions/v1" metadata_path relative
    local host_component session_component worktree_component file_component extra
    while IFS= read -r metadata_path; do
        [[ "$metadata_path" == "$sessions_v1/"* ]] || continue
        relative="${metadata_path#"$sessions_v1/"}"
        IFS='/' read -r host_component session_component worktree_component \
            file_component extra <<<"$relative"
        if [[ -n "$host_component" && "$session_component" == "$expected_hash" \
            && -n "$worktree_component" && "$file_component" == "meta.json" \
            && -z "$extra" ]]; then
            return 0
        fi
    done <<<"$metadata_paths"
    return 1
}

fmix_session_hash_has_local_root() {
    # A scratch DB name carries only the session hash, and the same hash can
    # legitimately exist under another FMIX_HOME on this host (the DB server is
    # shared). Only a session root in THIS home proves fmix created the DB here.
    # Without it, the database may belong to another agent's live home: a second
    # FMIX_HOME once classified two live ~/.ct-fmix scratch DBs as orphans and
    # only the leaked backends stopped the DROP. Never destructive-clean a DB
    # this home cannot prove it owns.
    local session_hash="$1" session_dir
    [[ "$session_hash" =~ ^[0-9a-f]{16}$ ]] || return 1
    for session_dir in "$FMIX_HOME"/sessions/v1/*/"$session_hash"; do
        [[ -d "$session_dir" && ! -L "$session_dir" ]] && return 0
    done
    return 1
}

fmix_drop_orphan_session_db() {
    # Destructive orphan cleanup must serialize with first-session setup. A
    # snapshot taken before a session publishes meta.json is advisory only;
    # acquire the exact session lease and re-enumerate while holding it before
    # dropping the database. Contention or discovery failure preserves data.
    local db_name="$1" diagnostic_name="${2:-orphan session DB cleanup}"
    local session_hash session_lock current_meta_paths drop_rc=0
    if [[ ! "$db_name" =~ ^ct_fmix_s_([0-9a-f]{16})$ ]]; then
        fmix_warn "Refusing lease-aware cleanup for non-session DB: $db_name"
        return 2
    fi
    session_hash="${BASH_REMATCH[1]}"
    # Enforced here, not only in doctor: gc calls this helper directly and the
    # Postgres server is shared across FMIX_HOMEs. A hash with no root in this
    # home may be a live session in another home.
    if ! fmix_session_hash_has_local_root "$session_hash"; then
        fmix_warn "Refusing orphan cleanup for $db_name: no session root in this FMIX_HOME."
        return 2
    fi
    session_lock="session-$session_hash"
    if fmix_lock_acquire "$session_lock" 0 "$diagnostic_name" >/dev/null 2>&1; then
        :
    else
        local acquire_rc=$?
        fmix_lock_failure_is_fatal "$acquire_rc" && return 70
        fmix_warn "Session $session_hash became active; keeping $db_name."
        return 2
    fi
    if ! current_meta_paths="$(fmix_session_files meta.json)"; then
        fmix_warn "Session metadata revalidation failed; keeping $db_name."
        fmix_lock_release_optional "$session_lock" || {
            local release_rc=$?
            fmix_lock_failure_is_fatal "$release_rc" && return 70
            fmix_warn "Session cleanup lease metadata could not be retired."
        }
        return 2
    fi
    if fmix_session_metadata_references_hash "$current_meta_paths" "$session_hash"; then
        fmix_lock_release_optional "$session_lock" || {
            local release_rc=$?
            fmix_lock_failure_is_fatal "$release_rc" && return 70
            fmix_warn "Session cleanup lease metadata could not be retired."
        }
        return 2
    fi
    fmix_guard_db_name "$db_name" || drop_rc=1
    if (( drop_rc == 0 )); then
        # Lease + local-root proof above: this is this home's expired orphan.
        fmix_drop_db "$db_name" 1 || drop_rc=$?
    fi
    fmix_lock_release_optional "$session_lock" || {
        local release_rc=$?
        fmix_lock_failure_is_fatal "$release_rc" && return 70
        fmix_warn "Session cleanup lease metadata could not be retired after dropping $db_name."
    }
    return "$drop_rc"
}

fmix_purge_expired_sessions() {
    local quiet="${1:-0}"
    local ttl_hours ttl_seconds
    ttl_hours="$(fmix_effective_session_ttl_hours)"
    ttl_seconds="$(fmix_session_ttl_seconds "$ttl_hours")"
    local now session_meta session_root session_hash session_last session_epoch session_age session_lock session_db
    local dir_mtime dir_age session_meta_paths empty_dir_paths
    now="$(fmix_epoch)"

    local purged_count=0
    [[ -d "$FMIX_HOME/sessions" ]] || return 0
    if ! session_meta_paths="$(fmix_session_files meta.json)"; then
        fmix_error "Could not enumerate session metadata; refusing session cleanup."
        return 1
    fi
    if ! empty_dir_paths="$(fmix_empty_session_dirs)"; then
        fmix_error "Could not enumerate empty session directories; refusing session cleanup."
        return 1
    fi

    while IFS= read -r session_meta; do
        [[ -f "$session_meta" ]] || continue
        session_root="$(dirname "$session_meta")"

        if ! session_hash="$(fmix_session_hash_from_metadata_path "$session_meta")"; then
            fmix_warn "Refusing cleanup for malformed session metadata path: $session_meta"
            continue
        fi
        if ! fmix_session_metadata_identity_matches_path "$session_meta"; then
            fmix_warn "Refusing cleanup for mismatched session metadata identity: $session_meta"
            continue
        fi

        session_last="$(grep -o '"last_accessed"[[:space:]]*:[[:space:]]*"[^"]*"' \
            "$session_meta" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
        [[ -n "$session_last" ]] || session_last="$(grep -o '"last_used"[[:space:]]*:[[:space:]]*"[^"]*"' \
            "$session_meta" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
        if [[ -z "$session_last" ]]; then
            session_last="$(grep -o '"last_accessed"[[:space:]]*:[[:space:]]*[0-9.]*' \
                "$session_meta" 2>/dev/null | head -1 | sed 's/.*:[[:space:]]*//')"
        fi
        if [[ -z "$session_last" ]]; then
            session_last="$(grep -o '"last_used"[[:space:]]*:[[:space:]]*[0-9.]*' \
                "$session_meta" 2>/dev/null | head -1 | sed 's/.*:[[:space:]]*//')"
        fi

        # If meta.json is missing or missing last_accessed, DO NOT purge it!
        [[ -n "$session_last" ]] || continue

        if [[ "$session_last" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
            session_epoch="${session_last%.*}"
        else
            session_epoch="$(fmix_iso_epoch "$session_last" 2>/dev/null)" || continue
        fi
        [[ "$session_epoch" =~ ^[0-9]+$ ]] || continue

        # Inspect session directory mtime or creation time.
        # If meta.json is missing or missing last_accessed, OR if the session directory mtime is less than 60 seconds old
        # AND last_accessed was not explicitly backdated to an expired timestamp, treat as initializing active session and skip.
        dir_mtime="$(fmix_stat_mtime "$session_root" 2>/dev/null || echo "$now")"
        [[ "$dir_mtime" =~ ^[0-9]+$ ]] || dir_mtime="$now"
        dir_age=$(( now - dir_mtime ))

        session_age=$(( now - session_epoch ))

        # DO NOT purge if session directory mtime is less than 60s old UNLESS last_accessed is expired (session_age >= ttl_seconds)
        # and last_accessed is valid. But wait, if dir_age < 60 AND session_last was not populated or session is initializing:
        # If meta.json is missing or missing last_accessed, OR if session directory mtime is < 60s and session is not expired:
        if (( dir_age < 60 )) && (( session_age < ttl_seconds )); then
            continue
        fi

        if (( session_age >= ttl_seconds )); then
            session_lock="session-$session_hash"
            if fmix_lock_acquire "$session_lock" 0 "session TTL purge" >/dev/null 2>&1; then
                if ! fmix_session_meta_is_expired "$session_meta" "$session_hash" "$ttl_seconds"; then
                    fmix_lock_release_optional "$session_lock" || {
                        local release_rc=$?
                        fmix_lock_failure_is_fatal "$release_rc" && return 70
                        true
                    }
                    continue
                fi
                session_db="ct_fmix_s_$session_hash"
                if fmix_db_exists "$session_db"; then
                    fmix_drop_db "$session_db" 1 >/dev/null 2>&1 || {
                        local drop_rc=$?
                        if fmix_lock_failure_is_fatal "$drop_rc"; then
                            fmix_command_lock_finish "$session_lock" "$drop_rc"
                            return $?
                        fi
                    }
                fi
                if fmix_guard_path "$session_root"; then
                    rm -rf "$session_root"
                    purged_count=$(( purged_count + 1 ))
                fi
                fmix_lock_release_optional "$session_lock" || {
                    local release_rc=$?
                    fmix_lock_failure_is_fatal "$release_rc" && return 70
                    true
                }
            else
                local acquire_rc=$?
                fmix_lock_failure_is_fatal "$acquire_rc" && return 70
            fi
        fi
    done <<<"$session_meta_paths"

    if [[ -d "$FMIX_HOME/sessions" ]]; then
        local empty_dir empty_mtime empty_age
        while IFS= read -r empty_dir; do
            [[ -d "$empty_dir" ]] || continue
            empty_mtime="$(fmix_stat_mtime "$empty_dir" 2>/dev/null || echo "$now")"
            [[ "$empty_mtime" =~ ^[0-9]+$ ]] || empty_mtime="$now"
            empty_age=$(( now - empty_mtime ))
            if (( empty_age >= 60 )); then
                rmdir "$empty_dir" 2>/dev/null || true
            fi
        done <<<"$empty_dir_paths"
    fi

    if (( quiet == 0 && purged_count > 0 )); then
        fmix_info "Purged $purged_count expired session build artifact(s) (TTL: ${ttl_hours}h)."
    fi
    return 0
}

fmix_clear_active_session() {
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    unset MIX_DEPS_PATH MIX_BUILD_PATH
    export FMIX_ACTIVE_SESSION_HASH FMIX_ACTIVE_SESSION_ROOT FMIX_ACTIVE_SESSION_SOURCE
}

# REL-3972: print the worktree a session record declares (empty when the record
# declares none). Exit 1 when the record cannot be read as a JSON object.
fmix_session_record_worktree() {
    local meta="$1" py_bin
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    "$py_bin" -I -S -B - "$meta" <<'PY'
import json
import os
import sys

try:
    with open(sys.argv[1], encoding="utf-8") as handle:
        value = json.load(handle)
except (OSError, ValueError):
    raise SystemExit(1)
if not isinstance(value, dict):
    raise SystemExit(1)
declared = value.get("worktree")
if declared in (None, ""):
    print("")
    raise SystemExit(0)
if not isinstance(declared, str) or not os.path.isabs(declared):
    raise SystemExit(1)
print(os.path.realpath(declared))
PY
}

fmix_activate_session() {
    local worktree="$1" requested="${2:-}" real logical host_hash worktree_hash
    local session_hash session_root created_session_root priv_link expected_priv session_lock activation_rc=0
    local session_root_preexisting=0 identity_output
    real="$(fmix_realpath "$worktree")" || {
        fmix_clear_active_session
        return 1
    }

    if [[ -n "${MIX_DEPS_PATH:-}" && "$MIX_DEPS_PATH" == "$FMIX_HOME/sessions/"* ]]; then
        unset MIX_DEPS_PATH
    fi
    if [[ -n "${MIX_BUILD_PATH:-}" && "$MIX_BUILD_PATH" == "$FMIX_HOME/sessions/"* ]]; then
        unset MIX_BUILD_PATH
    fi
    if [[ -n "${MIX_DEPS_PATH:-}" && "$MIX_DEPS_PATH" != "deps" ]] \
        || [[ -n "${MIX_BUILD_PATH:-}" && "$MIX_BUILD_PATH" != "_build" ]]; then
        fmix_error "FMix v2 owns MIX_DEPS_PATH and MIX_BUILD_PATH for session isolation."
        fmix_error "Unset both variables and use --session or FMIX_SESSION_ID instead."
        fmix_clear_active_session
        return 1
    fi
    fmix_clear_active_session

    identity_output="$(fmix_resolve_session_identity "$requested")" || {
        fmix_clear_active_session
        return 1
    }
    IFS=$'\t' read -r FMIX_ACTIVE_SESSION_SOURCE logical <<<"$identity_output" || {
        fmix_clear_active_session
        return 1
    }
    [[ -n "$FMIX_ACTIVE_SESSION_SOURCE" && -n "$logical" ]] || {
        fmix_clear_active_session
        return 1
    }
    host_hash="$(fmix_host_identity)" || {
        fmix_clear_active_session
        return 1
    }
    worktree_hash="$(
        {
            printf 'fmix-session-worktree-v1\n'
            printf '%s\n' "$real"
        } | fmix_hash_stdin | cut -c1-16
    )" || {
        fmix_clear_active_session
        return 1
    }
    session_hash="$(
        {
            printf 'fmix-session-id-v1\n'
            printf 'host=%s\n' "$host_hash"
            printf 'logical=%s\n' "$logical"
            printf 'worktree=%s\n' "$real"
        } | fmix_hash_stdin | cut -c1-16
    )" || {
        fmix_clear_active_session
        return 1
    }
    session_root="$FMIX_HOME/sessions/v1/$host_hash/$session_hash/$worktree_hash"
    session_lock="session-$session_hash"

    # Shared (read) activation is used only when the session overlay is already
    # warm (root + meta + priv bridge present). Creation and session housekeeping
    # are mutations and always run under the exclusive lease.
    local activation_mode="exclusive"
    if fmix_session_lock_split_enabled \
        && fmix_activation_probe_readonly "$session_root" "$real"; then
        activation_mode="shared"
    fi
    fmix_lock_acquire "$session_lock" "$FMIX_WORKTREE_LOCK_TIMEOUT" \
        "session activation" 0 "$activation_mode" || {
        activation_rc=$?
        fmix_clear_active_session
        return "$activation_rc"
    }
    if [[ "$activation_mode" == "shared" ]]; then
        # Re-verify the warm activation conditions under the lease: the overlay
        # may have been created or removed while the lock was acquired.
        if ! fmix_activation_probe_readonly "$session_root" "$real"; then
            fmix_lock_escalate_exclusive "session root creation" || {
                activation_rc=$?
                fmix_clear_active_session
                return "$activation_rc"
            }
            activation_mode="exclusive"
        fi
    fi
    if [[ -e "$session_root" || -L "$session_root" ]]; then
        session_root_preexisting=1
    fi
    if (( activation_rc == 0 )) && [[ "$activation_mode" == "exclusive" ]]; then
        if created_session_root="$(fmix_create_session_root \
            "$host_hash" "$session_hash" "$worktree_hash")"; then
            session_root="$created_session_root"
        else
            activation_rc=1
        fi
    fi
    if (( activation_rc == 0 )) && [[ "$activation_mode" == "exclusive" ]]; then
        local housekeeping_rc=0
        fmix_purge_expired_sessions 1 || housekeeping_rc=$?
        if fmix_lock_failure_is_fatal "$housekeeping_rc"; then
            activation_rc=70
        elif (( housekeeping_rc != 0 )); then
            fmix_warn "Session housekeeping is degraded; activation will continue without destructive cleanup."
        fi
    fi
    if (( activation_rc == 0 )) && [[ "$activation_mode" == "exclusive" ]]; then
        chmod 0700 "$FMIX_HOME" "$FMIX_HOME/sessions" "$FMIX_HOME/sessions/v1" \
        "$FMIX_HOME/sessions/v1/$host_hash" \
        "$FMIX_HOME/sessions/v1/$host_hash/$session_hash" "$session_root" \
        2>/dev/null || true
    fi

    # REL-3972: a session root is only ever activated for the worktree its
    # record names. Refuse before any priv bridge or metadata mutation.
    # An unreadable record is regenerated by the normal metadata write below;
    # only a readable record that names another worktree is refused.
    if (( activation_rc == 0 )) && [[ -e "$session_root/meta.json" || -L "$session_root/meta.json" ]]; then
        local recorded_worktree=""
        recorded_worktree="$(fmix_session_record_worktree "$session_root/meta.json" 2>/dev/null)" \
            || recorded_worktree=""
        if [[ -n "$recorded_worktree" && "$recorded_worktree" != "$real" ]]; then
            fmix_error "worktree_session_mismatch: session $session_hash records worktree $recorded_worktree, not $real."
            fmix_error "Refusing to run this worktree inside another worktree's session. No session state was changed."
            activation_rc=1
        fi
    fi

    FMIX_ACTIVE_SESSION_HASH="$session_hash"
    FMIX_ACTIVE_SESSION_ROOT="$session_root"
    MIX_DEPS_PATH="$session_root/deps"
    # MIX_BUILD_PATH is the final environment-specific build path when set
    # explicitly; Mix does not append /test. The surrounding _build directory
    # remains FMix's atomic clone/publish unit.
    MIX_BUILD_PATH="$session_root/_build/test"
    export FMIX_ACTIVE_SESSION_HASH FMIX_ACTIVE_SESSION_ROOT
    export MIX_DEPS_PATH MIX_BUILD_PATH

    # Mix creates _build/test/lib/cdrcisco/priv as ../../../../priv. With an
    # external build root that resolves to <session>/priv, so publish one
    # session-owned bridge to the checkout's real priv directory.
    priv_link="$session_root/priv"
    expected_priv="$real/priv"
    if (( activation_rc == 0 )) && [[ -L "$priv_link" ]]; then
        if [[ "$(readlink "$priv_link" 2>/dev/null)" != "$expected_priv" ]]; then
            fmix_error "Session priv bridge points at another checkout: $priv_link"
            activation_rc=1
        fi
    elif (( activation_rc == 0 )) && [[ -e "$priv_link" ]]; then
        fmix_error "Session priv bridge path is occupied by non-symlink state: $priv_link"
        activation_rc=1
    elif (( activation_rc == 0 )); then
        if fmix_lock_any_shared_held; then
            fmix_lock_escalate_exclusive "session priv bridge creation" \
                || activation_rc=70
        fi
        if (( activation_rc == 0 )); then
            ln -s "$expected_priv" "$priv_link" || activation_rc=1
        fi
    fi

    if (( activation_rc == 0 )) && ! fmix_write_session_meta "$real"; then
        activation_rc=1
    fi
    if (( activation_rc != 0 && activation_rc != 70 && session_root_preexisting == 0 )) \
        && [[ "$session_root" == "$FMIX_HOME/sessions/v1/$host_hash/$session_hash/$worktree_hash" ]]; then
        if ! fmix_guard_path "$session_root" || ! rm -rf "$session_root"; then
            fmix_warn "Failed session activation left partial state for review: $session_root"
        fi
    fi
    local activation_release_rc=0
    fmix_lock_release "$session_lock" || activation_release_rc=$?
    if fmix_lock_failure_is_fatal "$activation_release_rc"; then
        printf '{"error":"command_lock_cleanup_failed","command_exit_code":%d,"cleanup_exit_code":%d}\n' "$activation_rc" "$activation_release_rc" >&2
        activation_rc=70
    elif (( activation_release_rc != 0 )); then
        fmix_warn "Session activation lease metadata could not be retired."
    fi
    if (( activation_rc != 0 )); then
        fmix_clear_active_session
        return "$activation_rc"
    fi
    fmix_info "Session: $session_hash ($FMIX_ACTIVE_SESSION_SOURCE)"
    fmix_info "Session artifacts: $session_root"

    # Disk-pressure early warning: each session owns a full deps/_build overlay,
    # so unbounded session accumulation quietly consumes tens of GB.
    local session_count session_warn_threshold
    session_warn_threshold="$(fmix_uint_or_default \
        "$FMIX_SESSION_WARN_THRESHOLD" 24 FMIX_SESSION_WARN_THRESHOLD)"
    session_count="$(find "$FMIX_HOME/sessions/v1/$host_hash" -mindepth 1 -maxdepth 1 \
        -type d 2>/dev/null | wc -l | tr -d ' ')"
    if [[ "$session_count" =~ ^[0-9]+$ ]] \
        && (( session_count > session_warn_threshold )); then
        fmix_warn "$session_count fmix sessions exist on this host (warn threshold: $session_warn_threshold)."
        fmix_warn "Review with 'fmix timing' / 'fmix gc', then reclaim with 'fmix gc --consolidate --yes'."
    fi

    # Per-worktree multi-session warning (super-hot SLO: prefer 1 overlay).
    local per_wt_count per_wt_warn
    per_wt_warn="$(fmix_uint_or_default \
        "${FMIX_SESSION_PER_WORKTREE_WARN:-1}" 1 FMIX_SESSION_PER_WORKTREE_WARN)"
    per_wt_count="$(
        find "$FMIX_HOME/sessions/v1/$host_hash" -mindepth 2 -maxdepth 2 \
            -type d -name "$worktree_hash" 2>/dev/null | wc -l | tr -d ' '
    )"
    if [[ "$per_wt_count" =~ ^[0-9]+$ ]] \
        && (( per_wt_count > per_wt_warn )); then
        fmix_warn "$per_wt_count fmix sessions exist for this worktree (hot path wants ≤${per_wt_warn})."
        fmix_warn "Each extra session is ~0.5GB and a multi-minute full recompile. Reclaim: fmix gc --consolidate --worktree $real --yes"
    fi
}

fmix_session_deps_root() {
    local worktree="$1" configured="${MIX_DEPS_PATH:-deps}"
    if [[ "$configured" == /* ]]; then
        printf '%s\n' "$configured"
    else
        printf '%s/%s\n' "$(fmix_realpath "$worktree")" "$configured"
    fi
}

fmix_execution_lock_name() {
    local worktree="$1"
    if [[ -n "$FMIX_ACTIVE_SESSION_HASH" ]]; then
        printf 'session-%s\n' "$FMIX_ACTIVE_SESSION_HASH"
    else
        printf 'worktree-%s\n' "$(fmix_worktree_id "$worktree")"
    fi
}

fmix_artifact_layout_is_owned() {
    local worktree="$1" deps_root build_root
    deps_root="$(fmix_session_deps_root "$worktree")" || return 1
    build_root="$(fmix_compile_build_root "$worktree")" || return 1
    if [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]]; then
        [[ "$deps_root" == "$FMIX_ACTIVE_SESSION_ROOT/deps" \
            && "$build_root" == "$FMIX_ACTIVE_SESSION_ROOT/_build" ]]
        return
    fi
    [[ "${MIX_DEPS_PATH:-deps}" == "deps" \
        && "${MIX_BUILD_PATH:-_build}" == "_build" ]]
}

# ---------------------------------------------------------------------------
# Safety guard: assert a path/db name is fmix-owned before destructive ops
# ---------------------------------------------------------------------------

fmix_guard_db_name() {
    # Strict allow-list, not just a prefix check: these names are interpolated
    # into SQL identifiers, so a crafted datname (e.g. containing a double
    # quote) read back from postgres or a state file must never reach psql
    # (codex P1). Generated names are ct_fmix_<sha8>,
    # ct_fmix_s_<session>, or ct_fmix_tmpl_<16hex>.
    local name="$1"
    if [[ ! "$name" =~ ^ct_fmix_(s_|tmpl_|snap_)?[0-9a-f]{8,40}$ ]]; then
        fmix_error "SAFETY: refusing to touch database '$name' — fmix only manages its ct_fmix_<hex> namespaces."
        fmix_error "If this is unexpected, file a bug. Do NOT manually edit the state files."
        return 1
    fi
}

fmix_guard_template_db_name() {
    # Same rationale as fmix_guard_db_name, for READ-ONLY template sources we
    # interpolate into CREATE DATABASE … TEMPLATE "<name>" (codex P1).
    local name="$1"
    if [[ ! "$name" =~ ^ct_fmix_(tmpl_|snap_)[0-9a-f]{8,40}$ ]]; then
        fmix_error "SAFETY: refusing to use template database '$name' — fmix only clones its own published tmpl/snap namespace."
        return 1
    fi
}

fmix_guard_publish_source_db_name() {
    # Hot-base publication is the one operation that clones FROM a mutable
    # session scratch DB. Keep this namespace narrower than the general DB
    # guard; the caller must additionally prove it is the current session's
    # exact deterministic scratch name.
    local name="$1"
    if [[ ! "$name" =~ ^ct_fmix_(s_[0-9a-f]{16}|[0-9a-f]{8})$ ]]; then
        fmix_error "SAFETY: refusing hot-base publish source '$name' — expected an exact FMix session/worktree scratch database."
        return 1
    fi
}

fmix_guard_path() {
    local path="$1"
    local real_path
    real_path="$(fmix_realpath "$path" 2>/dev/null || echo "$path")"
    local fmix_home_real
    fmix_home_real="$(fmix_realpath "$FMIX_HOME" 2>/dev/null || echo "$FMIX_HOME")"
    if [[ "$real_path" != "$fmix_home_real" \
        && "$real_path" != "$fmix_home_real/"* ]]; then
        fmix_error "SAFETY: refusing to delete '$path' — it is not under FMIX_HOME ($FMIX_HOME)."
        fmix_error "Run 'fmix gc' to manage stale artifacts safely."
        return 1
    fi
}

fmix_guard_stale_build() {
    # Guard for stale _build dirs: must match pattern _build.fmix-stale.* AND
    # sit directly inside a real cisco-cdr checkout — the recorded worktree
    # path comes from a state file a corrupt/hand-edited copy of which must
    # not be able to point gc --reap at an arbitrary directory (codex P2).
    local path="$1"
    local base parent
    base="$(basename "$path")"
    parent="$(dirname "$path")"
    if [[ "$base" != _build.fmix-stale.* ]]; then
        fmix_error "SAFETY: refusing to delete '$path' — expected _build.fmix-stale.* pattern."
        return 1
    fi
    if ! fmix_worktree_has_cisco_cdr_app "$parent"; then
        fmix_error "SAFETY: refusing to delete '$path' — parent is not a cisco-cdr checkout."
        return 1
    fi
}

fmix_guard_worktree_subdir() {
    # Guard for destructive ops on deps/ or _build/ inside a worktree.
    # Asserts: path ends in /deps or /_build, and the parent contains mix.exs with app: :cdrcisco.
    local path="$1"
    local base parent
    base="$(basename "$path")"
    parent="$(dirname "$path")"
    if [[ "$base" != "deps" && "$base" != "_build" ]]; then
        fmix_error "SAFETY: refusing to rm '$path' — expected path ending in /deps or /_build."
        return 1
    fi
    if ! fmix_worktree_has_cisco_cdr_app "$parent"; then
        fmix_error "SAFETY: refusing to rm '$path' — parent '$parent' is not a cisco-cdr checkout."
        return 1
    fi
    return 0
}

# ---------------------------------------------------------------------------
# Template key computation
# Template key (v5) = first 16 hex of sha256 over:
#   resolved BEAM ABI + dependency declarations/resolution + local dependency
#   source inputs + a digest of priv/repo/migrations (names and contents) +
#   uname -sm.
# ---------------------------------------------------------------------------

fmix_migrations_digest() {
    # API-3576: a shared template that outlives a migration change is stale in
    # a way "0 pending migrations" can never reveal, because Ecto compares
    # versions, not contents. A migration edited in place (or a migration whose
    # body delegates to code that changed beside it) keeps its version while the
    # schema it produces moves on. Hashing every migration's relative name and
    # content makes any such change a new key, so the old template is simply
    # never selected. Emits a deterministic, path-relative manifest on stdout.
    local worktree="$1" dir listing file
    local -a files=()
    dir="$worktree/priv/repo/migrations"
    if [[ ! -d "$dir" ]]; then
        printf 'migrations:none\n'
        return 0
    fi
    listing="$(mktemp)" || return 1
    if ! find "$dir" -type f -print 2>/dev/null | LC_ALL=C sort >"$listing"; then
        rm -f "$listing"
        return 1
    fi
    while IFS= read -r file; do
        files+=("$file")
    done <"$listing"
    rm -f "$listing"
    printf 'migrations:v1\n'
    (( ${#files[@]} > 0 )) || return 0
    # Batched hashing keeps this to a handful of processes even for the
    # ~1000 migrations of a mature repository. Paths are made relative so the
    # digest does not depend on where the worktree lives.
    fmix_hash_file_batches "${files[@]}" | awk -v prefix="$dir/" '
        {
            digest = $1
            $1 = ""
            sub(/^ +/, "")
            if (index($0, prefix) == 1) $0 = substr($0, length(prefix) + 1)
            printf "migration:%s\t%s\n", $0, digest
        }' | LC_ALL=C sort
    [[ "${PIPESTATUS[0]}" == "0" && "${PIPESTATUS[1]}" == "0" ]]
}

fmix_compute_template_key() {
    fmix_template_key_manifest_hash "$1" fmix-template-key-v5 1
}

# FMix <= 2.7.9 addressed templates and stamped sessions with the v4 key, which
# had no migrations digest. Kept only so artifact adoption can prove a session
# stamped under v4 still describes the exact same non-migration inputs.
fmix_compute_legacy_template_key_v4() {
    fmix_template_key_manifest_hash "$1" fmix-template-key-v4 0
}

fmix_template_key_manifest_hash() {
    # The template caches compiled dependencies and an application baseline.
    # mix.lock alone is insufficient: path dependencies and dependency options
    # can change in mix.exs without producing a lockfile delta.
    #
    # Do NOT hash config/config.exs or config/test.exs here: on a shared,
    # actively-developed checkout those files change constantly (branch
    # switches, agent edits, compile-time config providers), which flipped the
    # key on nearly every run -> permanent mismatch -> reclone + full recompile
    # every time, defeating the entire cache. Config does not change which deps
    # compile; Mix's own compile manifest already tracks Application.compile_env
    # and recompiles config-dependent APP modules after the post-clone
    # `mix compile`. Database selection uses the separate migration-content
    # manifest below and never includes wall-clock dates.
    local worktree="$1" key_tag="$2" with_migrations="$3"
    local key toolchain_identity manifest rc
    toolchain_identity="${FMIX_TOOLCHAIN_IDENTITY:-}"
    if [[ -z "$toolchain_identity" ]]; then
        toolchain_identity="$(fmix_resolved_toolchain_identity "$worktree")" || return 1
    fi
    manifest="$(mktemp)" || return 1
    (
        printf '%s\n' "$key_tag"
        printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
        printf '%s\n' "$toolchain_identity"
        for f in .tool-versions mix.exs mix.lock; do
            if [[ -f "$worktree/$f" ]]; then
                printf 'file=%s\n' "$f"
                cat "$worktree/$f"
            else
                printf 'MISSING:%s\n' "$f"
            fi
        done
        for dir in vendor dev_tools; do
            if [[ -d "$worktree/$dir" ]]; then
                fmix_stable_seed_hash_tree "$worktree" "$dir" || return 1
            else
                printf 'MISSING:%s\n' "$dir"
            fi
        done
        fmix_stable_seed_path_dependency_manifests "$worktree" || return 1
        if [[ "$with_migrations" == "1" ]]; then
            fmix_migrations_digest "$worktree" || return 1
        fi
    ) >"$manifest"
    rc=$?
    if (( rc != 0 )); then
        rm -f "$manifest"
        return "$rc"
    fi
    key="$(fmix_hash_stdin <"$manifest")"
    rc=$?
    rm -f "$manifest"
    (( rc == 0 )) || return "$rc"
    [[ "$key" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s\n' "${key:0:16}"
}

# Compatibility reader for worktree provenance written by FMix 1.4.x. This is
# deliberately not used to address new templates: it exists only so a storage
# key schema upgrade can prove that already-compiled, worktree-local artifacts
# still describe the exact same declared inputs.
fmix_compute_legacy_template_key_v2() {
    local worktree="$1" key
    key="$(
        {
            printf 'fmix-template-key-v2\n'
            printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
            for f in .tool-versions mix.lock; do
                if [[ -f "$worktree/$f" ]]; then
                    cat "$worktree/$f"
                else
                    printf 'MISSING:%s\n' "$f"
                fi
            done
        } | fmix_hash_stdin
    )"
    printf '%s\n' "${key:0:16}"
}

# ---------------------------------------------------------------------------
# Stable dependency seed identity (v1)
# ---------------------------------------------------------------------------

fmix_validate_stable_base() {
    [[ "${1:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-stable$ ]]
}

fmix_stable_seed_dir() {
    (( $# == 3 )) || return 1
    printf '%s/stable-seeds/v1/cisco-cdr/%s/%s/%s\n' \
        "$FMIX_HOME" "$1" "$2" "$3"
}

fmix_stable_seed_hash_file() {
    local root="$1" relative="$2" file="$1/$2"
    [[ -f "$file" && -r "$file" ]] || return 1
    printf 'file:%s\n' "$relative"
    printf 'content:'
    fmix_hash_stdin <"$file"
}

fmix_stable_seed_hash_tree() {
    local root="$1" relative="$2" tree="$1/$2" listing file path
    [[ -d "$tree" && -r "$tree" && -x "$tree" ]] || return 1
    if [[ -n "$(find "$tree" -type l -print -quit 2>/dev/null)" ]]; then
        fmix_error "Stable seed compatibility does not support symlinks under $relative."
        return 1
    fi

    listing="$(mktemp)" || return 1
    if ! find "$tree" -type f -print 2>/dev/null | LC_ALL=C sort >"$listing"; then
        rm -f "$listing"
        return 1
    fi
    printf 'tree:%s\n' "$relative"
    while IFS= read -r file; do
        case "$file" in
            "$root/"*) path="${file#"$root/"}" ;;
            *)
                rm -f "$listing"
                return 1
                ;;
        esac
        fmix_stable_seed_hash_file "$root" "$path" || {
            rm -f "$listing"
            return 1
        }
    done <"$listing"
    rm -f "$listing"
}

fmix_stable_seed_hash_optional_tree() {
    local root="$1" relative="$2" tree="$1/$2"
    if [[ ! -e "$tree" && ! -L "$tree" ]]; then
        printf 'tree:%s\n' "$relative"
        printf 'state:absent\n'
        return 0
    fi
    fmix_stable_seed_hash_tree "$root" "$relative"
}

fmix_stable_seed_path_dependency_manifests() {
    local worktree="$1" source declared_count literal_count path target manifest found
    local worktree_real target_real current component
    local -a paths=() components=()
    [[ -f "$worktree/mix.exs" && -r "$worktree/mix.exs" ]] || return 1
    worktree_real="$(fmix_realpath "$worktree")" || return 1
    source="$(sed '/^[[:space:]]*#/d' "$worktree/mix.exs" | tr '\n' ' ')"
    declared_count="$(printf '%s' "$source" \
        | grep -oE '(^|[^[:alnum:]_])path[[:space:]]*:' 2>/dev/null \
        | wc -l | tr -d ' ')"
    while IFS= read -r path; do
        [[ -n "$path" ]] && paths+=("$path")
    done < <(
        printf '%s' "$source" \
            | grep -oE '(^|[^[:alnum:]_])path[[:space:]]*:[[:space:]]*"[^"\\]*"' 2>/dev/null \
            | sed -E 's/^.*path[[:space:]]*:[[:space:]]*"([^"]*)"$/\1/'
    )
    literal_count="${#paths[@]}"
    if (( declared_count != literal_count )); then
        fmix_error "Stable seed compatibility could not parse every path dependency."
        return 1
    fi

    if (( literal_count == 0 )); then
        printf 'path-dependencies:none\n'
        return 0
    fi

    for path in "${paths[@]}"; do
        if [[ "$path" == /* ]]; then
            fmix_error "Stable seed compatibility rejects absolute path dependencies."
            return 1
        fi
        target="$worktree_real/$path"
        [[ -d "$target" && -r "$target" && -x "$target" ]] || return 1
        target_real="$(fmix_realpath "$target")" || return 1
        case "$target_real" in
            "$worktree_real"/*) ;;
            *)
                fmix_error "Stable seed compatibility rejects path dependencies outside the worktree."
                return 1
                ;;
        esac
        components=()
        IFS='/' read -r -a components <<<"$path"
        current="$worktree_real"
        for component in "${components[@]}"; do
            case "$component" in
                ""|.) ;;
                ..) current="$(dirname "$current")" ;;
                *)
                    current="$current/$component"
                    if [[ -L "$current" ]]; then
                        fmix_error "Stable seed compatibility rejects symlinked path dependencies."
                        return 1
                    fi
                    ;;
            esac
        done
        printf 'path-dependency:%s\n' "$path"
        found=0
        for manifest in .tool-versions mix.exs mix.lock rebar.config rebar.lock \
            Cargo.toml Cargo.lock Makefile; do
            if [[ -e "$target_real/$manifest" ]]; then
                [[ ! -L "$target_real/$manifest" ]] || return 1
                [[ -f "$target_real/$manifest" && -r "$target_real/$manifest" ]] || return 1
                found=1
                printf 'path-manifest:%s/%s\n' "$path" "$manifest"
                printf 'content:'
                fmix_hash_stdin <"$target_real/$manifest" || return 1
            fi
        done
        (( found == 1 )) || return 1
        # Compiled path-dependency artifacts can change when source changes
        # even if their manifest does not. Hash the contained source tree by
        # its worktree-relative name so the shared cache remains portable.
        fmix_stable_seed_hash_tree "$worktree_real" "$path" || return 1
    done
}

fmix_stable_seed_environment() {
    local worktree="$1" name value discovered
    discovered="$(fmix_discovered_environment_names "$worktree/mix.exs")"

    fmix_emit_environment_fingerprint MIX_ENV test
    fmix_emit_environment_fingerprint MIX_BUILD_PATH _build
    fmix_emit_environment_fingerprint MIX_DEPS_PATH deps
    fmix_emit_environment_fingerprint MIX_TARGET host
    printf '%s\n' "$discovered" | sed '/^$/d' | LC_ALL=C sort -u | while IFS= read -r name; do
        case "$name" in
            MIX_ENV|MIX_BUILD_PATH|MIX_DEPS_PATH|MIX_TARGET) ;;
            *)
                value="$(fmix_environment_value "$name")"
                fmix_emit_environment_fingerprint "$name" "$value"
                ;;
        esac
    done
}

fmix_stable_seed_compatibility() {
    local worktree="${1:-}" manifest rc toolchain_identity
    [[ -d "$worktree" && -r "$worktree" && -x "$worktree" ]] || return 1
    if [[ -n "${MIX_TARGET+x}" && "$MIX_TARGET" != "host" ]]; then
        return 1
    fi
    [[ -f "$worktree/.tool-versions" && -r "$worktree/.tool-versions" ]] || return 1
    [[ -f "$worktree/mix.exs" && -r "$worktree/mix.exs" ]] || return 1
    [[ -f "$worktree/mix.lock" && -r "$worktree/mix.lock" ]] || return 1
    [[ -d "$worktree/vendor" && -r "$worktree/vendor" && -x "$worktree/vendor" ]] || return 1
    toolchain_identity="${FMIX_TOOLCHAIN_IDENTITY:-}"
    if [[ -z "$toolchain_identity" ]]; then
        toolchain_identity="$(fmix_resolved_toolchain_identity "$worktree")" || return 1
    fi

    manifest="$(mktemp)" || return 1
    (
        printf 'fmix-stable-seed-compatibility-%s\n' "$FMIX_STABLE_SEED_COMPAT_VERSION"
        printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
        printf '%s\n' "$toolchain_identity"
        fmix_stable_seed_hash_file "$worktree" .tool-versions || return 1
        fmix_stable_seed_hash_file "$worktree" mix.exs || return 1
        fmix_stable_seed_hash_file "$worktree" mix.lock || return 1
        fmix_stable_seed_hash_tree "$worktree" vendor || return 1
        fmix_stable_seed_hash_optional_tree "$worktree" dev_tools || return 1
        fmix_stable_seed_path_dependency_manifests "$worktree" || return 1
        fmix_stable_seed_environment "$worktree" || return 1
    ) >"$manifest"
    rc=$?
    if (( rc != 0 )); then
        rm -f "$manifest"
        return "$rc"
    fi
    fmix_hash_stdin <"$manifest"
    rc=$?
    rm -f "$manifest"
    return "$rc"
}

# A reconciliation lane is deliberately broader than an exact dependency
# fingerprint. It admits only artifacts built for the same host ABI, complete
# Erlang/Elixir toolchain, Mix target, and dependency-sensitive environment.
# mix.exs/mix.lock/vendor/path-dependency content remain in the exact key and
# are intentionally excluded here: a different exact key may seed a producer,
# but can never be reported as a consumer hit.
fmix_dependency_lane_fingerprint() {
    local worktree="${1:-}" manifest rc toolchain_identity
    [[ -d "$worktree" && -f "$worktree/mix.exs" ]] || return 1
    if [[ -n "${MIX_TARGET+x}" && "$MIX_TARGET" != "host" ]]; then
        return 1
    fi
    toolchain_identity="${FMIX_TOOLCHAIN_IDENTITY:-}"
    if [[ -z "$toolchain_identity" ]]; then
        toolchain_identity="$(fmix_resolved_toolchain_identity "$worktree")" || return 1
    fi

    manifest="$(mktemp)" || return 1
    (
        printf 'fmix-dependency-lane-%s\n' "$FMIX_DEPENDENCY_LANE_VERSION"
        printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
        printf '%s\n' "$toolchain_identity"
        fmix_emit_environment_fingerprint MIX_ENV test
        fmix_emit_environment_fingerprint MIX_BUILD_PATH _build
        fmix_emit_environment_fingerprint MIX_DEPS_PATH deps
        fmix_emit_environment_fingerprint MIX_TARGET host
        fmix_dependency_environment "$worktree"
    ) >"$manifest"
    rc=$?
    if (( rc != 0 )); then
        rm -f "$manifest"
        return "$rc"
    fi
    fmix_hash_stdin <"$manifest"
    rc=$?
    rm -f "$manifest"
    return "$rc"
}

fmix_artifact_v2_managed_entrypoint() {
    local py_bin runner managed_home="$FMIX_HOME"
    if [[ "${FMIX_SELF_TEST_MANAGED_REEXEC:-0}" == "1" \
        && " ${FUNCNAME[*]} " == *" cmd_self_test "* \
        && -n "${FMIX_SELF_TEST_RUNNER_HOME:-}" ]]; then
        managed_home="$FMIX_SELF_TEST_RUNNER_HOME"
    fi
    py_bin="$(fmix_python_bin)" || return 1
    runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || return 1
    "$py_bin" -I -B - "$HOME" "$managed_home" "$0" "$runner" <<'PY'
import hashlib,os,stat,sys
user_home,fmix_home,entrypoint,runner=sys.argv[1:]
uid=os.getuid(); euid=os.geteuid(); user_home=os.path.abspath(user_home); fmix_home=os.path.abspath(fmix_home)
def reject(reason):
    print(reason,file=sys.stderr)
    raise SystemExit(1)
if uid==0 or euid!=uid: reject("privileged_cleaner_forbidden")
entrypoint=os.path.abspath(entrypoint)
if os.path.realpath(user_home)!=user_home or os.path.realpath(fmix_home)!=fmix_home:
    reject("noncanonical_managed_home")
known={user_home+"/.local/bin/fmix",user_home+"/.local/share/fmix/bin/fmix"}
custom=os.environ.get("FMIX_INSTALL_DIR")
if custom:
    custom=os.path.abspath(custom)
    if os.path.commonpath((user_home,custom))!=user_home: raise SystemExit(1)
    known.add(os.path.join(custom,"fmix"))
if entrypoint not in known and entrypoint!=runner: reject("unrecognized_managed_entrypoint")
paths=[]
for path in sorted(known):
    if not os.path.lexists(path): continue
    parent=os.path.dirname(path)
    if os.path.commonpath((user_home,parent))!=user_home: raise SystemExit(1)
    rel=os.path.relpath(parent,user_home); current=user_home
    for part in (() if rel=="." else rel.split(os.sep)):
        current=os.path.join(current,part); s=os.lstat(current)
        if not stat.S_ISDIR(s.st_mode) or stat.S_ISLNK(s.st_mode) or s.st_uid!=uid or s.st_mode&0o022:
            reject("unsafe_launcher_parent")
    link=os.lstat(path)
    if not stat.S_ISLNK(link.st_mode) or link.st_uid!=uid or link.st_nlink!=1 or os.path.realpath(path)!=runner:
        reject("managed_launcher_mismatch")
    paths.append(path)
if entrypoint not in paths and (entrypoint!=runner or not paths):
    reject("managed_launcher_missing")
fd=os.open(runner,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0))
try:
    s=os.fstat(fd)
    if not stat.S_ISREG(s.st_mode) or s.st_uid!=uid or s.st_nlink!=1 or s.st_mode&0o222 or not s.st_mode&0o111 or s.st_size>4*1024*1024:
        reject("unsafe_runner_identity")
    parent=os.open(fmix_home+"/runtime",os.O_RDONLY|os.O_DIRECTORY|getattr(os,"O_NOFOLLOW",0))
    try:
        runtime=os.fstat(parent)
        if runtime.st_uid!=uid or runtime.st_dev!=s.st_dev or runtime.st_mode&0o022:
            reject("unsafe_runner_runtime")
    finally: os.close(parent)
    h=hashlib.sha256()
    for block in iter(lambda: os.read(fd,65536),b""): h.update(block)
    if runner!=fmix_home+"/runtime/fmix-"+h.hexdigest():
        reject("managed_launcher_runner_mismatch")
finally: os.close(fd)
PY
}
fmix_managed_publication_gate() {
    # Shared-cache publication requires the managed install (fmix install).
    # An npm/mise-linked runner is refused. Report the validator's reason and
    # the remediation, so the hold is never misattributed to disk capacity.
    local reason
    reason="$(fmix_artifact_v2_managed_entrypoint 2>&1)" && return 0
    fmix_warn "Shared ${1:-artifact} publication is held: managed launcher check failed (${reason:-unknown})."
    fmix_warn "Run 'fmix install' and invoke fmix as \$HOME/.local/bin/fmix so shared templates and dependency artifacts can publish."
    return 1
}

fmix_artifact_v2_producer_runner_is_known() {
    local digest="${1:-}" py_bin
    [[ "$digest" =~ ^[0-9a-f]{64}$ ]] || return 1
    py_bin="$(fmix_python_bin)" || return 1
    "$py_bin" -I -B - "$FMIX_HOME" "$digest" <<'PY'
import hashlib,os,stat,sys
home,digest=sys.argv[1:]; runtime=home+"/runtime"; path=runtime+"/fmix-"+digest
try:
    d=os.lstat(runtime)
    if not stat.S_ISDIR(d.st_mode) or stat.S_ISLNK(d.st_mode) or d.st_uid!=os.getuid(): raise ValueError()
    with os.fdopen(os.open(path,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0)),"rb") as f:
        s=os.fstat(f.fileno())
        if not stat.S_ISREG(s.st_mode) or s.st_uid!=os.getuid() or s.st_nlink!=1 or s.st_mode&0o222 or not s.st_mode&0o111 or s.st_size>4*1024*1024: raise ValueError()
        h=hashlib.sha256()
        for block in iter(lambda:f.read(65536),b""): h.update(block)
        if h.hexdigest()!=digest: raise ValueError()
except (OSError,ValueError): raise SystemExit(1)
PY
}
fmix_with_reused_artifact_lease() {
    local lock_name="${1:-}" operation="${2:-}" index
    shift 2
    if index="$(fmix_lock_find_index "$lock_name")"; then
        kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
        "$operation" "$@"
    else
        fmix_with_artifact_lease "$lock_name" "$operation" "$@"
    fi
}
fmix_artifact_v2_prepare_directory() {
    local rel="${1:-}" py_bin
    [[ "$rel" == artifacts/v2/templates || "$rel" == quarantine/artifacts-v2/templates || "$rel" == quarantine/artifacts-v2/dependencies || "$rel" == quarantine/artifacts-v2/app-compiles || "$rel" == artifact-access/v2/templates || "$rel" =~ ^artifacts/v2/dependencies/[0-9a-f]{64}$ || "$rel" =~ ^artifact-access/v2/dependencies/[0-9a-f]{64}$ || "$rel" =~ ^artifacts/v2/app-compiles/[0-9a-f]{64}$ || "$rel" =~ ^artifact-access/v2/app-compiles/[0-9a-f]{64}$ ]] || return 1
    py_bin="$(fmix_python_bin)" || return 1
    "$py_bin" -I -B - "$FMIX_HOME" "$rel" <<'PY'
import os,stat,sys
home,rel=sys.argv[1:]; flags=os.O_RDONLY|os.O_DIRECTORY|getattr(os,"O_NOFOLLOW",0)
if os.getuid()==0 or os.geteuid()!=os.getuid() or os.path.realpath(home)!=home: raise SystemExit(1)
fd=os.open(home,flags)
try:
    root=os.fstat(fd)
    if root.st_uid!=os.getuid(): raise ValueError()
    for part in rel.split("/"):
        try: os.mkdir(part,0o700,dir_fd=fd)
        except FileExistsError: pass
        child=os.open(part,flags,dir_fd=fd); info=os.fstat(child)
        if info.st_uid!=os.getuid() or info.st_dev!=root.st_dev or not stat.S_ISDIR(info.st_mode): os.close(child); raise ValueError()
        os.close(fd); fd=child
    os.fsync(fd)
finally: os.close(fd)
PY
}
fmix_dependency_artifact_v2_dir() {
    local lane="${1:-}" exact="${2:-}"
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s/artifacts/v2/dependencies/%s/%s\n' "$FMIX_HOME" "$lane" "$exact"
}
fmix_app_compile_artifact_v2_dir() {
    # The app-compile pool is v2-only: exact keys are content-exact compile
    # fingerprints (fmix_compute_compile_fingerprint) and lanes are dependency
    # lane fingerprints (fmix_dependency_lane_fingerprint).
    local lane="${1:-}" exact="${2:-}"
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s/artifacts/v2/app-compiles/%s/%s\n' "$FMIX_HOME" "$lane" "$exact"
}
fmix_dependency_artifact_legacy_dir() {
    local lane="${1:-}" exact="${2:-}"
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s/dependency-artifacts/v1/%s/%s\n' "$FMIX_HOME" "$lane" "$exact"
}
fmix_dependency_artifact_dir() {
    local lane="${1:-}" exact="${2:-}" kind="${3:-dependency}" v2
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    [[ "$kind" == "dependency" || "$kind" == "app" ]] || return 1
    if [[ "$kind" == "app" ]]; then
        fmix_app_compile_artifact_v2_dir "$lane" "$exact"
        return $?
    fi
    v2="$(fmix_dependency_artifact_v2_dir "$lane" "$exact")" || return 1
    if [[ -e "$v2" || -L "$v2" ]]; then printf '%s\n' "$v2"
    else fmix_dependency_artifact_legacy_dir "$lane" "$exact"; fi
}

fmix_touch_dependency_artifact_access() {
    # Access timestamps live outside the CAS and land via one atomic
    # mktemp+mv, so a lease is never acquired just to refresh one. When the
    # caller already holds the exact artifact lease, keep the fail-closed
    # keeper check (a dead keeper is corrupt hold state) and write through
    # the same atomic path.
    local lane="${1:-}" exact="${2:-}" lock_name index
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    lock_name="dependency-artifact-${lane:0:16}-${exact:0:16}"
    if index="$(fmix_lock_find_index "$lock_name")"; then
        kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
    fi
    _fmix_touch_dependency_artifact_access_write "$lane" "$exact"
}

_fmix_touch_dependency_artifact_access_write() {
    local lane="${1:-}" exact="${2:-}" root access tmp artifact
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    artifact="$FMIX_HOME/artifacts/v2/dependencies/$lane/$exact"
    if [[ -e "$artifact" || -L "$artifact" ]]; then
        fmix_artifact_v2_managed_entrypoint || return 1
        root="$FMIX_HOME/artifact-access/v2/dependencies/$lane"
        fmix_artifact_v2_prepare_directory "artifact-access/v2/dependencies/$lane" || return 1
    else
        root="$FMIX_HOME/dependency-artifact-access/$lane"
        mkdir -p "$root" || return 1
    fi
    access="$root/$exact"
    tmp="$(mktemp "${access}.tmp.XXXXXX")" || return 1
    printf '%s\n' "$(fmix_now)" >"$tmp" || { rm -f "$tmp"; return 1; }
    mv "$tmp" "$access" || { rm -f "$tmp"; return 1; }
}

fmix_touch_app_compile_artifact_access() {
    # Access timestamps live outside the CAS and land via one atomic
    # mktemp+mv, so a lease is never acquired just to refresh one. When the
    # caller already holds the exact artifact lease, keep the fail-closed
    # keeper check (a dead keeper is corrupt hold state) and write through
    # the same atomic path.
    local lane="${1:-}" exact="${2:-}" lock_name index
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    lock_name="app-compile-${lane:0:16}-${exact:0:16}"
    if index="$(fmix_lock_find_index "$lock_name")"; then
        kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
    fi
    _fmix_touch_app_compile_artifact_access_write "$lane" "$exact"
}

_fmix_touch_app_compile_artifact_access_write() {
    # Mutable access timestamps stay outside the immutable CAS, mirroring the
    # dependency pool's outside-CAS access pattern.
    local lane="${1:-}" exact="${2:-}" root access tmp artifact
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    artifact="$FMIX_HOME/artifacts/v2/app-compiles/$lane/$exact"
    if [[ -e "$artifact" || -L "$artifact" ]]; then
        fmix_artifact_v2_managed_entrypoint || return 1
        root="$FMIX_HOME/artifact-access/v2/app-compiles/$lane"
        fmix_artifact_v2_prepare_directory "artifact-access/v2/app-compiles/$lane" || return 1
    else
        return 1
    fi
    access="$root/$exact"
    tmp="$(mktemp "${access}.tmp.XXXXXX")" || return 1
    printf '%s\n' "$(fmix_now)" >"$tmp" || { rm -f "$tmp"; return 1; }
    mv "$tmp" "$access" || { rm -f "$tmp"; return 1; }
}

fmix_dependency_artifact_manifest_digest() {
    local root="${1:-}" output="${2:-}" py_bin tmp digest
    (( $# == 1 || $# == 2 )) || return 1
    [[ -d "$root/deps" && -d "$root/_build/test/lib" ]] || return 1
    py_bin="$(fmix_python_bin)"
    tmp="${output:-$(mktemp)}" || return 1
    if ! "$py_bin" - "$root" >"$tmp" <<'PY'
import hashlib
import os
import sys

root = os.path.realpath(sys.argv[1])
for top in ("deps", "_build"):
    start = os.path.join(root, top)
    if not os.path.isdir(start) or os.path.islink(start):
        raise SystemExit(1)
    for current, dirs, files in os.walk(start, topdown=True, followlinks=False):
        dirs.sort()
        files.sort()
        for name in list(dirs) + files:
            path = os.path.join(current, name)
            rel = os.path.relpath(path, root)
            info = os.lstat(path)
            if os.path.islink(path):
                raise SystemExit(1)
            if os.path.isdir(path):
                print(f"D\t{rel}\t-")
            elif os.path.isfile(path):
                value = hashlib.sha256()
                with open(path, "rb") as handle:
                    for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                        value.update(chunk)
                print(f"F\t{rel}\t{info.st_size}\t{value.hexdigest()}")
            else:
                raise SystemExit(1)
PY
    then
        [[ -n "$output" ]] || rm -f "$tmp"
        return 1
    fi
    digest="$(fmix_hash_stdin <"$tmp")" || {
        [[ -n "$output" ]] || rm -f "$tmp"
        return 1
    }
    [[ -n "$output" ]] || rm -f "$tmp"
    printf '%s\n' "$digest"
}

fmix_app_compile_artifact_manifest_digest() {
    # fmix_dependency_artifact_manifest_digest-equivalent digest for the
    # application-only transport. Rows cover every node below _build (never
    # _build itself), and the payload is strictly link-free like dependency
    # children: the Mix app priv link is materialized at publication
    # (fmix_template_materialize_app_priv) so a shared generation never
    # retains a host/worktree-bound link.
    local root="${1:-}" output="${2:-}" py_bin tmp digest
    (( $# == 1 || $# == 2 )) || return 1
    [[ -d "$root/_build/test/lib" ]] || return 1
    py_bin="$(fmix_python_bin)"
    tmp="${output:-$(mktemp)}" || return 1
    if ! "$py_bin" - "$root" >"$tmp" <<'PY'
import hashlib
import os
import sys

root = os.path.realpath(sys.argv[1])
start = os.path.join(root, "_build")
if not os.path.isdir(start) or os.path.islink(start):
    raise SystemExit(1)
for current, dirs, files in os.walk(start, topdown=True, followlinks=False):
    dirs.sort()
    files.sort()
    for name in list(dirs) + files:
        path = os.path.join(current, name)
        rel = os.path.relpath(path, root)
        info = os.lstat(path)
        if os.path.islink(path):
            raise SystemExit(1)
        if os.path.isdir(path):
            print(f"D\t{rel}\t-")
        elif os.path.isfile(path):
            value = hashlib.sha256()
            with open(path, "rb") as handle:
                for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                    value.update(chunk)
            print(f"F\t{rel}\t{info.st_size}\t{value.hexdigest()}")
        else:
            raise SystemExit(1)
PY
    then
        [[ -n "$output" ]] || rm -f "$tmp"
        return 1
    fi
    digest="$(fmix_hash_stdin <"$tmp")" || {
        [[ -n "$output" ]] || rm -f "$tmp"
        return 1
    }
    [[ -n "$output" ]] || rm -f "$tmp"
    printf '%s\n' "$digest"
}

fmix_dependency_artifact_meta_matches() {
    local artifact="${1:-}" expected_lane="${2:-}" expected_exact="${3:-}"
    local py_bin validation_output
    (( $# == 3 )) || return 1
    py_bin="$(fmix_python_bin)"
    validation_output="$("$py_bin" - "$artifact/meta.json" \
        "$FMIX_DEPENDENCY_ARTIFACT_SCHEMA" "$expected_lane" "$expected_exact" <<'PY'
import json
import re
import sys

def strict_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate key")
        result[key] = value
    return result

path, schema, lane, exact = sys.argv[1:]
try:
    with open(path, encoding="utf-8") as handle:
        data = json.load(handle, object_pairs_hook=strict_object)
except (OSError, ValueError, json.JSONDecodeError):
    raise SystemExit(1)

is_v2 = "/artifacts/v2/dependencies/" in path
required = {
    "schema", "lane", "dependency_fingerprint", "producer_sha",
    "source_clean", "manifest_sha256", "built_at",
}
if is_v2:
    required |= {"producer_runner_sha256", "consumer_protocol"}
if set(data) != required:
    raise SystemExit(1)
if data["schema"] != ("2" if is_v2 else schema) or data["lane"] != lane:
    raise SystemExit(1)
if data["dependency_fingerprint"] != exact:
    raise SystemExit(1)
if not re.fullmatch(r"[0-9a-f]{40}", data["producer_sha"]):
    raise SystemExit(1)
if data["source_clean"] not in ("true", "false"):
    raise SystemExit(1)
if not re.fullmatch(r"[0-9a-f]{64}", data["manifest_sha256"]):
    raise SystemExit(1)
if not isinstance(data["built_at"], str) or not data["built_at"]:
    raise SystemExit(1)
if is_v2 and (not re.fullmatch(r"[0-9a-f]{64}", data["producer_runner_sha256"])
        or data["consumer_protocol"] != "fmix-native-artifacts.v2"):
    raise SystemExit(1)
PY
)" || return 1
    if [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
        local producer_runner_sha
        producer_runner_sha="$(fmix_read_state "$artifact/meta.json" producer_runner_sha256)" || return 1
        fmix_artifact_v2_producer_runner_is_known "$producer_runner_sha" || return 1
    fi
}

fmix_dependency_artifact_quick_ready() {
    # O(1) maintenance probe for a publisher that already completed a full
    # immutable verification. Consumers never use this shortcut: exact restore
    # still verifies the complete manifest before installing any artifact.
    local artifact="${1:-}" lane="${2:-}" exact="${3:-}"
    (( $# == 3 )) || return 1
    [[ -d "$artifact" && ! -L "$artifact" && ! -w "$artifact" ]] || return 1
    [[ -d "$artifact/deps" && ! -L "$artifact/deps" ]] || return 1
    [[ -d "$artifact/_build/test/lib" \
        && ! -L "$artifact/_build" \
        && ! -L "$artifact/_build/test" \
        && ! -L "$artifact/_build/test/lib" ]] || return 1
    if [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
        fmix_artifact_v2_managed_entrypoint || return 1
        local producer_runner_sha
        producer_runner_sha="$(fmix_read_state "$artifact/meta.json" producer_runner_sha256)" || return 1
        fmix_artifact_v2_producer_runner_is_known "$producer_runner_sha" || return 1
    fi
    [[ -f "$artifact/meta.json" && ! -L "$artifact/meta.json" ]] || return 1
    [[ -f "$artifact/manifest.tsv" && ! -L "$artifact/manifest.tsv" ]] || return 1
    [[ -f "$artifact/manifest.sha256" && ! -L "$artifact/manifest.sha256" ]] || return 1
    if [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
        fmix_artifact_v2_managed_entrypoint || return 1
        fmix_dependency_artifact_verify_full "$artifact" "$lane" "$exact"
    else
        fmix_dependency_artifact_meta_matches "$artifact" "$lane" "$exact"
    fi
}

fmix_dependency_artifact_is_complete() {
    local artifact="${1:-}" lane="${2:-}" exact="${3:-}" allow_writable="${4:-0}"
    local expected recorded unexpected writable
    (( $# == 3 || $# == 4 )) || return 1
    [[ "$allow_writable" == "0" || "$allow_writable" == "1" ]] || return 1
    [[ -d "$artifact" && ! -L "$artifact" ]] || return 1
    [[ -f "$artifact/meta.json" && ! -L "$artifact/meta.json" ]] || return 1
    [[ -f "$artifact/manifest.tsv" && ! -L "$artifact/manifest.tsv" ]] || return 1
    [[ -f "$artifact/manifest.sha256" && ! -L "$artifact/manifest.sha256" ]] || return 1
    unexpected="$(find "$artifact" -mindepth 1 -maxdepth 1 \
        ! -name deps ! -name _build ! -name meta.json \
        ! -name manifest.tsv ! -name manifest.sha256 -print -quit 2>/dev/null)" \
        || return 1
    [[ -z "$unexpected" ]] || return 1
    unexpected="$(find "$artifact/_build" -mindepth 1 -maxdepth 1 \
        ! -name test -print -quit 2>/dev/null)" || return 1
    [[ -z "$unexpected" ]] || return 1
    unexpected="$(find "$artifact/_build/test" -mindepth 1 -maxdepth 1 \
        ! -name lib -print -quit 2>/dev/null)" || return 1
    [[ -z "$unexpected" ]] || return 1
    fmix_stable_seed_artifacts_are_safe \
        "$artifact/deps" "$artifact/_build/test/lib" 0 || return 1
    fmix_dependency_artifact_meta_matches "$artifact" "$lane" "$exact" || return 1
    IFS= read -r expected <"$artifact/manifest.sha256"
    recorded="$(fmix_read_state "$artifact/meta.json" manifest_sha256)"
    [[ "$expected" =~ ^[0-9a-f]{64}$ && "$recorded" == "$expected" ]] || return 1
    if [[ "$allow_writable" == "0" ]]; then
        writable="$(find "$artifact" ! -type l -perm -u+w -print -quit 2>/dev/null)" || return 1
        [[ -z "$writable" ]] || return 1
    fi
}

fmix_dependency_artifact_verify_full_unleased() {
    local artifact="${1:-}" lane="${2:-}" exact="${3:-}" expected actual
    fmix_dependency_artifact_is_complete "$artifact" "$lane" "$exact" || return 1
    IFS= read -r expected <"$artifact/manifest.sha256"
    actual="$(fmix_dependency_artifact_manifest_digest "$artifact")" || return 1
    [[ "$actual" == "$expected" ]]
}

fmix_dependency_artifact_cas_read_identity() {
    # meta.json + manifest.sha256 identity snapshot for lock-free v2 reads
    # (see the retirement engine's identity() audit fields). A mid-read
    # quarantine rename or replacement publication changes it; missing
    # metadata fails closed as an ordinary miss.
    local artifact="${1:-}"
    [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]] || return 1
    fmix_stat_identity "$artifact/meta.json" || return 1
    fmix_stat_identity "$artifact/manifest.sha256" || return 1
}

fmix_dependency_artifact_verify_full() {
    local artifact="${1:-}" lane="${2:-}" exact="${3:-}" lock_name index
    local attempt before after outcome
    if [[ "$artifact" != "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
        fmix_dependency_artifact_verify_full_unleased "$@"
        return $?
    fi
    fmix_artifact_v2_managed_entrypoint || return 1
    lock_name="dependency-artifact-${lane:0:16}-${exact:0:16}"
    if index="$(fmix_lock_find_index "$lock_name")"; then
        # A mutation pipeline (install/publish/quarantine) already holds the
        # exact artifact lease: keep the serialized verify.
        kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
        fmix_dependency_artifact_verify_full_unleased "$@"
        return $?
    fi
    # Lock-free CAS read. The published tree is immutable and this read never
    # promotes or writes CAS contents, so the exact artifact lease is not
    # taken: pure readers must not queue behind a publisher's lease. After
    # validation, re-stat the meta.json / manifest.sha256 identities to
    # detect a mid-read quarantine rename or replacement publication and
    # retry once on identity change. An identity that still moves on the
    # retry fails closed as a miss.
    for attempt in 1 2; do
        before="$(fmix_dependency_artifact_cas_read_identity "$artifact")" || return 1
        outcome=1
        fmix_dependency_artifact_verify_full_unleased "$@" && outcome=0
        after="$(fmix_dependency_artifact_cas_read_identity "$artifact")" || after="missing"
        if [[ "$before" == "$after" ]]; then
            return "$outcome"
        fi
    done
    return 1
}

fmix_dependency_artifact_quarantine() {
    # Reader-observable CAS mutation: move the exact artifact into the
    # pre-computed unique quarantine destination with ONE atomic mv — a
    # single rename into the final name, no intermediate name, no copy — so
    # a concurrent lock-free reader sees complete-old or ENOENT -> ordinary
    # miss, never a torn read. Same-filesystem rename is enforced before any
    # mutation: a cross-device source fails closed instead of letting mv
    # fall back to a recursive copy. Darwin refuses a cross-parent rename of
    # a directory whose own owner-write bit is clear (see
    # fmix_template_make_readonly), so the move root alone is re-enabled for
    # owner-write immediately before the rename; the sealed contents are
    # never touched.
    local artifact="${1:-}" reason="${2:-invalid dependency artifact}"
    local destination quarantine_root source_device quarantine_device
    [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]] || return 1
    [[ -e "$artifact" || -L "$artifact" ]] || return 0
    fmix_dependency_artifact_path_is_owned "$artifact" || return 1
    quarantine_root="$FMIX_HOME/quarantine/artifacts-v2/dependencies"
    destination="$quarantine_root/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
    fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/dependencies" || return 1
    [[ ! -e "$destination" && ! -L "$destination" ]] || return 1
    source_device="$(fmix_stat_device "$artifact")" || return 1
    quarantine_device="$(fmix_stat_device "$quarantine_root")" || return 1
    [[ "$source_device" == "$quarantine_device" ]] || return 1
    if [[ "$FMIX_OS" == "Darwin" && -d "$artifact" && ! -L "$artifact" ]]; then
        chmod u+w "$artifact" || return 1
    fi
    if mv "$artifact" "$destination"; then
        fmix_warn "Quarantined dependency artifact ($reason): $destination"
        return 0
    fi
    return 1
}

fmix_app_compile_payload_is_safe() {
    # A shared application payload is strictly link-free and contains only
    # ordinary files and directories, exactly like dependency children. The
    # Mix app priv link is materialized at publication
    # (fmix_template_materialize_app_priv) before this gate runs; any other
    # link or special file is refused.
    local app_dir="${1:-}" py_bin
    (( $# == 1 )) || return 1
    [[ -d "$app_dir" && ! -L "$app_dir" ]] || return 1
    py_bin="$(fmix_python_bin)" || return 1
    "$py_bin" - "$app_dir" <<'PY'
import os
import stat
import sys

root = os.path.realpath(sys.argv[1])
if os.path.islink(sys.argv[1]):
    raise SystemExit(1)
for current, dirs, files in os.walk(root, topdown=True, followlinks=False):
    for name in list(dirs) + files:
        path = os.path.join(current, name)
        info = os.lstat(path)
        if stat.S_ISLNK(info.st_mode):
            raise SystemExit(1)
        if not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)):
            raise SystemExit(1)
PY
}

fmix_app_compile_artifact_meta_matches() {
    local artifact="${1:-}" expected_lane="${2:-}" expected_exact="${3:-}"
    local py_bin producer_runner_sha
    (( $# == 3 )) || return 1
    [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
    py_bin="$(fmix_python_bin)"
    if ! "$py_bin" - "$artifact/meta.json" "$expected_lane" "$expected_exact" <<'PY'
import json
import re
import sys

def strict_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate key")
        result[key] = value
    return result

path, lane, exact = sys.argv[1:]
try:
    with open(path, encoding="utf-8") as handle:
        data = json.load(handle, object_pairs_hook=strict_object)
except (OSError, ValueError, json.JSONDecodeError):
    raise SystemExit(1)

required = {
    "schema", "lane", "compile_fingerprint", "producer_sha",
    "source_clean", "manifest_sha256", "built_at",
    "producer_runner_sha256", "consumer_protocol",
}
if set(data) != required:
    raise SystemExit(1)
if data["schema"] != "2" or data["lane"] != lane:
    raise SystemExit(1)
if data["compile_fingerprint"] != exact:
    raise SystemExit(1)
if not re.fullmatch(r"[0-9a-f]{40}", data["producer_sha"]):
    raise SystemExit(1)
if data["source_clean"] not in ("true", "false"):
    raise SystemExit(1)
if not re.fullmatch(r"[0-9a-f]{64}", data["manifest_sha256"]):
    raise SystemExit(1)
if not isinstance(data["built_at"], str) or not data["built_at"]:
    raise SystemExit(1)
if (not re.fullmatch(r"[0-9a-f]{64}", data["producer_runner_sha256"])
        or data["consumer_protocol"] != "fmix-native-artifacts.v2"):
    raise SystemExit(1)
PY
    then
        return 1
    fi
    producer_runner_sha="$(fmix_read_state "$artifact/meta.json" producer_runner_sha256)" \
        || return 1
    fmix_artifact_v2_producer_runner_is_known "$producer_runner_sha"
}

fmix_app_compile_artifact_is_complete() {
    local artifact="${1:-}" lane="${2:-}" exact="${3:-}" allow_writable="${4:-0}"
    local expected recorded unexpected writable
    (( $# == 3 || $# == 4 )) || return 1
    [[ "$allow_writable" == "0" || "$allow_writable" == "1" ]] || return 1
    [[ -d "$artifact" && ! -L "$artifact" ]] || return 1
    [[ -f "$artifact/meta.json" && ! -L "$artifact/meta.json" ]] || return 1
    [[ -f "$artifact/manifest.tsv" && ! -L "$artifact/manifest.tsv" ]] || return 1
    [[ -f "$artifact/manifest.sha256" && ! -L "$artifact/manifest.sha256" ]] || return 1
    unexpected="$(find "$artifact" -mindepth 1 -maxdepth 1 \
        ! -name _build ! -name meta.json \
        ! -name manifest.tsv ! -name manifest.sha256 -print -quit 2>/dev/null)" \
        || return 1
    [[ -z "$unexpected" ]] || return 1
    unexpected="$(find "$artifact/_build" -mindepth 1 -maxdepth 1 \
        ! -name test -print -quit 2>/dev/null)" || return 1
    [[ -z "$unexpected" ]] || return 1
    unexpected="$(find "$artifact/_build/test" -mindepth 1 -maxdepth 1 \
        ! -name lib -print -quit 2>/dev/null)" || return 1
    [[ -z "$unexpected" ]] || return 1
    unexpected="$(find "$artifact/_build/test/lib" -mindepth 1 -maxdepth 1 \
        ! -name cdrcisco -print -quit 2>/dev/null)" || return 1
    [[ -z "$unexpected" ]] || return 1
    fmix_app_compile_payload_is_safe "$artifact/_build/test/lib/cdrcisco" || return 1
    fmix_app_compile_artifact_meta_matches "$artifact" "$lane" "$exact" || return 1
    IFS= read -r expected <"$artifact/manifest.sha256"
    recorded="$(fmix_read_state "$artifact/meta.json" manifest_sha256)"
    [[ "$expected" =~ ^[0-9a-f]{64}$ && "$recorded" == "$expected" ]] || return 1
    if [[ "$allow_writable" == "0" ]]; then
        writable="$(find "$artifact" ! -type l -perm -u+w -print -quit 2>/dev/null)" || return 1
        [[ -z "$writable" ]] || return 1
    fi
}

fmix_app_compile_artifact_verify_full_unleased() {
    local artifact="${1:-}" lane="${2:-}" exact="${3:-}" expected actual
    fmix_app_compile_artifact_is_complete "$artifact" "$lane" "$exact" || return 1
    IFS= read -r expected <"$artifact/manifest.sha256"
    actual="$(fmix_app_compile_artifact_manifest_digest "$artifact")" || return 1
    [[ "$actual" == "$expected" ]]
}

fmix_app_compile_artifact_cas_read_identity() {
    # meta.json + manifest.sha256 identity snapshot for lock-free v2 reads
    # (see the retirement engine's identity() audit fields). A mid-read
    # quarantine rename or replacement publication changes it; missing
    # metadata fails closed as an ordinary miss.
    local artifact="${1:-}"
    [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
    fmix_stat_identity "$artifact/meta.json" || return 1
    fmix_stat_identity "$artifact/manifest.sha256" || return 1
}

fmix_app_compile_artifact_verify_full() {
    local artifact="${1:-}" lane="${2:-}" exact="${3:-}" lock_name index
    local attempt before after outcome
    (( $# == 3 )) || return 1
    [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
    fmix_artifact_v2_managed_entrypoint || return 1
    lock_name="app-compile-${lane:0:16}-${exact:0:16}"
    if index="$(fmix_lock_find_index "$lock_name")"; then
        # A mutation pipeline (install/publish/quarantine) already holds the
        # exact artifact lease: keep the serialized verify.
        kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
        fmix_app_compile_artifact_verify_full_unleased "$@"
        return $?
    fi
    # Lock-free CAS read. The published tree is immutable and this read never
    # promotes or writes CAS contents, so the exact artifact lease is not
    # taken: pure readers must not queue behind a publisher's lease. After
    # validation, re-stat the meta.json / manifest.sha256 identities to
    # detect a mid-read quarantine rename or replacement publication and
    # retry once on identity change. An identity that still moves on the
    # retry fails closed as a miss.
    for attempt in 1 2; do
        before="$(fmix_app_compile_artifact_cas_read_identity "$artifact")" || return 1
        outcome=1
        fmix_app_compile_artifact_verify_full_unleased "$@" && outcome=0
        after="$(fmix_app_compile_artifact_cas_read_identity "$artifact")" || after="missing"
        if [[ "$before" == "$after" ]]; then
            return "$outcome"
        fi
    done
    return 1
}

fmix_app_compile_artifact_quick_ready() {
    # O(1) maintenance probe for a publisher that already completed a full
    # immutable verification. Consumers never use this shortcut: exact
    # installation still verifies the complete manifest first.
    local artifact="${1:-}" lane="${2:-}" exact="${3:-}" producer_runner_sha
    (( $# == 3 )) || return 1
    [[ -d "$artifact" && ! -L "$artifact" && ! -w "$artifact" ]] || return 1
    [[ -d "$artifact/_build/test/lib" \
        && ! -L "$artifact/_build" \
        && ! -L "$artifact/_build/test" \
        && ! -L "$artifact/_build/test/lib" ]] || return 1
    [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
    fmix_artifact_v2_managed_entrypoint || return 1
    producer_runner_sha="$(fmix_read_state "$artifact/meta.json" producer_runner_sha256)" \
        || return 1
    fmix_artifact_v2_producer_runner_is_known "$producer_runner_sha" || return 1
    [[ -f "$artifact/meta.json" && ! -L "$artifact/meta.json" ]] || return 1
    [[ -f "$artifact/manifest.tsv" && ! -L "$artifact/manifest.tsv" ]] || return 1
    [[ -f "$artifact/manifest.sha256" && ! -L "$artifact/manifest.sha256" ]] || return 1
    fmix_app_compile_artifact_verify_full "$artifact" "$lane" "$exact"
}

fmix_app_compile_artifact_path_is_owned() {
    # Every generation ancestor must belong to this home's lease namespace.
    local py_bin
    py_bin="$(fmix_python_bin)" || return 1
    "$py_bin" -I -B - "$FMIX_HOME" "$1" <<'PY'
import os, re, stat, sys
home, artifact = sys.argv[1:]
fd = None
try:
    if os.path.realpath(home) != home:
        raise ValueError()
    if artifact.startswith(home + "/artifacts/v2/app-compiles/"):
        suffix = artifact[len(home + "/artifacts/v2/app-compiles/"):]
        components = ("artifacts", "v2", "app-compiles", *suffix.split("/"))
    else:
        raise ValueError()
    if not re.fullmatch(r"[0-9a-f]{64}/[0-9a-f]{64}", suffix):
        raise ValueError()
    flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
    fd = os.open(home, flags)
    device = os.fstat(fd).st_dev
    if os.fstat(fd).st_uid != os.getuid():
        raise ValueError()
    for component in components:
        child = os.open(component, flags, dir_fd=fd)
        os.close(fd)
        fd = child
        info = os.fstat(fd)
        if info.st_uid != os.getuid() or info.st_dev != device or not stat.S_ISDIR(info.st_mode):
            raise ValueError()
except (OSError, ValueError):
    raise SystemExit(1)
finally:
    if fd is not None:
        os.close(fd)
PY
}

fmix_app_compile_artifact_quarantine() {
    # Reader-observable CAS mutation: move the exact artifact into the
    # pre-computed unique quarantine destination with ONE atomic mv — a
    # single rename into the final name, no intermediate name, no copy — so
    # a concurrent lock-free reader sees complete-old or ENOENT -> ordinary
    # miss, never a torn read. Same-filesystem rename is enforced before any
    # mutation: a cross-device source fails closed instead of letting mv
    # fall back to a recursive copy. Darwin refuses a cross-parent rename of
    # a directory whose own owner-write bit is clear (see
    # fmix_template_make_readonly), so the move root alone is re-enabled for
    # owner-write immediately before the rename; the sealed contents are
    # never touched.
    local artifact="${1:-}" reason="${2:-invalid app compile artifact}"
    local destination quarantine_root source_device quarantine_device
    [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
    [[ -e "$artifact" || -L "$artifact" ]] || return 0
    fmix_app_compile_artifact_path_is_owned "$artifact" || return 1
    quarantine_root="$FMIX_HOME/quarantine/artifacts-v2/app-compiles"
    destination="$quarantine_root/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
    fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/app-compiles" || return 1
    [[ ! -e "$destination" && ! -L "$destination" ]] || return 1
    source_device="$(fmix_stat_device "$artifact")" || return 1
    quarantine_device="$(fmix_stat_device "$quarantine_root")" || return 1
    [[ "$source_device" == "$quarantine_device" ]] || return 1
    if [[ "$FMIX_OS" == "Darwin" && -d "$artifact" && ! -L "$artifact" ]]; then
        chmod u+w "$artifact" || return 1
    fi
    if mv "$artifact" "$destination"; then
        fmix_warn "Quarantined app compile artifact ($reason): $destination"
        return 0
    fi
    return 1
}

fmix_stable_seed_parse_meta() {
    local seed_dir="${1:-}" meta
    meta="$seed_dir/meta.json"
    [[ -f "$meta" && -r "$meta" ]] || return 1
    awk '
        function reject() { bad = 1 }
        {
            line = $0
            sub(/^[[:space:]]+/, "", line)
            sub(/[[:space:]]+$/, "", line)
            if (line == "") next
            if (!opened) {
                if (line != "{") reject()
                opened = 1
                next
            }
            if (closed) {
                reject()
                next
            }
            if (line == "}") {
                closed = 1
                next
            }
            has_comma = (line ~ /,$/)
            if (has_comma) sub(/,$/, "", line)
            if (line !~ /^"[^"]+"[[:space:]]*:[[:space:]]*"[^"]*"$/) {
                reject()
                next
            }
            text = line
            sub(/^"/, "", text)
            quote = index(text, "\"")
            key = substr(text, 1, quote - 1)
            text = substr(text, quote + 1)
            sub(/^[[:space:]]*:[[:space:]]*"/, "", text)
            sub(/"$/, "", text)
            value = text
            if (value !~ /^[A-Za-z0-9._\/-]+$/) reject()
            if (key != "schema" && key != "base_ref" && key != "producer_ref" \
                && key != "producer_sha" && key != "compatibility") reject()
            count[key]++
            values[key] = value
            members++
            comma[members] = has_comma
        }
        END {
            if (!opened || !closed || bad || members != 5) exit 1
            for (i = 1; i < members; i++) if (!comma[i]) exit 1
            if (comma[members]) exit 1
            if (count["schema"] != 1 || count["base_ref"] != 1 \
                || count["producer_ref"] != 1 || count["producer_sha"] != 1 \
                || count["compatibility"] != 1) exit 1
            printf "%s\t%s\t%s\t%s\t%s\n", values["schema"], values["base_ref"], \
                values["producer_ref"], values["producer_sha"], values["compatibility"]
        }
    ' "$meta"
}

fmix_stable_seed_read_meta() {
    local seed_dir="${1:-}" field="${2:-}" parsed
    local schema base_ref producer_ref producer_sha compatibility extra
    case "$field" in
        schema|base_ref|producer_ref|producer_sha|compatibility) ;;
        *) return 1 ;;
    esac
    parsed="$(fmix_stable_seed_parse_meta "$seed_dir")" || return 1
    IFS=$'\t' read -r schema base_ref producer_ref producer_sha compatibility extra <<<"$parsed"
    [[ -z "${extra:-}" ]] || return 1
    case "$field" in
        schema) printf '%s\n' "$schema" ;;
        base_ref) printf '%s\n' "$base_ref" ;;
        producer_ref) printf '%s\n' "$producer_ref" ;;
        producer_sha) printf '%s\n' "$producer_sha" ;;
        compatibility) printf '%s\n' "$compatibility" ;;
    esac
}

fmix_stable_seed_source_tree_is_safe() {
    local tree="${1:-}" source_root="${2:-}" build_lib="${3:-}"
    local allowed_deps="${4:-${2:-}/deps}"
    local links link raw_target resolved_target
    (( $# == 3 || $# == 4 )) || return 1
    [[ -d "$tree" && ! -L "$tree" ]] || return 1
    links="$(find "$tree" -type l -print 2>/dev/null)" || return 1
    [[ -n "$links" ]] || return 0

    while IFS= read -r link; do
        [[ -n "$link" && -L "$link" ]] || return 1
        raw_target="$(readlink "$link" 2>/dev/null)" || return 1
        [[ -n "$raw_target" && "$raw_target" != /* ]] || return 1
        resolved_target="$(fmix_realpath "$link" 2>/dev/null)" || return 1
        [[ -e "$resolved_target" ]] || return 1
        case "$resolved_target" in
            "$build_lib/cdrcisco"|"$build_lib/cdrcisco"/*) return 1 ;;
            "$allowed_deps"|"$allowed_deps"/*|\
            "$source_root/vendor"|"$source_root/vendor"/*|\
            "$source_root/dev_tools"|"$source_root/dev_tools"/*|\
            "$build_lib"|"$build_lib"/*) ;;
            *) return 1 ;;
        esac
    done <<<"$links"
    return 0
}

fmix_relativize_session_links() {
    # Rewrite ABSOLUTE symlinks that point back INSIDE this fmix session
    # directory into equivalent relative links. Usage:
    #   fmix_relativize_session_links <session_root> <tree_root>...
    #
    # A dependency's own build can create an absolute link entirely inside the
    # session: rebar3 links deps/otel_http/_build/prod/plugins/rebar3_ex_doc to
    # the matching default/plugins directory using the session's absolute path.
    # That link is neither an escape nor host-bound state -- it is the session's
    # own content -- yet the absolute-link guards (template manifest, stable-seed
    # and dependency-artifact publication) rejected it, so `fmix setup` failed
    # and operators hand-edited the session to get past it.
    #
    # Relativizing preserves the link's exact meaning, so what the guards see is
    # what the absolute form already resolved to; nothing is weakened:
    #   * only links whose normalized absolute target lies inside <session_root>
    #     are rewritten; a link to anywhere else stays absolute and is still
    #     rejected by the guards;
    #   * a tree_root that is itself a symlink, or that resolves outside the
    #     session, is never touched or traversed (a real symlinked _build/deps
    #     ancestor is still rejected downstream);
    #   * links are never followed while walking.
    local session_root="${1:-}"
    shift || true
    [[ -n "$session_root" && -d "$session_root" && ! -L "$session_root" ]] || return 0
    (( $# > 0 )) || return 0
    local py_bin
    py_bin="$(fmix_python_bin)" || return 1
    "$py_bin" - "$session_root" "$@" <<'PY'
import os
import sys

given = os.path.normpath(sys.argv[1])
real = os.path.realpath(given)
prefixes = {given, real}


def inside(path):
    return any(path == p or path.startswith(p + os.sep) for p in prefixes)


def to_real(path):
    for p in sorted(prefixes, key=len, reverse=True):
        if path == p or path.startswith(p + os.sep):
            return real + path[len(p):]
    return path


for top in sys.argv[2:]:
    top = os.path.normpath(top)
    if os.path.islink(top) or not os.path.isdir(top):
        continue
    if not inside(os.path.realpath(top)):
        continue
    for current, dirs, files in os.walk(top, topdown=True, followlinks=False):
        for name in list(dirs) + files:
            path = os.path.join(current, name)
            if not os.path.islink(path):
                continue
            target = os.readlink(path)
            if not os.path.isabs(target):
                continue
            normalized = os.path.normpath(target)
            if not inside(normalized):
                continue
            relative = os.path.relpath(
                to_real(normalized), os.path.realpath(os.path.dirname(path))
            )
            staged = f"{path}.fmix-relink-{os.getpid()}"
            os.symlink(relative, staged)
            os.replace(staged, path)
PY
}

fmix_session_normalize_links() {
    # Relativize the session's own absolute links before any guard inspects it.
    # No-op outside an fmix session (an arbitrary worktree's deps/_build is
    # never rewritten).
    local worktree="${1:-}" deps_root build_root
    [[ -n "${FMIX_ACTIVE_SESSION_ROOT:-}" ]] || return 0
    deps_root="$(fmix_session_deps_root "$worktree")" || return 0
    build_root="$(fmix_compile_build_root "$worktree")" || return 0
    fmix_relativize_session_links "$FMIX_ACTIVE_SESSION_ROOT" "$deps_root" "$build_root"
}

fmix_stable_seed_artifacts_are_safe() {
    # Validate the exact dependency transport roots without following links.
    # allow_app=1 is only for a publisher source, where the real cdrcisco build
    # directory is present but deliberately excluded from transport.
    local deps_dir="${1:-}" lib_dir="${2:-}" allow_app="${3:-0}"
    local source_root="${4:-}" build_dir="${5:-}" test_dir expected_lib
    local links child child_name
    local -a children=()
    [[ "$allow_app" == "0" || "$allow_app" == "1" ]] || return 1
    if [[ "$allow_app" == "1" ]]; then
        (( $# == 4 || $# == 5 )) || return 1
    else
        (( $# == 3 )) || return 1
    fi
    [[ -d "$deps_dir" && ! -L "$deps_dir" && -r "$deps_dir" && -x "$deps_dir" ]] \
        || return 1
    if [[ "$allow_app" == "1" ]]; then
        # A publisher must read artifacts from the locked canonical worktree,
        # rather than through a symlinked _build ancestor that could point at
        # another worktree or an uncontrolled shared cache.
        [[ -n "$build_dir" ]] || build_dir="$source_root/_build"
        [[ ! -L "$build_dir" ]] || return 1
        build_dir="$(fmix_realpath "$build_dir" 2>/dev/null)" || return 1
        test_dir="$build_dir/test"
        expected_lib="$test_dir/lib"
        [[ -d "$build_dir" && ! -L "$build_dir" && -r "$build_dir" && -x "$build_dir" ]] \
            || return 1
        [[ -d "$test_dir" && ! -L "$test_dir" && -r "$test_dir" && -x "$test_dir" ]] \
            || return 1
        [[ "$lib_dir" == "$expected_lib" ]] || return 1
        [[ "$(fmix_realpath "$lib_dir" 2>/dev/null)" == "$expected_lib" ]] || return 1
    fi
    [[ -d "$lib_dir" && ! -L "$lib_dir" && -r "$lib_dir" && -x "$lib_dir" ]] \
        || return 1

    if [[ "$allow_app" == "1" ]]; then
        fmix_stable_seed_source_tree_is_safe \
            "$deps_dir" "$source_root" "$lib_dir" "$deps_dir" || return 1
    else
        links="$(find "$deps_dir" -type l -print -quit 2>/dev/null)" || return 1
        [[ -z "$links" ]] || return 1
    fi

    children=("$lib_dir"/* "$lib_dir"/.[!.]* "$lib_dir"/..?*)
    for child in "${children[@]}"; do
        [[ -e "$child" || -L "$child" ]] || continue
        child_name="$(basename "$child")"
        [[ "$child_name" != .* ]] || return 1
        [[ -d "$child" && ! -L "$child" ]] || return 1
        if [[ "$child_name" == "cdrcisco" ]]; then
            [[ "$allow_app" == "1" ]] || return 1
            # The app subtree is never transported. Mix may legitimately place
            # a priv symlink inside it, so only dependency children are scanned.
            continue
        fi
        if [[ "$allow_app" == "1" ]]; then
            fmix_stable_seed_source_tree_is_safe \
                "$child" "$source_root" "$lib_dir" "$deps_dir" || return 1
        else
            links="$(find "$child" -type l -print -quit 2>/dev/null)" || return 1
            [[ -z "$links" ]] || return 1
        fi
    done
    return 0
}

fmix_stable_seed_clone_tree() {
    # Safe publisher sources are already constrained to contained relative
    # links. Materialize those links so immutable seeds never retain them.
    local source="${1:-}" destination="${2:-}" links
    (( $# == 2 )) || return 1
    links="$(find "$source" -type l -print -quit 2>/dev/null)" || return 1
    if [[ -z "$links" ]]; then
        fmix_cow_clone "$source" "$destination"
    else
        cp -RL "$source" "$destination"
    fi
}

fmix_stable_seed_structure_is_safe() {
    local seed_dir="${1:-}" unexpected
    (( $# == 1 )) || return 1
    [[ -d "$seed_dir" && ! -L "$seed_dir" && -r "$seed_dir" && -x "$seed_dir" ]] \
        || return 1
    [[ -f "$seed_dir/meta.json" && ! -L "$seed_dir/meta.json" \
        && -r "$seed_dir/meta.json" ]] || return 1
    [[ -d "$seed_dir/_build" && ! -L "$seed_dir/_build" ]] || return 1
    [[ -d "$seed_dir/_build/test" && ! -L "$seed_dir/_build/test" ]] || return 1

    unexpected="$(find "$seed_dir" -mindepth 1 -maxdepth 1 \
        ! -name deps ! -name _build ! -name meta.json -print -quit 2>/dev/null)" \
        || return 1
    [[ -z "$unexpected" ]] || return 1
    unexpected="$(find "$seed_dir/_build" -mindepth 1 -maxdepth 1 \
        ! -name test -print -quit 2>/dev/null)" || return 1
    [[ -z "$unexpected" ]] || return 1
    unexpected="$(find "$seed_dir/_build/test" -mindepth 1 -maxdepth 1 \
        ! -name lib -print -quit 2>/dev/null)" || return 1
    [[ -z "$unexpected" ]] || return 1

    fmix_stable_seed_artifacts_are_safe \
        "$seed_dir/deps" "$seed_dir/_build/test/lib" 0
}

fmix_stable_seed_is_complete() {
    local seed_dir="${1:-}" expected_base="${2:-}" expected_sha="${3:-}"
    local expected_compatibility="${4:-}" parsed
    local schema base_ref producer_ref producer_sha compatibility extra
    fmix_stable_seed_structure_is_safe "$seed_dir" || return 1
    fmix_validate_stable_base "$expected_base" || return 1
    [[ "$expected_sha" =~ ^[0-9a-f]{40}$ ]] || return 1
    [[ "$expected_compatibility" =~ ^[0-9a-f]{64}$ ]] || return 1
    parsed="$(fmix_stable_seed_parse_meta "$seed_dir")" || return 1
    IFS=$'\t' read -r schema base_ref producer_ref producer_sha compatibility extra <<<"$parsed"
    [[ -z "${extra:-}" ]] || return 1
    [[ "$schema" == "$FMIX_STABLE_SEED_SCHEMA" ]] || return 1
    [[ "$base_ref" == "$expected_base" ]] || return 1
    [[ "$producer_ref" == "$expected_base" ]] || return 1
    [[ "$producer_sha" == "$expected_sha" ]] || return 1
    [[ "$compatibility" == "$expected_compatibility" ]] || return 1
}

fmix_select_stable_seed() {
    local worktree="${1:-}" base="${2:-}" real consumer_sha compatibility
    local base_root producer_dir candidate producer_sha candidate_compatibility
    local candidate_distance selected_distance="" selected=""
    local saw_compatible=0 saw_metadata_miss=0 saw_base_miss=0 saw_ancestry_miss=0
    local ref belongs_to_base
    local -a base_refs=() candidates=()

    FMIX_STABLE_SEED_SELECTION_REASON="unknown"
    FMIX_STABLE_SEED_CANDIDATE_COUNT=0
    FMIX_STABLE_SEED_CONSUMER_SHA=""

    (( $# == 2 )) || {
        FMIX_STABLE_SEED_SELECTION_REASON="invalid-request"
        return 1
    }
    fmix_validate_stable_base "$base" || {
        FMIX_STABLE_SEED_SELECTION_REASON="invalid-base"
        return 1
    }
    if [[ -n "${MIX_TARGET+x}" && "$MIX_TARGET" != "host" ]]; then
        FMIX_STABLE_SEED_SELECTION_REASON="artifact-layout"
        return 1
    fi
    [[ -d "$worktree" ]] || {
        FMIX_STABLE_SEED_SELECTION_REASON="worktree"
        return 1
    }
    real="$(fmix_realpath "$worktree")" || {
        FMIX_STABLE_SEED_SELECTION_REASON="worktree"
        return 1
    }
    git -C "$real" rev-parse --is-inside-work-tree >/dev/null 2>&1 || {
        FMIX_STABLE_SEED_SELECTION_REASON="worktree"
        return 1
    }
    consumer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" || {
        FMIX_STABLE_SEED_SELECTION_REASON="consumer-head"
        return 1
    }
    [[ "$consumer_sha" =~ ^[0-9a-f]{40}$ ]] || {
        FMIX_STABLE_SEED_SELECTION_REASON="consumer-head"
        return 1
    }
    FMIX_STABLE_SEED_CONSUMER_SHA="$consumer_sha"

    if git -C "$real" show-ref --verify --quiet "refs/heads/$base"; then
        base_refs+=("refs/heads/$base")
    fi
    if git -C "$real" show-ref --verify --quiet "refs/remotes/origin/$base"; then
        base_refs+=("refs/remotes/origin/$base")
    fi
    if (( ${#base_refs[@]} == 0 )); then
        FMIX_STABLE_SEED_SELECTION_REASON="base-ref"
        return 1
    fi

    compatibility="$(fmix_stable_seed_compatibility "$real" 2>/dev/null)" || {
        FMIX_STABLE_SEED_SELECTION_REASON="compatibility"
        return 1
    }
    [[ "$compatibility" =~ ^[0-9a-f]{64}$ ]] || {
        FMIX_STABLE_SEED_SELECTION_REASON="compatibility"
        return 1
    }
    base_root="$FMIX_HOME/stable-seeds/v1/cisco-cdr/$base"
    if [[ ! -d "$base_root" || -L "$base_root" ]]; then
        FMIX_STABLE_SEED_SELECTION_REASON="no-candidates"
        return 1
    fi

    while IFS= read -r -d '' candidate; do
        candidates+=("$candidate")
    done < <(find "$base_root" -mindepth 2 -maxdepth 2 -type d -print0 2>/dev/null \
        | LC_ALL=C sort -z)
    FMIX_STABLE_SEED_CANDIDATE_COUNT="${#candidates[@]}"
    if (( FMIX_STABLE_SEED_CANDIDATE_COUNT == 0 )); then
        FMIX_STABLE_SEED_SELECTION_REASON="no-candidates"
        return 1
    fi

    for candidate in "${candidates[@]}"; do
        producer_dir="$(dirname "$candidate")"
        producer_sha="$(basename "$producer_dir")"
        candidate_compatibility="$(basename "$candidate")"
        [[ "$producer_sha" =~ ^[0-9a-f]{40}$ \
            && "$candidate_compatibility" =~ ^[0-9a-f]{64}$ ]] || {
            saw_metadata_miss=1
            continue
        }
        [[ "$candidate_compatibility" == "$compatibility" ]] || continue
        saw_compatible=1
        if ! fmix_stable_seed_is_complete \
            "$candidate" "$base" "$producer_sha" "$compatibility"; then
            saw_metadata_miss=1
            continue
        fi
        if ! git -C "$real" cat-file -e "${producer_sha}^{commit}" 2>/dev/null; then
            saw_ancestry_miss=1
            continue
        fi
        belongs_to_base=0
        for ref in "${base_refs[@]}"; do
            if git -C "$real" merge-base --is-ancestor "$producer_sha" "$ref" \
                >/dev/null 2>&1; then
                belongs_to_base=1
                break
            fi
        done
        if (( belongs_to_base == 0 )); then
            saw_base_miss=1
            continue
        fi
        if ! git -C "$real" merge-base --is-ancestor "$producer_sha" "$consumer_sha" \
            >/dev/null 2>&1; then
            saw_ancestry_miss=1
            continue
        fi
        candidate_distance="$(git -C "$real" rev-list --count \
            "${producer_sha}..${consumer_sha}" 2>/dev/null)" || {
            saw_ancestry_miss=1
            continue
        }
        [[ "$candidate_distance" =~ ^[0-9]+$ ]] || {
            saw_ancestry_miss=1
            continue
        }
        if [[ -z "$selected" ]] || (( candidate_distance < selected_distance )); then
            selected="$candidate"
            selected_distance="$candidate_distance"
        fi
    done

    if [[ -n "$selected" ]]; then
        FMIX_STABLE_SEED_SELECTION_REASON="ancestor"
        printf '%s\n' "$selected"
        return 0
    fi
    if (( saw_compatible == 0 )); then
        FMIX_STABLE_SEED_SELECTION_REASON="compatibility"
    elif (( saw_metadata_miss == 1 )); then
        FMIX_STABLE_SEED_SELECTION_REASON="metadata"
    elif (( saw_base_miss == 1 )); then
        FMIX_STABLE_SEED_SELECTION_REASON="base-membership"
    elif (( saw_ancestry_miss == 1 )); then
        FMIX_STABLE_SEED_SELECTION_REASON="ancestry"
    else
        FMIX_STABLE_SEED_SELECTION_REASON="no-match"
    fi
    return 1
}

_fmix_restore_stable_seed_rollback() {
    (( restore_transaction_armed == 1 )) || return 0
    restore_transaction_armed=0
    local rollback_ok=1

    if (( wrote_dependency_stamp == 1 )); then
        rm -f "$dependency_stamp" || rollback_ok=0
    fi
    if (( installed_lib == 1 )); then
        rm -rf "$target_lib" || rollback_ok=0
    fi
    if (( had_lib == 1 )); then
        if [[ -e "$target_lib" || -L "$target_lib" ]] \
            || ! mv "$restore_dir/old-lib" "$target_lib"; then
            rollback_ok=0
        fi
    fi
    if (( installed_deps == 1 )); then
        rm -rf "$target_deps" || rollback_ok=0
    fi
    if (( had_deps == 1 )); then
        if [[ -e "$target_deps" || -L "$target_deps" ]] \
            || ! mv "$restore_dir/old-deps" "$target_deps"; then
            rollback_ok=0
        fi
    fi
    if (( had_dependency_stamp == 1 )); then
        if [[ -e "$dependency_stamp" || -L "$dependency_stamp" ]]; then
            rollback_ok=0
        else
            mkdir -p "$(dirname "$dependency_stamp")" \
                && mv "$restore_dir/old-dependency-stamp" "$dependency_stamp" \
                || rollback_ok=0
        fi
    fi
    if (( had_compile_stamp == 1 )); then
        if [[ -e "$compile_stamp" || -L "$compile_stamp" ]]; then
            rollback_ok=0
        else
            mkdir -p "$(dirname "$compile_stamp")" \
                && mv "$restore_dir/old-compile-stamp" "$compile_stamp" \
                || rollback_ok=0
        fi
    fi
    if (( created_test == 1 )); then
        rmdir "$target_build/test" 2>/dev/null || rollback_ok=0
    fi
    if (( created_build == 1 )); then
        rmdir "$target_build" 2>/dev/null || rollback_ok=0
    fi
    if (( rollback_ok == 1 )); then
        rm -rf "$restore_dir" || rollback_ok=0
    fi
    if (( rollback_ok == 0 )); then
        restore_rollback_failed=1
        fmix_error "Stable seed rollback was incomplete; recovery data remains at $restore_dir"
        return 1
    fi
    return 0
}

_fmix_restore_stable_seed_interrupt() {
    restore_interrupted=1
    restore_interrupt_rc="${1:-130}"
}

fmix_restore_stable_seed() {
    local worktree="${1:-}" base="${2:-}" real selection_file seed_dir restore_dir
    local seed_child child_name target_deps target_build target_lib
    local dependency_stamp compile_stamp dependency_fingerprint
    local had_deps=0 had_lib=0 had_dependency_stamp=0 had_compile_stamp=0
    local created_build=0 created_test=0 installed_deps=0 installed_lib=0
    local install_ok=0 wrote_dependency_stamp=0
    local restore_transaction_armed=0 restore_interrupted=0 restore_interrupt_rc=0
    local restore_rollback_failed=0
    local rollback_rc=0
    local saved_trap_int saved_trap_term saved_trap_hup saved_trap_exit

    (( $# == 2 )) || return 1
    fmix_artifact_layout_is_owned "$worktree" || {
        FMIX_STABLE_SEED_SELECTION_REASON="artifact-layout"
        return 1
    }
    selection_file="$(mktemp)" || return 1
    if ! fmix_select_stable_seed "$worktree" "$base" >"$selection_file"; then
        rm -f "$selection_file"
        return 1
    fi
    IFS= read -r seed_dir <"$selection_file"
    rm -f "$selection_file"
    [[ -n "$seed_dir" && -d "$seed_dir" ]] || return 1

    real="$(fmix_realpath "$worktree")" || return 1
    target_deps="$(fmix_session_deps_root "$real")" || return 1
    target_build="$(fmix_compile_build_root "$real")"
    mkdir -p "$(dirname "$target_deps")" "$(dirname "$target_build")" || return 1
    restore_dir="$(mktemp -d "$(dirname "$target_deps")/.fmix-stable-restore.XXXXXX")" \
        || return 1
    target_lib="$target_build/test/lib"
    dependency_stamp="$(fmix_dependency_stamp_file "$real")"
    compile_stamp="$(fmix_compile_stamp_file "$real")"
    saved_trap_int="$(trap -p INT)"
    saved_trap_term="$(trap -p TERM)"
    saved_trap_hup="$(trap -p HUP)"
    saved_trap_exit="$(trap -p EXIT)"
    restore_transaction_armed=1
    trap '_fmix_restore_stable_seed_interrupt 130' INT
    trap '_fmix_restore_stable_seed_interrupt 143' TERM
    trap '_fmix_restore_stable_seed_interrupt 129' HUP
    trap '_fmix_restore_stable_seed_rollback' EXIT

    if ! fmix_cow_clone "$seed_dir/deps" "$restore_dir/new-deps" \
        || ! mkdir -p "$restore_dir/new-lib" \
        || (( restore_interrupted != 0 )); then
        _fmix_restore_stable_seed_rollback
        rollback_rc=$?
        trap - INT TERM HUP EXIT
        [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
        [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
        [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
        [[ -n "$saved_trap_exit" ]] && eval "$saved_trap_exit"
        (( rollback_rc == 0 && restore_rollback_failed == 0 )) || return 2
        (( restore_interrupted == 0 )) || return "$restore_interrupt_rc"
        return 1
    fi
    for seed_child in "$seed_dir/_build/test/lib"/*; do
        [[ -e "$seed_child" || -L "$seed_child" ]] || continue
        child_name="$(basename "$seed_child")"
        [[ "$child_name" == "cdrcisco" ]] && continue
        if [[ ! -d "$seed_child" || -L "$seed_child" ]] \
            || ! fmix_cow_clone "$seed_child" "$restore_dir/new-lib/$child_name" \
            || (( restore_interrupted != 0 )); then
            _fmix_restore_stable_seed_rollback
            rollback_rc=$?
            trap - INT TERM HUP EXIT
            [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
            [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
            [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
            [[ -n "$saved_trap_exit" ]] && eval "$saved_trap_exit"
            (( rollback_rc == 0 && restore_rollback_failed == 0 )) || return 2
            (( restore_interrupted == 0 )) || return "$restore_interrupt_rc"
            return 1
        fi
    done

    while :; do
        (( restore_interrupted == 0 )) || break
        if [[ ! -e "$target_build" && ! -L "$target_build" ]]; then
            mkdir "$target_build" || break
            created_build=1
        elif [[ ! -d "$target_build" || -L "$target_build" ]]; then
            break
        fi
        if [[ ! -e "$target_build/test" && ! -L "$target_build/test" ]]; then
            mkdir "$target_build/test" || break
            created_test=1
        elif [[ ! -d "$target_build/test" || -L "$target_build/test" ]]; then
            break
        fi
        (( restore_interrupted == 0 )) || break

        if [[ -e "$target_deps" || -L "$target_deps" ]]; then
            mv "$target_deps" "$restore_dir/old-deps" || break
            had_deps=1
        fi
        (( restore_interrupted == 0 )) || break
        mv "$restore_dir/new-deps" "$target_deps" || break
        installed_deps=1
        (( restore_interrupted == 0 )) || break

        if [[ -e "$target_lib" || -L "$target_lib" ]]; then
            mv "$target_lib" "$restore_dir/old-lib" || break
            had_lib=1
        fi
        (( restore_interrupted == 0 )) || break
        mv "$restore_dir/new-lib" "$target_lib" || break
        installed_lib=1
        (( restore_interrupted == 0 )) || break

        if [[ -e "$dependency_stamp" || -L "$dependency_stamp" ]]; then
            mv "$dependency_stamp" "$restore_dir/old-dependency-stamp" || break
            had_dependency_stamp=1
        fi
        (( restore_interrupted == 0 )) || break
        if [[ -e "$compile_stamp" || -L "$compile_stamp" ]]; then
            mv "$compile_stamp" "$restore_dir/old-compile-stamp" || break
            had_compile_stamp=1
        fi
        (( restore_interrupted == 0 )) || break

        dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$real")" \
            || break
        [[ -n "$dependency_fingerprint" ]] || break
        (( restore_interrupted == 0 )) || break
        fmix_write_dependency_stamp "$real" "$dependency_fingerprint" || break
        wrote_dependency_stamp=1
        (( restore_interrupted == 0 )) || break
        fmix_dependency_stamp_matches "$real" "$dependency_fingerprint" || break
        (( restore_interrupted == 0 )) || break
        install_ok=1
        break
    done

    if (( install_ok == 0 )); then
        _fmix_restore_stable_seed_rollback
        rollback_rc=$?
        trap - INT TERM HUP EXIT
        [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
        [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
        [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
        [[ -n "$saved_trap_exit" ]] && eval "$saved_trap_exit"
        (( rollback_rc == 0 && restore_rollback_failed == 0 )) || return 2
        (( restore_interrupted == 0 )) || return "$restore_interrupt_rc"
        return 1
    fi

    # Keep rollback armed while clearing the restore-specific signal traps.
    # A signal caught in this final pre-commit window must still restore the
    # consumer's prior state and return its conventional hard-abort status.
    trap - INT TERM HUP
    if (( restore_interrupted != 0 )); then
        _fmix_restore_stable_seed_rollback
        rollback_rc=$?
        trap - EXIT
        [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
        [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
        [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
        [[ -n "$saved_trap_exit" ]] && eval "$saved_trap_exit"
        (( rollback_rc == 0 && restore_rollback_failed == 0 )) || return 2
        return "$restore_interrupt_rc"
    fi

    restore_transaction_armed=0
    trap - EXIT
    [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
    [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
    [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
    [[ -n "$saved_trap_exit" ]] && eval "$saved_trap_exit"
    rm -rf "$restore_dir" \
        || fmix_warn "Stable seed restore succeeded, but staging cleanup failed: $restore_dir"
    fmix_info "Restored stable dependency artifacts from an ancestor seed."
    return 0
}

_fmix_stable_seed_publish_snapshot_matches() {
    local real="${1:-}" base="${2:-}" expected_sha="${3:-}"
    local expected_compatibility="${4:-}" expected_dependency="${5:-}"
    local expected_compile="${6:-}"
    local git_status branch head_sha branch_sha compatibility
    local dependency_fingerprint compile_fingerprint build_lib
    (( $# == 6 )) || return 1

    git_status="$(git -C "$real" status --porcelain --untracked-files=all 2>/dev/null)" \
        || return 1
    [[ -z "$git_status" ]] || return 1
    branch="$(git -C "$real" branch --show-current 2>/dev/null)" || return 1
    head_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
        || return 1
    branch_sha="$(git -C "$real" rev-parse --verify "refs/heads/$base" 2>/dev/null)" \
        || return 1
    [[ "$branch" == "$base" && "$head_sha" == "$expected_sha" \
        && "$branch_sha" == "$expected_sha" ]] || return 1

    compatibility="$(fmix_stable_seed_compatibility "$real" 2>/dev/null)" || return 1
    dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$real" 2>/dev/null)" \
        || return 1
    compile_fingerprint="$(fmix_compute_compile_fingerprint "$real" 2>/dev/null)" \
        || return 1
    [[ "$compatibility" == "$expected_compatibility" \
        && "$dependency_fingerprint" == "$expected_dependency" \
        && "$compile_fingerprint" == "$expected_compile" ]] || return 1
    fmix_dependency_stamp_matches "$real" "$expected_dependency" \
        >/dev/null 2>&1 || return 1
    fmix_compile_stamp_matches "$real" "$expected_compile" \
        >/dev/null 2>&1 || return 1

    build_lib="$(fmix_compile_build_root "$real")/test/lib"
    fmix_stable_seed_artifacts_are_safe \
        "$(fmix_session_deps_root "$real")" "$build_lib" 1 "$real" \
        "$(fmix_compile_build_root "$real")"
}

_fmix_seed_publish_locked() {
    # The caller holds both the canonical worktree lock and the immutable-seed
    # destination lock for this producer.
    local real="${1:-}" base="${2:-}" expected_sha="${3:-}"
    local branch producer_sha branch_sha compatibility git_status
    local dependency_fingerprint compile_fingerprint seed_dir seed_parent tmp_dir
    local build_lib child child_name

    if ! git_status="$(git -C "$real" status --porcelain --untracked-files=all 2>/dev/null)"; then
        fmix_error "Stable seed publication could not determine worktree cleanliness for '$base'."
        return 1
    fi
    if [[ -n "$git_status" ]]; then
        fmix_error "Stable seed publication requires a clean worktree for '$base'."
        return 1
    fi
    branch="$(git -C "$real" branch --show-current 2>/dev/null)" || return 1
    producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
        || return 1
    branch_sha="$(git -C "$real" rev-parse --verify "refs/heads/$base" 2>/dev/null)" || {
        fmix_error "Stable seed publication requires local branch '$base'."
        return 1
    }
    if [[ "$branch" != "$base" || "$producer_sha" != "$branch_sha" \
        || "$producer_sha" != "$expected_sha" ]]; then
        fmix_error "Stable seed publication requires '$base' checked out at its local branch tip."
        return 1
    fi
    [[ "$producer_sha" =~ ^[0-9a-f]{40}$ ]] || return 1

    compatibility="$(fmix_stable_seed_compatibility "$real" 2>/dev/null)" || {
        fmix_error "Stable seed compatibility could not be computed for '$base'."
        return 1
    }
    dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$real" 2>/dev/null)" \
        || {
            fmix_error "Stable seed dependency provenance could not be computed for '$base'."
            return 1
        }
    compile_fingerprint="$(fmix_compute_compile_fingerprint "$real" 2>/dev/null)" \
        || {
            fmix_error "Stable seed compile provenance could not be computed for '$base'."
            return 1
        }
    if ! fmix_dependency_stamp_matches "$real" "$dependency_fingerprint"; then
        fmix_error "Stable seed publication requires a current target-local dependency stamp. Run fmix setup first."
        return 1
    fi
    if ! fmix_compile_stamp_matches "$real" "$compile_fingerprint"; then
        fmix_error "Stable seed publication requires a current target-local compile stamp. Run fmix setup first."
        return 1
    fi

    fmix_session_normalize_links "$real" || return 1
    build_lib="$(fmix_compile_build_root "$real")/test/lib"
    if ! fmix_stable_seed_artifacts_are_safe \
        "$(fmix_session_deps_root "$real")" "$build_lib" 1 "$real" \
        "$(fmix_compile_build_root "$real")"; then
        fmix_error "Stable seed publication source artifacts are incomplete or contain unsafe links."
        return 1
    fi

    seed_dir="$(fmix_stable_seed_dir "$base" "$producer_sha" "$compatibility")" \
        || return 1
    seed_parent="$(dirname "$seed_dir")"
    if [[ -L "$seed_dir" ]]; then
        fmix_error "Stable seed destination for '$base' must not be a symlink."
        return 1
    fi
    if [[ -e "$seed_dir" ]]; then
        if fmix_stable_seed_is_complete \
            "$seed_dir" "$base" "$producer_sha" "$compatibility"; then
            return 0
        fi
        fmix_error "Stable seed destination for '$base' is occupied by invalid immutable state."
        return 1
    fi

    if ! mkdir -p "$seed_parent" 2>/dev/null; then
        fmix_error "Stable seed destination for '$base' could not be prepared."
        return 1
    fi
    tmp_dir="${seed_dir}.tmp-$$"
    if [[ -e "$tmp_dir" || -L "$tmp_dir" ]]; then
        fmix_error "Stable seed staging state for '$base' is already occupied."
        return 1
    fi
    if ! mkdir "$tmp_dir" 2>/dev/null; then
        fmix_error "Stable seed staging state for '$base' could not be created."
        return 1
    fi

    if ! fmix_stable_seed_clone_tree \
        "$(fmix_session_deps_root "$real")" "$tmp_dir/deps" 2>/dev/null \
        || ! mkdir -p "$tmp_dir/_build/test/lib" 2>/dev/null; then
        fmix_error "Stable seed dependency snapshot failed for '$base'."
        rm -rf "$tmp_dir" 2>/dev/null \
            || fmix_error "Stable seed staging cleanup failed for '$base'."
        return 1
    fi
    for child in "$build_lib"/*; do
        [[ -e "$child" || -L "$child" ]] || continue
        child_name="$(basename "$child")"
        [[ "$child_name" == "cdrcisco" ]] && continue
        if ! fmix_stable_seed_clone_tree \
            "$child" "$tmp_dir/_build/test/lib/$child_name" 2>/dev/null; then
            fmix_error "Stable seed dependency snapshot failed for '$base'."
            rm -rf "$tmp_dir" 2>/dev/null \
                || fmix_error "Stable seed staging cleanup failed for '$base'."
            return 1
        fi
    done

    if ! cat 2>/dev/null >"$tmp_dir/meta.json" <<EOF
{
  "schema": "$FMIX_STABLE_SEED_SCHEMA",
  "base_ref": "$base",
  "producer_ref": "$base",
  "producer_sha": "$producer_sha",
  "compatibility": "$compatibility"
}
EOF
    then
        fmix_error "Stable seed metadata staging failed for '$base'."
        rm -rf "$tmp_dir" 2>/dev/null \
            || fmix_error "Stable seed staging cleanup failed for '$base'."
        return 1
    fi
    if ! fmix_stable_seed_is_complete \
        "$tmp_dir" "$base" "$producer_sha" "$compatibility"; then
        fmix_error "Stable seed staging state failed strict validation for '$base'."
        rm -rf "$tmp_dir" 2>/dev/null \
            || fmix_error "Stable seed staging cleanup failed for '$base'."
        return 1
    fi
    if ! _fmix_stable_seed_publish_snapshot_matches \
        "$real" "$base" "$producer_sha" "$compatibility" \
        "$dependency_fingerprint" "$compile_fingerprint"; then
        fmix_error "Stable seed producer state changed during publication for '$base'."
        rm -rf "$tmp_dir" 2>/dev/null \
            || fmix_error "Stable seed staging cleanup failed for '$base'."
        return 1
    fi
    if [[ -e "$seed_dir" || -L "$seed_dir" ]] \
        || ! mv "$tmp_dir" "$seed_dir" 2>/dev/null; then
        fmix_error "Stable seed destination for '$base' changed during publication."
        rm -rf "$tmp_dir" 2>/dev/null \
            || fmix_error "Stable seed staging cleanup failed for '$base'."
        return 1
    fi

    fmix_info "Published immutable stable dependency seed for '$base'."
    return 0
}

fmix_seed_publish() {
    # Publish only dependency artifacts from a clean, compiled stable worktree.
    # The canonical worktree lock is acquired here because cmd_seed does not
    # already hold it. Current test/setup paths never call this helper, avoiding
    # recursive acquisition while preserving worktree -> seed lock ordering.
    local worktree="${1:-}" base="${2:-}" real producer_sha
    local worktree_lock seed_lock publish_rc

    (( $# == 2 )) || { fmix_error "Usage: fmix_seed_publish <worktree> <base>."; return 2; }
    fmix_validate_stable_base "$base" || {
        fmix_error "Stable seed base must be a local N.N.N-stable branch (got '$base')."
        return 1
    }
    [[ -d "$worktree" ]] || {
        fmix_error "Stable seed worktree for '$base' does not exist."
        return 1
    }
    real="$(fmix_realpath "$worktree")" || return 1
    fmix_activate_toolchain "$real" || return 1
    fmix_artifact_layout_is_owned "$real" || {
        fmix_error "Stable seed publication requires FMix-owned session artifact paths."
        return 1
    }
    git -C "$real" rev-parse --is-inside-work-tree >/dev/null 2>&1 || {
        fmix_error "Stable seed source for '$base' is not a Git worktree."
        return 1
    }

    worktree_lock="$(fmix_execution_lock_name "$real")"
    fmix_lock_acquire \
        "$worktree_lock" "$FMIX_WORKTREE_LOCK_TIMEOUT" "stable seed worktree" \
        || return $?
    producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
        || {
            fmix_error "Stable seed producer commit could not be resolved for '$base'."
            fmix_command_lock_finish "$worktree_lock" 1
            return $?
        }
    if [[ ! "$producer_sha" =~ ^[0-9a-f]{40}$ ]]; then
        fmix_command_lock_finish "$worktree_lock" 1
        return $?
    fi
    seed_lock="stable-seed-${base}-${producer_sha}"
    if fmix_lock_acquire \
        "$seed_lock" "$FMIX_LOCK_TIMEOUT" "stable seed for '$base'"; then
        :
    else
        local acquire_rc=$?
        fmix_command_lock_finish "$worktree_lock" "$acquire_rc"
        return $?
    fi

    publish_rc=0
    _fmix_seed_publish_locked "$real" "$base" "$producer_sha" || publish_rc=$?
    fmix_command_lock_finish "$seed_lock" "$publish_rc" || publish_rc=$?
    fmix_command_lock_finish "$worktree_lock" "$publish_rc"
    return $?
}

fmix_cache_filesystem_bytes() {
    local py_bin
    py_bin="$(fmix_python_bin)" || return 1
    "$py_bin" -I -B - "$FMIX_HOME" <<'PY'
import os, stat, sys
path = sys.argv[1]
try:
    before = os.lstat(path)
    if (not stat.S_ISDIR(before.st_mode) or before.st_uid != os.getuid()
            or os.path.realpath(path) != path):
        raise ValueError()
    capacity = os.statvfs(path)
    after = os.lstat(path)
    if (before.st_dev, before.st_ino) != (after.st_dev, after.st_ino):
        raise ValueError()
    print(capacity.f_bavail * capacity.f_frsize, capacity.f_blocks * capacity.f_frsize)
except (OSError, ValueError):
    raise SystemExit(1)
PY
}

fmix_optional_cache_has_headroom() {
    # Advisory prevention for optional extra cache copies, not a host quota.
    # No environment/CLI bypass; tests replace the capacity provider only in
    # their isolated sourced library. Actual cache hits allocate no new copy.
    # Canonical ordinary roots are a publication invariant; supported contained
    # nested links are materialized and counted, not authority to alias a root.
    local capacity free total estimate py_bin
    capacity="$(fmix_cache_filesystem_bytes)" || return 3
    read -r free total <<<"$capacity"
    [[ "$free" =~ ^[0-9]+$ && "$total" =~ ^[0-9]+$ \
        && ${#free} -le 15 && ${#total} -le 15 ]] || return 3
    (( free <= total && total > 0 )) || return 3
    py_bin="$(fmix_python_bin)" || return 3
    estimate="$("$py_bin" -I -B - "$@" <<'PY'
import os, stat, sys
try:
    if not 1 <= len(sys.argv[1:]) <= 2:
        raise ValueError()
    for path in sys.argv[1:]:
        info = os.lstat(path)
        if (not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid()
                or os.path.realpath(path) != path):
            raise ValueError()
    # Publication materializes permitted links with cp -RL. Count every
    # transport occurrence (not unique inodes or allocated source blocks),
    # including repeated link targets. Cycles/drift/unknown types hold.
    import time
    # Network filesystems (NFS-backed shared FMIX_HOME) need far more than a
    # workstation-local 5s to stat-walk a compiled artifact tree; a timeout
    # here fail-closes as "incomplete capacity observation" and holds every
    # optional publication. Bound the walk generously and still fail closed.
    deadline = time.monotonic() + 300
    remaining = 200000
    total = 0
    def identity(info):
        return (info.st_dev, info.st_ino, info.st_uid, info.st_mode,
                info.st_size, info.st_mtime_ns, info.st_ctime_ns)
    def measure(path, ancestors):
        global remaining, total
        remaining -= 1
        if remaining < 0 or time.monotonic() > deadline:
            raise ValueError()
        link_before = os.lstat(path)
        before = os.stat(path)
        if link_before.st_uid != os.getuid() or before.st_uid != os.getuid():
            raise ValueError()
        if stat.S_ISREG(before.st_mode):
            total += ((before.st_size + 4095) // 4096) * 4096 + 4096
        elif stat.S_ISDIR(before.st_mode):
            key = (before.st_dev, before.st_ino)
            if key in ancestors:
                raise ValueError()
            total += 4096
            with os.scandir(path) as iterator:
                for entry in iterator:
                    measure(os.path.join(path, entry.name), ancestors | {key})
        else:
            raise ValueError()
        if identity(before) != identity(os.stat(path)) or identity(link_before) != identity(os.lstat(path)):
            raise ValueError()
    for path in sys.argv[1:]:
        measure(path, set())
    print(total)
except (OSError, ValueError, RecursionError):
    raise SystemExit(1)
PY
    )" || return 3
    [[ "$estimate" =~ ^[0-9]+$ && ${#estimate} -le 15 ]] || return 3
    # Tiny metadata-sized fixture/cache copies retain the existing emergency
    # floor. Real dependency copies (>1 MiB) preserve a 10% / 200 GB buffer.
    local floor=$(( total / 10 ))
    (( floor <= 200000000000 )) || floor=200000000000
    if (( estimate <= 1048576 )); then
        floor=$(( total / 40 ))
        (( floor <= 50000000000 )) || floor=50000000000
    fi
    (( free >= floor && estimate <= free - floor )) || return 3
    return 0
}

fmix_publish_dependency_artifact() {
    local worktree="${1:-}" expected="${2:-}" lane
    (( $# == 2 )) || return 1
    [[ "$expected" =~ ^[0-9a-f]{64}$ ]] || return 1
    lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
    [[ "$lane" =~ ^[0-9a-f]{64}$ ]] || return 1
    fmix_with_artifact_lease "dependency-artifact-${lane:0:16}-${expected:0:16}" \
        _fmix_publish_dependency_artifact_locked "$@"
}

_fmix_publish_dependency_artifact_locked() {
    # Publish only after the active dependency stamp proves the exact key.
    # This cache is automatic and commit-agnostic; producer_sha is selection
    # metadata for future reconciliation, never part of exact-hit validity.
    # rc=3 holds a miss before publication. Other nonzero results may follow
    # verified publication (access refresh/release failure); callers preserve
    # the session and must not infer payload absence or erase the generation.
    local worktree="${1:-}" expected_exact="${2:-}" real lane artifact legacy_artifact parent tmp
    local deps_root build_root build_lib producer_sha source_clean source_status manifest_sha runner_sha
    local lock_name child child_name current_exact current_lane writable
    (( $# == 2 )) || return 1
    [[ "$expected_exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    real="$(fmix_realpath "$worktree")" || return 1
    current_exact="$(fmix_compute_dependency_fingerprint "$real")" || return 1
    [[ "$current_exact" == "$expected_exact" ]] || return 1
    fmix_dependency_stamp_matches "$real" "$expected_exact" || return 1
    lane="$(fmix_dependency_lane_fingerprint "$real")" || return 1
    artifact="$(fmix_dependency_artifact_v2_dir "$lane" "$expected_exact")" || return 1
    legacy_artifact="$(fmix_dependency_artifact_legacy_dir "$lane" "$expected_exact")" || return 1
    lock_name="dependency-artifact-${lane:0:16}-${expected_exact:0:16}"
    if fmix_dependency_artifact_verify_full "$artifact" "$lane" "$expected_exact"; then
        fmix_artifact_v2_managed_entrypoint || return 3
        fmix_touch_dependency_artifact_access "$lane" "$expected_exact" \
            >/dev/null 2>&1 || return $?
        return 0
    fi
    if fmix_dependency_artifact_verify_full "$legacy_artifact" "$lane" "$expected_exact"; then
        fmix_touch_dependency_artifact_access "$lane" "$expected_exact" \
            >/dev/null 2>&1 || return $?
        return 0
    fi
    deps_root="$(fmix_session_deps_root "$real")" || {
        return 1
    }
    build_root="$(fmix_compile_build_root "$real")" || {
        return 1
    }
    fmix_session_normalize_links "$real" || return 1
    build_lib="$build_root/test/lib"
    if ! fmix_stable_seed_artifacts_are_safe \
        "$deps_root" "$build_lib" 1 "$real" "$build_root"; then
        return 1
    fi
    if ! fmix_optional_cache_has_headroom "$deps_root" "$build_lib"; then
        fmix_warn "Optional dependency-cache publication held by disk pressure or incomplete capacity observation; preserving and reusing the proven session."
        return 3
    fi
    if [[ -e "$artifact" || -L "$artifact" ]]; then
        fmix_dependency_artifact_quarantine "$artifact" \
            "failed exact integrity verification" || {
            return 1
        }
    fi
    producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
        || producer_sha=""
    [[ "$producer_sha" =~ ^[0-9a-f]{40}$ ]] || {
        return 1
    }
    if ! fmix_artifact_v2_managed_entrypoint; then
        fmix_warn "Optional dependency publication held because the managed runner handoff is unproven; keeping the current session."
        return 3
    fi
    runner_sha="$(fmix_hash_stdin <"$(fmix_realpath "${BASH_SOURCE[0]}")")" || return 1
    source_status="$(git -C "$real" status --porcelain --untracked-files=all 2>/dev/null)" \
        || {
            return 1
        }
    if [[ -z "$source_status" ]]; then
        source_clean=true
    else
        source_clean=false
    fi

    fmix_artifact_v2_prepare_directory "artifacts/v2/dependencies/$lane" || return 1
    tmp="${artifact}.tmp-$$-${RANDOM}"
    if [[ -e "$tmp" || -L "$tmp" ]] || ! mkdir "$tmp"; then
        return 1
    fi
    if ! fmix_stable_seed_clone_tree "$deps_root" "$tmp/deps" 2>/dev/null \
        || ! mkdir -p "$tmp/_build/test/lib"; then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    for child in "$build_lib"/*; do
        [[ -e "$child" || -L "$child" ]] || continue
        child_name="$(basename "$child")"
        [[ "$child_name" == "cdrcisco" ]] && continue
        if ! fmix_stable_seed_clone_tree \
            "$child" "$tmp/_build/test/lib/$child_name" 2>/dev/null; then
            rm -rf "$tmp" 2>/dev/null || true
            return 1
        fi
    done
    manifest_sha="$(fmix_dependency_artifact_manifest_digest \
        "$tmp" "$tmp/manifest.tsv")" || {
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    }
    printf '%s\n' "$manifest_sha" >"$tmp/manifest.sha256" || {
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    }
    if ! cat >"$tmp/meta.json" <<EOF
{
  "schema": "2",
  "lane": "$lane",
  "dependency_fingerprint": "$expected_exact",
  "producer_sha": "$producer_sha",
  "source_clean": "$source_clean",
  "manifest_sha256": "$manifest_sha",
  "built_at": "$(fmix_now)",
  "producer_runner_sha256": "$runner_sha",
  "consumer_protocol": "fmix-native-artifacts.v2"
}
EOF
    then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    current_exact="$(fmix_compute_dependency_fingerprint "$real")" || current_exact=""
    current_lane="$(fmix_dependency_lane_fingerprint "$real")" || current_lane=""
    if [[ "$current_exact" != "$expected_exact" || "$current_lane" != "$lane" ]] \
        || ! fmix_dependency_stamp_matches "$real" "$expected_exact" \
        || ! fmix_dependency_artifact_is_complete \
            "$tmp" "$lane" "$expected_exact" 1; then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    chmod -R a-w "$tmp" || {
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    }
    chmod u+w "$tmp" || {
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    }
    writable="$(find "$tmp" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
        || writable=invalid
    if ! fmix_artifact_v2_managed_entrypoint; then
        rm -rf "$tmp" 2>/dev/null || true
        fmix_warn "Optional dependency publication held after launcher handoff changed; keeping the current session."
        return 3
    fi
    if [[ -n "$writable" || -e "$artifact" || -L "$artifact" ]] \
        || ! mv "$tmp" "$artifact"; then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    chmod a-w "$artifact" || {
        fmix_dependency_artifact_quarantine "$artifact" \
            "could not seal exact publication" >/dev/null 2>&1 || true
        return 1
    }
    if ! fmix_dependency_artifact_verify_full \
        "$artifact" "$lane" "$expected_exact"; then
        fmix_dependency_artifact_quarantine "$artifact" \
            "post-publication verification failed" >/dev/null 2>&1 || true
        return 1
    fi
    fmix_touch_dependency_artifact_access "$lane" "$expected_exact" \
        >/dev/null 2>&1 || return $?
    if ! fmix_artifact_v2_managed_entrypoint; then
        fmix_warn "Dependency generation published, but the launcher handoff changed; preserving the generation and current session."
        return 3
    fi
    fmix_info "Published immutable exact dependency artifact."
    return 0
}

fmix_dependency_reconciler_distance() {
    local candidate="$1" worktree="$2" lane="$3" exact="$4" head="$5"
    local candidate_exact producer clean distance
    candidate_exact="$(basename "$candidate")"
    fmix_dependency_artifact_path_is_owned "$candidate" || return 1
    fmix_dependency_artifact_verify_full "$candidate" "$lane" "$candidate_exact" || return 1
    clean="$(fmix_read_state "$candidate/meta.json" source_clean)"
    [[ "$clean" == "true" ]] || return 1
    producer="$(fmix_read_state "$candidate/meta.json" producer_sha)"
    [[ "$producer" =~ ^[0-9a-f]{40}$ ]] || return 1
    git -C "$worktree" merge-base --is-ancestor "$producer" "$head" >/dev/null 2>&1 || return 1
    distance="$(git -C "$worktree" rev-list --count "$producer..$head" 2>/dev/null)" || return 1
    [[ "$distance" =~ ^[0-9]+$ ]] || return 1
    printf '%s\n' "$distance"
}

fmix_find_dependency_reconciler() {
    local worktree="${1:-}" lane="${2:-}" exact="${3:-}" root head distance
    local candidate candidate_exact selected="" selected_distance=""
    local -a roots=()
    (( $# == 3 )) || return 1
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    roots=("$FMIX_HOME/artifacts/v2/dependencies/$lane"
           "$FMIX_HOME/dependency-artifacts/v1/$lane")
    head="$(git -C "$worktree" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
        || return 1
    for root in "${roots[@]}"; do
        [[ -d "$root" && ! -L "$root" ]] || continue
        for candidate in "$root"/*; do
        [[ -d "$candidate" && ! -L "$candidate" ]] || continue
        candidate_exact="$(basename "$candidate")"
        [[ "$candidate_exact" =~ ^[0-9a-f]{64}$ && "$candidate_exact" != "$exact" ]] \
            || continue
        # Reconciler selection is a pure read audit over candidate
        # generations: verification runs lock-free (see
        # fmix_dependency_artifact_verify_full) and never takes a
        # candidate's artifact lease.
        distance="$(fmix_dependency_reconciler_distance \
            "$candidate" "$worktree" "$lane" "$exact" "$head")" || continue
        if [[ -z "$selected_distance" || "$distance" -lt "$selected_distance" ]]; then
            selected="$candidate"
            selected_distance="$distance"
        fi
        done
    done
    [[ -n "$selected" ]] || return 1
    printf '%s\n' "$selected"
}

_fmix_dependency_install_interrupt() {
    dependency_install_interrupted=1
    dependency_install_interrupt_rc="${1:-130}"
}

fmix_effective_artifact_ttl_hours() {
    local pool="${1:-}" value legacy
    case "$pool" in
        dependency|app)
            value="${FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS-}"
            legacy="${FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS-}"
            if [[ -z "$value" && -n "$legacy" ]]; then
                [[ "$legacy" =~ ^[0-9]+$ && ${#legacy} -le 3 ]] \
                    && (( 10#$legacy <= 365 )) || {
                    fmix_error "Dependency cache TTL days must be an integer from 0 to 365."
                    return 2
                }
                printf '%s\n' "$(( 10#$legacy * 24 ))"
                return 0
            fi ;;
        template) value="${FMIX_TEMPLATE_TTL_HOURS-}" ;;
        *) return 2 ;;
    esac
    value="${value:-$FMIX_ARTIFACT_TTL_DEFAULT_HOURS}"
    [[ "$value" =~ ^[0-9]+$ && ${#value} -le 4 ]] \
        && (( 10#$value <= 8760 )) || {
        fmix_error "Artifact cache TTL hours must be an integer from 0 to 8760."
        return 2
    }
    printf '%s\n' "$(( 10#$value ))"
}

fmix_auto_expire_batch_limit() {
    # FMIX_AUTO_EXPIRE_MAX bounds one auto-expire pass (default 3, bounded
    # 1-10): at most this many retirement operations run per pass, pending
    # journals first (forward-only), then the oldest fresh candidates.
    # Invalid values fall back to the default; out-of-range clamps to bounds.
    local value="${FMIX_AUTO_EXPIRE_MAX:-}"
    [[ -n "$value" ]] || { printf '%s\n' "$FMIX_AUTO_EXPIRE_MAX_DEFAULT"; return 0; }
    if [[ ! "$value" =~ ^[0-9]+$ ]] || (( ${#value} > 4 )); then
        fmix_warn "FMIX_AUTO_EXPIRE_MAX='$value' must be an integer; using $FMIX_AUTO_EXPIRE_MAX_DEFAULT."
        printf '%s\n' "$FMIX_AUTO_EXPIRE_MAX_DEFAULT"
        return 0
    fi
    if (( 10#$value < 1 )); then
        fmix_warn "FMIX_AUTO_EXPIRE_MAX='$value' is below 1; using 1."
        printf '1\n'
    elif (( 10#$value > FMIX_AUTO_EXPIRE_MAX_LIMIT )); then
        fmix_warn "FMIX_AUTO_EXPIRE_MAX='$value' exceeds $FMIX_AUTO_EXPIRE_MAX_LIMIT; using $FMIX_AUTO_EXPIRE_MAX_LIMIT."
        printf '%s\n' "$FMIX_AUTO_EXPIRE_MAX_LIMIT"
    else
        printf '%s\n' "$(( 10#$value ))"
    fi
}

fmix_with_artifact_lease() {
    # Readers use the publisher's existing kernel/mixed-version lease for the
    # entire verification, copy and access refresh. Never nest or steal leases.
    local lock_name="$1" operation="$2" operation_rc=0 release_rc=0 acquire_rc=0
    FMIX_ARTIFACT_LEASE_RELEASE_FAILED=0
    shift 2
    fmix_lock_acquire "$lock_name" "$FMIX_LOCK_TIMEOUT" "artifact reader" \
        || acquire_rc=$?
    if (( acquire_rc != 0 )); then
        fmix_lock_failure_is_fatal "$acquire_rc" && return 70
        return "$acquire_rc"
    fi
    "$operation" "$@" || operation_rc=$?
    fmix_lock_release "$lock_name" || release_rc=$?
    if (( release_rc != 0 )); then
        FMIX_ARTIFACT_LEASE_RELEASE_FAILED=1
        printf '{"error":"artifact_lock_cleanup_failed","operation_exit_code":%d,"cleanup_exit_code":%d}\n' \
            "$operation_rc" "$release_rc" >&2
        fmix_error "Artifact reader release failed (operation rc=$operation_rc, release rc=$release_rc)."
    fi
    (( operation_rc == 0 )) || return "$operation_rc"
    (( release_rc == 0 )) || return "$release_rc"
    return 0
}

fmix_with_artifact_reference_lease() {
    local lock_name="$1" operation="$2" index
    shift 2
    if index="$(fmix_lock_find_index "$lock_name")"; then
        kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 70
        "$operation" "$@"
    else
        fmix_with_artifact_lease "$lock_name" "$operation" "$@"
    fi
}

fmix_install_dependency_artifact() {
    local artifact="${2:-}" lane exact
    (( $# == 3 )) || return 1
    lane="$(basename "$(dirname "$artifact")")"
    exact="$(basename "$artifact")"
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    [[ "$artifact" == "$FMIX_HOME/dependency-artifacts/v1/$lane/$exact" \
        || "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/$lane/$exact" ]] || return 1
    fmix_dependency_artifact_path_is_owned "$artifact" || return 1
    fmix_with_artifact_lease "dependency-artifact-${lane:0:16}-${exact:0:16}" \
        _fmix_install_dependency_artifact_locked "$@"
}

fmix_dependency_artifact_path_is_owned() {
    # Every generation ancestor must belong to this home's lease namespace.
    # Final-component checks and lexical containment do not reject lane aliases.
    local py_bin
    py_bin="$(fmix_python_bin)" || return 1
    "$py_bin" -I -B - "$FMIX_HOME" "$1" <<'PY'
import os, re, stat, sys
home, artifact = sys.argv[1:]
fd = None
try:
    if os.path.realpath(home) != home:
        raise ValueError()
    if artifact.startswith(home + "/dependency-artifacts/v1/"):
        suffix = artifact[len(home + "/dependency-artifacts/v1/"):]
        components = ("dependency-artifacts", "v1", *suffix.split("/"))
    elif artifact.startswith(home + "/artifacts/v2/dependencies/"):
        suffix = artifact[len(home + "/artifacts/v2/dependencies/"):]
        components = ("artifacts", "v2", "dependencies", *suffix.split("/"))
    else:
        raise ValueError()
    if not re.fullmatch(r"[0-9a-f]{64}/[0-9a-f]{64}", suffix):
        raise ValueError()
    flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
    fd = os.open(home, flags)
    device = os.fstat(fd).st_dev
    if os.fstat(fd).st_uid != os.getuid():
        raise ValueError()
    for component in components:
        child = os.open(component, flags, dir_fd=fd)
        os.close(fd)
        fd = child
        info = os.fstat(fd)
        if info.st_uid != os.getuid() or info.st_dev != device or not stat.S_ISDIR(info.st_mode):
            raise ValueError()
except (OSError, ValueError):
    raise SystemExit(1)
finally:
    if fd is not None:
        os.close(fd)
PY
}

_fmix_install_dependency_artifact_locked() {
    # Install into mutable session staging. exact=1 establishes an exact
    # dependency stamp. exact=0 is explicitly unproven builder input and
    # removes both stamps so Mix must reconcile and publish a new exact key.
    local worktree="${1:-}" artifact="${2:-}" exact_mode="${3:-0}"
    local real deps_root build_root target_lib stage retired artifact_exact lane
    local dep_stamp compile_stamp staged_manifest installed_deps=0 installed_lib=0
    local attempted_deps=0 attempted_lib=0 stamp_attempted=0 rollback_failed=0
    local had_deps=0 had_lib=0 had_dep_stamp=0 had_compile_stamp=0 ok=0 switch_failed=0
    local dependency_install_interrupted=0 dependency_install_interrupt_rc=0
    local saved_trap_int saved_trap_term saved_trap_hup
    (( $# == 3 )) || return 1
    fmix_dependency_artifact_path_is_owned "$artifact" || return 1
    if [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
        fmix_artifact_v2_managed_entrypoint || return 3
    fi
    [[ "$exact_mode" == "0" || "$exact_mode" == "1" ]] || return 1
    [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]] || return 1
    real="$(fmix_realpath "$worktree")" || return 1
    deps_root="$(fmix_session_deps_root "$real")" || return 1
    build_root="$(fmix_compile_build_root "$real")" || return 1
    [[ "$deps_root" == "$FMIX_ACTIVE_SESSION_ROOT/deps" \
        && "$build_root" == "$FMIX_ACTIVE_SESSION_ROOT/_build" ]] || return 1
    artifact_exact="$(fmix_read_state "$artifact/meta.json" dependency_fingerprint)"
    lane="$(fmix_read_state "$artifact/meta.json" lane)"
    fmix_dependency_artifact_verify_full \
        "$artifact" "$lane" "$artifact_exact" || return 1

    target_lib="$build_root/test/lib"
    mkdir -p "$build_root/test" || return 1
    [[ ! -L "$build_root" && ! -L "$build_root/test" \
        && ! -L "$target_lib" ]] || return 1
    stage="$(mktemp -d "$FMIX_ACTIVE_SESSION_ROOT/.dependency-install.XXXXXX")" || return 1
    retired="$stage/retired"
    mkdir -p "$stage/new/_build/test/lib" "$retired" || return 1
    if ! fmix_cow_clone "$artifact/deps" "$stage/new/deps"; then
        rm -rf "$stage" 2>/dev/null || true
        return 1
    fi
    local child child_name
    for child in "$artifact/_build/test/lib"/*; do
        [[ -e "$child" || -L "$child" ]] || continue
        child_name="$(basename "$child")"
        if ! fmix_cow_clone "$child" "$stage/new/_build/test/lib/$child_name"; then
            rm -rf "$stage" 2>/dev/null || true
            return 1
        fi
    done
    # Prove the staged transport before adding the mutable application build.
    staged_manifest="$(fmix_dependency_artifact_manifest_digest \
        "$stage/new" "$stage/new/manifest.tsv")" || {
        rm -rf "$stage" 2>/dev/null || true
        return 1
    }
    if [[ "$staged_manifest" != "$(fmix_read_state "$artifact/meta.json" manifest_sha256)" ]]; then
        rm -rf "$stage" 2>/dev/null || true
        return 1
    fi
    # Preserve the application build as a mutable incremental candidate. It
    # remains independently guarded by the compile fingerprint and is never
    # included in the shared dependency artifact.
    if [[ -d "$target_lib/cdrcisco" && ! -L "$target_lib/cdrcisco" ]]; then
        if ! fmix_cow_clone "$target_lib/cdrcisco" "$stage/new/_build/test/lib/cdrcisco"; then
            rm -rf "$stage" 2>/dev/null || true
            return 1
        fi
    fi
    chmod -R u+w "$stage/new/deps" "$stage/new/_build/test/lib" || {
        rm -rf "$stage" 2>/dev/null || true
        return 1
    }
    if [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
        if ! fmix_artifact_v2_managed_entrypoint; then
            rm -rf "$stage" 2>/dev/null || true
            return 3
        fi
        if ! fmix_dependency_artifact_verify_full "$artifact" "$lane" "$artifact_exact"; then
            rm -rf "$stage" 2>/dev/null || true
            return 1
        fi
    fi

    dep_stamp="$(fmix_dependency_stamp_file "$real")"
    compile_stamp="$(fmix_compile_stamp_file "$real")"
    saved_trap_int="$(trap -p INT)"
    saved_trap_term="$(trap -p TERM)"
    saved_trap_hup="$(trap -p HUP)"
    trap '_fmix_dependency_install_interrupt 130' INT
    trap '_fmix_dependency_install_interrupt 143' TERM
    trap '_fmix_dependency_install_interrupt 129' HUP
    if [[ -e "$deps_root" || -L "$deps_root" ]]; then
        if mv "$deps_root" "$retired/deps"; then
            had_deps=1
        else
            switch_failed=1
        fi
    fi
    if (( switch_failed == 0 )) && [[ -e "$target_lib" || -L "$target_lib" ]]; then
        if mv "$target_lib" "$retired/lib"; then
            had_lib=1
        else
            switch_failed=1
        fi
    fi
    if (( switch_failed == 0 )) && [[ -f "$dep_stamp" ]]; then
        if mv "$dep_stamp" "$retired/dependency-stamp.json"; then
            had_dep_stamp=1
        else
            switch_failed=1
        fi
    fi
    if (( switch_failed == 0 )) \
        && [[ "$exact_mode" == "0" && -f "$compile_stamp" ]]; then
        if mv "$compile_stamp" "$retired/compile-stamp.json"; then
            had_compile_stamp=1
        else
            switch_failed=1
        fi
    fi

    if (( switch_failed == 0 && dependency_install_interrupted == 0 )); then
        attempted_deps=1
        if mv "$stage/new/deps" "$deps_root"; then installed_deps=1; else switch_failed=1; fi
    fi
    if (( switch_failed == 0 && dependency_install_interrupted == 0 )); then
        attempted_lib=1
        if mv "$stage/new/_build/test/lib" "$target_lib"; then
            installed_lib=1
            if [[ "$exact_mode" == "1" ]]; then
                stamp_attempted=1
                if (( dependency_install_interrupted == 0 )) \
                    && fmix_write_dependency_stamp "$real" "$artifact_exact" \
                    && fmix_dependency_stamp_matches "$real" "$artifact_exact" \
                    && (( dependency_install_interrupted == 0 )); then
                    ok=1
                fi
            else
                if (( dependency_install_interrupted == 0 )) \
                    && [[ ! -e "$dep_stamp" && ! -e "$compile_stamp" ]] \
                    && (( dependency_install_interrupted == 0 )); then
                    ok=1
                fi
            fi
        fi
    fi

    if (( ok == 0 || dependency_install_interrupted != 0 )); then
        [[ ! -e "$retired/deps" && ! -L "$retired/deps" ]] || had_deps=1
        [[ ! -e "$retired/lib" && ! -L "$retired/lib" ]] || had_lib=1
        [[ ! -e "$retired/dependency-stamp.json" && ! -L "$retired/dependency-stamp.json" ]] || had_dep_stamp=1
        [[ ! -e "$retired/compile-stamp.json" && ! -L "$retired/compile-stamp.json" ]] || had_compile_stamp=1
        if (( attempted_deps != 0 )) && [[ ! -e "$stage/new/deps" && ! -L "$stage/new/deps" \
            && ( -e "$deps_root" || -L "$deps_root" ) ]]; then installed_deps=1; fi
        if (( attempted_lib != 0 )) && [[ ! -e "$stage/new/_build/test/lib" && ! -L "$stage/new/_build/test/lib" \
            && ( -e "$target_lib" || -L "$target_lib" ) ]]; then installed_lib=1; fi
        (( installed_deps == 0 )) || rm -rf "$deps_root" || rollback_failed=1
        (( installed_lib == 0 )) || rm -rf "$target_lib" || rollback_failed=1
        if (( had_deps != 0 )); then
            if [[ ! -e "$deps_root" && ! -L "$deps_root" ]]; then
                mv "$retired/deps" "$deps_root" || rollback_failed=1
            else rollback_failed=1; fi
        fi
        if (( had_lib != 0 )); then
            if [[ ! -e "$target_lib" && ! -L "$target_lib" ]]; then
                mv "$retired/lib" "$target_lib" || rollback_failed=1
            else rollback_failed=1; fi
        fi
        if (( stamp_attempted != 0 || had_dep_stamp != 0 )); then
            rm -f "$dep_stamp" || rollback_failed=1
        fi
        if (( had_dep_stamp != 0 )); then
            if [[ ! -e "$dep_stamp" && ! -L "$dep_stamp" ]]; then
                mv "$retired/dependency-stamp.json" "$dep_stamp" || rollback_failed=1
            else rollback_failed=1; fi
        fi
        if (( had_compile_stamp != 0 )); then
            if [[ ! -e "$compile_stamp" && ! -L "$compile_stamp" ]]; then
                mv "$retired/compile-stamp.json" "$compile_stamp" || rollback_failed=1
            else rollback_failed=1; fi
        fi
        trap - INT TERM HUP
        [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
        [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
        [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
        if (( rollback_failed != 0 )); then
            fmix_error "Dependency replacement rollback incomplete; preserving recovery inputs: $stage"
            return 2
        fi
        rm -rf "$stage" || fmix_warn "Owned dependency staging remains: $stage"
        (( dependency_install_interrupted == 0 )) \
            || return "$dependency_install_interrupt_rc"
        return 1
    fi
    rm -rf "$stage" 2>/dev/null || \
        fmix_warn "Dependency install succeeded, but retired staging remains: $stage"
    trap - INT TERM HUP
    [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
    [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
    [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
    (( dependency_install_interrupted == 0 )) \
        || return "$dependency_install_interrupt_rc"
    fmix_touch_dependency_artifact_access "$lane" "$artifact_exact" || return 1
    return 0
}

fmix_prepare_dependency_artifacts() {
    local worktree="${1:-}" exact lane artifact reconciler reconciler_exact install_rc
    (( $# == 1 )) || return 1
    exact="$(fmix_compute_dependency_fingerprint "$worktree")" || return 1
    if fmix_dependency_stamp_matches "$worktree" "$exact"; then
        return 0
    fi
    lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
    artifact="$(fmix_dependency_artifact_dir "$lane" "$exact")" || return 1
    if [[ -e "$artifact" || -L "$artifact" ]]; then
        if fmix_install_dependency_artifact "$worktree" "$artifact" 1; then
            fmix_info "Exact dependency artifact hit — skipping dependency resolution and compilation."
            return 0
        else
            install_rc=$?
            case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
            fmix_lock_failure_is_fatal "$install_rc" && return 70
            [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
            # Consumers must not quarantine a generation on an unlocked probe:
            # a concurrent publisher may have replaced it. The leased producer
            # handles corrupt entries before publishing their replacement.
            fmix_warn "Exact dependency artifact failed verification; rebuilding under its publisher lease."
        fi
    fi
    if reconciler="$(fmix_find_dependency_reconciler \
        "$worktree" "$lane" "$exact" 2>/dev/null)"; then
        reconciler_exact="$(basename "$reconciler")"
        if fmix_install_dependency_artifact "$worktree" "$reconciler" 0; then
            fmix_info "Seeded dependency reconciliation from the closest proven ancestor."
            fmix_info "This is builder input, not an exact cache hit; Mix must publish the new fingerprint."
            return 0
        else
            install_rc=$?
            case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
            fmix_lock_failure_is_fatal "$install_rc" && return 70
            [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
        fi
        fmix_warn "Ancestor dependency seed was unusable; continuing with a cold dependency build."
    fi
    return 0
}

# ---------------------------------------------------------------------------
# Local app-compile CAS — shared compiled application layer
# (artifacts/v2/app-compiles/<lane>/<exact>). Reuses the dependency store's
# lease, manifest-digest, quarantine, and outside-CAS access conventions.
# ---------------------------------------------------------------------------

fmix_publish_app_compile_artifact() {
    local worktree="${1:-}" expected="${2:-}" lane
    (( $# == 2 )) || return 1
    [[ "$expected" =~ ^[0-9a-f]{64}$ ]] || return 1
    [[ "${FMIX_APP_CAS:-1}" != "0" ]] || return 1
    lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
    [[ "$lane" =~ ^[0-9a-f]{64}$ ]] || return 1
    fmix_with_artifact_lease "app-compile-${lane:0:16}-${expected:0:16}" \
        _fmix_publish_app_compile_artifact_locked "$@"
}

_fmix_publish_app_compile_artifact_locked() {
    # Publish only after the active compile stamp proves the exact key. This
    # cache is automatic and commit-agnostic; producer_sha is selection
    # metadata, never part of exact-hit validity. Callers treat every
    # non-signal failure as a best-effort hold, never a run failure.
    local worktree="${1:-}" expected_exact="${2:-}" real lane artifact app_source
    local build_root producer_sha source_clean source_status manifest_sha runner_sha
    local tmp writable current_exact current_lane
    (( $# == 2 )) || return 1
    [[ "$expected_exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    real="$(fmix_realpath "$worktree")" || return 1
    current_exact="$(fmix_compute_compile_fingerprint "$real")" || return 1
    [[ "$current_exact" == "$expected_exact" ]] || return 1
    fmix_compile_stamp_matches "$real" "$expected_exact" || return 1
    lane="$(fmix_dependency_lane_fingerprint "$real")" || return 1
    artifact="$(fmix_app_compile_artifact_v2_dir "$lane" "$expected_exact")" || return 1
    if fmix_app_compile_artifact_verify_full "$artifact" "$lane" "$expected_exact"; then
        fmix_artifact_v2_managed_entrypoint || return 3
        fmix_touch_app_compile_artifact_access "$lane" "$expected_exact" \
            >/dev/null 2>&1 || return $?
        return 0
    fi
    build_root="$(fmix_compile_build_root "$real")" || return 1
    app_source="$build_root/test/lib/cdrcisco"
    [[ -d "$app_source" && ! -L "$app_source" ]] || return 1
    [[ -d "$app_source/.mix" && -d "$app_source/ebin" ]] || return 1
    [[ -n "$(find "$app_source/ebin" -maxdepth 1 -type f -name '*.beam' \
        -print -quit 2>/dev/null)" ]] || return 1
    fmix_session_normalize_links "$real" || return 1
    if ! fmix_optional_cache_has_headroom "$app_source"; then
        fmix_warn "Optional app-compile publication held by disk pressure or incomplete capacity observation; preserving and reusing the proven session."
        return 3
    fi
    if [[ -e "$artifact" || -L "$artifact" ]]; then
        fmix_app_compile_artifact_quarantine "$artifact" \
            "failed exact integrity verification" || return 1
    fi
    producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
        || producer_sha=""
    [[ "$producer_sha" =~ ^[0-9a-f]{40}$ ]] || return 1
    if ! fmix_managed_publication_gate app-compile; then
        fmix_warn "Optional app-compile publication held because the managed runner handoff is unproven; keeping the current session."
        return 3
    fi
    runner_sha="$(fmix_hash_stdin <"$(fmix_realpath "${BASH_SOURCE[0]}")")" || return 1
    source_status="$(git -C "$real" status --porcelain --untracked-files=all 2>/dev/null)" \
        || return 1
    if [[ -z "$source_status" ]]; then
        source_clean=true
    else
        source_clean=false
    fi

    fmix_artifact_v2_prepare_directory "artifacts/v2/app-compiles/$lane" || return 1
    tmp="${artifact}.tmp-$$-${RANDOM}"
    if [[ -e "$tmp" || -L "$tmp" ]] || ! mkdir "$tmp"; then
        return 1
    fi
    if ! mkdir -p "$tmp/_build/test/lib" \
        || ! fmix_cow_clone "$app_source" "$tmp/_build/test/lib/cdrcisco" 2>/dev/null; then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    # A shared generation must never retain the host/worktree-bound Mix priv
    # link; materialize it exactly like the template publisher does.
    if ! fmix_template_materialize_app_priv "$tmp" "$real" "$build_root"; then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    if ! fmix_app_compile_payload_is_safe "$tmp/_build/test/lib/cdrcisco"; then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    manifest_sha="$(fmix_app_compile_artifact_manifest_digest \
        "$tmp" "$tmp/manifest.tsv")" || {
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    }
    printf '%s\n' "$manifest_sha" >"$tmp/manifest.sha256" || {
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    }
    if ! cat >"$tmp/meta.json" <<EOF
{
  "schema": "2",
  "lane": "$lane",
  "compile_fingerprint": "$expected_exact",
  "producer_sha": "$producer_sha",
  "source_clean": "$source_clean",
  "manifest_sha256": "$manifest_sha",
  "built_at": "$(fmix_now)",
  "producer_runner_sha256": "$runner_sha",
  "consumer_protocol": "fmix-native-artifacts.v2"
}
EOF
    then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    current_exact="$(fmix_compute_compile_fingerprint "$real")" || current_exact=""
    current_lane="$(fmix_dependency_lane_fingerprint "$real")" || current_lane=""
    if [[ "$current_exact" != "$expected_exact" || "$current_lane" != "$lane" ]] \
        || ! fmix_compile_stamp_matches "$real" "$expected_exact" \
        || ! fmix_app_compile_artifact_is_complete \
            "$tmp" "$lane" "$expected_exact" 1; then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    chmod -R a-w "$tmp" || {
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    }
    chmod u+w "$tmp" || {
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    }
    writable="$(find "$tmp" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
        || writable=invalid
    if ! fmix_artifact_v2_managed_entrypoint; then
        rm -rf "$tmp" 2>/dev/null || true
        fmix_warn "Optional app-compile publication held after launcher handoff changed; keeping the current session."
        return 3
    fi
    if [[ -n "$writable" || -e "$artifact" || -L "$artifact" ]] \
        || ! mv "$tmp" "$artifact"; then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    chmod a-w "$artifact" || {
        fmix_app_compile_artifact_quarantine "$artifact" \
            "could not seal exact publication" >/dev/null 2>&1 || true
        return 1
    }
    if ! fmix_app_compile_artifact_verify_full \
        "$artifact" "$lane" "$expected_exact"; then
        fmix_app_compile_artifact_quarantine "$artifact" \
            "post-publication verification failed" >/dev/null 2>&1 || true
        return 1
    fi
    fmix_touch_app_compile_artifact_access "$lane" "$expected_exact" \
        >/dev/null 2>&1 || return $?
    fmix_info "Published immutable exact app compile artifact."
    return 0
}

fmix_install_app_compile_artifact() {
    local artifact="${2:-}" lane exact
    (( $# == 3 )) || return 1
    [[ "${FMIX_APP_CAS:-1}" != "0" ]] || return 1
    lane="$(basename "$(dirname "$artifact")")"
    exact="$(basename "$artifact")"
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/$lane/$exact" ]] || return 1
    fmix_app_compile_artifact_path_is_owned "$artifact" || return 1
    fmix_with_artifact_lease "app-compile-${lane:0:16}-${exact:0:16}" \
        _fmix_install_app_compile_artifact_locked "$@"
}

_fmix_app_compile_install_interrupt() {
    app_compile_install_interrupted=1
    app_compile_install_interrupt_rc="${1:-130}"
}

_fmix_install_app_compile_artifact_locked() {
    # Install into mutable session staging, bind fresh provenance to this
    # worktree's path/build_root (the same binding fmix_donor_rebind_staged_stamps
    # performs for donor stamps), and re-run fmix_compile_stamp_matches to
    # prove admission before committing. ANY verification failure rolls the
    # transaction back so the caller falls through to the normal bounded
    # compile — never a forced full rebuild.
    local worktree="${1:-}" artifact="${2:-}" exact="${3:-}"
    local real build_root target_lib target stage retired artifact_lane
    local compile_stamp staged_manifest
    local had_target=0 had_compile_stamp=0 installed=0 recorded=0 ok=0 rollback_failed=0
    local switch_failed=0
    local app_compile_install_interrupted=0 app_compile_install_interrupt_rc=0
    local saved_trap_int saved_trap_term saved_trap_hup
    (( $# == 3 )) || return 1
    [[ "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    fmix_app_compile_artifact_path_is_owned "$artifact" || return 1
    fmix_artifact_v2_managed_entrypoint || return 3
    real="$(fmix_realpath "$worktree")" || return 1
    build_root="$(fmix_compile_build_root "$real")" || return 1
    artifact_lane="$(basename "$(dirname "$artifact")")"
    fmix_app_compile_artifact_verify_full "$artifact" "$artifact_lane" "$exact" || return 1

    target_lib="$build_root/test/lib"
    target="$target_lib/cdrcisco"
    mkdir -p "$target_lib" || return 1
    [[ ! -L "$build_root" && ! -L "$build_root/test" \
        && ! -L "$target_lib" ]] || return 1

    stage="$(mktemp -d "$target_lib/.app-compile-install.XXXXXX")" || return 1
    retired="$stage/retired"
    if ! mkdir -p "$stage/new/_build/test/lib" "$retired"; then
        rm -rf "$stage" 2>/dev/null || true
        return 1
    fi
    if ! fmix_cow_clone "$artifact/_build/test/lib/cdrcisco" \
        "$stage/new/_build/test/lib/cdrcisco"; then
        rm -rf "$stage" 2>/dev/null || true
        return 1
    fi
    # The donor clone's manifest freshness rule: cloned Mix manifests must
    # never look stale to an incremental compile.
    find "$stage/new" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true
    # Prove the staged transport before touching any live path.
    staged_manifest="$(fmix_app_compile_artifact_manifest_digest \
        "$stage/new" "$stage/new/manifest.tsv")" || {
        rm -rf "$stage" 2>/dev/null || true
        return 1
    }
    if [[ "$staged_manifest" != "$(fmix_read_state "$artifact/meta.json" manifest_sha256)" ]]; then
        rm -rf "$stage" 2>/dev/null || true
        return 1
    fi
    chmod -R u+w "$stage/new/_build/test/lib" || {
        rm -rf "$stage" 2>/dev/null || true
        return 1
    }
    if ! fmix_app_compile_artifact_verify_full \
        "$artifact" "$artifact_lane" "$exact"; then
        rm -rf "$stage" 2>/dev/null || true
        return 1
    fi

    compile_stamp="$(fmix_compile_stamp_file "$real")"
    saved_trap_int="$(trap -p INT)"
    saved_trap_term="$(trap -p TERM)"
    saved_trap_hup="$(trap -p HUP)"
    trap '_fmix_app_compile_install_interrupt 130' INT
    trap '_fmix_app_compile_install_interrupt 143' TERM
    trap '_fmix_app_compile_install_interrupt 129' HUP
    if [[ -e "$target" || -L "$target" ]]; then
        if mv "$target" "$retired/cdrcisco"; then
            had_target=1
        else
            switch_failed=1
        fi
    fi
    if (( switch_failed == 0 && app_compile_install_interrupted == 0 )); then
        if mv "$stage/new/_build/test/lib/cdrcisco" "$target"; then
            installed=1
        else
            switch_failed=1
        fi
    fi
    if (( installed == 1 && switch_failed == 0 && app_compile_install_interrupted == 0 )); then
        if [[ -f "$compile_stamp" ]]; then
            if mv "$compile_stamp" "$retired/compile-stamp.json"; then
                had_compile_stamp=1
            else
                switch_failed=1
            fi
        fi
    fi
    if (( installed == 1 && switch_failed == 0 && app_compile_install_interrupted == 0 )); then
        if fmix_write_compile_stamp "$real" "$exact"; then
            recorded=1
        else
            switch_failed=1
        fi
    fi
    if (( recorded == 1 && switch_failed == 0 && app_compile_install_interrupted == 0 )) \
        && fmix_compile_stamp_matches "$real" "$exact"; then
        ok=1
    fi

    if (( ok == 1 && switch_failed == 0 && app_compile_install_interrupted == 0 )); then
        rm -rf "$stage" 2>/dev/null || \
            fmix_warn "App compile install succeeded, but retired staging remains: $stage"
        trap - INT TERM HUP
        [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
        [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
        [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
        fmix_touch_app_compile_artifact_access "$artifact_lane" "$exact" || return 1
        fmix_session_relink_app_priv "$build_root" \
            || fmix_warn "Could not relink the application priv to this checkout: $target/priv"
        return 0
    fi

    # Roll back: never leave a half-installed application layer behind.
    if (( installed == 1 )); then
        if [[ -e "$target" || -L "$target" ]]; then
            chmod -R u+w "$target" 2>/dev/null || true
            rm -rf "$target" || rollback_failed=1
        fi
    fi
    if (( recorded == 1 )); then
        rm -f "$compile_stamp" || rollback_failed=1
    fi
    if (( had_compile_stamp == 1 )); then
        if [[ ! -e "$compile_stamp" && ! -L "$compile_stamp" ]]; then
            mv "$retired/compile-stamp.json" "$compile_stamp" || rollback_failed=1
        else rollback_failed=1; fi
    fi
    if (( had_target == 1 )); then
        if [[ ! -e "$target" && ! -L "$target" ]]; then
            mv "$retired/cdrcisco" "$target" || rollback_failed=1
        else rollback_failed=1; fi
    fi
    trap - INT TERM HUP
    [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
    [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
    [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
    if (( rollback_failed != 0 )); then
        fmix_error "App compile replacement rollback incomplete; preserving recovery inputs: $stage"
        return 2
    fi
    rm -rf "$stage" 2>/dev/null || \
        fmix_warn "Owned app compile staging remains: $stage"
    if (( app_compile_install_interrupted != 0 )); then
        return "$app_compile_install_interrupt_rc"
    fi
    return 1
}


fmix_try_install_app_compile_artifact() {
    # Consumer gate for the local app-compile CAS. Returns 0 only after the
    # payload installed AND the recorded stamps prove admission. Every
    # verification outcome is a miss: the caller falls through to the normal
    # bounded compile (never a forced full rebuild).
    local worktree="${1:-}" fingerprint="${2:-}" lane artifact install_rc
    (( $# >= 2 )) || return 1
    [[ "${FMIX_APP_CAS:-1}" != "0" ]] || return 1
    [[ "$fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
    lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
    [[ "$lane" =~ ^[0-9a-f]{64}$ ]] || return 1
    artifact="$(fmix_dependency_artifact_dir "$lane" "$fingerprint" app)" || return 1
    if [[ ! -e "$artifact" && ! -L "$artifact" ]]; then
        return 1
    fi
    if fmix_install_app_compile_artifact "$worktree" "$artifact" "$fingerprint"; then
        fmix_info "App compile artifact payload installed; stamps prove admission."
        return 0
    else
        install_rc=$?
        case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
        fmix_lock_failure_is_fatal "$install_rc" && return 70
        [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
        # Consumers must not quarantine a generation on an unlocked probe: a
        # concurrent publisher may have replaced it. The leased producer
        # handles corrupt entries before publishing their replacement.
        fmix_warn "Exact app compile artifact failed verification; compiling locally."
    fi
    return 1
}

# ---------------------------------------------------------------------------
# DB fingerprint — verbatim port of compute_api_test_db_fingerprint from ct-local-dev
# Uses the same hash_cisco_source_paths approach but simplified for non-git use.
# ---------------------------------------------------------------------------

fmix_hash_source_paths() {
    local root="$1" tmp_tracked="" tmp_diff="" tmp_staged=""
    local unstaged_hash="" staged_hash="" rc
    shift
    local path

    if [[ -d "$root/.git" || -f "$root/.git" ]]; then
        git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1 \
            || return 1
        tmp_tracked="$(mktemp)" || return 1
        tmp_diff="$(mktemp)" || { rm -f "$tmp_tracked"; return 1; }
        tmp_staged="$(mktemp)" \
            || { rm -f "$tmp_tracked" "$tmp_diff"; return 1; }

        if ! git -C "$root" ls-files -s -- "$@" \
            | awk '$1 != "160000" { print $0 }' \
            | LC_ALL=C sort >"$tmp_tracked"; then
            rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"
            return 1
        fi
        if ! git -C "$root" diff --binary -- "$@" >"$tmp_diff" 2>/dev/null; then
            rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"
            return 1
        fi
        if ! git -C "$root" diff --cached --binary -- "$@" \
            >"$tmp_staged" 2>/dev/null; then
            rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"
            return 1
        fi
        if [[ -s "$tmp_diff" ]]; then
            unstaged_hash="$(fmix_hash_files "$tmp_diff" | awk '{print $1}')" \
                || { rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"; return 1; }
        fi
        if [[ -s "$tmp_staged" ]]; then
            staged_hash="$(fmix_hash_files "$tmp_staged" | awk '{print $1}')" \
                || { rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"; return 1; }
        fi
        {
            cat "$tmp_tracked"
            [[ -z "$unstaged_hash" ]] \
                || printf 'unstaged-diff:%s\n' "$unstaged_hash"
            [[ -z "$staged_hash" ]] \
                || printf 'staged-diff:%s\n' "$staged_hash"
        }
        rc=$?
        rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"
        return "$rc"
    else
        for path in "$@"; do
            if [[ -f "$root/$path" || -L "$root/$path" ]]; then
                fmix_hash_files "$root/$path"
            elif [[ -d "$root/$path" ]]; then
                find "$root/$path" -type f -print0 2>/dev/null \
                    | LC_ALL=C sort -z \
                    | while IFS= read -r -d '' f; do
                        fmix_hash_files "$f"
                    done
            fi
        done
    fi
}

# ---------------------------------------------------------------------------
# State file helpers
# ---------------------------------------------------------------------------

fmix_worktree_id() {
    # sha8 of the canonical realpath
    local path="$1"
    local real
    real="$(fmix_realpath "$path")"
    printf '%s\n' "$real" | fmix_hash_stdin | cut -c1-8
}

fmix_worktree_state_file() {
    local worktree="$1"
    if [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]]; then
        printf '%s/state.json\n' "$FMIX_ACTIVE_SESSION_ROOT"
        return 0
    fi
    local wid
    wid="$(fmix_worktree_id "$worktree")"
    printf '%s/worktrees/%s.json\n' "$FMIX_HOME" "$wid"
}

fmix_artifact_state_file() {
    local worktree="$1"
    if [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]]; then
        printf '%s/artifact-state.json\n' "$FMIX_ACTIVE_SESSION_ROOT"
        return 0
    fi
    printf '%s/artifact-states/%s.json\n' \
        "$FMIX_HOME" "$(fmix_worktree_id "$worktree")"
}

fmix_write_artifact_state() {
    (( $# == 2 )) || return 1
    [[ "$2" =~ ^[0-9a-f]{16}$ ]] || return 1
    fmix_with_artifact_reference_lease "build-$2" _fmix_write_artifact_state_locked "$@"
}

_fmix_write_artifact_state_locked() {
    local worktree="$1" template_key="$2" real state tmp
    local base_key=""
    [[ "$template_key" =~ ^[0-9a-f]{16}$ ]] || return 1
    real="$(fmix_realpath "$worktree")" || return 1
    state="$(fmix_artifact_state_file "$real")" || return 1
    mkdir -p "$(dirname "$state")" || return 1
    tmp="$(mktemp "${state}.tmp.XXXXXX")" || return 1
    # The template key minus the migrations digest. A later migration-only key
    # change is recognised by this staying equal (see
    # fmix_adopt_migration_only_key_change); empty when it cannot be computed,
    # which simply disables that adoption.
    base_key="$(fmix_compute_legacy_template_key_v4 "$real" 2>/dev/null)" || base_key=""
    [[ "$base_key" =~ ^[0-9a-f]{16}$ ]] || base_key=""
    if ! cat >"$tmp" <<EOF
{
  "schema": "fmix-artifacts-v1",
  "path": $(fmix_json_escape "$real"),
  "template_key": $(fmix_json_escape "$template_key"),
  "template_base_key": $(fmix_json_escape "$base_key"),
  "verified_at": $(fmix_json_escape "$(fmix_now)")
}
EOF
    then
        rm -f "$tmp"
        return 1
    fi
    mv "$tmp" "$state" || { rm -f "$tmp"; return 1; }
}

fmix_worktree_schema_manifest_file() {
    local worktree="$1" key="$2"
    [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
    printf '%s/worktree-manifests/%s/%s.tsv\n' \
        "$FMIX_HOME" "$(fmix_worktree_id "$worktree")" "$key"
}

fmix_write_worktree_schema_manifest() {
    # Preserve the exact migration contents proven against a scratch DB. The
    # file is immutable and content-addressed; state publication points at it.
    local worktree="$1" key="$2" manifest tmp actual_key
    manifest="$(fmix_worktree_schema_manifest_file "$worktree" "$key")" || return 1
    mkdir -p "$(dirname "$manifest")" || return 1
    tmp="${manifest}.tmp-$$"
    fmix_write_schema_manifest "$worktree" "$tmp" || { rm -f "$tmp"; return 1; }
    actual_key="$(fmix_schema_key_from_manifest "$tmp")" || { rm -f "$tmp"; return 1; }
    if [[ "$actual_key" != "$key" ]]; then
        rm -f "$tmp"
        fmix_error "Refusing to publish scratch provenance: manifest key $actual_key != state key $key."
        return 1
    fi
    if [[ -e "$manifest" ]]; then
        if cmp -s "$manifest" "$tmp"; then
            rm -f "$tmp"
            return 0
        fi
        rm -f "$tmp"
        fmix_error "Immutable scratch provenance collision for schema key $key."
        return 1
    fi
    mv "$tmp" "$manifest" || { rm -f "$tmp"; return 1; }
}

fmix_worktree_schema_manifest_is_prefix() {
    local worktree="$1" key="$2" manifest current recorded_key
    manifest="$(fmix_worktree_schema_manifest_file "$worktree" "$key")" || return 1
    [[ -s "$manifest" ]] || return 1
    recorded_key="$(fmix_schema_key_from_manifest "$manifest")" || return 1
    [[ "$recorded_key" == "$key" ]] || return 1
    current="$(mktemp)" || return 1
    fmix_write_schema_manifest "$worktree" "$current" || { rm -f "$current"; return 1; }
    fmix_manifest_is_prefix "$manifest" "$current"
    local rc=$?
    rm -f "$current"
    return "$rc"
}

fmix_read_state() {
    # Read a field from a JSON state file (supports strings, numbers, booleans)
    local state_file="$1" field="$2"
    [[ -f "$state_file" ]] || return 1
    local line
    line="$(grep -E "\"${field}\"[[:space:]]*:" "$state_file" 2>/dev/null | head -1)"
    if [[ "$line" =~ \"${field}\"[[:space:]]*:[[:space:]]*\"([^\"]*)\" ]]; then
        printf '%s\n' "${BASH_REMATCH[1]}"
    elif [[ "$line" =~ \"${field}\"[[:space:]]*:[[:space:]]*([0-9]+|true|false|null) ]]; then
        printf '%s\n' "${BASH_REMATCH[1]}"
    fi
}

fmix_write_worktree_state() {
    local key="${2:-}"
    if [[ "$key" =~ ^[0-9a-f]{16}$ ]]; then
        fmix_with_artifact_reference_lease "build-$key" _fmix_write_worktree_state_locked "$@"
    else
        _fmix_write_worktree_state_locked "$@"
    fi
}

_fmix_write_worktree_state_locked() {
    local worktree="$1" template_key="$2" db_name="$3"
    local mig_stamp="$4" last_used="$5"
    local db_schema_key="${6:-}" db_base_id="${7:-}" db_source_schema_key="${8:-${6:-}}"
    local state_file tmp_file
    state_file="$(fmix_worktree_state_file "$worktree")"
    mkdir -p "$(dirname "$state_file")" || return 1
    if [[ -n "$db_schema_key" ]]; then
        fmix_write_worktree_schema_manifest "$worktree" "$db_schema_key" || return 1
    fi
    local real_path
    real_path="$(fmix_realpath "$worktree")"
    tmp_file="${state_file}.tmp-$$"
    if ! cat >"$tmp_file" <<EOF
{
  "path": $(fmix_json_escape "$real_path"),
  "template_key": $(fmix_json_escape "$template_key"),
  "db_name": $(fmix_json_escape "$db_name"),
  "db_schema_key": $(fmix_json_escape "$db_schema_key"),
  "db_source_schema_key": $(fmix_json_escape "$db_source_schema_key"),
  "db_base_id": $(fmix_json_escape "$db_base_id"),
  "last_migration_stamp": $(fmix_json_escape "$mig_stamp"),
  "last_used": $(fmix_json_escape "$last_used")
}
EOF
    then
        rm -f "$tmp_file"
        return 1
    fi
    mv "$tmp_file" "$state_file" || { rm -f "$tmp_file"; return 1; }
}

fmix_update_last_used() {
    local state_file="$1"
    [[ -f "$state_file" ]] || return 0
    local now
    now="$(fmix_now)"
    local tmp
    tmp="$(mktemp)"
    sed "s/\"last_used\": \"[^\"]*\"/\"last_used\": \"$now\"/" "$state_file" >"$tmp" \
        || { rm -f "$tmp"; return 1; }
    mv "$tmp" "$state_file" || { rm -f "$tmp"; return 1; }
}

fmix_read_template_meta() {
    local key="$1" field="$2"
    local tdir meta
    tdir="$(fmix_template_dir "$key")" || return 1
    meta="$tdir/meta.json"
    [[ -f "$meta" ]] || return 1
    grep -o "\"${field}\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" "$meta" 2>/dev/null \
        | head -1 | sed 's/.*: *"\(.*\)".*/\1/'
}

fmix_write_template_meta() {
    # Write meta.json to an arbitrary target directory (NOT necessarily the live template dir).
    # Callers must pass the full directory path as $1 (not the key).
    local dir="$1" status="$2" built_at="$3" toolchain="$4" source_commit="$5"
    local template_key="${6:-}" manifest_sha="${7:-}"
    local meta="$dir/meta.json" schema="$FMIX_TEMPLATE_SCHEMA" runner_sha="" extra=""
    if [[ "$dir" == "$FMIX_HOME/artifacts/v2/templates/"* ]]; then
        runner_sha="$(fmix_hash_stdin <"$(fmix_realpath "${BASH_SOURCE[0]}")")" || return 1
        schema=2
        printf -v extra '  "producer_runner_sha256": "%s",\n  "consumer_protocol": "fmix-native-artifacts.v2",' "$runner_sha"
    fi
    mkdir -p "$dir"
    cat >"$meta" <<EOF
{
  "schema": "$schema",
  "status": $(fmix_json_escape "$status"),
  "template_key": $(fmix_json_escape "$template_key"),
  "manifest_sha256": $(fmix_json_escape "$manifest_sha"),
  "built_at": $(fmix_json_escape "$built_at"),
  "toolchain": $(fmix_json_escape "$toolchain"),
$extra
  "source_commit": $(fmix_json_escape "$source_commit")
}
EOF
}

fmix_template_access_file() {
    local key="${1:-}" v2
    v2="$(fmix_template_v2_dir "$key")" || return 1
    if [[ -e "$v2" || -L "$v2" ]]; then
        printf '%s/artifact-access/v2/templates/%s\n' "$FMIX_HOME" "$key"
    else
        printf '%s/template-access/%s\n' "$FMIX_HOME" "$key"
    fi
}

fmix_update_template_last_used() {
    # Access timestamps live outside the CAS and land via one atomic
    # mktemp+mv, so a lease is never acquired just to refresh one. When the
    # caller already holds the exact build lease, keep the fail-closed
    # keeper check (a dead keeper is corrupt hold state) and write through
    # the same atomic path.
    local key="${1:-}" lock_name index
    [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
    # A pressure-held producer kept a proven session, not a cache generation.
    # Do not invent a successful cache access for a generation never published.
    if [[ "${FMIX_TEMPLATE_PUBLICATION_HELD_KEY:-}" == "$key" ]] \
        && ! fmix_template_is_complete "$key"; then
        return 0
    fi
    lock_name="build-$key"
    if index="$(fmix_lock_find_index "$lock_name")"; then
        kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
    fi
    _fmix_update_template_last_used_write "$key"
}

_fmix_update_template_last_used_write() {
    # Templates are immutable. Mutable access accounting lives beside the CAS,
    # never inside it, so concurrent readers cannot alter a published tree.
    local key="$1" access tmp v2
    [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
    v2="$(fmix_template_v2_dir "$key")" || return 1
    if [[ -e "$v2" || -L "$v2" ]]; then
        fmix_artifact_v2_managed_entrypoint || return 1
    fi
    access="$(fmix_template_access_file "$key")"
    if [[ "$access" == "$FMIX_HOME/artifact-access/v2/templates/"* ]]; then
        fmix_artifact_v2_prepare_directory "artifact-access/v2/templates" || return 1
    else
        mkdir -p "$(dirname "$access")" || return 1
    fi
    tmp="$(mktemp "${access}.tmp.XXXXXX")" || return 1
    printf '%s\n' "$(fmix_now)" >"$tmp" || { rm -f "$tmp"; return 1; }
    mv "$tmp" "$access" || { rm -f "$tmp"; return 1; }
}

fmix_read_template_last_used() {
    local key="$1" access value
    access="$(fmix_template_access_file "$key")"
    if [[ -s "$access" ]]; then
        IFS= read -r value <"$access"
        printf '%s\n' "$value"
    else
        fmix_read_template_meta "$key" "built_at"
    fi
}

# ---------------------------------------------------------------------------
# Full-operation kernel locking with legacy mkdir interoperability
# ---------------------------------------------------------------------------

fmix_lock_process_start() {
    ps -o lstart= -p "$1" 2>/dev/null | sed 's/^[[:space:]]*//; s/[[:space:]]*$//'
}

fmix_lock_find_index() {
    local lock_name="$1" i
    for (( i = 0; i < ${#FMIX_HELD_LOCK_NAMES[@]}; i++ )); do
        if [[ "${FMIX_HELD_LOCK_NAMES[$i]:-}" == "$lock_name" ]]; then
            printf '%s\n' "$i"
            return 0
        fi
    done
    return 1
}

fmix_lock_quarantine_metadata() {
    local lock_name="$1" lock_dir="$2" reason="$3" destination
    local expected_snapshot="${4:-}" current_snapshot
    [[ "$lock_name" =~ ^[A-Za-z0-9._-]+$ ]] || return 1
    if [[ ! -d "$lock_dir" || -L "$lock_dir" ]]; then
        [[ -z "$expected_snapshot" ]] && return 0
        return 1
    fi
    destination="$FMIX_HOME/lock-metadata/stale/${lock_name}.$(fmix_epoch).$$.${RANDOM}"
    mkdir -p "$(dirname "$destination")" || return 1
    if [[ -n "$expected_snapshot" ]]; then
        current_snapshot="$(fmix_lock_publication_snapshot "$lock_dir")" || return 1
        [[ "$current_snapshot" == "$expected_snapshot" ]] || return 1
    fi
    if mv "$lock_dir" "$destination"; then
        fmix_warn "Quarantined stale lock metadata for '$lock_name' ($reason): $destination"
        return 0
    fi
    return 1
}

fmix_lock_publication_snapshot() {
    local lock_dir="$1" path
    [[ -d "$lock_dir" && ! -L "$lock_dir" ]] || return 1
    if [[ "$FMIX_OS" == Darwin ]]; then
        stat -f '%d:%i' "$lock_dir" || return 1
    else
        stat -c '%d:%i' "$lock_dir" || return 1
    fi
    for path in "$lock_dir"/* "$lock_dir"/.[!.]* "$lock_dir"/..?*; do
        [[ -e "$path" || -L "$path" ]] || continue
        [[ "$path" == "$lock_dir/pid" || "$path" == "$lock_dir/owner" ]] || return 1
        [[ -f "$path" && ! -L "$path" ]] || return 1
    done
    for path in "$lock_dir/pid" "$lock_dir/owner"; do
        if [[ -e "$path" ]]; then
            fmix_hash_files "$path" || return 1
        else
            printf 'absent:%s\n' "$path"
        fi
    done
}

fmix_lock_keeper_start() {
    local path="$1" mode="$2" timeout="$3"
    local diagnostic_name="${4:-lock}"
    local lock_name="${5:-${diagnostic_name:-lock}}"
    local py_bin owner_pid owner_file state keeper_pid status keeper_source
    local bootstrap_deadline acquire_deadline="" failure="keeper exited before readiness"
    local probe_pid
    # Failed retirement is not contention. Preserve its exact recovery handle
    # rather than overwriting it with a second keeper, even for a different lock.
    if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]; then
        printf '{"error":"lock_keeper_cleanup_pending"}\n' >&2
        return 70
    fi
    for probe_pid in ${FMIX_LOCK_STOP_PROBE_PIDS[@]+"${FMIX_LOCK_STOP_PROBE_PIDS[@]}"}; do
        if kill -0 "$probe_pid" 2>/dev/null; then
            printf '{"error":"lock_keeper_cleanup_probe_pending"}\n' >&2
            return 70
        fi
        wait "$probe_pid" 2>/dev/null || true
    done
    FMIX_LOCK_STOP_PROBE_PIDS=()
    FMIX_LAST_LOCK_KEEPER_PID=""
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    # Bash 3.2 does not expose BASHPID, and $$ intentionally remains the
    # top-level shell PID inside a subshell. Ask a short-lived child for its
    # real parent so the keeper monitors the process that actually owns it.
    owner_pid="${BASHPID:-}"
    if [[ ! "$owner_pid" =~ ^[0-9]+$ ]]; then
        owner_file="$(mktemp)" || {
            printf '{"error":"lock_keeper_bootstrap_failed","reason":"owner discovery preparation failed"}\n' >&2
            return 70
        }
        if ! "$py_bin" -c 'import os; print(os.getppid())' >"$owner_file" \
            || ! IFS= read -r owner_pid <"$owner_file"; then
            rm -f "$owner_file"
            printf '{"error":"lock_keeper_bootstrap_failed","reason":"owner discovery failed"}\n' >&2
            return 70
        fi
        rm -f "$owner_file"
        [[ "$owner_pid" =~ ^[0-9]+$ ]] || {
            printf '{"error":"lock_keeper_bootstrap_failed","reason":"invalid keeper owner"}\n' >&2
            return 70
        }
    fi
    mkdir -p "$FMIX_HOME/lock-keeper-state" || {
        printf '{"error":"lock_keeper_bootstrap_failed","reason":"state preparation failed"}\n' >&2
        fmix_error "Check filesystem permissions and agent sandbox write access to FMIX_HOME: $FMIX_HOME"
        return 70
    }
    state="$FMIX_HOME/lock-keeper-state/${lock_name}.${owner_pid}.${RANDOM}.state"
    # Keep the program in argv, not a background heredoc pipe that Bash must
    # fill before exec. A quoted literal also avoids a heredoc-backed command
    # substitution while retaining the single-file Bash 3.2 runner contract.
    keeper_source='import errno
import fcntl
import json
import os
import signal
import sys
import time
from pathlib import Path

path = sys.argv[1]
mode = sys.argv[2]
timeout = int(sys.argv[3])
diag_name = sys.argv[4] if sys.argv[4] else "lock"
lock_name = sys.argv[5] if sys.argv[5] else diag_name
fmix_home = sys.argv[6]
owner_pid = int(sys.argv[7])
state_path = Path(sys.argv[8])

start_time = time.monotonic()
deadline = start_time + timeout
last_heartbeat = start_time
stop_requested = False


def request_stop(_signum, _frame):
    global stop_requested
    stop_requested = True


def io_failure(operation, target, error):
    hint = "Check available disk space and filesystem health for FMIX_HOME."
    if error.errno in (errno.EACCES, errno.EPERM, errno.EROFS):
        hint = (
            "Check filesystem permissions and agent sandbox write access to the configured "
            "FMIX_HOME. Retry only after access is authorized; do not bypass locks or "
            "relocate only lock state away from the shared cache."
        )
    sys.stderr.write(json.dumps({
        "error": "lock_keeper_io_failed", "operation": operation,
        "path": str(target), "errno": error.errno, "hint": hint,
    }) + "\n")
    sys.stderr.flush()
    raise SystemExit(70)


def publish_state(value):
    temporary = state_path.with_name(
        state_path.name + f".tmp-{os.getpid()}"
    )
    try:
        temporary.write_text(value + "\n", encoding="utf-8")
        os.replace(temporary, state_path)
    except OSError as error:
        io_failure("publish_state", state_path, error)


def owner_alive():
    if os.getppid() != owner_pid:
        return False
    try:
        os.kill(owner_pid, 0)
    except OSError:
        return False
    return True


def get_holder_info(lock_name, fmix_home):
    if not lock_name or not fmix_home:
        return "unknown", diag_name
    meta_path = Path(fmix_home) / "lock-metadata" / f"{lock_name}.json"
    if meta_path.is_file():
        try:
            d = json.loads(meta_path.read_text(encoding="utf-8"))
            return str(d.get("pid", "unknown")), d.get("purpose", diag_name)
        except Exception:
            pass
    legacy_pid = Path(fmix_home) / "locks" / lock_name / "pid"
    if legacy_pid.is_file():
        try:
            p = legacy_pid.read_text(encoding="utf-8").strip()
            if p:
                return p, diag_name
        except Exception:
            pass
    return "unknown", diag_name

signal.signal(signal.SIGTERM, request_stop)
signal.signal(signal.SIGINT, request_stop)
publish_state("started")
try:
    fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
except OSError as error:
    io_failure("open_kernel_lock", path, error)
os.set_inheritable(fd, False)
operation = fcntl.LOCK_SH if mode == "shared" else fcntl.LOCK_EX
try:
    while not stop_requested and owner_alive():
        try:
            fcntl.flock(fd, operation | fcntl.LOCK_NB)
            break
        except BlockingIOError:
            now = time.monotonic()
            if now >= deadline:
                publish_state("timeout")
                raise SystemExit(1)
            if now - last_heartbeat >= 15.0:
                elapsed = int(now - start_time)
                holder_pid, purpose = get_holder_info(lock_name, fmix_home)
                sys.stderr.write(
                    f"[fmix] Waiting for lock {lock_name!r} ({elapsed}s elapsed, "
                    f"timeout {timeout}s, holder PID: {holder_pid}, "
                    f"purpose: \"{purpose}\") ...\n"
                )
                sys.stderr.flush()
                last_heartbeat = now
            time.sleep(0.05)
        except OSError as error:
            io_failure("acquire_kernel_lock", path, error)
    else:
        publish_state("stopped")
        raise SystemExit(1)

    publish_state("ready")
    while not stop_requested and owner_alive():
        time.sleep(0.05)
finally:
    os.close(fd)
'
    (
        exec "$py_bin" -c "$keeper_source" "$path" "$mode" "$timeout" \
            "$diagnostic_name" "$lock_name" "$FMIX_HOME" "$owner_pid" "$state" </dev/null
    ) >/dev/null &
    keeper_pid=$!
    FMIX_LAST_LOCK_KEEPER_PID="$keeper_pid"
    # Bootstrap is separate from legitimate lock contention. Zero-timeout
    # try-locks still need a finite startup allowance, but a started keeper may
    # wait for the original contention timeout. SECONDS is shell-local and
    # avoids launching a clock subprocess for every poll.
    bootstrap_deadline=$(( SECONDS + 5 ))
    while true; do
        if [[ -s "$state" ]]; then
            IFS= read -r status <"$state"
            case "$status" in
                ready)
                    if kill -0 "$keeper_pid" 2>/dev/null; then
                        rm -f "$state" 2>/dev/null || true
                        FMIX_LAST_LOCK_KEEPER_PID="$keeper_pid"
                        return 0
                    fi
                    break
                    ;;
                started)
                    # Do not unlink an intermediate state: the atomic ready
                    # publication could otherwise be removed before we read it.
                    [[ -n "$acquire_deadline" ]] \
                        || acquire_deadline=$(( SECONDS + 10#$timeout + 1 ))
                    ;;
                timeout)
                    # Only the keeper's actual flock contention is retryable.
                    fmix_lock_keeper_retire "$keeper_pid" "$state" || return 70
                    return 1
                    ;;
                *)
                    failure="invalid keeper handshake"
                    break
                    ;;
            esac
        fi
        if ! kill -0 "$keeper_pid" 2>/dev/null; then
            break
        fi
        if [[ -z "$acquire_deadline" ]]; then
            if (( SECONDS >= bootstrap_deadline )); then
                failure="keeper bootstrap deadline exceeded"
                break
            fi
        elif (( SECONDS >= acquire_deadline )); then
            failure="keeper readiness deadline exceeded"
            break
        fi
        sleep 0.05
    done
    # This is exactly the child launched above, never an inferred lock holder.
    printf '{"error":"lock_keeper_bootstrap_failed","reason":"%s"}\n' "$failure" >&2
    fmix_lock_keeper_retire "$keeper_pid" "$state" || return 70
    return 70
}

fmix_lock_keeper_reap_completed() {
    local keeper_pid="$1" job_line
    local terminal_job='^\[[0-9]+\][+-]?[[:space:]]+([1-9][0-9]*)[[:space:]]+(Done|Exit|Killed|Terminated|Hangup|Interrupt)([[:space:]:]|$)'
    # A terminal entry permits nonblocking wait, never a signal. The one
    # shell-owned C-locale snapshot excludes Running/Stopped/unknown states.
    # Recheck kernel liveness AFTER reap: a cached Done entry with a reused
    # numeric PID must still refuse, not supply signal or cleanup authority.
    while IFS= read -r job_line; do
        if [[ "$job_line" =~ $terminal_job && "${BASH_REMATCH[1]}" == "$keeper_pid" ]]; then
            wait "$keeper_pid" 2>/dev/null || true
            ! kill -0 "$keeper_pid" 2>/dev/null
            return $?
        fi
    done <<<"$(LC_ALL=C jobs -l)"
    return 1
}

fmix_lock_keeper_signal_owned() {
    local keeper_pid="$1" signal="$2" child_pid
    [[ "$keeper_pid" =~ ^[1-9][0-9]*$ && ( "$signal" == TERM || "$signal" == KILL ) ]] || return 70
    # A cached Done job can outlive its kernel PID. Require a current running
    # job before every keeper/registered-probe signal, not just admission. This
    # closes the already-completed-job case; it is not atomic pidfd identity
    # protection against exit/PID reuse between this observation and kill.
    for child_pid in $(jobs -pr); do
        if [[ "$child_pid" == "$keeper_pid" ]]; then
            kill "-$signal" "$keeper_pid" 2>/dev/null || true
            return 0
        fi
    done
    if ! kill -0 "$keeper_pid" 2>/dev/null; then
        wait "$keeper_pid" 2>/dev/null || true
        return 0
    fi
    printf '{"error":"lock_keeper_cleanup_unowned"}\n' >&2
    return 70
}

fmix_lock_keeper_stop() {
    local keeper_pid="${1:-}" child_pid owned=0 py_bin probe_source probe_pid
    local cleanup_deadline kill_at remaining ignored keeper_done=0 probe_done=0
    local keeper_killed=0 probe_killed=0 keeper_refused=0 probe_refused=0
    local probe_channel probe_channel_open=0 probe_channel_ready=0
    [[ "$keeper_pid" =~ ^[1-9][0-9]*$ ]] || return 70
    # One shell-owned deadline includes interpreter startup, both signal
    # phases, and probe retirement. SECONDS is coarse: reserve its final tick
    # for nonblocking reap checks, leaving headroom below the four-second
    # cleanup contract without waiting on another external clock or sleep.
    cleanup_deadline=$(( SECONDS + 3 ))
    kill_at=$(( cleanup_deadline - 1 ))
    # These handles come only from our own prior launches. Do not signal a
    # retained PID later (it could have been reused), or replace unresolved
    # recovery state with another probe. Only proven exits can be reaped here.
    for child_pid in ${FMIX_LOCK_STOP_PROBE_PIDS[@]+"${FMIX_LOCK_STOP_PROBE_PIDS[@]}"}; do
        if kill -0 "$child_pid" 2>/dev/null; then
            printf '{"error":"lock_keeper_cleanup_probe_pending"}\n' >&2
            return 70
        fi
        wait "$child_pid" 2>/dev/null || true
    done
    FMIX_LOCK_STOP_PROBE_PIDS=()
    # Only running jobs supply current ownership evidence; jobs -p also lists
    # completed jobs whose numeric PID may already belong to another process.
    for child_pid in $(jobs -pr); do
        [[ "$child_pid" != "$keeper_pid" ]] || owned=1
    done
    if (( owned == 0 )); then
        fmix_lock_keeper_reap_completed "$keeper_pid" && return 0
        if ! kill -0 "$keeper_pid" 2>/dev/null; then
            wait "$keeper_pid" 2>/dev/null || true
            return 0
        fi
        printf '{"error":"lock_keeper_cleanup_unowned"}\n' >&2
        return 70
    fi
    py_bin="$(fmix_python_bin)"
    # The probe only waits for exit. Its exit status, error, EOF or startup
    # timeout never proves keeper exit: the owning shell checks that itself.
    probe_channel="$FMIX_HOME/.lock-stop-probe-$$-$RANDOM-$RANDOM"
    [[ ! -e "$probe_channel" && ! -L "$probe_channel" ]] || {
        printf '{"error":"lock_keeper_cleanup_failed"}\n' >&2
        return 70
    }
    # Preparation runs in the same registered background child as the probe:
    # no foreground mkfifo/interpreter startup or blocking FIFO open can run
    # beyond the owning shell deadline. A writer connects nonblockingly only
    # after our read/write open; it then unlinks the private create-only FIFO.
    probe_source='import errno, os, sys, time
pid = int(sys.argv[1])
channel = sys.argv[2]
fd = -1
created = False
try:
    os.mkfifo(channel, 0o600)
    created = True
    while fd < 0:
        try:
            fd = os.open(channel, os.O_WRONLY | os.O_NONBLOCK)
        except OSError as exc:
            if exc.errno not in (errno.ENXIO, errno.EINTR):
                raise
            time.sleep(0.05)
    os.unlink(channel)
    created = False
    os.write(fd, b".")
    while True:
        try:
            os.kill(pid, 0)
        except ProcessLookupError:
            raise SystemExit(0)
        except OSError:
            raise SystemExit(1)
        # Wake the shell; this is not keeper exit or signal-ownership proof.
        os.write(fd, b".")
        time.sleep(0.05)
finally:
    if fd >= 0:
        os.close(fd)
    if created:
        os.unlink(channel)'
    fmix_lock_keeper_signal_owned "$keeper_pid" TERM || return 70
    # Unlike process substitution, this single exec job is visible in jobs -pr
    # on both Bash 3.2 and 5. Capture only this exact freshly launched child.
    (umask 077; exec "$py_bin" -c "$probe_source" "$keeper_pid" "$probe_channel" </dev/null) >/dev/null 2>/dev/null &
    probe_pid=$!
    FMIX_LOCK_STOP_PROBE_PIDS=("$probe_pid")
    while (( SECONDS < cleanup_deadline )); do
        if ! kill -0 "$keeper_pid" 2>/dev/null; then keeper_done=1; fi
        if (( probe_done == 0 )) && ! kill -0 "$probe_pid" 2>/dev/null; then
            wait "$probe_pid" 2>/dev/null || true
            probe_done=1
            (( probe_refused )) || FMIX_LOCK_STOP_PROBE_PIDS=()
        fi
        if (( keeper_done && probe_done )); then
            (( keeper_refused == 0 && probe_refused == 0 )) || return 70
            [[ ! -e "$probe_channel" && ! -L "$probe_channel" ]] || break
            wait "$keeper_pid" 2>/dev/null || true
            return 0
        fi
        if (( probe_channel_open == 0 )) && [[ -p "$probe_channel" && ! -L "$probe_channel" ]]; then
            if exec 9<>"$probe_channel"; then probe_channel_open=1; fi
        fi
        if (( keeper_done || probe_done || SECONDS >= kill_at )); then
            if (( keeper_done == 0 && keeper_killed == 0 && keeper_refused == 0 )); then
                if fmix_lock_keeper_signal_owned "$keeper_pid" KILL; then
                    keeper_killed=1
                else
                    keeper_refused=1
                fi
            fi
            if (( probe_done == 0 && probe_killed == 0 && probe_refused == 0 \
                  && (probe_channel_ready || SECONDS >= kill_at) )); then
                if fmix_lock_keeper_signal_owned "$probe_pid" KILL; then
                    probe_killed=1
                else
                    probe_refused=1
                    printf '{"error":"lock_keeper_cleanup_probe_unowned"}\n' >&2
                fi
            fi
        fi
        # A failed/retired probe does not permit waiting on a live keeper.
        if (( probe_done && keeper_done == 0 && (keeper_killed || keeper_refused) )); then break; fi
        remaining=$(( cleanup_deadline - SECONDS ))
        # Our read/write open masks FIFO EOF. Once retirement is observed or
        # requested, a timed read can waste a full second on an exited writer;
        # use only nonblocking liveness/reap checks inside the same deadline.
        if (( remaining > 1 && probe_channel_open && keeper_done == 0 \
              && probe_done == 0 && keeper_killed == 0 && probe_killed == 0 \
              && keeper_refused == 0 && probe_refused == 0 )); then
            if IFS= read -r -n 1 -t 1 ignored <&9; then probe_channel_ready=1; fi
        fi
        # During the final coarse clock tick only builtins run: no new probe,
        # foreground ps/sleep, deadline reset, or blocking wait can extend it.
    done
    if (( keeper_done == 0 && keeper_killed == 0 && keeper_refused == 0 )); then
        fmix_lock_keeper_signal_owned "$keeper_pid" KILL || keeper_refused=1
    fi
    if (( probe_done == 0 && probe_killed == 0 && probe_refused == 0 )); then
        if fmix_lock_keeper_signal_owned "$probe_pid" KILL; then
            probe_killed=1
        else
            probe_refused=1
            printf '{"error":"lock_keeper_cleanup_probe_unowned"}\n' >&2
        fi
    fi
    if (( probe_done == 0 )) && ! kill -0 "$probe_pid" 2>/dev/null; then
        wait "$probe_pid" 2>/dev/null || true
        probe_done=1
        (( probe_refused )) || FMIX_LOCK_STOP_PROBE_PIDS=()
    fi
    # A refused probe signal stays latched even after a later confirmed exit.
    # Keep its recovery handle; never turn disappearance into a green cleanup.
    (( keeper_refused == 0 && probe_refused == 0 )) || return 70
    if [[ -e "$probe_channel" || -L "$probe_channel" ]]; then
        # An orphaned channel is not a live child or a signal permit. Retain
        # the caller's typed cleanup failure, but never restore an already
        # reaped numeric PID (which could now belong to another process).
        (( probe_done )) || FMIX_LOCK_STOP_PROBE_PIDS=("$probe_pid")
        printf '{"error":"lock_keeper_cleanup_probe_channel_pending"}\n' >&2
        return 70
    fi
    if (( probe_done )) && ! kill -0 "$keeper_pid" 2>/dev/null; then
        wait "$keeper_pid" 2>/dev/null || true
        return 0
    fi
    printf '{"error":"lock_keeper_cleanup_failed"}\n' >&2
    return 70
} 9<&-

fmix_lock_keeper_retire() {
    local keeper_pid="${1:-}" state="${2:-}"
    [[ "$keeper_pid" =~ ^[1-9][0-9]*$ ]] || return 70
    # Do not replace another unresolved owner. Held locks also retain their
    # indexed handles; an unadmitted keeper needs this explicit recovery slot.
    if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" \
        && "$FMIX_PENDING_LOCK_KEEPER_PID" != "$keeper_pid" ]]; then
        printf '{"error":"lock_keeper_cleanup_pending"}\n' >&2
        return 70
    fi
    fmix_lock_keeper_stop "$keeper_pid" || {
        FMIX_PENDING_LOCK_KEEPER_PID="$keeper_pid"
        [[ -z "$state" ]] || FMIX_PENDING_LOCK_KEEPER_STATE="$state"
        return 70
    }
    # Only the bounded stopper's confirmed exit permits state/handle removal.
    if [[ "$FMIX_PENDING_LOCK_KEEPER_PID" == "$keeper_pid" ]]; then
        [[ -n "$state" ]] || state="$FMIX_PENDING_LOCK_KEEPER_STATE"
        FMIX_PENDING_LOCK_KEEPER_PID=""
        FMIX_PENDING_LOCK_KEEPER_STATE=""
    fi
    [[ -z "$state" ]] || rm -f "$state" "$state.tmp-$keeper_pid" 2>/dev/null || true
    [[ "$FMIX_LAST_LOCK_KEEPER_PID" != "$keeper_pid" ]] || FMIX_LAST_LOCK_KEEPER_PID=""
    return 0
}

fmix_lock_acquire() {
    local lock_name="${1:-}" timeout="${2:-$FMIX_LOCK_TIMEOUT}"
    local diagnostic_name="${3:-${1:-}}" lock_dir kernel_file deadline
    local passive="${4:-0}" metadata_file metadata_document
    local mode="${5:-exclusive}"
    local keeper_pid token owner_start holder_pid holder_start recorded_start
    local lock_mtime lock_age grace printed_wait=0 index py_bin
    local publication_identity publication_snapshot current_snapshot rollback_keeper_pid rollback_rc rollback_stop_at

    [[ "$lock_name" =~ ^[A-Za-z0-9._-]+$ ]] || {
        fmix_error "Invalid FMix lock name: '${lock_name:-empty}'."
        return 1
    }
    [[ "$passive" == "0" || "$passive" == "1" ]] || {
        fmix_error "Invalid passive FMix lock mode."
        return 1
    }
    [[ "$mode" == "exclusive" || "$mode" == "shared" ]] || {
        fmix_error "Invalid FMix lock lease mode: '${mode:-empty}'."
        return 1
    }
    if [[ "$mode" == "shared" && "$passive" == "1" ]]; then
        fmix_error "Passive artifact leases are always exclusive; shared read leases are not passive."
        return 1
    fi
    if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]; then
        printf '{"error":"lock_keeper_cleanup_pending"}\n' >&2
        return 70
    fi
    if index="$(fmix_lock_find_index "$lock_name")"; then
        fmix_error "Nested acquisition of FMix lock '$diagnostic_name' is not supported (keeper pid=${FMIX_HELD_LOCK_KEEPER_PIDS[$index]})."
        return 1
    fi
    py_bin="$(fmix_python_bin)"
    "$py_bin" -c 'import fcntl' >/dev/null 2>&1 || {
            fmix_error "Python fcntl.flock support is required for FMix cache coordination."
            return 1
        }

    timeout="$(fmix_uint_or_default "$timeout" "$FMIX_LOCK_TIMEOUT" "lock timeout")"
    grace="$(fmix_uint_or_default "$FMIX_LOCK_INIT_GRACE" 5 FMIX_LOCK_INIT_GRACE)"
    deadline=$(( $(fmix_epoch) + timeout ))
    lock_dir="$FMIX_HOME/locks/$lock_name"
    kernel_file="$FMIX_HOME/lock-kernel/$lock_name"
    metadata_file="$FMIX_HOME/lock-metadata/${lock_name}.json"
    mkdir -p "$FMIX_HOME/locks" "$FMIX_HOME/lock-kernel" "$FMIX_HOME/lock-metadata" || return 1

    while true; do
        local remaining=$(( deadline - $(fmix_epoch) ))
        (( remaining >= 0 )) || remaining=0
        local keeper_rc=0
        fmix_lock_keeper_start "$kernel_file" "$mode" "$remaining" \
            "$diagnostic_name" "$lock_name" || keeper_rc=$?
        if (( keeper_rc != 0 )); then
            (( keeper_rc == 1 )) || return "$keeper_rc"
            fmix_error "Timed out waiting for kernel lock '$diagnostic_name' after ${timeout}s."
            fmix_error "Inspect with: fmix status"
            return 1
        fi
        keeper_pid="$FMIX_LAST_LOCK_KEEPER_PID"

        # Retirement is passive: do not interpret or repair legacy lock state.
        # Refuse preexisting metadata while holding the kernel lease, then release only our keeper.
        if [[ "$passive" == "1" && ( -e "$lock_dir" || -L "$lock_dir" || -e "$metadata_file" || -L "$metadata_file" ) ]]; then
            # Cross-pod shared homes: our keeper already holds the kernel lease,
            # so a preexisting record can only belong to a DEAD holder. When the
            # death is provable (recorded pid gone, or pid+start pair reused --
            # the exact conditions the active path quarantines on), quarantine
            # the dead record -- never rewrite it -- and retry the acquisition.
            # Unprovable records are still refused; passive holders never
            # interpret live state.
            local passive_dead=0 passive_pid passive_recorded_start passive_live_start
            if [[ -d "$lock_dir" && ! -L "$lock_dir" ]]; then
                passive_pid="$(cat "$lock_dir/pid" 2>/dev/null || true)"
                passive_recorded_start="$(sed -n 's/^start=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
                passive_live_start=""
                [[ "$passive_pid" =~ ^[0-9]+$ ]] \
                    && passive_live_start="$(fmix_lock_process_start "$passive_pid")"
                if [[ "$passive_pid" =~ ^[0-9]+$ ]] \
                    && { [[ -z "$passive_live_start" ]] \
                        || { [[ -n "$passive_recorded_start" ]] \
                            && [[ "$passive_recorded_start" != "$passive_live_start" ]]; }; }; then
                    passive_dead=1
                fi
            elif [[ -e "$metadata_file" && ! -L "$metadata_file" ]]; then
                passive_pid="$(sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$metadata_file" | head -1)"
                if [[ "$passive_pid" =~ ^[0-9]+$ ]] && ! kill -0 "$passive_pid" 2>/dev/null; then
                    passive_dead=1
                fi
            fi
            if (( passive_dead == 1 )); then
                fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
                    "dead holder record observed with kernel lease free" || true
                if [[ -e "$metadata_file" && ! -L "$metadata_file" ]]; then
                    mv "$metadata_file" \
                        "$FMIX_HOME/lock-metadata/stale/${lock_name}.$(fmix_epoch).$$.${RANDOM}.json" \
                        2>/dev/null || true
                fi
                fmix_lock_keeper_retire "$keeper_pid" || return 70
                sleep 0.05
                continue
            fi
            fmix_lock_keeper_retire "$keeper_pid" || return 70
            fmix_error "Passive artifact lease held by preexisting lock metadata."
            return 1
        fi

        # Keep a directory-shaped record for older FMix binaries. mkdir remains
        # the mixed-version arbitration point, while the persistent inode above
        # is the authority for all v2 contenders and stays locked until release.
        if [[ -d "$lock_dir" && ! -L "$lock_dir" ]]; then
            holder_pid="$(cat "$lock_dir/pid" 2>/dev/null || true)"
            recorded_start="$(sed -n 's/^start=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
            holder_start=""
            [[ "$holder_pid" =~ ^[0-9]+$ ]] \
                && holder_start="$(fmix_lock_process_start "$holder_pid")"
            if [[ ! "$holder_pid" =~ ^[0-9]+$ ]]; then
                lock_mtime="$(fmix_stat_mtime "$lock_dir" 2>/dev/null || fmix_epoch)"
                lock_age=$(( $(fmix_epoch) - lock_mtime ))
                if (( lock_age >= grace )); then
                    fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
                        "owner publication never completed" || {
                            fmix_lock_keeper_retire "$keeper_pid" || return 70
                            return 1
                        }
                else
                    fmix_lock_keeper_retire "$keeper_pid" || return 70
                    sleep 0.05
                    continue
                fi
            elif [[ -z "$holder_start" ]] \
                || { [[ -n "$recorded_start" ]] && [[ "$recorded_start" != "$holder_start" ]]; }; then
                fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
                    "dead or reused pid $holder_pid" || {
                        fmix_lock_keeper_retire "$keeper_pid" || return 70
                        return 1
                    }
            else
                if [[ "$mode" == "shared" ]] \
                    && fmix_lock_owner_declares_shared "$lock_dir"; then
                    # A live shared publisher owns the legacy record. Join it:
                    # the kernel LOCK_SH lease already arbitrates against every
                    # exclusive contender, and the publisher retires the record.
                    token="$(
                        printf '%s:%s:%s:%s\n' "$$" "$RANDOM" "$(fmix_epoch)" "$lock_name" \
                            | fmix_hash_stdin | cut -c1-24
                    )"
                    FMIX_HELD_LOCK_NAMES+=("$lock_name")
                    FMIX_HELD_LOCK_KEEPER_PIDS+=("$keeper_pid")
                    FMIX_HELD_LOCK_TOKENS+=("$token")
                    FMIX_HELD_LOCK_MODES+=("shared")
                    FMIX_HELD_LOCK_PUBLISHED+=(0)
                    return 0
                fi
                if (( printed_wait == 0 )); then
                    fmix_info "Waiting for mixed-version lock '$diagnostic_name' (pid=$holder_pid) …"
                    printed_wait=1
                fi
                fmix_lock_keeper_retire "$keeper_pid" || return 70
                if (( $(fmix_epoch) >= deadline )); then
                    fmix_error "Timed out waiting for mixed-version lock '$diagnostic_name' after ${timeout}s."
                    return 1
                fi
                sleep 0.1
                continue
            fi
        elif [[ -e "$lock_dir" || -L "$lock_dir" ]]; then
            fmix_lock_keeper_retire "$keeper_pid" || return 70
            fmix_error "Lock metadata path is not a directory: $lock_dir"
            return 1
        fi

        if ! mkdir "$lock_dir" 2>/dev/null; then
            fmix_lock_keeper_retire "$keeper_pid" || return 70
            if [[ "$passive" == "1" ]]; then
                fmix_error "Passive artifact lease lost the legacy directory-lock race."
                return 1
            fi
            if (( $(fmix_epoch) >= deadline )); then
                fmix_error "Timed out publishing lock metadata for '$diagnostic_name'."
                return 1
            fi
            sleep 0.05
            continue
        fi

        publication_identity="$(fmix_lock_publication_snapshot "$lock_dir")" || {
            fmix_lock_keeper_retire "$keeper_pid" || return 70
            printf '{"error":"lock_owner_publication_failed"}\n' >&2
            return 70
        }
        publication_identity="${publication_identity%%$'\n'*}"
        token="$(
            printf '%s:%s:%s:%s\n' "$$" "$RANDOM" "$(fmix_epoch)" "$lock_name" \
                | fmix_hash_stdin | cut -c1-24
        )"
        owner_start="$(fmix_lock_process_start "$$")"
        if ! printf '%d\n' "$$" >"$lock_dir/pid" \
            || ! cat >"$lock_dir/owner" <<EOF
token=$token
pid=$$
start=$owner_start
mode=$mode
session=${FMIX_ACTIVE_SESSION_HASH:-none}
command=${FMIX_INTERNAL_RUN_MODE:-${1:-fmix}}
EOF
        then
            publication_snapshot="$(fmix_lock_publication_snapshot "$lock_dir")" || publication_snapshot=""
            fmix_lock_keeper_retire "$keeper_pid" || return 70
            # Only successful owned retirement permits rollback. Recheck the
            # exact directory and published bytes after that yielding cleanup;
            # a changed/foreign path remains untouched, never stale-arbitrated
            # merely because our failed publication left a live $$ pid.
            current_snapshot="$(fmix_lock_publication_snapshot "$lock_dir")" || current_snapshot=""
            if [[ -n "$publication_snapshot" && "$current_snapshot" == "$publication_snapshot" \
                && "${current_snapshot%%$'\n'*}" == "$publication_identity" ]]; then
                # Retirement released the kernel. Reacquire that same inode
                # with zero contention wait before the final recheck/move, so
                # kernel-cooperating contenders cannot replace metadata in
                # between. No atomic FS-CAS is claimed against out-of-band
                # writers or legacy implementations that ignore this kernel.
                fmix_lock_keeper_start "$kernel_file" exclusive 0 \
                    "$diagnostic_name publication rollback" "$lock_name" || {
                        printf '{"error":"lock_owner_publication_rollback_unverified"}\n' >&2
                        return 70
                    }
                rollback_keeper_pid="$FMIX_LAST_LOCK_KEEPER_PID"
                rollback_rc=0
                fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
                    "owned incomplete publication rolled back" "$publication_snapshot" || rollback_rc=1
                # This short-lived rollback owner needs no second exit-probe
                # cycle. Use the ordinary stop's pre-escalation window and
                # current running-child signal check, then confirm actual exit
                # with builtins only. Unconfirmed exit retains the handle;
                # never extend the budget with another stopper invocation.
                rollback_stop_at=$(( SECONDS + 2 ))
                fmix_lock_keeper_signal_owned "$rollback_keeper_pid" TERM || {
                    FMIX_PENDING_LOCK_KEEPER_PID="$rollback_keeper_pid"
                    return 70
                }
                while kill -0 "$rollback_keeper_pid" 2>/dev/null \
                    && (( SECONDS < rollback_stop_at )); do :; done
                if kill -0 "$rollback_keeper_pid" 2>/dev/null; then
                    FMIX_PENDING_LOCK_KEEPER_PID="$rollback_keeper_pid"
                    printf '{"error":"lock_keeper_cleanup_failed"}\n' >&2
                    return 70
                fi
                fmix_lock_keeper_retire "$rollback_keeper_pid" || return 70
                if (( rollback_rc != 0 )); then
                    printf '{"error":"lock_owner_publication_rollback_failed"}\n' >&2
                    return 70
                fi
            else
                printf '{"error":"lock_owner_publication_rollback_unverified"}\n' >&2
                return 70
            fi
            fmix_error "Could not publish ownership for lock '$diagnostic_name'."
            printf '{"error":"lock_owner_publication_failed"}\n' >&2
            return 70
        fi

        # Publish structured lock-metadata without replacing unknown state.
        metadata_document="$(cat <<EOF
{
  "lock_name": $(fmix_json_escape "$lock_name"),
  "pid": $$,
  "mode": $(fmix_json_escape "$mode"),
  "start_time": $(fmix_json_escape "$(fmix_now)"),
  "purpose": $(fmix_json_escape "$diagnostic_name"),
  "worktree": $(fmix_json_escape "${FMIX_ACTIVE_WORKTREE:-}")
}
EOF
)"
        if [[ "$passive" == "1" ]]; then
            if ! (set -o noclobber; printf '%s\n' "$metadata_document" >"$metadata_file" 2>/dev/null); then
                fmix_lock_keeper_retire "$keeper_pid" || return 70
                printf '{"error":"passive_lock_metadata_collision"}\n' >&2
                return 70
            fi
        else
            printf '%s\n' "$metadata_document" >"$metadata_file" 2>/dev/null || true
        fi

        FMIX_HELD_LOCK_NAMES+=("$lock_name")
        FMIX_HELD_LOCK_KEEPER_PIDS+=("$keeper_pid")
        FMIX_HELD_LOCK_TOKENS+=("$token")
        FMIX_HELD_LOCK_MODES+=("$mode")
        FMIX_HELD_LOCK_PUBLISHED+=(1)
        return 0
    done
}

fmix_lock_release() {
    local lock_name="${1:-}" index keeper_pid token lock_dir recorded_token destination
    local published
    [[ -n "$lock_name" ]] || {
        fmix_error "fmix_lock_release called with empty lock name — refusing."
        return 1
    }
    index="$(fmix_lock_find_index "$lock_name")" || {
        lock_dir="$FMIX_HOME/locks/$lock_name"
        if [[ ! -e "$lock_dir" ]]; then
            return 0
        fi
        fmix_error "Refusing to release unowned FMix lock '$lock_name'."
        return 1
    }
    keeper_pid="${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}"
    token="${FMIX_HELD_LOCK_TOKENS[$index]}"
    published="${FMIX_HELD_LOCK_PUBLISHED[$index]:-1}"
    lock_dir="$FMIX_HOME/locks/$lock_name"
    # A failed stop retains the indexed owner and all metadata for recovery.
    # Retirement can yield: recheck the token/pid afterwards, never remove a
    # foreign replacement based on the pre-cleanup snapshot.
    fmix_lock_keeper_retire "$keeper_pid" || return 70
    FMIX_HELD_LOCK_NAMES[$index]=""
    FMIX_HELD_LOCK_KEEPER_PIDS[$index]=""
    FMIX_HELD_LOCK_TOKENS[$index]=""
    FMIX_HELD_LOCK_MODES[$index]=""
    FMIX_HELD_LOCK_PUBLISHED[$index]=""
    if [[ "$published" != "1" ]]; then
        # Joined shared read lease: the publishing holder owns the legacy
        # metadata record and retires it. Our kernel lease is already released.
        return 0
    fi
    recorded_token="$(sed -n 's/^token=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
    if [[ "$recorded_token" != "$token" ]] \
        || [[ "$(cat "$lock_dir/pid" 2>/dev/null || true)" != "$$" ]]; then
        fmix_error "Refusing to remove lock metadata for '$lock_name': ownership changed."
        return 1
    fi

    rm -f "$FMIX_HOME/lock-metadata/${lock_name}.json" 2>/dev/null || true

    destination="$FMIX_HOME/lock-metadata/released/${lock_name}.$(fmix_epoch).$$.${RANDOM}"
    if ! mkdir -p "$(dirname "$destination")" \
        || ! mv "$lock_dir" "$destination"; then
        fmix_error "Could not retire lock metadata for '$lock_name'."
        fmix_error "The kernel lock was released; stale metadata will be quarantined by the next owner."
        return 1
    fi
    return 0
}

fmix_lock_failure_is_fatal() {
    # Ordinary contention/cache misses remain retryable. An unresolved owned
    # keeper is fail-stop even when an older optional wrapper returned 1.
    (( ${1:-0} == 70 )) || [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]
}

fmix_session_lock_split_enabled() {
    # Kill switch for the shared/exclusive session-lock split. Default ON;
    # FMIX_SESSION_LOCK_SPLIT=0 forces every acquisition back to the legacy
    # exclusive-only behaviour (required for mixed-version FMIX_HOME safety).
    case "${FMIX_SESSION_LOCK_SPLIT:-1}" in
        0|false|FALSE|no|NO|off|OFF) return 1 ;;
        *) return 0 ;;
    esac
}

fmix_lock_owner_declares_shared() {
    local lock_dir="${1:-}" owner_mode=""
    [[ -d "$lock_dir" && -f "$lock_dir/owner" ]] || return 1
    owner_mode="$(sed -n 's/^mode=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
    [[ "$owner_mode" == "shared" ]]
}

fmix_lock_any_shared_held() {
    local i
    for (( i = 0; i < ${#FMIX_HELD_LOCK_NAMES[@]}; i++ )); do
        [[ -n "${FMIX_HELD_LOCK_NAMES[$i]:-}" ]] || continue
        [[ "${FMIX_HELD_LOCK_MODES[$i]:-}" == "shared" ]] && return 0
    done
    return 1
}

fmix_lock_escalate_exclusive() {
    # Clean mid-run escalation: release every shared (read) hold, re-acquire
    # the same lock names exclusively, then let the caller re-verify its warm
    # conditions before mutating. Never mutate under a shared hold.
    local reason="${1:-shared-state mutation}" index name acquire_rc
    for (( index = 0; index < ${#FMIX_HELD_LOCK_NAMES[@]}; index++ )); do
        [[ -n "${FMIX_HELD_LOCK_NAMES[$index]:-}" ]] || continue
        [[ "${FMIX_HELD_LOCK_MODES[$index]:-}" == "shared" ]] || continue
        name="${FMIX_HELD_LOCK_NAMES[$index]}"
        fmix_info "Escalating session lock '$name' to exclusive ($reason)."
        fmix_lock_release "$name" || return 70
        acquire_rc=0
        fmix_lock_acquire "$name" "$FMIX_WORKTREE_LOCK_TIMEOUT" \
            "escalated: $reason" 0 exclusive || acquire_rc=$?
        if (( acquire_rc != 0 )); then
            (( acquire_rc == 1 )) || return 70
            fmix_error "Could not escalate lock '$name' to exclusive for: $reason"
            return 70
        fi
    done
    return 0
}

fmix_lock_mutate_gate() {
    # Called immediately before any shared-state mutation. A shared hold must
    # escalate first and re-verify; return 200 tells the calling wrapper to
    # re-run its (cheap) warm decision under the new exclusive hold. An
    # exclusive (or absent) hold passes straight through.
    local reason="${1:-shared-state mutation}" escalate_rc=0
    fmix_lock_any_shared_held || return 0
    fmix_lock_escalate_exclusive "$reason" || escalate_rc=$?
    (( escalate_rc == 0 )) || return "$escalate_rc"
    FMIX_LOCK_GATE_RETRY=1
    return 200
}

fmix_lock_release_optional() {
    # Housekeeping may tolerate retired metadata warnings, never a pending
    # live owner. Do not clear handles or retry retirement here.
    local rc=0
    fmix_lock_release "$@" || rc=$?
    if fmix_lock_failure_is_fatal "$rc"; then return 70; fi
    return "$rc"
}

fmix_lock_display_name() {
    local lock_name="${1:-}"
    if [[ "$lock_name" =~ ^stable-seed-([0-9]+\.[0-9]+\.[0-9]+-stable)-[0-9a-f]{40}$ ]]; then
        printf 'stable-seed-%s\n' "${BASH_REMATCH[1]}"
    else
        printf '%s\n' "$lock_name"
    fi
}

fmix_host_test_lock_name() {
    # Only PostgreSQL database DDL is machine-global. Compilation, migration,
    # and ExUnit are worktree-scoped and must not queue behind unrelated tests.
    printf 'host-db-ddl'
}

fmix_host_test_lock_enabled() {
    case "${FMIX_HOST_TEST_LOCK:-1}" in
        0|false|FALSE|no|NO|off|OFF) return 1 ;;
        *) return 0 ;;
    esac
}

# ---------------------------------------------------------------------------
# Worktree resolution: find nearest cisco-cdr checkout from CWD
# ---------------------------------------------------------------------------

fmix_ensure_worktree_submodules() {
    local target_dir="$1"
    local selected_gitlink="${2:-}"

    # Find top-level repo if inside a Git tree
    local top_repo
    top_repo="$(git -C "$target_dir" rev-parse --show-toplevel 2>/dev/null)" || return 0

    # 1. If target_dir itself is missing mix.exs (e.g. cisco-cdr submodule directory is uninitialized in a worktree)
    if [[ ! -f "$target_dir/mix.exs" ]]; then
        if [[ -f "$top_repo/.gitmodules" ]]; then
            fmix_info "Detected uninitialized submodules in $top_repo. Initializing..." >&2
            if [[ -n "$selected_gitlink" ]]; then
                git -C "$top_repo" submodule update --init --recursive -- ":(top,literal)$selected_gitlink" >&2 || true
            else
                git -C "$top_repo" submodule update --init --recursive >&2 || true
            fi
        fi
    fi

    # 2. If target_dir has mix.exs (cisco-cdr), check if nested submodules (like proto) inside target_dir need initialization
    if [[ -f "$target_dir/mix.exs" && -f "$target_dir/.gitmodules" ]]; then
        local nested_sub
        while IFS= read -r nested_sub; do
            [[ -z "$nested_sub" ]] && continue
            if [[ -d "$target_dir/$nested_sub" && ! -f "$target_dir/$nested_sub/mix.exs" && ! -f "$target_dir/$nested_sub/package.json" && -z "$(ls -A "$target_dir/$nested_sub" 2>/dev/null)" ]]; then
                fmix_info "Detected uninitialized nested submodule '$nested_sub' in $target_dir. Initializing..." >&2
                git -C "$target_dir" submodule update --init --recursive >&2 || true
                break
            fi
        done < <(git -C "$target_dir" config --file .gitmodules --get-regexp '^submodule\..*\.path$' 2>/dev/null | awk '{print $2}')
    fi
}

fmix_worktree_has_cisco_cdr_app() {
    [[ -f "$1/mix.exs" ]] || return 1

    # A bounded static recognizer, not an Elixir interpreter. Require one
    # literal module, a direct use Mix.Project and its literal project list.
    # Python is isolated from site/PYTHONPATH and cannot create bytecode; no
    # project code, helper, toolchain, home or session preparation runs here.
    python3 -I -S -B - "$1/mix.exs" <<'PY' 2>/dev/null
import re
import sys


class Refuse(Exception):
    pass


def require(condition):
    if not condition:
        raise Refuse()


def literal_end(source, start):
    quote = source[start]
    delimiter = quote * (3 if source.startswith(quote * 3, start) else 1)
    i = start + len(delimiter)
    while i < len(source):
        if source[i] == "\\":
            i += 2
        elif source.startswith("#{", i):
            # Canonical project strings interpolate simple names/calls.
            # Nested/quoted interpolation is outside this static subset.
            end = source.find("}", i + 2)
            require(end != -1 and re.fullmatch(r"[A-Za-z0-9_.&!?()\[\] +*/=-]+", source[i + 2:end]))
            i = end + 1
        elif source.startswith(delimiter, i):
            return i + len(delimiter)
        else:
            i += 1
    raise Refuse()


def tokenize(source):
    tokens = []
    identifier = re.compile(r"[A-Za-z_][A-Za-z0-9_]*[!?]?")
    i = 0
    while i < len(source):
        start = i
        c = source[i]
        if c.isspace():
            i += 1
            continue
        if c == "#":
            end = source.find("\n", i)
            i = len(source) if end == -1 else end
            continue
        if c in "\"'":
            i = literal_end(source, i)
            value = "<literal>"
        elif c == "~":
            # Only canonical plain ASCII wordlists are supported. All other
            # sigils (including unused ~S decoys) refuse the whole candidate.
            require(source[i + 1:i + 2] in ("w", "W"))
            opener = source[i + 2:i + 3]
            closer = {"(": ")", "[": "]", "{": "}", "<": ">", "/": "/", "|": "|",
                      "\"": "\"", "'": "'"}.get(opener)
            require(closer is not None)
            end = source.find(closer, i + 3)
            require(end != -1 and re.fullmatch(r"[A-Za-z0-9_\s]*", source[i + 3:end]))
            i = end + 1
            modifier_start = i
            while i < len(source) and source[i] in "acs":
                i += 1
            require(source[modifier_start:i] in ("", "a", "c", "s"))
            require(i == len(source) or not (source[i].isalnum() or source[i] == "_"))
            value = "<literal>"
        else:
            word = identifier.match(source, i)
            require(c != "?")  # Character literals are outside this subset.
            value = word.group() if word else c
            i += len(value)
        tokens.append((value, start, i))
        require(len(tokens) <= 65_536)
    return tokens


def recognizes(source):
    tokens = tokenize(source)
    words = [token[0] for token in tokens]
    require(len(words) >= 7 and words[0] == "defmodule")

    # Elixir atoms and keyword keys glue the colon to the word: `:end` and
    # `end:`. `: end` and `end :` are syntax errors. Requiring that adjacency
    # keeps a real block `end` followed on the next line by an atom-led
    # expression (for example `end` then `:code.add_patha(...)`) from being
    # mistaken for an `end:` keyword key. Adjacency matches Elixir's lexical
    # grammar without widening the literal project-identity checks.
    def atom(i):
        return (i > 0 and words[i - 1] == ":"
                and tokens[i - 1][2] == tokens[i][1])

    def keyword_key(i):
        return (i + 1 < len(words) and words[i + 1] == ":"
                and tokens[i][2] == tokens[i + 1][1])

    def codeword(i, word):
        return (words[i] == word and (i == 0 or words[i - 1] != ".")
                and not atom(i) and not keyword_key(i))

    # Never let a helper module or quoted/metaprogrammed definition become
    # authority. Even otherwise-valid multi-module mix.exs files fail closed.
    require(sum(codeword(i, "defmodule") for i in range(len(words))) == 1)
    require(not any(codeword(i, word) for i in range(len(words))
                    for word in ("quote", "unquote", "unquote_splicing")))
    # Do not infer ownership through aliases or imported macros. This also
    # excludes qualified Kernel.alias/import; literal atoms/keyword keys do
    # not change lexical resolution and remain opaque field values.
    require(not any(word in ("alias", "import") and not atom(i) and not keyword_key(i)
                    for i, word in enumerate(words)))
    projects = [i for i, word in enumerate(words[:-1])
                if word in ("def", "defp") and codeword(i, word) and words[i + 1] == "project"]
    require(len(projects) == 1)

    i = 1
    module = []
    while i < len(words) and words[i] != "do":
        module.append(words[i])
        i += 1
    require(module and len(module) % 2 == 1
            and all(value == "." if index % 2 else re.fullmatch(r"[A-Z][A-Za-z0-9_]*", value)
                    for index, value in enumerate(module)))
    require(i < len(words) and codeword(i, "do"))
    module_do = i
    i += 1
    blocks = ["module"]
    delimiters = []
    closing = {"]": "[", ")": "(", "}": "{"}
    uses = 0
    project_ok = False
    functions_seen = False

    def statement_start(index):
        return (index - 1 == module_do or words[index - 1] == ";"
                or "\n" in source[tokens[index - 1][2]:tokens[index][1]])

    def project_list(index):
        if words[index:index + 2] == ["(", ")"]:
            index += 2
        inline = words[index:index + 3] == [",", "do", ":"]
        require(inline or words[index:index + 1] == ["do"])
        index += 3 if inline else 1
        require(words[index:index + 1] == ["["])
        depth = ["["]
        entries = []
        entry = []
        index += 1
        while index < len(words) and depth:
            word = words[index]
            if word in ("[", "(", "{"):
                depth.append(word)
            elif word in closing:
                require(depth[-1] == closing[word])
                depth.pop()
                if not depth:
                    break
            # Control blocks or spliced lists are not literal keyword fields.
            require(not any(codeword(index, key) for key in ("do", "fn", "end")))
            if word == "," and len(depth) == 1:
                entries.append(entry)
                entry = []
            else:
                entry.append(word)
            index += 1
        require(not depth)
        if entry:
            entries.append(entry)
        require(entries and all(len(field) >= 3 and field[1] == ":"
                                and re.fullmatch(r"[a-z_][A-Za-z0-9_]*[!?]?", field[0])
                                for field in entries))
        require([field[2:] for field in entries if field[0] == "app"] == [[":", "cdrcisco"]])
        index += 1
        require(index < len(words))
        if inline:
            require(words[index] in (";", "end")
                    or (statement_start(index) and words[index] in ("def", "defp", "@")))
        else:
            require(codeword(index, "end"))
            index += 1
        return index

    while i < len(words):
        word = words[i]
        if codeword(i, "use"):
            require(blocks == ["module"] and not delimiters and not functions_seen
                    and statement_start(i) and words[i + 1:i + 4] == ["Mix", ".", "Project"])
            uses += 1
            require(uses == 1)
            i += 4
            require(i < len(words) and (words[i] in (";", "end") or statement_start(i))
                    and words[i] not in (",", "."))
            continue
        if word in ("def", "defp") and codeword(i, word):
            functions_seen = True
            if i == projects[0]:
                require(word == "def" and blocks == ["module"] and not delimiters
                        and uses == 1 and statement_start(i))
                i = project_list(i + 2)
                project_ok = True
                continue
        if word in ("[", "(", "{"):
            delimiters.append(word)
        elif word in closing:
            require(delimiters and delimiters.pop() == closing[word])
        elif codeword(i, "do") or codeword(i, "fn"):
            blocks.append("block")
        elif codeword(i, "end"):
            require(blocks)
            blocks.pop()
            if not blocks:
                require(not delimiters and all(value == ";" for value in words[i + 1:]))
                return uses == 1 and project_ok
        i += 1
    return False


try:
    with open(sys.argv[1], "rb") as handle:
        raw = handle.read(1_048_577)
    require(len(raw) <= 1_048_576)
    source = raw.decode("utf-8")
    sys.exit(0 if recognizes(source) else 1)
except (OSError, UnicodeError, Refuse, IndexError):
    sys.exit(1)
PY
}

fmix_worktree_is_cold_submodule() {
    # A missing mix.exs is not a checkout identity. Admit the one cold
    # exception only when Git registers this exact directory as an
    # uninitialized Gitlink and .gitmodules names the cisco-cdr source.
    [[ -d "$1" && ! -e "$1/mix.exs" ]] || return 1
    local target top relative entry key registered_path url status
    target="$(fmix_realpath "$1")" || return 1
    top="$(git -C "$target" rev-parse --show-toplevel 2>/dev/null)" || return 1
    top="$(fmix_realpath "$top")" || return 1
    [[ "$target" == "$top/"* && -f "$top/.gitmodules" ]] || return 1
    relative="${target#"$top/"}"
    entry="$(git -C "$top" ls-files --stage -- "$relative" 2>/dev/null)" || return 1
    [[ "$entry" != *$'\n'* && "$entry" =~ ^160000\ [0-9a-f]{40}\ 0$'\t' ]] || return 1
    [[ "${entry#*$'\t'}" == "$relative" ]] || return 1

    while IFS= read -r key; do
        registered_path="$(git -C "$top" config --file .gitmodules --get "$key" 2>/dev/null)" || continue
        [[ "$registered_path" == "$relative" ]] || continue
        url="$(git -C "$top" config --file .gitmodules --get "${key%.path}.url" 2>/dev/null)" || return 1
        case "$url" in
            https://github.com/calltelemetry/cisco-cdr|https://github.com/calltelemetry/cisco-cdr.git|git@github.com:calltelemetry/cisco-cdr|git@github.com:calltelemetry/cisco-cdr.git|ssh://git@github.com/calltelemetry/cisco-cdr|ssh://git@github.com/calltelemetry/cisco-cdr.git) ;;
            *) return 1 ;;
        esac
        status="$(git -C "$top" submodule status -- "$relative" 2>/dev/null)" || return 1
        [[ "$status" == -[0-9a-f]* ]] || return 1
        printf '%s\n' "$relative"
        return 0
    done < <(git -C "$top" config --file .gitmodules --name-only --get-regexp '^submodule\..*\.path$' 2>/dev/null)
    return 1
}

fmix_find_worktree() {
    local path="$1"
    # Admission needs a verified candidate without initializing submodules.
    # The default resolution still initializes and verifies the checkout.
    local resolution_mode="${2:-initialize}"
    local search_from
    local cold_relative

    if [[ "$path" == "auto" ]]; then
        search_from="$(pwd)"
        # Walk up looking for mix.exs with app: :cdrcisco
        local dir="$search_from"
        while true; do
            cold_relative=""
            if fmix_worktree_has_cisco_cdr_app "$dir"; then
                :
            elif cold_relative="$(fmix_worktree_is_cold_submodule "$dir")"; then
                :
            else
                cold_relative=""
            fi
            if fmix_worktree_has_cisco_cdr_app "$dir" || [[ -n "$cold_relative" ]]; then
                if [[ "$resolution_mode" != "readonly" ]]; then
                    if [[ -n "$cold_relative" ]]; then
                        fmix_ensure_worktree_submodules "$dir" "$cold_relative"
                    else
                        fmix_ensure_worktree_submodules "$dir"
                    fi
                    fmix_worktree_has_cisco_cdr_app "$dir" || return 1
                fi
                printf '%s\n' "$dir"
                return 0
            fi
            local parent
            parent="$(dirname "$dir")"
            if [[ "$parent" == "$dir" ]]; then
                break
            fi
            dir="$parent"
        done

        # If not found walking up, check if CWD has a cisco-cdr subdirectory
        if [[ -d "$search_from/cisco-cdr" ]]; then
            if [[ "$resolution_mode" == "readonly" ]]; then
                cold_relative=""
                if ! fmix_worktree_has_cisco_cdr_app "$search_from/cisco-cdr"; then
                    cold_relative="$(fmix_worktree_is_cold_submodule "$search_from/cisco-cdr")" || cold_relative=""
                fi
                if fmix_worktree_has_cisco_cdr_app "$search_from/cisco-cdr" || [[ -n "$cold_relative" ]]; then
                    printf '%s\n' "$search_from/cisco-cdr"
                    return 0
                fi
            else
                cold_relative=""
                if ! fmix_worktree_has_cisco_cdr_app "$search_from/cisco-cdr"; then
                    cold_relative="$(fmix_worktree_is_cold_submodule "$search_from/cisco-cdr")" || cold_relative=""
                fi
                if [[ -n "$cold_relative" ]]; then
                    fmix_ensure_worktree_submodules "$search_from/cisco-cdr" "$cold_relative"
                elif fmix_worktree_has_cisco_cdr_app "$search_from/cisco-cdr"; then
                    fmix_ensure_worktree_submodules "$search_from/cisco-cdr"
                fi
                if fmix_worktree_has_cisco_cdr_app "$search_from/cisco-cdr"; then
                    printf '%s\n' "$search_from/cisco-cdr"
                    return 0
                fi
            fi
        fi

        fmix_error "Could not find a cisco-cdr checkout (mix.exs with app: :cdrcisco) from $search_from."
        fmix_error "Run from inside a cisco-cdr directory, or pass --worktree <path>."
        return 1
    else
        if [[ ! -d "$path" ]]; then
            fmix_error "Worktree path '$path' does not exist."
            return 1
        fi

        # REL-3972: an explicit --worktree always resolves to its canonical
        # realpath, the same identity that keys sessions and receipts.
        local resolved_dir
        resolved_dir="$(fmix_realpath "$path")" || return 1
        if [[ ! -f "$resolved_dir/mix.exs" && -d "$resolved_dir/cisco-cdr" ]]; then
            resolved_dir="$resolved_dir/cisco-cdr"
        fi

        cold_relative=""
        if ! fmix_worktree_has_cisco_cdr_app "$resolved_dir"; then
            cold_relative="$(fmix_worktree_is_cold_submodule "$resolved_dir")" || cold_relative=""
        fi

        if [[ "$resolution_mode" == "readonly" ]]; then
            if ! fmix_worktree_has_cisco_cdr_app "$resolved_dir" && [[ -z "$cold_relative" ]]; then
                fmix_error "'$path' is not a cisco-cdr checkout (mix.exs missing or app: :cdrcisco not found; no recognized uninitialized cisco-cdr Gitlink)."
                return 1
            fi
            printf '%s\n' "$resolved_dir"
            return 0
        fi
        if [[ -n "$cold_relative" ]]; then
            fmix_ensure_worktree_submodules "$resolved_dir" "$cold_relative"
        elif fmix_worktree_has_cisco_cdr_app "$resolved_dir"; then
            fmix_ensure_worktree_submodules "$resolved_dir"
        else
            fmix_error "'$path' is not a cisco-cdr checkout (not inside a cisco-cdr checkout, mix.exs missing or app: :cdrcisco not found)."
            fmix_error "fmix v1 only supports cisco-cdr worktrees."
            return 1
        fi

        if ! fmix_worktree_has_cisco_cdr_app "$resolved_dir"; then
            fmix_error "'$path' is not a cisco-cdr checkout (not inside a cisco-cdr checkout, mix.exs missing or app: :cdrcisco not found)."
            fmix_error "fmix v1 only supports cisco-cdr worktrees."
            return 1
        fi
        printf '%s\n' "$resolved_dir"
        return 0
    fi
}

fmix_find_worktree_root() {
    fmix_find_worktree "$@"
}

# REL-3972: an explicit --worktree must resolve to its own realpath, or to the
# documented <path>/cisco-cdr child. Any other result is a different worktree,
# and the verb refuses before it activates a session, compiles, or writes.
fmix_check_resolved_worktree() {
    local raw="$1" resolved="$2" expected resolved_real
    [[ "$raw" == "auto" ]] && return 0
    expected="$(fmix_realpath "$raw")" || return 1
    resolved_real="$(fmix_realpath "$resolved")" || return 1
    if [[ "$resolved_real" == "$expected" || "$resolved_real" == "$expected/cisco-cdr" ]]; then
        return 0
    fi
    fmix_error "worktree_session_mismatch: --worktree '$raw' resolved to '$resolved_real' (requested realpath '$expected')."
    fmix_error "Refusing to run in a different worktree. Pass the exact cisco-cdr worktree path."
    return 1
}

# ---------------------------------------------------------------------------
# Preflight checks
# ---------------------------------------------------------------------------

fmix_preflight() {
    local worktree="$1"
    local fail=0
    local purge_marker="$FMIX_HOME/logs/.last-session-purge"
    local now purge_age=999999

    # Throttle expired-session purge to once per 5 minutes — was paid every run.
    now="$(fmix_epoch)"
    if [[ -f "$purge_marker" ]]; then
        purge_age=$(( now - $(fmix_stat_mtime "$purge_marker" 2>/dev/null || echo 0) ))
    fi
    if (( purge_age >= 300 )); then
        if fmix_purge_expired_sessions 1; then
            :
        else
            local housekeeping_rc=$?
            fmix_lock_failure_is_fatal "$housekeeping_rc" && return 70
            fmix_warn "Session housekeeping is degraded; preflight will continue without destructive cleanup."
        fi
        mkdir -p "$(dirname "$purge_marker")" 2>/dev/null || true
        printf '%s\n' "$now" >"$purge_marker" 2>/dev/null || true
    fi

    if fmix_worktree_uses_oban_repo "$worktree"; then
        fmix_template_credential_preflight "$worktree" || fail=1
    fi

    # This is a hard gate, not a warning. It runs before any artifact adoption
    # or Mix invocation and validates both the declared and active ABI.
    # Skip re-activation when cmd_test already verified the toolchain.
    if [[ -z "${FMIX_TOOLCHAIN_IDENTITY:-}" ]]; then
        fmix_activate_toolchain "$worktree" || fail=1
    fi

    # Show exactly what fmix will use, and warn about the #1 footgun: an ambient
    # DB_HOSTNAME/DB_HOST_IPV4 pointing at a docker-only name. fmix pins these to
    # localhost for native runs, but it's worth telling the user their shell env
    # is misleading (a bare `mix test` outside fmix WOULD hit :nxdomain).
    echo "  Resolved infra (native): postgres $DB_HOST:$DB_PORT, NATS $NATS_HOST:$NATS_PORT"
    local amb
    for amb in DB_HOSTNAME DB_HOST_IPV4 LOCAL_NATS; do
        local v="${!amb:-}"
        case "$v" in
            ""|localhost|127.0.0.1) : ;;
            *docker.internal*|*containers.internal*)
                echo "  [WARN] ambient $amb=$v is a docker-only name (won't resolve natively). fmix ignores it; unset it before a bare 'mix test'." ;;
        esac
    done

    # Shared postgres + NATS. fmix owns this plane (one host-wide ct-infra
    # project) rather than delegating to a monorepo-only helper script: a
    # standalone npm consumer has no monorepo root to run it from.
    if ! fmix_ensure_infra; then
        fail=1
    fi

    # NATS JetStream check (warn only — tests stub NATS)
    if ! fmix_nats_jetstream_probe "$NATS_HOST" "$NATS_PORT"; then
        fmix_warn "NATS JetStream not answering at $NATS_HOST:$NATS_PORT: $FMIX_NATS_PROBE_DETAIL."
        fmix_warn "Run: fmix ensure — some tests may fail without NATS."
    fi

    # psql availability check
    if ! fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1; then
        fmix_error "Cannot connect to postgres as user '$DB_USER'. Check DB credentials or run 'fmix ensure'."
        fail=1
    fi

    return $fail
}

fmix_reject_raw_cover() {
    local arg="${1:-}"
    if [[ "$arg" == "--cover"* ]]; then
        fmix_error "Raw mix --cover is disabled: it instruments the entire application and defeats FMix isolation."
        fmix_error "Use: fmix coverage --worktree <path> --base <git-ref> -- <test paths>"
        return 2
    fi
    return 0
}

fmix_check_mix_lock() {
    local wt="$1"
    if [[ ! -f "$wt/mix.lock" || ! -r "$wt/mix.lock" ]]; then
        fmix_error "mix.lock missing or unreadable in worktree: $wt"
        return 1
    fi
    return 0
}

# ---------------------------------------------------------------------------
# Connection pool check (budget-aware, QA-349)
# ---------------------------------------------------------------------------

# Real per-run Postgres connection cost. config/test.exs sandboxes 13 repos
# total: the primary Repo (DB_TEST_POOL_SIZE, default 30) plus 12 more
# purpose-specific repos with their own pools (CallControlAPIRepo,
# BackgroundRepo, AnalyticalRollupRepo, CdrIngestRepo, PostCallRepo,
# CubeTelemetryRepo, MaintenanceDdlRepo, XccRollupRepo, ObanRepo,
# DiscoveryRepo, ReportingRepo, AuthRepo). Their defaults sum to 39, so one
# fmix run opens ~69 connections, not the 30 an agent would assume from
# DB_TEST_POOL_SIZE alone. That makes true saturation ~8 concurrent runs at
# max_connections=600 (8*69=552), not the ~20 the old hardcoded-500 warning
# implied. Summed here from the live env (falling back to the config/test.exs
# defaults) so an override of any one pool size is reflected automatically.
fmix_per_run_pg_connection_budget() {
    local total=0
    local -a vars=(
        "DB_TEST_POOL_SIZE:30"
        "DB_TEST_CALL_CONTROL_POOL_SIZE:5"
        "DB_TEST_BACKGROUND_POOL_SIZE:5"
        "DB_TEST_ANALYTICAL_ROLLUP_POOL_SIZE:4"
        "DB_TEST_CDR_INGEST_POOL_SIZE:1"
        "DB_TEST_POST_CALL_POOL_SIZE:2"
        "DB_TEST_CUBE_TELEMETRY_POOL_SIZE:3"
        "DB_TEST_MAINTENANCE_DDL_POOL_SIZE:3"
        "DB_TEST_XCC_ROLLUP_POOL_SIZE:2"
        "DB_TEST_OBAN_POOL_SIZE:5"
        "DB_TEST_DISCOVERY_POOL_SIZE:5"
        "DB_TEST_REPORTING_POOL_SIZE:2"
        "DB_TEST_AUTH_POOL_SIZE:2"
    )
    local entry name default value
    for entry in "${vars[@]}"; do
        name="${entry%%:*}"
        default="${entry##*:}"
        value="$(fmix_uint_or_default "${!name:-$default}" "$default" "$name")"
        total=$(( total + value ))
    done
    printf '%s\n' "$total"
}

# Budget-aware: instead of comparing current usage alone to a hardcoded
# 500/600, add THIS run's own pending connection cost to current usage before
# comparing against max_connections. An agent sitting at 480 current
# connections used to pass a "count > 500" check and then open ~69 more,
# blowing past 600 — the check was decorative because it ignored the run's
# own budget. Warns when current+budget would exceed 85% of max_connections,
# errors (still non-fatal — a warning surfaced loudly) when it would exceed
# max_connections outright.
fmix_check_pg_connections() {
    local max_conn=600
    local count
    count="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -t -c "SELECT count(*) FROM pg_stat_activity" 2>/dev/null | tr -d ' ')" || return 0
    [[ "$count" =~ ^[0-9]+$ ]] || return 0

    local budget
    budget="$(fmix_per_run_pg_connection_budget)"
    local projected=$(( count + budget ))
    local warn_threshold=$(( max_conn * 85 / 100 ))

    if (( projected > max_conn )); then
        fmix_warn "Postgres is at $count connections; this run needs ~$budget more (projected $projected > max_connections=$max_conn). This run is likely to hit connection-limit errors or force other concurrent agents to fail. Wait for other agents to finish, or raise max_connections."
    elif (( projected > warn_threshold )); then
        fmix_warn "Postgres is at $count connections; this run needs ~$budget more (projected $projected, limit $max_conn). Getting close — avoid starting more concurrent runs."
    fi
}

fmix_check_known_nif_caches() {
    # Some local worktrees carry deps/_build artifacts compiled by a different
    # Erlang/OTP runtime. Those can emit noisy on_load failures during tests
    # while unrelated tests still pass. Detect the known cmark case up front,
    # recompile it once, and explain that this is local cache state.
    local worktree="$1"
    local build_root deps_root cmark_path pa_path
    build_root="$(fmix_compile_build_root "$worktree")"
    deps_root="$(fmix_session_deps_root "$worktree")"
    cmark_path="$build_root/test/lib/cmark"
    pa_path="$build_root/test/lib/*/ebin"

    [[ -d "$deps_root/cmark" ]] || return 0
    [[ -d "$cmark_path" ]] || return 0

    local out rc
    out="$(
        cd "$worktree" || exit 1
        MIX_ENV=test \
            MEESEEKS_HTML5EVER_BUILD=0 \
            elixir -pa "$pa_path" -e 'Code.ensure_loaded(Cmark.Nif)' 2>&1
    )"
    rc=$?

    if false; then
        fmix_warn "Detected stale compiled NIF cache for cmark in this worktree."
        fmix_warn "This is local deps/_build state, not a repo, ct-meta, or upstream skill change."
        fmix_warn "Repairing with: mix deps.compile cmark --force"

        local -a build_env=()
        [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
        [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")

        if (
            cd "$worktree" || exit 1
            exec env \
                "${build_env[@]+"${build_env[@]}"}" \
                MIX_ENV=test \
                MEESEEKS_HTML5EVER_BUILD=0 \
                mix deps.compile cmark --force >/tmp/fmix-cmark-recompile-$$.log 2>&1
        ); then
            rm -f /tmp/fmix-cmark-recompile-$$.log
            fmix_info "Recompiled cmark NIF cache for the active Erlang runtime."
        else
            fmix_warn "Could not auto-recompile cmark. See /tmp/fmix-cmark-recompile-$$.log"
            fmix_warn "Manual repair: cd $worktree && MIX_ENV=test mix deps.compile cmark --force"
        fi
    fi
}

# ---------------------------------------------------------------------------
# Template build and artifact management
# ---------------------------------------------------------------------------

fmix_template_v2_dir() {
    [[ "${1:-}" =~ ^[0-9a-f]{16}$ ]] || return 1
    printf '%s/artifacts/v2/templates/%s\n' "$FMIX_HOME" "$1"
}
fmix_template_legacy_dir() {
    [[ "${1:-}" =~ ^[0-9a-f]{16}$ ]] || return 1
    printf '%s/templates/%s\n' "$FMIX_HOME" "$1"
}
fmix_template_dir() {
    local key="${1:-}" v2
    [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
    v2="$(fmix_template_v2_dir "$key")" || return 1
    if [[ -e "$v2" || -L "$v2" ]]; then printf '%s\n' "$v2"
    else fmix_template_legacy_dir "$key"; fi
}

fmix_template_write_manifest() {
    local root="$1" manifest digest py_bin
    manifest="$root/manifest.tsv"
    py_bin="$(fmix_python_bin)"
    if ! "$py_bin" - "$root" >"$manifest" <<'PY'
import hashlib
import os
import sys

root = os.path.realpath(sys.argv[1])

def safe_text(value: str) -> str:
    if "\n" in value or "\r" in value or "\t" in value:
        raise ValueError("template paths and links may not contain control separators")
    return value

for top in ("deps", "_build"):
    start = os.path.join(root, top)
    if not os.path.isdir(start) or os.path.islink(start):
        raise SystemExit(f"missing safe template root: {top}")
    for current, dirs, files in os.walk(start, topdown=True, followlinks=False):
        dirs.sort()
        files.sort()
        for name in list(dirs) + files:
            path = os.path.join(current, name)
            rel = safe_text(os.path.relpath(path, root))
            info = os.lstat(path)
            if os.path.islink(path):
                target = safe_text(os.readlink(path))
                if os.path.isabs(target):
                    raise SystemExit(f"absolute template symlink: {rel} -> {target}")
                resolved = os.path.normpath(os.path.join(os.path.dirname(path), target))
                if os.path.commonpath((root, resolved)) != root:
                    raise SystemExit(f"escaping template symlink: {rel} -> {target}")
                print(f"L\t{rel}\t{target}")
            elif os.path.isdir(path):
                print(f"D\t{rel}\t-")
            elif os.path.isfile(path):
                digest = hashlib.sha256()
                with open(path, "rb") as handle:
                    for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                        digest.update(chunk)
                print(f"F\t{rel}\t{info.st_size}\t{digest.hexdigest()}")
            else:
                raise SystemExit(f"unsupported template entry: {rel}")
PY
    then
        rm -f "$manifest"
        return 1
    fi
    digest="$(fmix_hash_stdin <"$manifest")" || return 1
    printf '%s\n' "$digest" >"$root/manifest.sha256"
    printf '%s\n' "$digest"
}

fmix_template_materialize_app_priv() {
    # Mix creates the application priv link back to the source worktree. A
    # shared template must never retain that host/worktree-bound link, so copy
    # its exact target into staging before the general link validator runs.
    local root="$1" worktree="$2" build_root="$3"
    local source_link staged_link expected_priv resolved
    source_link="$build_root/test/lib/cdrcisco/priv"
    staged_link="$root/_build/test/lib/cdrcisco/priv"
    [[ -L "$staged_link" ]] || return 0
    [[ -L "$source_link" ]] || return 1
    [[ "$(readlink "$source_link" 2>/dev/null)" != /* ]] || return 1
    expected_priv="$(fmix_realpath "$worktree/priv")" || return 1
    resolved="$(fmix_realpath "$source_link")" || return 1
    [[ "$resolved" == "$expected_priv" && -d "$resolved" ]] || return 1
    rm -f "$staged_link" || return 1
    fmix_cow_clone "$resolved" "$staged_link"
}

fmix_session_relink_app_priv() {
    # Templates and the app compile CAS carry a materialized copy of the
    # application priv (fmix_template_materialize_app_priv). Installed as-is,
    # that copy is the publisher's priv, not this checkout's, and it lives on
    # FMIX_HOME (NFS on runners: ~125x slower to walk than the worktree).
    # Restore Mix's own relative link, which resolves through the session priv
    # bridge to the active checkout.
    local build_root="$1" app_priv
    app_priv="$build_root/test/lib/cdrcisco/priv"
    [[ -L "$app_priv" || ! -d "$app_priv" ]] && return 0
    fmix_guard_path "$app_priv" || return 1
    rm -rf "$app_priv" || return 1
    ln -s ../../../../priv "$app_priv"
}

fmix_template_make_readonly() {
    local root="$1" writable
    [[ "$root" == "$FMIX_HOME/templates/"*.tmp-* \
        || "$root" == "$FMIX_HOME/artifacts/v2/templates/"*.tmp-* ]] || return 1
    chmod -R a-w "$root" || return 1
    # Darwin refuses to rename a directory whose own owner-write bit is clear.
    # Leave only the staging root writable for the atomic rename. Consumers
    # reject the destination until the publisher clears that final bit.
    chmod u+w "$root" || return 1
    writable="$(find "$root" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
        || return 1
    [[ -z "$writable" ]]
}

fmix_template_quarantine() {
    # Reader-observable CAS mutation: move the exact tree into the
    # pre-computed unique quarantine destination with ONE atomic mv — a
    # single rename into the final name, no intermediate name, no copy — so
    # a concurrent lock-free reader sees complete-old or ENOENT -> ordinary
    # miss, never a torn read. Same-filesystem rename is enforced before any
    # mutation: a cross-device source fails closed instead of letting mv
    # fall back to a recursive copy. Darwin refuses a cross-parent rename of
    # a directory whose own owner-write bit is clear (see
    # fmix_template_make_readonly), so the move root alone is re-enabled for
    # owner-write immediately before the rename; the sealed contents are
    # never touched and staging roots are already owner-writable.
    local path="$1" reason="$2" quarantine_root destination source_device quarantine_device
    [[ "$path" == "$FMIX_HOME/artifacts/v2/templates/"* ]] || return 1
    [[ -e "$path" || -L "$path" ]] || return 0
    quarantine_root="$FMIX_HOME/quarantine/artifacts-v2/templates"
    destination="$quarantine_root/$(basename "$path").$(fmix_epoch).$$.${RANDOM}"
    fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/templates" || return 1
    [[ ! -e "$destination" && ! -L "$destination" ]] || return 1
    source_device="$(fmix_stat_device "$path")" || return 1
    quarantine_device="$(fmix_stat_device "$quarantine_root")" || return 1
    [[ "$source_device" == "$quarantine_device" ]] || return 1
    if [[ "$FMIX_OS" == "Darwin" && -d "$path" && ! -L "$path" ]]; then
        chmod u+w "$path" || return 1
    fi
    if mv "$path" "$destination"; then
        fmix_warn "Quarantined template state ($reason): $destination"
        return 0
    fi
    return 1
}

fmix_template_is_complete_unleased() {
    local key="$1" tdir recorded_key recorded_schema manifest_sha recorded_sha expected_schema="1"
    local producer_runner_sha consumer_protocol
    local writable unexpected
    tdir="$(fmix_template_dir "$key")"
    [[ -d "$tdir" && ! -L "$tdir" ]] || return 1
    [[ -f "$tdir/meta.json" && ! -L "$tdir/meta.json" ]] || return 1
    [[ -f "$tdir/manifest.tsv" && ! -L "$tdir/manifest.tsv" ]] || return 1
    [[ -f "$tdir/manifest.sha256" && ! -L "$tdir/manifest.sha256" ]] || return 1
    [[ -d "$tdir/deps" && ! -L "$tdir/deps" ]] || return 1
    [[ -d "$tdir/_build" && ! -L "$tdir/_build" ]] || return 1
    unexpected="$(find "$tdir" -mindepth 1 -maxdepth 1 \
        ! -name deps ! -name _build ! -name meta.json \
        ! -name manifest.tsv ! -name manifest.sha256 -print -quit 2>/dev/null)" \
        || return 1
    [[ -z "$unexpected" ]] || return 1
    grep -q '"status": "complete"' "$tdir/meta.json" 2>/dev/null || return 1
    recorded_schema="$(fmix_read_template_meta "$key" schema)"
    recorded_key="$(fmix_read_template_meta "$key" template_key)"
    recorded_sha="$(fmix_read_template_meta "$key" manifest_sha256)"
    IFS= read -r manifest_sha <"$tdir/manifest.sha256"
    if [[ "$tdir" == "$FMIX_HOME/artifacts/v2/templates/"* ]]; then
        expected_schema="2"
        producer_runner_sha="$(fmix_read_template_meta "$key" producer_runner_sha256)"
        consumer_protocol="$(fmix_read_template_meta "$key" consumer_protocol)"
        [[ "$consumer_protocol" == "fmix-native-artifacts.v2" ]] || return 1
        fmix_artifact_v2_managed_entrypoint || return 1
        fmix_artifact_v2_producer_runner_is_known "$producer_runner_sha" || return 1
    fi
    [[ "$recorded_schema" == "$expected_schema" ]] || return 1
    [[ "$recorded_key" == "$key" ]] || return 1
    [[ "$recorded_sha" =~ ^[0-9a-f]{64}$ && "$recorded_sha" == "$manifest_sha" ]] \
        || return 1
    writable="$(find "$tdir" -maxdepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
        || return 1
    [[ -z "$writable" ]]
}

fmix_template_cas_read_identity() {
    # meta.json + manifest.sha256 identity snapshot for lock-free v2 reads
    # (see the retirement engine's identity() audit fields). A mid-read
    # quarantine rename or replacement publication changes it; missing
    # metadata fails closed as an ordinary miss.
    local key="${1:-}" tdir
    [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
    tdir="$(fmix_template_dir "$key")" || return 1
    fmix_stat_identity "$tdir/meta.json" || return 1
    fmix_stat_identity "$tdir/manifest.sha256" || return 1
}

fmix_template_is_complete() {
    local key="${1:-}" tdir attempt before after outcome
    [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
    tdir="$(fmix_template_dir "$key")" || return 1
    if [[ "$tdir" != "$FMIX_HOME/artifacts/v2/templates/"* ]]; then
        fmix_template_is_complete_unleased "$key"
        return $?
    fi
    fmix_artifact_v2_managed_entrypoint || return 1
    # Lock-free CAS read. The published tree is immutable and this check
    # never promotes or writes CAS contents, so the exclusive build-<key>
    # lease is not taken: warm reads must not queue behind a producer's
    # minutes-long build lease. After validation, re-stat the meta.json /
    # manifest.sha256 identities to detect a mid-read quarantine rename or
    # replacement publication and retry once on identity change. An
    # identity that still moves on the retry fails closed as a miss.
    for attempt in 1 2; do
        before="$(fmix_template_cas_read_identity "$key")" || return 1
        outcome=1
        fmix_template_is_complete_unleased "$key" && outcome=0
        after="$(fmix_template_cas_read_identity "$key")" || after="missing"
        if [[ "$before" == "$after" ]]; then
            return "$outcome"
        fi
    done
    return 1
}

fmix_template_verify_full_unleased() {
    local key="$1" tdir expected actual_tmp actual writable py_bin
    fmix_template_is_complete "$key" || return 1
    tdir="$(fmix_template_dir "$key")"
    IFS= read -r expected <"$tdir/manifest.sha256"
    actual_tmp="$(mktemp "${TMPDIR:-/tmp}/fmix-template-verify.${key}.XXXXXX")" \
        || return 1
    py_bin="$(fmix_python_bin)"
    if ! "$py_bin" - "$tdir" >"$actual_tmp" <<'PY'
import hashlib
import os
import sys

root = os.path.realpath(sys.argv[1])
for top in ("deps", "_build"):
    start = os.path.join(root, top)
    for current, dirs, files in os.walk(start, topdown=True, followlinks=False):
        dirs.sort()
        files.sort()
        for name in list(dirs) + files:
            path = os.path.join(current, name)
            rel = os.path.relpath(path, root)
            info = os.lstat(path)
            if os.path.islink(path):
                print(f"L\t{rel}\t{os.readlink(path)}")
            elif os.path.isdir(path):
                print(f"D\t{rel}\t-")
            elif os.path.isfile(path):
                digest = hashlib.sha256()
                with open(path, "rb") as handle:
                    for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                        digest.update(chunk)
                print(f"F\t{rel}\t{info.st_size}\t{digest.hexdigest()}")
            else:
                raise SystemExit(1)
PY
    then
        rm -f "$actual_tmp"
        return 1
    fi
    actual="$(fmix_hash_stdin <"$actual_tmp")"
    rm -f "$actual_tmp"
    [[ "$actual" == "$expected" ]] || return 1
    writable="$(find "$tdir" ! -type l -perm -u+w -print -quit 2>/dev/null)" || return 1
    [[ -z "$writable" ]]
}

fmix_template_verify_full() {
    local key="${1:-}" tdir
    tdir="$(fmix_template_dir "$key")" || return 1
    if [[ "$tdir" != "$FMIX_HOME/artifacts/v2/templates/"* ]]; then
        fmix_template_verify_full_unleased "$key"
        return $?
    fi
    fmix_artifact_v2_managed_entrypoint || return 1
    fmix_with_reused_artifact_lease "build-$key" fmix_template_verify_full_unleased "$key"
}

fmix_collect_process_tree() {
    # Snapshot a process tree (root first). Collect BEFORE signalling: a TERM
    # pass that exits an intermediate process reparents its children, making
    # them undiscoverable via pgrep -P on a later walk.
    local pid="$1" child
    printf '%s\n' "$pid"
    if command -v pgrep >/dev/null 2>&1; then
        while IFS= read -r child; do
            [[ "$child" =~ ^[0-9]+$ ]] || continue
            fmix_collect_process_tree "$child"
        done < <(pgrep -P "$pid" 2>/dev/null || true)
    fi
}

fmix_signal_retained_set() {
    # Signal an already-collected PID set. Dead PIDs are ignored; the retained
    # set guarantees TERM-surviving descendants still receive the KILL pass
    # even after reparenting.
    local signal="$1" set="$2" p
    while IFS= read -r p; do
        [[ "$p" =~ ^[0-9]+$ ]] || continue
        kill "-$signal" "$p" 2>/dev/null || true
    done <<<"$set"
}

fmix_template_build_abort() {
    # Signal-time cleanup for an in-flight template build: reap the ENTIRE
    # compile tree (TERM, brief grace, then KILL), wait so nothing can still
    # be mutating the session overlay, quarantine the staging dir, strip the
    # ephemeral Oban repo, and only then release the build lease. Releasing
    # earlier would let the next lock holder compile on a still-mutating
    # overlay.
    local pid="${1:-}" worktree="$2" lock_name="$3" code="${4:-130}"
    local tmp_dir="${5:-}" child retained=""
    if [[ -z "$pid" ]]; then
        # Signal landed between the spawn and `build_pid=$!`. We cannot name
        # the child, but at this point in the build every direct child of this
        # process is ours — reap them all so nothing survives the lease.
        if command -v pgrep >/dev/null 2>&1; then
            while IFS= read -r child; do
                [[ "$child" =~ ^[0-9]+$ ]] || continue
                retained+="$(fmix_collect_process_tree "$child")"$'\n'
            done < <(pgrep -P $$ 2>/dev/null || true)
        fi
    else
        retained="$(fmix_collect_process_tree "$pid")"
    fi
    if [[ -n "$retained" ]]; then
        fmix_signal_retained_set TERM "$retained"
        sleep 1
        fmix_signal_retained_set KILL "$retained"
        # KILL delivery is asynchronous — confirm every retained PID is gone
        # (bounded poll) before quarantine and lease release, so no dying
        # compiler is still flushing into the overlay when the next lock
        # holder starts.
        local reap_try reap_pid reap_alive
        for reap_try in 1 2 3 4 5 6 7 8 9 10; do
            reap_alive=0
            while IFS= read -r reap_pid; do
                [[ "$reap_pid" =~ ^[0-9]+$ ]] || continue
                if kill -0 "$reap_pid" 2>/dev/null; then
                    reap_alive=1
                    break
                fi
            done <<<"$retained"
            (( reap_alive == 0 )) && break
            sleep 0.5
        done
    fi
    [[ -n "$pid" ]] && wait "$pid" 2>/dev/null || true
    if [[ -n "$tmp_dir" && -e "$tmp_dir" ]]; then
        fmix_template_quarantine "$tmp_dir" "aborted producer compile" >/dev/null 2>&1 || true
    fi
    fmix_remove_ephemeral_oban_repo "$worktree" 2>/dev/null || true
    fmix_command_lock_finish "$lock_name" "$code" 1 || true
    exit "$code"
}

fmix_template_build_active() {
    # Non-destructive probe: is the build kernel lease for this template
    # currently held by a live producer? Attempts a non-blocking exclusive
    # flock on the kernel file and releases it immediately when it succeeds.
    local key="$1" kernel_file py_bin
    kernel_file="$FMIX_HOME/lock-kernel/build-${key}"
    [[ -e "$kernel_file" ]] || return 1
    py_bin="$(fmix_python_bin)"
    "$py_bin" - "$kernel_file" <<'PY'
import fcntl
import sys

try:
    handle = open(sys.argv[1], "a")
except OSError:
    raise SystemExit(1)
try:
    fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
    raise SystemExit(0)   # lease held -> a producer is building
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
raise SystemExit(1)       # acquired freely -> nobody is building
PY
}

fmix_template_credential_preflight() {
    # Validate Oban Pro credential availability without disturbing an
    # operator-supplied OBAN_LICENSE_KEY environment value: the preflight only
    # unsets the key when it loaded one itself (file or Doppler), so the later
    # real dependency resolution sees exactly the environment it started with.
    local worktree="$1" had_env=0
    [[ -n "${OBAN_LICENSE_KEY:-}" ]] && had_env=1
    if ! fmix_load_oban_license_key; then
        fmix_error "Oban credential preflight failed for worktree: $worktree"
        return 1
    fi
    if (( had_env == 0 )); then
        unset OBAN_LICENSE_KEY
    fi
    return 0
}

fmix_surface_log_tail() {
    # Surface the tail of a redirected build log on stderr so failures inside
    # `>>log 2>&1` phases are visible inline instead of buried in a log file
    # the caller has to hunt for.
    local log_file="$1" n="${2:-15}"
    [[ -f "$log_file" ]] || return 0
    fmix_warn "Last ${n} lines of $log_file:"
    tail -n "$n" "$log_file" 2>/dev/null | sed 's/^/  | /' >&2 || true
    return 0
}

fmix_retain_session_on_template_pressure() {
    local key="$1" tmp_dir="$2" lock_name="$3"
    local cause="${4:-disk pressure or incomplete capacity observation}"
    fmix_warn "Optional template publication held by ${cause}; keeping the proven writable session."
    # This producer's staging is still empty. Never recursively erase an
    # unexpected payload or a recovery stage to manufacture a successful skip.
    if ! rmdir "$tmp_dir"; then
        fmix_lock_release "$lock_name" || fmix_error "Template lease release also failed after staging hold."
        return 1
    fi
    if ! fmix_lock_release "$lock_name"; then
        FMIX_ARTIFACT_LEASE_RELEASE_FAILED=1
        return 2
    fi
    FMIX_TEMPLATE_PUBLICATION_HELD_KEY="$key"
    return 0
}

fmix_build_template() {
    # A template may be seeded only from the active session after exact
    # dependency and compile stamps prove those mutable artifacts. Otherwise
    # build in the session first. Arbitrary worktree deps/_build are never
    # promoted into the shared cache.
    local worktree="$1" key="$2" lock_name tdir tmp_dir log_dir
    lock_name="build-${key}"
    local deps_root build_root dependency_fingerprint compile_fingerprint
    local source_commit toolchain built_at manifest_sha proven=0
    FMIX_TEMPLATE_PUBLICATION_HELD_KEY=""
    tdir="$(fmix_template_dir "$key")"
    tdir="$(fmix_template_v2_dir "$key")" || return 1
    tmp_dir="$FMIX_HOME/artifacts/v2/templates/${key}.tmp-$$-${RANDOM}"
    log_dir="$FMIX_HOME/logs"
    deps_root="$(fmix_session_deps_root "$worktree")" || return 1
    build_root="$(fmix_compile_build_root "$worktree")" || return 1
    mkdir -p "$log_dir" || return 1
    fmix_artifact_v2_prepare_directory "artifacts/v2/templates" || return 1

    # An already-complete template needs no build (and therefore no
    # credentials); return before any preflight so offline consumers of a
    # published template are never blocked on credential resolution.
    if fmix_template_is_complete "$key"; then
        return 0
    fi

    # Split dependency reuse from the source/config template key. An exact
    # artifact is a consumer hit. A closest-ancestor artifact may only seed
    # this producer; its stamps are removed so Mix must reconcile and prove
    # the final exact dependency fingerprint before publication.
    local dependency_preparation_rc=0
    fmix_prepare_dependency_artifacts "$worktree" || dependency_preparation_rc=$?
    if (( dependency_preparation_rc != 0 )); then
        fmix_error "Dependency artifact preparation failed closed."
        return "$dependency_preparation_rc"
    fi

    # Credential preflight BEFORE queueing on the build lock. Credentials are
    # only ever consumed by `mix deps.get`, and `fmix_ensure_compile` runs
    # deps.get only on a dependency-stamp miss — a stale compile over proven
    # dependencies rebuilds offline. So preflight strictly on the dependency
    # stamp: when it is unproven and the credential is unavailable, every
    # queued builder would otherwise acquire the lock, fail deps.get inside
    # the redirected build log, release, and let the next one repeat the same
    # failure — serially and invisibly (2026-07-30 multi-agent swarm
    # regression).
    local preflight_dep preflight_deps_proven=0
    if [[ -d "$deps_root" ]]; then
        preflight_dep="$(fmix_compute_dependency_fingerprint "$worktree" 2>/dev/null)" \
            || preflight_dep=""
        if [[ -n "$preflight_dep" ]] \
            && fmix_dependency_stamp_matches "$worktree" "$preflight_dep"; then
            preflight_deps_proven=1
        fi
    fi
    if (( preflight_deps_proven == 0 )) && fmix_worktree_uses_oban_repo "$worktree"; then
        if ! fmix_template_credential_preflight "$worktree"; then
            # A credential-less process can still consume a template that a
            # credentialed producer is building right now — wait for that
            # publication instead of failing what would have succeeded. The
            # probe window covers the producer's own credential preflight
            # (Doppler is bounded to 15s), so a producer between preflight
            # and lease acquisition is not misread as absent; template
            # completeness is re-checked throughout and before the final
            # fail-fast. This path only runs when this process has no
            # credential anywhere, so the bounded wait is rare.
            local producer_probe producer_active=0
            for producer_probe in 1 2 3 4 5 6 7 8 9 10; do
                if fmix_template_build_active "$key"; then
                    producer_active=1
                    break
                fi
                if fmix_template_is_complete "$key"; then
                    return 0
                fi
                (( producer_probe < 10 )) && sleep 2
            done
            if (( producer_active )); then
                fmix_warn "Credentials unavailable, but a live producer holds the build lease for template $key — waiting for its publication."
                if fmix_wait_for_template "$key"; then
                    return 0
                fi
                fmix_error "The active template build did not publish in time, and this process has no credentials to build it."
                return 1
            fi
            if fmix_template_is_complete "$key"; then
                return 0
            fi
            fmix_error "Credential preflight failed; not queueing for the template build lock."
            return 1
        fi
    fi

    fmix_lock_acquire "$lock_name" "$FMIX_LOCK_TIMEOUT" || return $?

    if fmix_template_is_complete "$key"; then
        fmix_info "Template $key completed by another process while we waited."
        fmix_command_lock_finish "$lock_name" 0
        return $?
    fi
    if [[ -e "$tdir" || -L "$tdir" ]]; then
        fmix_template_quarantine "$tdir" "failed integrity or incomplete publication" || {
            fmix_command_lock_finish "$lock_name" 1
            return $?
        }
    fi

    fmix_info "Building template $key …"
    mkdir "$tmp_dir" || {
        fmix_command_lock_finish "$lock_name" 1
        return $?
    }
    local log_file="$log_dir/build-${key}-$$-${RANDOM}.log"
    source_commit="$(git -C "$worktree" rev-parse --short HEAD 2>/dev/null || echo "unknown")"
    toolchain="${FMIX_TOOLCHAIN_IDENTITY:-unknown}"
    fmix_prepend_toolchain_paths

    dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree" 2>/dev/null)" \
        || dependency_fingerprint=""
    compile_fingerprint="$(fmix_compute_compile_fingerprint "$worktree" 2>/dev/null)" \
        || compile_fingerprint=""
    if [[ -d "$deps_root" && -d "$build_root" \
        && -n "$dependency_fingerprint" && -n "$compile_fingerprint" ]] \
        && fmix_dependency_stamp_matches "$worktree" "$dependency_fingerprint" \
        && fmix_compile_stamp_matches "$worktree" "$compile_fingerprint"; then
        proven=1
        fmix_info "Session artifacts have exact provenance — publishing without recompilation."
    fi

    if (( proven == 0 )); then
        fmix_info "No proven session baseline; resolving and compiling once before publication …"
        fmix_info "Template build output captured in: $log_file"
        local build_pid="" build_rc=0 build_started build_now build_last build_bytes build_hb
        local prev_trap_int prev_trap_term
        # If this builder dies (Ctrl-C, agent timeout), the backgrounded
        # compile tree must die with it BEFORE the build lease is released —
        # an orphan compiler mutating session state under a new lock holder
        # would corrupt the build. Traps are installed before the spawn so no
        # signal window exists; SIGKILL cannot be covered. Single-quoted so
        # $build_pid resolves at signal time.
        prev_trap_int="$(trap -p INT)"
        prev_trap_term="$(trap -p TERM)"
        trap 'fmix_template_build_abort "${build_pid:-}" "$worktree" "$lock_name" 130 "$tmp_dir"' INT
        trap 'fmix_template_build_abort "${build_pid:-}" "$worktree" "$lock_name" 143 "$tmp_dir"' TERM
        fmix_ensure_compile "$worktree" "$(fmix_db_name_for_worktree "$worktree")" setup \
            >>"$log_file" 2>&1 &
        build_pid=$!
        build_hb="$(fmix_uint_or_default "$FMIX_COMPILE_HEARTBEAT" 30 FMIX_COMPILE_HEARTBEAT)"
        build_started="$(fmix_epoch)"
        build_last="$build_started"
        while kill -0 "$build_pid" 2>/dev/null; do
            sleep 5
            build_now="$(fmix_epoch)"
            if (( build_hb > 0 && build_now - build_last >= build_hb )); then
                build_bytes="$(wc -c <"$log_file" 2>/dev/null | tr -d ' ')"
                fmix_info "Template build running ($(( build_now - build_started ))s elapsed, $(( ${build_bytes:-0} / 1024 )) KB logged) …"
                build_last="$build_now"
            fi
        done
        wait "$build_pid" 2>/dev/null || build_rc=$?
        eval "${prev_trap_int:-trap - INT}"
        eval "${prev_trap_term:-trap - TERM}"
        if (( build_rc != 0 )); then
            # Keep compiler-path failure distinct from artifact admission or
            # metadata refusal when an outer command retires its own lease.
            FMIX_LAST_ARTIFACTS_COMPILE_FAILURE=1
            fmix_error "Session compile failed. See log: $log_file"
            if fmix_lock_failure_is_fatal "$build_rc"; then
                fmix_command_lock_finish "$lock_name" "$build_rc" 1
                return $?
            fi
            fmix_surface_log_tail "$log_file" 15
            fmix_template_quarantine "$tmp_dir" "failed producer compile" >/dev/null 2>&1 || true
            fmix_command_lock_finish "$lock_name" "$build_rc" 1
            return $?
        fi
        dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" || {
            fmix_template_quarantine "$tmp_dir" "dependency fingerprint failed" >/dev/null 2>&1 || true
            fmix_command_lock_finish "$lock_name" 1
            return $?
        }
        compile_fingerprint="$(fmix_compute_compile_fingerprint "$worktree")" || {
            fmix_template_quarantine "$tmp_dir" "compile fingerprint failed" >/dev/null 2>&1 || true
            fmix_command_lock_finish "$lock_name" 1
            return $?
        }
        if ! fmix_dependency_stamp_matches "$worktree" "$dependency_fingerprint" \
            || ! fmix_compile_stamp_matches "$worktree" "$compile_fingerprint"; then
            fmix_error "Compiled session did not establish exact artifact provenance."
            fmix_template_quarantine "$tmp_dir" "producer provenance failed" >/dev/null 2>&1 || true
            fmix_command_lock_finish "$lock_name" 1
            return $?
        fi
    fi


    # Missing managed handoff is an optional publication hold, not a cold-build
    # failure. Retain the exact writable session and publish no shared generation.
    if ! fmix_managed_publication_gate template; then
        fmix_retain_session_on_template_pressure "$key" "$tmp_dir" "$lock_name" \
            "managed launcher handoff unproven"
        return $?
    fi

    # The exact writable session is already proven above. Publishing another
    # full copy is optional: pressure/unknown capacity must not force a cold
    # rebuild, discard this overlay, or claim a template was published.
    if ! fmix_optional_cache_has_headroom "$deps_root" "$build_root"; then
        fmix_retain_session_on_template_pressure "$key" "$tmp_dir" "$lock_name"
        return $?
    fi

    local publication_rc=0
    fmix_publish_dependency_artifact \
        "$worktree" "$dependency_fingerprint" || publication_rc=$?
    if (( publication_rc != 0 )); then
        if fmix_lock_failure_is_fatal "$publication_rc"; then
            fmix_template_quarantine "$tmp_dir" "dependency publication fatal lock outcome" >/dev/null 2>&1 || true
            fmix_command_lock_finish "$lock_name" "$publication_rc"
            return $?
        fi
        case "$publication_rc" in
            2|129|130|143)
                fmix_template_quarantine "$tmp_dir" "dependency publication terminal failure" >/dev/null 2>&1 || true
                fmix_command_lock_finish "$lock_name" "$publication_rc"
                return $? ;;
        esac
        if [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" != "0" ]]; then
            fmix_template_quarantine "$tmp_dir" "dependency lease release failure" >/dev/null 2>&1 || true
            fmix_command_lock_finish "$lock_name" "$publication_rc"
            return $?
        fi
        fmix_warn "Exact dependency artifact publication failed; keeping the proven session while attempting optional template publication."
    fi

    # A cache hit may return before its publisher normalizes session-internal
    # links; normalize here before the full-template manifest and copy.
    if ! fmix_session_normalize_links "$worktree" >>"$log_file" 2>&1; then
        fmix_error "Could not normalize session-internal symlinks. See log: $log_file"
        fmix_template_quarantine "$tmp_dir" "session link normalization failed" >/dev/null 2>&1 || true
        fmix_command_lock_finish "$lock_name" 1
        return $?
    fi

    # The dependency publication above may have consumed the earlier buffer.
    # Re-observe before the full-template copy; this remains advisory, not an
    # atomic host reservation against concurrent/nonparticipating allocators.
    if ! fmix_optional_cache_has_headroom "$deps_root" "$build_root"; then
        fmix_retain_session_on_template_pressure "$key" "$tmp_dir" "$lock_name"
        return $?
    fi
    fmix_info "Cloning proven session artifacts into immutable staging …"
    if ! fmix_cow_clone "$deps_root" "$tmp_dir/deps" >>"$log_file" 2>&1 \
        || ! fmix_cow_clone "$build_root" "$tmp_dir/_build" >>"$log_file" 2>&1; then
        fmix_error "Failed to stage proven artifacts. See log: $log_file"
        fmix_template_quarantine "$tmp_dir" "artifact staging failed" >/dev/null 2>&1 || true
        fmix_command_lock_finish "$lock_name" 1
        return $?
    fi
    if ! fmix_template_materialize_app_priv \
        "$tmp_dir" "$worktree" "$build_root" >>"$log_file" 2>&1; then
        fmix_error "Template app priv link was not the exact worktree target."
        fmix_template_quarantine "$tmp_dir" "unsafe app priv link" >/dev/null 2>&1 || true
        fmix_command_lock_finish "$lock_name" 1
        return $?
    fi

    manifest_sha="$(fmix_template_write_manifest "$tmp_dir")" || {
        fmix_error "Template manifest validation failed; publication was quarantined."
        fmix_template_quarantine "$tmp_dir" "manifest validation failed" >/dev/null 2>&1 || true
        fmix_command_lock_finish "$lock_name" 1
        return $?
    }
    built_at="$(fmix_now)"
    fmix_write_template_meta \
        "$tmp_dir" "complete" "$built_at" "$toolchain" "$source_commit" \
        "$key" "$manifest_sha" || {
        fmix_template_quarantine "$tmp_dir" "metadata publication failed" >/dev/null 2>&1 || true
        fmix_command_lock_finish "$lock_name" 1
        return $?
    }
    if ! fmix_template_make_readonly "$tmp_dir"; then
        fmix_error "Could not make template staging read-only."
        fmix_template_quarantine "$tmp_dir" "read-only assertion failed" >/dev/null 2>&1 || true
        fmix_command_lock_finish "$lock_name" 1
        return $?
    fi
    if ! fmix_artifact_v2_managed_entrypoint; then
        fmix_template_quarantine "$tmp_dir" "managed launcher handoff changed before publication" || {
            fmix_command_lock_finish "$lock_name" 1
            return $?
        }
        fmix_command_lock_finish "$lock_name" 0 || return $?
        FMIX_TEMPLATE_PUBLICATION_HELD_KEY="$key"
        return 0
    fi
    if [[ -e "$tdir" || -L "$tdir" ]] || ! mv "$tmp_dir" "$tdir"; then
        fmix_error "Immutable destination was occupied during publication: $tdir"
        fmix_template_quarantine "$tmp_dir" "publication collision" >/dev/null 2>&1 || true
        fmix_command_lock_finish "$lock_name" 1
        return $?
    fi
    chmod a-w "$tdir" || {
        fmix_error "Published template root could not be sealed read-only."
        fmix_template_quarantine "$tdir" "root seal failed" >/dev/null 2>&1 || true
        fmix_command_lock_finish "$lock_name" 1
        return $?
    }
    fmix_template_is_complete "$key" || {
        fmix_error "Published template failed its shallow integrity assertion."
        fmix_template_quarantine "$tdir" "post-publication assertion failed" >/dev/null 2>&1 || true
        fmix_command_lock_finish "$lock_name" 1
        return $?
    }

    fmix_command_lock_finish "$lock_name" 0 || return $?
    fmix_info "Template $key ready. Build log: $log_file"
    FMIX_TEMPLATE_BUILT_FROM_ACTIVE_SESSION=1
    return 0
}

fmix_wait_for_template() {
    # Poll for an in-progress template build (another process is building it)
    local key="$1"
    local deadline=$(( $(fmix_epoch) + FMIX_LOCK_TIMEOUT ))
    local n=0

    while ! fmix_template_is_complete "$key"; do
        if (( $(fmix_epoch) >= deadline )); then
            fmix_error "Timed out waiting for template $key to be built."
            fmix_error "If the builder process crashed, delete $FMIX_HOME/templates/${key}.tmp-* and retry."
            return 1
        fi
        n=$(( n + 1 ))
        local elapsed=$(( n * 5 ))
        fmix_info "Waiting for template build ($elapsed s elapsed) …"
        sleep 5
    done
    return 0
}

fmix_ensure_template() {
    local worktree="$1" key="$2"
    FMIX_TEMPLATE_PUBLICATION_HELD_KEY=""

    if fmix_template_is_complete "$key"; then
        fmix_update_template_last_used "$key" || return $?
        return 0
    fi

    fmix_build_template "$worktree" "$key" || return $?
    [[ "${FMIX_TEMPLATE_PUBLICATION_HELD_KEY:-}" != "$key" ]] || return 0
    fmix_update_template_last_used "$key" || return $?
    return 0
}

# ---------------------------------------------------------------------------
# Warm donor bootstrap (2.2.0+): CoW a proven peer session for the same
# worktree + template_key instead of cold template + full recompile.
# ---------------------------------------------------------------------------

fmix_find_warm_donor_session() {
    local worktree="$1" template_key="$2"
    local real py_bin donor
    shift 2
    real="$(fmix_realpath "$worktree")" || return 1
    [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]] || return 1
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    donor="$(
        FMIX_HOME_FOR_DONOR="$FMIX_HOME" \
        DONOR_WORKTREE="$real" \
        DONOR_TEMPLATE_KEY="$template_key" \
        DONOR_EXCLUDE="$FMIX_ACTIVE_SESSION_ROOT" \
        "$py_bin" - "$@" <<'PY'
import json, os, sys
from pathlib import Path

home = Path(os.environ["FMIX_HOME_FOR_DONOR"])
wt = os.environ["DONOR_WORKTREE"]
key = os.environ["DONOR_TEMPLATE_KEY"]
excluded = {os.environ["DONOR_EXCLUDE"]}
excluded.update(sys.argv[1:])
root = home / "sessions" / "v1"
best = None  # (is_same_wt, last, path)
if not root.is_dir():
    raise SystemExit(0)
for meta in root.glob("*/*/*/meta.json"):
    session_root = meta.parent
    if str(session_root) in excluded:
        continue
    try:
        d = json.loads(meta.read_text(encoding="utf-8"))
    except Exception:
        continue
    session_wt = d.get("worktree") or ""
    art = session_root / "artifact-state.json"
    stamp = session_root / "compile-stamp.json"
    deps = session_root / "deps"
    build = session_root / "_build"
    if not (art.is_file() and stamp.is_file() and deps.is_dir() and build.is_dir()):
        continue
    try:
        art_d = json.loads(art.read_text(encoding="utf-8"))
    except Exception:
        continue
    if (art_d.get("template_key") or "") != key:
        continue
    # REL-3972: a cross-worktree candidate needs the same proof the revalidator
    # requires (schema-2 stamp, clean tree), applied before ranking so an
    # unproven newer donor cannot hide a valid older one.
    if session_wt != wt:
        try:
            stamp_d = json.loads(stamp.read_text(encoding="utf-8"))
        except Exception:
            continue
        if stamp_d.get("schema_version") != 2 or stamp_d.get("dirty_hash", "clean") != "clean":
            continue
    is_same_wt = 1 if session_wt == wt else 0
    last = d.get("last_accessed") or d.get("last_used") or ""
    cand = (is_same_wt, last, str(session_root))
    if best is None or cand > best:
        best = cand
if best:
    print(best[2])
PY
    )" || donor=""
    [[ -n "$donor" && -d "$donor/deps" && -d "$donor/_build" ]] || return 1
    # Never clone from self.
    [[ "$donor" != "$FMIX_ACTIVE_SESSION_ROOT" ]] || return 1
    printf '%s\n' "$donor"
}

fmix_donor_session_roots_are_owned() {
    local donor="$1" py_bin
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    FMIX_HOME_FOR_DONOR="$FMIX_HOME" \
    DONOR_ROOT="$donor" \
    "$py_bin" - <<'PY'
import os
import re
import stat
import sys

configured_home = os.environ["FMIX_HOME_FOR_DONOR"].rstrip(os.sep)
home = os.path.realpath(configured_home)
donor = os.path.abspath(os.environ["DONOR_ROOT"])
fd = None
try:
    if not os.path.isabs(configured_home) or not os.path.isdir(home):
        raise ValueError("home path")
    prefix = os.path.join(configured_home, "sessions", "v1") + os.sep
    if not donor.startswith(prefix) or os.path.normpath(donor) != donor:
        raise ValueError("session path")
    components = donor[len(prefix):].split(os.sep)
    if (len(components) != 3
            or any(part in ("", ".", "..") for part in components)
            or not re.fullmatch(r"[0-9a-f]{16}", components[1])):
        raise ValueError("session components")

    if not hasattr(os, "O_NOFOLLOW") or not hasattr(os, "O_DIRECTORY"):
        raise ValueError("no-follow directory opens unavailable")
    flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
    fd = os.open(home, flags)
    home_stat = os.fstat(fd)
    device = home_stat.st_dev
    owner = os.getuid()
    if home_stat.st_uid != owner or not stat.S_ISDIR(home_stat.st_mode):
        raise ValueError("home ownership")
    for component in ("sessions", "v1", *components):
        child = os.open(component, flags, dir_fd=fd)
        os.close(fd)
        fd = child
        current = os.fstat(fd)
        if (current.st_uid != owner or current.st_dev != device
                or not stat.S_ISDIR(current.st_mode)):
            raise ValueError("session root ownership")
    for component in ("deps", "_build"):
        child = os.open(component, flags, dir_fd=fd)
        current = os.fstat(child)
        os.close(child)
        if (current.st_uid != owner or current.st_dev != device
                or not stat.S_ISDIR(current.st_mode)):
            raise ValueError("artifact root ownership")
except (OSError, ValueError):
    raise SystemExit(1)
finally:
    if fd is not None:
        os.close(fd)
PY
}

fmix_donor_session_revalidate() {
    local donor="$1" target_worktree="$2" template_key="$3" expected_session_hash="$4"
    local donor_meta="$donor/meta.json" current_session_hash py_bin
    fmix_donor_session_roots_are_owned "$donor" || return $?
    [[ -d "$donor/deps" && ! -L "$donor/deps" \
        && -d "$donor/_build" && ! -L "$donor/_build" \
        && -f "$donor/artifact-state.json" && -f "$donor/compile-stamp.json" ]] || return 1
    current_session_hash="$(fmix_session_hash_from_metadata_path "$donor_meta")" || return $?
    [[ "$current_session_hash" == "$expected_session_hash" ]] || return 1
    fmix_session_metadata_identity_matches_path "$donor_meta" || return $?
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    DONOR_ROOT="$donor" \
    DONOR_TARGET_WORKTREE="$target_worktree" \
    DONOR_TEMPLATE_KEY="$template_key" \
    DONOR_SESSION_HASH="$expected_session_hash" \
    "$py_bin" - <<'PY'
import json
import os
from pathlib import Path

root = Path(os.path.abspath(os.environ["DONOR_ROOT"]))
target_worktree = os.path.realpath(os.environ["DONOR_TARGET_WORKTREE"])
template_key = os.environ["DONOR_TEMPLATE_KEY"]
session_hash = os.environ["DONOR_SESSION_HASH"]

def read_object(name):
    path = root / name
    if path.is_symlink() or not path.is_file():
        raise ValueError(name)
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise ValueError(name)
    return value

def canonical_path(value):
    if not isinstance(value, str) or not value or not os.path.isabs(value):
        raise ValueError("path")
    return os.path.realpath(value)

try:
    meta = read_object("meta.json")
    if meta.get("session_hash") not in (None, session_hash):
        raise ValueError("session hash")
    if meta.get("session_id") not in (None, session_hash):
        raise ValueError("session id")
    source_worktree = canonical_path(meta.get("worktree"))
    if ("deps_path" in meta
            and canonical_path(meta["deps_path"]) != os.path.realpath(root / "deps")):
        raise ValueError("metadata deps path")
    if "build_path" in meta:
        recorded_build_path = canonical_path(meta["build_path"])
        allowed_build_paths = {
            os.path.realpath(root / "_build"),
            os.path.realpath(root / "_build" / "test"),
        }
        if recorded_build_path not in allowed_build_paths:
            raise ValueError("metadata build path")

    artifact_state = read_object("artifact-state.json")
    if artifact_state.get("template_key") != template_key:
        raise ValueError("template key")

    compile_stamp = read_object("compile-stamp.json")
    if ("template_key" in compile_stamp
            and compile_stamp.get("template_key") != template_key):
        raise ValueError("compile template key")
    if ("path" in compile_stamp
            and canonical_path(compile_stamp["path"]) != source_worktree):
        raise ValueError("compile path")
    if ("build_root" in compile_stamp
            and canonical_path(compile_stamp["build_root"]) != os.path.realpath(root / "_build")):
        raise ValueError("compile build root")

    dependency_stamp_path = root / "dependency-stamp.json"
    if dependency_stamp_path.exists() or dependency_stamp_path.is_symlink():
        dependency_stamp = read_object("dependency-stamp.json")
        if ("path" in dependency_stamp
                and canonical_path(dependency_stamp["path"]) != source_worktree):
            raise ValueError("dependency path")
        if ("build_root" in dependency_stamp
                and canonical_path(dependency_stamp["build_root"]) != os.path.realpath(root / "_build")):
            raise ValueError("dependency build root")

    # REL-3972: a donor from another worktree must prove a clean tree with a
    # schema-2 stamp. Legacy or unproven stamps cannot carry that worktree's
    # compiled _build into this one.
    if source_worktree != target_worktree:
        if compile_stamp.get("schema_version") != 2:
            raise ValueError("unproven cross-worktree donor")
        if compile_stamp.get("dirty_hash", "clean") != "clean":
            raise ValueError("dirty cross-worktree donor")
except (OSError, TypeError, ValueError, json.JSONDecodeError):
    raise SystemExit(1)
PY
}

fmix_donor_make_stage_writable() {
    (( $# == 2 )) || return 1
    chmod -R u+w "$1" "$2"
}

fmix_donor_copy_stamps() {
    (( $# == 2 )) || return 1
    local donor="$1" stage_root="$2"
    cp -f "$donor/compile-stamp.json" "$stage_root/compile-stamp.json" || return 1
    if [[ -f "$donor/dependency-stamp.json" ]]; then
        cp -f "$donor/dependency-stamp.json" "$stage_root/dependency-stamp.json" || return 1
    fi
}

fmix_donor_rebind_staged_stamps() {
    local stage_root="$1" real="$2" build_root="$3" py_bin="$4"
    "$py_bin" - "$stage_root" "$real" "$build_root" <<'PY'
import json
import os
import sys
from pathlib import Path

root = Path(sys.argv[1])
real = sys.argv[2]
build_root = sys.argv[3]
for name in ("compile-stamp.json", "dependency-stamp.json"):
    path = root / name
    if not path.exists() and not path.is_symlink():
        if name == "compile-stamp.json":
            raise SystemExit(1)
        continue
    if path.is_symlink() or not path.is_file():
        raise SystemExit(1)
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
        if not isinstance(value, dict):
            raise ValueError(name)
        value["path"] = real
        value["build_root"] = build_root
        temporary = path.with_name(path.name + f".tmp-{os.getpid()}")
        temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8")
        os.replace(temporary, path)
    except (OSError, TypeError, ValueError, json.JSONDecodeError):
        raise SystemExit(1)
PY
}

fmix_donor_stage_artifact_state() {
    (( $# == 3 )) || return 1
    local staged_root="$1" worktree="$2" template_key="$3"
    local original_session_root="$FMIX_ACTIVE_SESSION_ROOT" rc=0
    FMIX_ACTIVE_SESSION_ROOT="$staged_root"
    fmix_write_artifact_state "$worktree" "$template_key" || rc=$?
    FMIX_ACTIVE_SESSION_ROOT="$original_session_root"
    return "$rc"
}

fmix_donor_transaction_move() {
    (( $# == 3 )) || return 1
    mv "$1" "$2"
}

fmix_donor_transaction_stage_cleanup() {
    (( $# == 1 )) || return 1
    local stage="$1"
    fmix_guard_path "$stage" || return 1
    rm -rf "$stage" || return 1
    [[ ! -e "$stage" && ! -L "$stage" ]]
}

_fmix_donor_install_interrupt() {
    if (( ${donor_install_interrupted:-0} == 0 )); then
        donor_install_interrupted=1
        donor_install_interrupt_rc="${1:-130}"
    fi
}

fmix_donor_restore_interrupt_traps() {
    (( $# == 3 )) || return 1
    local saved_int="$1" saved_term="$2" saved_hup="$3"
    if [[ -n "$saved_int" ]]; then eval "$saved_int"; else trap - INT; fi
    if [[ -n "$saved_term" ]]; then eval "$saved_term"; else trap - TERM; fi
    if [[ -n "$saved_hup" ]]; then eval "$saved_hup"; else trap - HUP; fi
}

fmix_donor_session_lease_release() {
    local lock_name="${1:-}" operation_rc="${2:-0}" release_rc=0
    fmix_lock_release "$lock_name" || release_rc=$?
    if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]] && (( release_rc == 0 )); then
        release_rc=70
    fi
    if (( release_rc != 0 )); then
        FMIX_ARTIFACT_LEASE_RELEASE_FAILED=1
        printf '{"error":"donor_session_lock_cleanup_failed","operation_exit_code":%d,"cleanup_exit_code":%d}\n' \
            "$operation_rc" "$release_rc" >&2
        fmix_error "Donor session lease cleanup failed (operation rc=$operation_rc, release rc=$release_rc)."
        return 70
    fi
    return 0
}

_fmix_donor_abort_staging() {
    (( $# == 4 )) || return 70
    local lock_name="$1" stage="${2:-}" operation_rc="$3"
    local lease_held="$4" release_rc=0 cleanup_rc=0 restore_rc=0

    if (( donor_install_interrupted != 0 )); then
        operation_rc="$donor_install_interrupt_rc"
    fi
    # The scoped signal handler only records cancellation while cleanup runs;
    # keep it installed through lease retirement and stage removal.
    if (( lease_held != 0 )); then
        fmix_donor_session_lease_release "$lock_name" "$operation_rc" \
            || release_rc=$?
    fi
    # Keep staging inputs when lease release is not confirmed. Cleanup failure
    # also remains fatal, with whatever recovery data is left kept in place.
    if (( release_rc == 0 )) && [[ -n "$stage" ]]; then
        fmix_donor_transaction_stage_cleanup "$stage" || cleanup_rc=$?
    fi
    if (( cleanup_rc != 0 )); then
        fmix_error "Could not clean failed donor staging; preserving recovery inputs: $stage"
    fi
    fmix_donor_restore_interrupt_traps \
        "$saved_trap_int" "$saved_trap_term" "$saved_trap_hup" || restore_rc=$?
    # A signal delivered while the previous handlers are being restored must
    # still become the caller-visible result instead of an ordinary cache miss.
    if (( donor_install_interrupted != 0 )); then
        operation_rc="$donor_install_interrupt_rc"
    fi
    if (( release_rc != 0 )); then
        return 70
    fi
    if (( cleanup_rc != 0 )); then
        return 70
    fi
    if (( restore_rc != 0 )); then
        fmix_error "Could not restore caller signal traps after donor staging cleanup."
        return 70
    fi
    return "$operation_rc"
}

fmix_clone_donor_to_session() {
    local worktree="$1" donor="$2" template_key="${3:-}"
    local deps_root build_root real py_bin
    local donor_meta donor_session_hash donor_lock_name
    local target_session_root dependency_stamp compile_stamp artifact_state
    local donor_lease_rc=0 donor_lease_held=0 donor_restore_rc=0
    local donor_signal_after_restore=0
    local stage="" stage_new stage_old stage_rc=0 stage_cleanup_rc=0
    local transaction_rc=0 rollback_failed=0 index item_name item_source item_target move_rc
    local revalidate_rc=0
    local donor_install_interrupted=0 donor_install_interrupt_rc=0
    local saved_trap_int saved_trap_term saved_trap_hup
    (( $# == 3 )) && [[ "$template_key" =~ ^[0-9a-f]{16}$ ]] || return 1
    real="$(fmix_realpath "$worktree")" || return 1
    deps_root="$(fmix_session_deps_root "$worktree")" || return 1
    build_root="$(fmix_compile_build_root "$worktree")" || return 1

    [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]] || return 1
    target_session_root="$FMIX_ACTIVE_SESSION_ROOT"
    [[ -d "$target_session_root" && ! -L "$target_session_root" ]] || return 1
    [[ "$deps_root" == "$FMIX_ACTIVE_SESSION_ROOT/deps" \
        && "$build_root" == "$FMIX_ACTIVE_SESSION_ROOT/_build" ]] || return 1
    dependency_stamp="$(fmix_dependency_stamp_file "$worktree")" || return 1
    compile_stamp="$(fmix_compile_stamp_file "$worktree")" || return 1
    artifact_state="$(fmix_artifact_state_file "$worktree")" || return 1
    [[ "$dependency_stamp" == "$target_session_root/dependency-stamp.json" \
        && "$compile_stamp" == "$target_session_root/compile-stamp.json" \
        && "$artifact_state" == "$target_session_root/artifact-state.json" ]] || return 1
    fmix_guard_path "$donor" || {
        fmix_error "Donor path is outside FMIX_HOME: $donor"
        return 1
    }

    fmix_info "Cloning warm donor session into active overlay (avoid full recompile) …"
    fmix_info "Donor: $donor"

    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"

    # Donor sessions share the same persistent session kernel lock used by
    # execution and GC. Never derive this lock from a metadata field: metadata
    # is replaceable, so derive and validate the identity from its canonical
    # session path before acquiring the lease.
    donor_meta="$donor/meta.json"
    [[ -f "$donor_meta" && ! -L "$donor_meta" ]] || return 1
    donor_session_hash="$(fmix_session_hash_from_metadata_path "$donor_meta")" || return 1
    fmix_session_metadata_identity_matches_path "$donor_meta" || return 1
    donor_lock_name="session-$donor_session_hash"
    # Guard the entire leased read, including revalidation and staging copies.
    # The saved caller handlers are restored on every exit after admission.
    saved_trap_int="$(trap -p INT)"
    saved_trap_term="$(trap -p TERM)"
    saved_trap_hup="$(trap -p HUP)"
    trap '_fmix_donor_install_interrupt 130' INT
    trap '_fmix_donor_install_interrupt 143' TERM
    trap '_fmix_donor_install_interrupt 129' HUP
    # Use the canonical session lease so new and legacy FMix binaries arbitrate
    # on the same mkdir record as execution and GC. This intentionally takes an
    # exclusive, zero-wait lease only for the duration of copying one donor.
    # Passive mode refuses preexisting legacy metadata without stale cleanup.
    fmix_lock_acquire "$donor_lock_name" 0 "donor session clone" 1 || donor_lease_rc=$?
    if (( donor_lease_rc != 0 )); then
        fmix_donor_restore_interrupt_traps \
            "$saved_trap_int" "$saved_trap_term" "$saved_trap_hup" \
            || donor_restore_rc=$?
        if (( donor_install_interrupted != 0 )); then
            donor_signal_after_restore=1
        fi
        if (( donor_restore_rc != 0 )); then return 70; fi
        fmix_lock_failure_is_fatal "$donor_lease_rc" && return 70
        if (( donor_signal_after_restore != 0 )); then
            donor_lease_rc="$donor_install_interrupt_rc"
        fi
        fmix_warn "Could not acquire exclusive donor session lease for $donor."
        return "$donor_lease_rc"
    fi
    donor_lease_held=1
    if (( donor_install_interrupted != 0 )); then
        _fmix_donor_abort_staging \
            "$donor_lock_name" "" "$donor_install_interrupt_rc" "$donor_lease_held"
        return $?
    fi

    # Atomic metadata replacement does not release this path-derived canonical
    # session lease. Re-read identity, paths, key, and existing stamps while held.
    fmix_donor_session_revalidate \
        "$donor" "$real" "$template_key" "$donor_session_hash" || revalidate_rc=$?
    if (( donor_install_interrupted != 0 )); then
        revalidate_rc="$donor_install_interrupt_rc"
    fi
    if (( revalidate_rc != 0 )); then
        if (( donor_install_interrupted == 0 )); then
            fmix_warn "Donor session $donor failed identity or artifact revalidation."
        fi
        _fmix_donor_abort_staging \
            "$donor_lock_name" "" "$revalidate_rc" "$donor_lease_held"
        return $?
    fi

    stage="$(mktemp -d "$target_session_root/.donor-install.XXXXXX")" || stage_rc=$?
    if (( donor_install_interrupted != 0 )); then
        stage_rc="$donor_install_interrupt_rc"
    fi
    if (( stage_rc != 0 )); then
        _fmix_donor_abort_staging \
            "$donor_lock_name" "$stage" "$stage_rc" "$donor_lease_held"
        return $?
    fi
    stage_new="$stage/new"
    stage_old="$stage/old"
    mkdir -p "$stage_new" "$stage_old" || stage_rc=$?
    if (( donor_install_interrupted != 0 )); then
        stage_rc="$donor_install_interrupt_rc"
    fi
    if (( stage_rc == 0 )); then
        fmix_cow_clone "$donor/deps" "$stage_new/deps" || stage_rc=$?
        if (( donor_install_interrupted != 0 )); then
            stage_rc="$donor_install_interrupt_rc"
        fi
    fi
    if (( stage_rc == 0 )); then
        fmix_cow_clone "$donor/_build" "$stage_new/_build" || stage_rc=$?
        if (( donor_install_interrupted != 0 )); then
            stage_rc="$donor_install_interrupt_rc"
        fi
    fi
    if (( stage_rc == 0 )); then
        fmix_donor_make_stage_writable \
            "$stage_new/deps" "$stage_new/_build" || stage_rc=$?
        if (( donor_install_interrupted != 0 )); then
            stage_rc="$donor_install_interrupt_rc"
        fi
    fi
    if (( stage_rc == 0 )); then
        fmix_donor_copy_stamps "$donor" "$stage_new" || stage_rc=$?
        if (( donor_install_interrupted != 0 )); then
            stage_rc="$donor_install_interrupt_rc"
        fi
    fi
    if (( stage_rc == 0 )); then
        fmix_donor_rebind_staged_stamps \
            "$stage_new" "$real" "$build_root" "$py_bin" || stage_rc=$?
        if (( donor_install_interrupted != 0 )); then
            stage_rc="$donor_install_interrupt_rc"
        fi
    fi
    if (( stage_rc == 0 )); then
        find "$stage_new/_build" -type f -name 'compile.*' -exec touch {} + \
            2>/dev/null || stage_rc=$?
        if (( donor_install_interrupted != 0 )); then
            stage_rc="$donor_install_interrupt_rc"
        fi
        if (( stage_rc == 0 )); then
            find "$stage_new/deps" -type f -name 'CMakeCache.txt' -delete \
                2>/dev/null || stage_rc=$?
        fi
        if (( donor_install_interrupted != 0 )); then
            stage_rc="$donor_install_interrupt_rc"
        fi
        if (( stage_rc == 0 )); then
            find "$stage_new/deps" -type d -name 'c_build' -exec rm -rf {} + \
                2>/dev/null || stage_rc=$?
        fi
        if (( donor_install_interrupted != 0 )); then
            stage_rc="$donor_install_interrupt_rc"
        fi
        if (( stage_rc == 0 )); then
            find "$stage_new/deps" -type d -name 'CMakeFiles' -exec rm -rf {} + \
                2>/dev/null || stage_rc=$?
        fi
        if (( donor_install_interrupted != 0 )); then
            stage_rc="$donor_install_interrupt_rc"
        fi
    fi
    if (( stage_rc != 0 )); then
        _fmix_donor_abort_staging \
            "$donor_lock_name" "$stage" "$stage_rc" "$donor_lease_held"
        return $?
    fi
    # No donor bytes or stamps are read after this point; release the source
    # session lease before publishing the target's artifact-state marker.
    if ! fmix_donor_session_lease_release "$donor_lock_name" 0; then
        donor_lease_held=0
        donor_restore_rc=0
        fmix_donor_restore_interrupt_traps \
            "$saved_trap_int" "$saved_trap_term" "$saved_trap_hup" \
            || donor_restore_rc=$?
        if (( donor_install_interrupted != 0 )); then
            donor_lease_rc="$donor_install_interrupt_rc"
        fi
        (( donor_restore_rc == 0 )) || return 70
        return 70
    fi
    donor_lease_held=0
    if (( donor_install_interrupted != 0 )); then
        _fmix_donor_abort_staging \
            "$donor_lock_name" "$stage" "$donor_install_interrupt_rc" "$donor_lease_held"
        return $?
    fi

    stage_rc=0
    fmix_donor_stage_artifact_state \
        "$stage_new" "$worktree" "$template_key" || stage_rc=$?
    if (( donor_install_interrupted != 0 )); then
        stage_rc="$donor_install_interrupt_rc"
    fi
    if (( stage_rc != 0 )); then
        _fmix_donor_abort_staging \
            "$donor_lock_name" "$stage" "$stage_rc" "$donor_lease_held"
        return $?
    fi

    local -a donor_item_names=(deps _build dependency-stamp.json compile-stamp.json artifact-state.json)
    local -a donor_item_targets=("$deps_root" "$build_root" "$dependency_stamp" "$compile_stamp" "$artifact_state")
    local -a donor_item_backed=()
    local -a donor_item_installed=()
    for (( index = 0; index < ${#donor_item_names[@]}; index++ )); do
        donor_item_backed[$index]=0
        donor_item_installed[$index]=0
    done

    # Stage every donor byte and provenance file before moving any active path.
    # Keep old state beside the transaction until artifact-state is installed last.
    for (( index = 0; index < ${#donor_item_names[@]}; index++ )); do
        if (( donor_install_interrupted != 0 )); then
            transaction_rc="$donor_install_interrupt_rc"
            break
        fi
        item_name="${donor_item_names[$index]}"
        item_target="${donor_item_targets[$index]}"
        if [[ -e "$item_target" || -L "$item_target" ]]; then
            move_rc=0
            fmix_donor_transaction_move \
                "$item_target" "$stage_old/$item_name" "backup:$item_name" \
                || move_rc=$?
            if [[ ! -e "$item_target" && ! -L "$item_target" \
                && ( -e "$stage_old/$item_name" || -L "$stage_old/$item_name" ) ]]; then
                donor_item_backed[$index]=1
            fi
            if (( move_rc != 0 || donor_item_backed[$index] == 0 )); then
                transaction_rc="$move_rc"
                (( transaction_rc != 0 )) || transaction_rc=1
                break
            fi
        fi
    done
    if (( donor_install_interrupted != 0 )); then
        transaction_rc="$donor_install_interrupt_rc"
    fi
    if (( transaction_rc == 0 )); then
        for (( index = 0; index < ${#donor_item_names[@]}; index++ )); do
            if (( donor_install_interrupted != 0 )); then
                transaction_rc="$donor_install_interrupt_rc"
                break
            fi
            item_name="${donor_item_names[$index]}"
            item_source="$stage_new/$item_name"
            item_target="${donor_item_targets[$index]}"
            if [[ ! -e "$item_source" && ! -L "$item_source" ]]; then
                [[ "$item_name" == "dependency-stamp.json" ]] && continue
                transaction_rc=1
                break
            fi
            move_rc=0
            fmix_donor_transaction_move \
                "$item_source" "$item_target" "install:$item_name" \
                || move_rc=$?
            if [[ ! -e "$item_source" && ! -L "$item_source" \
                && ( -e "$item_target" || -L "$item_target" ) ]]; then
                donor_item_installed[$index]=1
            fi
            if (( move_rc != 0 || donor_item_installed[$index] == 0 )); then
                transaction_rc="$move_rc"
                (( transaction_rc != 0 )) || transaction_rc=1
                break
            fi
            if (( donor_install_interrupted != 0 )); then
                transaction_rc="$donor_install_interrupt_rc"
                break
            fi
        done
    fi
    if (( donor_install_interrupted != 0 )); then
        transaction_rc="$donor_install_interrupt_rc"
    fi

    if (( transaction_rc == 0 && donor_install_interrupted != 0 )); then
        transaction_rc="$donor_install_interrupt_rc"
    fi
    if (( transaction_rc != 0 )); then
        for (( index = ${#donor_item_names[@]} - 1; index >= 0; index-- )); do
            if (( donor_item_installed[$index] == 1 )); then
                item_name="${donor_item_names[$index]}"
                item_source="${donor_item_targets[$index]}"
                item_target="$stage_new/$item_name"
                if [[ ( -e "$item_source" || -L "$item_source" ) \
                    && ! -e "$item_target" && ! -L "$item_target" ]]; then
                    move_rc=0
                    fmix_donor_transaction_move \
                        "$item_source" "$item_target" "rollback-new:$item_name" \
                        || move_rc=$?
                    if [[ -e "$item_source" || -L "$item_source" \
                        || ! -e "$item_target" && ! -L "$item_target" ]]; then
                        rollback_failed=1
                    fi
                else
                    rollback_failed=1
                fi
            fi
        done
        for (( index = ${#donor_item_names[@]} - 1; index >= 0; index-- )); do
            if (( donor_item_backed[$index] == 1 )); then
                item_name="${donor_item_names[$index]}"
                item_source="$stage_old/$item_name"
                item_target="${donor_item_targets[$index]}"
                if [[ ( -e "$item_source" || -L "$item_source" ) \
                    && ! -e "$item_target" && ! -L "$item_target" ]]; then
                    move_rc=0
                    fmix_donor_transaction_move \
                        "$item_source" "$item_target" "rollback-old:$item_name" \
                        || move_rc=$?
                    if [[ -e "$item_source" || -L "$item_source" \
                        || ! -e "$item_target" && ! -L "$item_target" ]]; then
                        rollback_failed=1
                    fi
                else
                    rollback_failed=1
                fi
            fi
        done
        if (( donor_install_interrupted != 0 )); then
            transaction_rc="$donor_install_interrupt_rc"
        fi
        if (( rollback_failed != 0 )); then
            fmix_error "Donor clone rollback incomplete; preserving recovery inputs: $stage"
            donor_restore_rc=0
            fmix_donor_restore_interrupt_traps \
                "$saved_trap_int" "$saved_trap_term" "$saved_trap_hup" \
                || donor_restore_rc=$?
            if (( donor_install_interrupted != 0 )); then
                transaction_rc="$donor_install_interrupt_rc"
            fi
            (( donor_restore_rc == 0 )) || return 70
            return 2
        fi
        stage_cleanup_rc=0
        fmix_donor_transaction_stage_cleanup "$stage" || stage_cleanup_rc=$?
        if (( donor_install_interrupted != 0 )); then
            transaction_rc="$donor_install_interrupt_rc"
        fi
        if (( stage_cleanup_rc != 0 )); then
            fmix_error "Could not clean rolled-back donor staging: $stage"
        fi
        donor_restore_rc=0
        fmix_donor_restore_interrupt_traps \
            "$saved_trap_int" "$saved_trap_term" "$saved_trap_hup" \
            || donor_restore_rc=$?
        if (( donor_install_interrupted != 0 )); then
            transaction_rc="$donor_install_interrupt_rc"
        fi
        (( donor_restore_rc == 0 )) || return 70
        if (( stage_cleanup_rc != 0 )); then
            return 70
        fi
        return "$transaction_rc"
    fi

    # The source lease has been released after copy and stamp rebinding. Old
    # target state remains in the transaction until final staging cleanup.
    stage_cleanup_rc=0
    fmix_donor_transaction_stage_cleanup "$stage" || stage_cleanup_rc=$?
    if (( stage_cleanup_rc != 0 )); then
        fmix_error "Donor clone committed but old transaction data remains: $stage"
    fi
    donor_restore_rc=0
    fmix_donor_restore_interrupt_traps \
        "$saved_trap_int" "$saved_trap_term" "$saved_trap_hup" \
        || donor_restore_rc=$?
    if (( donor_install_interrupted != 0 )); then
        transaction_rc="$donor_install_interrupt_rc"
    fi
    (( donor_restore_rc == 0 )) || return 70
    if (( stage_cleanup_rc != 0 )); then
        return 70
    fi
    if (( donor_install_interrupted != 0 )); then
        return "$donor_install_interrupt_rc"
    fi

    fmix_session_relink_app_priv "$build_root" \
        || fmix_warn "Could not relink the application priv to this checkout: $build_root/test/lib/cdrcisco/priv"
    fmix_check_known_nif_caches "$worktree" 2>/dev/null || true
    fmix_info "Warm donor cloned into session."
    return 0
}

# ---------------------------------------------------------------------------
# Clone immutable template into the active session overlay
# ---------------------------------------------------------------------------

fmix_clone_template_to_worktree() {
    local key="${2:-}"
    (( $# == 2 )) || return 1
    [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
    fmix_with_artifact_lease "build-$key" _fmix_clone_template_to_worktree_locked "$@"
}

_fmix_template_install_interrupt() {
    template_install_interrupted=1
    template_install_rc="${1:-130}"
}

_fmix_clone_template_to_worktree_locked() {
    local worktree="$1" key="$2" tdir deps_root build_root stage stamp
    local dependency_fingerprint staged_manifest had_deps=0 had_build=0 had_stamp=0
    local installed_deps=0 installed_build=0 switch_failed=0 rollback_failed=0
    local attempted_deps=0 attempted_build=0 stamp_attempted=0
    local template_install_interrupted=0 template_install_rc=1
    local saved_trap_int saved_trap_term saved_trap_hup
    tdir="$(fmix_template_dir "$key")"
    deps_root="$(fmix_session_deps_root "$worktree")" || return 1
    build_root="$(fmix_compile_build_root "$worktree")" || return 1

    [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]] || {
        fmix_error "Refusing template clone without an active FMix session."
        return 1
    }
    [[ "$deps_root" == "$FMIX_ACTIVE_SESSION_ROOT/deps" \
        && "$build_root" == "$FMIX_ACTIVE_SESSION_ROOT/_build" ]] || {
        fmix_error "Session artifact paths escaped the active session root."
        return 1
    }
    [[ ! -L "$deps_root" && ! -L "$build_root" ]] || return 1
    fmix_template_verify_full "$key" || {
        fmix_error "Refusing to clone unverified template $key."
        return 1
    }

    fmix_info "Cloning immutable template into session overlay …"
    stage="$(mktemp -d "$FMIX_ACTIVE_SESSION_ROOT/.template-install.XXXXXX")" || return 1
    stamp="$(fmix_dependency_stamp_file "$worktree")"
    saved_trap_int="$(trap -p INT)"
    saved_trap_term="$(trap -p TERM)"
    saved_trap_hup="$(trap -p HUP)"
    trap '_fmix_template_install_interrupt 130' INT
    trap '_fmix_template_install_interrupt 143' TERM
    trap '_fmix_template_install_interrupt 129' HUP
    # Copy and prove staging before retiring the existing mutable overlay.
    if ! mkdir "$stage/new" \
        || ! fmix_cow_clone "$tdir/deps" "$stage/new/deps" \
        || ! fmix_cow_clone "$tdir/_build" "$stage/new/_build" \
        || ! chmod -R u+w "$stage/new/deps" "$stage/new/_build"; then
        switch_failed=1
    fi
    if (( switch_failed == 0 && template_install_interrupted == 0 )); then
        staged_manifest="$(fmix_template_write_manifest "$stage/new")" || switch_failed=1
        [[ "$staged_manifest" == "$(fmix_read_template_meta "$key" manifest_sha256)" ]] || switch_failed=1
    fi
    dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
        || switch_failed=1
    if (( switch_failed == 0 && template_install_interrupted == 0 )); then
        if [[ -e "$deps_root" ]]; then
            if mv "$deps_root" "$stage/old-deps"; then had_deps=1; else switch_failed=1; fi
        fi
        if (( switch_failed == 0 )) && [[ -e "$build_root" ]]; then
            if mv "$build_root" "$stage/old-build"; then had_build=1; else switch_failed=1; fi
        fi
        if (( switch_failed == 0 )) && [[ -e "$stamp" || -L "$stamp" ]]; then
            if [[ -f "$stamp" && ! -L "$stamp" ]] && mv "$stamp" "$stage/old-stamp"; then
                had_stamp=1
            else
                switch_failed=1
            fi
        fi
        if (( switch_failed == 0 && template_install_interrupted == 0 )); then
            attempted_deps=1
            if mv "$stage/new/deps" "$deps_root"; then installed_deps=1; else switch_failed=1; fi
        fi
        if (( switch_failed == 0 && template_install_interrupted == 0 )); then
            attempted_build=1
            if mv "$stage/new/_build" "$build_root"; then installed_build=1; else switch_failed=1; fi
        fi
        if (( switch_failed == 0 && template_install_interrupted == 0 )); then
            stamp_attempted=1
            fmix_write_dependency_stamp "$worktree" "$dependency_fingerprint" || switch_failed=1
            if (( switch_failed == 0 && template_install_interrupted == 0 )); then
                fmix_update_template_last_used "$key" || switch_failed=1
            fi
        fi
    fi
    if (( switch_failed != 0 || template_install_interrupted != 0 )); then
        # A rename may have completed before an interrupted child reports its
        # status. Reconcile the actual owned staging paths, not only flags.
        [[ ! -e "$stage/old-deps" && ! -L "$stage/old-deps" ]] || had_deps=1
        [[ ! -e "$stage/old-build" && ! -L "$stage/old-build" ]] || had_build=1
        [[ ! -e "$stage/old-stamp" && ! -L "$stage/old-stamp" ]] || had_stamp=1
        if (( attempted_deps != 0 )) && [[ ! -e "$stage/new/deps" && ! -L "$stage/new/deps" \
            && ( -e "$deps_root" || -L "$deps_root" ) ]]; then installed_deps=1; fi
        if (( attempted_build != 0 )) && [[ ! -e "$stage/new/_build" && ! -L "$stage/new/_build" \
            && ( -e "$build_root" || -L "$build_root" ) ]]; then installed_build=1; fi
        (( installed_deps == 0 )) || rm -rf "$deps_root" || rollback_failed=1
        (( installed_build == 0 )) || rm -rf "$build_root" || rollback_failed=1
        if (( had_deps != 0 )); then
            if [[ ! -e "$deps_root" && ! -L "$deps_root" ]]; then
                mv "$stage/old-deps" "$deps_root" || rollback_failed=1
            else rollback_failed=1; fi
        fi
        if (( had_build != 0 )); then
            if [[ ! -e "$build_root" && ! -L "$build_root" ]]; then
                mv "$stage/old-build" "$build_root" || rollback_failed=1
            else rollback_failed=1; fi
        fi
        if (( stamp_attempted != 0 || had_stamp != 0 )); then
            rm -f "$stamp" || rollback_failed=1
        fi
        if (( had_stamp != 0 )); then
            if [[ ! -e "$stamp" && ! -L "$stamp" ]]; then
                mv "$stage/old-stamp" "$stamp" || rollback_failed=1
            else rollback_failed=1; fi
        fi
    fi
    trap - INT TERM HUP
    [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
    [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
    [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
    if (( rollback_failed != 0 )); then
        fmix_error "Template replacement rollback incomplete; preserving recovery inputs: $stage"
        return 2
    fi
    rm -rf "$stage" || fmix_warn "Owned template staging remains: $stage"
    if (( switch_failed != 0 || template_install_interrupted != 0 )); then
        return "$template_install_rc"
    fi
    # Preserve warm compilation manifests only after transactional replacement.
    find "$build_root" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true
    fmix_info "Template cloned into session; dependency provenance established."
    return 0
}

# ---------------------------------------------------------------------------
# Ensure session artifacts (deps/ + _build/) are ready and template-matched
# ---------------------------------------------------------------------------

# REL-1244: is the application itself compiled into this session overlay?
#
# A matching template key proves deps and toolchain agree; it does NOT prove the
# app was compiled. An overlay from a compile that was killed by
# FMIX_COMPILE_TIMEOUT still has deps/ and _build/ and cdrcisco.app, but no .beam
# files and no .mix/compile.elixir. Accepting that as a session hit makes every
# later `mix compile` rebuild the whole DAG from nothing.
#
# Extracted as a function so a compatibility test can call the SHIPPED logic
# rather than replaying a copy of it.
fmix_session_has_app_manifest() {
    local worktree="$1" build_root="$2"
    local app_name="cdrcisco" found_app=""
    if [[ -f "$worktree/mix.exs" ]]; then
        found_app="$(grep -o 'app:[[:space:]]*:[a-zA-Z0-9_]*' "$worktree/mix.exs" 2>/dev/null | head -1 | sed 's/.*:\([a-zA-Z0-9_]*\)/\1/')"
        [[ -n "$found_app" ]] && app_name="$found_app"
    fi
    # fmix_compile_build_root returns the session's _build directory, while Mix
    # writes the app manifest under its MIX_ENV subdirectory (_build/test/lib).
    # Looking only at "$build_root/lib" never found it in a real session, so every
    # same-key session read as an interrupted overlay and was "repaired" from a
    # template that may not exist (API-3576: after the template key started to
    # include migrations that is the common case). Accept either layout.
    local layout
    for layout in "$build_root/lib" "$build_root/test/lib"; do
        [[ -f "$layout/$app_name/.mix/compile.elixir" ]] && return 0
        [[ -f "$layout/$app_name/.mix/compile.elixir_scm" ]] && return 0
    done
    return 1
}

_fmix_ensure_artifacts_impl() {
    FMIX_LAST_ARTIFACTS_COMPILE_FAILURE=0
    local worktree="$1" template_key="$2" allow_template_build="${3:-0}"
    local state_file artifact_state_file reconcile_rc donor_rc
    state_file="$(fmix_worktree_state_file "$worktree")"
    artifact_state_file="$(fmix_artifact_state_file "$worktree")"

    local recorded_key=""
    if [[ -f "$artifact_state_file" ]]; then
        recorded_key="$(fmix_read_state "$artifact_state_file" "template_key")"
    elif [[ -f "$state_file" ]]; then
        # One-time compatibility with FMix v1's combined DB/artifact state.
        recorded_key="$(fmix_read_state "$state_file" "template_key")"
    fi

    local deps_root build_root
    deps_root="$(fmix_session_deps_root "$worktree")" || return 1
    build_root="$(fmix_compile_build_root "$worktree")" || return 1
    local has_deps=0 has_build=0
    [[ -d "$deps_root" ]] && has_deps=1
    [[ -d "$build_root" ]] && has_build=1

    # REL-1244: a matching template key is NOT proof that this session was ever
    # compiled. The key is derived from mix.lock plus the toolchain, so two
    # worktrees sharing a lockfile share a key -- and a session that inherited an
    # interrupted overlay still matches it.
    #
    # has_deps/has_build only tested that the DIRECTORIES exist. In the failure this
    # guards, the session had deps/ and _build/ present and cdrcisco.app present,
    # but ZERO .beam files and no .mix/compile.elixir for the app, because a prior
    # compile was killed by FMIX_COMPILE_TIMEOUT before it wrote a manifest. FMix
    # reported session_hit and returned success, so every subsequent `mix compile`
    # rebuilt the whole DAG from nothing (measured: 5252 files, 513s) and the
    # pre-push hook -- which runs that compile -- blew its own budget and reported
    # a compile failure that was really an unrecoverable cold rebuild.
    #
    # The clone path below touches every compile.* manifest after copying, and that
    # touch is precisely what makes a cloned session incremental. The early-return
    # path skipped that repair. Require the app compile manifest to be present
    # before accepting a session hit; otherwise fall through so the template is
    # re-cloned and the manifests are synchronized.
    #
    # Scoped deliberately to the SAME-KEY fast path. The other branches have their
    # own proofs (exact stamps, or fmix_adopt_compatible_worktree_artifacts) and a
    # key change must still be able to adopt a compatible overlay; gating the whole
    # block on the manifest broke "template storage-key changes adopt current
    # worktree stamps without cloning".
    local has_app_manifest=0
    if fmix_session_has_app_manifest "$worktree" "$build_root"; then
        has_app_manifest=1
    fi

    if (( has_deps == 1 && has_build == 1 )); then
        if [[ -z "$recorded_key" ]]; then
            if [[ "$allow_template_build" != "1" ]]; then
                fmix_error "Existing session deps/_build have no FMix provenance; refusing to adopt them."
                fmix_error "Repair explicitly with: fmix setup --worktree $worktree"
                return 1
            fi
            local dependency_fingerprint compile_fingerprint
            dependency_fingerprint="$(
                fmix_compute_dependency_fingerprint "$worktree" 2>/dev/null
            )" || dependency_fingerprint=""
            compile_fingerprint="$(
                fmix_compute_compile_fingerprint "$worktree" 2>/dev/null
            )" || compile_fingerprint=""
            if fmix_template_is_complete "$template_key" \
                && [[ -n "$dependency_fingerprint" && -n "$compile_fingerprint" ]] \
                && fmix_dependency_stamp_matches \
                    "$worktree" "$dependency_fingerprint" \
                && fmix_compile_stamp_matches "$worktree" "$compile_fingerprint"; then
                fmix_write_artifact_state "$worktree" "$template_key" || return 1
                fmix_info "Exact stamps adopted the existing session overlay; skipping clone."
                FMIX_LAST_ARTIFACTS_OUTCOME="adopt_stamps"
                return 0
            fi
            fmix_info "Session artifact state is absent; exact stamps must prove it before publication."
        elif [[ "$recorded_key" == "$template_key" ]]; then
            if (( has_app_manifest == 0 )); then
                fmix_warn "Session artifacts match template key $template_key but the app compile manifest is missing (interrupted or partial overlay); repairing from the template."
            else
                [[ -f "$artifact_state_file" ]] \
                    || fmix_write_artifact_state "$worktree" "$template_key" \
                    || return 1
                fmix_info "Session artifacts match template key $template_key — skipping clone."
                FMIX_LAST_ARTIFACTS_OUTCOME="session_hit"
                return 0
            fi
        else
            fmix_info "Template key mismatch (recorded=$recorded_key, current=$template_key)."
            fmix_lock_mutate_gate \
                "artifact adoption under template key $template_key" || return $?
            if fmix_adopt_compatible_worktree_artifacts \
                "$worktree" "$recorded_key" "$template_key"; then
                fmix_write_artifact_state "$worktree" "$template_key" || return 1
                fmix_info "Compatible worktree artifacts adopted under template key $template_key — no clone, deps.get, or compile."
                FMIX_LAST_ARTIFACTS_OUTCOME="adopt_compatible"
                return 0
            fi
            if (( has_app_manifest == 1 )) \
                && fmix_adopt_migration_only_key_change \
                    "$worktree" "$recorded_key" "$template_key"; then
                fmix_write_artifact_state "$worktree" "$template_key" || return 1
                fmix_info "Only the migrations digest changed under template key $template_key — keeping the session build for incremental compile."
                FMIX_LAST_ARTIFACTS_OUTCOME="adopt_migration_delta"
                return 0
            fi
            if fmix_reconcile_same_toolchain_dependency_change \
                "$worktree" "$recorded_key" "$template_key"; then
                fmix_info "Dependency change adopted under template key $template_key — preserving the app cache for incremental compile."
                FMIX_LAST_ARTIFACTS_OUTCOME="dependency_reconcile"
                return 0
            else
                reconcile_rc=$?
                case "$reconcile_rc" in 2|129|130|143) return "$reconcile_rc" ;; esac
                [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$reconcile_rc"
                fmix_lock_failure_is_fatal "$reconcile_rc" && return 70
            fi
            fmix_info "Artifact compatibility proof failed; a verified template clone is required."
        fi
    fi

    # Need to clone from template. A normal test lane may use an existing cache
    # but must never launch a cold dependency/app build.
    if ! fmix_template_is_complete "$template_key" && [[ "$allow_template_build" != "1" ]]; then
        if [[ "${FMIX_AUTO_SETUP:-0}" == "1" ]]; then
            FMIX_LAST_ARTIFACTS_OUTCOME="missing_template"
            return 1
        fi
        fmix_error "Artifact template $template_key is missing."
        fmix_error "Refusing a cold dependency/app build in a test lane."
        fmix_error "Build it explicitly with: ./fmix setup --worktree $worktree"
        fmix_error "DO NOT push untested code to remote CI; run 'fmix setup --worktree $worktree' locally (takes ~30s)."
        FMIX_LAST_ARTIFACTS_OUTCOME="missing_template"
        return 1
    fi
    # Everything past this point mutates shared artifact state (donor fetch,
    # template build, or clone). A shared hold must escalate first.
    fmix_lock_mutate_gate "artifact clone, donor fetch, or template build" || return $?
    # Prefer a warm peer session for the same worktree+template over a cold
    # template clone (avoids ~4700-file recompile when isolate/new session).
    # A contended donor can be skipped, but the retry window is deliberately
    # small so donor discovery never becomes an unbounded session scan/clone.
    local donor="" donor_attempt donor_seen tried_donor
    local donor_attempt_limit=3 donor_attempted=0
    local -a attempted_donors=()
    for (( donor_attempt = 0; donor_attempt < donor_attempt_limit; donor_attempt++ )); do
        donor=""
        if ! donor="$(fmix_find_warm_donor_session \
            "$worktree" "$template_key" ${attempted_donors[@]+"${attempted_donors[@]}"})"; then
            break
        fi
        [[ -n "$donor" ]] || break
        donor_seen=0
        for tried_donor in ${attempted_donors[@]+"${attempted_donors[@]}"}; do
            if [[ "$tried_donor" == "$donor" ]]; then
                donor_seen=1
                break
            fi
        done
        # Be defensive against older wrappers or test doubles that do not
        # implement optional exclusions: never try the same donor twice.
        (( donor_seen == 0 )) || break
        attempted_donors+=("$donor")
        donor_attempted=$(( donor_attempted + 1 ))

        if fmix_clone_donor_to_session "$worktree" "$donor" "$template_key"; then
            FMIX_LAST_ARTIFACTS_OUTCOME="donor_clone"
            return 0
        else
            donor_rc=$?
            case "$donor_rc" in 2|129|130|143) return "$donor_rc" ;; esac
            [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$donor_rc"
            fmix_lock_failure_is_fatal "$donor_rc" && return 70
        fi
        # Only an ordinary donor miss permits fallback. A keeper bootstrap or
        # retirement failure must not admit artifacts or attempt another donor
        # while recovery is pending.
        (( donor_rc == 1 )) || return "$donor_rc"
        fmix_warn "Warm donor clone failed; trying another eligible donor if available."
    done
    if (( donor_attempted > 0 )); then
        fmix_warn "Warm donor attempts exhausted or unavailable; falling back to immutable template."
    fi

    FMIX_TEMPLATE_BUILT_FROM_ACTIVE_SESSION=0
    fmix_ensure_template "$worktree" "$template_key" || return $?
    if [[ "${FMIX_TEMPLATE_PUBLICATION_HELD_KEY:-}" == "$template_key" ]]; then
        fmix_write_artifact_state "$worktree" "$template_key" || return 1
        FMIX_LAST_ARTIFACTS_OUTCOME="session_only_disk_pressure"
        return 0
    fi
    if [[ "${FMIX_TEMPLATE_BUILT_FROM_ACTIVE_SESSION:-0}" == "1" ]]; then
        fmix_write_artifact_state "$worktree" "$template_key" || return 1
        fmix_info "Active session produced template $template_key; keeping its proven writable overlay."
        FMIX_LAST_ARTIFACTS_OUTCOME="produced_template"
        return 0
    fi
    fmix_clone_template_to_worktree "$worktree" "$template_key" || return $?
    fmix_write_artifact_state "$worktree" "$template_key" || return 1
    FMIX_LAST_ARTIFACTS_OUTCOME="template_clone"
    return 0
}

fmix_auto_expire_artifacts() {
    # Shared (read) holds never mutate the shared artifact-retirement indexes.
    # Exclusive runs and explicit `fmix gc` cover this housekeeping.
    fmix_lock_any_shared_held && return 0
    [[ "${FMIX_ARTIFACT_AUTO_EXPIRE:-1}" == "1" ]] || return 0
    case "${cmd:-${FMIX_INTERNAL_RUN_MODE:-}}" in
        test|coverage|setup|task|format) ;;
        *) return 0 ;;
    esac
    cmd_gc_artifact_retirement --artifacts-only --auto-expire >/dev/null 2>&1 || true
    return 0
}

fmix_run_probe_readonly() {
    # Pre-lock proof that the whole run is provably read-only w.r.t. shared
    # state (conditions a+b+c of the session-lock shared mode; condition d is
    # the caller's run-mode gate). STRICTLY read-only: any miss, ambiguity, or
    # probe error returns nonzero so the caller takes the exclusive lock.
    #   (a) fmix_ensure_artifacts resolves warm: session_hit (recorded template
    #       key + app manifest) or adopt_stamps (exact dependency/compile
    #       stamps) — no clone, no template build, no donor fetch.
    #   (b) compile is a stamp quick-hit (no deps.get, no mix compile).
    #   (c) the scratch DB exists and is migration-current via an unexpired
    #       schema-ready stamp (no CREATE/DROP, no migrate, no partitions).
    local worktree="$1" template_key="$2" db_name="$3"
    [[ -n "$FMIX_ACTIVE_SESSION_HASH" && -n "$FMIX_ACTIVE_SESSION_ROOT" ]]         || return 1
    [[ "$template_key" =~ ^[0-9a-f]{16}$ ]] || return 1

    # (a) artifacts warm without mutation.
    local state_file artifact_state_file recorded_key="" deps_root build_root
    state_file="$(fmix_worktree_state_file "$worktree")" || return 1
    artifact_state_file="$(fmix_artifact_state_file "$worktree")" || return 1
    if [[ -f "$artifact_state_file" ]]; then
        recorded_key="$(fmix_read_state "$artifact_state_file" "template_key")"
    elif [[ -f "$state_file" ]]; then
        recorded_key="$(fmix_read_state "$state_file" "template_key")"
    fi
    deps_root="$(fmix_session_deps_root "$worktree")" || return 1
    build_root="$(fmix_compile_build_root "$worktree")" || return 1
    [[ -d "$deps_root" && -d "$build_root" ]] || return 1
    if [[ -n "$recorded_key" ]]; then
        # session_hit: exact recorded key + intact overlay.
        [[ "$recorded_key" == "$template_key" ]] || return 1
        fmix_session_has_app_manifest "$worktree" "$build_root" || return 1
    else
        # adopt_stamps: only exact stamps may prove an unrecorded overlay.
        fmix_template_is_complete "$template_key" || return 1
        local dependency_fingerprint compile_fingerprint
        dependency_fingerprint="$(
            fmix_compute_dependency_fingerprint "$worktree" 2>/dev/null
        )" || return 1
        compile_fingerprint="$(
            fmix_compute_compile_fingerprint "$worktree" 2>/dev/null
        )" || return 1
        [[ -n "$dependency_fingerprint" && -n "$compile_fingerprint" ]] || return 1
        fmix_dependency_stamp_matches "$worktree" "$dependency_fingerprint" || return 1
        fmix_compile_stamp_matches "$worktree" "$compile_fingerprint" || return 1
    fi

    # (b) compile is a stamp quick-hit (read-only admission).
    fmix_try_compile_stamp_quick_hit "$worktree" || return 1

    # (c) scratch DB exists and is migration-current (no CREATE/DROP).
    fmix_db_exists "$db_name" || return 1
    fmix_schema_ready_stamp_warm_ro "$worktree" "$db_name" || return 1
    fmix_validate_db_integrity "$db_name" || return 1
    return 0
}

fmix_activation_probe_readonly() {
    # Warm session activation is provably read-only: the session root, its
    # metadata record, and the priv bridge already exist and are correct.
    # Anything missing requires creation (an exclusive mutation).
    local session_root="$1" real="$2"
    [[ -n "$session_root" && -d "$session_root" && ! -L "$session_root" ]] || return 1
    [[ -f "$session_root/meta.json" && ! -L "$session_root/meta.json" ]] || return 1
    [[ -L "$session_root/priv" ]] || return 1
    [[ "$(readlink "$session_root/priv" 2>/dev/null)" == "$real/priv" ]] || return 1
    return 0
}

fmix_publish_run_worktree_state() {
    # Shared-hold state publication contract (condition d): a run may publish
    # only provenance it just verified read-only. Identical provenance is a
    # timestamp-only refresh and stays under the shared hold; a publication
    # that would CREATE or CHANGE recorded provenance escalates to exclusive
    # first and then writes under the new hold.
    local worktree="$1" template_key="$2" db_name="$3" mig_stamp="$4"
    local schema_key="${5:-}" base_id="${6:-}" source_key="${7:-}"
    local state_file
    if fmix_lock_any_shared_held; then
        state_file="$(fmix_worktree_state_file "$worktree")" || return 1
        if [[ ! -f "$state_file" ]]             || [[ "$(fmix_read_state "$state_file" template_key)" != "$template_key" ]]             || [[ "$(fmix_read_state "$state_file" db_name)" != "$db_name" ]]             || [[ "$(fmix_read_state "$state_file" last_migration_stamp)" != "$mig_stamp" ]]             || [[ "$(fmix_read_state "$state_file" db_schema_key)" != "$schema_key" ]]             || [[ "$(fmix_read_state "$state_file" db_base_id)" != "$base_id" ]]             || [[ "$(fmix_read_state "$state_file" db_source_schema_key)" != "$source_key" ]]; then
            fmix_lock_escalate_exclusive "worktree state provenance publication"                 || return 70
        fi
    fi
    fmix_write_worktree_state "$worktree" "$template_key" "$db_name" "$mig_stamp"         "$(fmix_now)" "$schema_key" "$base_id" "$source_key"
}

fmix_ensure_artifacts() {
    local rc=0
    _fmix_ensure_artifacts_impl "$@" || rc=$?
    if (( rc == 200 )) && [[ "${FMIX_LOCK_GATE_RETRY:-}" == "1" ]]; then
        # A mutation gate escalated a shared hold mid-decision. Re-verify the
        # warm conditions once under the new exclusive hold: they may have
        # changed while the lease was upgraded, and only then mutate.
        FMIX_LOCK_GATE_RETRY=""
        rc=0
        _fmix_ensure_artifacts_impl "$@" || rc=$?
    fi
    (( rc == 0 )) || return "$rc"
    fmix_auto_expire_artifacts
}

# ---------------------------------------------------------------------------
# DB management


fmix_db_name_for_worktree() {
    local worktree="$1"
    if [[ "$FMIX_ACTIVE_SESSION_HASH" =~ ^[0-9a-f]{16}$ ]]; then
        printf 'ct_fmix_s_%s\n' "$FMIX_ACTIVE_SESSION_HASH"
        return 0
    fi
    local wid
    wid="$(fmix_worktree_id "$worktree")"
    printf 'ct_fmix_%s\n' "$wid"
}

fmix_validate_database_name() {
    local database_name="$1"
    if [[ ! "$database_name" =~ ^[A-Za-z][A-Za-z0-9_]{0,62}$ ]]; then
        fmix_error "Invalid named database '$database_name'; expected an identifier beginning with a letter and containing only letters, digits, or underscores."
        return 1
    fi
}

fmix_validate_mix_env() {
    local mix_env="$1"
    if [[ ! "$mix_env" =~ ^[a-z][a-z0-9_]{0,31}$ ]]; then
        fmix_error "Invalid Mix environment '$mix_env'; expected a lowercase identifier."
        return 1
    fi
}

fmix_db_exists() {
    local dbname="$1"
    # Name reaches a SQL literal — refuse anything outside the shapes fmix
    # ever legitimately probes (codex P1).
    if [[ ! "$dbname" =~ ^ct_fmix_(s_|tmpl_|snap_)?[0-9a-f]{8,40}$ ]]; then
        fmix_error "SAFETY: refusing to query unexpected database name '$dbname'."
        return 1
    fi
    local result
    result="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -t -c "SELECT 1 FROM pg_database WHERE datname='${dbname}'" 2>/dev/null | tr -d ' ')"
    [[ "$result" == "1" ]]
}

fmix_drop_error_is_active_sessions() {
    # PostgreSQL reports a refused drop in two places: the primary error
    # ("database ... is being accessed by other users") and its DETAIL line
    # ("There are N other sessions using the database"). Match either, and
    # lowercase first so the check does not depend on message casing.
    local message="$1" lowered
    lowered="$(printf '%s' "$message" | tr '[:upper:]' '[:lower:]')"
    [[ "$lowered" == *"is being accessed by other users"* \
        || "$lowered" == *"other sessions using the database"* ]]
}

fmix_drop_db() {
    local db_name="$1" force_active="${2:-0}"
    fmix_guard_db_name "$db_name" || return 1
    local timeout timeout_ms out rc ddl_lock=""
    if fmix_host_test_lock_enabled; then
        ddl_lock="$(fmix_host_test_lock_name)"
        fmix_lock_acquire "$ddl_lock" "$FMIX_HOST_LOCK_TIMEOUT" || return $?
    fi
    timeout="$(fmix_positive_uint_or_default "$FMIX_DB_DROP_TIMEOUT" 30 FMIX_DB_DROP_TIMEOUT)"
    timeout_ms=$(( timeout * 1000 ))
    # A snapshot template (ct_fmix_snap_*) is marked IS_TEMPLATE and cannot be
    # dropped until that flag is cleared. No-op/ignored for ordinary scratch DBs.
    PGCONNECT_TIMEOUT=5 PGOPTIONS="${PGOPTIONS:-} -c statement_timeout=${timeout_ms} -c lock_timeout=${timeout_ms}" \
        fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -c "ALTER DATABASE \"${db_name}\" IS_TEMPLATE false" >/dev/null 2>&1 || true
    local drop_sql="DROP DATABASE IF EXISTS \"${db_name}\""
    out="$(PGCONNECT_TIMEOUT=5 PGOPTIONS="${PGOPTIONS:-} -c statement_timeout=${timeout_ms} -c lock_timeout=${timeout_ms}" \
        fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -v ON_ERROR_STOP=1 -c "$drop_sql" 2>&1)"
    rc=$?
    # A scratch DB can outlive the session that owns it while a leaked
    # connection pool still holds idle backends. PostgreSQL then refuses the
    # DROP ("database ... is being accessed by other users") and the database
    # leaks forever — observed as two orphaned scratch DBs holding 142 idle
    # backends. Only callers that have proven this name is an orphan/expired
    # under this FMIX_HOME pass force_active=1, and they get one bounded FORCE
    # retry. PG13+ has WITH (FORCE); older servers get one explicit
    # backend-termination pass first. Callers without that proof keep the plain
    # drop so a live pool is never terminated by surprise.
    if (( rc != 0 )) && [[ "$force_active" == "1" ]] && fmix_drop_error_is_active_sessions "$out"; then
        local server_version
        server_version="$(fmix_server_version_num)"
        if [[ "$server_version" =~ ^[0-9]+$ ]] && (( server_version >= 130000 )); then
            out="$(PGCONNECT_TIMEOUT=5 PGOPTIONS="${PGOPTIONS:-} -c statement_timeout=${timeout_ms} -c lock_timeout=${timeout_ms}" \
                fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
                -v ON_ERROR_STOP=1 -c "${drop_sql} WITH (FORCE)" 2>&1)"
            rc=$?
        else
            fmix_control_psql "$timeout" -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
                -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${db_name}' AND pid <> pg_backend_pid()" \
                >/dev/null 2>&1 || true
            out="$(PGCONNECT_TIMEOUT=5 PGOPTIONS="${PGOPTIONS:-} -c statement_timeout=${timeout_ms} -c lock_timeout=${timeout_ms}" \
                fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
                -v ON_ERROR_STOP=1 -c "$drop_sql" 2>&1)"
            rc=$?
        fi
    fi
    if (( rc != 0 )); then
        printf '%s\n' "$out" | tail -8 >&2
        fmix_error "DROP DATABASE $db_name failed or exceeded ${timeout}s."
        if [[ -n "$ddl_lock" ]]; then
            fmix_command_lock_finish "$ddl_lock" 1
            return $?
        fi
        return 1
    fi
    if [[ -n "$ddl_lock" ]]; then
        fmix_command_lock_finish "$ddl_lock" 0 || return $?
    fi
    return 0
}

fmix_server_version_num() {
    fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -tAc "SHOW server_version_num" 2>/dev/null | tr -d '[:space:]'
}

fmix_db_create_pressure_details() {
    local min_age
    min_age="$(fmix_uint_or_default "$FMIX_DB_PRESSURE_MIN_AGE" 10 FMIX_DB_PRESSURE_MIN_AGE)"
    fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -Atc "
SELECT concat(
  'pid=', pid,
  ' db=', coalesce(datname, '-'),
  ' type=', coalesce(backend_type, '-'),
  ' wait=', coalesce(wait_event, '-'),
  ' age=', floor(extract(epoch FROM clock_timestamp() - coalesce(query_start, backend_start)))::bigint, 's',
  ' query=', left(regexp_replace(coalesce(query, ''), E'[\\n\\r]+', ' ', 'g'), 100)
)
FROM pg_stat_activity
WHERE pid <> pg_backend_pid()
  AND (
        (state = 'active' AND wait_event IN ('DataFileSync', 'DataFileImmediateSync', 'CheckpointDone'))
     OR (backend_type IN ('checkpointer', 'background writer', 'walwriter') AND wait_event_type = 'IO')
      )
  AND coalesce(query_start, backend_start) IS NOT NULL
  AND clock_timestamp() - coalesce(query_start, backend_start) >= make_interval(secs => ${min_age})
ORDER BY coalesce(query_start, backend_start);" 2>/dev/null
}

fmix_wait_for_db_create_admission() {
    local purpose="$1"
    if [[ "$FMIX_DB_CREATE_ADMISSION" == "0" ]]; then
        fmix_warn "Database-create admission disabled for $purpose (FMIX_DB_CREATE_ADMISSION=0)."
        return 0
    fi

    local timeout deadline details="" inspect_rc=0 announced=0 consecutive_positive=0
    timeout="$(fmix_uint_or_default "$FMIX_DB_ADMISSION_TIMEOUT" 20 FMIX_DB_ADMISSION_TIMEOUT)"
    deadline=$(( $(fmix_epoch) + timeout ))

    while true; do
        details="$(fmix_db_create_pressure_details)"
        inspect_rc=$?
        if (( inspect_rc != 0 )); then
            fmix_error "Database-create admission could not inspect pg_stat_activity for $purpose."
            fmix_error "Refusing CREATE DATABASE because pressure state is unknown."
            return 1
        fi
        if [[ -n "$details" ]]; then
            consecutive_positive=$(( consecutive_positive + 1 ))
            if (( consecutive_positive >= 3 )); then
                if (( announced == 0 )); then
                    fmix_warn "Database-create admission waiting up to ${timeout}s for checkpoint/WAL/fsync pressure to clear ($purpose)."
                    printf '%s\n' "$details" | sed 's/^/    /' >&2
                    announced=1
                fi
                if (( $(fmix_epoch) >= deadline )); then
                    fmix_error "Database-create admission denied for $purpose after ${timeout}s."
                    fmix_error "Postgres is already stalled on checkpoint/WAL/fsync waits; refusing to add CREATE DATABASE pressure."
                    printf '%s\n' "$details" | sed 's/^/    /' >&2
                    fmix_error "Retry after pressure clears. Override only deliberately with FMIX_DB_CREATE_ADMISSION=0."
                    return 1
                fi
            fi
        else
            if (( consecutive_positive > 0 )); then
                consecutive_positive=0
            fi
            if (( announced == 1 )); then
                fmix_info "Database-create admission recovered for $purpose."
            fi
            return 0
        fi
        if (( $(fmix_epoch) >= deadline )); then
            if (( consecutive_positive == 0 )); then
                # Debounce only suppresses pressure that actually CLEARED. If the
                # latest sample still shows pressure we must fail closed: with a
                # short or zero timeout the 3-sample debounce can never be
                # satisfied, which previously admitted sustained WAL/checkpoint
                # pressure on the very first sample.
                return 0
            fi
            fmix_error "Database-create admission denied for $purpose after ${timeout}s."
            return 1
        fi
        sleep 2
    done
}

fmix_create_database() {
    # All fmix CREATE DATABASE operations pass through one admission and timeout
    # boundary. PostgreSQL 14's file-copy implementation forces checkpoints;
    # PostgreSQL 15+ supports WAL_LOG, which avoids those forced checkpoints.
    local db_name="$1" template_name="${2:-}" source_kind="${3:-published}" ddl_lock=""
    fmix_guard_db_name "$db_name" || return 1
    if [[ -n "$template_name" ]]; then
        case "$source_kind" in
            published) fmix_guard_template_db_name "$template_name" || return 1 ;;
            scratch-publish) fmix_guard_publish_source_db_name "$template_name" || return 1 ;;
            *)
                fmix_error "SAFETY: unknown CREATE DATABASE source kind '$source_kind'."
                return 1
                ;;
        esac
    fi
    if fmix_host_test_lock_enabled; then
        ddl_lock="$(fmix_host_test_lock_name)"
        fmix_lock_acquire "$ddl_lock" "$FMIX_HOST_LOCK_TIMEOUT" || return $?
    fi
    fmix_wait_for_db_create_admission "CREATE DATABASE $db_name" || {
        if [[ -n "$ddl_lock" ]]; then
            fmix_command_lock_finish "$ddl_lock" 1
            return $?
        fi
        return 1
    }

    local version strategy="" timeout timeout_ms sql out rc
    version="$(fmix_server_version_num)"
    if [[ ! "$version" =~ ^[0-9]+$ ]]; then
        fmix_error "Could not determine PostgreSQL server version; refusing CREATE DATABASE."
        if [[ -n "$ddl_lock" ]]; then
            fmix_command_lock_finish "$ddl_lock" 1
            return $?
        fi
        return 1
    fi
    (( version >= 150000 )) && strategy=" STRATEGY = WAL_LOG"
    timeout="$(fmix_positive_uint_or_default "$FMIX_DB_CREATE_TIMEOUT" 60 FMIX_DB_CREATE_TIMEOUT)"
    timeout_ms=$(( timeout * 1000 ))

    sql="CREATE DATABASE \"${db_name}\""
    [[ -n "$template_name" ]] && sql+=" TEMPLATE \"${template_name}\""
    sql+="${strategy}"

    out="$(PGCONNECT_TIMEOUT=5 PGOPTIONS="${PGOPTIONS:-} -c statement_timeout=${timeout_ms} -c lock_timeout=${timeout_ms}" \
        fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -v ON_ERROR_STOP=1 -c "$sql" 2>&1)"
    rc=$?
    if (( rc != 0 )); then
        printf '%s\n' "$out" | tail -8 >&2
        fmix_error "CREATE DATABASE $db_name failed or exceeded ${timeout}s."
        if [[ -n "$ddl_lock" ]]; then
            fmix_command_lock_finish "$ddl_lock" 1
            return $?
        fi
        return 1
    fi
    if [[ -n "$ddl_lock" ]]; then
        fmix_command_lock_finish "$ddl_lock" 0 || return $?
    fi
    return 0
}

fmix_snapshot_db_name() {
    # Reusable snapshot template DB name, keyed by structure.sql CONTENT so it
    # auto-rebuilds when the dump changes and old snapshots become orphans (gc).
    local worktree="$1"
    local structure="$worktree/priv/repo/structure.sql"
    [[ -f "$structure" ]] || return 1
    local h
    h="$(fmix_hash_files "$structure" 2>/dev/null | awk '{print $1}')"
    [[ -n "$h" ]] || return 1
    printf 'ct_fmix_snap_%s\n' "${h:0:16}"
}

fmix_structure_recorded_versions() {
    # Extract the schema_migrations versions structure.sql attests to, straight
    # from its committed INSERT statements — the same source of truth
    # test/cdrcisco/release/structure_load_baseline_test.exs parses. This is a
    # content read, not a git-history inference.
    local structure_file="$1" output="$2"
    grep -oE 'INSERT INTO public\."schema_migrations" \(version\) VALUES \([0-9]{14}\)' \
        "$structure_file" \
        | grep -oE '[0-9]{14}' \
        | LC_ALL=C sort -u >"$output"
    [[ -s "$output" ]]
}

fmix_versions_are_migration_prefix() {
    # Ordered-prefix predicate used by fmix_migration_ledger_is_prefix to
    # decide whether an already-published DB template can be reused
    # incrementally for this branch (every applied version present on disk
    # AND the exact leading prefix of the ordered on-disk migration
    # versions). NOT used for the structure.sql cold-bootstrap gate — see
    # fmix_versions_are_migration_subset and the comment in
    # fmix_structure_matches_migration_history for why that's a different,
    # weaker-but-correct question (SET membership, not ordering).
    local versions_file="$1" files_file="$2"
    local normalized expected count
    normalized="$(mktemp)" || return 1
    expected="$(mktemp)" || { rm -f "$normalized"; return 1; }

    while IFS= read -r version; do
        if fmix_migration_version_is_known_orphan "$version" && ! grep -qx "$version" "$files_file"; then
            continue
        fi
        printf '%s\n' "$version" >>"$normalized"
    done <"$versions_file"

    if [[ ! -s "$normalized" ]]; then
        rm -f "$normalized" "$expected"
        return 1
    fi

    count="$(wc -l <"$normalized" | tr -d ' ')"
    head -n "$count" "$files_file" >"$expected"
    if [[ "$(wc -l <"$expected" | tr -d ' ')" != "$count" ]] || ! cmp -s "$normalized" "$expected"; then
        rm -f "$normalized" "$expected"
        return 1
    fi
    rm -f "$normalized" "$expected"
    return 0
}

fmix_versions_are_migration_subset() {
    # Every recorded version must either exist on disk or be a known orphan.
    # Unlike fmix_versions_are_migration_prefix, this does NOT require the
    # recorded set to be the ordered leading prefix of on-disk files — see
    # fmix_structure_matches_migration_history for why that ordering
    # requirement is wrong for this specific caller.
    local versions_file="$1" files_file="$2" unmatched
    unmatched="$(mktemp)" || return 1
    while IFS= read -r version; do
        grep -qx "$version" "$files_file" && continue
        fmix_migration_version_is_known_orphan "$version" && continue
        printf '%s\n' "$version" >>"$unmatched"
    done <"$versions_file"
    local rc=1
    [[ -s "$unmatched" ]] || rc=0
    rm -f "$unmatched"
    return "$rc"
}

fmix_structure_matches_migration_history() {
    # Cold-bootstrap provenance gate. Originally this required structure.sql's
    # commit to be an ancestor of HEAD with zero migration-content diff since —
    # i.e. "no migration file changed after structure.sql was last touched".
    # That is STRICTER than the load path's actual contract: the hot-clone path
    # never inspects structure.sql's commit history at all — its cache key is a
    # content-hash manifest of migration files (fmix_schema_key), and cold
    # bootstrap only needs to prove `Ecto.Migrator` can safely apply the delta
    # after `Cdrcisco.Release.StructureLoad` loads structure.sql.
    #
    # `Ecto.Migrator` treats `schema_migrations` as a SET (`migrated_versions/1`
    # is a membership query), not an ordered log — it applies every on-disk
    # file whose version isn't already recorded, regardless of numeric
    # position. Verified against this repo's real 0.8.7-stable structure.sql:
    # its recorded baseline is NOT the ordered prefix of on-disk migration
    # versions — 21 delta versions interleave with, rather than trail, the
    # recorded range (e.g. 20260703220000 is on disk but unrecorded, while
    # 20260722183000 — numerically later — IS recorded). That's a real,
    # harmless artifact of migrations landing slightly out of commit order,
    # not drift. A strict ordered-prefix requirement (the predicate
    # `fmix_migration_ledger_is_prefix` applies post-clone against an
    # already-*published* base, where it legitimately matters — see below)
    # would fail-closed on this real, healthy branch state and reproduce
    # today's outage under a different name.
    #
    # So this gate checks the actual correctness invariant instead: every
    # recorded version (minus known orphans) has a real on-disk file
    # (fmix_versions_are_migration_subset) — exactly the SET invariant
    # test/cdrcisco/release/structure_load_baseline_test.exs enforces
    # (bounded delta + known-orphan set), which is the authoritative,
    # CI-verified contract for this exact load path. The normal post-load
    # `ecto.migrate` + zero-pending-migration assertion still runs — this
    # gate is a fast pre-check, not the last line of defense.
    #
    # fmix_migration_ledger_is_prefix (governing reuse of an already-
    # published, already-migrated DB template) asks the same underlying
    # question and now uses the same set-based predicate
    # (fmix_versions_are_migration_subset) for the same reason: the cold
    # path clones this exact structure.sql snapshot, so its ledger is
    # exactly the recorded set above — interleaved on real branches, not
    # ordered — and an ordered-prefix check there would reject every
    # cold-bootstrapped hot-base on this branch. See that function's own
    # comment for the residual "ahead"/unknown-version protection it still
    # provides, and the FMIX_LEDGER_GATE=strict escape hatch that restores
    # the old ordered-prefix behavior.
    #
    # API-2846: the set check above is BLIND to a migration file whose
    # VERSION is unchanged but whose BODY was edited after being baked into
    # structure.sql — a real risk this repo's forward-only-repair pattern
    # makes concrete (an already-applied migration's data-repair logic can be
    # revised in place). A prior relaxation (#1066) dropped detection of this
    # case entirely as an "accepted residual risk" while fixing the much more
    # common false-positive (ordinary appended migrations). This function now
    # closes that gap with a narrower, content-based check
    # (fmix_structure_recorded_migrations_changed) that compares each
    # recorded version's on-disk blob against its blob at the commit that
    # last touched structure.sql — catching the same-version body-edit case
    # without resurrecting the old ordered-ancestry check's false positive on
    # ordinary appended migrations.
    local worktree="$1" structure_rel="priv/repo/structure.sql"
    local migrations_rel="priv/repo/migrations" untracked
    git -C "$worktree" rev-parse --is-inside-work-tree >/dev/null 2>&1 || return 1
    [[ -f "$worktree/$structure_rel" && -d "$worktree/$migrations_rel" ]] || return 1

    if ! git -C "$worktree" diff --quiet -- "$structure_rel" "$migrations_rel" \
        || ! git -C "$worktree" diff --cached --quiet -- "$structure_rel" "$migrations_rel"; then
        fmix_error "Cold DB bootstrap requires committed structure.sql and migration inputs."
        return 1
    fi
    untracked="$(git -C "$worktree" ls-files --others --exclude-standard -- "$migrations_rel")"
    if [[ -n "$untracked" ]]; then
        fmix_error "Cold DB bootstrap refuses untracked migration files."
        return 1
    fi

    local recorded files
    recorded="$(mktemp)" || return 1
    files="$(mktemp)" || { rm -f "$recorded"; return 1; }

    if ! fmix_structure_recorded_versions "$worktree/$structure_rel" "$recorded"; then
        rm -f "$recorded" "$files"
        fmix_error "structure.sql has no parseable schema_migrations rows."
        return 1
    fi
    if ! fmix_write_migration_versions "$worktree" "$files"; then
        rm -f "$recorded" "$files"
        fmix_error "Could not enumerate on-disk migration versions."
        return 1
    fi

    if ! fmix_versions_are_migration_subset "$recorded" "$files"; then
        rm -f "$recorded" "$files"
        fmix_error "structure.sql records a schema_migrations version with no on-disk migration" \
            "file and no known-orphan allowlist entry (drift)."
        fmix_error "Regenerate and commit structure.sql before explicit cold DB bootstrap."
        return 1
    fi

    local changed
    changed="$(mktemp)" || { rm -f "$recorded" "$files"; return 1; }
    if ! fmix_structure_recorded_migrations_changed "$worktree" "$recorded" "$structure_rel" "$changed"; then
        fmix_error "structure.sql recorded migration(s) whose file body changed after the snapshot was taken:"
        while IFS= read -r changed_path; do
            [[ -n "$changed_path" ]] && fmix_error "  $changed_path"
        done <"$changed"
        fmix_error "Regenerate and commit structure.sql before explicit cold DB bootstrap, or use migrate-from-zero."
        rm -f "$recorded" "$files" "$changed"
        return 1
    fi
    rm -f "$recorded" "$files" "$changed"
    return 0
}

fmix_structure_recorded_migrations_changed() {
    # API-2846: detects a migration file RECORDED in structure.sql's
    # schema_migrations snapshot whose BODY was edited (same version, same
    # path, different content) since the commit that produced structure.sql.
    # fmix_versions_are_migration_subset is a pure SET-membership check by
    # version and cannot see this — it is exactly the gap fmix_structure_
    # matches_migration_history's docstring documents. Ordinary appended
    # migrations (versions structure.sql never recorded) never reach this
    # function's comparison at all, so it does not resurrect the old
    # ordered-ancestry false positive on the ordinary, constant case of new
    # migrations landing after structure.sql was last regenerated.
    #
    # Writes every changed relative path (one per line) to $output for the
    # caller's error message. Returns 0 (nothing changed) or 1 (drift found).
    local worktree="$1" recorded="$2" structure_rel="$3" output="$4"
    : >"$output" || return 1

    local structure_commit
    structure_commit="$(git -C "$worktree" log -1 --format=%H -- "$structure_rel" 2>/dev/null)"
    # No resolvable commit for structure.sql (e.g. it is untracked) — there is
    # no snapshot commit to diff migration bodies against. The subset check
    # above is the only signal available in that case; do not fail-closed on
    # a check we cannot actually perform.
    [[ -n "$structure_commit" ]] || return 0

    local mig_dir="$worktree/priv/repo/migrations"
    local version file relative head_blob snap_blob
    while IFS= read -r version; do
        [[ "$version" =~ ^[0-9]{14}$ ]] || continue
        file="$(find "$mig_dir" -maxdepth 1 -type f -name "${version}_*.exs" -print -quit 2>/dev/null)"
        # No on-disk file for this recorded version: either the known orphan
        # or a real gap — fmix_versions_are_migration_subset already vetted
        # (or will veto) that; nothing to content-compare here.
        [[ -n "$file" ]] || continue
        relative="${file#"$worktree"/}"
        head_blob="$(git hash-object "$file" 2>/dev/null)"
        [[ -n "$head_blob" ]] || continue
        snap_blob="$(git -C "$worktree" rev-parse "${structure_commit}:${relative}" 2>/dev/null)"
        # Path did not exist at the snapshot commit (e.g. renamed since) —
        # not the same-version body-edit risk this check targets; leave it to
        # the subset/orphan checks.
        [[ -n "$snap_blob" ]] || continue
        if [[ "$head_blob" != "$snap_blob" ]]; then
            printf '%s\n' "$relative" >>"$output"
        fi
    done <"$recorded"
    [[ ! -s "$output" ]]
}

fmix_write_schema_manifest() {
    # Content-address every migration by version. The resulting sorted file is
    # the schema compatibility contract; structure.sql and wall-clock dates are
    # deliberately excluded from the hot path.
    local worktree="$1" output="$2" mig_dir
    mig_dir="$worktree/priv/repo/migrations"
    [[ -d "$mig_dir" ]] || return 1
    local tmp pairs paths hashes
    tmp="$(mktemp)" || return 1
    pairs="$(mktemp)" || { rm -f "$tmp"; return 1; }
    paths="$(mktemp)" || { rm -f "$tmp" "$pairs"; return 1; }
    hashes="$(mktemp)" || { rm -f "$tmp" "$pairs" "$paths"; return 1; }
    find "$mig_dir" -maxdepth 1 -type f -name '*.exs' -print \
        | while IFS= read -r file; do
            local name version relative
            name="${file##*/}"
            version="${name:0:14}"
            [[ "$version" =~ ^[0-9]{14}$ ]] || continue
            relative="${file#"$worktree"/}"
            printf '%s\t%s\n' "$version" "$relative"
        done | LC_ALL=C sort -u >"$pairs"
    cut -f2 "$pairs" >"$paths"
    (cd "$worktree" && git hash-object --stdin-paths <"$paths") >"$hashes" 2>/dev/null || {
        rm -f "$tmp" "$pairs" "$paths" "$hashes"
        return 1
    }
    paste <(cut -f1 "$pairs") "$hashes" >"$tmp"
    rm -f "$pairs" "$paths" "$hashes"
    if [[ ! -s "$tmp" ]] || grep -qEv '^[0-9]{14}[[:space:]][0-9a-f]{40,64}$' "$tmp"; then
        rm -f "$tmp"
        return 1
    fi
    mv "$tmp" "$output" || { rm -f "$tmp"; return 1; }
}

fmix_schema_key_from_manifest() {
    local manifest="$1" version major digest
    [[ -s "$manifest" ]] || return 1
    version="$(fmix_server_version_num)"
    [[ "$version" =~ ^[0-9]+$ ]] || return 1
    major=$(( version / 10000 ))
    digest="$({
        printf 'fmix-db-schema-epoch=%s\n' "$FMIX_DB_SCHEMA_EPOCH"
        printf 'postgres-major=%s\n' "$major"
        printf 'known-orphans=20260416223000\n'
        cat "$manifest"
    } | fmix_hash_stdin)"
    [[ -n "$digest" ]] || return 1
    printf '%s\n' "${digest:0:16}"
}

fmix_schema_key() {
    local worktree="$1" manifest key
    manifest="$(mktemp)" || return 1
    fmix_write_schema_manifest "$worktree" "$manifest" || { rm -f "$manifest"; return 1; }
    key="$(fmix_schema_key_from_manifest "$manifest")" || { rm -f "$manifest"; return 1; }
    rm -f "$manifest"
    printf '%s\n' "$key"
}

fmix_hot_base_name() {
    local key="$1"
    [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
    printf 'ct_fmix_tmpl_%s\n' "$key"
}

fmix_db_index_dir() {
    printf '%s/db-index/%s\n' "$FMIX_HOME" "$1"
}

fmix_read_db_index_field() {
    local key="$1" field="$2" meta
    meta="$(fmix_db_index_dir "$key")/meta.json"
    [[ -f "$meta" ]] || return 1
    grep -o "\"${field}\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" "$meta" 2>/dev/null \
        | head -1 | sed 's/.*: *"\(.*\)".*/\1/'
}

fmix_base_record_ready() {
    local key="$1" dir base status stored_key orphan manifest_sha actual_sha actual_key
    [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
    dir="$(fmix_db_index_dir "$key")"
    [[ -s "$dir/manifest.tsv" && -s "$dir/meta.json" ]] || return 1
    status="$(fmix_read_db_index_field "$key" status)"
    stored_key="$(fmix_read_db_index_field "$key" schema_key)"
    base="$(fmix_read_db_index_field "$key" base_id)"
    orphan="$(fmix_read_db_index_field "$key" known_orphans)"
    manifest_sha="$(fmix_read_db_index_field "$key" manifest_sha256)"
    [[ "$status" == "published" && "$stored_key" == "$key" ]] || return 1
    [[ "$orphan" == "20260416223000" ]] || return 1
    fmix_guard_template_db_name "$base" >/dev/null 2>&1 || return 1
    fmix_snapshot_ready "$base" || return 1
    actual_sha="$(fmix_hash_files "$dir/manifest.tsv" 2>/dev/null | awk '{print $1}')"
    [[ -n "$actual_sha" && "$actual_sha" == "$manifest_sha" ]] || return 1
    actual_key="$(fmix_schema_key_from_manifest "$dir/manifest.tsv")" || return 1
    [[ "$actual_key" == "$key" ]]
}

fmix_manifest_is_prefix() {
    local prefix="$1" full="$2" count expected
    [[ -s "$prefix" && -s "$full" ]] || return 1
    count="$(wc -l <"$prefix" | tr -d ' ')"
    [[ "$count" =~ ^[0-9]+$ ]] || return 1
    expected="$(mktemp)" || return 1
    head -n "$count" "$full" >"$expected"
    if [[ "$(wc -l <"$expected" | tr -d ' ')" == "$count" ]] && cmp -s "$prefix" "$expected"; then
        rm -f "$expected"
        return 0
    fi
    rm -f "$expected"
    return 1
}

fmix_index_manifest_is_prefix() {
    local key="$1" worktree="$2" current dir
    fmix_base_record_ready "$key" || return 1
    dir="$(fmix_db_index_dir "$key")"
    current="$(mktemp)" || return 1
    fmix_write_schema_manifest "$worktree" "$current" || { rm -f "$current"; return 1; }
    fmix_manifest_is_prefix "$dir/manifest.tsv" "$current"
    local rc=$?
    rm -f "$current"
    return "$rc"
}

fmix_select_indexed_base() {
    # Pure metadata selection: zero CREATE DATABASE calls. Echoes
    # "base_id<TAB>schema_key<TAB>delta_count" for the longest content-valid
    # prefix within the ordinary migration budget.
    local worktree="$1" current current_key current_count limit meta dir key count delta
    local best_key="" best_base="" best_count=-1
    current="$(mktemp)" || return 1
    fmix_write_schema_manifest "$worktree" "$current" || { rm -f "$current"; return 1; }
    current_key="$(fmix_schema_key_from_manifest "$current")" || { rm -f "$current"; return 1; }
    current_count="$(wc -l <"$current" | tr -d ' ')"
    limit="$(fmix_positive_uint_or_default "$FMIX_MIGRATION_DELTA_LIMIT" 50 FMIX_MIGRATION_DELTA_LIMIT)"

    if fmix_base_record_ready "$current_key"; then
        best_key="$current_key"
        best_count="$current_count"
    else
        while IFS= read -r meta; do
            [[ -n "$meta" ]] || continue
            dir="$(dirname "$meta")"
            key="$(basename "$dir")"
            fmix_base_record_ready "$key" || continue
            count="$(wc -l <"$dir/manifest.tsv" | tr -d ' ')"
            [[ "$count" =~ ^[0-9]+$ ]] || continue
            (( count <= current_count )) || continue
            delta=$(( current_count - count ))
            (( delta <= limit )) || continue
            fmix_manifest_is_prefix "$dir/manifest.tsv" "$current" || continue
            if (( count > best_count )); then
                best_key="$key"
                best_count="$count"
            fi
        done < <(find "$FMIX_HOME/db-index" -mindepth 2 -maxdepth 2 -name meta.json -type f 2>/dev/null | LC_ALL=C sort)
    fi

    rm -f "$current"
    [[ -n "$best_key" ]] || return 1
    best_base="$(fmix_read_db_index_field "$best_key" base_id)"
    printf '%s\t%s\t%s\n' "$best_base" "$best_key" "$(( current_count - best_count ))"
}

fmix_write_base_record() {
    local worktree="$1" base="$2" key="${3:-}" dir tmp manifest_sha count tip version
    fmix_guard_template_db_name "$base" || return 1
    fmix_snapshot_ready "$base" || return 1
    if [[ ! "$key" =~ ^[0-9a-f]{16}$ ]]; then
        key="$(fmix_schema_key "$worktree")" || return 1
    fi
    dir="$(fmix_db_index_dir "$key")"
    tmp="$FMIX_HOME/db-index/${key}.tmp-$$"
    mkdir -p "$FMIX_HOME/db-index"
    rm -rf "$tmp"
    mkdir -p "$tmp" || return 1
    fmix_write_schema_manifest "$worktree" "$tmp/manifest.tsv" || { rm -rf "$tmp"; return 1; }
    manifest_sha="$(fmix_hash_files "$tmp/manifest.tsv" | awk '{print $1}')"
    count="$(wc -l <"$tmp/manifest.tsv" | tr -d ' ')"
    tip="$(tail -1 "$tmp/manifest.tsv" | cut -f1)"
    version="$(fmix_server_version_num)"
    cat >"$tmp/meta.json" <<EOF
{
  "status": "published",
  "base_id": $(fmix_json_escape "$base"),
  "schema_key": $(fmix_json_escape "$key"),
  "manifest_sha256": $(fmix_json_escape "$manifest_sha"),
  "migration_count": $(fmix_json_escape "$count"),
  "migration_tip": $(fmix_json_escape "$tip"),
  "known_orphans": "20260416223000",
  "postgres_version_num": $(fmix_json_escape "$version"),
  "published_at": $(fmix_json_escape "$(fmix_now)")
}
EOF
    fmix_guard_path "$tmp" || { rm -rf "$tmp"; return 1; }
    if [[ -e "$dir" ]]; then
        fmix_guard_path "$dir" || { rm -rf "$tmp"; return 1; }
        rm -rf "$dir"
    fi
    mv "$tmp" "$dir" || { rm -rf "$tmp"; return 1; }
    printf '%s\n' "$key"
}

fmix_migration_version_is_known_orphan() {
    # cisco-cdr intentionally removed this superuser-only extension migration
    # while retaining its version in structure.sql and maintained templates.
    # Keep this exact allow-list synchronized with
    # test/cdrcisco/release/structure_load_baseline_test.exs. Unknown orphan
    # versions remain hard failures.
    [[ "$1" == "20260416223000" ]]
}

fmix_write_migration_versions() {
    local worktree="$1" output="$2" mig_dir file name version
    mig_dir="$worktree/priv/repo/migrations"
    [[ -d "$mig_dir" ]] || return 1
    : >"$output" || return 1
    while IFS= read -r file; do
        name="${file##*/}"
        version="${name:0:14}"
        [[ "$version" =~ ^[0-9]{14}$ ]] || continue
        printf '%s\n' "$version"
    done < <(find "$mig_dir" -maxdepth 1 -type f -name '*.exs' -print) \
        | LC_ALL=C sort -u >"$output"
    [[ -s "$output" ]]
}

fmix_migration_ledger_is_prefix() {
    # A reusable base is safe when every applied version is present on disk
    # (SET membership — fmix_versions_are_migration_subset), matching the same
    # invariant the cold-bootstrap gate checks (see
    # fmix_structure_matches_migration_history). This still rejects unknown
    # versions (ledger entries with no on-disk file and no known-orphan
    # allowlist entry — "ahead" or drifted ledgers). What it no longer
    # rejects is a *gapped* ledger, i.e. one where on-disk migrations land
    # out of numeric order relative to what's recorded — that's real,
    # harmless drift on this branch (see the cold-bootstrap gate's comment
    # for the concrete example), not a correctness problem: Ecto.Migrator
    # treats schema_migrations as a set, not an ordered log, so a gapped
    # ledger still finishes correctly via the delta migrate. The normal
    # post-clone migration gate (fmix_migration_ledger_is_current) still
    # applies and proves zero pending migrations after the delta — that,
    # plus the upstream content-hash manifest match that gates hot-base
    # *selection* (fmix_select_indexed_base / fmix_manifest_is_prefix), are
    # the real safety nets here, not the ordering of this predicate.
    #
    # FMIX_LEDGER_GATE=strict restores the old ordered-prefix predicate as an
    # escape hatch.
    local worktree="$1" db_name="$2"
    local mig_dir="$worktree/priv/repo/migrations"
    [[ -d "$mig_dir" ]] || return 1

    local files ledger version rc
    files="$(mktemp)" || return 1
    ledger="$(mktemp)" || { rm -f "$files"; return 1; }

    fmix_write_migration_versions "$worktree" "$files" || {
        rm -f "$files" "$ledger"
        return 1
    }
    fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$db_name" \
        -tAc "SELECT version FROM schema_migrations ORDER BY version" \
        2>/dev/null | sed 's/[[:space:]]//g; /^$/d' >"$ledger"

    if [[ ! -s "$files" || ! -s "$ledger" ]] || grep -qEv '^[0-9]{14}$' "$ledger"; then
        rm -f "$files" "$ledger"
        return 1
    fi

    if [[ "${FMIX_LEDGER_GATE:-}" == "strict" ]]; then
        fmix_versions_are_migration_prefix "$ledger" "$files"
    else
        fmix_versions_are_migration_subset "$ledger" "$files"
    fi
    rc=$?
    rm -f "$files" "$ledger"
    return $rc
}

fmix_ensure_snapshot_template() {
    # Build ONE reusable snapshot template DB from priv/repo/structure.sql and
    # reuse it as a CREATE DATABASE ... TEMPLATE source. structure.sql is a dump
    # of a known-good schema + its schema_migrations, so the snapshot is
    # consistent BY CONSTRUCTION — a clone can never have the recorded-but-
    # missing-object inconsistency that corrupted ct_template_test_* clones.
    # A first miss reaches this builder only after the compatible-snapshot path
    # has failed closed. Every later worktree with the exact hash reuses it.
    # Echoes ONLY the snapshot DB name on stdout (loggers go to stderr).
    local worktree="$1" snap
    fmix_structure_matches_migration_history "$worktree" || return 1
    snap="$(fmix_snapshot_db_name "$worktree")" || return 1
    fmix_guard_db_name "$snap" || return 1
    # ONLY trust a snapshot that is fully published — datistemplate=t AND
    # datallowconn=f, which is set as the LAST build step. Mere existence is not
    # enough: CREATE DATABASE succeeds before structure.sql is loaded, so a
    # concurrent consumer (or a crashed prior build) must never clone a half-
    # built snap (codex review).
    if fmix_snapshot_ready "$snap"; then printf '%s\n' "$snap"; return 0; fi

    local lock="snapshot-$snap"
    fmix_lock_acquire "$lock" "$FMIX_LOCK_TIMEOUT" || return $?
    if fmix_snapshot_ready "$snap"; then fmix_command_lock_finish "$lock" 0 || return $?; printf '%s\n' "$snap"; return 0; fi

    # A DB by this name that exists but is NOT ready is a crashed/partial build.
    # Drop it and rebuild from scratch (it would otherwise be trusted forever).
    if fmix_db_exists "$snap"; then
        fmix_warn "Removing incomplete snapshot template $snap (partial snapshot from an interrupted local fmix run) …"
        fmix_warn "This is local $FMIX_HOME/Postgres cache state, not a repo, ct-meta, or upstream skill change."
        fmix_warn "fmix will rebuild the snapshot now; later runs reuse it. Inspect with ./fmix status or clean old state with ./fmix gc --reap --yes."
        fmix_drop_db "$snap" || {
            local drop_rc=$?
            if fmix_lock_failure_is_fatal "$drop_rc"; then
                fmix_command_lock_finish "$lock" "$drop_rc"
                return $?
            fi
        }
    fi

    fmix_info "Building reusable snapshot template $snap from structure.sql (explicit maintenance, hard-capped) …"
    if fmix_create_database "$snap"; then
        :
    else
        local operation_rc=$?
        fmix_error "Failed to create snapshot template $snap."
        fmix_command_lock_finish "$lock" "$operation_rc"
        return $?
    fi
    if ! fmix_load_structure "$worktree" "$snap"; then
        fmix_drop_db "$snap" || {
            local drop_rc=$?
            if fmix_lock_failure_is_fatal "$drop_rc"; then
                fmix_command_lock_finish "$lock" "$drop_rc"
                return $?
            fi
        }
        fmix_command_lock_finish "$lock" 1
        return $?
    fi
    # PUBLISH step: mark immutable template + forbid connections. This exact flag
    # pair is what fmix_snapshot_ready checks, so it must be the final action and
    # a failure here must NOT publish — drop and fail loudly (codex review).
    if ! fmix_control_psql 10 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -c "ALTER DATABASE \"${snap}\" IS_TEMPLATE true ALLOW_CONNECTIONS false" >/dev/null 2>&1; then
        fmix_error "Failed to finalize snapshot template $snap (ALTER IS_TEMPLATE) — not publishing."
        fmix_drop_db "$snap" || {
            local drop_rc=$?
            if fmix_lock_failure_is_fatal "$drop_rc"; then
                fmix_command_lock_finish "$lock" "$drop_rc"
                return $?
            fi
        }
        fmix_command_lock_finish "$lock" 1
        return $?
    fi
    fmix_command_lock_finish "$lock" 0 || return $?
    printf '%s\n' "$snap"
    return 0
}

fmix_snapshot_ready() {
    # A snapshot template is publishable/reusable ONLY when fully built: marked
    # IS_TEMPLATE true AND ALLOW_CONNECTIONS false (the last build step). Returns
    # 0 only for that exact state — a half-built or crashed snap reads otherwise.
    local snap="$1" state
    state="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -tAc "SELECT CASE WHEN datistemplate THEN 't' ELSE 'f' END || '/' || CASE WHEN datallowconn THEN 't' ELSE 'f' END FROM pg_database WHERE datname='${snap}'" \
        2>/dev/null | tr -d ' ')"
    [[ "$state" == "t/f" ]]
}

fmix_validate_db_integrity() {
    # A usable base must be connectable and carry a non-empty migration ledger.
    # Real compatibility is owned by the content manifest and exact post-migrate
    # assertion below.
    #
    # We deliberately do NOT assert that specific objects (e.g. policy-history
    # materialized views) exist: a later migration legitimately DROPS them
    # (20260429130000 DropPolicyHistoryRollupMvsAndLegacyTables), so an
    # object-presence heuristic false-positives on a correctly-migrated DB and
    # forces an endless drop+rebuild+re-migrate loop. The schema_migrations
    # ledger vs. the migration files is the only authoritative signal.
    local db_name="$1"
    fmix_guard_db_name "$db_name" || return 1
    local count
    count="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$db_name" \
        -tAc "SELECT count(*) FROM schema_migrations" 2>/dev/null | tr -d '[:space:]')" || count=""
    if [[ ! "$count" =~ ^[1-9][0-9]*$ ]]; then
        fmix_error "Scratch DB $db_name has no readable migration ledger."
        return 1
    fi
    return 0
}

fmix_publish_hot_base() {
    # setup-only: publish the fully migrated, clean scratch DB as an immutable,
    # content-addressed hot base. Future worktrees select it from metadata and
    # pay exactly one bounded clone, never structure.sql or candidate probes.
    local worktree="$1" db_name="$2" key="${3:-${FMIX_ACTIVE_DB_SCHEMA_KEY:-}}" target lock expected_scratch
    if [[ "${FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP:-0}" != "1" ]]; then
        fmix_error "Refusing hot-base publication: this setup did not create the scratch DB from a trusted bootstrap source."
        return 1
    fi
    expected_scratch="$(fmix_db_name_for_worktree "$worktree")" || return 1
    if [[ "$db_name" != "$expected_scratch" ]]; then
        fmix_error "Refusing hot-base publication from $db_name: expected this worktree's scratch $expected_scratch."
        return 1
    fi
    fmix_guard_publish_source_db_name "$db_name" || return 1
    fmix_migration_ledger_is_current "$worktree" "$db_name" || {
        fmix_error "Refusing to publish $db_name: migration ledger is not current."
        return 1
    }
    fmix_validate_db_integrity "$db_name" || return 1
    if [[ ! "$key" =~ ^[0-9a-f]{16}$ ]]; then
        key="$(fmix_schema_key "$worktree")" || return 1
    fi
    target="$(fmix_hot_base_name "$key")" || return 1
    lock="db-publish-${key}"
    fmix_lock_acquire "$lock" "$FMIX_LOCK_TIMEOUT" || return $?

    if [[ "${FMIX_REPUBLISH_HOT_BASE:-0}" == "1" ]] && fmix_db_exists "$target"; then
        if fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
            # API-3576: an explicit cold rebuild may replace the exact indexed
            # base for this schema key. Never drop or re-index an unvalidated
            # target, even on an explicit rebuild path.
            fmix_warn "Replacing validated published hot base $target with the freshly rebuilt database."
            fmix_drop_db "$target" || {
                local operation_rc=$?
                fmix_command_lock_finish "$lock" "$operation_rc"
                return $?
            }
            if ! rm -rf "$(fmix_db_index_dir "$key")"; then
                fmix_error "Could not remove the old metadata index for $target; refusing to republish."
                fmix_command_lock_finish "$lock" 1
                return $?
            fi
        else
            fmix_error "Hot base $target exists without valid content-addressed metadata. Refusing to overwrite or re-index it."
            fmix_command_lock_finish "$lock" 1
            return $?
        fi
    fi

    if fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
        fmix_command_lock_finish "$lock" 0 || return $?
        printf '%s\n' "$target"
        return 0
    fi

    if fmix_db_exists "$target"; then
        fmix_error "Hot base $target exists without valid content-addressed metadata. Refusing to overwrite or re-index it."
        fmix_command_lock_finish "$lock" 1
        return $?
    fi

    fmix_info "Publishing hot DB base $target from current scratch $db_name …"
    fmix_create_database "$target" "$db_name" scratch-publish || {
        local operation_rc=$?
        fmix_command_lock_finish "$lock" "$operation_rc"
        return $?
    }
    if ! fmix_control_psql 10 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -c "ALTER DATABASE \"${target}\" IS_TEMPLATE true ALLOW_CONNECTIONS false" >/dev/null 2>&1; then
        fmix_error "Failed to finalize hot base $target; removing the unpublished clone."
        fmix_drop_db "$target" || {
            local drop_rc=$?
            if fmix_lock_failure_is_fatal "$drop_rc"; then
                fmix_command_lock_finish "$lock" "$drop_rc"
                return $?
            fi
        }
        fmix_command_lock_finish "$lock" 1
        return $?
    fi
    fmix_write_base_record "$worktree" "$target" "$key" >/dev/null || {
        fmix_error "Hot base $target was created but its metadata index could not be published."
        fmix_command_lock_finish "$lock" 1
        return $?
    }
    fmix_command_lock_finish "$lock" 0 || return $?
    printf '%s\n' "$target"
}

fmix_migrate_from_zero() {
    # API-2846: bootstrap fallback for when structure.sql is unusable for
    # cold bootstrap (missing, or fails fmix_structure_matches_migration_
    # history's freshness/provenance gate) and no usable content-indexed hot
    # base exists, or when an explicit --from-zero/--cold-db rebuild requests a
    # fresh migration path. Runs the FULL migration chain against an EMPTY
    # database via `mix ecto.migrate`, deliberately bypassing
    # FMIX_MIGRATION_DELTA_LIMIT (that cap protects the ordinary hot-clone
    # delta lane; it has no bearing on a from-scratch bootstrap, which is
    # expected to be large by construction).
    #
    # Lock-keyed by the CURRENT schema key (fmix_schema_key) — the exact same
    # keying fmix_publish_hot_base uses for its own publish lock — so
    # concurrent worktrees that land on the same migration set do this once
    # per machine, not once per agent: whichever caller wins the lock builds
    # and this function itself publishes the result as a hot base (reusing
    # fmix_write_base_record/fmix_hot_base_name exactly like
    # fmix_publish_hot_base does); every other caller blocks on the same
    # lock, then finds the hot base already published on the double-check
    # below and clones it instead of repeating the 1000+-migration replay.
    #
    # Fidelity note (API-2846 finding, empirically confirmed against this
    # repo's real 0.8.7-stable migration chain and structure.sql, side by
    # side, on a host with the TimescaleDB extension installed): the
    # structure.sql snapshot path is a `pg_dump`, which — per the CAGG
    # migrations' own comments — cannot portably capture TimescaleDB
    # hypertable/continuous-aggregate objects, even though their migration
    # versions ARE recorded in structure.sql's schema_migrations. A
    # snapshot-derived clone measured zero `timescaledb` extension, zero
    # hypertables, zero continuous aggregates. The SAME codebase migrated
    # from zero via this lane measured the `timescaledb` extension
    # installed, 1 real hypertable, and 7 continuous aggregates (with their
    # 7 backing internal hypertables) — created because this lane runs every
    # committed migration's real body instead of a static dump. Whether that
    # divergence is reachable depends on TimescaleDB extension availability
    # on the fmix host: those migrations are pg_available_extensions-guarded,
    # so on a host WITHOUT the extension both paths converge (both no-op on
    # those objects) — but wherever the extension IS available, this lane is
    # unconditionally MORE faithful than the snapshot path can ever be by
    # construction, not just "no worse".
    #
    # API-3576: the optional third argument "1" (replace) skips both reuse
    # checks and replaces any published base for this key with the freshly
    # migrated result. Explicit --cold-db/--from-zero pass it: reusing a
    # published base is exactly what a rebuild is meant to avoid.
    local worktree="$1" db_name="$2" replace="${3:-0}" key target lock timeout t0 t1
    fmix_guard_db_name "$db_name" || return 1
    key="$(fmix_schema_key "$worktree")" || return 1
    target="$(fmix_hot_base_name "$key")" || return 1

    if [[ "$replace" != "1" ]] && fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
        fmix_info "Hot base $target already published for schema $key — cloning instead of migrating from zero."
        fmix_create_database "$db_name" "$target" || return $?
        FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
        return 0
    fi

    lock="db-migrate-zero-${key}"
    fmix_lock_acquire "$lock" "$FMIX_LOCK_TIMEOUT" || return $?

    # Double-checked: another host process may have published this exact
    # schema's hot base while we waited for the lock.
    if [[ "$replace" != "1" ]] && fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
        fmix_command_lock_finish "$lock" 0 || return $?
        fmix_info "Hot base $target was published while waiting on the lock — cloning."
        fmix_create_database "$db_name" "$target" || return $?
        FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
        return 0
    fi

    if fmix_db_exists "$db_name"; then
        fmix_drop_db "$db_name" || {
            local operation_rc=$?
            fmix_command_lock_finish "$lock" "$operation_rc"
            return $?
        }
    fi
    if fmix_create_database "$db_name"; then
        :
    else
        local operation_rc=$?
        fmix_command_lock_finish "$lock" "$operation_rc"
        return $?
    fi

    timeout="$(fmix_positive_uint_or_default "$FMIX_MIGRATE_FROM_ZERO_TIMEOUT" 1800 FMIX_MIGRATE_FROM_ZERO_TIMEOUT)"
    fmix_warn "Migrating $db_name from an EMPTY database — full chain, hard-capped at ${timeout}s. This is a once-per-machine-per-schema cost; later callers reuse the published hot base."
    t0="$(fmix_epoch)"
    if fmix_run_migration_bounded "$worktree" "$db_name" "$timeout"; then
        :
    else
        local migration_rc=$? drop_rc=0
        FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE=1
        fmix_error "Full from-zero migration failed on $db_name."
        if fmix_lock_failure_is_fatal "$migration_rc"; then
            fmix_command_lock_finish "$lock" "$migration_rc" 1
            return $?
        fi
        fmix_drop_db "$db_name" || drop_rc=$?
        if fmix_lock_failure_is_fatal "$drop_rc"; then
            printf '{"error":"command_lock_cleanup_failed","command_exit_code":%d,"cleanup_exit_code":%d}\n' "$migration_rc" "$drop_rc" >&2
        fi
        fmix_command_lock_finish "$lock" "$migration_rc" 1
        return $?
    fi
    t1="$(fmix_epoch)"
    fmix_info "From-zero migration completed in $(( t1 - t0 ))s."

    if ! fmix_validate_db_integrity "$db_name" || ! fmix_migration_ledger_is_current "$worktree" "$db_name"; then
        fmix_error "From-zero migration finished but the ledger is not exactly current on $db_name."
        fmix_drop_db "$db_name" || {
            local drop_rc=$?
            if fmix_lock_failure_is_fatal "$drop_rc"; then
                fmix_command_lock_finish "$lock" "$drop_rc"
                return $?
            fi
        }
        fmix_command_lock_finish "$lock" 1
        return $?
    fi
    # This process created the empty database and completed the full migration
    # chain. The value is deliberately ephemeral: an existing scratch DB never
    # inherits publication trust from a prior setup, test, or task process.
    FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1

    fmix_info "Publishing hot DB base $target from freshly from-zero-migrated $db_name …"
    if fmix_db_exists "$target"; then
        if fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
            if [[ "$replace" == "1" ]]; then
                fmix_warn "Replacing validated hot base $target with the freshly migrated database."
                fmix_drop_db "$target" || {
                    local operation_rc=$?
                    fmix_command_lock_finish "$lock" "$operation_rc"
                    return $?
                }
                if ! rm -rf "$(fmix_db_index_dir "$key")"; then
                    fmix_error "Could not remove the old metadata index for $target; refusing to republish."
                    fmix_command_lock_finish "$lock" 1
                    return $?
                fi
            else
                fmix_info "The exact clean hot base $target is already published; leaving it unchanged."
                fmix_command_lock_finish "$lock" 0 || return $?
                return 0
            fi
        else
            fmix_error "Hot base $target exists without valid content-addressed metadata. Refusing to overwrite or re-index it."
            fmix_command_lock_finish "$lock" 1
            return $?
        fi
    fi
    if fmix_create_database "$target" "$db_name" scratch-publish; then
        :
    else
        local operation_rc=$?
        fmix_error "Could not publish $target from the from-zero-migrated $db_name; the scratch DB itself remains usable."
        if fmix_lock_failure_is_fatal "$operation_rc"; then
            fmix_command_lock_finish "$lock" "$operation_rc"
            return $?
        fi
        fmix_command_lock_finish "$lock" 0
        return $?
    fi
    if ! fmix_control_psql 10 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -c "ALTER DATABASE \"${target}\" IS_TEMPLATE true ALLOW_CONNECTIONS false" >/dev/null 2>&1; then
        fmix_error "Failed to finalize hot base $target; removing the unpublished clone. The scratch DB itself remains usable."
        fmix_drop_db "$target" || {
            local drop_rc=$?
            if fmix_lock_failure_is_fatal "$drop_rc"; then
                fmix_command_lock_finish "$lock" "$drop_rc"
                return $?
            fi
        }
        fmix_command_lock_finish "$lock" 0
        return $?
    fi
    fmix_write_base_record "$worktree" "$target" "$key" >/dev/null || {
        fmix_error "Hot base $target was created but its metadata index could not be published. The scratch DB itself remains usable."
        fmix_command_lock_finish "$lock" 0
        return $?
    }
    fmix_command_lock_finish "$lock" 0
    return $?
}

fmix_kill_process_tree() {
    local pid="$1" signal="${2:-TERM}" child
    if command -v pgrep >/dev/null 2>&1; then
        while IFS= read -r child; do
            [[ "$child" =~ ^[0-9]+$ ]] || continue
            fmix_kill_process_tree "$child" "$signal"
        done < <(pgrep -P "$pid" 2>/dev/null || true)
    fi
    kill "-$signal" "$pid" 2>/dev/null || true
}

fmix_structure_load_activity() {
    local app_name="$1"
    fmix_control_psql 2 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -tAc "
SELECT concat(
  'pid=', pid,
  ' wait=', coalesce(wait_event_type || '/' || wait_event, 'CPU'),
  ' age=', floor(extract(epoch FROM clock_timestamp() - query_start))::bigint, 's',
  ' sql=', left(regexp_replace(coalesce(query, ''), E'[\\n\\r]+', ' ', 'g'), 140)
)
FROM pg_stat_activity
WHERE application_name = '${app_name}'
  AND state = 'active'
ORDER BY query_start
LIMIT 1;" 2>/dev/null | sed 's/^[[:space:]]*//; s/[[:space:]]*$//'
}

fmix_run_structure_load_once() {
    local db_name="$1" dump="$2" output_file="$3"
    local timeout heartbeat app_name pid started now last_heartbeat activity rc
    timeout="$(fmix_positive_uint_or_default "$FMIX_STRUCTURE_LOAD_TIMEOUT" 120 FMIX_STRUCTURE_LOAD_TIMEOUT)"
    heartbeat="$(fmix_uint_or_default "$FMIX_STRUCTURE_LOAD_HEARTBEAT" 30 FMIX_STRUCTURE_LOAD_HEARTBEAT)"
    app_name="fmix-structure-$$-$(fmix_epoch)"
    started="$(fmix_epoch)"
    last_heartbeat="$started"

    (
        PGAPPNAME="$app_name" fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$db_name" \
            --single-transaction -v ON_ERROR_STOP=1 -q <"$dump"
    ) >"$output_file" 2>&1 &
    pid=$!

    while kill -0 "$pid" 2>/dev/null; do
        now="$(fmix_epoch)"
        if (( now - started >= timeout )); then
            # Capture the backend wait before terminating psql; after the client
            # exits pg_stat_activity normally has no row left to diagnose.
            activity="$(fmix_structure_load_activity "$app_name")"
            fmix_kill_process_tree "$pid"
            sleep 1
            kill -KILL "$pid" 2>/dev/null || true
            wait "$pid" 2>/dev/null || true
            fmix_error "structure.sql load exceeded ${timeout}s; cancelled instead of holding the fmix lane."
            [[ -n "$activity" ]] && fmix_error "$activity"
            return 124
        fi
        if (( heartbeat > 0 && now - last_heartbeat >= heartbeat )); then
            activity="$(fmix_structure_load_activity "$app_name")"
            if [[ -n "$activity" ]]; then
                fmix_info "structure.sql load heartbeat: $activity"
            else
                fmix_info "structure.sql load heartbeat: $(( now - started ))s elapsed (client pid=$pid)."
            fi
            last_heartbeat="$now"
        fi
        sleep 2
    done
    wait "$pid"
    rc=$?
    return "$rc"
}

fmix_load_structure() {
    # Load priv/repo/structure.sql (baked schema + populated schema_migrations)
    # into a freshly-created scratch DB without replaying historical/data
    # migrations. Runs AFTER fmix_ensure_compile, so
    # --no-compile is safe (and stops a redundant compile pass from racing a
    # concurrent one).
    local worktree="$1" db_name="$2"
    local structure="$worktree/priv/repo/structure.sql"
    if [[ ! -f "$structure" ]]; then
        fmix_error "No $structure to load — cannot create a migrated scratch DB without migrating from zero."
        fmix_error "Commit a current priv/repo/structure.sql before explicit --cold-db maintenance."
        return 1
    fi
    fmix_info "Loading baked schema (priv/repo/structure.sql) into $db_name …"
    local dump
    dump="$(mktemp)" || return 1
    # Strip the PG16+ `SET transaction_timeout = …` line that an older psql
    # rejects (verbatim ct-local-dev parity).
    sed '/^SET[[:space:]][[:space:]]*transaction_timeout[[:space:]]*=/d' "$structure" > "$dump"
    # Load via psql --single-transaction (NOT `mix ecto.load`): it is ATOMIC, so
    # a dropped connection — the shared box gets hammered by concurrent agents,
    # and a mid-load drop otherwise leaves a half-built DB — rolls back to empty,
    # letting a retry start clean. ON_ERROR_STOP aborts on the first real SQL
    # error instead of plowing on. It also needs no app boot/compile.
    local rc=1 out="" out_file
    out_file="$(mktemp)" || { rm -f "$dump"; return 1; }
    fmix_run_structure_load_once "$db_name" "$dump" "$out_file"
    rc=$?
    out="$(cat "$out_file")"
    rm -f "$out_file"
    rm -f "$dump"
    if (( rc != 0 )); then
        (( rc == 124 )) && fmix_warn "structure.sql load hit the hard timeout; not retrying the I/O-heavy replay."
        printf '%s\n' "$out" | tail -5
        fmix_error "Loading priv/repo/structure.sql into $db_name failed (rc=$rc)."
        return 1
    fi
    return 0
}

fmix_ensure_db() {
    local rc=0
    _fmix_ensure_db_impl "$@" || rc=$?
    if (( rc == 200 )) && [[ "${FMIX_LOCK_GATE_RETRY:-}" == "1" ]]; then
        # Escalated before a scratch-DB mutation: re-verify existence and
        # provenance once under the new exclusive hold before CREATE/DROP.
        FMIX_LOCK_GATE_RETRY=""
        rc=0
        _fmix_ensure_db_impl "$@" || rc=$?
    fi
    return "$rc"
}

_fmix_ensure_db_impl() {
    # Only this admission's actual bounded cold migration failure is primary
    # across its caller's retirement. Metadata/clone failures are not Mix.
    FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE=0
    local worktree="$1" db_name="$2" rebuild_existing="${3:-0}"
    local allow_structure_build="${4:-0}" allow_legacy_adopt="${5:-0}" force_from_zero="${6:-0}"
    local state_file stored_key stored_source stored_base current_key valid=0 selection base base_key delta expected_scratch
    local t0 t1 snap
    fmix_guard_db_name "$db_name" || return 1
    if [[ "$force_from_zero" == "1" ]]; then
        expected_scratch="$(fmix_db_name_for_worktree "$worktree")" || return 1
        if [[ "$db_name" != "$expected_scratch" ]]; then
            fmix_error "SAFETY: --from-zero may replace only this worktree's scratch DB $expected_scratch."
            return 1
        fi
    fi
    state_file="$(fmix_worktree_state_file "$worktree")"
    current_key="$(fmix_schema_key "$worktree")" || {
        fmix_error "Could not compute the migration-content schema key for $worktree."
        return 1
    }
    FMIX_ACTIVE_DB_SCHEMA_KEY=""
    FMIX_ACTIVE_DB_SOURCE_KEY=""
    FMIX_ACTIVE_DB_BASE_ID=""
    FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=0

    # --from-zero is an explicit request for a fresh, empty database and the
    # complete migration chain. Drop only this exact FMix-owned scratch; never
    # infer that a valid migration ledger makes its rows bootstrap-clean.
    if [[ "$force_from_zero" == "1" ]] && fmix_db_exists "$db_name"; then
        fmix_info "Explicit --from-zero is replacing owned scratch DB $db_name with an empty database."
        fmix_drop_db "$db_name" || return $?
    fi

    if fmix_db_exists "$db_name"; then
        fmix_info "Scratch DB $db_name already exists."
        if fmix_validate_db_integrity "$db_name" \
            && fmix_migration_ledger_is_prefix "$worktree" "$db_name"; then
            stored_key="$(fmix_read_state "$state_file" db_schema_key)"
            stored_source="$(fmix_read_state "$state_file" db_source_schema_key)"
            [[ -n "$stored_source" ]] || stored_source="$stored_key"
            stored_base="$(fmix_read_state "$state_file" db_base_id)"
            if [[ -z "$stored_key" ]]; then
                if [[ "$allow_legacy_adopt" == "1" ]]; then
                    fmix_warn "Adopting legacy fmix scratch provenance during explicit setup."
                    valid=1
                else
                    fmix_error "Scratch DB $db_name predates content-addressed provenance."
                    fmix_error "Run: ./fmix setup --worktree $worktree"
                    return 1
                fi
            elif [[ "$stored_key" == "$current_key" ]] \
                || fmix_worktree_schema_manifest_is_prefix "$worktree" "$stored_key"; then
                valid=1
            else
                fmix_error "Scratch DB $db_name provenance is not a content-valid prefix of this branch."
            fi
        fi
        if (( valid == 1 )) && [[ "$rebuild_existing" == "1" ]]; then
            # API-3576: an explicit rebuild must rebuild. A scratch DB whose
            # recorded schema key still matches reports "0 pending migrations"
            # forever, even when the schema under that ledger is stale, so
            # reusing it here made --rebuild-db/--cold-db/--from-zero silent
            # no-ops. The operator asked for a fresh database: drop it.
            fmix_warn "Explicit rebuild requested; replacing otherwise-valid scratch DB $db_name."
            valid=0
            fmix_lock_mutate_gate "scratch DB rebuild (DROP)" || return $?
            fmix_drop_db "$db_name" || return $?
        fi
        if (( valid == 1 )); then
            # The scratch will be asserted/migrated to the current manifest
            # before state publication. Preserve its source separately.
            FMIX_ACTIVE_DB_SCHEMA_KEY="$current_key"
            FMIX_ACTIVE_DB_SOURCE_KEY="${stored_source:-$current_key}"
            FMIX_ACTIVE_DB_BASE_ID="$stored_base"
            return 0
        fi
        if fmix_db_exists "$db_name"; then
            if [[ "$rebuild_existing" != "1" ]]; then
                fmix_error "Refusing to drop or reuse an unverified scratch DB in a normal lane."
                fmix_error "After confirming no live owner: ./fmix setup --rebuild-db --worktree $worktree"
                return 1
            fi
            fmix_warn "Explicit setup is replacing unverified scratch DB $db_name."
            fmix_lock_mutate_gate "scratch DB replacement (DROP)" || return $?
            fmix_drop_db "$db_name" || return $?
        fi
    fi

    # Scratch-DB creation (clone/cold bootstrap) mutates shared state.
    fmix_lock_mutate_gate "scratch DB creation" || return $?
    t0="$(fmix_epoch)"
    selection=""
    if [[ "$allow_structure_build" == "1" || "$force_from_zero" == "1" ]]; then
        # API-3576: --cold-db and --from-zero exist to build the schema again.
        # Selecting a published hot base first re-cloned the very base that was
        # stale, so these lanes could never repair it. Skip selection; the
        # rebuilt scratch is republished over the stale base (see setup).
        fmix_info "Explicit cold rebuild: bypassing published hot bases for $db_name."
    else
        fmix_info "Selecting one content-indexed DB base for $db_name …"
        selection="$(fmix_select_indexed_base "$worktree")" || selection=""
    fi
    if [[ -n "$selection" ]]; then
        IFS=$'\t' read -r base base_key delta <<<"$selection"
        fmix_guard_template_db_name "$base" || return 1
        fmix_info "Selected $base from metadata (schema=$base_key, delta=$delta); performing one clone."
        fmix_create_database "$db_name" "$base" || return $?
        FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
        FMIX_ACTIVE_DB_SCHEMA_KEY="$current_key"
        FMIX_ACTIVE_DB_SOURCE_KEY="$base_key"
        FMIX_ACTIVE_DB_BASE_ID="$base"
    elif [[ "$allow_structure_build" == "1" ]]; then
        local snapshot_rc=1
        if [[ "$force_from_zero" != "1" ]]; then
            snap="$(fmix_ensure_snapshot_template "$worktree")" && snapshot_rc=0 || snapshot_rc=$?
            (( snapshot_rc == 0 || snapshot_rc == 1 )) || return "$snapshot_rc"
        fi
        if (( snapshot_rc == 0 )); then
            fmix_warn "No indexed hot base exists; entering explicit, hard-capped cold maintenance."
            fmix_create_database "$db_name" "$snap" || return $?
            FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
            FMIX_ACTIVE_DB_SCHEMA_KEY="$current_key"
            FMIX_ACTIVE_DB_SOURCE_KEY="$current_key"
            FMIX_ACTIVE_DB_BASE_ID="$snap"
        else
            # API-2846: structure.sql is either missing, fails the freshness/
            # provenance gate (a recorded migration's body changed — see
            # fmix_structure_matches_migration_history), or --from-zero
            # forced this lane explicitly. structure.sql being permanently
            # stale is now an ordinary condition to absorb, not a transient
            # to wait out, so this is the only remaining legitimate
            # bootstrap path instead of a hard error.
            if [[ "$force_from_zero" == "1" ]]; then
                fmix_warn "No indexed hot base exists; --from-zero forced migrate-from-zero maintenance."
            else
                fmix_warn "No indexed hot base exists and structure.sql is unusable for cold bootstrap; migrating from zero."
            fi
            fmix_migrate_from_zero "$worktree" "$db_name" 1 || return $?
            FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
            FMIX_ACTIVE_DB_SCHEMA_KEY="$current_key"
            FMIX_ACTIVE_DB_SOURCE_KEY="$current_key"
            FMIX_ACTIVE_DB_BASE_ID="migrate-from-zero"
        fi
    else
        fmix_error "No content-indexed hot DB base is compatible with this branch."
        fmix_error "Ordinary lanes perform zero candidate probes and never replay structure.sql."
        fmix_error "Publish one from an already-prepared worktree, then ordinary lanes reuse it:"
        fmix_error "  ./fmix setup --cold-db --worktree $worktree"
        fmix_error "  (structure.sql unusable/stale beyond the freshness gate? that command falls back to --from-zero automatically)"
        return 1
    fi

    if ! fmix_validate_db_integrity "$db_name" \
        || ! fmix_migration_ledger_is_prefix "$worktree" "$db_name"; then
        fmix_error "The single selected base failed post-clone ledger validation; no fallback clone will be attempted."
        fmix_drop_db "$db_name" || {
            local drop_rc=$?
            fmix_lock_failure_is_fatal "$drop_rc" && return 70
        }
        return 1
    fi
    t1="$(fmix_epoch)"
    fmix_info "DB created from one selected base in $(( t1 - t0 ))s."
    return 0
}

fmix_migration_stamp() {
    local worktree="$1"
    local mig_dir="$worktree/priv/repo/migrations"
    if [[ -d "$mig_dir" ]]; then
        # Use the last migration file name as the stamp
        local last
        last="$(ls "$mig_dir" 2>/dev/null | LC_ALL=C sort | tail -1)"
        printf '%s\n' "${last:-none}"
    else
        printf 'none\n'
    fi
}

fmix_pending_migration_count() {
    # Ground-truth migration drift, the same thing Ecto.Migrator.migrations/1
    # reports as status :down, but computed via psql so it costs no BEAM boot:
    # migration-file versions (the 14-digit filename prefix) that are NOT present
    # in the scratch DB's schema_migrations table. (cisco-cdr's test repos all
    # share one DB / one schema_migrations table, so a single comparison is
    # authoritative.) Echoes the integer count; 0 = fully migrated.
    local worktree="$1" db_name="$2"
    local mig_dir="$worktree/priv/repo/migrations"
    [[ -d "$mig_dir" ]] || { printf '0\n'; return 0; }
    local file_versions db_versions
    local versions_file
    versions_file="$(mktemp)" || return 1
    fmix_write_migration_versions "$worktree" "$versions_file" || {
        rm -f "$versions_file"
        printf '0\n'
        return 0
    }
    file_versions="$(cat "$versions_file")"
    rm -f "$versions_file"
    [[ -n "$file_versions" ]] || { printf '0\n'; return 0; }
    db_versions="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$db_name" \
        -Atc 'SELECT version FROM schema_migrations' 2>/dev/null | LC_ALL=C sort -u)"
    # file versions present in files but absent from the DB = pending (:down).
    # grep -c prints 0 but returns 1 for no matches; normalize that valid zero
    # result so exact-ledger callers do not treat a current schema as an error.
    local pending
    pending="$(comm -23 <(printf '%s\n' "$file_versions") <(printf '%s\n' "$db_versions") \
        | grep -c '[0-9]' || true)"
    printf '%s\n' "${pending:-0}"
    return 0
}

fmix_migration_ledger_is_current() {
    local worktree="$1" db_name="$2" pending
    fmix_migration_ledger_is_prefix "$worktree" "$db_name" || return 1
    pending="$(fmix_pending_migration_count "$worktree" "$db_name")" || return 1
    [[ "$pending" == "0" ]]
}

fmix_run_migration_bounded() {
    # Optional $3 overrides the default $FMIX_MIGRATION_TIMEOUT-bounded budget
    # — used by fmix_migrate_from_zero, whose full-chain replay is orders of
    # magnitude longer than the ordinary bounded hot-lane delta this function
    # otherwise runs.
    local worktree="$1" db_name="$2" timeout pid started now log_file rc
    timeout="$(fmix_positive_uint_or_default "${3:-$FMIX_MIGRATION_TIMEOUT}" 120 FMIX_MIGRATION_TIMEOUT)"
    log_file="$FMIX_HOME/logs/migrate-$(fmix_worktree_id "$worktree")-$(date +%Y%m%dT%H%M%S).log"
    mkdir -p "$(dirname "$log_file")"
    # A compile-stamp hit (or restored pool artifacts on a fresh pod) skips the
    # compile path's Hex bootstrap; `mix ecto.migrate` then dies with "Could
    # not find an SCM for dependency" before running a single migration.
    fmix_ensure_hex "$worktree" || fmix_warn "Hex bootstrap failed; ecto.migrate may fail to resolve dependency SCMs."
    local -a build_env=()
    [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
    [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
    (
        cd "$worktree" || exit 1
        exec env \
            -u DB_HOST_IPV4 \
            "${build_env[@]+"${build_env[@]}"}" \
            MIX_ENV=test \
            DB_HOSTNAME="$DB_HOST" \
            DB_PORT="$DB_PORT" \
            DB_USER="$DB_USER" \
            DB_PASSWORD="$DB_PASSWORD" \
            DB_NAME="$db_name" \
            SECRET_KEY_BASE="$SECRET_KEY_BASE" \
            WORKER_NODE=TRUE \
            ADMIN_NODE=TRUE \
            ONPREM=TRUE \
            MEESEEKS_HTML5EVER_BUILD=0 \
            LOCAL_NATS="$NATS_HOST" \
            NATS_PORT="$NATS_PORT" \
            NATS_HOST="$NATS_HOST" \
            CT_NATS_HOST="$NATS_HOST" \
            NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
            POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
            POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
            mix ecto.migrate --no-compile
    ) >"$log_file" 2>&1 &
    pid=$!
    started="$(fmix_epoch)"
    while kill -0 "$pid" 2>/dev/null; do
        now="$(fmix_epoch)"
        if (( now - started >= timeout )); then
            fmix_kill_process_tree "$pid"
            sleep 1
            kill -KILL "$pid" 2>/dev/null || true
            wait "$pid" 2>/dev/null || true
            fmix_error "ecto.migrate exceeded ${timeout}s and was cancelled. Log: $log_file"
            return 124
        fi
        sleep 2
    done
    wait "$pid"
    rc=$?
    if (( rc != 0 )); then
        tail -20 "$log_file" >&2
    fi
    return "$rc"
}

fmix_schema_ready_stamp_file() {
    if [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]]; then
        printf '%s/schema-ready.json\n' "$FMIX_ACTIVE_SESSION_ROOT"
        return 0
    fi
    printf '%s/worktrees/%s.schema-ready.json\n' "$FMIX_HOME" "$(fmix_worktree_id "${1:-}")"
}

fmix_schema_ready_ttl_seconds() {
    # Auto-expire schema-ready skips so ledger is re-checked periodically.
    fmix_uint_or_default "${FMIX_SCHEMA_READY_TTL_S:-300}" 300 FMIX_SCHEMA_READY_TTL_S
}

fmix_write_schema_ready_stamp() {
    local worktree="$1" db_name="$2" mig_stamp schema_key stamp tmp now ttl
    mig_stamp="$(fmix_migration_stamp "$worktree")" || return 1
    schema_key="${FMIX_ACTIVE_DB_SCHEMA_KEY:-}"
    [[ -n "$schema_key" ]] || schema_key="$(fmix_schema_key "$worktree" 2>/dev/null || true)"
    now="$(fmix_epoch)"
    ttl="$(fmix_schema_ready_ttl_seconds)"
    stamp="$(fmix_schema_ready_stamp_file "$worktree")"
    mkdir -p "$(dirname "$stamp")"
    tmp="$(mktemp "${stamp}.tmp.XXXXXX")" || return 1
    cat >"$tmp" <<EOF
{
  "db_name": $(fmix_json_escape "$db_name"),
  "migration_stamp": $(fmix_json_escape "$mig_stamp"),
  "schema_key": $(fmix_json_escape "$schema_key"),
  "ready_at": $(fmix_json_escape "$(fmix_now)"),
  "ready_epoch": $(fmix_json_escape "$now"),
  "ttl_s": $(fmix_json_escape "$ttl")
}
EOF
    mv "$tmp" "$stamp" || { rm -f "$tmp"; return 1; }
}

fmix_schema_ready_stamp_warm_ro() {
    # Strictly read-only twin of fmix_schema_ready_stamp_matches: same
    # admission, but never removes an expired stamp. Shared (read) holds and
    # the pre-lock read-only probe must not mutate; stamp expiry cleanup stays
    # in the exclusive path.
    local worktree="$1" db_name="$2" stamp mig_stamp schema_key
    local recorded_db recorded_mig recorded_schema recorded_epoch ttl age now
    stamp="$(fmix_schema_ready_stamp_file "$worktree")"
    [[ -f "$stamp" ]] || return 1
    recorded_db="$(fmix_read_state "$stamp" db_name)"
    recorded_mig="$(fmix_read_state "$stamp" migration_stamp)"
    recorded_schema="$(fmix_read_state "$stamp" schema_key)"
    recorded_epoch="$(fmix_read_state "$stamp" ready_epoch)"
    ttl="$(fmix_read_state "$stamp" ttl_s)"
    [[ "$ttl" =~ ^[0-9]+$ ]] || ttl="$(fmix_schema_ready_ttl_seconds)"
    [[ "$recorded_epoch" =~ ^[0-9]+$ ]] || return 1
    now="$(fmix_epoch)"
    age=$(( now - recorded_epoch ))
    (( age >= 0 && age < ttl )) || return 1
    [[ "$recorded_db" == "$db_name" ]] || return 1
    mig_stamp="$(fmix_migration_stamp "$worktree")" || return 1
    [[ "$recorded_mig" == "$mig_stamp" ]] || return 1
    schema_key="${FMIX_ACTIVE_DB_SCHEMA_KEY:-}"
    if [[ -n "$schema_key" && -n "$recorded_schema" ]]; then
        [[ "$recorded_schema" == "$schema_key" ]] || return 1
    fi
    return 0
}

fmix_schema_ready_stamp_matches() {
    local worktree="$1" db_name="$2" stamp mig_stamp schema_key
    local recorded_db recorded_mig recorded_schema recorded_epoch ttl age now
    stamp="$(fmix_schema_ready_stamp_file "$worktree")"
    [[ -f "$stamp" ]] || return 1
    recorded_db="$(fmix_read_state "$stamp" db_name)"
    recorded_mig="$(fmix_read_state "$stamp" migration_stamp)"
    recorded_schema="$(fmix_read_state "$stamp" schema_key)"
    recorded_epoch="$(fmix_read_state "$stamp" ready_epoch)"
    ttl="$(fmix_read_state "$stamp" ttl_s)"
    [[ "$ttl" =~ ^[0-9]+$ ]] || ttl="$(fmix_schema_ready_ttl_seconds)"
    # Missing ready_epoch (pre-2.2.2 stamps) → treat as expired.
    if [[ ! "$recorded_epoch" =~ ^[0-9]+$ ]]; then
        rm -f "$stamp" 2>/dev/null || true
        return 1
    fi
    now="$(fmix_epoch)"
    age=$(( now - recorded_epoch ))
    if (( age < 0 || age >= ttl )); then
        # Auto-expire: force a full ledger re-scan on the next check.
        rm -f "$stamp" 2>/dev/null || true
        return 1
    fi
    [[ "$recorded_db" == "$db_name" ]] || return 1
    mig_stamp="$(fmix_migration_stamp "$worktree")" || return 1
    [[ "$recorded_mig" == "$mig_stamp" ]] || return 1
    schema_key="${FMIX_ACTIVE_DB_SCHEMA_KEY:-}"
    if [[ -n "$schema_key" && -n "$recorded_schema" ]]; then
        [[ "$recorded_schema" == "$schema_key" ]] || return 1
    fi
    return 0
}

fmix_ensure_migrations() {
    local rc=0
    _fmix_ensure_migrations_impl "$@" || rc=$?
    if (( rc == 200 )) && [[ "${FMIX_LOCK_GATE_RETRY:-}" == "1" ]]; then
        # Escalated before schema work: re-verify the warm schema state once
        # under the new exclusive hold before migrating or writing stamps.
        FMIX_LOCK_GATE_RETRY=""
        rc=0
        _fmix_ensure_migrations_impl "$@" || rc=$?
    fi
    return "$rc"
}

_fmix_ensure_migrations_impl() {
    local worktree="$1" db_name="$2" state_file="$3"
    fmix_prepend_toolchain_paths

    if fmix_lock_any_shared_held; then
        # Shared holds admit only the strictly read-only warm path. The stock
        # warm check auto-expires stale stamps (a mutation), so probe without
        # side effects; any miss escalates instead of scanning/writing under a
        # shared lease.
        if fmix_schema_ready_stamp_warm_ro "$worktree" "$db_name" \
            && fmix_validate_db_integrity "$db_name"; then
            fmix_info "Schema ready stamp hit (TTL $(fmix_schema_ready_ttl_seconds)s) — skipping migration ledger scan."
            return 0
        fi
        fmix_lock_mutate_gate \
            "migration ledger scan, migration delta, or schema-ready stamp" || return $?
    fi

    # Warm path: prior success stamp matching migration files + db name skips
    # repeated ledger scans (was ~2 full psql + file walks per run).
    if fmix_schema_ready_stamp_matches "$worktree" "$db_name"; then
        fmix_info "Schema ready stamp hit (TTL $(fmix_schema_ready_ttl_seconds)s) — skipping migration ledger scan."
        fmix_validate_db_integrity "$db_name" || {
            rm -f "$(fmix_schema_ready_stamp_file "$worktree")" 2>/dev/null || true
            fmix_error "Schema ready stamp was stale; integrity check failed."
            return 1
        }
        return 0
    fi

    # Reject extra/ahead/unknown database versions before considering a delta.
    # The old one-way files-minus-database check reported zero pending when a
    # scratch DB carried versions from a newer or divergent branch. Gapped
    # (out-of-order/backfilled) ledgers are accepted as long as every
    # recorded version is a real, known migration.
    if ! fmix_migration_ledger_is_prefix "$worktree" "$db_name"; then
        fmix_error "Scratch DB $db_name migration ledger is not a subset of this branch."
        fmix_error "Refusing to run tests against an ahead or unknown schema."
        return 1
    fi

    # Drift is the ground truth (files vs schema_migrations), NOT a filename
    # stamp heuristic: a stamp can match while the DB is partially migrated, and
    # mismatch when it is actually fine. Reading the real table is exact.
    local pending limit
    pending="$(fmix_pending_migration_count "$worktree" "$db_name")"
    [[ "$pending" =~ ^[0-9]+$ ]] || {
        fmix_error "Could not determine pending migration count for $db_name."
        return 1
    }
    limit="$(fmix_positive_uint_or_default "$FMIX_MIGRATION_DELTA_LIMIT" 50 FMIX_MIGRATION_DELTA_LIMIT)"
    if (( pending > limit )); then
        fmix_error "Migration delta $pending exceeds the hot-lane limit $limit."
        fmix_error "Publish a newer hot DB base; refusing a long migration replay."
        return 1
    fi
    if [[ "$pending" == "0" ]]; then
        fmix_info "Schema is current (0 pending migrations) — skipping ecto.migrate."
        # pending=0 + prefix already proves current; skip a third ledger scan.
    else
        fmix_info "Drift: $pending migration(s) not in schema_migrations — running ecto.migrate (delta) …"
        fmix_run_migration_bounded "$worktree" "$db_name" || {
            local migration_rc=$?
            fmix_error "ecto.migrate failed on $db_name."
            fmix_error "Check migration files in priv/repo/migrations/ for errors."
            return "$migration_rc"
        }
        # POST-ASSERT: zero pending now. This is the safety net test_helper used
        # to provide — but it DETECTS (read-only) and fails LOUDLY instead of
        # silently re-running migrations and swallowing the error (which is what
        # corrupted scratch DBs). With this proven, CT_SKIP_MIGRATION_TIMING=1
        # in the test env is a pure perf toggle, not a correctness crutch.
        local still
        still="$(fmix_pending_migration_count "$worktree" "$db_name")"
        if [[ "$still" != "0" ]] || ! fmix_migration_ledger_is_current "$worktree" "$db_name"; then
            fmix_error "After ecto.migrate, the scratch DB ledger is not exactly current (pending=$still)."
            fmix_error "Its source template is likely corrupt. Reset: ./fmix gc --reap --yes; then re-run ./fmix test."
            return 1
        fi
    fi
    fmix_ensure_partitions "$worktree" "$db_name" || return 1
    fmix_validate_db_integrity "$db_name" || return 1
    fmix_write_schema_ready_stamp "$worktree" "$db_name" \
        || fmix_warn "Schema verified but ready-stamp could not be written; next run re-scans the ledger."
    return 0
}

fmix_ensure_partitions() {
    # Date-partition freshness (API-2014 RCA, found via API-1755): scratch/template DBs are keyed by
    # structure.sql CONTENT, not date — but partitioned tables (cdrcalls,
    # cube_event_logs, …) only carry a finite forward horizon of daily
    # partitions from whenever the image was built. Reuse the image across a
    # date rollover and every "insert now()" fails with
    # `no partition of relation ... found for row` (Postgres 23514).
    # Cheap gate: if today's cdrcalls partition exists, do nothing (same-day
    # reuse costs one SELECT). Otherwise run the idempotent
    # `mix cdrcisco.bootstrap_partitions` (today + N days ahead, ~2-5s warm).
    local worktree="$1" db_name="$2"
    local today has_today probe_rc partitioned
    today="$(date -u +%Y%m%d)"
    # Older stable lines (including 0.8.6) keep cdrcalls as a regular table;
    # they do not ship the partition bootstrap Mix task. Do not turn that
    # branch capability difference into a setup failure. Newer partitioned
    # lines still take the existing horizon check below.
    partitioned="$(fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$db_name" \
        -Atc "SELECT CASE WHEN EXISTS (SELECT 1 FROM pg_partitioned_table p JOIN pg_class c ON c.oid = p.partrelid WHERE c.relname = 'cdrcalls') THEN 1 ELSE 0 END" \
        2>/dev/null)"
    probe_rc=$?
    if [[ "$probe_rc" -ne 0 ]]; then
        fmix_error "Partitioning capability probe failed (psql rc=$probe_rc) on $db_name — cannot determine whether horizon repair is required."
        return 1
    fi
    if [[ "$partitioned" != "1" ]]; then
        return 0
    fi
    # Distinguish "probe failed" (connection/auth) from "partition missing" —
    # both yield empty output, but a failed probe must not be misdiagnosed as a
    # stale horizon (claude T1 review, API-2014).
    has_today="$(fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$db_name" \
        -Atc "SELECT 1 FROM pg_class WHERE relname = 'cdrcalls_${today}'" 2>/dev/null)"
    probe_rc=$?
    if [[ "$probe_rc" -ne 0 ]]; then
        fmix_error "Partition-freshness probe failed (psql rc=$probe_rc) on $db_name — cannot verify horizon."
        return 1
    fi
    if [[ "$has_today" == "1" ]]; then
        return 0
    fi
    fmix_info "Partition horizon stale (no cdrcalls_${today}) — running cdrcisco.bootstrap_partitions …"
    (
        cd "$worktree"
        MIX_ENV=test \
            DB_HOSTNAME="$DB_HOST" \
            DB_PORT="$DB_PORT" \
            DB_USER="$DB_USER" \
            DB_PASSWORD="$DB_PASSWORD" \
            DB_NAME="$db_name" \
            SECRET_KEY_BASE="$SECRET_KEY_BASE" \
            WORKER_NODE=TRUE \
            ADMIN_NODE=TRUE \
            ONPREM=TRUE \
            MEESEEKS_HTML5EVER_BUILD=0 \
            LOCAL_NATS="$NATS_HOST" \
            NATS_PORT="$NATS_PORT" \
            NATS_HOST="$NATS_HOST" \
            CT_NATS_HOST="$NATS_HOST" \
            NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
            POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
            POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
            env -u DB_HOST_IPV4 mix cdrcisco.bootstrap_partitions
    ) || {
        fmix_error "cdrcisco.bootstrap_partitions failed on $db_name."
        return 1
    }
    return 0
}

# ---------------------------------------------------------------------------
# compile step: ensure app beams are up to date in the worktree
# ---------------------------------------------------------------------------

fmix_compile_build_root() {
    local worktree="$1" configured="${MIX_BUILD_PATH:-_build}"
    if [[ -n "$FMIX_ACTIVE_SESSION_ROOT" \
        && "$configured" == "$FMIX_ACTIVE_SESSION_ROOT/_build/test" ]]; then
        printf '%s/_build\n' "$FMIX_ACTIVE_SESSION_ROOT"
        return 0
    fi
    if [[ "$configured" == /* ]]; then
        printf '%s\n' "$configured"
    else
        printf '%s/%s\n' "$worktree" "$configured"
    fi
}

fmix_reject_compile_input_symlink_components() {
    # Compiler-input pathspecs are always relative to the canonical worktree.
    # Reject a symlink at any component below that root before asking Git to
    # enumerate the path: Git returns no entry for a pathspec beneath a tracked
    # directory symlink, which would otherwise make an escaped input invisible.
    # Path dependencies deliberately use fmix_hash_path_dependency instead; it
    # canonicalizes the explicitly configured dependency root first, then
    # rejects nested links beneath that allowed top-level alias.
    local root="$1" relative="$2" current remaining component
    [[ -n "$root" && -n "$relative" ]] || return 1
    case "$relative" in
        /*)
            fmix_error "Compiler input path must be relative to the worktree: $relative"
            return 1
            ;;
    esac

    current="${root%/}"
    remaining="$relative"
    while [[ -n "$remaining" ]]; do
        if [[ "$remaining" == */* ]]; then
            component="${remaining%%/*}"
            remaining="${remaining#*/}"
        else
            component="$remaining"
            remaining=""
        fi
        case "$component" in
            ""|.) continue ;;
            ..)
                fmix_error "Compiler input path escapes the worktree: $relative"
                return 1
                ;;
        esac
        current="$current/$component"
        if [[ -L "$current" ]]; then
            fmix_error "Symlinked compiler input is unsupported: $current"
            return 1
        fi
    done
    return 0
}

fmix_reject_repo_elixir_input_symlinks() {
    # priv/repo compiler inputs are discovered with find before they are passed
    # to fmix_hash_compile_paths. Validate the discovery root explicitly so a
    # root or nested directory alias cannot disappear from that candidate list.
    # This is a worktree-owned input root, not the deliberate top-level alias
    # exception for explicitly configured path dependencies.
    local root="$1" repo_root="${1%/}/priv/repo" probe symlink_path
    fmix_reject_compile_input_symlink_components "$root" "priv/repo" \
        || return 1
    [[ -d "$repo_root" ]] || return 0
    probe="$(mktemp)" || return 1
    if ! find "$repo_root" -type l -print -quit >"$probe" 2>/dev/null; then
        rm -f "$probe"
        return 1
    fi
    if [[ -s "$probe" ]]; then
        IFS= read -r symlink_path <"$probe" || symlink_path="$repo_root"
        rm -f "$probe"
        fmix_error "Symlinked compiler input is unsupported: $symlink_path"
        return 1
    fi
    rm -f "$probe"
    return 0
}

fmix_hash_compile_paths() {
    local root="$1" tracked_file="" untracked_file="" path file
    shift
    for path in "$@"; do
        fmix_reject_compile_input_symlink_components "$root" "$path" || return 1
    done
    if [[ -d "$root/.git" || -f "$root/.git" ]]; then
        git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1 \
            || return 1
        tracked_file="$(mktemp)" || return 1
        if ! git -C "$root" ls-files -s -z -- "$@" \
            >"$tracked_file" 2>/dev/null; then
            rm -f "$tracked_file"
            return 1
        fi
        if ! fmix_hash_tracked_compile_inputs "$root" "$tracked_file"; then
            rm -f "$tracked_file"
            return 1
        fi
        rm -f "$tracked_file"
        untracked_file="$(mktemp)" || return 1
        if ! (
            git -C "$root" ls-files --others --exclude-standard -z -- "$@" \
                || exit 1
            # Git ignores do not change what Mix can compile or execute. Keep
            # ignored source files in the exact run identity, but only beneath
            # the caller's bounded source/test pathspecs. Never widen an empty
            # pathspec into a scan of ignored cache artifacts.
            if (( $# > 0 )); then
                git -C "$root" ls-files --others --ignored \
                    --exclude-standard -z -- "$@" || exit 1
            fi
        ) >"$untracked_file" 2>/dev/null; then
            rm -f "$untracked_file"
            return 1
        fi
        local -a untracked_pairs=()
        while IFS= read -r -d '' path; do
            case "$path" in
                _build|_build/*|deps|deps/*) continue ;;
            esac
            if [[ -L "$root/$path" ]]; then
                fmix_error "Symlinked compiler input is unsupported: $root/$path"
                rm -f "$untracked_file"
                return 1
            fi
            [[ -f "$root/$path" ]] || continue
            untracked_pairs+=("$path" "$root/$path")
        done <"$untracked_file"
        rm -f "$untracked_file"
        fmix_hash_paired_lines "untracked" \
            "${untracked_pairs[@]+"${untracked_pairs[@]}"}" || return 1
        return 0
    fi

    for path in "$@"; do
        if [[ -L "$root/$path" ]]; then
            fmix_error "Symlinked compiler input is unsupported: $root/$path"
            return 1
        elif [[ -f "$root/$path" ]]; then
            printf 'file:%s:' "$path"
            fmix_hash_files "$root/$path"
        elif [[ -d "$root/$path" ]]; then
            fmix_reject_nested_source_symlinks "$root/$path" || return 1
            local -a dir_pairs=()
            while IFS= read -r file; do
                dir_pairs+=("${file#"$root/"}" "$file")
            done < <(find "$root/$path" -type f -print 2>/dev/null | LC_ALL=C sort)
            fmix_hash_paired_lines "file" \
                "${dir_pairs[@]+"${dir_pairs[@]}"}" || return 1
        else
            printf 'missing:%s\n' "$path"
        fi
    done
}

fmix_ignored_compile_inputs_hash() {
    # Git's ordinary dirty hash intentionally omits ignored files, but ignored
    # files under Mix compiler roots are still executable inputs. Hash only
    # that bounded set; never walk dependency, build, node, or artifact caches.
    local worktree="$1" real ignored_file manifest hash rc path
    local -a compile_paths=(
        .tool-versions mix.exs mix.lock
        config/config.exs config/config_sync.exs config/test.exs
        lib test/support test/cdrcisco/policies/reputation_signals/shared
        vendor dev_tools priv/repo
    )
    real="$(fmix_realpath "$worktree" 2>/dev/null)" || return 1
    if [[ ! -d "$real/.git" && ! -f "$real/.git" ]]; then
        printf 'non-git\n'
        return 0
    fi
    command -v git >/dev/null 2>&1 || return 1
    git -C "$real" rev-parse --is-inside-work-tree >/dev/null 2>&1 \
        || return 1
    ignored_file="$(mktemp)" || return 1
    manifest="$(mktemp)" || { rm -f "$ignored_file"; return 1; }
    if ! git -C "$real" ls-files --others --ignored --exclude-standard -z \
        -- "${compile_paths[@]}" >"$ignored_file" 2>/dev/null; then
        rm -f "$ignored_file" "$manifest"
        return 1
    fi
    rc=0
    local -a ignored_pairs=()
    {
        printf 'fmix-ignored-compile-inputs-v1\n'
        while IFS= read -r -d '' path; do
            case "/$path/" in
                */.git/*|*/_build/*|*/deps/*|*/node_modules/*|*/artifacts/*)
                    continue
                    ;;
            esac
            [[ -f "$real/$path" ]] || continue
            ignored_pairs+=("$path" "$real/$path")
        done <"$ignored_file"
        fmix_hash_paired_lines "ignored" \
            "${ignored_pairs[@]+"${ignored_pairs[@]}"}" || rc=1
    } >"$manifest"
    rm -f "$ignored_file"
    if (( rc != 0 )); then
        rm -f "$manifest"
        return "$rc"
    fi
    hash="$(fmix_hash_stdin <"$manifest")"
    rc=$?
    rm -f "$manifest"
    (( rc == 0 )) || return "$rc"
    [[ "$hash" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s\n' "$hash"
}

fmix_compute_compile_fingerprint() {
    # Content-only and deliberately conservative. Ordinary test files are not
    # compiler inputs, but all test elixirc paths, config, dependency inputs,
    # local path dependencies, and the compile environment are included.
    local worktree="$1" real build_root toolchain_identity manifest fingerprint rc
    real="$(fmix_realpath "$worktree")"
    build_root="$(fmix_compile_build_root "$real")"
    toolchain_identity="${FMIX_TOOLCHAIN_IDENTITY:-}"
    if [[ -z "$toolchain_identity" ]]; then
        toolchain_identity="$(fmix_resolved_toolchain_identity "$real")" || return 1
    fi
    local -a compile_paths=(
        .tool-versions mix.exs mix.lock
        config/config.exs config/config_sync.exs config/test.exs
        lib test/support test/cdrcisco/policies/reputation_signals/shared
        vendor dev_tools
    )
    local -a repo_elixir_paths=()
    fmix_reject_repo_elixir_input_symlinks "$real" || return 1
    while IFS= read -r file; do
        repo_elixir_paths+=("${file#"$real/"}")
    done < <(find "$real/priv/repo" \( -type f -o -type l \) \
        -name '*.ex' -print 2>/dev/null | LC_ALL=C sort)
    manifest="$(mktemp)" || return 1
    (
        printf 'fmix-compile-fingerprint-v4\n'
        printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
        printf '%s\n' "$toolchain_identity"
        fmix_hash_compile_paths "$real" "${compile_paths[@]}" "${repo_elixir_paths[@]+"${repo_elixir_paths[@]}"}" || return 1
        fmix_declared_path_dependency_guard "$real" || return 1
        fmix_path_dependency_source_guard "$real" || return 1
        fmix_compile_environment "$real" || return 1
    ) >"$manifest"
    rc=$?
    if (( rc != 0 )); then
        rm -f "$manifest"
        return "$rc"
    fi
    fingerprint="$(fmix_hash_stdin <"$manifest")"
    rc=$?
    rm -f "$manifest"
    (( rc == 0 )) || return "$rc"
    [[ "$fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s\n' "$fingerprint"
}

fmix_source_stability_compile_identity() {
    local worktree="${1:-}" real head manifest identity rc file
    local -a compile_paths=(
        .tool-versions mix.exs mix.lock
        config/config.exs config/config_sync.exs config/test.exs
        lib test/support test/cdrcisco/policies/reputation_signals/shared
        vendor dev_tools
    )
    local -a repo_elixir_paths=()
    (( $# >= 1 )) || return 1
    real="$(fmix_realpath "$worktree")" || return 1
    if [[ -d "$real/.git" || -f "$real/.git" ]]; then
        git -C "$real" rev-parse --is-inside-work-tree >/dev/null 2>&1 \
            || return 1
        head="$(git -C "$real" rev-parse HEAD 2>/dev/null)" || return 1
        [[ "$head" =~ ^[0-9a-f]{40}$ ]] || return 1
    else
        head="non-git"
    fi
    fmix_reject_repo_elixir_input_symlinks "$real" || return 1
    while IFS= read -r file; do
        repo_elixir_paths+=("${file#"$real/"}")
    done < <(find "$real/priv/repo" \( -type f -o -type l \) \
        -name '*.ex' -print 2>/dev/null | LC_ALL=C sort)
    manifest="$(mktemp)" || return 1
    {
        printf 'fmix-source-stability-compile-v1\n'
        printf 'worktree=%s\n' "$real"
        printf 'head=%s\n' "$head"
        printf 'compile-inputs\n'
        fmix_hash_compile_paths \
            "$real" \
            "${compile_paths[@]}" \
            "${repo_elixir_paths[@]+"${repo_elixir_paths[@]}"}" || return 1
        fmix_declared_path_dependency_guard "$real" || return 1
        fmix_path_dependency_source_guard "$real" || return 1
    } >"$manifest"
    rc=$?
    if (( rc != 0 )); then
        rm -f "$manifest"
        return "$rc"
    fi
    identity="$(fmix_hash_stdin <"$manifest")"
    rc=$?
    rm -f "$manifest"
    (( rc == 0 )) || return "$rc"
    [[ "$identity" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s\n' "$identity"
}

# Exact identity for an immutable test/coverage run. Bind the compiler inputs
# above to the selected tests and every shared helper file, including helper
# dependencies such as test_helper_nats.exs.
fmix_source_stability_identity() {
    local worktree="${1:-}" real manifest identity compile_identity rc arg candidate relative
    local selected_path_count=0 file
    local -a helper_paths=()
    (( $# >= 1 )) || return 1
    shift
    real="$(fmix_realpath "$worktree")" || return 1
    compile_identity="$(fmix_source_stability_compile_identity "$real")" || return 1
    while IFS= read -r file; do
        helper_paths+=("${file#"$real/"}")
    done < <(find "$real/test" \( -type f -o -type l \) \
        \( -name '*helper*.ex' -o -name '*helper*.exs' \) \
        -print 2>/dev/null | LC_ALL=C sort)

    manifest="$(mktemp)" || return 1
    {
        printf 'fmix-source-stability-v2\n'
        printf 'compile-identity=%s\n' "$compile_identity"
        printf 'shared-test-helpers\n'
        fmix_hash_compile_paths \
            "$real" \
            "${helper_paths[@]+"${helper_paths[@]}"}" || return 1
        printf 'selected-count=%s\n' "$#"
        for arg in "$@"; do
            printf 'selected-arg:'
            printf '%s' "$arg" | fmix_hash_stdin || return 1
            candidate="$arg"
            if [[ "$candidate" =~ ^(.+):[0-9]+$ ]]; then
                candidate="${BASH_REMATCH[1]}"
            fi
            [[ "$candidate" != -* ]] || continue
            if [[ "$candidate" == /* ]]; then
                case "$candidate" in
                    "$real"/*) relative="${candidate#"$real/"}" ;;
                    *) continue ;;
                esac
            else
                relative="${candidate#./}"
                case "$relative" in ../*|*/../*|..|*/..) continue ;; esac
            fi
            [[ -e "$real/$relative" || -L "$real/$relative" ]] || continue
            printf 'selected-path=%s\n' "$relative"
            fmix_hash_compile_paths "$real" "$relative" || return 1
            selected_path_count=$((selected_path_count + 1))
        done
        if (( selected_path_count == 0 )); then
            printf 'selected-default=test\n'
            fmix_hash_compile_paths "$real" test || return 1
        fi
    } >"$manifest"
    rc=$?
    if (( rc != 0 )); then
        rm -f "$manifest"
        return "$rc"
    fi
    identity="$(fmix_hash_stdin <"$manifest")"
    rc=$?
    rm -f "$manifest"
    (( rc == 0 )) || return "$rc"
    [[ "$identity" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s\n' "$identity"
}

fmix_invalidate_compile_stamp() {
    local worktree="${1:-}" stamp
    [[ -n "$worktree" ]] || return 1
    stamp="$(fmix_compile_stamp_file "$worktree" 2>/dev/null)" || return 1
    [[ -n "$stamp" ]] || return 1
    if [[ -e "$stamp" || -L "$stamp" ]]; then
        rm -f "$stamp" || {
            fmix_error "Could not invalidate rejected compile stamp: $stamp"
            return 1
        }
    fi
    return 0
}

fmix_invalidate_dependency_stamp() {
    local worktree="${1:-}" stamp
    [[ -n "$worktree" ]] || return 1
    stamp="$(fmix_dependency_stamp_file "$worktree" 2>/dev/null)" || return 1
    [[ -n "$stamp" ]] || return 1
    if [[ -e "$stamp" || -L "$stamp" ]]; then
        rm -f "$stamp" || {
            fmix_error "Could not invalidate rejected dependency stamp: $stamp"
            return 1
        }
    fi
    return 0
}

fmix_invalidate_rejected_stamps() {
    local worktree="${1:-}" rc=0
    # Stamp removal mutates the shared session overlay. Failure paths call this
    # without retrying, so escalate directly and proceed under exclusive.
    if fmix_lock_any_shared_held; then
        fmix_lock_escalate_exclusive "rejected-stamp invalidation" || return 70
    fi
    fmix_invalidate_compile_stamp "$worktree" || rc=1
    fmix_invalidate_dependency_stamp "$worktree" || rc=1
    return "$rc"
}

fmix_require_stable_source() {
    local worktree="${1:-}" phase="${2:-execution}" invalidate_stamps="${3:-0}" current
    [[ "${FMIX_SOURCE_STABILITY_REQUIRED:-0}" == "1" ]] || return 0
    [[ "${FMIX_SOURCE_STABILITY_IDENTITY:-}" =~ ^[0-9a-f]{64}$ ]] || {
        fmix_error "Source stability identity is missing; refusing $phase."
        [[ "$invalidate_stamps" != "1" ]] \
            || fmix_invalidate_rejected_stamps "$worktree"
        return 1
    }
    # Cheap stat-manifest pass first: per-file digests recorded at capture are
    # reused for stat-unchanged entries, so this revalidation re-reads nothing
    # while the snapshot is untouched. The verdict is still the captured
    # identity: any drift (or manifest anomaly) falls back to a full uncached
    # recompute before the fail-closed decision, so a source mutation between
    # capture and stamp publication can never pass as a warm hit.
    current=""
    if fmix_stat_hash_cache_use "$worktree"; then
        current="$(fmix_source_stability_identity \
            "$worktree" \
            "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}")" \
            || current=""
        fmix_stat_hash_cache_done
    fi
    if [[ -n "$current" && "$current" == "$FMIX_SOURCE_STABILITY_IDENTITY" ]]; then
        return 0
    fi
    current="$(fmix_source_stability_identity \
        "$worktree" \
        "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}")" \
        || {
            fmix_error "Source stability could not be revalidated; refusing $phase."
            [[ "$invalidate_stamps" != "1" ]] \
                || fmix_invalidate_rejected_stamps "$worktree"
            return 1
        }
    if [[ "$current" != "$FMIX_SOURCE_STABILITY_IDENTITY" ]]; then
        fmix_error "Source/test inputs changed during $phase; refusing to use mixed-revision results."
        [[ "$invalidate_stamps" != "1" ]] \
            || fmix_invalidate_rejected_stamps "$worktree"
        return 1
    fi
    return 0
}

fmix_compute_dependency_fingerprint() {
    # Inputs that can change dependency resolution or native dependency builds.
    # Production/test source and ordinary config changes deliberately stay out:
    # they require incremental app compilation, not another `mix deps.get`.
    local worktree="$1" real build_root toolchain_identity manifest fingerprint rc
    real="$(fmix_realpath "$worktree")"
    build_root="$(fmix_compile_build_root "$real")"
    toolchain_identity="${FMIX_TOOLCHAIN_IDENTITY:-}"
    if [[ -z "$toolchain_identity" ]]; then
        toolchain_identity="$(fmix_resolved_toolchain_identity "$real")" || return 1
    fi
    local -a dependency_paths=(
        .tool-versions mix.exs mix.lock vendor dev_tools
    )
    manifest="$(mktemp)" || return 1
    (
        printf 'fmix-dependency-fingerprint-v3\n'
        printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
        printf '%s\n' "$toolchain_identity"
        fmix_hash_compile_paths "$real" "${dependency_paths[@]}" || return 1
        fmix_declared_path_dependency_resolution_guard "$real" || return 1
        fmix_dependency_environment "$real" || return 1
    ) >"$manifest"
    rc=$?
    if (( rc != 0 )); then
        rm -f "$manifest"
        return "$rc"
    fi
    fingerprint="$(fmix_hash_stdin <"$manifest")"
    rc=$?
    rm -f "$manifest"
    (( rc == 0 )) || return "$rc"
    [[ "$fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s\n' "$fingerprint"
}

fmix_compute_mix_project_reconciliation_guard() {
    # Normalize mix.exs while replacing exactly one ordinary deps/0 body. This
    # permits dependency declaration/constraint edits but keeps application,
    # compiler, path-layout, and every helper definition bound to the retained
    # app build. Path deps and referenced environment are guarded separately.
    local worktree="$1" real guard
    real="$(fmix_realpath "$worktree")" || return 1
    [[ -f "$real/mix.exs" ]] || return 1
    if ! command -v elixir >/dev/null 2>&1; then
        # Stamp helpers are intentionally portable before toolchain activation.
        # Bind the full project file in that mode: this keeps ordinary stamp
        # round-trips usable but deliberately prevents dependency-only reuse
        # until Elixir can produce the narrower AST-backed proof.
        (
            printf 'fmix-raw-mix-project-v1\n'
            cat "$real/mix.exs"
        ) | fmix_hash_stdin
        return $?
    fi
    guard="$(cd "$real" && elixir -e '
      path = List.first(System.argv())

      with {:ok, source} <- File.read(path) do
        quoted = Code.string_to_quoted(source)

        if match?({:ok, _}, quoted) do
          {:ok, quoted} = quoted
        {normalized, count} =
          Macro.prewalk(quoted, 0, fn
            {kind, meta, [{:deps, call_meta, args}, body]} = node, count
            when kind in [:def, :defp] and args in [nil, []] and is_list(body) ->
              if Keyword.keyword?(body) and Keyword.has_key?(body, :do) do
                replacement =
                  {kind, meta,
                   [
                     {:deps, call_meta, args},
                     Keyword.put(body, :do, :__fmix_dependency_declarations__)
                   ]}

                {replacement, count + 1}
              else
                {node, count}
              end

            node, count ->
              {node, count}
          end)

          if count == 1 do
            IO.write("fmix-normalized-deps-v1\n" <> Macro.to_string(normalized))
          else
            IO.write("fmix-raw-mix-project-v1\n" <> source)
          end
        else
          IO.write("fmix-raw-mix-project-v1\n" <> source)
        end
      end
    ' mix.exs)" || return 1
    [[ -n "$guard" ]] || return 1
    printf '%s' "$guard" | fmix_hash_stdin
}

fmix_compute_dependency_reconciliation_guard() {
    # Identity for dependency-resolution inputs that must remain stable while
    # reusing an app build across an ordinary deps/0 + mix.lock transition.
    # Those two dependency declarations are intentionally excluded; every
    # other dependency/compile-shaping input remains bound to the stamp.
    local worktree="$1" real toolchain_identity manifest guard rc
    real="$(fmix_realpath "$worktree")" || return 1
    toolchain_identity="${FMIX_TOOLCHAIN_IDENTITY:-}"
    if [[ -z "$toolchain_identity" ]]; then
        toolchain_identity="$(fmix_resolved_toolchain_identity "$real")" \
            || return 1
    fi
    local -a guarded_paths=(
        .tool-versions vendor dev_tools
    )
    manifest="$(mktemp)" || return 1
    (
        printf 'fmix-dependency-reconciliation-guard-v1\n'
        printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
        printf '%s\n' "$toolchain_identity"
        fmix_hash_compile_paths "$real" "${guarded_paths[@]}" || return 1
        fmix_compute_mix_project_reconciliation_guard "$real" || return 1
        fmix_declared_path_dependency_resolution_guard "$real" || return 1
        fmix_dependency_environment "$real" || return 1
    ) >"$manifest"
    rc=$?
    if (( rc != 0 )); then
        rm -f "$manifest"
        return "$rc"
    fi
    guard="$(fmix_hash_stdin <"$manifest")"
    rc=$?
    rm -f "$manifest"
    (( rc == 0 )) || return "$rc"
    [[ "$guard" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s\n' "$guard"
}

fmix_compute_dependency_lock_identity() {
    local worktree="$1" real
    real="$(fmix_realpath "$worktree")" || return 1
    (
        printf 'fmix-dependency-lock-v1\n'
        fmix_hash_compile_paths "$real" mix.lock || return 1
    ) | fmix_hash_stdin
}

fmix_compute_legacy_compile_fingerprint_v2() {
    local worktree="$1" real build_root
    real="$(fmix_realpath "$worktree")"
    build_root="$(fmix_compile_build_root "$real")"
    local -a compile_paths=(
        .tool-versions mix.exs mix.lock
        config/config.exs config/config_sync.exs config/test.exs
        lib test/support test/cdrcisco/policies/reputation_signals/shared
        vendor dev_tools
    )
    local -a repo_elixir_paths=()
    fmix_reject_repo_elixir_input_symlinks "$real" || return 1
    while IFS= read -r file; do
        repo_elixir_paths+=("${file#"$real/"}")
    done < <(find "$real/priv/repo" \( -type f -o -type l \) \
        -name '*.ex' -print 2>/dev/null | LC_ALL=C sort)
    {
        printf 'fmix-compile-fingerprint-v2\n'
        printf 'worktree=%s\n' "$real"
        printf 'build_root=%s\n' "$build_root"
        printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
        fmix_hash_compile_paths "$real" "${compile_paths[@]}" "${repo_elixir_paths[@]+"${repo_elixir_paths[@]}"}" || return 1
        fmix_declared_path_dependency_guard "$real" || return 1
        fmix_path_dependency_source_guard "$real" || return 1
        fmix_compile_environment "$real" || return 1
    } | fmix_hash_stdin
}

fmix_compute_legacy_dependency_fingerprint_v1() {
    local worktree="$1" real build_root
    real="$(fmix_realpath "$worktree")"
    build_root="$(fmix_compile_build_root "$real")"
    local -a dependency_paths=(
        .tool-versions mix.exs mix.lock vendor dev_tools
    )
    {
        printf 'fmix-dependency-fingerprint-v1\n'
        printf 'worktree=%s\n' "$real"
        printf 'build_root=%s\n' "$build_root"
        printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
        fmix_hash_compile_paths "$real" "${dependency_paths[@]}" || return 1
        fmix_declared_path_dependency_resolution_guard "$real" || return 1
        fmix_dependency_environment "$real" || return 1
    } | fmix_hash_stdin
}

fmix_discovered_environment_names() {
    local file
    for file in "$@"; do
        [[ -f "$file" ]] || continue
        sed '/^[[:space:]]*#/d' "$file" | tr '\n' ' '
        printf '\n'
    done | grep -oE 'System\.(get_env|fetch_env!?)[[:space:]]*[(]?[[:space:]]*"[A-Za-z0-9_]+"' \
        | grep -oE '"[A-Za-z0-9_]+"' | tr -d '"' | LC_ALL=C sort -u
}

fmix_environment_value() {
    local name="$1"
    if [[ "$name" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then
        printf '%s\n' "${!name-}"
    else
        printenv "$name" 2>/dev/null || true
    fi
}

fmix_emit_environment_fingerprint() {
    local name="$1" value="$2"
    printf '%s=' "$name"
    printf '%s' "$value" | fmix_hash_stdin
}

fmix_dependency_environment() {
    local worktree="$1" name value
    local discovered=""
    discovered="$(fmix_discovered_environment_names "$worktree/mix.exs")"

    fmix_emit_environment_fingerprint MIX_ENV test
    if [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]]; then
        fmix_emit_environment_fingerprint MIX_DEPS_PATH fmix-session-v1
    else
        fmix_emit_environment_fingerprint MIX_DEPS_PATH "${MIX_DEPS_PATH:-deps}"
    fi
    fmix_emit_environment_fingerprint MIX_TARGET "${MIX_TARGET:-host}"
    printf '%s\n' "$discovered" | sed '/^$/d' | LC_ALL=C sort -u | while IFS= read -r name; do
        case "$name" in
            MIX_ENV|MIX_DEPS_PATH|MIX_TARGET) ;;
            *)
                value="$(fmix_environment_value "$name")"
                fmix_emit_environment_fingerprint "$name" "$value"
                ;;
        esac
    done
}

fmix_compile_environment() {
    # Hash only values that can affect Mix/Elixir compilation or config
    # evaluation. Hashing the entire caller environment made session tokens,
    # terminal variables, and agent metadata trigger a full compile every run.
    local worktree="$1" name value
    local -a compiler_vars=(
        BUILD_VERSION ELIXIR_COMPILER_WORKERS ELIXIR_ERL_OPTIONS
        ERL_AFLAGS ERL_FLAGS ERL_ZFLAGS MIX_BUILD_PATH MIX_DEPS_PATH MIX_TARGET
        CC CXX CFLAGS CPPFLAGS LDFLAGS MACOSX_DEPLOYMENT_TARGET
        RUSTC RUSTFLAGS RUSTC_WRAPPER
    )
    local discovered=""
    discovered="$(fmix_discovered_environment_names \
        "$worktree/mix.exs" \
        "$worktree/config/config.exs" \
        "$worktree/config/config_sync.exs" \
        "$worktree/config/test.exs")"

    fmix_emit_environment_fingerprint MIX_ENV test
    fmix_emit_environment_fingerprint DB_HOSTNAME "$DB_HOST"
    fmix_emit_environment_fingerprint DB_PORT "$DB_PORT"
    fmix_emit_environment_fingerprint DB_USER "$DB_USER"
    fmix_emit_environment_fingerprint DB_PASSWORD "$DB_PASSWORD"
    fmix_emit_environment_fingerprint SECRET_KEY_BASE "$SECRET_KEY_BASE"
    fmix_emit_environment_fingerprint WORKER_NODE TRUE
    fmix_emit_environment_fingerprint ADMIN_NODE TRUE
    fmix_emit_environment_fingerprint ONPREM TRUE
    fmix_emit_environment_fingerprint MEESEEKS_HTML5EVER_BUILD 0
    fmix_emit_environment_fingerprint LOCAL_NATS "$NATS_HOST"
    fmix_emit_environment_fingerprint NATS_PORT "$NATS_PORT"
    fmix_emit_environment_fingerprint NATS_HOST "$NATS_HOST"
    fmix_emit_environment_fingerprint CT_NATS_HOST "$NATS_HOST"
    fmix_emit_environment_fingerprint NATS_URL "nats://${NATS_HOST}:${NATS_PORT}"
    printf '%s\n' "${compiler_vars[@]}" "$discovered" \
        | sed '/^$/d' | LC_ALL=C sort -u | while IFS= read -r name; do
        case "$name" in
            MIX_ENV|DB_HOSTNAME|DB_PORT|DB_USER|DB_PASSWORD|SECRET_KEY_BASE|WORKER_NODE|ADMIN_NODE|ONPREM|MEESEEKS_HTML5EVER_BUILD|LOCAL_NATS|NATS_PORT|NATS_HOST|CT_NATS_HOST|NATS_URL)
                # Effective fmix values were emitted above; ignore ambient copies.
                ;;
            MIX_BUILD_PATH|MIX_DEPS_PATH)
                if [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]]; then
                    fmix_emit_environment_fingerprint "$name" fmix-session-v1
                else
                    value="$(fmix_environment_value "$name")"
                    fmix_emit_environment_fingerprint "$name" "$value"
                fi
                ;;
            *)
                value="$(fmix_environment_value "$name")"
                fmix_emit_environment_fingerprint "$name" "$value"
                ;;
        esac
    done
}

fmix_compile_manifest_guard() {
    local worktree="$1" build_root app_mix app_ebin file found=0
    build_root="$(fmix_compile_build_root "$worktree")"
    app_mix="$build_root/test/lib/cdrcisco/.mix"
    app_ebin="$build_root/test/lib/cdrcisco/ebin"
    [[ -d "$app_mix" && -d "$app_ebin" ]] || return 1
    [[ -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" ]] || return 1

    {
        while IFS= read -r file; do
            found=1
            printf '%s:' "$(basename "$file")"
            fmix_hash_files "$file"
        done < <(find "$app_mix" -maxdepth 1 -type f -name 'compile.*' -print 2>/dev/null | LC_ALL=C sort)
        (( found == 1 )) || return 1
    } | fmix_hash_stdin
}

fmix_compile_stamp_file() {
    local worktree="$1"
    if [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]]; then
        printf '%s/compile-stamp.json\n' "$FMIX_ACTIVE_SESSION_ROOT"
        return 0
    fi
    printf '%s/compile-stamps/%s.json\n' "$FMIX_HOME" "$(fmix_worktree_id "$worktree")"
}

fmix_dependency_source_root() {
    local worktree="$1" real configured
    real="$(fmix_realpath "$worktree")"
    configured="${MIX_DEPS_PATH:-deps}"
    if [[ "$configured" == /* ]]; then
        printf '%s\n' "$configured"
    else
        printf '%s/%s\n' "$real" "$configured"
    fi
}

fmix_reject_nested_source_symlinks() {
    # Local dependency roots may themselves be symlinks (Mix commonly creates
    # those for path deps), so canonicalize the explicit root first. Beneath
    # that root, never follow or accept another symlink: its target could escape
    # the bounded compiler-input tree, form a cycle, or change without changing
    # the link identity recorded by Git.
    local root="$1" real probe symlink_path
    real="$(fmix_realpath "$root")" || return 1
    [[ -d "$real" ]] || return 1
    probe="$(mktemp)" || return 1
    if ! find "$real" \
        \( \( -type d -o -type l \) \
            \( -name .git -o -name _build -o -name deps -o \
                -name target -o -name c_build -o -name node_modules -o \
                -name .elixir_ls \) -prune \) -o \
        -type l -print -quit >"$probe" 2>/dev/null; then
        rm -f "$probe"
        return 1
    fi
    if [[ -s "$probe" ]]; then
        IFS= read -r symlink_path <"$probe" || symlink_path="$real"
        rm -f "$probe"
        fmix_error "Symlinked compiler input is unsupported: $symlink_path"
        return 1
    fi
    rm -f "$probe"
    return 0
}

fmix_dependency_source_guard() {
    local worktree="$1" deps_root
    deps_root="$(fmix_dependency_source_root "$worktree")"
    if [[ ! -d "$deps_root" ]]; then
        printf 'dependencies:none\n' | fmix_hash_stdin
        return 0
    fi

    local dependency_count=0 dependency marker path_real manifest
    local -a hex_markers=() source_files=()
    {
        while IFS= read -r dependency; do
            dependency_count=$(( dependency_count + 1 ))
            printf '%s\n' "$(basename "$dependency")"
            if [[ -f "$dependency/.hex" ]]; then
                fmix_reject_nested_source_symlinks "$dependency" || return 1
                hex_markers+=("$dependency/.hex")
            elif [[ -e "$dependency/.git" ]]; then
                fmix_hash_git_dependency "$dependency" || return 1
            elif [[ -f "$dependency/mix.exs" || -f "$dependency/rebar.config" \
                || -f "$dependency/Cargo.toml" || -f "$dependency/Makefile" ]]; then
                path_real="$(fmix_realpath "$dependency")" || return 1
                printf '.path-dependency:%s\n' "$path_real"
                for manifest in mix.exs rebar.config Cargo.toml Makefile; do
                    if [[ -f "$dependency/$manifest" ]]; then
                        fmix_hash_files "$dependency/$manifest" || return 1
                    fi
                done
                fmix_hash_path_dependency "$dependency" || return 1
            elif [[ -n "$(find "$dependency" -type f -print -quit 2>/dev/null)" ]]; then
                path_real="$(fmix_realpath "$dependency")" || return 1
                printf '.custom-path-dependency:%s\n' "$path_real"
                fmix_hash_path_dependency "$dependency" || return 1
            else
                return 1
            fi
        done < <(
            find "$deps_root" -mindepth 1 -maxdepth 1 \( -type d -o -type l \) \
                -print 2>/dev/null | LC_ALL=C sort
        )
        if (( dependency_count == 0 )); then
            printf 'dependencies:none\n'
        fi
        if (( ${#hex_markers[@]} > 0 )); then
            fmix_hash_files "${hex_markers[@]}" || return 1
        fi

        while IFS= read -r marker; do
            printf 'source:%s\n' "${marker#"$deps_root/"}"
            source_files+=("$marker")
        done < <(
            find "$deps_root" \
                \( -type d \( -name .git -o -name _build -o -name target -o \
                    -name c_build -o -name node_modules -o -name .elixir_ls \) -prune \) -o \
                -type f \
                \( -name '*.ex' -o -name '*.exs' -o -name '*.erl' -o -name '*.hrl' \
                   -o -name '*.c' -o -name '*.h' -o -name '*.cpp' -o -name '*.rs' \
                   -o -name 'Cargo.toml' -o -name 'mix.exs' -o -name 'rebar.config' \
                   -o -name 'Makefile' \) \
                -print 2>/dev/null | LC_ALL=C sort
        )
        if (( ${#source_files[@]} > 0 )); then
            fmix_hash_file_batches "${source_files[@]}" || return 1
        fi
    } | fmix_hash_stdin
}

fmix_hash_path_dependency() {
    local dependency="$1" path_real file
    local -a files=()
    path_real="$(fmix_realpath "$dependency")" || return 1
    fmix_reject_nested_source_symlinks "$path_real" || return 1

    while IFS= read -r file; do
        files+=("$file")
    done < <(
        find "$path_real" \
            \( -type d \( -name .git -o -name _build -o -name deps -o \
                -name target -o -name c_build -o -name node_modules -o \
                -name .elixir_ls \) -prune \) -o \
            -type f -print 2>/dev/null | LC_ALL=C sort
    )

    printf '.path-source-root:%s\n' "$path_real"
    if (( ${#files[@]} > 0 )); then
        fmix_hash_file_batches "${files[@]}" || return 1
    fi
}

fmix_declared_path_dependency_guard() {
    local worktree="$1" source declared_count literal_count path target
    local -a paths=()
    [[ -f "$worktree/mix.exs" ]] || return 1
    source="$(sed '/^[[:space:]]*#/d' "$worktree/mix.exs" | tr '\n' ' ')"
    declared_count="$(printf '%s' "$source" \
        | grep -oE '(^|[^[:alnum:]_])path[[:space:]]*:' 2>/dev/null \
        | wc -l | tr -d ' ')"
    while IFS= read -r path; do
        [[ -n "$path" ]] && paths+=("$path")
    done < <(
        printf '%s' "$source" \
            | grep -oE '(^|[^[:alnum:]_])path[[:space:]]*:[[:space:]]*"[^"\\]*"' 2>/dev/null \
            | sed -E 's/^.*path[[:space:]]*:[[:space:]]*"([^"]*)"$/\1/'
    )
    literal_count="${#paths[@]}"
    (( declared_count == literal_count )) || return 1

    if (( literal_count == 0 )); then
        printf 'declared-path-dependencies:none\n'
        return 0
    fi

    for path in "${paths[@]}"; do
        if [[ "$path" == /* ]]; then
            target="$path"
        else
            target="$worktree/$path"
        fi
        [[ -d "$target" ]] || return 1
        printf 'declared-path-dependency:%s\n' "$path"
        fmix_hash_path_dependency "$target" || return 1
    done
}

fmix_declared_path_dependency_resolution_guard() {
    local worktree="$1" source declared_count literal_count path target manifest found
    local -a paths=()
    [[ -f "$worktree/mix.exs" ]] || return 1
    source="$(sed '/^[[:space:]]*#/d' "$worktree/mix.exs" | tr '\n' ' ')"
    declared_count="$(printf '%s' "$source" \
        | grep -oE '(^|[^[:alnum:]_])path[[:space:]]*:' 2>/dev/null \
        | wc -l | tr -d ' ')"
    while IFS= read -r path; do
        [[ -n "$path" ]] && paths+=("$path")
    done < <(
        printf '%s' "$source" \
            | grep -oE '(^|[^[:alnum:]_])path[[:space:]]*:[[:space:]]*"[^"\\]*"' 2>/dev/null \
            | sed -E 's/^.*path[[:space:]]*:[[:space:]]*"([^"]*)"$/\1/'
    )
    literal_count="${#paths[@]}"
    (( declared_count == literal_count )) || return 1

    if (( literal_count == 0 )); then
        printf 'declared-path-resolution:none\n'
        return 0
    fi

    for path in "${paths[@]}"; do
        if [[ "$path" == /* ]]; then
            target="$path"
        else
            target="$worktree/$path"
        fi
        [[ -d "$target" ]] || return 1
        printf 'declared-path-resolution:%s\n' "$path"
        found=0
        for manifest in .tool-versions mix.exs mix.lock rebar.config rebar.lock \
            Cargo.toml Cargo.lock Makefile; do
            if [[ -f "$target/$manifest" ]]; then
                found=1
                printf 'resolution-manifest:%s:' "$manifest"
                fmix_hash_files "$target/$manifest" || return 1
            fi
        done
        (( found == 1 )) || return 1
    done
}

fmix_hash_git_dependency() {
    local dependency="$1" commit diff_hash file untracked_file
    local -a untracked=()
    fmix_reject_nested_source_symlinks "$dependency" || return 1
    commit="$(git -C "$dependency" rev-parse HEAD 2>/dev/null)" || return 1
    [[ -n "$commit" ]] || return 1
    printf '.git-commit:%s\n' "$commit"

    diff_hash="$(git -C "$dependency" diff --no-ext-diff --binary HEAD 2>/dev/null \
        | fmix_hash_stdin)" || return 1
    printf '.git-worktree-diff:%s\n' "$diff_hash"

    untracked_file="$(mktemp)" || return 1
    if ! git -C "$dependency" ls-files --others --exclude-standard -z \
        >"$untracked_file" 2>/dev/null; then
        rm -f "$untracked_file"
        return 1
    fi
    while IFS= read -r -d '' file; do
        untracked+=("$dependency/$file")
    done <"$untracked_file"
    rm -f "$untracked_file"
    if (( ${#untracked[@]} > 0 )); then
        printf '.git-untracked-count:%s\n' "${#untracked[@]}"
        fmix_hash_file_batches "${untracked[@]}" || return 1
    fi
}

fmix_path_dependency_source_guard() {
    local worktree="$1" deps_root dependency found=0
    deps_root="$(fmix_dependency_source_root "$worktree")"
    if [[ ! -d "$deps_root" ]]; then
        printf 'path-dependencies:none\n'
        return 0
    fi

    while IFS= read -r dependency; do
        if [[ -f "$dependency/.hex" ]]; then
            continue
        elif [[ -e "$dependency/.git" ]]; then
            found=1
            printf 'git-dependency:%s\n' "$(basename "$dependency")"
            fmix_hash_git_dependency "$dependency" || return 1
        elif { [[ -f "$dependency/mix.exs" || -f "$dependency/rebar.config" \
                || -f "$dependency/Cargo.toml" || -f "$dependency/Makefile" ]] \
                || [[ -n "$(find "$dependency" -type f -print -quit 2>/dev/null)" ]]; }; then
            found=1
            printf 'path-dependency:%s\n' "$(basename "$dependency")"
            fmix_hash_path_dependency "$dependency" || return 1
        fi
    done < <(
        find "$deps_root" -mindepth 1 -maxdepth 1 \( -type d -o -type l \) \
            -print 2>/dev/null | LC_ALL=C sort
    )

    if (( found == 0 )); then
        printf 'path-dependencies:none\n'
    fi
    return 0
}

fmix_dependency_stamp_file() {
    local worktree="$1"
    if [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]]; then
        printf '%s/dependency-stamp.json\n' "$FMIX_ACTIVE_SESSION_ROOT"
        return 0
    fi
    printf '%s/dependency-stamps/%s.json\n' "$FMIX_HOME" "$(fmix_worktree_id "$worktree")"
}

fmix_write_dependency_stamp() {
    local worktree="${1:-}" fingerprint="${2:-}" lane
    (( $# == 2 )) && [[ "$fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
    lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
    [[ "$lane" =~ ^[0-9a-f]{64}$ ]] || return 1
    fmix_with_artifact_reference_lease "dependency-artifact-${lane:0:16}-${fingerprint:0:16}" \
        _fmix_write_dependency_stamp_locked "$@"
}

_fmix_write_dependency_stamp_locked() {
    local worktree="$1" dependency_fingerprint="$2" real build_root guard stamp tmp
    local reconciliation_guard lock_identity
    real="$(fmix_realpath "$worktree")"
    build_root="$(fmix_compile_build_root "$real")"
    guard="$(fmix_dependency_source_guard "$real")" || return 1
    reconciliation_guard="$(
        fmix_compute_dependency_reconciliation_guard "$real"
    )" || return 1
    lock_identity="$(fmix_compute_dependency_lock_identity "$real")" || return 1
    stamp="$(fmix_dependency_stamp_file "$real")"
    mkdir -p "$(dirname "$stamp")"
    tmp="$(mktemp "${stamp}.tmp.XXXXXX")" || return 1
    if ! cat >"$tmp" <<EOF
{
  "path": $(fmix_json_escape "$real"),
  "build_root": $(fmix_json_escape "$build_root"),
  "dependency_fingerprint": $(fmix_json_escape "$dependency_fingerprint"),
  "reconciliation_guard": $(fmix_json_escape "$reconciliation_guard"),
  "lock_identity": $(fmix_json_escape "$lock_identity"),
  "source_guard": $(fmix_json_escape "$guard"),
  "resolved_at": $(fmix_json_escape "$(fmix_now)")
}
EOF
    then
        rm -f "$tmp"
        return 1
    fi
    mv "$tmp" "$stamp" || { rm -f "$tmp"; return 1; }
}

# Cheap invalidator for the warm path: content hashes of lock/config manifests
# plus the newest mtime under compile roots. Avoids walking deps/ and hashing
# the full lib/ tree on every stamp-hit run (was ~8–10s of the compile phase).
fmix_compile_quick_guard() {
    local worktree="$1" real py_bin
    real="$(fmix_realpath "$worktree")" || return 1
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    "$py_bin" - "$real" <<'PY'
import hashlib, os, sys
from pathlib import Path

root = Path(sys.argv[1])
h = hashlib.sha256()
h.update(b"fmix-compile-quick-guard-v2\n")

def add_file(rel: str) -> None:
    p = root / rel
    h.update(rel.encode())
    h.update(b"\0")
    if p.is_file():
        h.update(p.read_bytes())
    h.update(b"\n")

for rel in (
    ".tool-versions",
    "mix.exs",
    "mix.lock",
    "config/config.exs",
    "config/config_sync.exs",
    "config/test.exs",
):
    add_file(rel)

# Per-file stat manifest (path -> dev,ino,mtime_ns,size) under compile roots.
# Replaces the old single max-mtime: adds, removes, replaces, and leaf edits
# all change the folded record set, while an unchanged stat tuple proves no
# re-hash is needed. Sorted for cross-process determinism; a stat anomaly is
# folded in as its own marker so it can never masquerade as stability.
stat_records = []
for rel in (
    "lib",
    "test/support",
    "test/cdrcisco/policies/reputation_signals/shared",
    "vendor",
    "dev_tools",
    "priv/repo",
):
    base = root / rel
    if not base.exists():
        continue
    if base.is_file():
        try:
            st = base.stat()
            stat_records.append(f"{rel}\0{st.st_dev},{st.st_ino},{st.st_mtime_ns},{st.st_size}\n")
        except OSError:
            stat_records.append(f"{rel}\0stat-error\n")
        continue
    for dirpath, dirnames, filenames in os.walk(base):
        # Skip heavy/irrelevant trees
        dirnames[:] = [d for d in dirnames if d not in {".git", "_build", "node_modules", "deps"}]
        for name in filenames:
            if not name.endswith((".ex", ".exs", ".heex", ".eex", ".leex", ".erl", ".hrl", ".c", ".h", ".rs", ".toml")):
                continue
            full = os.path.join(dirpath, name)
            rel_path = os.path.relpath(full, root)
            try:
                st = os.stat(full)
                stat_records.append(f"{rel_path}\0{st.st_dev},{st.st_ino},{st.st_mtime_ns},{st.st_size}\n")
            except OSError:
                stat_records.append(f"{rel_path}\0stat-error\n")

for stat_record in sorted(stat_records):
    h.update(stat_record.encode())
# Top-level deps dir signature (count + names + mtimes) — cheap vs full source_guard.
deps = root  # MIX_DEPS_PATH may be external; prefer env
deps_path = os.environ.get("MIX_DEPS_PATH") or str(root / "deps")
deps_root = Path(deps_path)
if deps_root.is_dir():
    names = []
    for child in sorted(deps_root.iterdir()):
        if not child.name.startswith("."):
            try:
                names.append(f"{child.name}:{int(child.stat().st_mtime)}")
            except OSError:
                names.append(child.name)
    h.update(("deps:" + ",".join(names) + "\n").encode())
else:
    h.update(b"deps:absent\n")

print(h.hexdigest())
PY
    [[ $? -eq 0 ]] || return 1
}

fmix_get_git_tree_hash() {
    local worktree="$1" real tree_hash
    real="$(fmix_realpath "$worktree" 2>/dev/null)" || return 1
    if [[ -d "$real/.git" || -f "$real/.git" ]]; then
        command -v git >/dev/null 2>&1 || return 1
        tree_hash="$(git -C "$real" rev-parse HEAD^{tree} 2>/dev/null)" \
            || return 1
        [[ "$tree_hash" =~ ^[0-9a-f]{40}$ ]] || return 1
        printf '%s\n' "$tree_hash"
        return 0
    fi
    printf 'unknown\n'
}

fmix_compute_compile_env_hash() {
    local worktree="$1" real toolchain_identity
    real="$(fmix_realpath "$worktree" 2>/dev/null || echo "$worktree")"
    toolchain_identity="${FMIX_TOOLCHAIN_IDENTITY:-}"
    if [[ -z "$toolchain_identity" ]]; then
        toolchain_identity="$(fmix_resolved_toolchain_identity "$real" 2>/dev/null || echo "")"
    fi
    (
        printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
        printf 'toolchain=%s\n' "$toolchain_identity"
        printf 'MIX_ENV=%s\n' "${MIX_ENV:-test}"
        printf 'MIX_TARGET=%s\n' "${MIX_TARGET:-host}"
        printf 'ERL_COMPILER_OPTIONS=%s\n' "${ERL_COMPILER_OPTIONS:-}"
        printf 'ELIXIR_ERL_OPTIONS=%s\n' "${ELIXIR_ERL_OPTIONS:-}"
    ) | fmix_hash_stdin
}

fmix_compute_dirty_hash() {
    local worktree="$1" real status manifest hash rc file
    local untracked_file diff_file staged_file
    local -a untracked=()
    shift
    local -a target_paths=("$@")
    if (( ${#target_paths[@]} == 0 )); then
        target_paths=(
            .tool-versions mix.exs mix.lock
            config lib test/support test/cdrcisco/policies/reputation_signals/shared
            vendor dev_tools priv/repo
        )
    fi
    real="$(fmix_realpath "$worktree" 2>/dev/null)" || return 1
    if [[ ! -d "$real/.git" && ! -f "$real/.git" ]]; then
        printf 'clean\n'
        return 0
    fi
    command -v git >/dev/null 2>&1 || return 1
    git -C "$real" rev-parse --is-inside-work-tree >/dev/null 2>&1 \
        || return 1
    status="$(git -C "$real" status --porcelain=v1 -- "${target_paths[@]}" 2>/dev/null)" || return 1
    if [[ -z "$status" ]]; then
        printf 'clean\n'
        return 0
    fi
    manifest="$(mktemp)" || return 1
    untracked_file="$(mktemp)" || { rm -f "$manifest"; return 1; }
    diff_file="$(mktemp)" \
        || { rm -f "$manifest" "$untracked_file"; return 1; }
    staged_file="$(mktemp)" \
        || { rm -f "$manifest" "$untracked_file" "$diff_file"; return 1; }
    if ! git -C "$real" ls-files --others --exclude-standard -z -- "${target_paths[@]}" \
        >"$untracked_file" 2>/dev/null; then
        rm -f "$manifest" "$untracked_file" "$diff_file" "$staged_file"
        return 1
    fi
    if ! git -C "$real" diff --no-ext-diff --binary -- "${target_paths[@]}" \
        >"$diff_file" 2>/dev/null; then
        rm -f "$manifest" "$untracked_file" "$diff_file" "$staged_file"
        return 1
    fi
    if ! git -C "$real" diff --cached --no-ext-diff --binary -- "${target_paths[@]}" \
        >"$staged_file" 2>/dev/null; then
        rm -f "$manifest" "$untracked_file" "$diff_file" "$staged_file"
        return 1
    fi
    while IFS= read -r -d '' file; do
        untracked+=("$file")
    done <"$untracked_file"
    (
        printf '%s\n' "$status"
        cat "$diff_file" || exit 1
        cat "$staged_file" || exit 1
        local -a untracked_pairs=()
        for file in "${untracked[@]+"${untracked[@]}"}"; do
            untracked_pairs+=("$file" "$real/$file")
        done
        fmix_hash_paired_lines "untracked" \
            "${untracked_pairs[@]+"${untracked_pairs[@]}"}" || exit 1
    ) >"$manifest"
    rc=$?
    rm -f "$untracked_file" "$diff_file" "$staged_file"
    if (( rc != 0 )); then
        rm -f "$manifest"
        return "$rc"
    fi
    hash="$(fmix_hash_stdin <"$manifest")"
    rc=$?
    rm -f "$manifest"
    (( rc == 0 )) || return "$rc"
    [[ "$hash" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s\n' "$hash"
}

fmix_write_compile_stamp() {
    local key
    (( $# == 2 )) || return 1
    key="$(fmix_compute_template_key "$1" 2>/dev/null)" || key=""
    if [[ "$key" =~ ^[0-9a-f]{16}$ ]]; then
        fmix_with_artifact_reference_lease "build-$key" _fmix_write_compile_stamp_locked "$@" "$key"
    else
        _fmix_write_compile_stamp_locked "$@" ""
    fi
}

_fmix_write_compile_stamp_locked() {
    local worktree="$1" fingerprint="$2" real build_root guard dependency_guard stamp tmp quick_guard template_key
    local template_key tree_hash env_hash dirty_hash ignored_compile_hash source_stability_identity
    local stat_manifest
    real="$(fmix_realpath "$worktree")"
    build_root="$(fmix_compile_build_root "$real")"
    guard="$(fmix_compile_manifest_guard "$real")" || return 1
    dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
    quick_guard="$(fmix_compile_quick_guard "$real")" || return 1
    if (( $# >= 3 )); then
        template_key="${3:-}"
    else
        template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
    fi
    tree_hash="$(fmix_get_git_tree_hash "$real")" || return 1
    env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
    dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null)" || return 1
    ignored_compile_hash="$(fmix_ignored_compile_inputs_hash "$real" 2>/dev/null)" \
        || return 1
    source_stability_identity="${FMIX_SOURCE_STABILITY_COMPILE_IDENTITY:-}"
    stat_manifest="$(fmix_stat_hash_cache_dump 2>/dev/null)" || stat_manifest=""
    stamp="$(fmix_compile_stamp_file "$real")"
    mkdir -p "$(dirname "$stamp")"
    tmp="$(mktemp "${stamp}.tmp.XXXXXX")" || return 1
    if ! cat >"$tmp" <<EOF
{
  "schema_version": 2,
  "path": $(fmix_json_escape "$real"),
  "build_root": $(fmix_json_escape "$build_root"),
  "template_key": $(fmix_json_escape "$template_key"),
  "git_tree_hash": $(fmix_json_escape "$tree_hash"),
  "compile_env_hash": $(fmix_json_escape "$env_hash"),
  "dirty_hash": $(fmix_json_escape "$dirty_hash"),
  "ignored_compile_hash": $(fmix_json_escape "$ignored_compile_hash"),
  "fingerprint": $(fmix_json_escape "$fingerprint"),
  "manifest_guard": $(fmix_json_escape "$guard"),
  "dependency_source_guard": $(fmix_json_escape "$dependency_guard"),
  "quick_guard": $(fmix_json_escape "$quick_guard"),
  "stat_manifest": $(fmix_json_escape "$stat_manifest"),
  "source_stability_identity": $(fmix_json_escape "$source_stability_identity"),
  "source_stability_run_identity": $(fmix_json_escape "${FMIX_SOURCE_STABILITY_IDENTITY:-}"),
  "source_stability_args_hash": $(fmix_json_escape "${FMIX_SOURCE_STABILITY_ARGS_HASH:-}"),
  "compiled_at": $(fmix_json_escape "$(fmix_now)")
}
EOF
    then
        rm -f "$tmp"
        return 1
    fi
    mv "$tmp" "$stamp" || { rm -f "$tmp"; return 1; }
}

# Warm-path staged admission: cheap invalidators reject obvious drift before
# bounded live-content and dependency-source guards authorize artifact reuse.
fmix_try_compile_stamp_quick_hit() {
    local worktree="$1" real build_root stamp dependency_stamp dependency_fingerprint
    local recorded_path recorded_build recorded_quick current_quick
    local recorded_tree_hash current_tree_hash recorded_dirty_hash current_dirty_hash
    local recorded_ignored_compile_hash current_ignored_compile_hash
    local recorded_fingerprint current_fingerprint
    local recorded_dependency_guard current_dependency_guard dependency_stamp_guard
    local recorded_source_stability_identity
    local app_ebin
    real="$(fmix_realpath "$worktree")" || return 1
    build_root="$(fmix_compile_build_root "$real")" || return 1
    stamp="$(fmix_compile_stamp_file "$real")"
    [[ -f "$stamp" ]] || return 1
    # A deps tree missing a native dep's NIF is never a quick hit; the slower
    # (mutating) path repairs it.
    [[ -z "$(fmix_native_deps_missing_so "$(fmix_session_deps_root "$real")")" ]] \
        || return 1
    recorded_path="$(fmix_read_state "$stamp" path)"
    recorded_build="$(fmix_read_state "$stamp" build_root)"
    recorded_quick="$(fmix_read_state "$stamp" quick_guard)"
    recorded_tree_hash="$(fmix_read_state "$stamp" git_tree_hash)"
    recorded_dirty_hash="$(fmix_read_state "$stamp" dirty_hash)"
    recorded_ignored_compile_hash="$(fmix_read_state "$stamp" ignored_compile_hash)"
    recorded_fingerprint="$(fmix_read_state "$stamp" fingerprint)"
    recorded_dependency_guard="$(fmix_read_state "$stamp" dependency_source_guard)"
    recorded_source_stability_identity="$(fmix_read_state "$stamp" source_stability_identity)"
    [[ "$recorded_path" == "$real" ]] || return 1
    [[ "$recorded_build" == "$build_root" ]] || return 1
    [[ -n "$recorded_quick" ]] || return 1
    [[ -n "$recorded_tree_hash" && "$recorded_tree_hash" != "unknown" ]] || return 1
    [[ -n "$recorded_dirty_hash" ]] || return 1
    [[ "$recorded_fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
    [[ "$recorded_dependency_guard" =~ ^[0-9a-f]{64}$ ]] || return 1
    [[ "$recorded_ignored_compile_hash" =~ ^[0-9a-f]{64}$ \
        || "$recorded_ignored_compile_hash" == "non-git" ]] || return 1
    if [[ "${FMIX_SOURCE_STABILITY_REQUIRED:-0}" == "1" ]]; then
        [[ "${FMIX_SOURCE_STABILITY_COMPILE_IDENTITY:-}" =~ ^[0-9a-f]{64}$ ]] || return 1
        [[ "$recorded_source_stability_identity" \
            == "$FMIX_SOURCE_STABILITY_COMPILE_IDENTITY" ]] || return 1
    fi
    app_ebin="$build_root/test/lib/cdrcisco/ebin"
    [[ -d "$app_ebin" ]] || return 1
    [[ -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" ]] || return 1
    current_quick="$(fmix_compile_quick_guard "$real")" || return 1
    [[ "$recorded_quick" == "$current_quick" ]] || return 1
    current_tree_hash="$(fmix_get_git_tree_hash "$real")" || return 1
    [[ "$current_tree_hash" != "unknown" \
        && "$recorded_tree_hash" == "$current_tree_hash" ]] || return 1
    current_dirty_hash="$(fmix_compute_dirty_hash "$real")" || return 1
    [[ "$recorded_dirty_hash" == "$current_dirty_hash" ]] || return 1
    current_ignored_compile_hash="$(fmix_ignored_compile_inputs_hash "$real")" \
        || return 1
    [[ "$recorded_ignored_compile_hash" == "$current_ignored_compile_hash" ]] \
        || return 1
    # Git's status/index stat cache and the mtime quick guard are only early
    # rejectors. Admission is content-exact for the bounded compiler inputs.
    # The recorded per-file stat manifest is an early rejector too: entries
    # whose stat tuple is unchanged reuse their recorded digest and only drift
    # is content-hashed. Any manifest anomaly (missing field on old stamps,
    # undecodable payload, stat/read errors) falls back to the full-hash path
    # below, so admission can never become weaker than a full recompute.
    current_fingerprint=""
    if fmix_stat_hash_cache_use "$real"; then
        if fmix_stat_hash_cache_seed "$(fmix_read_state "$stamp" stat_manifest)"; then
            current_fingerprint="$(fmix_compute_compile_fingerprint "$real")" \
                || current_fingerprint=""
        fi
        fmix_stat_hash_cache_done
    fi
    if [[ -z "$current_fingerprint" ]]; then
        current_fingerprint="$(fmix_compute_compile_fingerprint "$real")" || return 1
    fi
    [[ "$recorded_fingerprint" == "$current_fingerprint" ]] || return 1
    current_dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
    [[ "$recorded_dependency_guard" == "$current_dependency_guard" ]] || return 1
    # A quick hit must not accept a stale or partial dependency checkpoint.
    dependency_stamp="$(fmix_dependency_stamp_file "$real")"
    [[ -f "$dependency_stamp" ]] || return 1
    dependency_fingerprint="$(fmix_read_state "$dependency_stamp" dependency_fingerprint)"
    dependency_stamp_guard="$(fmix_read_state "$dependency_stamp" source_guard)"
    [[ "$dependency_fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
    [[ "$dependency_stamp_guard" == "$current_dependency_guard" ]] || return 1
    return 0
}

fmix_dependency_stamp_matches() {
    local worktree="$1" dependency_fingerprint="$2" real build_root stamp
    local recorded_path recorded_build recorded_dependency_fingerprint recorded_guard current_guard
    real="$(fmix_realpath "$worktree")"
    build_root="$(fmix_compile_build_root "$real")"
    stamp="$(fmix_dependency_stamp_file "$real")"
    [[ -f "$stamp" ]] || return 1
    recorded_path="$(fmix_read_state "$stamp" path)"
    recorded_build="$(fmix_read_state "$stamp" build_root)"
    recorded_dependency_fingerprint="$(fmix_read_state "$stamp" dependency_fingerprint)"
    recorded_guard="$(fmix_read_state "$stamp" source_guard)"
    [[ "$recorded_path" == "$real" ]] || return 1
    [[ "$recorded_build" == "$build_root" ]] || return 1
    [[ -n "$recorded_dependency_fingerprint" ]] || return 1
    [[ "$recorded_dependency_fingerprint" == "$dependency_fingerprint" ]] || return 1
    current_guard="$(fmix_dependency_source_guard "$real")" || return 1
    [[ -n "$recorded_guard" && "$recorded_guard" == "$current_guard" ]]
}

fmix_compile_stamp_matches() {
    local worktree="$1" fingerprint="$2" real build_root deps_root stamp
    local recorded_schema recorded_path recorded_build recorded_fingerprint recorded_guard current_guard
    local recorded_dependency_guard current_dependency_guard
    local recorded_template_key recorded_tree_hash recorded_env_hash recorded_dirty_hash
    local recorded_ignored_compile_hash current_ignored_compile_hash
    local recorded_source_stability_identity
    real="$(fmix_realpath "$worktree")"
    build_root="$(fmix_compile_build_root "$real")"
    stamp="$(fmix_compile_stamp_file "$real")"
    [[ -f "$stamp" ]] || return 1
    
    recorded_schema="$(fmix_read_state "$stamp" schema_version)"
    recorded_path="$(fmix_read_state "$stamp" path)"
    recorded_build="$(fmix_read_state "$stamp" build_root)"
    recorded_fingerprint="$(fmix_read_state "$stamp" fingerprint)"
    recorded_guard="$(fmix_read_state "$stamp" manifest_guard)"
    recorded_dependency_guard="$(fmix_read_state "$stamp" dependency_source_guard)"
    recorded_source_stability_identity="$(fmix_read_state "$stamp" source_stability_identity)"
    if [[ "${FMIX_SOURCE_STABILITY_REQUIRED:-0}" == "1" ]]; then
        [[ "${FMIX_SOURCE_STABILITY_COMPILE_IDENTITY:-}" =~ ^[0-9a-f]{64}$ ]] || return 1
        [[ "$recorded_source_stability_identity" \
            == "$FMIX_SOURCE_STABILITY_COMPILE_IDENTITY" ]] || return 1
    fi

    # Schema v2 content-identity matching (Patch 3)
    if [[ "$recorded_schema" == "2" ]]; then
        recorded_template_key="$(fmix_read_state "$stamp" template_key)"
        recorded_tree_hash="$(fmix_read_state "$stamp" git_tree_hash)"
        recorded_env_hash="$(fmix_read_state "$stamp" compile_env_hash)"
        recorded_dirty_hash="$(fmix_read_state "$stamp" dirty_hash)"
        recorded_ignored_compile_hash="$(fmix_read_state "$stamp" ignored_compile_hash)"

        local current_template_key current_tree_hash current_env_hash current_dirty_hash
        # The override lets artifact adoption prove a v4-stamped session against
        # the key it was actually stamped with (see
        # fmix_adopt_compatible_worktree_artifacts).
        current_template_key="${FMIX_COMPILE_STAMP_KEY_OVERRIDE:-$(fmix_compute_template_key "$real" 2>/dev/null || echo "")}"
        current_tree_hash="$(fmix_get_git_tree_hash "$real")" || return 1
        current_env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
        current_dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null)" \
            || return 1
        current_ignored_compile_hash="$(fmix_ignored_compile_inputs_hash "$real" 2>/dev/null)" \
            || return 1
        current_dependency_guard="$(fmix_dependency_source_guard "$real")" \
            || return 1

        if [[ "$recorded_tree_hash" != "unknown" && "$current_tree_hash" != "unknown" ]]; then
            # template_key is compared for equality rather than required to be
            # non-empty. fmix_compute_template_key returns empty when the
            # toolchain cannot be resolved, and requiring non-empty turned that
            # into a stamp that could NEVER match -- a permanently poisoned cache
            # entry rather than a miss. Identity is still enforced: tree hash and
            # env hash must both be present and equal, and env hash already
            # covers the resolved toolchain, OS/arch and MIX_ENV.
            if [[ "$recorded_template_key" == "$current_template_key" \
                && -n "$recorded_tree_hash" && "$recorded_tree_hash" == "$current_tree_hash" \
                && -n "$recorded_env_hash" && "$recorded_env_hash" == "$current_env_hash" \
                && "$recorded_dirty_hash" == "$current_dirty_hash" \
                && "$recorded_ignored_compile_hash" == "$current_ignored_compile_hash" \
                && "$recorded_fingerprint" == "$fingerprint" \
                && -n "$recorded_dependency_guard" \
                && "$recorded_dependency_guard" == "$current_dependency_guard" ]]; then
                local app_ebin="$build_root/test/lib/cdrcisco/ebin"
                if [[ -d "$app_ebin" ]] && [[ -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" ]]; then
                    return 0
                fi
            fi
            return 1
        fi
    fi

    # Legacy v1 dual-read fallback:
    if [[ "$recorded_path" != "$real" ]] || [[ "$recorded_build" != "$build_root" ]]; then
        return 1
    fi
    [[ "$recorded_fingerprint" == "$fingerprint" ]] || return 1
    current_guard="$(fmix_compile_manifest_guard "$real")" || return 1
    [[ -n "$recorded_guard" && "$recorded_guard" == "$current_guard" ]] || return 1

    deps_root="$(fmix_dependency_source_root "$real")"
    if [[ -d "$deps_root" ]]; then
        [[ -n "$recorded_dependency_guard" ]] || return 1
        current_dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
        [[ "$recorded_dependency_guard" == "$current_dependency_guard" ]] || return 1
    fi
    return 0
}

fmix_legacy_artifact_stamps_match() {
    # FMix 1.4.x forced the repo's asdf shims ahead of ambient runtimes and
    # keyed these stamps by the exact declared .tool-versions. FMix 1.5 first
    # verifies that active runtime exactly, then this reader additionally
    # requires both old fingerprints and both live artifact guards to match.
    # A merely similar template, missing stamp, source edit, dependency edit,
    # moved worktree, or damaged Mix manifest therefore fails closed.
    local worktree="$1" real build_root dependency_stamp compile_stamp
    local expected_dependency expected_compile current_dependency_guard
    local current_manifest_guard recorded_dependency_guard
    real="$(fmix_realpath "$worktree")"
    build_root="$(fmix_compile_build_root "$real")"
    dependency_stamp="$(fmix_dependency_stamp_file "$real")"
    compile_stamp="$(fmix_compile_stamp_file "$real")"
    [[ -f "$dependency_stamp" && -f "$compile_stamp" ]] || return 1

    expected_dependency="$(fmix_compute_legacy_dependency_fingerprint_v1 "$real")" \
        || return 1
    expected_compile="$(fmix_compute_legacy_compile_fingerprint_v2 "$real")" \
        || return 1
    current_dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
    current_manifest_guard="$(fmix_compile_manifest_guard "$real")" || return 1

    [[ "$(fmix_read_state "$dependency_stamp" path)" == "$real" ]] || return 1
    [[ "$(fmix_read_state "$dependency_stamp" build_root)" == "$build_root" ]] || return 1
    [[ "$(fmix_read_state "$dependency_stamp" dependency_fingerprint)" \
        == "$expected_dependency" ]] || return 1
    [[ "$(fmix_read_state "$dependency_stamp" source_guard)" \
        == "$current_dependency_guard" ]] || return 1

    [[ "$(fmix_read_state "$compile_stamp" path)" == "$real" ]] || return 1
    [[ "$(fmix_read_state "$compile_stamp" build_root)" == "$build_root" ]] || return 1
    [[ "$(fmix_read_state "$compile_stamp" fingerprint)" == "$expected_compile" ]] \
        || return 1
    [[ "$(fmix_read_state "$compile_stamp" manifest_guard)" \
        == "$current_manifest_guard" ]] || return 1
    recorded_dependency_guard="$(
        fmix_read_state "$compile_stamp" dependency_source_guard
    )"
    [[ -n "$recorded_dependency_guard" \
        && "$recorded_dependency_guard" == "$current_dependency_guard" ]]
}

fmix_update_worktree_template_key() {
    local worktree="$1" recorded_key="$2" template_key="$3"
    local real state_file artifact_state_file key_state_file tmp
    [[ "$recorded_key" =~ ^[0-9a-f]{16}$ \
        && "$template_key" =~ ^[0-9a-f]{16}$ ]] || return 1
    real="$(fmix_realpath "$worktree")"
    state_file="$(fmix_worktree_state_file "$real")"
    artifact_state_file="$(fmix_artifact_state_file "$real")"
    if [[ -f "$artifact_state_file" ]]; then
        key_state_file="$artifact_state_file"
    else
        key_state_file="$state_file"
    fi
    [[ -f "$key_state_file" ]] || return 1
    [[ "$(fmix_read_state "$key_state_file" path)" == "$real" ]] || return 1
    [[ "$(fmix_read_state "$key_state_file" template_key)" == "$recorded_key" ]] \
        || return 1
    [[ "$(grep -cF "\"template_key\": \"$recorded_key\"" "$key_state_file")" == "1" ]] \
        || return 1
    tmp="$(mktemp "${key_state_file}.tmp.XXXXXX")" || return 1
    if ! sed "s/\"template_key\": \"$recorded_key\"/\"template_key\": \"$template_key\"/" \
        "$key_state_file" >"$tmp"; then
        rm -f "$tmp"
        return 1
    fi
    if [[ "$(fmix_read_state "$tmp" path)" != "$real" \
        || "$(fmix_read_state "$tmp" template_key)" != "$template_key" ]]; then
        rm -f "$tmp"
        return 1
    fi
    mv "$tmp" "$key_state_file" || { rm -f "$tmp"; return 1; }
}

fmix_reconcile_same_toolchain_dependency_change() {
    # A dependency-only template-key change must not throw away a proven app
    # build. Prove that the existing session was compiled at the same ABI and
    # that its dependency/build guards are intact, advance only its storage
    # key, then let the split dependency lane install an exact/ancestor
    # artifact when available. With no shared artifact, the current session is
    # itself the reconciliation seed: clear its exact-hit claims so deps.get +
    # Mix perform an ordinary incremental repair in place.
    local worktree="$1" recorded_key="$2" template_key="$3"
    local real deps_root build_root state_file artifact_state_file key_state_file
    local dependency_stamp compile_stamp recorded_dependency current_dependency
    local recorded_dependency_guard current_dependency_guard
    local recorded_reconciliation_guard current_reconciliation_guard
    local recorded_lock_identity current_lock_identity
    local recorded_manifest_guard current_manifest_guard
    local recorded_env_hash current_env_hash recorded_stamp_key recorded_schema
    local app_ebin preparation_rc=0
    real="$(fmix_realpath "$worktree")" || return 1
    deps_root="$(fmix_session_deps_root "$real")" || return 1
    build_root="$(fmix_compile_build_root "$real")" || return 1
    state_file="$(fmix_worktree_state_file "$real")"
    artifact_state_file="$(fmix_artifact_state_file "$real")"
    if [[ -f "$artifact_state_file" ]]; then
        key_state_file="$artifact_state_file"
    else
        key_state_file="$state_file"
    fi
    dependency_stamp="$(fmix_dependency_stamp_file "$real")"
    compile_stamp="$(fmix_compile_stamp_file "$real")"
    app_ebin="$build_root/test/lib/cdrcisco/ebin"

    [[ -d "$deps_root" && -d "$build_root" \
        && -f "$key_state_file" \
        && -f "$dependency_stamp" && -f "$compile_stamp" \
        && -d "$app_ebin" \
        && -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" ]] \
        || return 1
    [[ "$(fmix_read_state "$key_state_file" path)" == "$real" \
        && "$(fmix_read_state "$key_state_file" template_key)" == "$recorded_key" ]] \
        || return 1

    recorded_schema="$(fmix_read_state "$compile_stamp" schema_version)"
    recorded_stamp_key="$(fmix_read_state "$compile_stamp" template_key)"
    recorded_env_hash="$(fmix_read_state "$compile_stamp" compile_env_hash)"
    current_env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null)" \
        || return 1
    [[ "$recorded_schema" == "2" \
        && "$recorded_stamp_key" == "$recorded_key" \
        && -n "$recorded_env_hash" \
        && "$recorded_env_hash" == "$current_env_hash" ]] || return 1
    [[ "$(fmix_read_state "$dependency_stamp" path)" == "$real" \
        && "$(fmix_read_state "$dependency_stamp" build_root)" == "$build_root" \
        && "$(fmix_read_state "$compile_stamp" path)" == "$real" \
        && "$(fmix_read_state "$compile_stamp" build_root)" == "$build_root" ]] \
        || return 1

    recorded_dependency="$(
        fmix_read_state "$dependency_stamp" dependency_fingerprint
    )"
    current_dependency="$(fmix_compute_dependency_fingerprint "$real")" \
        || return 1
    [[ "$recorded_dependency" =~ ^[0-9a-f]{64}$ \
        && "$current_dependency" =~ ^[0-9a-f]{64}$ \
        && "$recorded_dependency" != "$current_dependency" ]] || return 1

    recorded_reconciliation_guard="$(
        fmix_read_state "$dependency_stamp" reconciliation_guard
    )"
    current_reconciliation_guard="$(
        fmix_compute_dependency_reconciliation_guard "$real" 2>/dev/null
    )" || return 1
    recorded_lock_identity="$(
        fmix_read_state "$dependency_stamp" lock_identity
    )"
    current_lock_identity="$(
        fmix_compute_dependency_lock_identity "$real" 2>/dev/null
    )" || return 1
    [[ "$recorded_reconciliation_guard" =~ ^[0-9a-f]{64}$ \
        && "$current_reconciliation_guard" == "$recorded_reconciliation_guard" \
        && "$recorded_lock_identity" =~ ^[0-9a-f]{64}$ \
        && "$current_lock_identity" =~ ^[0-9a-f]{64}$ \
        && "$current_lock_identity" != "$recorded_lock_identity" ]] || return 1

    recorded_dependency_guard="$(fmix_read_state "$dependency_stamp" source_guard)"
    current_dependency_guard="$(fmix_dependency_source_guard "$real")" \
        || return 1
    [[ -n "$recorded_dependency_guard" \
        && "$recorded_dependency_guard" == "$current_dependency_guard" ]] \
        || return 1
    recorded_manifest_guard="$(fmix_read_state "$compile_stamp" manifest_guard)"
    current_manifest_guard="$(fmix_compile_manifest_guard "$real")" \
        || return 1
    [[ -n "$recorded_manifest_guard" \
        && "$recorded_manifest_guard" == "$current_manifest_guard" ]] \
        || return 1

    # Move the cheap metadata first. Dependency installation is transactional;
    # if preparation rejects the candidate, restore the old key and leave the
    # prior session claims untouched.
    fmix_update_worktree_template_key \
        "$real" "$recorded_key" "$template_key" || return 1
    fmix_prepare_dependency_artifacts "$real" || preparation_rc=$?
    if (( preparation_rc != 0 )); then
        fmix_update_worktree_template_key \
            "$real" "$template_key" "$recorded_key" >/dev/null 2>&1 || true
        return "$preparation_rc"
    fi

    if ! fmix_dependency_stamp_matches "$real" "$current_dependency"; then
        # No exact artifact was installed (an ancestor artifact may already
        # have replaced the dependency tree). Remove both exact claims so the
        # next compile resolves and incrementally repairs this retained build.
        rm -f "$dependency_stamp" "$compile_stamp" || return 1
    fi
    [[ -d "$deps_root" && -d "$build_root" \
        && -d "$app_ebin" \
        && -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" \
        && "$(fmix_read_state "$key_state_file" template_key)" == "$template_key" ]] \
        || return 1
    fmix_info "Same-toolchain dependency change retained the proven app build for incremental reconciliation."
    return 0
}

fmix_adopt_migration_only_key_change() {
    # API-3576: the template key now includes a migrations digest, so landing a
    # migration changes the key. Nothing the template caches (compiled deps and
    # the app baseline) depends on migrations, so a session whose recorded base
    # key (everything but the digest) still equals the current one keeps its
    # artifacts and only its storage key advances; Mix recompiles any changed
    # sources incrementally exactly as it did when migrations were not keyed.
    #
    # Deliberately does NOT adopt a v4-stamped session (see
    # fmix_adopt_compatible_worktree_artifacts, which also re-records stamps):
    # this path leaves stamps to the incremental compile that a changed tree
    # forces, so it requires proof that the tree actually changed.
    local worktree="$1" recorded_key="$2" template_key="$3"
    local real state_file artifact_state_file key_state_file recorded_base current_base
    local compile_stamp recorded_tree current_tree
    real="$(fmix_realpath "$worktree")" || return 1
    state_file="$(fmix_worktree_state_file "$real")"
    artifact_state_file="$(fmix_artifact_state_file "$real")"
    [[ -f "$artifact_state_file" ]] || return 1
    key_state_file="$artifact_state_file"
    [[ "$(fmix_read_state "$key_state_file" path)" == "$real" ]] || return 1
    recorded_base="$(fmix_read_state "$key_state_file" template_base_key)"
    [[ "$recorded_base" =~ ^[0-9a-f]{16}$ ]] || return 1
    current_base="$(fmix_compute_legacy_template_key_v4 "$real" 2>/dev/null)" || return 1
    [[ "$recorded_base" == "$current_base" ]] || return 1
    compile_stamp="$(fmix_compile_stamp_file "$real")"
    [[ -f "$compile_stamp" ]] || return 1
    recorded_tree="$(fmix_read_state "$compile_stamp" git_tree_hash)"
    current_tree="$(fmix_get_git_tree_hash "$real")" || return 1
    [[ -n "$recorded_tree" && "$recorded_tree" != "unknown" \
        && "$current_tree" != "unknown" && "$recorded_tree" != "$current_tree" ]] || return 1
    fmix_update_worktree_template_key "$real" "$recorded_key" "$template_key"
}

fmix_adopt_compatible_worktree_artifacts() {
    local worktree="$1" recorded_key="$2" template_key="$3"
    local real state_file artifact_state_file key_state_file
    local dependency_stamp compile_stamp
    local dependency_fingerprint compile_fingerprint legacy_key
    local migration_dir mode="" deps_root build_root
    real="$(fmix_realpath "$worktree")"
    deps_root="$(fmix_session_deps_root "$real")" || return 1
    build_root="$(fmix_compile_build_root "$real")" || return 1
    state_file="$(fmix_worktree_state_file "$real")"
    artifact_state_file="$(fmix_artifact_state_file "$real")"
    if [[ -f "$artifact_state_file" ]]; then
        key_state_file="$artifact_state_file"
    else
        key_state_file="$state_file"
    fi
    dependency_stamp="$(fmix_dependency_stamp_file "$real")"
    compile_stamp="$(fmix_compile_stamp_file "$real")"
    [[ -d "$deps_root" && -d "$build_root" ]] || return 1

    dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$real")" \
        || return 1
    compile_fingerprint="$(fmix_compute_compile_fingerprint "$real")" || return 1
    if fmix_dependency_stamp_matches "$real" "$dependency_fingerprint" \
        && fmix_compile_stamp_matches "$real" "$compile_fingerprint"; then
        mode="current"
    elif legacy_key="$(fmix_compute_legacy_template_key_v4 "$real" 2>/dev/null)" \
        && [[ "$recorded_key" == "$legacy_key" ]] \
        && fmix_dependency_stamp_matches "$real" "$dependency_fingerprint" \
        && FMIX_COMPILE_STAMP_KEY_OVERRIDE="$legacy_key" \
            fmix_compile_stamp_matches "$real" "$compile_fingerprint"; then
        # API-3576: v5 added the migrations digest to the key, so every session
        # stamped by FMix <= 2.7.9 reads as a key mismatch even though nothing
        # it compiled changed. The recorded v4 key equals the v4 key of these
        # exact inputs and every stamp matches under it, so only the storage key
        # moves; stamps are re-recorded under v5 below.
        mode="v4"
    else
        legacy_key="$(fmix_compute_legacy_template_key_v2 "$real")" || return 1
        [[ "$recorded_key" == "$legacy_key" ]] || return 1
        fmix_legacy_artifact_stamps_match "$real" || return 1
        mode="legacy"
    fi

    migration_dir="$(mktemp -d "$FMIX_HOME/artifact-adoption.XXXXXX")" \
        || return 1
    if ! cp "$key_state_file" "$migration_dir/state.json" \
        || ! cp "$dependency_stamp" "$migration_dir/dependency.json" \
        || ! cp "$compile_stamp" "$migration_dir/compile.json"; then
        rm -rf "$migration_dir"
        return 1
    fi

    if [[ "$mode" == "legacy" || "$mode" == "v4" ]]; then
        if ! fmix_write_dependency_stamp "$real" "$dependency_fingerprint" \
            || ! fmix_write_compile_stamp "$real" "$compile_fingerprint"; then
            cp "$migration_dir/dependency.json" "$dependency_stamp" || true
            cp "$migration_dir/compile.json" "$compile_stamp" || true
            rm -rf "$migration_dir"
            return 1
        fi
    fi
    if ! fmix_update_worktree_template_key "$real" "$recorded_key" "$template_key"; then
        cp "$migration_dir/state.json" "$key_state_file" || true
        cp "$migration_dir/dependency.json" "$dependency_stamp" || true
        cp "$migration_dir/compile.json" "$compile_stamp" || true
        rm -rf "$migration_dir"
        return 1
    fi
    rm -rf "$migration_dir"
    return 0
}

FMIX_CURRENT_SEMAPHORE_SLOT=""
FMIX_CURRENT_SEMAPHORE_KEEPER_PID=""

fmix_compile_semaphore_permits() {
    if [[ -n "${FMIX_COMPILE_PERMITS:-}" ]]; then
        local p
        p="$(fmix_positive_uint_or_default "$FMIX_COMPILE_PERMITS" 2 FMIX_COMPILE_PERMITS)"
        printf '%s\n' "$p"
        return 0
    fi
    local cores
    cores="$(sysctl -n hw.ncpu 2>/dev/null || nproc 2>/dev/null || echo 4)"
    [[ "$cores" =~ ^[0-9]+$ ]] || cores=4
    local p=$(( cores / 8 ))
    (( p >= 1 )) || p=1
    (( p <= 2 )) || p=2
    printf '%s\n' "$p"
}

fmix_compile_semaphore_acquire() {
    local worktree="$1"
    # Never overwrite the handle retained after an unsuccessful release.
    if [[ -n "$FMIX_CURRENT_SEMAPHORE_SLOT" \
        || -n "$FMIX_CURRENT_SEMAPHORE_KEEPER_PID" ]]; then
        printf '{"error":"compile_semaphore_cleanup_pending"}\n' >&2
        return 70
    fi
    local permits deadline_secs
    permits="$(fmix_compile_semaphore_permits)"
    deadline_secs="${FMIX_CALLER_DEADLINE_SECS:-}"

    local slot acquired_slot=-1 acquired_keeper_pid=""
    mkdir -p "$FMIX_HOME/lock-kernel" "$FMIX_HOME/lock-metadata" || return 1

    local t0=$(fmix_epoch)
    local last_heartbeat=$t0
    local estimated_compile_s=60

    while true; do
        for (( slot = 0; slot < permits; slot++ )); do
            local kfile="$FMIX_HOME/lock-kernel/compile-permit-${slot}"
            local keeper_rc=0
            if fmix_lock_keeper_start "$kfile" exclusive 0 \
                "compile permit ${slot}" "compile-permit-${slot}"; then
                acquired_slot="$slot"
                acquired_keeper_pid="$FMIX_LAST_LOCK_KEEPER_PID"
                break
            else
                keeper_rc=$?
                # A broken bootstrap is not permit contention. Surface its
                # typed failure immediately instead of retrying indefinitely.
                (( keeper_rc == 1 )) || return "$keeper_rc"
            fi
        done

        if (( acquired_slot >= 0 )); then
            FMIX_CURRENT_SEMAPHORE_SLOT="$acquired_slot"
            FMIX_CURRENT_SEMAPHORE_KEEPER_PID="$acquired_keeper_pid"
            cat >"$FMIX_HOME/lock-metadata/compile-permit-${acquired_slot}.json" 2>/dev/null <<EOF
{
  "slot": $acquired_slot,
  "pid": $$,
  "start_time": "$(fmix_now)",
  "worktree": $(fmix_json_escape "$worktree")
}
EOF
            true
            return 0
        fi

        local now=$(fmix_epoch)
        local elapsed=$(( now - t0 ))
        local queue_depth=$permits

        if [[ -n "$deadline_secs" && "$deadline_secs" =~ ^[0-9]+$ ]]; then
            local estimated_wait=$(( (queue_depth / permits) * estimated_compile_s ))
            if (( elapsed + estimated_wait + estimated_compile_s > deadline_secs )); then
                local err_json
                err_json="$(printf '{"error": "host_compile_deadline_exceeded", "queue_depth": %d, "estimated_wait_s": %d, "permit_limit": %d}' \
                    "$queue_depth" "$estimated_wait" "$permits")"
                printf '%s\n' "$err_json" >&2
                return 75
            fi
        fi

        if (( now - last_heartbeat >= 15 )); then
            fmix_info "Waiting for host compilation semaphore permit (${elapsed}s elapsed, limit: ${permits} permits) …"
            last_heartbeat="$now"
        fi

        sleep 0.2
    done
}

fmix_compile_semaphore_release() {
    if [[ -n "$FMIX_CURRENT_SEMAPHORE_SLOT" \
        && -n "$FMIX_CURRENT_SEMAPHORE_KEEPER_PID" ]]; then
        # Keep both the recovery handle and metadata until this exact owned
        # keeper has actually stopped. A failed stop is not a released permit.
        fmix_lock_keeper_stop "$FMIX_CURRENT_SEMAPHORE_KEEPER_PID" || return $?
        rm -f "$FMIX_HOME/lock-metadata/compile-permit-${FMIX_CURRENT_SEMAPHORE_SLOT}.json" 2>/dev/null || true
        FMIX_CURRENT_SEMAPHORE_SLOT=""
        FMIX_CURRENT_SEMAPHORE_KEEPER_PID=""
    fi
    return 0
}

fmix_run_compile_streamed() {
    # Stream new compiler output at two-second granularity and emit a heartbeat
    # when Mix is CPU-bound without producing lines. Preserve compiler failures;
    # a successful compile is not green if its owned permit cannot be released.
    local worktree="$1" db_name="$2" extra="$3" log_file="$4"
    local timeout_override="${5:-}" stall_override="${6:-}"
    local heartbeat timeout stall=0 pid shown=0 lines now started last_output last_progress rc sem_rc=0 cleanup_rc=0
    local cancel_reason
    heartbeat="$(fmix_uint_or_default "$FMIX_COMPILE_HEARTBEAT" 30 FMIX_COMPILE_HEARTBEAT)"
    if [[ -n "$timeout_override" ]]; then
        timeout="$(fmix_positive_uint_or_default "$timeout_override" 900 FMIX_SETUP_COMPILE_TIMEOUT)"
    else
        timeout="$(fmix_positive_uint_or_default "$FMIX_COMPILE_TIMEOUT" 900 FMIX_COMPILE_TIMEOUT)"
    fi
    # A stall budget (0 = disabled) cancels only when the compiler has produced
    # no new log output for that long. Heartbeats do not count as progress.
    if [[ -n "$stall_override" ]]; then
        stall="$(fmix_positive_uint_or_default "$stall_override" 600 FMIX_SETUP_COMPILE_STALL_TIMEOUT)"
    fi

    # Split this consecutive phase boundary so host contention is not
    # mistaken for compiler execution. Existing exit/permit semantics stay put.
    fmix_run_telemetry_phase "compile_preparation"
    fmix_compile_semaphore_acquire "$worktree" || sem_rc=$?
    fmix_run_telemetry_phase "compile_permit_wait"
    if (( sem_rc != 0 )); then
        if (( sem_rc == 75 )); then
            return 75
        fi
        fmix_error "Could not acquire host compilation semaphore."
        return "$sem_rc"
    fi

    mkdir -p "$(dirname "$log_file")"
    : >"$log_file"
    _fmix_run_compile "$worktree" "$db_name" "$extra" >"$log_file" 2>&1 &
    pid=$!
    started="$(fmix_epoch)"
    last_output="$started"
    last_progress="$started"

    while kill -0 "$pid" 2>/dev/null; do
        now="$(fmix_epoch)"
        cancel_reason=""
        if (( timeout > 0 && now - started >= timeout )); then
            cancel_reason="Compile exceeded ${timeout}s; cancelling instead of holding the fmix lane."
        fi
        if [[ -z "$cancel_reason" ]]; then
            lines="$(wc -l <"$log_file" | tr -d ' ')"
            if (( lines > shown )); then
                sed -n "$(( shown + 1 )),${lines}p" "$log_file" >&2
                shown="$lines"
                last_output="$(fmix_epoch)"
                last_progress="$last_output"
            else
                if (( heartbeat > 0 && now - last_output >= heartbeat )); then
                    fmix_info "Compile still running ($(( now - last_output ))s without output, pid=$pid). Log: $log_file"
                    last_output="$now"
                fi
                if (( stall > 0 && now - last_progress >= stall )); then
                    cancel_reason="Compile produced no new output for ${stall}s (no-output stall budget); cancelling."
                fi
            fi
        fi
        if [[ -n "$cancel_reason" ]]; then
            fmix_error "$cancel_reason Log: $log_file"
            fmix_kill_process_tree "$pid"
            sleep 1
            kill -KILL "$pid" 2>/dev/null || true
            wait "$pid" 2>/dev/null || true
            fmix_compile_semaphore_release || cleanup_rc=$?
            if (( cleanup_rc != 0 )); then
                printf '{"error":"compile_semaphore_cleanup_failed","compile_exit_code":124,"cleanup_exit_code":%d}\n' "$cleanup_rc" >&2
            fi
            return 124
        fi
        sleep 2
    done
    rc=0
    wait "$pid" || rc=$?
    fmix_compile_semaphore_release || cleanup_rc=$?
    if (( cleanup_rc != 0 )); then
        printf '{"error":"compile_semaphore_cleanup_failed","compile_exit_code":%d,"cleanup_exit_code":%d}\n' "$rc" "$cleanup_rc" >&2
    fi
    lines="$(wc -l <"$log_file" | tr -d ' ')"
    if (( lines > shown )); then
        sed -n "$(( shown + 1 )),${lines}p" "$log_file" >&2
    fi
    (( rc != 0 )) || rc="$cleanup_rc"
    return "$rc"
}

_fmix_run_compile() {
    # $1=worktree $2=db_name $3=extra flag (e.g. --force). Echoes combined
    # stdout/stderr; returns mix's exit code.
    local worktree="$1" db_name="$2" extra="$3"
    local _fmix_deps_root
    _fmix_deps_root="$(fmix_session_deps_root "$worktree")"
    fmix_heal_cmake_nif_caches "$_fmix_deps_root"
    fmix_heal_toolchain_stale_nifs "$_fmix_deps_root"
    # The heal above purges .so files, but Mix will not recompile deps it
    # already considers built; rebuild the purged native deps explicitly.
    fmix_repair_missing_native_deps "$worktree"
    local -a build_env=()
    [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
    [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
    (
        cd "$worktree" || exit 1
        exec env \
            "${build_env[@]+"${build_env[@]}"}" \
            MIX_ENV=test \
            DB_HOSTNAME="$DB_HOST" \
            DB_PORT="$DB_PORT" \
            DB_USER="$DB_USER" \
            DB_PASSWORD="$DB_PASSWORD" \
            DB_NAME="$db_name" \
            SECRET_KEY_BASE="$SECRET_KEY_BASE" \
            WORKER_NODE=TRUE \
            ADMIN_NODE=TRUE \
            ONPREM=TRUE \
            MEESEEKS_HTML5EVER_BUILD=0 \
            LOCAL_NATS="$NATS_HOST" \
            NATS_PORT="$NATS_PORT" \
            NATS_HOST="$NATS_HOST" \
            CT_NATS_HOST="$NATS_HOST" \
            NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
            POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
            POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
            mix compile $extra 2>&1
    )
}

fmix_worktree_uses_oban_repo() {
    local worktree="$1"
    [[ -f "$worktree/mix.lock" ]] \
        && grep -Eq '^[[:space:]]*"oban_pro":.*"oban"' "$worktree/mix.lock"
}

fmix_private_env_file() {
    if [[ -n "$FMIX_ENV_FILE" ]]; then
        printf '%s\n' "$FMIX_ENV_FILE"
        return
    fi

    local config_file legacy_file source_path
    config_file="$FMIX_CONFIG_HOME/fmix.env"
    if [[ -f "$config_file" ]]; then
        printf '%s\n' "$config_file"
        return
    fi

    source_path="$(fmix_realpath "${BASH_SOURCE[0]}")"
    legacy_file="$(dirname "$source_path")/.env"
    if [[ -f "$legacy_file" ]]; then
        fmix_warn "Using legacy FMix credential file: $legacy_file"
        fmix_warn "Move it to $config_file (mode 0600); runtime snapshots are not a secret store."
        printf '%s\n' "$legacy_file"
        return
    fi
    printf '%s\n' "$config_file"
}

fmix_doppler_fetch_secret() {
    # Bounded `doppler secrets get --plain`; prints the value on success.
    # Never logs the value; the temp capture file is created 0600 by mktemp.
    local name="$1" project="$2" config="$3" timeout="${4:-15}"
    local out_file pid waited=0 value
    command -v doppler >/dev/null 2>&1 || return 1
    out_file="$(mktemp "${TMPDIR:-/tmp}/fmix-doppler.XXXXXX")" || return 1
    # The 0600 temp file briefly holds the secret; remove it on every function
    # return path (RETURN traps are scoped to this function invocation).
    # shellcheck disable=SC2064
    trap "rm -f '$out_file' 2>/dev/null" RETURN
    doppler secrets get "$name" --plain --project "$project" --config "$config" \
        >"$out_file" 2>/dev/null &
    pid=$!
    while kill -0 "$pid" 2>/dev/null; do
        if (( waited >= timeout )); then
            local doppler_tree
            doppler_tree="$(fmix_collect_process_tree "$pid")"
            fmix_signal_retained_set TERM "$doppler_tree"
            sleep 1
            fmix_signal_retained_set KILL "$doppler_tree"
            wait "$pid" 2>/dev/null || true
            rm -f "$out_file"
            return 1
        fi
        sleep 1
        waited=$(( waited + 1 ))
    done
    if ! wait "$pid" 2>/dev/null; then
        rm -f "$out_file"
        return 1
    fi
    value="$(cat "$out_file" 2>/dev/null)"
    rm -f "$out_file"
    [[ -n "$value" ]] || return 1
    printf '%s\n' "$value"
}

fmix_load_oban_license_from_doppler() {
    # Doppler is the source of truth for OBAN_LICENSE_KEY. On a local miss,
    # fetch it and write-through to the canonical 0600 credential file so
    # subsequent runs are offline-safe.
    local project="${FMIX_DOPPLER_PROJECT:-ai-workspace}"
    local config="${FMIX_DOPPLER_CONFIG:-dev_personal}"
    local value cache tmp
    value="$(fmix_doppler_fetch_secret OBAN_LICENSE_KEY "$project" "$config" 15)" \
        || { fmix_error "Doppler secret fetch failed. Run 'doppler login' and retry."; return 1; }
    OBAN_LICENSE_KEY="$value"
    fmix_info "OBAN_LICENSE_KEY resolved from Doppler ($project/$config)."

    # Cache to the same file reads resolve first: an explicit FMIX_ENV_FILE
    # override must receive the write-through, or subsequent offline runs
    # under that override would never see the cached credential.
    if [[ -n "$FMIX_ENV_FILE" ]]; then
        cache="$FMIX_ENV_FILE"
        mkdir -p "$(dirname "$cache")" 2>/dev/null || return 0
    else
        cache="$FMIX_CONFIG_HOME/fmix.env"
        mkdir -p "$FMIX_CONFIG_HOME" 2>/dev/null || return 0
        chmod 0700 "$FMIX_CONFIG_HOME" 2>/dev/null || true
    fi
    tmp="${cache}.tmp-$$-${RANDOM}"
    if (
        umask 177
        if [[ -f "$cache" ]]; then
            {
                awk '!/^[[:space:]]*(export[[:space:]]+)?OBAN_LICENSE_KEY[[:space:]]*=/' \
                    "$cache" 2>/dev/null
                printf 'OBAN_LICENSE_KEY=%s\n' "$value"
            } >"$tmp"
        else
            printf 'OBAN_LICENSE_KEY=%s\n' "$value" >"$tmp"
        fi
    ) 2>/dev/null; then
        chmod 0600 "$tmp" 2>/dev/null || true
        if mv "$tmp" "$cache" 2>/dev/null; then
            fmix_info "Cached Doppler credential to $cache (mode 0600) for offline runs."
        else
            rm -f "$tmp" 2>/dev/null || true
        fi
    else
        rm -f "$tmp" 2>/dev/null || true
    fi
    return 0
}

fmix_load_oban_license_key() {
    [[ -n "${OBAN_LICENSE_KEY:-}" ]] && return 0

    local env_file mode env_line env_value
    env_file="$(fmix_private_env_file)"
    if [[ -f "$env_file" ]]; then
        if [[ "$FMIX_OS" == "Darwin" ]]; then
            mode="$(stat -f '%Lp' "$env_file" 2>/dev/null || true)"
        else
            mode="$(stat -c '%a' "$env_file" 2>/dev/null || true)"
        fi
        if [[ "$mode" != "600" && "$mode" != "400" ]]; then
            # Fail closed: a group/world-readable secret file is a problem to
            # fix, not to silently route around via Doppler.
            fmix_error "Refusing private dependency credential file with mode ${mode:-unknown}: $env_file (expected 0600 or 0400)."
            return 1
        fi

        env_line="$(awk '/^[[:space:]]*(export[[:space:]]+)?OBAN_LICENSE_KEY[[:space:]]*=/{line=$0} END{print line}' "$env_file")"
        env_value="${env_line#*=}"
        env_value="${env_value#"${env_value%%[![:space:]]*}"}"
        env_value="${env_value%\"}"
        env_value="${env_value#\"}"
        env_value="${env_value%\'}"
        env_value="${env_value#\'}"
        if [[ -n "$env_value" ]]; then
            OBAN_LICENSE_KEY="$env_value"
            return 0
        fi
        fmix_warn "OBAN_LICENSE_KEY is missing or empty in $env_file; trying Doppler."
    fi

    fmix_load_oban_license_from_doppler && return 0

    fmix_error "Oban Pro dependency resolution needs OBAN_LICENSE_KEY from the environment, $env_file, or Doppler (project ${FMIX_DOPPLER_PROJECT:-ai-workspace}, config ${FMIX_DOPPLER_CONFIG:-dev_personal})."
    fmix_error "Fix: 'doppler login' and retry, or write OBAN_LICENSE_KEY=… to $env_file (mode 0600)."
    return 1
}

fmix_load_oban_license() {
    fmix_load_oban_license_key "$@"
}

fmix_configure_ephemeral_oban_repo() {
    local worktree="$1"
    fmix_worktree_uses_oban_repo "$worktree" || return 0
    fmix_load_oban_license_key || return 1

    mkdir -p "$FMIX_HEX_HOME"
    chmod 700 "$FMIX_HEX_HOME" 2>/dev/null || true
    export HEX_HOME="$FMIX_HEX_HOME"
    if ! mix local.hex --force --if-missing >/dev/null; then
        unset OBAN_LICENSE_KEY
        fmix_error "Failed to install Hex before configuring the isolated Oban Pro repository."
        return 1
    fi
    mix hex.repo remove oban >/dev/null 2>&1 || true
    if ! mix hex.repo add oban https://repo.oban.pro \
        --fetch-public-key 'SHA256:4/OSKi0NRF91QVVXlGAhb/BIMLnK8NHcx/EWs+aIWPc' \
        --auth-key "$OBAN_LICENSE_KEY" >/dev/null; then
        unset OBAN_LICENSE_KEY
        fmix_error "Failed to configure the isolated Oban Pro repository for FMix."
        return 1
    fi
    unset OBAN_LICENSE_KEY
}

fmix_remove_ephemeral_oban_repo() {
    local worktree="$1"
    fmix_worktree_uses_oban_repo "$worktree" || return 0
    HEX_HOME="$FMIX_HEX_HOME" mix hex.repo remove oban >/dev/null 2>&1 || true
}

# Ensures the Hex package manager is installed for this FMIX_HOME. deps.get is
# normally what installs it, but a dependency stamp hit skips deps.get entirely;
# compiling then fails closed with "Could not find an SCM for dependency" on any
# fresh MIX_HOME (new pod, node replacement, or a session cloned without it).
fmix_ensure_hex() {
    local worktree="$1"
    (
        cd "$worktree" || exit 1
        HEX_HOME="$FMIX_HEX_HOME" mix local.hex --force --if-missing
    ) >/dev/null 2>&1
}

_fmix_run_deps_get() {
    local worktree="$1"
    local -a build_env=()
    [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
    [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
    (
        cd "$worktree" || exit 1
        fmix_configure_ephemeral_oban_repo "$worktree" || exit 1
        trap 'fmix_remove_ephemeral_oban_repo "$worktree"' EXIT INT TERM
        env \
            "${build_env[@]+"${build_env[@]}"}" \
            HEX_HOME="$FMIX_HEX_HOME" \
            HEX_HTTP_TIMEOUT=300 \
            MIX_ENV=test mix deps.get
    )
}

fmix_run_deps_get() {
    local worktree="$1" timeout stall_timeout heartbeat log_file pid started now
    local last_heartbeat last_progress last_size current_size rc private_repo_lock=0
    timeout="$(fmix_positive_uint_or_default "$FMIX_DEPS_TIMEOUT" 600 FMIX_DEPS_TIMEOUT)"
    stall_timeout="$(fmix_positive_uint_or_default "$FMIX_DEPS_STALL_TIMEOUT" 120 FMIX_DEPS_STALL_TIMEOUT)"
    heartbeat="$(fmix_uint_or_default "$FMIX_DEPS_HEARTBEAT" 15 FMIX_DEPS_HEARTBEAT)"
    log_file="$FMIX_HOME/logs/deps-$(fmix_worktree_id "$worktree")-$(date +%Y%m%dT%H%M%S)-$$-${RANDOM}.log"
    mkdir -p "$(dirname "$log_file")"
    : >"$log_file"

    if fmix_worktree_uses_oban_repo "$worktree"; then
        fmix_lock_acquire "hex-private-repo" "$FMIX_LOCK_TIMEOUT" || return $?
        private_repo_lock=1
    fi

    _fmix_run_deps_get "$worktree" >"$log_file" 2>&1 &
    pid=$!
    started="$(fmix_epoch)"
    last_heartbeat="$started"
    last_progress="$started"
    last_size=0

    while kill -0 "$pid" 2>/dev/null; do
        now="$(fmix_epoch)"
        current_size="$(wc -c <"$log_file" | tr -d '[:space:]')"
        if [[ "$current_size" =~ ^[0-9]+$ ]] && (( current_size != last_size )); then
            last_size="$current_size"
            last_progress="$now"
        fi
        if (( now - started >= timeout )); then
            fmix_error "mix deps.get exceeded the ${timeout}s hard limit; cancelling. Log: $log_file"
            fmix_kill_process_tree "$pid"
            sleep 1
            kill -KILL "$pid" 2>/dev/null || true
            wait "$pid" 2>/dev/null || true
            fmix_remove_ephemeral_oban_repo "$worktree"
            if (( private_repo_lock == 1 )); then
                fmix_command_lock_finish "hex-private-repo" 124 1 || return $?
            fi
            return 124
        fi
        if (( now - last_progress >= stall_timeout )); then
            fmix_error "mix deps.get made no logged progress for ${stall_timeout}s; cancelling. Log: $log_file"
            fmix_kill_process_tree "$pid"
            sleep 1
            kill -KILL "$pid" 2>/dev/null || true
            wait "$pid" 2>/dev/null || true
            fmix_remove_ephemeral_oban_repo "$worktree"
            if (( private_repo_lock == 1 )); then
                fmix_command_lock_finish "hex-private-repo" 124 1 || return $?
            fi
            return 124
        fi
        if (( heartbeat > 0 && now - last_heartbeat >= heartbeat )); then
            fmix_info "mix deps.get still running ($(( now - started ))s, pid=$pid). Log: $log_file"
            last_heartbeat="$now"
        fi
        sleep 1
    done

    wait "$pid"
    rc=$?
    fmix_remove_ephemeral_oban_repo "$worktree"
    if (( private_repo_lock == 1 )); then
        fmix_command_lock_finish "hex-private-repo" "$rc" 1 || rc=$?
    fi
    if (( rc != 0 )); then
        fmix_error "mix deps.get failed (rc=$rc). Log: $log_file"
        tail -80 "$log_file" >&2
    fi
    return "$rc"
}

fmix_ensure_compile() {
    local rc=0
    _fmix_ensure_compile_impl "$@" || rc=$?
    if (( rc == 200 )) && [[ "${FMIX_LOCK_GATE_RETRY:-}" == "1" ]]; then
        # Escalated mid-decision: re-verify the warm stamp state once under the
        # new exclusive hold before resolving dependencies or compiling.
        FMIX_LOCK_GATE_RETRY=""
        rc=0
        _fmix_ensure_compile_impl "$@" || rc=$?
    fi
    return "$rc"
}

_fmix_ensure_compile_impl() {
    local worktree="$1" db_name="$2" compile_mode="${3:-incremental}"
    fmix_prepend_toolchain_paths
    FMIX_LAST_COMPILE_OUTCOME=""
    FMIX_LAST_COMPILE_FILES="0"
    FMIX_LAST_COMPILE_SECONDS="0"
    FMIX_LAST_COMPILE_LOG=""

    if [[ "${FMIX_SOURCE_STABILITY_REQUIRED:-0}" == "1" ]]; then
        if ! fmix_require_stable_source "$worktree" "compile preparation" 1; then
            FMIX_LAST_COMPILE_OUTCOME="error"
            return 1
        fi
        if [[ ! "${FMIX_SOURCE_STABILITY_COMPILE_IDENTITY:-}" =~ ^[0-9a-f]{64}$ ]]; then
            FMIX_SOURCE_STABILITY_COMPILE_IDENTITY="$(
                fmix_source_stability_compile_identity "$worktree"
            )" || {
                fmix_invalidate_rejected_stamps "$worktree"
                FMIX_LAST_COMPILE_OUTCOME="error"
                return 1
            }
        fi
    fi

    # Warm-path staged admission: cheap stat/manifest checks reject obvious
    # drift before bounded live-content and dependency-source verification.
    if fmix_try_compile_stamp_quick_hit "$worktree"; then
        fmix_info "Compile stamp quick-hit — skipping deps.get and mix compile."
        FMIX_LAST_COMPILE_OUTCOME="stamp_hit_quick"
        return 0
    fi
    # Only the stamp quick-hit is provably read-only. Stamp writes, deps.get,
    # and compilation mutate the shared session overlay.
    fmix_lock_mutate_gate "dependency resolution or compilation" || return $?
    # Donor clones, dependency artifacts and stamp hits can all carry a deps/
    # tree whose NIF .so was purged (the quick-hit above refuses such a tree).
    # Verify and rebuild before any stamp or CAS admission can bless it.
    fmix_repair_missing_native_deps "$worktree"

    # The content/config stamp is authoritative for this exact realpath and
    # includes mix.lock, toolchain, compiler config, path deps, and Mix
    # manifests. A warm hit must return before dependency resolution or Mix
    # startup; this is the seconds-scale inner loop. Compiled artifacts remain
    # runnable without dependency source checkouts. The first source/config
    # miss below validates the dependency stamp before Mix may compile again.
    local fingerprint="" dependency_fingerprint="" deps_root=""
    fingerprint="$(fmix_compute_compile_fingerprint "$worktree")" || fingerprint=""
    if [[ -n "$fingerprint" ]] && fmix_compile_stamp_matches "$worktree" "$fingerprint"; then
        deps_root="$(fmix_dependency_source_root "$worktree")"
        if [[ ! -d "$deps_root" ]]; then
            fmix_info "Compile stamp hit — skipping deps.get and mix compile."
            FMIX_LAST_COMPILE_OUTCOME="stamp_hit"
            # Backfill quick_guard on older stamps so the next run is cheap.
            fmix_write_compile_stamp "$worktree" "$fingerprint" >/dev/null 2>&1 || true
            return 0
        fi

        dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
            || dependency_fingerprint=""
        if [[ -n "$dependency_fingerprint" ]] \
            && fmix_dependency_stamp_matches "$worktree" "$dependency_fingerprint"; then
            fmix_info "Compile and dependency stamps hit — skipping deps.get and mix compile."
            FMIX_LAST_COMPILE_OUTCOME="stamp_hit"
            fmix_write_compile_stamp "$worktree" "$fingerprint" >/dev/null 2>&1 || true
            return 0
        fi

        # A pre-v2 compile stamp may already prove the final dependency source
        # guard while its dependency checkpoint still describes the state
        # before Mix compiled native/generated inputs. Repair that checkpoint
        # without resolving or compiling again.
        if [[ -n "$dependency_fingerprint" ]] \
            && fmix_write_dependency_stamp "$worktree" "$dependency_fingerprint"; then
            fmix_info "Repaired final dependency provenance from the exact compile stamp."
            FMIX_LAST_COMPILE_OUTCOME="stamp_hit_repaired"
            fmix_write_compile_stamp "$worktree" "$fingerprint" >/dev/null 2>&1 || true
            return 0
        fi
        fmix_error "Compile artifacts are valid, but final dependency provenance could not be recorded."
        FMIX_LAST_COMPILE_OUTCOME="error"
        return 1
    fi

    [[ -n "$dependency_fingerprint" ]] \
        || dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
        || dependency_fingerprint=""
    if [[ -n "$dependency_fingerprint" ]] \
        && fmix_dependency_stamp_matches "$worktree" "$dependency_fingerprint"; then
        fmix_info "Dependency stamp hit — skipping deps.get for source-only compile."
    else
        fmix_info "Dependency stamp miss; resolving dependencies once …"
        # Transient registry/CDN stalls (e.g. the Hex tarball fetcher's internal
        # 120s await timing out against hex.pm) are retryable; only unresolvable
        # dependencies are fatal.
        local deps_rc=0 deps_attempt
        for deps_attempt in 1 2 3; do
            fmix_run_deps_get "$worktree" && { deps_rc=0; break; }
            deps_rc=$?
            if (( deps_attempt < 3 )); then
                fmix_warn "mix deps.get attempt ${deps_attempt} failed (rc=${deps_rc}); retrying in 15s …"
                sleep 15
            fi
        done
        if (( deps_rc != 0 )); then
            fmix_error "mix deps.get failed; refusing to compile against unresolved dependencies."
            FMIX_LAST_COMPILE_OUTCOME="error"
            return "$deps_rc"
        fi
        dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
            || dependency_fingerprint=""
        if [[ -n "$dependency_fingerprint" ]]; then
            fmix_write_dependency_stamp "$worktree" "$dependency_fingerprint" \
                || fmix_warn "Dependencies resolved, but their stamp could not be recorded; the next run will resolve them again."
        fi
    fi

    # deps.get may update mix.lock. Recompute before deciding whether a compile
    # is still needed.
    fingerprint="$(fmix_compute_compile_fingerprint "$worktree")" || fingerprint=""
    if [[ -n "$fingerprint" ]] && fmix_compile_stamp_matches "$worktree" "$fingerprint"; then
        fmix_info "Compile stamp restored after dependency resolution — skipping mix compile."
        FMIX_LAST_COMPILE_OUTCOME="stamp_hit_after_deps"
        return 0
    fi

    # Local app-compile CAS consumer: a content-exact shared application layer
    # can replace this compile outright. Any miss, corrupt generation, or
    # proof failure is discarded and falls through to the normal bounded
    # compile below — never a forced full rebuild. Opt out with FMIX_APP_CAS=0.
    local app_cas_rc=0
    if [[ "${FMIX_APP_CAS:-1}" != "0" && -n "$fingerprint" ]] \
        && fmix_try_install_app_compile_artifact "$worktree" "$fingerprint"; then
        fmix_info "Exact app compile artifact hit — skipping mix compile."
        FMIX_LAST_COMPILE_OUTCOME="app_cas_hit"
        return 0
    else
        app_cas_rc=$?
        case "$app_cas_rc" in
            2|70|129|130|143)
                FMIX_LAST_COMPILE_OUTCOME="error"
                return "$app_cas_rc" ;;
        esac
    fi

    fmix_info "Compiling app (incremental) …"
    local stamp_file log_file t0 t1 rc
    stamp_file="$(fmix_compile_stamp_file "$worktree")"
    rm -f "$stamp_file"
    log_file="$FMIX_HOME/logs/compile-$(fmix_worktree_id "$worktree")-$(date +%Y%m%dT%H%M%S).log"
    FMIX_LAST_COMPILE_LOG="$log_file"
    mkdir -p "$(dirname "$log_file")"
    t0=$(fmix_epoch)
    local compile_timeout="" compile_stall=""
    if [[ "$compile_mode" == "setup" ]]; then
        compile_timeout="$(fmix_positive_uint_or_default "$FMIX_SETUP_COMPILE_TIMEOUT" 7200 FMIX_SETUP_COMPILE_TIMEOUT)"
        compile_stall="$(fmix_positive_uint_or_default "$FMIX_SETUP_COMPILE_STALL_TIMEOUT" 600 FMIX_SETUP_COMPILE_STALL_TIMEOUT)"
        fmix_info "Explicit setup compile: cancel after ${compile_stall}s without compiler output (ceiling ${compile_timeout}s)."
    fi
    if ! fmix_require_stable_source "$worktree" "compile start" 1; then
        FMIX_LAST_COMPILE_OUTCOME="error"
        return 1
    fi
    fmix_ensure_hex "$worktree" || fmix_warn "Hex bootstrap failed; compile may fail to resolve dependency SCMs."
    fmix_run_compile_streamed "$worktree" "$db_name" "" "$log_file" "$compile_timeout" "$compile_stall"
    rc=$?
    t1=$(fmix_epoch)
    FMIX_LAST_COMPILE_SECONDS=$(( t1 - t0 ))
    if (( rc != 0 )); then
        if (( rc == 75 )); then
            FMIX_LAST_COMPILE_OUTCOME="deadline_exceeded"
            return 75
        fi
        local elapsed_compile=$(( t1 - t0 ))
        FMIX_LAST_COMPILE_OUTCOME="error"
        if (( rc == 124 )); then
            fmix_error "mix compile was cancelled after ${elapsed_compile}s (no-output stall budget or setup ceiling; see the compile log)."
        else
            fmix_error "Incremental mix compile failed (${elapsed_compile}s); no automatic full recompile was started."
        fi
        fmix_error "Compile log: $log_file"
        fmix_error "Fix the source error or explicitly repair the worktree build before retrying."
        return "$rc"
    fi
    if ! fmix_require_stable_source "$worktree" "compile" 1; then
        FMIX_LAST_COMPILE_OUTCOME="error"
        return 1
    fi
    local compiled_files=0
    compiled_files="$(sed -nE 's/.*Compiling ([0-9]+) files?.*/\1/p' "$log_file" 2>/dev/null \
        | awk '{ total += $1 } END { print total + 0 }')" || compiled_files=0
    compiled_files="${compiled_files:-0}"
    FMIX_LAST_COMPILE_FILES="$compiled_files"
    if [[ "$compiled_files" =~ ^[0-9]+$ ]] && (( compiled_files > 0 )); then
        fmix_info "Compiled $compiled_files file(s) in $(( t1 - t0 ))s."
        if (( compiled_files >= 1000 )); then
            FMIX_LAST_COMPILE_OUTCOME="full_recompile"
            fmix_warn "Full/near-full recompile ($compiled_files files). Often means a NEW session (check session source), stamp miss after path drift, or first use of this session overlay."
        else
            FMIX_LAST_COMPILE_OUTCOME="incremental"
        fi
    else
        fmix_info "Nothing to recompile ($(( t1 - t0 ))s)."
        FMIX_LAST_COMPILE_OUTCOME="noop_compile"
    fi

    # Dependency compilation can generate source or native build inputs inside
    # deps/. Record the final, post-compile dependency guard so a successful
    # setup is immediately eligible for exact template provenance.
    dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
        || dependency_fingerprint=""
    if [[ -z "$dependency_fingerprint" ]] \
        || ! fmix_write_dependency_stamp "$worktree" "$dependency_fingerprint"; then
        fmix_invalidate_rejected_stamps "$worktree"
        fmix_error "Compile succeeded, but final dependency provenance could not be recorded."
        FMIX_LAST_COMPILE_OUTCOME="error"
        return 1
    fi
    if ! fmix_require_stable_source "$worktree" "final dependency provenance" 1; then
        FMIX_LAST_COMPILE_OUTCOME="error"
        return 1
    fi

    # Stamp provenance: per-file digests recorded during this content hash are
    # persisted as the stamp's stat manifest so the next warm admission can
    # re-stat and content-hash only drift. Reuse is stat-validated (ctime
    # keyed), so anything mutated earlier in this run is re-hashed here, and
    # the requirement checks still fail closed on any source change.
    fmix_stat_hash_cache_use "$worktree" || true
    fingerprint="$(fmix_compute_compile_fingerprint "$worktree")" || fingerprint=""
    if [[ -z "$fingerprint" ]] \
        || ! fmix_require_stable_source "$worktree" "compile stamp construction" 1 \
        || ! fmix_write_compile_stamp "$worktree" "$fingerprint"; then
        fmix_stat_hash_cache_done
        fmix_invalidate_rejected_stamps "$worktree"
        fmix_error "Compile succeeded, but final content/config provenance could not be recorded."
        FMIX_LAST_COMPILE_OUTCOME="error"
        return 1
    fi
    if ! fmix_require_stable_source "$worktree" "compile stamp publication" 1; then
        fmix_stat_hash_cache_done
        FMIX_LAST_COMPILE_OUTCOME="error"
        return 1
    fi
    # Local app-compile CAS producer: best-effort publication of the proven
    # application layer for future worktrees. Ordinary publication failures
    # warn and never fail the run; interrupted/fatal outcomes still surface.
    local app_publish_rc=0
    if [[ "${FMIX_APP_CAS:-1}" != "0" ]]; then
        fmix_publish_app_compile_artifact "$worktree" "$fingerprint" \
            || app_publish_rc=$?
        case "$app_publish_rc" in
            0) ;;
            2|70|129|130|143) return "$app_publish_rc" ;;
            *) fmix_warn "Optional app compile artifact publication failed; keeping the proven session." ;;
        esac
    fi
    fmix_stat_hash_cache_done
    return 0
}

# ---------------------------------------------------------------------------
# cmd: fmix seed
# ---------------------------------------------------------------------------

cmd_seed() {
    local action="${1:-}" worktree_arg="auto" cache_base="" session_arg=""
    [[ -n "$action" ]] || {
        fmix_error "Usage: fmix seed publish --worktree <path> --cache-base <N.N.N-stable>"
        return 2
    }
    shift
    case "$action" in
        publish) ;;
        *)
            fmix_error "Unknown seed action: $action. Usage: fmix seed publish --worktree <path> --cache-base <N.N.N-stable>"
            return 2
            ;;
    esac
    while (( $# > 0 )); do
        case "$1" in
            --worktree)
                [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }
                worktree_arg="$2"
                shift 2
                ;;
            --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
            --cache-base)
                [[ $# -ge 2 ]] || { fmix_error "--cache-base requires a stable branch."; return 2; }
                cache_base="$2"
                shift 2
                ;;
            --cache-base=*) cache_base="${1#--cache-base=}"; shift ;;
            --session)
                [[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }
                session_arg="$2"
                shift 2
                ;;
            --session=*) session_arg="${1#--session=}"; shift ;;
            *)
                fmix_error "Unknown seed publish option: $1. Usage: fmix seed publish --worktree <path> --cache-base <N.N.N-stable>"
                return 2
                ;;
        esac
    done
    [[ -n "$cache_base" ]] || {
        fmix_error "seed publish requires --cache-base <N.N.N-stable>."
        return 2
    }
    local worktree real
    worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
    fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1
    real="$(fmix_realpath "$worktree")" || return 1
    fmix_activate_toolchain "$real" || return 1
    fmix_activate_session "$real" "$session_arg" || return $?
    fmix_seed_publish "$real" "$cache_base"
}

# ---------------------------------------------------------------------------
# cmd: fmix cache
# ---------------------------------------------------------------------------

# Cross-pod transport of the local v2 pools (dependency and app-compile): the
# runner image ships pool entries to and from an object store as one packed
# archive per entry. These verbs never talk to the network; they only read a
# verified pool entry into an archive (export) or admit an archive into the
# pool through the same staging, sealing, lease and verification discipline
# as local publication (import). Any failure is an ordinary miss.
fmix_cache_keys() {
    local real="${1:-}" lane dependency exact runner
    # Test and setup lanes build and publish inside an active session, whose
    # fingerprints hash the fmix-session-v1 marker in place of MIX_DEPS_PATH and
    # MIX_BUILD_PATH. Compute the same keys here without activating a session
    # (no session directories, no locks); otherwise every key misses.
    local FMIX_ACTIVE_SESSION_ROOT="${FMIX_ACTIVE_SESSION_ROOT:-fmix-cache-keys}"
    lane="$(fmix_dependency_lane_fingerprint "$real")" || return 1
    dependency="$(fmix_compute_dependency_fingerprint "$real")" || return 1
    exact="$(fmix_compute_compile_fingerprint "$real")" || return 1
    runner="$(fmix_hash_stdin <"$(fmix_realpath "${BASH_SOURCE[0]}")")" || return 1
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$dependency" =~ ^[0-9a-f]{64}$ \
        && "$exact" =~ ^[0-9a-f]{64}$ && "$runner" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '{"lane":"%s","dependency":"%s","exact":"%s","runner":"%s"}\n' \
        "$lane" "$dependency" "$exact" "$runner"
}

fmix_cache_pool_artifact_dir() {
    local kind="${1:-}" lane="${2:-}" exact="${3:-}"
    case "$kind" in
        dependency) fmix_dependency_artifact_v2_dir "$lane" "$exact" ;;
        app) [[ "${FMIX_APP_CAS:-1}" != "0" ]] || return 1
             fmix_app_compile_artifact_v2_dir "$lane" "$exact" ;;
        *) return 1 ;;
    esac
}

fmix_cache_pool_verify() {
    local kind="${1:-}"
    shift
    case "$kind" in
        dependency) fmix_dependency_artifact_verify_full "$@" ;;
        app) fmix_app_compile_artifact_verify_full "$@" ;;
        *) return 1 ;;
    esac
}

fmix_cache_export() {
    local kind="${1:-}" lane="${2:-}" exact="${3:-}" output="${4:-}"
    local artifact tmp rc
    local -a entries=(_build meta.json manifest.tsv manifest.sha256)
    local -a pipe_rc=()
    [[ -n "$output" ]] || return 1
    artifact="$(fmix_cache_pool_artifact_dir "$kind" "$lane" "$exact")" || return 1
    [[ -d "$artifact" && ! -L "$artifact" ]] || return 1
    [[ "$artifact" == "$FMIX_HOME/artifacts/v2/"* ]] || return 1
    command -v zstd >/dev/null 2>&1 || { fmix_error "zstd is required for cache export."; return 1; }
    fmix_artifact_v2_managed_entrypoint || return 3
    # Export only what the full manifest verification just proved.
    fmix_cache_pool_verify "$kind" "$artifact" "$lane" "$exact" || return 1
    [[ "$kind" == "dependency" ]] && entries=(deps "${entries[@]}")
    mkdir -p "$(dirname "$output")" || return 1
    tmp="${output}.tmp.$$"
    rm -f "$tmp"
    tar -cf - -C "$artifact" "${entries[@]}" | zstd -T0 -3 -q -f -o "$tmp"
    pipe_rc=("${PIPESTATUS[@]}")
    if (( pipe_rc[0] != 0 || pipe_rc[1] != 0 )); then
        rm -f "$tmp"
        return 1
    fi
    mv "$tmp" "$output" || { rm -f "$tmp"; return 1; }
}

fmix_cache_import() {
    local kind="${1:-}" lane="${2:-}" exact="${3:-}" archive="${4:-}"
    local artifact lock_name
    [[ -f "$archive" ]] || return 1
    artifact="$(fmix_cache_pool_artifact_dir "$kind" "$lane" "$exact")" || return 1
    command -v zstd >/dev/null 2>&1 || { fmix_error "zstd is required for cache import."; return 1; }
    fmix_artifact_v2_managed_entrypoint || return 3
    if [[ "$kind" == "dependency" ]]; then
        lock_name="dependency-artifact-${lane:0:16}-${exact:0:16}"
    else
        lock_name="app-compile-${lane:0:16}-${exact:0:16}"
    fi
    fmix_with_artifact_lease "$lock_name" _fmix_cache_import_locked \
        "$kind" "$lane" "$exact" "$archive" "$artifact"
}

_fmix_cache_import_locked() {
    local kind="$1" lane="$2" exact="$3" archive="$4" artifact="$5"
    local tmp pool_rel expected actual writable pipe_rc_zstd pipe_rc_tar
    local -a pipe_rc=()
    if fmix_cache_pool_verify "$kind" "$artifact" "$lane" "$exact"; then
        return 0
    fi
    if [[ "$kind" == "dependency" ]]; then
        pool_rel="artifacts/v2/dependencies/$lane"
    else
        pool_rel="artifacts/v2/app-compiles/$lane"
    fi
    fmix_artifact_v2_prepare_directory "$pool_rel" || return 1
    tmp="${artifact}.tmp-$$-${RANDOM}"
    if [[ -e "$tmp" || -L "$tmp" ]] || ! mkdir "$tmp"; then
        return 1
    fi
    zstd -d -q -c "$archive" | tar -xf - -C "$tmp"
    pipe_rc=("${PIPESTATUS[@]}")
    pipe_rc_zstd="${pipe_rc[0]}"
    pipe_rc_tar="${pipe_rc[1]}"
    if (( pipe_rc_zstd != 0 || pipe_rc_tar != 0 )); then
        chmod -R u+w "$tmp" 2>/dev/null || true
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    # Structure, schema, key identity and producer-runner proof first, then the
    # full manifest digest of the payload, all on the staged tree.
    chmod -R u+w "$tmp" 2>/dev/null || true
    if [[ "$kind" == "dependency" ]]; then
        fmix_dependency_artifact_is_complete "$tmp" "$lane" "$exact" 1 || {
            rm -rf "$tmp" 2>/dev/null || true
            return 1
        }
        actual="$(fmix_dependency_artifact_manifest_digest "$tmp")" || actual=""
    else
        fmix_app_compile_artifact_is_complete "$tmp" "$lane" "$exact" 1 || {
            rm -rf "$tmp" 2>/dev/null || true
            return 1
        }
        actual="$(fmix_app_compile_artifact_manifest_digest "$tmp")" || actual=""
    fi
    IFS= read -r expected <"$tmp/manifest.sha256"
    if [[ ! "$actual" =~ ^[0-9a-f]{64}$ || "$actual" != "$expected" ]]; then
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    chmod -R a-w "$tmp" || { chmod -R u+w "$tmp" 2>/dev/null; rm -rf "$tmp" 2>/dev/null; return 1; }
    chmod u+w "$tmp" || { chmod -R u+w "$tmp" 2>/dev/null; rm -rf "$tmp" 2>/dev/null; return 1; }
    writable="$(find "$tmp" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
        || writable=invalid
    if [[ -n "$writable" ]]; then
        chmod -R u+w "$tmp" 2>/dev/null || true
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    if [[ -e "$artifact" || -L "$artifact" ]]; then
        # Present but failed verification above: the lease holder replaces it.
        if [[ "$kind" == "dependency" ]]; then
            fmix_dependency_artifact_quarantine "$artifact" \
                "failed exact integrity verification" || { chmod -R u+w "$tmp" 2>/dev/null; rm -rf "$tmp"; return 1; }
        else
            fmix_app_compile_artifact_quarantine "$artifact" \
                "failed exact integrity verification" || { chmod -R u+w "$tmp" 2>/dev/null; rm -rf "$tmp"; return 1; }
        fi
    fi
    if ! mv "$tmp" "$artifact"; then
        chmod -R u+w "$tmp" 2>/dev/null || true
        rm -rf "$tmp" 2>/dev/null || true
        return 1
    fi
    chmod a-w "$artifact" || return 1
    if ! fmix_cache_pool_verify "$kind" "$artifact" "$lane" "$exact"; then
        if [[ "$kind" == "dependency" ]]; then
            fmix_dependency_artifact_quarantine "$artifact" \
                "post-import verification failed" >/dev/null 2>&1 || true
        else
            fmix_app_compile_artifact_quarantine "$artifact" \
                "post-import verification failed" >/dev/null 2>&1 || true
        fi
        return 1
    fi
    if [[ "$kind" == "dependency" ]]; then
        fmix_touch_dependency_artifact_access "$lane" "$exact" >/dev/null 2>&1 || true
    else
        fmix_touch_app_compile_artifact_access "$lane" "$exact" >/dev/null 2>&1 || true
    fi
    fmix_info "Imported $kind pool artifact ${exact:0:12} from archive."
}

cmd_cache() {
    local action="${1:-}" worktree_arg="auto" cache_base="" key=""
    local pool_kind="" pool_lane="" pool_exact="" pool_file=""
    case "$action" in
        explain|verify|keys|export|import) ;;
        *)
            fmix_error "Usage: fmix cache explain --worktree <path> --cache-base <N.N.N-stable>"
            fmix_error "   or: fmix cache verify [--key <16-hex-template-key>]"
            fmix_error "   or: fmix cache keys --worktree <path>"
            fmix_error "   or: fmix cache export --kind dependency|app --lane <64-hex> --exact <64-hex> --archive <file.tar.zst>"
            fmix_error "   or: fmix cache import --kind dependency|app --lane <64-hex> --exact <64-hex> --archive <file.tar.zst>"
            return 2
            ;;
    esac
    shift
    while (( $# > 0 )); do
        case "$1" in
            --worktree)
                [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }
                worktree_arg="$2"
                shift 2
                ;;
            --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
            --cache-base)
                [[ $# -ge 2 ]] || { fmix_error "--cache-base requires a stable branch."; return 2; }
                cache_base="$2"
                shift 2
                ;;
            --cache-base=*) cache_base="${1#--cache-base=}"; shift ;;
            --key)
                [[ $# -ge 2 ]] || { fmix_error "--key requires a template key."; return 2; }
                key="$2"
                shift 2
                ;;
            --key=*) key="${1#--key=}"; shift ;;
            --kind|--lane|--exact|--archive)
                [[ $# -ge 2 ]] || { fmix_error "$1 requires a value."; return 2; }
                case "$1" in
                    --kind) pool_kind="$2" ;;
                    --lane) pool_lane="$2" ;;
                    --exact) pool_exact="$2" ;;
                    --archive) pool_file="$2" ;;
                esac
                shift 2
                ;;
            *)
                fmix_error "Unknown cache $action option: $1."
                return 2
                ;;
        esac
    done

    if [[ "$action" == "keys" ]]; then
        local keys_worktree keys_real
        keys_worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
        fmix_check_resolved_worktree "$worktree_arg" "$keys_worktree" || return 1
        keys_real="$(fmix_realpath "$keys_worktree")" || return 1
        fmix_activate_toolchain "$keys_real" || return 1
        fmix_cache_keys "$keys_real" || {
            fmix_error "Could not compute cache keys for $keys_real."
            return 1
        }
        return 0
    fi

    if [[ "$action" == "export" || "$action" == "import" ]]; then
        [[ "$pool_kind" == "dependency" || "$pool_kind" == "app" ]] || {
            fmix_error "--kind must be dependency or app."
            return 2
        }
        [[ "$pool_lane" =~ ^[0-9a-f]{64}$ && "$pool_exact" =~ ^[0-9a-f]{64}$ ]] || {
            fmix_error "--lane and --exact must be 64-hex fingerprints."
            return 2
        }
        [[ -n "$pool_file" ]] || { fmix_error "--archive is required."; return 2; }
        if [[ "$action" == "export" ]]; then
            fmix_cache_export "$pool_kind" "$pool_lane" "$pool_exact" "$pool_file"
        else
            fmix_cache_import "$pool_kind" "$pool_lane" "$pool_exact" "$pool_file"
        fi
        return $?
    fi

    if [[ "$action" == "verify" ]]; then
        [[ -z "$worktree_arg" || "$worktree_arg" == "auto" ]] || {
            fmix_error "--worktree is not valid with 'fmix cache verify'."
            return 2
        }
        [[ -z "$cache_base" ]] || {
            fmix_error "--cache-base is not valid with 'fmix cache verify'."
            return 2
        }
        [[ -z "$key" || "$key" =~ ^[0-9a-f]{16}$ ]] || {
            fmix_error "Template key must be exactly 16 lowercase hexadecimal characters."
            return 2
        }
        local candidate checked=0 failed=0 candidate_key
        local -a candidates=()
        if [[ -n "$key" ]]; then
            candidates=("$(fmix_template_dir "$key")")
        else
            while IFS= read -r candidate; do
                candidates+=("$candidate")
            done < <(find "$FMIX_HOME/templates" -mindepth 1 -maxdepth 1 -type d \
                ! -name '*.tmp-*' -print 2>/dev/null | LC_ALL=C sort)
        fi
        for candidate in "${candidates[@]+"${candidates[@]}"}"; do
            candidate_key="$(basename "$candidate")"
            [[ "$candidate_key" =~ ^[0-9a-f]{16}$ ]] || continue
            checked=$(( checked + 1 ))
            if fmix_template_verify_full "$candidate_key"; then
                printf 'OK %s\n' "$candidate_key"
            else
                printf 'CORRUPT %s\n' "$candidate_key" >&2
                failed=$(( failed + 1 ))
            fi
        done
        printf 'verified=%s failed=%s\n' "$checked" "$failed"
        (( checked > 0 )) || {
            fmix_error "No matching FMix v2 templates were found."
            return 1
        }
        (( failed == 0 ))
        return
    fi

    [[ -z "$key" ]] || {
        fmix_error "--key is only valid with 'fmix cache verify'."
        return 2
    }
    [[ -n "$cache_base" ]] || {
        fmix_error "cache explain requires --cache-base <N.N.N-stable>."
        return 2
    }

    local worktree real selection_file selected=0 consumer_short="unavailable"
    worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
    fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1
    real="$(fmix_realpath "$worktree")" || return 1
    fmix_activate_toolchain "$real" || return 1
    selection_file="$(mktemp)" || return 1
    if fmix_select_stable_seed "$real" "$cache_base" >"$selection_file"; then
        selected=1
    fi
    rm -f "$selection_file"
    if [[ "$FMIX_STABLE_SEED_CONSUMER_SHA" =~ ^[0-9a-f]{40}$ ]]; then
        consumer_short="${FMIX_STABLE_SEED_CONSUMER_SHA:0:12}"
    fi
    printf 'base=%s\n' "$cache_base"
    printf 'consumer=%s\n' "$consumer_short"
    printf 'candidates=%s\n' "${FMIX_STABLE_SEED_CANDIDATE_COUNT:-0}"
    if (( selected == 1 )); then
        printf 'hit=ancestor\n'
    else
        printf 'miss=%s\n' "${FMIX_STABLE_SEED_SELECTION_REASON:-unknown}"
    fi
    return 0
}

# ---------------------------------------------------------------------------
# cmd: fmix setup
# ---------------------------------------------------------------------------

fmix_command_lock_finish() {
    # Retirement is part of admission/completion, not best-effort cleanup.
    # Preserve an actual compiler/Mix failure as the primary result, with a
    # separate cleanup diagnostic, just like the compile-semaphore contract.
    local lock_name="$1" command_rc="$2" preserve_failure="${3:-0}" cleanup_rc=0
    fmix_lock_release "$lock_name" || cleanup_rc=$?
    if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]] && (( cleanup_rc == 0 )); then
        cleanup_rc=70
    fi
    if (( cleanup_rc != 0 )); then
        printf '{"error":"command_lock_cleanup_failed","command_exit_code":%d,"cleanup_exit_code":%d}\n' "$command_rc" "$cleanup_rc" >&2
        if (( command_rc == 0 || (command_rc == 1 && preserve_failure == 0) )); then
            # A metadata retirement refusal is not retryable lock contention.
            (( cleanup_rc != 1 )) || cleanup_rc=70
            return "$cleanup_rc"
        fi
    fi
    return "$command_rc"
}

cmd_setup() {
    # Command substitutions inside one setup inherit the parent's `bash fmix
    # setup ...` argv and can look recursive in a process snapshot, but they do
    # not call cmd_setup again. A descendant wrapper that actually launches
    # setup does re-enter this function, so carry a function-scoped sentinel
    # through the environment and reject that child before any setup work.
    if [[ "${FMIX_SETUP_ACTIVE:-0}" == "1" ]]; then
        fmix_error "Recursive fmix setup invocation refused; a setup descendant attempted to re-enter setup."
        return 2
    fi
    local FMIX_SETUP_ACTIVE=1
    export FMIX_SETUP_ACTIVE

    local worktree_arg="auto"
    local session_arg=""
    local rebuild_existing=0
    local allow_structure_build=0
    local force_from_zero=0
    while (( $# > 0 )); do
        case "$1" in
            --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
            --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
            --session) [[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }; session_arg="$2"; shift 2 ;;
            --session=*) session_arg="${1#--session=}"; shift ;;
            --rebuild-db) rebuild_existing=1; shift ;;
            --cold-db) rebuild_existing=1; allow_structure_build=1; shift ;;
            # API-2846: explicit, hard-capped full-chain migration from an
            # empty database (bypasses structure.sql entirely — see
            # fmix_migrate_from_zero). Use when structure.sql is stale beyond
            # the freshness gate's tolerance and no hot base exists yet.
            --from-zero) rebuild_existing=1; allow_structure_build=1; force_from_zero=1; shift ;;
            *) fmix_error "Unknown option: $1. Usage: fmix setup [--worktree <path>] [--rebuild-db|--cold-db|--from-zero]"; return 1 ;;
        esac
    done

    local worktree
    worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
    fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1
    local real_worktree
    real_worktree="$(fmix_realpath "$worktree")"
    fmix_activate_toolchain "$real_worktree" || return 1
    fmix_activate_session "$real_worktree" "$session_arg" || return $?
    local template_key
    template_key="$(fmix_compute_template_key "$real_worktree")" || return 1
    local db_name
    db_name="$(fmix_db_name_for_worktree "$real_worktree")"
    local state_file
    state_file="$(fmix_worktree_state_file "$real_worktree")"

    fmix_info "=== fmix setup ==="
    fmix_info "Worktree: $real_worktree"
    fmix_info "Session root: $FMIX_ACTIVE_SESSION_ROOT"
    fmix_info "Template key: $template_key"
    # Surface an unmanaged launcher before a long cold compile, not after it.
    # The publication hold itself is non-fatal; this is advisory only.
    if ! fmix_artifact_v2_managed_entrypoint >/dev/null 2>&1; then
        fmix_warn "This fmix launcher is not the managed install. The cold compile will run, but shared template and dependency artifacts will not publish from it (run 'fmix install', then use \$HOME/.local/bin/fmix)."
    fi
    fmix_info "DB name: $db_name"

    fmix_preflight "$real_worktree" || return $?
    fmix_check_pg_connections

    local lock_name
    lock_name="$(fmix_execution_lock_name "$real_worktree")"
    fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || return $?

    local setup_artifacts_rc=0
    fmix_ensure_artifacts "$real_worktree" "$template_key" 1 || {
        setup_artifacts_rc=$?
        fmix_command_lock_finish "$lock_name" "$setup_artifacts_rc" "$FMIX_LAST_ARTIFACTS_COMPILE_FAILURE"
        return $?
    }
    local setup_compile_rc=0
    fmix_ensure_compile "$real_worktree" "$db_name" setup || setup_compile_rc=$?
    if (( setup_compile_rc != 0 )); then
        fmix_command_lock_finish "$lock_name" "$setup_compile_rc" 1
        return $?
    fi
    # Explicit setup is also the maintenance/backfill lane for the split
    # dependency cache. This imports older proven sessions/templates without
    # slowing ordinary `fmix test` warm hits. Publication remains best-effort:
    # the full source/config template is still authoritative on failure.
    local setup_dependency_fingerprint setup_dependency_lane setup_dependency_artifact
    local setup_dependency_stamp setup_recorded_dependency setup_publication_rc=0
    setup_dependency_fingerprint="$(fmix_compute_dependency_fingerprint \
        "$real_worktree" 2>/dev/null)" || setup_dependency_fingerprint=""
    setup_dependency_stamp="$(fmix_dependency_stamp_file "$real_worktree")"
    setup_recorded_dependency="$(fmix_read_state \
        "$setup_dependency_stamp" dependency_fingerprint 2>/dev/null)" \
        || setup_recorded_dependency=""
    # fmix_ensure_compile just proved or repaired this session. Comparing its
    # recorded exact key to the current manifest/toolchain key avoids another
    # recursive dependency-source guard on every explicit warm setup.
    if [[ -n "$setup_dependency_fingerprint" \
        && "$setup_recorded_dependency" == "$setup_dependency_fingerprint" ]]; then
        setup_dependency_lane="$(fmix_dependency_lane_fingerprint \
            "$real_worktree" 2>/dev/null)" || setup_dependency_lane=""
        setup_dependency_artifact="$(fmix_dependency_artifact_dir \
            "$setup_dependency_lane" "$setup_dependency_fingerprint" 2>/dev/null)" \
            || setup_dependency_artifact=""
        if [[ -n "$setup_dependency_artifact" ]] \
            && fmix_dependency_artifact_quick_ready \
                "$setup_dependency_artifact" "$setup_dependency_lane" \
                "$setup_dependency_fingerprint"; then
            fmix_touch_dependency_artifact_access \
                "$setup_dependency_lane" "$setup_dependency_fingerprint" \
                >/dev/null 2>&1 || setup_publication_rc=$?
        else
            fmix_publish_dependency_artifact \
                "$real_worktree" "$setup_dependency_fingerprint" \
                || setup_publication_rc=$?
        fi
        if (( setup_publication_rc != 0 )); then
            if fmix_lock_failure_is_fatal "$setup_publication_rc"; then
                fmix_command_lock_finish "$lock_name" "$setup_publication_rc"
                return $?
            fi
            case "$setup_publication_rc" in
                2|129|130|143)
                    fmix_command_lock_finish "$lock_name" "$setup_publication_rc"
                    return $? ;;
            esac
            if [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" != "0" ]]; then
                fmix_command_lock_finish "$lock_name" "$setup_publication_rc"
                return $?
            fi
            fmix_warn "Could not backfill the exact dependency artifact during setup."
        fi
    fi
    # Explicit setup is also the maintenance/backfill lane for the local
    # app-compile CAS. Publication remains best-effort: the session's proven
    # application layer is authoritative on failure.
    local setup_app_fingerprint setup_app_lane setup_app_artifact
    local setup_app_publication_rc=0
    if [[ "${FMIX_APP_CAS:-1}" != "0" ]]; then
        setup_app_fingerprint="$(fmix_compute_compile_fingerprint \
            "$real_worktree" 2>/dev/null)" || setup_app_fingerprint=""
        if [[ -n "$setup_app_fingerprint" ]] \
            && fmix_compile_stamp_matches "$real_worktree" "$setup_app_fingerprint"; then
            setup_app_lane="$(fmix_dependency_lane_fingerprint \
                "$real_worktree" 2>/dev/null)" || setup_app_lane=""
            setup_app_artifact="$(fmix_dependency_artifact_dir \
                "$setup_app_lane" "$setup_app_fingerprint" app 2>/dev/null)" \
                || setup_app_artifact=""
            if [[ -n "$setup_app_artifact" ]] \
                && fmix_app_compile_artifact_quick_ready \
                    "$setup_app_artifact" "$setup_app_lane" "$setup_app_fingerprint"; then
                fmix_touch_app_compile_artifact_access \
                    "$setup_app_lane" "$setup_app_fingerprint" \
                    >/dev/null 2>&1 || setup_app_publication_rc=$?
            else
                fmix_publish_app_compile_artifact \
                    "$real_worktree" "$setup_app_fingerprint" \
                    || setup_app_publication_rc=$?
            fi
            if (( setup_app_publication_rc != 0 )); then
                if fmix_lock_failure_is_fatal "$setup_app_publication_rc"; then
                    fmix_command_lock_finish "$lock_name" "$setup_app_publication_rc"
                    return $?
                fi
                case "$setup_app_publication_rc" in
                    2|129|130|143)
                        fmix_command_lock_finish "$lock_name" "$setup_app_publication_rc"
                        return $? ;;
                esac
                if [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" != "0" ]]; then
                    fmix_command_lock_finish "$lock_name" "$setup_app_publication_rc"
                    return $?
                fi
                fmix_warn "Could not backfill the exact app compile artifact during setup."
            fi
        fi
    fi
    fmix_ensure_db "$real_worktree" "$db_name" "$rebuild_existing" "$allow_structure_build" 1 "$force_from_zero" || {
        local operation_rc=$?
        fmix_command_lock_finish "$lock_name" "$operation_rc" "$FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE"
        return $?
    }

    fmix_ensure_migrations "$real_worktree" "$db_name" "$state_file" || {
        local operation_rc=$?
        fmix_command_lock_finish "$lock_name" "$operation_rc" 1
        return $?
    }

    local mig_stamp schema_key published_base
    schema_key="$FMIX_ACTIVE_DB_SCHEMA_KEY"
    if [[ "${FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP:-0}" == "1" ]]; then
        # API-3576: a structure.sql rebuild replaces its same-key published
        # base. From-zero migration publishes under its own lock and has
        # already performed the guarded replacement.
        if [[ "$allow_structure_build" == "1" && "${FMIX_ACTIVE_DB_BASE_ID:-}" != "migrate-from-zero" ]]; then
            FMIX_REPUBLISH_HOT_BASE=1
        else
            FMIX_REPUBLISH_HOT_BASE=0
        fi
        export FMIX_REPUBLISH_HOT_BASE
        published_base="$(fmix_publish_hot_base "$real_worktree" "$db_name" "$schema_key")" || {
            local operation_rc=$?
            fmix_command_lock_finish "$lock_name" "$operation_rc"
            return $?
        }
    else
        # Existing scratch rows may have been changed by a test, task, or
        # operator since the prior setup. A current migration ledger proves
        # schema compatibility only, so this setup can use the DB but cannot
        # promote it into a reusable bootstrap base.
        fmix_warn "Scratch DB already existed; keeping it local because its rows are not proven bootstrap-clean. Use --from-zero for a fresh publishable bootstrap."
        published_base="$FMIX_ACTIVE_DB_BASE_ID"
    fi
    mig_stamp="$(fmix_migration_stamp "$real_worktree")"
    fmix_write_worktree_state "$real_worktree" "$template_key" "$db_name" "$mig_stamp" "$(fmix_now)" "$schema_key" "$published_base" "$schema_key" || {
        fmix_command_lock_finish "$lock_name" 1
        return $?
    }
    local setup_access_rc=0 setup_finish_rc=0
    fmix_update_template_last_used "$template_key" || setup_access_rc=$?
    fmix_command_lock_finish "$lock_name" "$setup_access_rc" || setup_finish_rc=$?
    if (( setup_finish_rc != 0 )); then
        fmix_error "Setup completion failed (template access rc=$setup_access_rc, final rc=$setup_finish_rc)."
        return "$setup_finish_rc"
    fi
    if [[ "${FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP:-0}" == "1" ]]; then
        fmix_info "=== setup complete; hot DB base: $published_base ==="
    else
        fmix_info "=== setup complete; scratch DB remains worktree-local ==="
    fi
    fmix_info "Run: ./fmix test --worktree $real_worktree -- <test args>"
    return 0
}

# ---------------------------------------------------------------------------
# Chromium provisioning for ChromicPDF-backed tests (API-1184)
#
# The real-PDF suites (test/cdrcisco/reporting/uat/*, golden_pdf) delete the
# :pdf_client mock and render via ChromicPDF -> a headless Chromium. ChromicPDF
# auto-discovers `chromium`/`google-chrome` on PATH (deps/chromic_pdf
# chrome_runner.ex). A native macOS runner usually has only "Google Chrome.app"
# (a stub launcher ChromicPDF cannot drive) -> setup_all times out -> the suite
# reports "invalid". CI's Linux api container has a real Chromium, so it passes
# there.
#
# Most dev Macs already have a full headless Chromium from Playwright/Puppeteer
# (the ct-quasar e2e + cdr-corpus tooling install it). Discover one and expose
# it as a PATH `chromium` via a tiny exec-wrapper. A bare symlink does NOT work:
# launching an .app-bundle inner binary through a symlink breaks its
# @executable_path framework resolution and Chrome dies immediately; an exec
# wrapper keeps the real path so the frameworks load. chrome-headless-shell is
# intentionally NOT used — ChromicPDF's --remote-debugging-pipe launch does not
# drive it.
# ---------------------------------------------------------------------------

# Echo a usable full Chromium binary path, or rc=1. Does NOT consider PATH
# (caller checks that first). Order: explicit override, Playwright/Puppeteer
# caches (mac + linux), then full app bundles.
fmix_discover_chromium_binary() {
    if [[ -n "${FMIX_CHROME:-}" && -x "${FMIX_CHROME}" ]]; then
        printf '%s\n' "$FMIX_CHROME"
        return 0
    fi
    # nullglob (scoped to the subshell) so an unmatched cache glob disappears
    # instead of iterating as a literal pattern. Cache binaries (known-good
    # headless Chromium-for-Testing) are checked before the system app bundles.
    local found
    found="$(
        shopt -s nullglob
        for c in \
            "$HOME"/Library/Caches/ms-playwright/chromium-*/chrome-mac*/Chromium.app/Contents/MacOS/Chromium \
            "$HOME"/.cache/ms-playwright/chromium-*/chrome-linux*/chrome \
            "$HOME"/.cache/puppeteer/chrome/*/chrome-mac*/Google\ Chrome\ for\ Testing.app/Contents/MacOS/Google\ Chrome\ for\ Testing \
            "$HOME"/.cache/puppeteer/chrome/*/chrome-linux*/chrome \
            "/Applications/Chromium.app/Contents/MacOS/Chromium" \
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; do
            [[ -x "$c" ]] && { printf '%s\n' "$c"; break; }
        done
    )"
    [[ -n "$found" ]] && { printf '%s\n' "$found"; return 0; }
    return 1
}

# On success rc=0 and echoes a dir to PREPEND to PATH (empty if `chromium` is
# already discoverable, meaning nothing to do). On failure rc=1 (no usable
# Chromium found — caller leaves PATH untouched so the real-PDF suites stay
# "invalid" exactly as before, never worse). Idempotent.
fmix_ensure_chromium() {
    local p
    for p in chromium chromium-browser google-chrome google-chrome-stable; do
        command -v "$p" >/dev/null 2>&1 && return 0
    done
    local chrome bindir shim safe_chrome
    chrome="$(fmix_discover_chromium_binary)" || return 1
    bindir="$FMIX_HOME/chrome"
    shim="$bindir/chromium"
    mkdir -p "$bindir" || return 1
    # Escape single quotes (' -> '\'') so a path with shell metacharacters
    # (quotes, backslashes, $) can't break or inject into the wrapper script.
    safe_chrome="${chrome//\'/\'\\\'\'}"
    if [[ ! -x "$shim" ]] || ! grep -qF "exec '$safe_chrome'" "$shim" 2>/dev/null; then
        # Installing the shim writes shared FMIX_HOME state; escalate first.
        if fmix_lock_any_shared_held; then
            fmix_lock_escalate_exclusive "Chromium shim installation" || return 1
        fi
        printf '#!/bin/sh\nexec '\''%s'\'' "$@"\n' "$safe_chrome" >"$shim" || return 1
        chmod +x "$shim" || return 1
    fi
    printf '%s\n' "$bindir"
    return 0
}

# ---------------------------------------------------------------------------
# cmd: fmix test
# ---------------------------------------------------------------------------

fmix_validate_test_targets() {
    # Mix silently drops nonexistent selections when another file runs. Admit
    # every positional path before home/session/setup effects, without treating
    # Mix option values (tags, regexes, formatters, numbers) as file selections.
    local worktree="$1"
    shift
    local selection option boolean_name target prefix remaining part resolved
    local positional_only=0 takes_value=0
    while (( $# > 0 )); do
        selection="$1"
        shift
        if (( positional_only == 0 )); then
            takes_value=0
            option="${selection%%=*}"
            case "$option" in
                --)
                    if [[ "$selection" == "--" ]]; then
                        positional_only=1
                        continue
                    fi
                    fmix_error "Unsupported or ambiguous Mix test option: $option. Target admission supports documented mix test options only; use -- before a literal positional selection."
                    return 2
                    ;;
                --include|--exclude|--only|--formatter|--name-pattern|--export-coverage|--profile-require|--max-cases|--max-failures|--max-requires|--seed|--timeout|--slowest|--slowest-modules|--partitions|--exit-status|--repeat-until-failure)
                    takes_value=1
                    ;;
                --*)
                    boolean_name="${option#--}"
                    boolean_name="${boolean_name#no-}"
                    case "$boolean_name" in
                        all-warnings|breakpoints|force|color|cover|trace|compile|start|raise|deps-check|archives-check|elixir-version-check|failed|stale|listen-on-stdin|preload-modules|warnings-as-errors|dry-run)
                            continue
                            ;;
                        *)
                            fmix_error "Unsupported or ambiguous Mix test option: $option. Target admission supports documented mix test options only; use -- before a literal positional selection."
                            return 2
                            ;;
                    esac
                    ;;
                -*)
                    # Mix's only short aliases are -b (boolean) and -n
                    # (regex). A cluster ending in -n also consumes a value;
                    # a numeric suffix is an attached value, as in -n2pattern.
                    if [[ "$option" =~ ^-b*n$ ]]; then
                        takes_value=1
                    elif [[ "$option" =~ ^-b+$ || "$option" =~ ^-b*n[0-9][^-_]*$ ]]; then
                        continue
                    elif [[ "$selection" != "-" && "$selection" != "- "* \
                        && ! ( "$selection" =~ ^-[0-9] && "$selection" != *=* ) ]]; then
                        fmix_error "Unsupported or ambiguous Mix test option: $option. Target admission supports documented mix test options only; use -- before a literal positional selection."
                        return 2
                    fi
                    ;;
            esac
            if (( takes_value == 1 )); then
                [[ "$selection" == "$option" ]] || continue
                # Match OptionParser: another switch is not a value, but a
                # negative number, lone '-' or '- ' prefix can be one. Refuse
                # unknown arity before effects; leave value/type validation to
                # Mix rather than implementing another full option parser.
                if (( $# > 0 )) && { [[ "$1" != -* || "$1" == "-" || "$1" == "- "* ]] \
                    || [[ "$1" =~ ^-[0-9] ]]; }; then
                    shift
                else
                    fmix_error "Mix test option requires a value: $option."
                    return 2
                fi
                continue
            fi
        fi
        if [[ -z "$selection" ]]; then
            fmix_error "Invalid test target: empty positional selection."
            return 2
        fi
        # ExUnit treats the first positive numeric colon component as the
        # location boundary (including multiple lines and +/leading-zero forms).
        # Colons before that boundary remain part of the filename.
        target="$selection"
        prefix="${selection%%:*}"
        remaining="$selection"
        while [[ "$remaining" == *:* ]]; do
            remaining="${remaining#*:}"
            part="${remaining%%:*}"
            if [[ "$part" =~ ^[+]?0*[1-9][0-9]*$ ]]; then
                target="$prefix"
                break
            fi
            prefix="$prefix:$part"
        done
        case "$target" in
            /*) resolved="$target" ;;
            *) resolved="$worktree/$target" ;;
        esac
        if [[ -z "$target" || ! -f "$resolved" && ! -d "$resolved" ]]; then
            fmix_error "Missing or non-regular test target: $selection (resolved path: $resolved)."
            return 2
        fi
    done
    return 0
}

cmd_test() {
    local run_mode="${FMIX_INTERNAL_RUN_MODE:-test}"
    local worktree_arg="auto"
    local cache_base="${FMIX_STABLE_BASE:-}"
    local session_arg=""
    local event_fd="${FMIX_EVENT_FD:-}"
    local mix_args=() mix_args_present=0
    local found_sep=0
    local coverage_base=""
    local coverage_threshold="80"
    local -a coverage_sources=()
    # --unit: faithfully reproduce CI's pure-unit lane locally —
    # `CT_TEST_PROFILE=unit mix test.unit --no-start`. The default path runs
    # `mix test.nomigrate`, which STARTS the :cdrcisco app and therefore masks
    # pure-unit failures (missing app-supervised processes, setup_all/on_exit
    # lifecycle) that only surface in CI's --no-start lane. Use --unit before
    # pushing any test that the unit lane will select (test/**/unit/** files
    # that don't `use` a DB-capable case).
    local unit_mode=0 profile_boot=0 profile_fixtures=0
    local isolate_mode=0
    local auto_setup=1
    if [[ "${FMIX_NO_AUTO_SETUP:-0}" == "1" ]]; then
        auto_setup=0
    fi

    while (( $# > 0 )); do
        case "$1" in
            --no-auto-setup)
                auto_setup=0
                shift
                ;;
            --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
            --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
            --cache-base) [[ $# -ge 2 ]] || { fmix_error "--cache-base requires a stable branch."; return 2; }; cache_base="$2"; shift 2 ;;
            --cache-base=*) cache_base="${1#--cache-base=}"; shift ;;
            --session) [[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }; session_arg="$2"; shift 2 ;;
            --session=*) session_arg="${1#--session=}"; shift ;;
            --event-fd)
                [[ $# -ge 2 ]] || { fmix_error "--event-fd requires a file descriptor integer (e.g. 3)."; return 2; }
                event_fd="$2"
                shift 2
                ;;
            --event-fd=*)
                event_fd="${1#--event-fd=}"
                shift
                ;;
            --isolate)
                isolate_mode=1
                shift
                ;;
            --base)
                if [[ "$run_mode" != "coverage" ]]; then
                    fmix_error "--base is only valid with 'fmix coverage'."
                    return 2
                fi
                [[ $# -ge 2 ]] || { fmix_error "--base requires a git ref."; return 2; }
                coverage_base="$2"
                shift 2
                ;;
            --base=*)
                if [[ "$run_mode" != "coverage" ]]; then
                    fmix_error "--base is only valid with 'fmix coverage'."
                    return 2
                fi
                coverage_base="${1#--base=}"
                shift
                ;;
            --threshold)
                if [[ "$run_mode" != "coverage" ]]; then
                    fmix_error "--threshold is only valid with 'fmix coverage'."
                    return 2
                fi
                [[ $# -ge 2 ]] || { fmix_error "--threshold requires a percentage."; return 2; }
                coverage_threshold="$2"
                shift 2
                ;;
            --threshold=*)
                if [[ "$run_mode" != "coverage" ]]; then
                    fmix_error "--threshold is only valid with 'fmix coverage'."
                    return 2
                fi
                coverage_threshold="${1#--threshold=}"
                shift
                ;;
            --source)
                if [[ "$run_mode" != "coverage" ]]; then
                    fmix_error "--source is only valid with 'fmix coverage'."
                    return 2
                fi
                [[ $# -ge 2 ]] || { fmix_error "--source requires a lib/**/*.ex path."; return 2; }
                coverage_sources+=("$2")
                shift 2
                ;;
            --source=*)
                if [[ "$run_mode" != "coverage" ]]; then
                    fmix_error "--source is only valid with 'fmix coverage'."
                    return 2
                fi
                coverage_sources+=("${1#--source=}")
                shift
                ;;
            --unit)
                if [[ "$run_mode" == "coverage" ]]; then
                    fmix_error "--unit is not supported by 'fmix coverage'."
                    return 2
                fi
                unit_mode=1
                shift
                ;;
            --profile-boot|--profile-fixtures)
                if [[ "$run_mode" == "coverage" ]]; then
                    fmix_error "$1 is not supported by 'fmix coverage'."
                    return 2
                fi
                [[ "$1" == "--profile-boot" ]] && profile_boot=1 || profile_fixtures=1
                shift
                ;;
            --) found_sep=1; shift; break ;;
            *)
                if [[ "$run_mode" == "coverage" ]]; then
                    fmix_error "Unknown option: $1. Usage: fmix coverage [--worktree <path>] [--cache-base <N.N.N-stable>] [--no-auto-setup] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>"
                else
                    fmix_error "Unknown option: $1. Usage: fmix test [--worktree <path>] [--cache-base <N.N.N-stable>] [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>"
                fi
                return 1
                ;;
        esac
    done
    if [[ -n "$event_fd" ]]; then
        if [[ ! "$event_fd" =~ ^[0-9]+$ ]]; then
            fmix_error "--event-fd must be a valid integer file descriptor (e.g. 3)."
            return 2
        fi
        export FMIX_EVENT_FD="$event_fd"
    fi
    if (( found_sep == 1 )); then
        if (( $# > 0 )); then
            mix_args=("$@")
            mix_args_present=1
        fi
    fi

    if [[ "$run_mode" == "coverage" ]]; then
        if [[ -z "$coverage_base" ]]; then
            fmix_error "'fmix coverage' requires --base <git-ref> so the changed-module set is explicit."
            return 2
        fi
        if [[ ! "$coverage_threshold" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
            fmix_error "--threshold must be a non-negative number."
            return 2
        fi
        if (( mix_args_present == 0 )); then
            fmix_error "'fmix coverage' requires one or more explicit test paths after --."
            return 2
        fi
        local coverage_target
        if (( mix_args_present == 1 )); then
            for coverage_target in "${mix_args[@]}"; do
                if [[ "$coverage_target" == -* ]]; then
                    fmix_error "'fmix coverage' accepts test paths only after --; unsupported argument: $coverage_target"
                    return 2
                fi
            done
        fi
        local coverage_source
        for coverage_source in ${coverage_sources[@]+"${coverage_sources[@]}"}; do
            if [[ "$coverage_source" != lib/*.ex ]]; then
                fmix_error "--source must name a lib/**/*.ex file: $coverage_source"
                return 2
            fi
        done
    else
        local mix_arg
        if (( mix_args_present == 1 )); then
            for mix_arg in "${mix_args[@]}"; do
                case "$mix_arg" in
                    --cover|--cover=*)
                        fmix_error "Raw mix --cover is disabled: it instruments the entire application and defeats FMix isolation."
                        fmix_error "Use: fmix coverage --worktree <path> --base <git-ref> -- <test paths>"
                        return 2
                        ;;
                esac
            done
        fi
    fi

    local worktree real_worktree
    worktree="$(fmix_find_worktree "$worktree_arg" readonly)" || return 1
    fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1
    real_worktree="$(fmix_realpath "$worktree")" || return 1
    if (( mix_args_present == 1 )); then
        fmix_validate_test_targets "$real_worktree" "${mix_args[@]}" || return $?
    fi

    # main defers all mutable test/coverage preparation until admission passes.
    fmix_prepare_command_home || return 1
    fmix_run_telemetry_begin "$run_mode"

    if (( isolate_mode == 1 )); then
        export FMIX_ISOLATE=1
        if [[ -z "$session_arg" && -z "${FMIX_SESSION_ID:-}" ]]; then
            fmix_error "--isolate requires a stable --session name (or FMIX_SESSION_ID)."
            fmix_error "Default shared mode already serializes concurrent tests on one worktree."
            fmix_run_telemetry_finish 2
            return 2
        fi
    fi

    # Initialize/verify this same candidate only after target admission. This
    # retains cold submodule bootstrap and the normal no-target default.
    worktree="$(fmix_find_worktree "$real_worktree")" || {
        fmix_run_telemetry_finish 1
        return 1
    }
    fmix_activate_toolchain "$real_worktree" || {
        fmix_run_telemetry_finish 1
        return 1
    }
    fmix_emit_phase_change "session" "started"
    fmix_activate_session "$real_worktree" "$session_arg" || {
        local session_rc=$?
        fmix_emit_phase_change "session" "failed"
        fmix_run_telemetry_finish "$session_rc"
        return "$session_rc"
    }
    fmix_run_telemetry_phase "session"
    fmix_emit_phase_change "session" "completed"
    local template_key
    template_key="$(fmix_compute_template_key "$real_worktree")" || {
        fmix_run_telemetry_finish 1
        return 1
    }
    local db_name
    db_name="$(fmix_db_name_for_worktree "$real_worktree")"
    local state_file
    state_file="$(fmix_worktree_state_file "$real_worktree")"
    fmix_run_telemetry_meta \
        "worktree=$real_worktree" \
        "template=$template_key" \
        "db=$db_name"

    fmix_info "=== fmix $run_mode ==="
    fmix_info "Worktree: $real_worktree"
    fmix_info "Session root: $FMIX_ACTIVE_SESSION_ROOT"
    fmix_info "Session source: ${FMIX_ACTIVE_SESSION_SOURCE:-unknown} (hash=${FMIX_ACTIVE_SESSION_HASH:-?})"

    fmix_info "Template key: $template_key"
    fmix_info "DB: $db_name"

    # Cheap preflight on every run
    fmix_emit_phase_change "preflight" "started"
    fmix_preflight "$real_worktree" || {
        local preflight_rc=$?
        fmix_emit_phase_change "preflight" "failed"
        fmix_run_telemetry_finish "$preflight_rc"
        return "$preflight_rc"
    }
    fmix_check_pg_connections
    fmix_run_telemetry_phase "preflight"
    fmix_emit_phase_change "preflight" "completed"

    # Per-worktree lock (serializes concurrent runs in same worktree).
    # Shared (read) mode is used ONLY when the whole run is provably read-only
    # w.r.t. shared state: (a) artifacts resolve warm without mutation, (b)
    # compile is a stamp quick-hit, (c) the scratch DB exists and is
    # migration-current, and (d) this run mode writes no receipts/stamps that
    # mutate shared indexes (test-lane receipts are per-worktree; see
    # docs/fmix.md). Any uncertainty falls back to the exclusive lock, and a
    # shared run that discovers a mutation escalates cleanly before mutating.
    local lock_name lock_mode="exclusive"
    lock_name="$(fmix_execution_lock_name "$real_worktree")"
    if fmix_session_lock_split_enabled \
        && [[ "$run_mode" == "test" ]] \
        && [[ -z "$cache_base" ]] \
        && fmix_run_probe_readonly "$real_worktree" "$template_key" "$db_name"; then
        lock_mode="shared"
        fmix_info "Session lock: shared (provably read-only warm run)."
    else
        fmix_info "Session lock: exclusive."
    fi
    fmix_emit_phase_change "lock" "started"
    fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" \
        "test run" 0 "$lock_mode" || {
        local lock_rc=$?
        fmix_emit_phase_change "lock" "failed"
        fmix_run_telemetry_finish "$lock_rc"
        return "$lock_rc"
    }
    fmix_run_telemetry_phase "lock"
    fmix_emit_phase_change "lock" "completed"

    # Test and coverage runs are immutable snapshots. Capture exact compiler
    # inputs, HEAD, and selected test content only after the canonical
    # worktree lock is held. `fmix task` deliberately does not enable this
    # guard because generators are expected to mutate repository inputs.
    local FMIX_SOURCE_STABILITY_REQUIRED=1
    local FMIX_SOURCE_STABILITY_IDENTITY=""
    local FMIX_SOURCE_STABILITY_COMPILE_IDENTITY=""
    local FMIX_SOURCE_STABILITY_ARGS_HASH=""
    local -a FMIX_SOURCE_STABILITY_SELECTED_ARGS=("${mix_args[@]+"${mix_args[@]}"}")
    FMIX_SOURCE_STABILITY_ARGS_HASH="$(printf '%s\0' "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}" | fmix_hash_stdin)" \
        || FMIX_SOURCE_STABILITY_ARGS_HASH=""
    # Stat-validated capture: per-file digests persisted in the compile stamp
    # (bound to these exact selected args) are reused for stat-unchanged
    # entries; drift is content-hashed fresh. The identity itself is persisted
    # in the next compile stamp, and every fmix_require_stable_source
    # checkpoint revalidates it through the same stat manifest.
    fmix_stat_hash_cache_use "$real_worktree" || true
    if [[ -n "$FMIX_SOURCE_STABILITY_ARGS_HASH" ]] \
        && [[ "$(fmix_read_state "$(fmix_compile_stamp_file "$real_worktree")" source_stability_args_hash 2>/dev/null)" == "$FMIX_SOURCE_STABILITY_ARGS_HASH" ]]; then
        fmix_stat_hash_cache_seed "$(fmix_read_state "$(fmix_compile_stamp_file "$real_worktree")" stat_manifest 2>/dev/null)" \
            || true
    fi
    FMIX_SOURCE_STABILITY_IDENTITY="$(fmix_source_stability_identity \
        "$real_worktree" \
        "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}")" \
        || {
            fmix_stat_hash_cache_done
            fmix_error "Could not capture a source-stability identity after acquiring the worktree lock."
            fmix_invalidate_rejected_stamps "$real_worktree"
            local source_rc=1
            fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
            fmix_run_telemetry_finish "$source_rc"
            return "$source_rc"
        }
    FMIX_SOURCE_STABILITY_COMPILE_IDENTITY="$(
        fmix_source_stability_compile_identity "$real_worktree"
    )" || {
        fmix_stat_hash_cache_done
        fmix_error "Could not capture compile-source identity after acquiring the worktree lock."
        fmix_invalidate_rejected_stamps "$real_worktree"
        local source_rc=1
        fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
        fmix_run_telemetry_finish "$source_rc"
        return "$source_rc"
    }
    fmix_stat_hash_cache_done
    if ! fmix_require_stable_source "$real_worktree" "source identity capture" 1; then
        local source_rc=1
        fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
        fmix_run_telemetry_finish "$source_rc"
        return "$source_rc"
    fi

    # An explicitly selected stable base may seed dependency artifacts. A
    # selector or restore miss is intentionally cold: the unchanged V2
    # artifact path below remains authoritative.
    fmix_emit_phase_change "artifacts" "started"
    local stable_seed_restored=0 stable_seed_restore_rc=1
    if [[ -n "$cache_base" ]]; then
        if fmix_restore_stable_seed "$real_worktree" "$cache_base"; then
            stable_seed_restored=1
            FMIX_LAST_ARTIFACTS_OUTCOME="stable_seed"
        else
            stable_seed_restore_rc=$?
            if (( stable_seed_restore_rc != 1 )); then
                if (( stable_seed_restore_rc == 2 )); then
                    fmix_error "Stable seed restore could not roll back safely; refusing V2 artifact fallback."
                else
                    fmix_error "Stable seed restore was interrupted; refusing V2 artifact fallback."
                fi
                fmix_command_lock_finish "$lock_name" "$stable_seed_restore_rc" 1 || stable_seed_restore_rc=$?
                fmix_emit_phase_change "artifacts" "failed"
                fmix_run_telemetry_finish "$stable_seed_restore_rc"
                return "$stable_seed_restore_rc"
            fi
        fi
    fi
    if (( stable_seed_restored == 0 )); then
        local artifacts_rc=0
        FMIX_AUTO_SETUP="$auto_setup" fmix_ensure_artifacts "$real_worktree" "$template_key" 0 || artifacts_rc=$?
        if (( artifacts_rc != 0 )); then
            if [[ "$FMIX_LAST_ARTIFACTS_OUTCOME" == "missing_template" && "$auto_setup" == "1" ]]; then
                fmix_info "Artifact template $template_key is missing. Auto-bootstrapping setup (--worktree $real_worktree)..."
                fmix_command_lock_finish "$lock_name" 0 || true
                local setup_rc=0
                local -a auto_setup_cmd=(cmd_setup --worktree "$real_worktree")
                [[ -n "$session_arg" ]] && auto_setup_cmd+=(--session "$session_arg")
                "${auto_setup_cmd[@]}" || setup_rc=$?
                if (( setup_rc != 0 )); then
                    fmix_error "Auto-setup failed (exit $setup_rc)."
                    fmix_error "DO NOT push untested code to remote CI; run 'fmix setup --worktree $real_worktree' locally (takes ~30s)."
                    fmix_emit_phase_change "artifacts" "failed"
                    fmix_run_telemetry_finish "$setup_rc"
                    fmix_write_test_receipt "$real_worktree" "$setup_rc" "$session_arg" "${mix_args[*]:-}"
                    return "$setup_rc"
                fi
                fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || {
                    local re_lock_rc=$?
                    fmix_emit_phase_change "artifacts" "failed"
                    fmix_run_telemetry_finish "$re_lock_rc"
                    fmix_write_test_receipt "$real_worktree" "$re_lock_rc" "$session_arg" "${mix_args[*]:-}"
                    return "$re_lock_rc"
                }
                FMIX_AUTO_SETUP=0 fmix_ensure_artifacts "$real_worktree" "$template_key" 0 || {
                    local operation_rc=$?
                    fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
                    FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-error}"
                    fmix_emit_phase_change "artifacts" "failed"
                    fmix_run_telemetry_finish "$operation_rc"
                    fmix_write_test_receipt "$real_worktree" "$operation_rc" "$session_arg" "${mix_args[*]:-}"
                    return "$operation_rc"
                }
            else
                local operation_rc="$artifacts_rc"
                fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
                FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-error}"
                fmix_emit_phase_change "artifacts" "failed"
                fmix_run_telemetry_finish "$operation_rc"
                fmix_write_test_receipt "$real_worktree" "$operation_rc" "$session_arg" "${mix_args[*]:-}"
                return "$operation_rc"
            fi
        fi
        FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-ready}"
    fi
    fmix_run_telemetry_phase "artifacts"
    fmix_emit_phase_change "artifacts" "completed"

    # Compile (incremental)
    fmix_emit_phase_change "compile" "started"
    local compile_rc=0
    fmix_ensure_compile "$real_worktree" "$db_name" || compile_rc=$?
    if (( compile_rc != 0 )); then
        fmix_command_lock_finish "$lock_name" "$compile_rc" 1 || compile_rc=$?
        fmix_emit_phase_change "compile" "failed"
        fmix_run_telemetry_finish "$compile_rc"
        fmix_write_test_receipt "$real_worktree" "$compile_rc" "$session_arg" "${mix_args[*]:-}"
        return "$compile_rc"
    fi
    if ! fmix_require_stable_source "$real_worktree" "compilation" 1; then
        local source_rc=1
        fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
        fmix_emit_phase_change "compile" "failed"
        fmix_run_telemetry_finish "$source_rc"
        fmix_write_test_receipt "$real_worktree" "$source_rc" "$session_arg" "${mix_args[*]:-}"
        return "$source_rc"
    fi
    fmix_run_telemetry_phase "compile"
    fmix_emit_phase_change "compile" "completed"

    # Ensure DB exists
    fmix_emit_phase_change "db" "started"
    fmix_ensure_db "$real_worktree" "$db_name" 0 0 0 || {
        local operation_rc=$?
        fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
        fmix_emit_phase_change "db" "failed"
        fmix_run_telemetry_finish "$operation_rc"
        return "$operation_rc"
    }
    fmix_run_telemetry_phase "db"
    fmix_emit_phase_change "db" "completed"

    # Migration drift check (compares current stamp against what is in the state file)
    fmix_emit_phase_change "migrate" "started"
    fmix_ensure_migrations "$real_worktree" "$db_name" "$state_file" || {
        local operation_rc=$?
        fmix_command_lock_finish "$lock_name" "$operation_rc" 1 || operation_rc=$?
        fmix_emit_phase_change "migrate" "failed"
        fmix_run_telemetry_finish "$operation_rc"
        return "$operation_rc"
    }
    fmix_run_telemetry_phase "migrate"
    fmix_emit_phase_change "migrate" "completed"

    local mig_stamp schema_key
    schema_key="$FMIX_ACTIVE_DB_SCHEMA_KEY"
    mig_stamp="$(fmix_migration_stamp "$real_worktree")"
    fmix_publish_run_worktree_state "$real_worktree" "$template_key" "$db_name" "$mig_stamp" "$schema_key" "$FMIX_ACTIVE_DB_BASE_ID" "$FMIX_ACTIVE_DB_SOURCE_KEY" || {
        local operation_rc=$?
        fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
        fmix_run_telemetry_finish "$operation_rc"
        return "$operation_rc"
    }
    # Keep the worktree lock through ExUnit: callers for the same realpath share
    # one scratch DB. Different worktrees remain fully independent.
    fmix_prepend_toolchain_paths

    # API-1184: make a headless Chromium discoverable so ChromicPDF-backed
    # reporting suites render natively instead of timing out ("invalid").
    local _chrome_bindir
    if _chrome_bindir="$(fmix_ensure_chromium)"; then
        [[ -n "$_chrome_bindir" ]] && export PATH="$_chrome_bindir:$PATH"
    else
        fmix_info "No headless Chromium found — real-PDF suites (reporting/uat) will report 'invalid'. Install one: 'npx playwright install chromium' or set FMIX_CHROME=/path/to/chromium."
    fi

    # Pure-unit lane fidelity: CI runs `CT_TEST_PROFILE=unit mix test.unit
    # --no-start`. Reproduce that EXACTLY in --unit mode so app-not-started
    # failures surface locally instead of in CI. Default mode keeps
    # `mix test.nomigrate` (full app + warm DB).
    local mix_task="test.nomigrate"
    # fmix already completed and verified the incremental compile while holding
    # the per-worktree lock. Do not make Mix run the compiler pipeline again as
    # the test task starts. User arguments remain last so test selection and
    # formatter options retain their normal behavior.
    local -a run_args
    run_args=("--no-compile")
    if (( mix_args_present == 1 )); then
        run_args+=("${mix_args[@]}")
    fi
    if [[ "$run_mode" == "coverage" ]]; then
        fmix_info "Running targeted diff coverage against $coverage_base (${#mix_args[@]} explicit test target(s), threshold ${coverage_threshold}%)."
        if (( ${#coverage_sources[@]} > 0 )); then
            fmix_info "Source scope: ${#coverage_sources[@]} explicit changed module(s)."
        else
            fmix_info "Source scope: every changed lib module."
        fi
        fmix_info "Compilation is disabled; only scoped changed-module BEAMs will be cover-instrumented."
    elif (( unit_mode == 1 )); then
        mix_task="test.unit"
        run_args=("--no-start" "--no-compile")
        if (( mix_args_present == 1 )); then
            run_args+=("${mix_args[@]}")
        fi
        fmix_info "Running (pure-unit lane / CI parity): CT_TEST_PROFILE=unit mix ${mix_task} ${run_args[*]+"${run_args[*]}"}"
    else
        fmix_info "Running: mix ${mix_task} ${run_args[*]+"${run_args[*]}"}"
    fi
    fmix_info "DB: $db_name"
    fmix_check_known_nif_caches "$real_worktree"
    echo "" >&2

    local t0 t1
    t0=$(fmix_epoch)

    # CT_SKIP_MIGRATION_TIMING=1: under `mix test.nomigrate`, test_helper.exs
    # otherwise runs Ecto.Migrator.run/3 on every secondary repo "to time
    # migrations" — but fmix has ALREADY brought the scratch DB to the right
    # schema (structure.sql load + delta migrate). That redundant pass re-applies
    # migrations against a clone whose schema_migrations may not perfectly match
    # the live MVs and corrupts the scratch DB. fmix owns migrations; tell the
    # test boot to trust the DB.
    # In --unit mode set CT_TEST_PROFILE=unit so test_helper.exs takes the
    # pure-unit path (skips Application.ensure_all_started(:cdrcisco)), matching
    # the CI lane on top of `--no-start`.
    local -a profile_env=()
    (( unit_mode == 1 )) && profile_env=("CT_TEST_PROFILE=unit")
    # Opt-in TestProf-style hooks implemented by the cisco-cdr harness.
    (( profile_boot == 1 )) && profile_env+=("CT_TEST_BOOT_PROFILE=1")
    (( profile_fixtures == 1 )) && profile_env+=("CT_TEST_FIXTURE_PROF=1")
    local mix_guard_pre_ms mix_spawn_ms mix_exit_ms
    mix_guard_pre_ms="$(fmix_epoch_ms)"

    local -a build_env=()
    [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
    [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")

    if ! fmix_require_stable_source "$real_worktree" "Mix startup"; then
        local source_rc=1
        fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
        fmix_emit_phase_change "mix_test" "failed"
        fmix_run_telemetry_finish "$source_rc"
        return "$source_rc"
    fi

    fmix_emit_phase_change "mix_test" "started"
    local test_rc=0
    mix_spawn_ms="$(fmix_epoch_ms)"
    (
        cd "$real_worktree" || exit 1
        local -a common_env=(
            -u DB_HOST_IPV4
            "${build_env[@]+"${build_env[@]}"}"
            "${profile_env[@]+"${profile_env[@]}"}"
            MIX_ENV=test
            DB_HOSTNAME="$DB_HOST"
            DB_PORT="$DB_PORT"
            DB_USER="$DB_USER"
            DB_PASSWORD="$DB_PASSWORD"
            DB_NAME="$db_name"
            DB_TEST_POOL_SIZE=30
            LOCAL_NATS="$NATS_HOST"
            NATS_PORT="$NATS_PORT"
            NATS_HOST="$NATS_HOST"
            CT_NATS_HOST="$NATS_HOST"
            NATS_URL="nats://${NATS_HOST}:${NATS_PORT}"
            WORKER_NODE=TRUE
            ADMIN_NODE=TRUE
            ONPREM=TRUE
            SECRET_KEY_BASE="$SECRET_KEY_BASE"
            MEESEEKS_HTML5EVER_BUILD=0
            CT_SKIP_MIGRATION_TIMING=1
            POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}"
            POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}"
        )
        [[ -n "$event_fd" ]] && common_env+=("FMIX_EVENT_FD=$event_fd")
        # The child must observe the same run and session identity that
        # fmix_emit_phase_change stamps into each NDJSON record, or a consumer
        # cannot correlate the child's output with the phase stream.
        local pass_session_id="${FMIX_SESSION_ID:-${session_arg:-${FMIX_ACTIVE_SESSION_HASH:-}}}"
        [[ -n "$pass_session_id" ]] && common_env+=("FMIX_SESSION_ID=$pass_session_id")
        [[ -n "${FMIX_RUN_ID:-}" ]] && common_env+=("FMIX_RUN_ID=$FMIX_RUN_ID")
        common_env+=("FMIX_MIX_SPAWN_AT_MS=$mix_spawn_ms")
        if [[ "$run_mode" == "coverage" ]]; then
            local coverage_targets="${mix_args[*]}"
            local coverage_bootstrap
            coverage_bootstrap='
unless function_exported?(Mix.TasksServer, :put, 1) do
  Mix.raise("fmix coverage requires Mix.TasksServer.put/1 to enforce no-compile execution")
end

Mix.TasksServer.put({:task, "compile", Mix.Project.get()})

{opts, _argv, invalid} =
  OptionParser.parse(System.argv(),
    strict: [
      base: :string,
      source: :keep,
      test_targets: :string,
      threshold: :float
    ]
  )

if invalid != [] do
  Mix.raise("fmix coverage received invalid targeted options: #{inspect(invalid)}")
end

sources = Keyword.get_values(opts, :source)

if sources == [] do
  Mix.Tasks.Cdrcisco.DiffCoverage.run(System.argv())
else
  base = Keyword.fetch!(opts, :base)
  threshold = Keyword.get(opts, :threshold, 80.0)
  base_sha = Mix.Tasks.Cdrcisco.DiffCoverage.resolve_base_sha(base, false)

  changed =
    Mix.Tasks.Cdrcisco.DiffCoverage.changed_lib_files_from_paths(
      Enum.join(sources, "\n"),
      &Mix.Tasks.Cdrcisco.DiffCoverage.changed_lines(base, false, &1, "HEAD")
    )

  gate_opts = [test_targets: Keyword.fetch!(opts, :test_targets)]

  Mix.Tasks.Cdrcisco.DiffCoverage.run_gate(
    base,
    base_sha,
    changed,
    gate_opts,
    threshold
  )
end
'
            local -a coverage_source_args=()
            local coverage_source
            for coverage_source in ${coverage_sources[@]+"${coverage_sources[@]}"}; do
                coverage_source_args+=(--source "$coverage_source")
            done
            exec env "${common_env[@]}" \
                mix run --no-start --no-compile \
                -e "$coverage_bootstrap" -- \
                --base "$coverage_base" \
                "${coverage_source_args[@]+"${coverage_source_args[@]}"}" \
                --test-targets "$coverage_targets" \
                --threshold "$coverage_threshold"
        else
            exec env "${common_env[@]}" \
                mix "$mix_task" "${run_args[@]+"${run_args[@]}"}"
        fi
    )
    test_rc=$?
    mix_exit_ms="$(fmix_epoch_ms)"

    local source_stable_after_mix=1
    if ! fmix_require_stable_source "$real_worktree" "Mix execution"; then
        source_stable_after_mix=0
        test_rc=1
    fi
    fmix_write_mix_boundaries "$mix_guard_pre_ms" "$mix_spawn_ms" "$mix_exit_ms" "$(fmix_epoch_ms)" \
        "$( (( profile_boot == 1 )) && echo true || echo false)" "$( (( profile_fixtures == 1 )) && echo true || echo false)"

    t1=$(fmix_epoch)
    local test_duration_ms=$(( (t1 - t0) * 1000 ))
    (( test_duration_ms < 0 )) && test_duration_ms=0
    fmix_run_telemetry_phase "mix_test"
    if (( test_rc == 0 )); then
        fmix_emit_phase_change "mix_test" "completed" "$test_duration_ms"
    else
        fmix_emit_phase_change "mix_test" "failed" "$test_duration_ms"
    fi

    # A drifted run must not refresh successful-use provenance. Ordinary test
    # failures retain the historical last-used behavior when source stayed
    # fixed for the entire run.
    if (( source_stable_after_mix == 1 )); then
        fmix_update_last_used "$state_file"
        fmix_update_template_last_used "$template_key"
    fi
    fmix_command_lock_finish "$lock_name" "$test_rc" 1 || test_rc=$?

    if [[ "$run_mode" == "coverage" ]]; then
        fmix_info "Targeted coverage completed in $(( t1 - t0 ))s (rc=$test_rc)."
    else
        fmix_info "Test run completed in $(( t1 - t0 ))s (rc=$test_rc)."
    fi
    fmix_write_test_receipt "$real_worktree" "$test_rc" "$session_arg" "${mix_args[*]:-}"
    fmix_run_telemetry_finish "$test_rc"
    return $test_rc
}

cmd_coverage() {
    FMIX_INTERNAL_RUN_MODE=coverage cmd_test "$@"
}

# ---------------------------------------------------------------------------
# Pre-Push Circuit Breaker & Proof-of-Test Receipt
# ---------------------------------------------------------------------------

fmix_git_dir() {
    local wt="$1"
    local gd
    gd="$(git -C "$wt" rev-parse --path-format=absolute --git-dir 2>/dev/null)" || {
        gd="$(git -C "$wt" rev-parse --git-dir 2>/dev/null)" || return 1
        gd="$(cd "$wt" && cd "$gd" && pwd -P)" || return 1
    }
    printf '%s\n' "$gd"
}

fmix_compute_code_tree_hash() {
    local wt="$1"
    local py_bin
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    "$py_bin" - "$wt" <<'PY'
import hashlib, os, subprocess, sys
from pathlib import Path

root = Path(sys.argv[1]).resolve()
tree = {}
prefixes = ("lib", "test", "priv", "config", "mix.exs", "mix.lock")

# 1. Committed blobs from HEAD
res = subprocess.run(
    ["git", "-C", str(root), "-c", "core.quotepath=false", "ls-tree", "-r", "HEAD", "--", *prefixes],
    capture_output=True, text=True, check=False
)
if res.returncode == 0:
    for line in res.stdout.splitlines():
        if not line:
            continue
        parts = line.split(None, 3)
        if len(parts) >= 4 and parts[1] == "blob":
            tree[parts[3]] = parts[2]

# 2. Status changes (modified, added, untracked, deleted)
res = subprocess.run(
    ["git", "-C", str(root), "-c", "core.quotepath=false", "status", "--porcelain", "-uall", "--", *prefixes],
    capture_output=True, text=True, check=False
)
if res.returncode == 0:
    for line in res.stdout.splitlines():
        if not line:
            continue
        rpath = line[3:].strip()
        if " -> " in rpath:
            old_p, new_p = rpath.split(" -> ", 1)
            tree.pop(old_p.strip(), None)
            rpath = new_p.strip()
        fpath = root / rpath
        if fpath.is_file() and not fpath.is_symlink():
            try:
                data = fpath.read_bytes()
                sha = hashlib.sha1(f"blob {len(data)}\0".encode("utf-8") + data).hexdigest()
                tree[rpath] = sha
            except OSError:
                tree.pop(rpath, None)
        else:
            tree.pop(rpath, None)

manifest = "\n".join(f"{p}\t{tree[p]}" for p in sorted(tree.keys())) + "\n"
print(hashlib.sha256(manifest.encode("utf-8")).hexdigest())
PY
}

# REL-3972: a receipt records the canonical worktree it was produced for.
# verify-push accepts it only when that path equals the worktree being pushed.
fmix_receipt_worktree() {
    local receipt_file="$1" py_bin declared=""
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    declared="$("$py_bin" -I -S -B - "$receipt_file" 2>/dev/null <<'PY'
import json
import sys

with open(sys.argv[1], "r", encoding="utf-8") as handle:
    value = json.load(handle)
declared = value.get("worktree") if isinstance(value, dict) else None
print(declared if isinstance(declared, str) else "")
PY
)" || declared=""
    printf '%s\n' "$declared"
}

fmix_write_test_receipt() {
    local wt="$1" rc="${2:-0}" session="${3:-}" test_args="${4:-}"
    local git_dir real_wt
    git_dir="$(fmix_git_dir "$wt" 2>/dev/null)" || return 0
    [[ -d "$git_dir" ]] || return 0
    real_wt="$(fmix_realpath "$wt")" || return 0

    # REL-3972: never attest a run for this worktree from another worktree's
    # active session record.
    if [[ -n "${FMIX_ACTIVE_SESSION_ROOT:-}" && -f "$FMIX_ACTIVE_SESSION_ROOT/meta.json" ]]; then
        local recorded_wt=""
        recorded_wt="$(fmix_session_record_worktree "$FMIX_ACTIVE_SESSION_ROOT/meta.json" 2>/dev/null)" \
            || recorded_wt=""
        if [[ -n "$recorded_wt" && "$recorded_wt" != "$real_wt" ]]; then
            fmix_error "worktree_session_mismatch: active session records worktree $recorded_wt, not $real_wt; no receipt written."
            return 1
        fi
    fi

    local code_tree_hash
    code_tree_hash="$(fmix_compute_code_tree_hash "$wt" 2>/dev/null)" || code_tree_hash=""
    [[ -n "$code_tree_hash" ]] || return 0

    local head_sha
    head_sha="$(git -C "$wt" rev-parse HEAD 2>/dev/null || echo "0000000000000000000000000000000000000000")"
    local now
    now="$(fmix_epoch)"
    local passed="false"
    (( rc == 0 )) && passed="true"

    local receipt_file="$git_dir/ct-fmix-receipt.json"
    local tmp_file
    tmp_file="$(mktemp "${TMPDIR:-/tmp}/ct-fmix-receipt.XXXXXX")" || return 0

    local py_bin
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    "$py_bin" - "$tmp_file" "$passed" "$rc" "$now" "$head_sha" "$code_tree_hash" "$session" "$test_args" "$real_wt" <<'PY'
import json, sys
tmp_file, passed, rc, ts, head, code_hash, session, args, worktree = sys.argv[1:10]
doc = {
    "schema_version": 1,
    "passed": passed == "true",
    "rc": int(rc),
    "ts_epoch": int(ts),
    "head_sha": head,
    "code_tree_hash": code_hash,
    "session": session,
    "test_args": args,
    "worktree": worktree
}
with open(tmp_file, "w", encoding="utf-8") as f:
    json.dump(doc, f, indent=2)
    f.write("\n")
PY
    mv -f "$tmp_file" "$receipt_file" 2>/dev/null || rm -f "$tmp_file"
    fmix_info "Proof-of-test receipt recorded at $receipt_file (passed=$passed, code_tree_hash=$code_tree_hash)"
}

fmix_record_push_ledger() {
    local wt="$1" git_dir="$2"
    local ledger_file="$git_dir/ct-push-ledger.tsv"
    local branch
    branch="$(git -C "$wt" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "HEAD")"
    local now
    now="$(fmix_epoch)"
    local receipt_file="$git_dir/ct-fmix-receipt.json"
    local receipt_epoch=0
    if [[ -f "$receipt_file" ]]; then
        receipt_epoch="$(grep -o '"ts_epoch":[[:space:]]*[0-9]*' "$receipt_file" 2>/dev/null | awk -F: '{print $2}' | tr -d ' ')"
    fi
    receipt_epoch="${receipt_epoch:-0}"
    printf '%s\t%s\t%s\t%s\n' "$now" "$branch" "pass" "$receipt_epoch" >> "$ledger_file"
}

cmd_verify_push() {
    local worktree_arg="auto"
    local cooldown_minutes=30
    local require_receipt=0

    while (( $# > 0 )); do
        case "$1" in
            --worktree)
                [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }
                worktree_arg="$2"
                shift 2
                ;;
            --worktree=*)
                worktree_arg="${1#--worktree=}"
                shift
                ;;
            --cooldown-minutes)
                [[ $# -ge 2 ]] || { fmix_error "--cooldown-minutes requires an integer."; return 2; }
                cooldown_minutes="$2"
                shift 2
                ;;
            --cooldown-minutes=*)
                cooldown_minutes="${1#--cooldown-minutes=}"
                shift
                ;;
            --require-receipt)
                require_receipt=1
                shift
                ;;
            --help|-h)
                fmix_verb_help "verify-push"
                return 0
                ;;
            *)
                # Git pre-push hook passes remote name and url as positional arguments; ignore them
                shift
                ;;
        esac
    done

    # 1. Human Escape Hatch
    if [[ "${CT_HUMAN:-0}" == "1" || "${FMIX_BYPASS_PUSH_GATE:-0}" == "1" ]]; then
        fmix_info "[fmix verify-push] Push allowed: human bypass active (CT_HUMAN=1 or FMIX_BYPASS_PUSH_GATE=1)."
        return 0
    fi

    local worktree=""
    if [[ "$worktree_arg" != "auto" ]]; then
        worktree="$(fmix_find_worktree "$worktree_arg" 2>/dev/null || fmix_realpath "$worktree_arg")"
        fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1
    else
        worktree="$(fmix_find_worktree auto 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
    fi
    local real_worktree
    real_worktree="$(fmix_realpath "$worktree")"

    if ! git -C "$real_worktree" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
        fmix_error "Path is not inside a git worktree: $real_worktree"
        return 1
    fi

    local git_dir
    git_dir="$(fmix_git_dir "$real_worktree")" || {
        fmix_error "Could not resolve git directory for $real_worktree"
        return 1
    }

    # 2. Docs / Workflow-Only Fast Pass
    local base_ref=""
    if git -C "$real_worktree" rev-parse --verify "@{upstream}" >/dev/null 2>&1; then
        base_ref="@{upstream}"
    else
        local candidate
        for candidate in origin/0.8.8-stable origin/0.8.7-stable origin/0.8.6-stable origin/main main; do
            if git -C "$real_worktree" rev-parse --verify "$candidate" >/dev/null 2>&1; then
                base_ref="$candidate"
                break
            fi
        done
    fi

    if [[ -n "$base_ref" ]]; then
        local diff_files
        diff_files="$(git -C "$real_worktree" diff --name-only "$base_ref"...HEAD 2>/dev/null || true)"
        if [[ -n "$diff_files" ]]; then
            local elixir_code_touched=0
            local f
            while IFS= read -r f; do
                [[ -z "$f" ]] && continue
                case "$f" in
                    lib/*|test/*|priv/*|mix.exs|mix.lock|config/*)
                        elixir_code_touched=1
                        break
                        ;;
                esac
            done <<< "$diff_files"
            if (( elixir_code_touched == 0 )); then
                fmix_info "[fmix verify-push] Push allowed: only non-Elixir files modified (docs/workflows)."
                return 0
            fi
        fi
    fi

    # 3. Draft PR Fast Pass (unless --require-receipt is explicitly specified)
    local pr_status=""
    if (( require_receipt == 0 )); then
        local py_bin
        py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
        pr_status="$("$py_bin" - "$real_worktree" <<'PY'
import json, subprocess, sys

wt = sys.argv[1]
try:
    res = subprocess.run(
        ["gh", "pr", "view", "--json", "isDraft,state"],
        cwd=wt,
        capture_output=True,
        text=True,
        timeout=4.0
    )
    if res.returncode != 0:
        # No open PR found or gh error
        print("no_open_pr")
        sys.exit(0)
    data = json.loads(res.stdout)
    if data.get("state") != "OPEN":
        print("no_open_pr")
    elif data.get("isDraft") is True:
        print("draft_pr")
    else:
        print("non_draft_pr")
except subprocess.TimeoutExpired:
    print("timeout")
except Exception:
    print("error")
PY
)"
        case "$pr_status" in
            no_open_pr|draft_pr|timeout|error)
                fmix_info "[fmix verify-push] Push allowed: no open ready PR ($pr_status). Encouraging Draft-First PR workflow."
                fmix_record_push_ledger "$real_worktree" "$git_dir"
                return 0
                ;;
        esac
    fi

    # 4. Proof-of-Local-Test Gate (Open Non-Draft PR or --require-receipt)
    local receipt_file="$git_dir/ct-fmix-receipt.json"
    local current_code_tree_hash
    current_code_tree_hash="$(fmix_compute_code_tree_hash "$real_worktree" 2>/dev/null)" || current_code_tree_hash=""

    local receipt_valid=0 receipt_reason=""
    local receipt_passed=0
    local receipt_hash=""
    local receipt_epoch=0

    if [[ -f "$receipt_file" ]]; then
        local py_bin
        py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
        local receipt_info
        receipt_info="$("$py_bin" - "$receipt_file" <<'PY'
import json, sys
try:
    with open(sys.argv[1], "r", encoding="utf-8") as f:
        d = json.load(f)
    passed = "1" if d.get("passed") is True else "0"
    h = str(d.get("code_tree_hash", ""))
    ts = str(d.get("ts_epoch", 0))
    print(f"{passed}\t{h}\t{ts}")
except Exception:
    print("0\t\t0")
PY
)"
        IFS=$'\t' read -r receipt_passed receipt_hash receipt_epoch <<< "$receipt_info"
        # REL-3972: a receipt only proves the worktree it names.
        local receipt_worktree
        receipt_worktree="$(fmix_receipt_worktree "$receipt_file" 2>/dev/null)" || receipt_worktree=""
        if [[ -z "$receipt_worktree" ]]; then
            receipt_reason="receipt predates worktree binding; re-run fmix test"
            receipt_passed=0
        elif [[ "$receipt_worktree" != "$real_worktree" ]]; then
            receipt_reason="receipt worktree $receipt_worktree != $real_worktree"
            receipt_passed=0
        fi
        if [[ "$receipt_passed" == "1" && "$receipt_hash" == "$current_code_tree_hash" && -n "$current_code_tree_hash" ]]; then
            receipt_valid=1
        fi
    fi

    if (( receipt_valid == 0 )); then
        if [[ -n "$receipt_reason" ]]; then
            fmix_error "[fmix CIRCUIT BREAKER] Receipt refused: $receipt_reason."
        fi
        fmix_error "[fmix CIRCUIT BREAKER] Refusing push to open non-draft PR without a passing local fmix test receipt for the current code state. Run 'fmix test -- <test_files>' locally first, OR convert the PR to draft ('gh pr ready --undo') before pushing WIP commits."
        return 1
    fi

    # 5. 30-Minute Push Rate-Limiter (<git-dir>/ct-push-ledger.tsv)
    local ledger_file="$git_dir/ct-push-ledger.tsv"
    local branch
    branch="$(git -C "$real_worktree" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "HEAD")"
    local now
    now="$(fmix_epoch)"
    local window_seconds=$(( cooldown_minutes * 60 ))
    local cutoff=$(( now - window_seconds ))

    local recent_pushes=0
    local last_push_epoch=0

    if [[ -f "$ledger_file" ]]; then
        while IFS=$'\t' read -r p_ts p_branch p_hash p_rec_ts; do
            [[ -z "$p_ts" || "$p_branch" != "$branch" ]] && continue
            if (( p_ts >= cutoff )); then
                recent_pushes=$(( recent_pushes + 1 ))
            fi
            if (( p_ts > last_push_epoch )); then
                last_push_epoch="$p_ts"
            fi
        done < "$ledger_file"
    fi

    if (( recent_pushes >= 2 && receipt_epoch <= last_push_epoch )); then
        fmix_error "[fmix CIRCUIT BREAKER] Push rate limit exceeded: $recent_pushes pushes in the last ${cooldown_minutes}m without a new passing test receipt recorded since the last push ($last_push_epoch). Run 'fmix test' locally before pushing again."
        return 1
    fi

    printf '%s\t%s\t%s\t%s\n' "$now" "$branch" "$current_code_tree_hash" "$receipt_epoch" >> "$ledger_file"
    fmix_info "[fmix verify-push] Push verified and allowed."
    return 0
}

cmd_hook_install() {
    local worktree_arg="auto"
    while (( $# > 0 )); do
        case "$1" in
            --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
            --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
            *) fmix_error "Unknown option: $1. Usage: fmix hook install [--worktree <path>]"; return 1 ;;
        esac
    done
    local worktree=""
    if [[ "$worktree_arg" != "auto" ]]; then
        worktree="$(fmix_find_worktree "$worktree_arg" 2>/dev/null || fmix_realpath "$worktree_arg")"
        fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1
    else
        worktree="$(fmix_find_worktree auto 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
    fi
    local real_worktree
    real_worktree="$(fmix_realpath "$worktree")"
    if ! git -C "$real_worktree" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
        fmix_error "Path is not inside a git worktree: $real_worktree"
        return 1
    fi
    local git_dir
    git_dir="$(fmix_git_dir "$real_worktree")" || {
        fmix_error "Could not resolve git directory for $real_worktree"
        return 1
    }
    local hooks_dir="$git_dir/hooks"
    mkdir -p "$hooks_dir" || return 1
    local hook_file="$hooks_dir/pre-push"
    if [[ -f "$hook_file" ]]; then
        if grep -q "fmix verify-push" "$hook_file"; then
            fmix_info "fmix pre-push hook already installed in $hook_file"
            return 0
        fi
        printf '\n# fmix pre-push circuit breaker\nfmix verify-push --worktree "$PWD" "$@"\n' >> "$hook_file"
    else
        cat > "$hook_file" <<'EOF'
#!/usr/bin/env bash
# Installed by fmix hook install
set -e
fmix verify-push --worktree "$PWD" "$@"
EOF
        chmod +x "$hook_file"
    fi
    fmix_info "Installed pre-push hook in $hook_file"
    return 0
}

cmd_hook() {
    local subcmd="${1:-}"
    shift || true
    case "$subcmd" in
        install)
            cmd_hook_install "$@"
            ;;
        *)
            fmix_error "Unknown hook subcommand: '${subcmd:-empty}'. Usage: fmix hook install [--worktree <path>]"
            return 1
            ;;
    esac
}

# ---------------------------------------------------------------------------
# cmd: fmix runner — distributed runner CLI (portal Worker + orchestrator REST)
# ---------------------------------------------------------------------------
# The CLI speaks plain REST against the portal base URL (FMIX_RUNNER_URL); the
# portal Worker signs the inner HMAC envelope for orchestrator hops itself.
# Auth is the Cloudflare Access service-token pair sent as
# CF-Access-Client-Id / CF-Access-Client-Secret headers (mcp-launch env
# convention), with FMIX_RUNNER_TOKEN as a bearer fallback.

FMIX_RUNNER_URL_DEFAULT="https://mcp.calltelemetry.com/fmix-runner"
FMIX_RUNNER_HOOK_MARKER="# managed-by: fmix runner/hooks"

fmix_runner_base_url() {
    local url="${FMIX_RUNNER_URL:-$FMIX_RUNNER_URL_DEFAULT}"
    printf '%s\n' "${url%/}"
}

fmix_runner_resolve_auth() {
    FMIX_RUNNER_AUTH_ID=""
    FMIX_RUNNER_AUTH_SECRET=""
    FMIX_RUNNER_AUTH_BEARER="${FMIX_RUNNER_TOKEN:-}"
    if [[ -n "${CF_ACCESS_CLIENT_ID:-}" && -n "${CF_ACCESS_CLIENT_SECRET:-}" ]]; then
        FMIX_RUNNER_AUTH_ID="$CF_ACCESS_CLIENT_ID"
        FMIX_RUNNER_AUTH_SECRET="$CF_ACCESS_CLIENT_SECRET"
        return 0
    fi
    local user_name id_val secret_val
    user_name="${USER:-$(id -un 2>/dev/null || printf '')}"
    if [[ -n "$user_name" ]]; then
        id_val="$(printenv "MCP_ACCESS_CLIENT_ID_${user_name}" 2>/dev/null || true)"
        secret_val="$(printenv "MCP_ACCESS_CLIENT_SECRET_${user_name}" 2>/dev/null || true)"
        if [[ -n "$id_val" && -n "$secret_val" ]]; then
            FMIX_RUNNER_AUTH_ID="$id_val"
            FMIX_RUNNER_AUTH_SECRET="$secret_val"
            return 0
        fi
    fi
    if [[ -n "$FMIX_RUNNER_AUTH_BEARER" ]]; then
        return 0
    fi
    fmix_error "fmix runner: missing portal credentials (no request sent)."
    fmix_error "Set CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET (Cloudflare Access service token),"
    fmix_error "or the per-user pair MCP_ACCESS_CLIENT_ID_${user_name:-<USER>} / MCP_ACCESS_CLIENT_SECRET_${user_name:-<USER>},"
    fmix_error "or FMIX_RUNNER_TOKEN as a bearer token."
    return 1
}

fmix_runner_http_ok() {
    case "${FMIX_RUNNER_HTTP_STATUS:-}" in
        2*) return 0 ;;
    esac
    return 1
}

fmix_runner_request() {
    # fmix_runner_request <METHOD> <path> [<json-body>]
    # Lands the response body in FMIX_RUNNER_HTTP_BODY and the HTTP status in
    # FMIX_RUNNER_HTTP_STATUS (globals: callers must NOT run this in a
    # command substitution). Curl transport failures return 1 (no status).
    local method="$1" path="$2" body="${3:-}"
    FMIX_RUNNER_HTTP_STATUS=""
    FMIX_RUNNER_HTTP_BODY=""
    local url resp_file http_code curl_rc
    url="$(fmix_runner_base_url)$path"
    resp_file="$(mktemp "${TMPDIR:-/tmp}/fmix-runner.XXXXXX")" || {
        fmix_error "fmix runner: could not allocate a response file."
        return 1
    }
    local -a curl_args=()
    curl_args=(-sS --connect-timeout "${FMIX_RUNNER_CONNECT_TIMEOUT_S:-5}" --max-time "${FMIX_RUNNER_TIMEOUT_S:-60}")
    curl_args+=(-X "$method" -H "Accept: application/json")
    if [[ -n "$FMIX_RUNNER_AUTH_ID" ]]; then
        curl_args+=(-H "CF-Access-Client-Id: ${FMIX_RUNNER_AUTH_ID}")
        curl_args+=(-H "CF-Access-Client-Secret: ${FMIX_RUNNER_AUTH_SECRET}")
    fi
    if [[ -n "$FMIX_RUNNER_AUTH_BEARER" ]]; then
        curl_args+=(-H "Authorization: Bearer ${FMIX_RUNNER_AUTH_BEARER}")
    fi
    if [[ -n "$body" ]]; then
        curl_args+=(-H "Content-Type: application/json")
        curl_args+=(--data-binary "$body")
    fi
    curl_args+=(-o "$resp_file" -w '%{http_code}')
    http_code="$(curl "${curl_args[@]+"${curl_args[@]}"}" "$url")"
    curl_rc=$?
    if (( curl_rc != 0 )); then
        rm -f "$resp_file"
        fmix_error "fmix runner: transport failure calling $url (curl exit $curl_rc)."
        return 1
    fi
    FMIX_RUNNER_HTTP_STATUS="$http_code"
    if [[ -s "$resp_file" ]]; then
        FMIX_RUNNER_HTTP_BODY="$(cat "$resp_file")"
    fi
    rm -f "$resp_file"
    return 0
}

fmix_runner_reply_ok() {
    # fmix_runner_reply_ok <context> <body> — shared non-2xx error path.
    local context="$1" body="${2:-}"
    if fmix_runner_http_ok; then
        return 0
    fi
    fmix_error "fmix runner: $context failed (HTTP ${FMIX_RUNNER_HTTP_STATUS:-000})."
    if [[ -n "$body" ]]; then
        fmix_error "$body"
    fi
    return 1
}

fmix_runner_json_field() {
    # fmix_runner_json_field <field> — reads a JSON object on stdin and prints
    # one top-level field (empty output when absent or unparseable). Nested
    # values print as compact JSON.
    local field="$1" py_bin
    py_bin="$(fmix_python_bin 2>/dev/null || printf 'python3')"
    "$py_bin" -c '
import json, sys
try:
    data = json.load(sys.stdin)
except Exception:
    sys.exit(1)
value = data.get(sys.argv[1], "") if isinstance(data, dict) else ""
if isinstance(value, (dict, list)):
    print(json.dumps(value, separators=(",", ":")))
elif value is None or value == "":
    sys.exit(0)
elif isinstance(value, bool):
    print("true" if value else "false")
else:
    print(value)
' "$field"
}

fmix_runner_require_job_id() {
    local job_id="${1:-}"
    if [[ -z "$job_id" ]]; then
        fmix_error "fmix runner: missing <job-id>."
        return 1
    fi
    if [[ ! "$job_id" =~ ^[A-Za-z0-9._-]{1,128}$ ]]; then
        fmix_error "fmix runner: job id '$job_id' must match [A-Za-z0-9._-]{1,128}."
        return 1
    fi
    printf '%s\n' "$job_id"
}

fmix_runner_worktree_name() {
    # Named runner worktree = basename of the resolved local checkout.
    basename "$1"
}

fmix_runner_submit_body() {
    # fmix_runner_submit_body <repo> <worktree-name> <ref> <command> [args...]
    local repo="$1" worktree_name="$2" ref="$3" command="$4"
    shift 4
    local args_json="" a
    for a in "$@"; do
        args_json="${args_json}${args_json:+,}$(fmix_json_escape "$a")"
    done
    printf '{"repo": %s, "worktree": %s, "ref": %s, "rebase": "none", "command": %s, "args": [%s], "mode": "ephemeral"}\n' \
        "$(fmix_json_escape "$repo")" \
        "$(fmix_json_escape "$worktree_name")" \
        "$(fmix_json_escape "$ref")" \
        "$(fmix_json_escape "$command")" \
        "$args_json"
}

cmd_runner_submit() {
    local worktree_arg="auto" ref_arg="" saw_sep=0
    while (( $# > 0 )); do
        case "$1" in
            --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
            --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
            --ref) [[ $# -ge 2 ]] || { fmix_error "--ref requires a ref argument."; return 2; }; ref_arg="$2"; shift 2 ;;
            --ref=*) ref_arg="${1#--ref=}"; shift ;;
            --) shift; saw_sep=1; break ;;
            *) fmix_error "Unknown option: $1. Usage: fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]"; return 1 ;;
        esac
    done
    if (( saw_sep == 0 )); then
        fmix_error "fmix runner submit requires '--': fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]"
        return 1
    fi
    if [[ $# -lt 1 ]]; then
        fmix_error "fmix runner submit needs a command after '--' (test, coverage, or task)."
        return 1
    fi
    local command="$1"
    shift
    case "$command" in
        test|coverage|task) ;;
        *) fmix_error "fmix runner submit command must be test, coverage, or task (got '$command')."; return 1 ;;
    esac
    local -a args=("$@")

    local worktree
    if [[ "$worktree_arg" != "auto" ]]; then
        worktree="$(fmix_find_worktree "$worktree_arg" readonly 2>/dev/null || fmix_realpath "$worktree_arg")"
        fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1
    else
        worktree="$(fmix_find_worktree auto readonly 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
    fi
    local real_worktree
    real_worktree="$(fmix_realpath "$worktree")"
    local origin_url repo
    origin_url="$(git -C "$real_worktree" remote get-url origin 2>/dev/null || true)"
    if [[ -z "$origin_url" ]]; then
        fmix_error "fmix runner submit: no 'origin' remote in $real_worktree; cannot derive owner/name."
        return 1
    fi
    # Same owner/name normalisation the runner pre-push hook uses.
    repo="$(printf '%s' "$origin_url" | sed -E -e 's#^.*github\.com[:/]##' -e 's#\.git$##' -e 's#/$##')"
    local worktree_name
    worktree_name="$(fmix_runner_worktree_name "$real_worktree")"
    local ref="$ref_arg"
    if [[ -z "$ref" ]]; then
        ref="$(git -C "$real_worktree" rev-parse HEAD 2>/dev/null || true)"
        if [[ -z "$ref" ]]; then
            fmix_error "fmix runner submit: could not resolve HEAD in $real_worktree (pass --ref <ref>)."
            return 1
        fi
    fi

    local body
    body="$(fmix_runner_submit_body "$repo" "$worktree_name" "$ref" "$command" ${args[@]+"${args[@]}"})"
    fmix_runner_resolve_auth || return 1
    local resp job_id state
    fmix_runner_request POST "/jobs" "$body" || return 1
    resp="$FMIX_RUNNER_HTTP_BODY"
    fmix_runner_reply_ok "submit" "$resp" || return 1
    job_id="$(printf '%s' "$resp" | fmix_runner_json_field job_id 2>/dev/null || true)"
    if [[ -z "$job_id" ]]; then
        fmix_error "fmix runner: submit response carried no job_id:"
        fmix_error "$resp"
        return 1
    fi
    state="$(printf '%s' "$resp" | fmix_runner_json_field state 2>/dev/null || true)"
    fmix_info "Runner job accepted: $job_id (state=${state:-unknown}, repo=$repo, ref=$ref)"
    printf '%s\n' "$job_id"
    return 0
}

cmd_runner_status() {
    if [[ $# -gt 1 ]]; then
        fmix_error "Usage: fmix runner status <job-id>"
        return 1
    fi
    local job_id
    job_id="$(fmix_runner_require_job_id "${1:-}")" || return 1
    fmix_runner_resolve_auth || return 1
    local resp state
    fmix_runner_request GET "/jobs/$job_id" || return 1
    resp="$FMIX_RUNNER_HTTP_BODY"
    fmix_runner_reply_ok "status $job_id" "$resp" || return 1
    state="$(printf '%s' "$resp" | fmix_runner_json_field state 2>/dev/null || true)"
    if [[ -n "$state" ]]; then
        fmix_info "Job $job_id state: $state"
    fi
    printf '%s\n' "$resp"
}

cmd_runner_logs() {
    local job_id="" tail_n="" query=""
    while (( $# > 0 )); do
        case "$1" in
            --tail) [[ $# -ge 2 ]] || { fmix_error "--tail requires a line count."; return 2; }; tail_n="$2"; shift 2 ;;
            --tail=*) tail_n="${1#--tail=}"; shift ;;
            -*) fmix_error "Unknown option: $1. Usage: fmix runner logs <job-id> [--tail N]"; return 1 ;;
            *) if [[ -z "$job_id" ]]; then job_id="$1"; shift; else fmix_error "Unexpected argument: $1. Usage: fmix runner logs <job-id> [--tail N]"; return 1; fi ;;
        esac
    done
    job_id="$(fmix_runner_require_job_id "$job_id")" || return 1
    if [[ -n "$tail_n" ]]; then
        if [[ ! "$tail_n" =~ ^[1-9][0-9]*$ ]] || (( 10#$tail_n > 10000 )); then
            fmix_error "fmix runner logs --tail must be an integer in [1, 10000]."
            return 1
        fi
        query="?tail=$tail_n"
    fi
    fmix_runner_resolve_auth || return 1
    local resp
    fmix_runner_request GET "/jobs/$job_id/logs$query" || return 1
    resp="$FMIX_RUNNER_HTTP_BODY"
    fmix_runner_reply_ok "logs $job_id" "$resp" || return 1
    if [[ -n "$tail_n" ]]; then
        printf '%s\n' "$resp" | tail -n "$tail_n"
    else
        printf '%s\n' "$resp"
    fi
}

cmd_runner_cancel() {
    if [[ $# -gt 1 ]]; then
        fmix_error "Usage: fmix runner cancel <job-id>"
        return 1
    fi
    local job_id
    job_id="$(fmix_runner_require_job_id "${1:-}")" || return 1
    fmix_runner_resolve_auth || return 1
    local resp
    fmix_runner_request DELETE "/jobs/$job_id" || return 1
    resp="$FMIX_RUNNER_HTTP_BODY"
    fmix_runner_reply_ok "cancel $job_id" "$resp" || return 1
    printf '%s\n' "$resp"
}

cmd_runner_list() {
    local worktree_filter="" state_filter="" query=""
    while (( $# > 0 )); do
        case "$1" in
            --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a name argument."; return 2; }; worktree_filter="$2"; shift 2 ;;
            --worktree=*) worktree_filter="${1#--worktree=}"; shift ;;
            --state) [[ $# -ge 2 ]] || { fmix_error "--state requires a state argument."; return 2; }; state_filter="$2"; shift 2 ;;
            --state=*) state_filter="${1#--state=}"; shift ;;
            *) fmix_error "Unknown option: $1. Usage: fmix runner list [--worktree <name>] [--state <state>]"; return 1 ;;
        esac
    done
    if [[ -n "$worktree_filter" ]]; then
        if [[ ! "$worktree_filter" =~ ^[A-Za-z0-9._/:-]{1,256}$ ]]; then
            fmix_error "fmix runner list: invalid --worktree name '$worktree_filter'."
            return 1
        fi
        query="?worktree=$worktree_filter"
    fi
    if [[ -n "$state_filter" ]]; then
        if [[ ! "$state_filter" =~ ^[A-Za-z0-9_-]{1,64}$ ]]; then
            fmix_error "fmix runner list: invalid --state '$state_filter'."
            return 1
        fi
        if [[ -n "$query" ]]; then
            query="$query&state=$state_filter"
        else
            query="?state=$state_filter"
        fi
    fi
    fmix_runner_resolve_auth || return 1
    local resp
    fmix_runner_request GET "/jobs$query" || return 1
    resp="$FMIX_RUNNER_HTTP_BODY"
    fmix_runner_reply_ok "list" "$resp" || return 1
    printf '%s\n' "$resp"
}

fmix_runner_verify_receipt() {
    # fmix_runner_verify_receipt <receipt-json> <pubkey-file>
    # Offline Ed25519 verification of the receipt_v1 envelope: the signature
    # covers the canonical JSON (sorted keys, Go json.Marshal string escaping)
    # of every field except signature. Uses `openssl pkeyutl -rawin` when the
    # local openssl supports it, else an embedded python3 verifier. Fail-closed:
    # missing capability, unreadable key, or any mismatch is a hard failure.
    local receipt_json="$1" pubkey_path="$2"
    local py_bin tmp_dir prep_rc verify_rc=1
    py_bin="$(fmix_python_bin 2>/dev/null || printf 'python3')"
    if ! command -v "$py_bin" >/dev/null 2>&1; then
        fmix_error "fmix runner: python3 is required for receipt verification."
        return 1
    fi
    tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/fmix-receipt.XXXXXX")" || {
        fmix_error "fmix runner: could not allocate a verification directory."
        return 1
    }
    printf '%s' "$receipt_json" > "$tmp_dir/receipt.json"
    "$py_bin" - "$tmp_dir" "$pubkey_path" <<'FMIX_RECEIPT_PREPARE_PY'
import base64, binascii, json, os, sys


def fail(msg):
    sys.stderr.write("  [fmix ERROR] fmix runner receipt: " + msg + "\n")
    raise SystemExit(1)


def go_string(value):
    # Mirror Go encoding/json string output: UTF-8 kept, HTML characters
    # always escaped, standard short escapes for control characters.
    out = json.dumps(value, ensure_ascii=False)
    for src, dst in (
        ("&", "\\u0026"),
        ("<", "\\u003c"),
        (">", "\\u003e"),
        ("\u2028", "\\u2028"),
        ("\u2029", "\\u2029"),
    ):
        out = out.replace(src, dst)
    return out


def canonical(node):
    if isinstance(node, dict):
        parts = []
        for key in sorted(node):
            parts.append(go_string(key) + ":" + canonical(node[key]))
        return "{" + ",".join(parts) + "}"
    if isinstance(node, list):
        return "[" + ",".join(canonical(item) for item in node) + "]"
    if node is None:
        return "null"
    if isinstance(node, bool):
        return "true" if node else "false"
    if isinstance(node, (int, float)):
        return json.dumps(node)
    return go_string(node)


def decode_32_key(raw):
    text = raw.strip()
    if b"-----BEGIN" in text:
        lines = [line for line in text.splitlines() if b"-----" not in line]
        try:
            der = base64.b64decode(b"".join(lines))
        except (binascii.Error, ValueError):
            fail("could not decode public key PEM")
        prefix = bytes.fromhex("302a300506032b6570032100")
        if len(der) != 44 or not der.startswith(prefix):
            fail("public key PEM is not an Ed25519 SPKI key")
        return der[12:]
    try:
        text.decode("ascii")
    except UnicodeDecodeError:
        fail("public key must be Ed25519 SPKI PEM, base64, or hex")
    candidates = []
    try:
        candidates.append(binascii.unhexlify(text))
    except (binascii.Error, ValueError):
        pass
    for decoder in (
        lambda s: base64.b64decode(s, validate=True),
        lambda s: base64.b64decode(s + b"=" * (-len(s) % 4)),
    ):
        try:
            candidates.append(decoder(text))
        except (binascii.Error, ValueError):
            pass
    for candidate in candidates:
        if len(candidate) == 32:
            return candidate
    fail("public key must decode to 32 raw Ed25519 bytes (base64 or hex) or an SPKI PEM")


def decode_sig(value):
    try:
        raw = value.encode("ascii")
    except UnicodeDecodeError:
        fail("signature is not base64")
    candidates = []
    for decoder in (
        lambda s: base64.b64decode(s, validate=True),
        lambda s: base64.b64decode(s + b"=" * (-len(s) % 4)),
    ):
        try:
            candidates.append(decoder(raw))
        except (binascii.Error, ValueError):
            pass
    for candidate in candidates:
        if len(candidate) == 64:
            return candidate
    fail("signature is not 64-byte base64 Ed25519 material")


out_dir = sys.argv[1]
pubkey_path = sys.argv[2]
try:
    with open(os.path.join(out_dir, "receipt.json"), encoding="utf-8") as handle:
        receipt = json.load(handle)
except (OSError, ValueError):
    fail("receipt is not valid JSON")
if not isinstance(receipt, dict):
    fail("receipt must be a JSON object")
signature = receipt.get("signature", "")
if not isinstance(signature, str) or not signature:
    fail("receipt is unsigned (missing signature)")
view = dict(receipt)
del view["signature"]
with open(os.path.join(out_dir, "canon.bin"), "wb") as handle:
    handle.write(canonical(view).encode("utf-8"))
with open(os.path.join(out_dir, "sig.bin"), "wb") as handle:
    handle.write(decode_sig(signature))
try:
    with open(pubkey_path, "rb") as handle:
        pub_raw = handle.read()
except OSError:
    fail("could not read public key " + pubkey_path)
key = decode_32_key(pub_raw)
with open(os.path.join(out_dir, "pub.bin"), "wb") as handle:
    handle.write(key)
prefix = bytes.fromhex("302a300506032b6570032100")
pem_text = (
    "-----BEGIN PUBLIC KEY-----\n"
    + base64.encodebytes(prefix + key).decode("ascii")
    + "-----END PUBLIC KEY-----\n"
)
with open(os.path.join(out_dir, "pub.pem"), "w", encoding="ascii") as handle:
    handle.write(pem_text)
FMIX_RECEIPT_PREPARE_PY
    prep_rc=$?
    if (( prep_rc != 0 )); then
        rm -rf "$tmp_dir"
        return 1
    fi
    if command -v openssl >/dev/null 2>&1 && openssl pkeyutl -help 2>&1 | grep -q -- '-rawin'; then
        if openssl pkeyutl -verify -pubin -inkey "$tmp_dir/pub.pem" -rawin -in "$tmp_dir/canon.bin" -sigfile "$tmp_dir/sig.bin" >/dev/null 2>&1; then
            verify_rc=0
        fi
    else
        "$py_bin" - "$tmp_dir" <<'FMIX_RECEIPT_ED25519_PY'
# Pure-python Ed25519 verify (RFC 8032), used only when the local openssl
# cannot do `pkeyutl -rawin`. Reads canon.bin / sig.bin / pub.bin from argv[1].
import hashlib, os, sys

p = 2 ** 255 - 19
d = (-121665 * pow(121666, p - 2, p)) % p
q = 2 ** 252 + 27742317777372353535851937790883648493


def inv(x):
    return pow(x, p - 2, p)


def xrecover(y):
    xx = (y * y - 1) * inv(d * y * y + 1)
    x = pow(xx, (p + 3) // 8, p)
    if (x * x - xx) % p != 0:
        x = (x * pow(2, (p - 1) // 4, p)) % p
    if x % 2 != 0:
        x = p - x
    return x


By = 4 * inv(5)
Bx = xrecover(By)
B = (Bx % p, By % p, 1, (Bx * By) % p)


def edwards_add(P, Q):
    x1, y1, z1, t1 = P
    x2, y2, z2, t2 = Q
    a = ((y1 - x1) * (y2 - x2)) % p
    b = ((y1 + x1) * (y2 + x2)) % p
    c = (2 * t1 * t2 * d) % p
    dd = (2 * z1 * z2) % p
    e = b - a
    f = dd - c
    g = dd + c
    h = b + a
    return ((e * f) % p, (g * h) % p, (f * g) % p, (e * h) % p)


def scalarmult(P, e):
    Q = (0, 1, 1, 0)
    while e > 0:
        if e & 1:
            Q = edwards_add(Q, P)
        P = edwards_add(P, P)
        e >>= 1
    return Q


def encodepoint(P):
    x, y, z, t = P
    zi = inv(z)
    x = x * zi % p
    y = y * zi % p
    bits = [(y >> i) & 1 for i in range(255)] + [x & 1]
    return bytes(sum(bits[i * 8 + j] << j for j in range(8)) for i in range(32))


def decodeint(s):
    return int.from_bytes(s, "little")


def decodepoint(s):
    y = decodeint(s)
    sign = (y >> 255) & 1
    y &= (1 << 255) - 1
    if y >= p:
        raise ValueError("non-canonical point encoding")
    x = xrecover(y)
    if x & 1 != sign:
        x = p - x
    return (x, y, 1, (x * y) % p)


out_dir = sys.argv[1]
pub = open(os.path.join(out_dir, "pub.bin"), "rb").read()
sig = open(os.path.join(out_dir, "sig.bin"), "rb").read()
msg = open(os.path.join(out_dir, "canon.bin"), "rb").read()
if len(pub) != 32 or len(sig) != 64:
    sys.exit(1)
try:
    A = decodepoint(pub)
    R = decodepoint(sig[:32])
except Exception:
    sys.exit(1)
S = decodeint(sig[32:])
if S >= q:
    sys.exit(1)
h = decodeint(hashlib.sha512(sig[:32] + pub + msg).digest()) % q
left = encodepoint(scalarmult(B, S))
right = encodepoint(edwards_add(R, scalarmult(A, h)))
sys.exit(0 if left == right else 1)
FMIX_RECEIPT_ED25519_PY
        verify_rc=$?
    fi
    rm -rf "$tmp_dir"
    return "$verify_rc"
}

cmd_runner_receipt() {
    local job_id="" verify=0 pubkey="${FMIX_RUNNER_PUBKEY:-}" verify_rc=0
    while (( $# > 0 )); do
        case "$1" in
            --verify) verify=1; shift ;;
            --pubkey) [[ $# -ge 2 ]] || { fmix_error "--pubkey requires a path argument."; return 2; }; pubkey="$2"; shift 2 ;;
            --pubkey=*) pubkey="${1#--pubkey=}"; shift ;;
            -*) fmix_error "Unknown option: $1. Usage: fmix runner receipt <job-id> [--verify [--pubkey <path>]]"; return 1 ;;
            *) if [[ -z "$job_id" ]]; then job_id="$1"; shift; else fmix_error "Unexpected argument: $1. Usage: fmix runner receipt <job-id> [--verify [--pubkey <path>]]"; return 1; fi ;;
        esac
    done
    job_id="$(fmix_runner_require_job_id "$job_id")" || return 1
    fmix_runner_resolve_auth || return 1
    local resp
    fmix_runner_request GET "/jobs/$job_id/receipt" || return 1
    resp="$FMIX_RUNNER_HTTP_BODY"
    fmix_runner_reply_ok "receipt $job_id" "$resp" || return 1
    if (( verify == 1 )); then
        if [[ -z "$pubkey" ]]; then
            fmix_error "fmix runner: receipt --verify needs an Ed25519 public key (--pubkey <path> or FMIX_RUNNER_PUBKEY)."
            return 1
        fi
        if [[ ! -f "$pubkey" ]]; then
            fmix_error "fmix runner: receipt public key '$pubkey' not found."
            return 1
        fi
        if ! fmix_runner_verify_receipt "$resp" "$pubkey"; then
            fmix_error "fmix runner: receipt $job_id signature verification FAILED."
            verify_rc=1
        else
            fmix_info "Receipt $job_id signature verified (ed25519)."
        fi
    fi
    printf '%s\n' "$resp"
    return "$verify_rc"
}

cmd_runner_gc_worktree() {
    if [[ $# -gt 1 ]]; then
        fmix_error "Usage: fmix runner gc-worktree <worktree>"
        return 1
    fi
    local worktree_name="${1:-}"
    if [[ -z "$worktree_name" ]]; then
        fmix_error "Usage: fmix runner gc-worktree <worktree>"
        return 1
    fi
    if [[ ! "$worktree_name" =~ ^[A-Za-z0-9._/:-]{1,256}$ ]]; then
        fmix_error "fmix runner gc-worktree: invalid worktree name '$worktree_name' (want [A-Za-z0-9._/:-]{1,256})."
        return 1
    fi
    local body
    body="{\"worktree\": $(fmix_json_escape "$worktree_name")}"
    fmix_runner_resolve_auth || return 1
    local resp
    fmix_runner_request POST "/worktrees/gc" "$body" || return 1
    resp="$FMIX_RUNNER_HTTP_BODY"
    fmix_runner_reply_ok "gc-worktree $worktree_name" "$resp" || return 1
    printf '%s\n' "$resp"
}

fmix_runner_write_pre_push_hook() {
    # Minimal fmix runner pre-push hook body (used when runner/hooks/ is not
    # vendored next to this script). Same hard contract as runner/hooks/pre-push:
    # NEVER blocks or fails a push; every path exits 0.
    cat <<'FMIX_HOOK_EOF'
#!/usr/bin/env bash
# managed-by: fmix runner/hooks
# Minimal fmix runner pre-push hook (installed by `fmix runner install-hooks`).
# Fires the runner's ahead-of-webhook trigger lane BEFORE refs are remote
# visible. HARD CONTRACT: never blocks or fails a push; every path exits 0.
#
# Config (env first, then git config):
#   FMIX_RUNNER_HOOK_URL  portal hook endpoint; defaults to
#                         ${FMIX_RUNNER_URL%/}/hooks/git when FMIX_RUNNER_URL is set
#   FMIX_RUNNER_TOKEN     bearer token (fmix.runnerToken)
#   FMIX_RUNNER_LANE      lane params (fmix.lane; default "mix test --seed 0")
#   FMIX_RUNNER_SECRET    optional HMAC secret (fmix.runnerSecret)

HOOK_URL="${FMIX_RUNNER_HOOK_URL:-}"
TOKEN="${FMIX_RUNNER_TOKEN:-}"
LANE="${FMIX_RUNNER_LANE:-}"
SECRET="${FMIX_RUNNER_SECRET:-}"
[ -n "$TOKEN" ] || TOKEN="$(git config --get fmix.runnerToken 2>/dev/null || true)"
[ -n "$LANE" ] || LANE="$(git config --get fmix.lane 2>/dev/null || true)"
LANE="${LANE:-mix test --seed 0}"
[ -n "$SECRET" ] || SECRET="$(git config --get fmix.runnerSecret 2>/dev/null || true)"
if [ -z "$HOOK_URL" ] && [ -n "${FMIX_RUNNER_URL:-}" ]; then
  HOOK_URL="${FMIX_RUNNER_URL%/}/hooks/git"
fi
[ -n "$HOOK_URL" ] || exit 0

ORIGIN_URL="$(git remote get-url origin 2>/dev/null || true)"
[ -n "$ORIGIN_URL" ] || exit 0
REPO="$(printf '%s' "$ORIGIN_URL" | sed -E \
  -e 's#^.*github\.com[:/]##' \
  -e 's#\.git$##' \
  -e 's#/$##')"
ZERO_SHA="0000000000000000000000000000000000000000"

fire() {
  head_sha="$1"
  remote_ref="$2"
  nonce="$$-$(date +%s)-${RANDOM}"
  ts="$(date +%s)"
  lane_esc="$(printf '%s' "$LANE" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')"
  body="{\"repo\":\"$REPO\",\"head_sha\":\"$head_sha\",\"remote_ref\":\"$remote_ref\",\"awaiting_ref\":true,\"lane\":\"$lane_esc\"}"
  curl_args=(-sS --connect-timeout 2 --max-time 3 -H "Content-Type: application/json")
  if [ -n "$TOKEN" ]; then
    curl_args+=(-H "Authorization: Bearer ${TOKEN}")
  fi
  if [ -n "$SECRET" ] && command -v openssl >/dev/null 2>&1; then
    sig="$(printf 'v1:%s:%s:%s' "$ts" "$nonce" "$body" \
      | openssl dgst -sha256 -hmac "$SECRET" 2>/dev/null | awk '{print $NF}')"
    if [ -n "$sig" ]; then
      curl_args+=(-H "X-Fmix-Runner-Timestamp: ${ts}")
      curl_args+=(-H "X-Fmix-Runner-Nonce: ${nonce}")
      curl_args+=(-H "X-Fmix-Runner-Signature: sha256=${sig}")
    fi
  fi
  ( curl "${curl_args[@]}" -d "$body" "$HOOK_URL" >/dev/null 2>&1 ) &
}

seen_refs=""
while read -r local_ref local_sha remote_ref; do
  [ -z "$local_ref" ] && continue
  [ "$local_sha" = "$ZERO_SHA" ] && continue
  case "$seen_refs" in
    *"|$remote_ref|"*) continue ;;
  esac
  seen_refs="$seen_refs|$remote_ref|"
  fire "$local_sha" "$remote_ref"
done
exit 0
FMIX_HOOK_EOF
}

cmd_runner_install_hooks() {
    local worktree_arg="auto" legacy=0 force=0
    while (( $# > 0 )); do
        case "$1" in
            --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
            --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
            --legacy) legacy=1; shift ;;
            --force) force=1; shift ;;
            *) fmix_error "Unknown option: $1. Usage: fmix runner install-hooks [--worktree <path>] [--legacy] [--force]"; return 1 ;;
        esac
    done
    local worktree
    if [[ "$worktree_arg" != "auto" ]]; then
        worktree="$(fmix_find_worktree "$worktree_arg" readonly 2>/dev/null || fmix_realpath "$worktree_arg")"
        fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1
    else
        worktree="$(fmix_find_worktree auto readonly 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
    fi
    local real_worktree
    real_worktree="$(fmix_realpath "$worktree")"
    # A repo checkout carries runner/hooks/install-hooks.sh next to this
    # script; delegate to it so dev installs match the shipped hooks exactly.
    local self_dir installer=""
    self_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
    if [[ -f "$self_dir/runner/hooks/install-hooks.sh" ]]; then
        installer="$self_dir/runner/hooks/install-hooks.sh"
    fi
    local -a inst_args=()
    if (( legacy == 1 )); then
        inst_args+=(--legacy)
    fi
    if (( force == 1 )); then
        inst_args+=(--force)
    fi
    if [[ -n "$installer" ]]; then
        fmix_info "fmix runner install-hooks: delegating to $installer"
        ( cd "$real_worktree" && bash "$installer" ${inst_args[@]+"${inst_args[@]}"} )
        return $?
    fi

    # Minimal inline install (idempotent): pre-push into .githooks/ +
    # core.hooksPath, or straight into .git/hooks with --legacy. A foreign
    # (unmarked) hook is never clobbered without --force.
    local repo_root git_dir
    repo_root="$(git -C "$real_worktree" rev-parse --show-toplevel 2>/dev/null || true)"
    git_dir="$(fmix_git_dir "$real_worktree" 2>/dev/null || true)"
    if [[ -z "$repo_root" || -z "$git_dir" ]]; then
        fmix_warn "fmix runner install-hooks: not inside a git repository — nothing installed"
        return 0
    fi
    local target_dir mode="path"
    if (( legacy == 1 )); then
        target_dir="$git_dir/hooks"
        mode="legacy"
    else
        target_dir="$repo_root/.githooks"
    fi
    mkdir -p "$target_dir" || return 1
    local src_tmp dst installed=0 unchanged=0 refused=0
    src_tmp="$(mktemp "${TMPDIR:-/tmp}/fmix-pre-push.XXXXXX")" || return 1
    fmix_runner_write_pre_push_hook > "$src_tmp"
    dst="$target_dir/pre-push"
    if [[ -f "$dst" ]]; then
        if cmp -s "$src_tmp" "$dst"; then
            unchanged=1
        elif ! grep -q "$FMIX_RUNNER_HOOK_MARKER" "$dst" 2>/dev/null && (( force == 0 )); then
            fmix_warn "fmix runner install-hooks: REFUSING to overwrite foreign hook $dst (use --force)"
            refused=1
        elif cp "$src_tmp" "$dst" && chmod 755 "$dst"; then
            installed=1
        else
            fmix_warn "fmix runner install-hooks: could not install $dst"
        fi
    elif cp "$src_tmp" "$dst" && chmod 755 "$dst"; then
        installed=1
    else
        fmix_warn "fmix runner install-hooks: could not install $dst"
    fi
    rm -f "$src_tmp"
    if (( legacy == 0 )); then
        local current
        current="$(git -C "$real_worktree" config --get core.hooksPath 2>/dev/null || true)"
        if [[ "$current" != ".githooks" ]]; then
            if git -C "$real_worktree" config core.hooksPath .githooks; then
                fmix_info "fmix runner install-hooks: core.hooksPath -> .githooks"
            fi
        fi
    fi
    fmix_info "fmix runner install-hooks: complete (installed=$installed unchanged=$unchanged refused=$refused mode=$mode)"
    return 0
}

cmd_runner() {
    local subcmd="${1:-}"
    shift || true
    case "$subcmd" in
        submit)       cmd_runner_submit "$@" ;;
        status)       cmd_runner_status "$@" ;;
        logs)         cmd_runner_logs "$@" ;;
        cancel)       cmd_runner_cancel "$@" ;;
        list)         cmd_runner_list "$@" ;;
        receipt)      cmd_runner_receipt "$@" ;;
        install-hooks) cmd_runner_install_hooks "$@" ;;
        gc-worktree)  cmd_runner_gc_worktree "$@" ;;
        ""|help|--help|-h)
            fmix_verb_help runner
            ;;
        *)
            fmix_error "Unknown runner subcommand: '${subcmd:-empty}'."
            fmix_error "Valid runner subcommands: submit, status, logs, cancel, list, receipt, install-hooks, gc-worktree"
            fmix_error "Run 'fmix help runner' for focused usage."
            return 1
            ;;
    esac
}

# ---------------------------------------------------------------------------
# cmd: fmix task
# ---------------------------------------------------------------------------

cmd_task() {
    # Run a non-test Mix task against the same exact pinned runtime and
    # session-local incremental deps/_build state as fmix setup/test. This is
    # the supported path for generators and developer tasks that may introduce
    # new dependencies; it never uses Docker, Depot, GHCR, or a prebuilt deps
    # image.
    local worktree_arg="auto"
    local session_arg=""
    local database_arg=""
    local mix_env_arg="test"
    local allow_run=0
    local found_sep=0
    local -a mix_args=()
    while (( $# > 0 )); do
        case "$1" in
            --worktree)
                [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }
                worktree_arg="$2"
                shift 2
                ;;
            --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
            --session)
                [[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }
                session_arg="$2"
                shift 2
                ;;
            --session=*) session_arg="${1#--session=}"; shift ;;
            --database)
                [[ $# -ge 2 ]] || { fmix_error "--database requires a database name."; return 2; }
                database_arg="$2"
                shift 2
                ;;
            --database=*) database_arg="${1#--database=}"; shift ;;
            --mix-env)
                [[ $# -ge 2 ]] || { fmix_error "--mix-env requires an environment name."; return 2; }
                mix_env_arg="$2"
                shift 2
                ;;
            --mix-env=*) mix_env_arg="${1#--mix-env=}"; shift ;;
            --allow-run) allow_run=1; shift ;;
            --) found_sep=1; shift; break ;;
            *)
                fmix_error "Unknown option: $1. Usage: fmix task [--worktree <path>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]"
                return 2
                ;;
        esac
    done
    (( found_sep == 1 )) || {
        fmix_error "'fmix task' requires -- before the Mix task."
        return 2
    }
    mix_args=("$@")
    (( ${#mix_args[@]} > 0 )) || {
        fmix_error "'fmix task' requires a Mix task after --."
        return 2
    }
    case "${mix_args[0]}" in
        test|test.*)
            fmix_error "Use 'fmix test' for ExUnit tasks so database and test-lane isolation remain enforced."
            return 2
            ;;
        do|cmd)
            fmix_error "'fmix task' runs one repository Mix task; nested execution via '${mix_args[0]}' is not allowed."
            fmix_error "Use 'fmix test' for ExUnit, or invoke the intended non-test task directly."
            return 2
            ;;
        run)
            if (( allow_run == 0 )); then
                fmix_error "'mix run' requires explicit --allow-run because it executes repository code outside a named Mix task."
                return 2
            fi
            ;;
    esac

    [[ -z "$database_arg" ]] || fmix_validate_database_name "$database_arg" || return 2
    fmix_validate_mix_env "$mix_env_arg" || return 2

    local worktree real_worktree template_key db_name task_db_name state_file lock_name
    worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
    fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1
    real_worktree="$(fmix_realpath "$worktree")" || return 1
    fmix_activate_toolchain "$real_worktree" || return 1
    fmix_activate_session "$real_worktree" "$session_arg" || return $?
    template_key="$(fmix_compute_template_key "$real_worktree")" || return 1
    db_name="$(fmix_db_name_for_worktree "$real_worktree")"
    task_db_name="${database_arg:-$db_name}"
    state_file="$(fmix_worktree_state_file "$real_worktree")"
    lock_name="$(fmix_execution_lock_name "$real_worktree")"

    fmix_info "=== fmix task ==="
    fmix_info "Worktree: $real_worktree"
    fmix_info "Session root: $FMIX_ACTIVE_SESSION_ROOT"
    fmix_info "Template key: $template_key"
    fmix_info "Mix environment: $mix_env_arg"
    [[ -z "$database_arg" ]] || fmix_info "Named database: $task_db_name (explicit override)"
    [[ "$allow_run" == "1" ]] && fmix_info "Explicitly allowing repository script execution"
    fmix_info "Running with local deps/_build: mix ${mix_args[*]}"

    fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || return $?
    local task_rc=0
    fmix_ensure_artifacts "$real_worktree" "$template_key" 1 || {
        task_rc=$?
        fmix_command_lock_finish "$lock_name" "$task_rc" "$FMIX_LAST_ARTIFACTS_COMPILE_FAILURE"
        return $?
    }
    fmix_ensure_compile "$real_worktree" "$db_name" setup || {
        task_rc=$?
        fmix_command_lock_finish "$lock_name" "$task_rc" 1
        return $?
    }

    local -a build_env=()
    [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
    [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
    (
        cd "$real_worktree" || exit 1
        exec env \
            -u DB_HOST_IPV4 \
            "${build_env[@]+"${build_env[@]}"}" \
            MIX_ENV="$mix_env_arg" \
            DB_HOSTNAME="$DB_HOST" \
            DB_PORT="$DB_PORT" \
            DB_USER="$DB_USER" \
            DB_PASSWORD="$DB_PASSWORD" \
            DB_NAME="$task_db_name" \
            LOCAL_NATS="$NATS_HOST" \
            NATS_PORT="$NATS_PORT" \
            NATS_HOST="$NATS_HOST" \
            CT_NATS_HOST="$NATS_HOST" \
            NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
            WORKER_NODE=TRUE \
            ADMIN_NODE=TRUE \
            ONPREM=TRUE \
            SECRET_KEY_BASE="$SECRET_KEY_BASE" \
            MEESEEKS_HTML5EVER_BUILD=0 \
            POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
            POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
            mix "${mix_args[@]}"
    ) || task_rc=$?

    local task_preserve_failure=1
    if (( task_rc == 0 )); then
        # A task may generate compiler inputs or change dependency inputs.
        # Revalidate once while still holding the worktree lock, then record
        # provenance for the post-task content rather than the pre-task key.
        if fmix_ensure_compile "$real_worktree" "$db_name" setup; then
            template_key="$(fmix_compute_template_key "$real_worktree")" || {
                task_rc=1
                task_preserve_failure=0
            }
        else
            task_rc=$?
        fi
    fi
    if (( task_rc == 0 )); then
        local prior_schema="" prior_base="" prior_source="" prior_migration=""
        if [[ -f "$state_file" ]]; then
            prior_schema="$(fmix_read_state "$state_file" db_schema_key)"
            prior_base="$(fmix_read_state "$state_file" db_base_id)"
            prior_source="$(fmix_read_state "$state_file" db_source_schema_key)"
            prior_migration="$(fmix_read_state "$state_file" last_migration_stamp)"
        fi
        fmix_write_worktree_state \
            "$real_worktree" "$template_key" "$db_name" "$prior_migration" "$(fmix_now)" \
            "$prior_schema" "$prior_base" "$prior_source" || {
                task_rc=1
                task_preserve_failure=0
            }
        fmix_update_template_last_used "$template_key"
    fi
    fmix_command_lock_finish "$lock_name" "$task_rc" "$task_preserve_failure" || task_rc=$?
    fmix_info "Mix task completed (rc=$task_rc)."
    return "$task_rc"
}

cmd_format() {
    # Format Elixir sources with the exact pinned toolchain (.tool-versions)
    # and the same session deps/_build state fmix test compiles against.
    #
    # Formatting with an ambient manager shim (mise/asdf/global) whose Elixir
    # differs from the repo pin is a known hazard: a newer formatter silently
    # rewrites unrelated hunks and formatter plugins can fail to resolve
    # (".formatter.exs import_deps" needs the pinned deps compiled). This is
    # the supported alternative to bare `mix format`.
    #
    # Formatting is DB-free: no database is provisioned or contacted, and no
    # MIX_ENV database variables are injected.
    local worktree_arg="auto"
    local session_arg=""
    local mix_env_arg="test"
    local dot_formatter_arg=""
    local check_only=0
    local found_sep=0
    local -a fmt_args=()
    while (( $# > 0 )); do
        case "$1" in
            --worktree)
                [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }
                worktree_arg="$2"
                shift 2
                ;;
            --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
            --session)
                [[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }
                session_arg="$2"
                shift 2
                ;;
            --session=*) session_arg="${1#--session=}"; shift ;;
            --mix-env)
                [[ $# -ge 2 ]] || { fmix_error "--mix-env requires an environment name."; return 2; }
                mix_env_arg="$2"
                shift 2
                ;;
            --mix-env=*) mix_env_arg="${1#--mix-env=}"; shift ;;
            --dot-formatter)
                [[ $# -ge 2 ]] || { fmix_error "--dot-formatter requires a path argument."; return 2; }
                dot_formatter_arg="$2"
                shift 2
                ;;
            --dot-formatter=*) dot_formatter_arg="${1#--dot-formatter=}"; shift ;;
            --check) check_only=1; shift ;;
            --) found_sep=1; shift; break ;;
            *)
                fmix_error "Unknown option: $1. Usage: fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--dot-formatter <path>] [--check] -- <files...>"
                return 2
                ;;
        esac
    done
    (( found_sep == 1 )) || {
        fmix_error "'fmix format' requires -- before the file arguments."
        return 2
    }
    fmt_args=("$@")
    (( ${#fmt_args[@]} > 0 )) || {
        fmix_error "'fmix format' requires at least one file or glob argument after --."
        return 2
    }
    case "${fmt_args[0]}" in
        test.*)
            fmix_error "'fmix format' formats files; pass file paths, not a Mix task."
            return 2
            ;;
    esac

    fmix_validate_mix_env "$mix_env_arg" || return 2

    local worktree real_worktree template_key lock_name
    worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
    fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1
    real_worktree="$(fmix_realpath "$worktree")" || return 1
    fmix_activate_toolchain "$real_worktree" || return 1
    fmix_activate_session "$real_worktree" "$session_arg" || return $?
    template_key="$(fmix_compute_template_key "$real_worktree")" || return 1
    lock_name="$(fmix_execution_lock_name "$real_worktree")"

    fmix_info "=== fmix format ==="
    fmix_info "Worktree: $real_worktree"
    fmix_info "Session root: $FMIX_ACTIVE_SESSION_ROOT"
    fmix_info "Template key: $template_key"
    fmix_info "Mix environment: $mix_env_arg"
    if (( check_only == 1 )); then
        fmix_info "Mode: --check-formatted (read-only; no files are rewritten)"
    fi
    fmix_info "Running with pinned toolchain + session deps: mix format ${fmt_args[*]}"

    fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || return $?
    # Formatter plugins (e.g. .formatter.exs import_deps) require the pinned
    # deps to be present and compiled; reuse the same ensure path as task.
    local fmt_rc=0
    fmix_ensure_artifacts "$real_worktree" "$template_key" 1 || {
        fmt_rc=$?
        fmix_command_lock_finish "$lock_name" "$fmt_rc" "$FMIX_LAST_ARTIFACTS_COMPILE_FAILURE"
        return $?
    }
    fmix_ensure_compile "$real_worktree" "$(fmix_db_name_for_worktree "$real_worktree")" setup || {
        fmt_rc=$?
        fmix_command_lock_finish "$lock_name" "$fmt_rc" 1
        return $?
    }

    local -a build_env=()
    [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
    [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")

    local -a mix_cmd=(format)
    if (( check_only == 1 )); then
        mix_cmd+=(--check-formatted)
    fi
    # Formatter-configuration scopes: repos with `subdirectories` entries in
    # .formatter.exs (e.g. Ecto migrations under priv/*/migrations) format
    # those files with a different import_deps/locals_without_parens set than
    # the root config. --dot-formatter selects that config explicitly while
    # deps still resolve from the project root.
    if [[ -n "$dot_formatter_arg" ]]; then
        mix_cmd+=(--dot-formatter "$dot_formatter_arg")
    fi
    mix_cmd+=("${fmt_args[@]}")

    (
        cd "$real_worktree" || exit 1
        exec env \
            -u DB_HOST_IPV4 \
            "${build_env[@]+"${build_env[@]}"}" \
            MIX_ENV="$mix_env_arg" \
            mix "${mix_cmd[@]}"
    ) || fmt_rc=$?

    local fmt_preserve_failure=1
    if (( fmt_rc == 0 && check_only == 0 )); then
        # Formatting rewrites sources, so refresh compile stamps and template
        # provenance while still holding the worktree lock.
        if fmix_ensure_compile "$real_worktree" "$(fmix_db_name_for_worktree "$real_worktree")" setup; then
            template_key="$(fmix_compute_template_key "$real_worktree")" || {
                fmt_rc=1
                fmt_preserve_failure=0
            }
        else
            fmt_rc=$?
        fi
        if (( fmt_rc == 0 )); then
            fmix_update_template_last_used "$template_key"
        fi
    fi
    fmix_command_lock_finish "$lock_name" "$fmt_rc" "$fmt_preserve_failure" || fmt_rc=$?
    if (( check_only == 1 && fmt_rc == 1 )); then
        fmix_error "Format check failed: files are not formatted per the pinned toolchain."
        return 1
    fi
    fmix_info "Format completed (rc=$fmt_rc)."
    return "$fmt_rc"
}

# ---------------------------------------------------------------------------
# cmd: fmix doctor
# ---------------------------------------------------------------------------

# ---------------------------------------------------------------------------
# Shared postgres + NATS (one host-wide ct-infra plane)
# ---------------------------------------------------------------------------

fmix_infra_postgres_ready() {
    nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null \
        && fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1
}

fmix_infra_nats_ready() {
    fmix_nats_jetstream_probe "$NATS_HOST" "$NATS_PORT" >/dev/null 2>&1
}

fmix_infra_ready() {
    fmix_infra_postgres_ready && fmix_infra_nats_ready
}

# True when the local NATS port is held by a listener fmix does not own: TCP
# answers, JetStream does not, and neither the shared ct-infra container nor
# the managed nats-server pid is the owner. Remote hosts are never "foreign".
fmix_nats_port_foreign() {
    fmix_nats_host_is_local || return 1
    nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null || return 1
    fmix_infra_nats_ready && return 1
    if docker inspect "${FMIX_INFRA_PROJECT}-nats-1" >/dev/null 2>&1; then
        return 1
    fi
    local pid_file="$FMIX_HOME/nats/nats-server.pid" pid=""
    if [[ -f "$pid_file" ]]; then
        pid="$(cat "$pid_file" 2>/dev/null || true)"
        if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
            return 1
        fi
    fi
    return 0
}

# Starts a managed JetStream nats-server on the local port, idempotently:
# a live managed pid is waited on, never duplicated. Returns 0 only once the
# JetStream probe passes. Data lives under FMIX_HOME, never in the repo.
fmix_start_managed_nats() {
    local dir="$FMIX_HOME/nats" pid_file="$FMIX_HOME/nats/nats-server.pid" pid="" now deadline
    mkdir -p "$dir/store" || return 1
    if [[ -f "$pid_file" ]]; then
        pid="$(cat "$pid_file" 2>/dev/null || true)"
    fi
    if [[ -z "$pid" ]] || ! kill -0 "$pid" 2>/dev/null; then
        echo "  starting managed nats-server -js on localhost:$NATS_PORT..."
        nohup nats-server -js -sd "$dir/store" -p "$NATS_PORT" -P "$pid_file" \
            >"$dir/nats-server.log" 2>&1 </dev/null &
        disown 2>/dev/null || true
    else
        echo "  waiting on managed nats-server pid $pid..."
    fi
    now="$(fmix_epoch)"
    deadline=$(( now + FMIX_ENSURE_TIMEOUT ))
    while (( $(fmix_epoch) < deadline )); do
        if fmix_infra_nats_ready; then
            return 0
        fi
        sleep 1
    done
    fmix_error "managed nats-server did not answer JetStream on localhost:$NATS_PORT within ${FMIX_ENSURE_TIMEOUT}s (log: $dir/nats-server.log)"
    return 1
}

fmix_docker_usable() {
    command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1
}

fmix_infra_host_is_local() {
    case "$DB_HOST" in
        localhost|127.0.0.1|::1) return 0 ;;
        *) return 1 ;;
    esac
}

fmix_nats_host_is_local() {
    case "$NATS_HOST" in
        localhost|127.0.0.1|::1) return 0 ;;
        *) return 1 ;;
    esac
}

fmix_write_ensure_compose() {
    local dir="$FMIX_HOME/infra"
    mkdir -p "$dir" || return 1
    cat >"$dir/nats.conf" <<'NATS'
max_payload: 5242880
jetstream {
    store_dir: "/data/jetstream"
    max_memory_store: 1G
    max_file_store: 10G
}
http_port: 8222
debug: false
trace: false
max_connections: 500
NATS
    cat >"$dir/compose-ensure.yml" <<YAML
# Written by fmix ensure (schema ${FMIX_INFRA_SCHEMA}). Postgres + NATS only.
# Project name ${FMIX_INFRA_PROJECT} matches ai-workspace ./infra.sh so one stack is reused.
services:
  postgres:
    hostname: postgres
    image: calltelemetry/postgres:14
    restart: unless-stopped
    command:
      - postgres
      - -c
      - max_connections=600
      - -c
      - shared_buffers=512MB
      - -c
      - work_mem=16MB
    environment:
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: calltelemetry_dev
    ports:
      - "${DB_PORT}:5432"
    volumes:
      - ct-pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${DB_USER} -d calltelemetry_dev"]
      interval: 5s
      timeout: 5s
      retries: 12
      start_period: 20s
  nats:
    hostname: nats
    image: nats:2.11
    restart: unless-stopped
    command: ["-c", "/etc/nats/nats.conf"]
    ports:
      - "${NATS_PORT}:4222"
      - "8222:8222"
    volumes:
      - ${dir}/nats.conf:/etc/nats/nats.conf:ro
      - ct-natsdata:/data
volumes:
  ct-pgdata:
  ct-natsdata:
YAML
}

fmix_start_existing_ct_infra() {
    local name started=0
    local -a targets=("${FMIX_INFRA_PROJECT}-postgres-1")
    if fmix_nats_host_is_local; then
        targets+=("${FMIX_INFRA_PROJECT}-nats-1")
    fi
    for name in "${targets[@]}"; do
        if docker inspect "$name" >/dev/null 2>&1; then
            docker start "$name" >/dev/null 2>&1 || true
            started=1
        fi
    done
    [[ "$started" == "1" ]]
}

fmix_compose_up_ensure() {
    fmix_write_ensure_compose || return 1
    local -a services=(postgres)
    if fmix_nats_host_is_local; then
        services+=(nats)
    fi
    docker compose -p "$FMIX_INFRA_PROJECT" -f "$FMIX_HOME/infra/compose-ensure.yml" up -d "${services[@]}"
}

fmix_wait_infra() {
    local now deadline
    now="$(fmix_epoch)"
    deadline=$(( now + FMIX_ENSURE_TIMEOUT ))
    while (( $(fmix_epoch) < deadline )); do
        if fmix_infra_ready; then
            return 0
        fi
        if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
            return 1
        fi
        sleep 1
    done
    return 1
}

fmix_infra_capacity_bytes() {
    local py_bin
    py_bin="$(fmix_python_bin)" || return 1
    "$py_bin" - <<'PY'
import json
import os
import platform
import subprocess
import sys

def probe(*args):
    result = subprocess.run(args, capture_output=True, text=True, timeout=5)
    if result.returncode or len(result.stdout) > 1024 * 1024:
        raise ValueError("incomplete native observation")
    return result.stdout.strip()

try:
    # DOCKER_CONTEXT takes precedence over DOCKER_HOST. Never use a local
    # capacity reading to admit allocation on an unobserved remote daemon.
    context = os.environ.get("DOCKER_CONTEXT", "")
    host = os.environ.get("DOCKER_HOST", "")
    if context:
        if context.startswith("-"):
            raise ValueError("invalid context")
        host = json.loads(probe("docker", "context", "inspect", "--format",
                                "{{json .Endpoints.docker.Host}}", context))
    elif not host:
        host = json.loads(probe("docker", "context", "inspect", "--format",
                                "{{json .Endpoints.docker.Host}}"))
    if not isinstance(host, str) or not host.startswith("unix:///"):
        raise ValueError("unobserved remote storage")

    if platform.system() == "Darwin":
        if not host.endswith("/.orbstack/run/docker.sock"):
            raise ValueError("unobserved macOS Docker storage")
        # Discover the *open* backing image rather than assuming its default
        # path: OrbStack can place data on a different filesystem. Only read
        # native descriptor metadata; do not traverse protected app storage.
        raw = probe("lsof", "-nP", "-a", "-u", str(os.getuid()),
                    "-c", "OrbStack", "-Fn")
        paths = {line[1:] for line in raw.splitlines()
                 if line.startswith("n/") and line.endswith("/data.img.raw")}
        if len(paths) != 1:
            raise ValueError("ambiguous or unavailable Docker backing storage")
        anchor = paths.pop()
    elif platform.system() == "Linux":
        anchor = json.loads(probe("docker", "info", "--format", "{{json .DockerRootDir}}"))
        if not isinstance(anchor, str) or not os.path.isabs(anchor):
            raise ValueError("unavailable Docker storage root")
    else:
        raise ValueError("unsupported native storage observation")
    before = os.stat(anchor)
    capacity = os.statvfs(anchor)
    after = os.stat(anchor)
    if (before.st_dev, before.st_ino) != (after.st_dev, after.st_ino):
        raise ValueError("storage identity changed")
    free = capacity.f_bavail * capacity.f_frsize
    total = capacity.f_blocks * capacity.f_frsize
    if not 0 <= free <= total < 10**18 or total == 0:
        raise ValueError("invalid native capacity")
    print(f"{free} {total}")
except Exception:
    print("[fmix] Docker storage capacity unavailable; refusing cold infrastructure allocation.",
          file=sys.stderr)
    sys.exit(1)
PY
}

fmix_infra_has_headroom() {
    # An 8 decimal GB cold-start allowance covers the observed post-reset
    # image/cache refill. This is admission, not an OS quota or a reservation
    # against nonparticipating Docker clients. No public bypass/override.
    local capacity free total floor reserve=8000000000
    capacity="$(fmix_infra_capacity_bytes)" || {
        fmix_error "Docker disk capacity is unknown; holding infrastructure startup."
        return 75
    }
    if [[ ! "$capacity" =~ ^[0-9]{1,18}[[:blank:]][0-9]{1,18}$ ]]; then
        fmix_error "Invalid Docker disk capacity; holding infrastructure startup."
        return 75
    fi
    read -r free total <<<"$capacity"
    free=$((10#$free))
    total=$((10#$total))
    if (( total <= 0 || free > total )); then
        fmix_error "Invalid Docker disk capacity; holding infrastructure startup."
        return 75
    fi
    floor=$(( total / 20 ))
    (( floor <= 100000000000 )) || floor=100000000000
    if (( free < reserve || free - reserve < floor )); then
        fmix_error "Docker disk pressure: free=${free}B, startup allowance=${reserve}B, retained floor=${floor}B. Holding startup; reuse ready infrastructure or reclaim through its owner."
        return 75
    fi
}

fmix_ensure_infra() {
    if fmix_infra_ready; then
        echo "  [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
        return 0
    fi

    if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
        fmix_error "Remote/Tailnet NATS $NATS_HOST:$NATS_PORT is not reachable. Check Tailscale connectivity or set FMIX_NATS_HOST=localhost."
        return 1
    fi

    if [[ "$FMIX_ENSURE" != "1" ]]; then
        fmix_error "Postgres/NATS not ready at $DB_HOST:$DB_PORT / $NATS_HOST:$NATS_PORT (FMIX_ENSURE=0)."
        return 1
    fi

    if ! fmix_infra_host_is_local; then
        fmix_error "Postgres $DB_HOST:$DB_PORT is not reachable. Remote FMIX_DB_HOST is operator-owned; fmix will not start Docker."
        return 1
    fi

    if nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null && ! fmix_infra_postgres_ready; then
        fmix_error "Port $DB_PORT is occupied but not postgres user '$DB_USER'. Refusing to start a second database."
        return 1
    fi

    # Never start a second NATS on a port another listener owns (API-1460: a
    # non-JetStream pod answered localhost:4222). A listener counts as ours only
    # when it is the shared ct-infra container or the managed nats-server pid.
    if fmix_nats_port_foreign; then
        fmix_error "$NATS_HOST:$NATS_PORT answers TCP without JetStream and no ${FMIX_INFRA_PROJECT}-nats-1 container or managed nats-server owns it. Refusing to start a second NATS; free the port, or set FMIX_NATS_HOST to a healthy JetStream server."
        return 1
    fi

    # No Docker, but Postgres is up and only NATS is missing: run a managed
    # nats-server -js when the binary exists, so fmix test needs no manual host.
    if ! fmix_docker_usable && fmix_infra_postgres_ready && ! fmix_infra_nats_ready && command -v nats-server >/dev/null 2>&1; then
        if fmix_start_managed_nats; then
            echo "  [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT (managed nats-server -js)"
            return 0
        fi
        return 1
    fi

    if ! fmix_docker_usable; then
        fmix_error "Shared postgres/NATS is down and Docker is not usable. Start OrbStack/Docker, then retry: fmix ensure"
        return 1
    fi

    # Coalesce concurrent callers after an engine reset. The native lease is
    # held through readiness and admission; never force another owner's lock.
    local lock_name="infra-ensure" startup_rc=0
    fmix_lock_acquire "$lock_name" "$FMIX_ENSURE_TIMEOUT" "shared infrastructure startup" || return $?
    fmix_ensure_infra_locked || startup_rc=$?
    if ! fmix_lock_release "$lock_name"; then
        fmix_error "Infrastructure startup lease release failed."
        return 1
    fi
    return "$startup_rc"
}

fmix_ensure_infra_locked() {
    if fmix_infra_ready; then
        echo "  [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
        return 0
    fi
    if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
        fmix_error "Remote/Tailnet NATS $NATS_HOST:$NATS_PORT is not reachable. Check Tailscale connectivity or set FMIX_NATS_HOST=localhost."
        return 1
    fi
    fmix_infra_has_headroom || return 75
    if fmix_nats_host_is_local; then
        echo "  starting shared $FMIX_INFRA_PROJECT (postgres + nats)..."
    else
        echo "  starting shared $FMIX_INFRA_PROJECT (postgres)..."
    fi
    fmix_start_existing_ct_infra || true
    if fmix_wait_infra; then
        echo "  [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
        return 0
    fi
    if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
        fmix_error "Remote/Tailnet NATS $NATS_HOST:$NATS_PORT is not reachable. Check Tailscale connectivity or set FMIX_NATS_HOST=localhost."
        return 1
    fi
    # Another producer may allocate while existing services are warming.
    fmix_infra_has_headroom || return 75
    if ! fmix_compose_up_ensure; then
        if fmix_nats_host_is_local; then
            fmix_error "docker compose could not start $FMIX_INFRA_PROJECT postgres/nats"
        else
            fmix_error "docker compose could not start $FMIX_INFRA_PROJECT postgres"
        fi
        return 1
    fi
    if ! fmix_wait_infra; then
        if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
            fmix_error "Remote/Tailnet NATS $NATS_HOST:$NATS_PORT is not reachable. Check Tailscale connectivity or set FMIX_NATS_HOST=localhost."
            return 1
        fi
        fmix_error "Shared infra did not become ready within ${FMIX_ENSURE_TIMEOUT}s at $DB_HOST:$DB_PORT / $NATS_HOST:$NATS_PORT"
        return 1
    fi
    echo "  [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
    return 0
}

cmd_ensure() {
    echo "=== fmix ensure ==="
    echo "  target: postgres $DB_HOST:$DB_PORT user=$DB_USER ; nats $NATS_HOST:$NATS_PORT"
    echo "  project: $FMIX_INFRA_PROJECT (one host-wide plane; not a per-branch stack)"
    echo "  nats selection: $FMIX_NATS_HOST_REASON"
    fmix_ensure_infra
}

cmd_doctor() {
    local worktree_arg="auto" session_arg=""
    while (( $# > 0 )); do
        case "$1" in
            --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
            --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
            --session) [[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }; session_arg="$2"; shift 2 ;;
            --session=*) session_arg="${1#--session=}"; shift ;;
            *) shift ;;  # Ignore unknown for doctor
        esac
    done

    echo "=== fmix doctor ==="
    local fail=0

    # Try to find worktree. When run from the ai-workspace root (no --worktree),
    # fmix_find_worktree's "auto" walk-up won't find cisco-cdr (it's a subdir,
    # not an ancestor), leaving the toolchain check to fall back to $HOME — which
    # has no .tool-versions, so it wrongly reports "Elixir not found". Probe the
    # conventional ./cisco-cdr subdir before giving up.
    local worktree=""
    worktree="$(fmix_find_worktree "$worktree_arg" 2>/dev/null)" || true
    if [[ -n "$worktree" ]]; then fmix_check_resolved_worktree "$worktree_arg" "$worktree" || return 1; fi
    if [[ -z "$worktree" && "$worktree_arg" == "auto" && -f "$PWD/cisco-cdr/mix.exs" ]]; then
        worktree="$(fmix_find_worktree "$PWD/cisco-cdr" 2>/dev/null)" || true
        [[ -n "$worktree" ]] && echo "  (auto-resolved worktree: $worktree — pass --worktree to be explicit)"
    fi

    # OS detection
    echo "  OS: $FMIX_OS $FMIX_ARCH"
    echo "  FMIX_HOME: $FMIX_HOME"

    # asdf
    fmix_prepend_toolchain_paths
    if command -v asdf >/dev/null 2>&1; then
        local asdf_ver
        asdf_ver="$(asdf --version 2>/dev/null | head -1)"
        echo "  [OK] asdf: $asdf_ver"
    else
        echo "  [WARN] asdf not found (asdf not on PATH) — elixir/erlang version management unavailable"
    fi

    # Elixir — check from worktree so asdf reads .tool-versions there
    local check_dir="${worktree:-$HOME}"
    local elixir_ver
    elixir_ver="$(cd "$check_dir" 2>/dev/null && elixir --version 2>/dev/null | grep 'Elixir' | awk '{print $2}')" || true
    if [[ -n "$elixir_ver" ]]; then
        echo "  [OK] elixir: $elixir_ver"
    else
        echo "  [FAIL] elixir not available — run: cd $check_dir && asdf install"
        fail=1
    fi

    # Mix
    local mix_ver
    mix_ver="$(cd "$check_dir" 2>/dev/null && mix --version 2>/dev/null | sed -n '/^Mix /p' | head -1)" || true
    if [[ -n "$mix_ver" ]]; then
        echo "  [OK] mix: $mix_ver"
    else
        echo "  [FAIL] mix not on PATH — run: cd $check_dir && asdf install"
        fail=1
    fi

    # psql
    local psql_loc
    psql_loc="$(fmix_find_psql)"
    if [[ -n "$psql_loc" ]]; then
        echo "  [OK] psql: $psql_loc"
    elif fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" \
        -d postgres -c "SELECT 1" >/dev/null 2>&1; then
        # A configured control adapter (for example a test stub or a remote
        # container wrapper) is sufficient even when no host psql binary is
        # discoverable. The explicit auth probe below remains authoritative.
        echo "  [OK] psql: configured control adapter"
    else
        echo "  [FAIL] psql not found — install postgresql or ensure docker is running for fallback"
        fail=1
    fi

    # Surface resolved endpoints + the ambient docker-host footgun (fmix pins
    # localhost natively; a bare `mix test` with these set WOULD hit :nxdomain).
    echo "  Resolved infra (native): postgres $DB_HOST:$DB_PORT, NATS $NATS_HOST:$NATS_PORT"
    local amb av
    for amb in DB_HOSTNAME DB_HOST_IPV4 LOCAL_NATS; do
        av="${!amb:-}"
        case "$av" in
            *docker.internal*|*containers.internal*)
                echo "  [WARN] ambient $amb=$av is docker-only (won't resolve natively); fmix ignores it — unset before a bare 'mix test'" ;;
        esac
    done

    # postgres TCP
    if nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null; then
        echo "  [OK] postgres TCP $DB_HOST:$DB_PORT"
    else
        echo "  [FAIL] postgres not reachable at $DB_HOST:$DB_PORT — run: ./infra.sh up"
        fail=1
    fi

    # postgres auth
    if fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1; then
        local conn_count
        conn_count="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
            -t -c "SELECT count(*) FROM pg_stat_activity" 2>/dev/null | tr -d ' ')"
        echo "  [OK] postgres auth (user=$DB_USER, connections=$conn_count)"
    else
        echo "  [FAIL] postgres auth failed for user=$DB_USER — check FMIX_DB_USER/FMIX_DB_PASSWORD env vars"
        fail=1
    fi

    # Content-indexed hot DB bases
    local tmpl_count index_count
    tmpl_count="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -t -c "SELECT count(*) FROM pg_database WHERE datname LIKE 'ct_fmix_tmpl_%' AND datistemplate AND NOT datallowconn" \
        2>/dev/null | tr -d ' ')"
    index_count="$(find "$FMIX_HOME/db-index" -mindepth 2 -maxdepth 2 -name meta.json -type f 2>/dev/null | wc -l | tr -d ' ')"
    if [[ -n "$tmpl_count" && -n "$index_count" ]] && (( tmpl_count > 0 && index_count > 0 )); then
        echo "  [OK] content-indexed hot DB bases: databases=$tmpl_count records=$index_count"
    else
        echo "  [WARN] No complete content-indexed hot DB base found — run './fmix setup --cold-db' (falls back to --from-zero if structure.sql is unusable) for explicit bootstrap maintenance"
    fi

    # NATS JetStream round trip (bounded). TCP alone is not health: a remote can
    # accept the connection and never answer JetStream, which aborts app boot.
    local nats_where="remote/tailnet"
    fmix_nats_host_is_local && nats_where="local"
    if fmix_nats_jetstream_probe "$NATS_HOST" "$NATS_PORT"; then
        echo "  [OK] nats: $NATS_HOST:$NATS_PORT ($nats_where) JetStream answered in $FMIX_NATS_PROBE_DETAIL"
        echo "       selection: $FMIX_NATS_HOST_REASON"
    elif nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
        echo "  [FAIL] nats: $NATS_HOST:$NATS_PORT ($nats_where) accepts TCP but JetStream did not answer: $FMIX_NATS_PROBE_DETAIL (bound ${FMIX_NATS_PROBE_TIMEOUT}s)"
        echo "         app boot needs JetStream KV; set FMIX_NATS_HOST=localhost once a local JetStream NATS is up, or restore JetStream on $NATS_HOST"
        fail=1
    else
        if ! fmix_nats_host_is_local; then
            echo "  [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT (remote/tailnet) — check Tailscale connectivity or set FMIX_NATS_HOST=localhost"
        else
            echo "  [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT — run: ./infra.sh up (some tests may fail)"
        fi
    fi

    # Headless Chromium for ChromicPDF-backed reporting suites (API-1184).
    # Informational only — needed by test/cdrcisco/reporting/uat/*, not the
    # bulk of the suite, so a miss is a WARN not a FAIL.
    local chrome_p chrome_bin
    chrome_p=""
    for chrome_bin in chromium chromium-browser google-chrome google-chrome-stable; do
        command -v "$chrome_bin" >/dev/null 2>&1 && { chrome_p="$(command -v "$chrome_bin")"; break; }
    done
    if [[ -z "$chrome_p" ]]; then
        chrome_p="$(fmix_discover_chromium_binary 2>/dev/null)" || chrome_p=""
    fi
    if [[ -n "$chrome_p" ]]; then
        echo "  [OK] headless Chromium (ChromicPDF/reporting): $chrome_p"
    else
        echo "  [WARN] no headless Chromium found — reporting/uat real-PDF suites will be 'invalid'. Install: 'npx playwright install chromium' or set FMIX_CHROME=/path"
    fi

    # Oban Pro secret preflight check
    local oban_had_env=0
    [[ -n "${OBAN_LICENSE_KEY:-}" ]] && oban_had_env=1
    if fmix_load_oban_license_key >/dev/null 2>&1; then
        echo "  [OK] Oban credentials: key available"
        if (( oban_had_env == 0 )); then
            unset OBAN_LICENSE_KEY
        fi
    else
        local private_env
        private_env="$(fmix_private_env_file 2>/dev/null || echo "$FMIX_CONFIG_HOME/fmix.env")"
        echo "  [FAIL] Oban credentials missing — run 'doppler login' or write OBAN_LICENSE_KEY=… to $private_env (mode 0600)"
        fail=$(( fail + 1 ))
    fi

    # Doppler CLI status
    if command -v doppler >/dev/null 2>&1; then
        local dop_v
        dop_v="$(doppler --version 2>/dev/null | head -1)" || dop_v="available"
        echo "  [OK] doppler CLI: $dop_v"
    else
        echo "  [WARN] doppler CLI not found — fallback credential fetch from Doppler disabled"
    fi

    # Worktree-specific checks
    if [[ -n "$worktree" ]]; then
        local real_wt
        real_wt="$(fmix_realpath "$worktree")"
        echo "  [OK] worktree: $real_wt"
        if fmix_activate_toolchain "$real_wt"; then
            echo "  [OK] exact repo toolchain ABI"
            if fmix_activate_session "$real_wt" "$session_arg"; then
                echo "  [OK] session-owned artifact namespace: $FMIX_ACTIVE_SESSION_ROOT"
            else
                local activation_rc=$?
                fmix_lock_failure_is_fatal "$activation_rc" && return 70
                echo "  [FAIL] session-owned artifact namespace could not be activated"
                fail=$(( fail + 1 ))
            fi
        else
            if ! command -v erl >/dev/null 2>&1; then
                echo "  [WARN] exact repo toolchain ABI unavailable (erl not installed) — run asdf install for strict verification"
            else
                echo "  [FAIL] active BEAM runtime does not match .tool-versions"
                fail=$(( fail + 1 ))
            fi
        fi
        local tk
        if tk="$(fmix_compute_template_key "$real_wt")"; then
            echo "  Template key: $tk"
        fi
        local db_name
        db_name="$(fmix_db_name_for_worktree "$real_wt")"
        echo "  Scratch DB: $db_name"
        # Existence check: the session's scratch DB must actually exist in
        # Postgres, or runtime tasks that try to boot the app against it will
        # fail at runtime anyway. Filesystem deps/build present is necessary
        # but not sufficient — a poisoned session can retain deps yet never
        # have created the scratch DB on this host postgres.
        if [[ -n "$DB_HOST" && -n "$DB_PORT" && -n "$DB_USER" ]]; then
            if fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$db_name" -c "SELECT 1" >/dev/null 2>&1; then
                echo "  [OK] scratch DB reachable: $db_name"
            else
                echo "  [FAIL] scratch DB missing or unreachable: $db_name"
                echo "       fix: run 'fmix setup --worktree $real_wt' to (re)create the session scratch DB"
                fail=$(( fail + 1 ))
            fi
        else
            echo "  [INFO] scratch DB check skipped (DB_HOST/DB_PORT/DB_USER unset)"
        fi
        local doctor_deps doctor_build
        doctor_deps="$(fmix_session_deps_root "$real_wt")"
        doctor_build="$(fmix_compile_build_root "$real_wt")"
        if [[ -d "$doctor_deps" ]]; then
            echo "  [OK] session deps exists: $doctor_deps"
        else
            echo "  [INFO] session deps missing — will be created by 'fmix setup'"
        fi
        if [[ -d "$doctor_build/test" ]]; then
            echo "  [OK] session build exists: $doctor_build/test"
        else
            echo "  [INFO] session build missing — will be created by 'fmix setup'"
        fi
        local state_file
        state_file="$(fmix_worktree_state_file "$real_wt")"
        if [[ -f "$state_file" ]]; then
            echo "  [OK] state file: $state_file"
        else
            echo "  [INFO] no state file yet — will be created on first run"
        fi
    fi

    # fmix state dir
    if [[ -d "$FMIX_HOME" ]]; then
        echo "  [OK] FMIX_HOME exists: $FMIX_HOME"
    else
        echo "  [INFO] FMIX_HOME will be created on first run: $FMIX_HOME"
    fi

    # Session metadata & TTL cache lifecycle inspection & purging
    local ttl_val
    ttl_val="$(fmix_effective_session_ttl_hours)"
    echo "  Session metadata & TTL cache inspection (FMIX_SESSION_TTL_HOURS=${ttl_val}h):"
    local session_meta_paths="" session_scan_ok=1
    if fmix_purge_expired_sessions 0; then
        :
    else
        local housekeeping_rc=$?
        fmix_lock_failure_is_fatal "$housekeeping_rc" && return 70
        echo "  [FAIL] session discovery failed; skipped orphan scratch DB cleanup"
        fail=$(( fail + 1 ))
        session_scan_ok=0
    fi
    if (( session_scan_ok == 1 )) && ! session_meta_paths="$(fmix_session_files meta.json)"; then
        echo "  [FAIL] session metadata discovery failed; skipped orphan scratch DB cleanup"
        fail=$(( fail + 1 ))
        session_scan_ok=0
    fi

    if (( session_scan_ok == 1 )) \
        && fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1; then
        local s_dbs db_name shash session_found orphan_drop_rc
        s_dbs="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
            -t -c "SELECT datname FROM pg_database WHERE datname ~ '^ct_fmix_s_[0-9a-f]{16}\$'" 2>/dev/null | tr -d ' ')"
        for db_name in $s_dbs; do
            [[ -n "$db_name" ]] || continue
            shash="${db_name#ct_fmix_s_}"
            session_found=0
            if [[ -d "$FMIX_HOME/sessions" ]] \
                && fmix_session_metadata_references_hash "$session_meta_paths" "$shash"; then
                session_found=1
            fi
            if (( session_found == 0 )); then
                if [[ ! "$db_name" =~ ^ct_fmix_s_[0-9a-f]{16}$ ]]; then
                    echo "  [WARN] Refusing cleanup for malformed session DB name: $db_name"
                    continue
                fi
                # The Postgres server is host-global but session roots are
                # per-FMIX_HOME. A DB with no root here may be live under a
                # different FMIX_HOME; only this home's own orphans are safe to
                # destroy. See fmix_session_hash_has_local_root.
                if ! fmix_session_hash_has_local_root "$shash"; then
                    echo "  [INFO] Skipping scratch DB with no session root in this FMIX_HOME: $db_name"
                    continue
                fi
                orphan_drop_rc=0
                fmix_drop_orphan_session_db "$db_name" "doctor orphan DB sweep" \
                    >/dev/null || orphan_drop_rc=$?
                fmix_lock_failure_is_fatal "$orphan_drop_rc" && return 70
                if (( orphan_drop_rc == 0 )); then
                    echo "  [INFO] Purged orphaned scratch DB: $db_name"
                elif (( orphan_drop_rc == 1 )); then
                    echo "  [WARN] Bounded cleanup failed for orphaned scratch DB: $db_name"
                else
                    echo "  [INFO] Preserved scratch DB after lease revalidation: $db_name"
                fi
            fi
        done
    fi
    if (( session_scan_ok == 1 )); then
        echo "  [OK] build package metadata verified & TTL cache purged"
    else
        echo "  [FAIL] build package metadata verification and TTL cleanup were skipped"
    fi

    echo ""
    if (( fail == 0 )); then
        echo "  doctor: all checks passed"
        return 0
    else
        echo "  doctor: $fail check(s) FAILED — fix the above issues before running fmix test"
        return 1
    fi
}

# ---------------------------------------------------------------------------
# cmd: fmix status
# ---------------------------------------------------------------------------

# REL-1244: report a tree size WITHOUT stat()ing every file.
#
# fmix status and fmix doctor called `du -sh` on the artifact trees. On this host
# the store is 1,682,684 files (753,820 templates + 928,864 dependency
# artifacts, ~42 GB apparent). `du -sh` stats every one: measured at 40.9s for
# templates and 63.5s for dependency-artifacts, i.e. ~104s of the 162s that
# `fmix status` takes - all of it to print a size label nobody parses.
#
# Sizes are now read from a small cache beside each tree and refreshed at most
# once per TTL. An uncached read returns "?" rather than blocking: a status
# command must never be the slowest thing in a push.
FMIX_TREE_SIZE_TTL="${FMIX_TREE_SIZE_TTL:-604800}"   # 7 days

fmix_tree_size_cached() {
    local dir="$1" label="${2:-$(basename "$1")}"
    [[ -d "$dir" ]] || { printf '?\n'; return 0; }
    local cache="$FMIX_HOME/tree-sizes/${label}.json"
    local now recorded value
    now="$(date +%s)"
    if [[ -f "$cache" ]]; then
        recorded="$(fmix_read_state "$cache" recorded_at 2>/dev/null)"
        value="$(fmix_read_state "$cache" size 2>/dev/null)"
        # TTL is ENFORCED, not merely recorded. A cache entry without a usable
        # timestamp is treated as expired rather than trusted: an unenforced TTL
        # would report a size that a prune or a template rebuild has since
        # invalidated, and nothing would ever correct it.
        # A timestamp in the FUTURE is also invalid: `now - recorded` would be
        # negative and read as "very fresh". Clock skew or a hand-edited cache must
        # not be able to pin a stale size indefinitely.
        if [[ -n "$value" && "$recorded" =~ ^[0-9]+$ ]] \
            && (( recorded <= now )) \
            && (( now - recorded < FMIX_TREE_SIZE_TTL )); then
            printf '%s\n' "$value"
            return 0
        fi
    fi
    # No usable cached value: report unknown rather than walking 1.68M files here.
    # `fmix status --refresh-sizes` populates it explicitly.
    printf '?\n'
    return 0
}

# Explicit, bounded refresh of the cached tree sizes.
#
# Labels MUST match what fmix_tree_size_cached is called with, or the cache is
# written under keys nothing reads and every status stays "?". Templates are
# cached per template key because the reader iterates per template.
# Atomic: write beside the target and rename, so a concurrent reader never sees a
# truncated file and two concurrent refreshes cannot interleave.
fmix_tree_size_write() {
    local cache="$1" now="$2" size="$3" tmp
    tmp="${cache}.tmp-$$"
    if printf '{"recorded_at": %s, "size": "%s"}\n' "$now" "$size" > "$tmp" 2>/dev/null; then
        mv -f "$tmp" "$cache" 2>/dev/null || rm -f "$tmp" 2>/dev/null
    else
        rm -f "$tmp" 2>/dev/null
    fi
}

fmix_tree_size_refresh() {
    local dirs_root="$FMIX_HOME/templates" key size now
    mkdir -p "$FMIX_HOME/tree-sizes" 2>/dev/null || true
    now="$(date +%s)"
    # Keys written this run; anything else in the cache refers to a tree that no
    # longer exists and is pruned below, so the cache cannot grow without bound
    # across prune/rebuild cycles.
    local -a live_keys=()
    if [[ -d "$dirs_root" ]]; then
        for dir in "$dirs_root"/*/; do
            [[ -d "$dir" ]] || continue
            key="$(basename "$dir")"
            size="$(du -sh "$dir" 2>/dev/null | awk '{print $1}')" || size="?"
            fmix_tree_size_write "$FMIX_HOME/tree-sizes/template_${key}.json" "$now" "$size"
            live_keys+=("template_${key}.json")
            printf '%s  %s\n' "$size" "$dir"
        done
    fi
    local dep_root="$FMIX_HOME/dependency-artifacts/v1"
    if [[ -d "$dep_root" ]]; then
        size="$(du -sh "$dep_root" 2>/dev/null | awk '{print $1}')" || size="?"
        fmix_tree_size_write "$FMIX_HOME/tree-sizes/dependency_artifacts_v1.json" "$now" "$size"
        live_keys+=("dependency_artifacts_v1.json")
        printf '%s  %s\n' "$size" "$dep_root"
    fi
    local existing base keep lk
    shopt -s nullglob
    for existing in "$FMIX_HOME/tree-sizes"/*.json; do
        base="$(basename "$existing")"
        keep=0
        for lk in "${live_keys[@]+"${live_keys[@]}"}"; do
            [[ "$base" == "$lk" ]] && { keep=1; break; }
        done
        (( keep == 0 )) && rm -f "$existing" 2>/dev/null
    done
    shopt -u nullglob
}

cmd_status() {
    local scoped_run_id="" scoped_json=0 refresh_sizes=0
    while (( $# > 0 )); do
        case "$1" in
            --run-id)
                [[ $# -ge 2 ]] || { fmix_error "--run-id requires a UUID."; return 2; }
                scoped_run_id="$2"
                shift 2
                ;;
            --run-id=*) scoped_run_id="${1#--run-id=}"; shift ;;
            --json) scoped_json=1; shift ;;
            --refresh-sizes) refresh_sizes=1; shift ;;
            *) fmix_error "Unknown status option: $1. Usage: fmix status [--run-id <uuid> --json] [--refresh-sizes]"; return 2 ;;
        esac
    done
    # NOTE: the refresh runs further down, AFTER --run-id validation. It walks every
    # artifact tree (~90s), so doing it before validation would spend that cost on an
    # invocation that is about to exit 2 with a usage error.
    if [[ -n "$scoped_run_id" ]]; then
        if ! fmix_run_id_is_valid "$scoped_run_id"; then
            fmix_error "Invalid FMix run ID: $scoped_run_id"
            return 2
        fi
        if (( scoped_json != 1 )); then
            fmix_error "Scoped status requires --json. Usage: fmix status --run-id <uuid> --json"
            return 2
        fi
        local runs_root="$FMIX_HOME/telemetry/runs"
        local run_dir="$runs_root/$scoped_run_id"
        local canonical_runs canonical_run
        if [[ ! -d "$runs_root" || -L "$runs_root" || ! -d "$run_dir" || -L "$run_dir" ]]; then
            fmix_error "FMix run not found: $scoped_run_id"
            return 1
        fi
        canonical_runs="$(fmix_realpath "$runs_root" 2>/dev/null)" || canonical_runs=""
        canonical_run="$(fmix_realpath "$run_dir" 2>/dev/null)" || canonical_run=""
        if [[ -z "$canonical_runs" || "$canonical_runs" == "/" ]]; then
            fmix_error "FMix run not found: $scoped_run_id"
            return 1
        fi
        case "$canonical_run" in
            "$canonical_runs"/*) ;;
            *) fmix_error "FMix run not found: $scoped_run_id"; return 1 ;;
        esac
        local snapshot_path="$canonical_run/snapshot.json"
        if [[ ! -f "$snapshot_path" || -L "$snapshot_path" ]]; then
            fmix_error "FMix run not found: $scoped_run_id"
            return 1
        fi
        local py_bin
        py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
        "$py_bin" - "$snapshot_path" "$scoped_run_id" <<'PY'
import json
import sys

snapshot_path, expected_run_id = sys.argv[1:3]
try:
    with open(snapshot_path, encoding="utf-8") as fh:
        snapshot = json.load(fh)
except (OSError, json.JSONDecodeError):
    raise SystemExit(1)
if snapshot.get("version") != "fmix-session.v1" or snapshot.get("runId") != expected_run_id:
    raise SystemExit(1)
print(json.dumps(snapshot, separators=(",", ":")))
PY
        return $?
    fi
    if (( scoped_json == 1 )); then
        fmix_error "--json requires --run-id <uuid>."
        return 2
    fi

    local status_incomplete=0
    echo "=== fmix status ==="
    echo ""

    echo "--- Active Locks ($FMIX_HOME/locks/) ---"
    if [[ -d "$FMIX_HOME/locks" ]]; then
        local any_locks=0
        for ldir in "$FMIX_HOME/locks"/*/; do
            [[ -d "$ldir" ]] || continue
            any_locks=1
            local lname display_name pid state
            lname="$(basename "$ldir")"
            display_name="$(fmix_lock_display_name "$lname")"
            pid="$(cat "$ldir/pid" 2>/dev/null || echo "unknown")"
            if [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
                state="alive"
            else
                state="stale"
            fi
            printf "  %s  pid=%s  state=%s\n" "$display_name" "$pid" "$state"
        done
        (( any_locks == 0 )) && echo "  (none)"
    else
        echo "  (no locks directory yet)"
    fi
    echo ""

    # Templates
    # Explicit, bounded: walks the artifact trees ONCE and records the result.
    # Normal status never does this; it reads the cached figure. Ordered after all
    # argument validation so a rejected invocation never pays for the walk.
    if (( refresh_sizes == 1 )); then
        fmix_tree_size_refresh >/dev/null
    fi

    echo "--- Templates ($FMIX_HOME/templates/) ---"
    if [[ -d "$FMIX_HOME/templates" ]]; then
        local any_templates=0
        for tdir in "$FMIX_HOME/templates"/*/; do
            [[ -d "$tdir" ]] || continue
            local key
            key="$(basename "$tdir")"
            if [[ "$key" == *.tmp-* ]]; then
                echo "  [in-progress] $key"
                continue
            fi
            any_templates=1
            local status built_at last_used
            status="$(fmix_read_template_meta "$key" "status")"
            built_at="$(fmix_read_template_meta "$key" "built_at")"
            last_used="$(fmix_read_template_last_used "$key")"
            local size=""
            size="$(fmix_tree_size_cached "$tdir" "template_${key}")"
            printf "  %s  status=%-10s  built=%s  last_used=%s  size=%s\n" \
                "$key" "$status" "$built_at" "$last_used" "$size"
        done
        (( any_templates == 0 )) && echo "  (none)"
    else
        echo "  (no templates directory yet)"
    fi
    echo ""

    echo "--- Exact dependency artifacts ($FMIX_HOME/dependency-artifacts/) ---"
    local dependency_artifact_count=0 dependency_artifact_bytes="0"
    if [[ -d "$FMIX_HOME/dependency-artifacts/v1" ]]; then
        dependency_artifact_count="$(find "$FMIX_HOME/dependency-artifacts/v1" \
            -mindepth 2 -maxdepth 2 -type d 2>/dev/null | wc -l | tr -d ' ')"
        dependency_artifact_bytes="$(fmix_tree_size_cached "$FMIX_HOME/dependency-artifacts/v1" "dependency_artifacts_v1")"
        printf '  generations=%s  size=%s  ttl=%sd\n' \
            "${dependency_artifact_count:-0}" "${dependency_artifact_bytes:-0}" \
            "$FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS"
    else
        echo "  (none)"
    fi
    echo ""

    # Session-owned mutable overlays
    echo "--- Sessions ($FMIX_HOME/sessions/) ---"
    local any_sessions=0 session_meta session_root session_hash source path last_used
    local session_meta_paths
    if ! session_meta_paths="$(fmix_session_files meta.json)"; then
        fmix_error "Could not enumerate session metadata; the session list is incomplete."
        session_meta_paths=""
        status_incomplete=1
    fi
    while IFS= read -r session_meta; do
        [[ -f "$session_meta" ]] || continue
        any_sessions=1
        session_root="$(dirname "$session_meta")"
        session_hash="$(grep -o '"session_hash"[[:space:]]*:[[:space:]]*"[^"]*"' \
            "$session_meta" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
        source="$(grep -o '"source"[[:space:]]*:[[:space:]]*"[^"]*"' \
            "$session_meta" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
        path="$(grep -o '"worktree"[[:space:]]*:[[:space:]]*"[^"]*"' \
            "$session_meta" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
        last_used="$(grep -o '"last_used"[[:space:]]*:[[:space:]]*"[^"]*"' \
            "$session_meta" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
        printf "  %s  source=%s  last_used=%s\n    worktree=%s\n    root=%s\n" \
            "${session_hash:-unknown}" "${source:-unknown}" "${last_used:-unknown}" \
            "${path:-unknown}" "$session_root"
    done < <(printf '%s\n' "$session_meta_paths" | LC_ALL=C sort)
    if (( status_incomplete == 1 )); then
        echo "  (incomplete)"
    elif (( any_sessions == 0 )); then
        echo "  (none)"
    fi
    echo ""

    # Worktrees
    echo "--- Worktrees ($FMIX_HOME/worktrees/) ---"
    if [[ -d "$FMIX_HOME/worktrees" ]]; then
        local any_wt=0
        for sf in "$FMIX_HOME/worktrees"/*.json; do
            [[ -f "$sf" ]] || continue
            any_wt=1
            local path tk db lu
            path="$(fmix_read_state "$sf" "path")"
            tk="$(fmix_read_state "$sf" "template_key")"
            db="$(fmix_read_state "$sf" "db_name")"
            lu="$(fmix_read_state "$sf" "last_used")"
            local exists_marker="  "
            [[ -d "$path" ]] || exists_marker="[GONE]"
            printf "  %s%s\n    template=%s  db=%s  last_used=%s\n" \
                "$exists_marker" "$path" "$tk" "$db" "$lu"
        done
        (( any_wt == 0 )) && echo "  (none)"
    else
        echo "  (no worktrees directory yet)"
    fi
    echo ""

    # Scratch DBs
    echo "--- Scratch DBs (ct_fmix_*) ---"
    local dbs
    dbs="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -t -c "SELECT datname FROM pg_database WHERE datname LIKE 'ct_fmix_%' ORDER BY datname" \
        2>/dev/null | tr -d ' ')" || dbs=""
    if [[ -n "$dbs" ]]; then
        printf '%s\n' "$dbs" | while IFS= read -r db; do
            [[ -n "$db" ]] || continue
            echo "  $db"
        done
    else
        echo "  (none)"
    fi
    echo ""

    # Active locks
    echo "--- Active locks ($FMIX_HOME/locks/) ---"
    if [[ -d "$FMIX_HOME/locks" ]]; then
        local any_locks=0
        for ldir in "$FMIX_HOME/locks"/*/; do
            [[ -d "$ldir" ]] || continue
            any_locks=1
            local lock_name display_name pid alive
            lock_name="$(basename "$ldir")"
            display_name="$(fmix_lock_display_name "$lock_name")"
            pid="$(cat "$ldir/pid" 2>/dev/null || echo "?")"
            alive="dead"
            kill -0 "$pid" 2>/dev/null && alive="alive"
            echo "  $display_name  pid=$pid  ($alive)"
        done
        (( any_locks == 0 )) && echo "  (none)"
    else
        echo "  (none)"
    fi
    echo ""
    (( status_incomplete == 0 )) || return 1
}

# ---------------------------------------------------------------------------
# cmd: fmix timing
# Review recent run telemetry (JSONL) and session fragmentation signals.
# ---------------------------------------------------------------------------

cmd_timing() {
    local limit=20 worktree_filter="" json_mode=0
    while (( $# > 0 )); do
        case "$1" in
            --limit) [[ $# -ge 2 ]] || { fmix_error "--limit requires N."; return 2; }; limit="$2"; shift 2 ;;
            --limit=*) limit="${1#--limit=}"; shift ;;
            --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path."; return 2; }; worktree_filter="$2"; shift 2 ;;
            --worktree=*) worktree_filter="${1#--worktree=}"; shift ;;
            --json) json_mode=1; shift ;;
            -h|--help)
                cat <<'EOF'
Usage: fmix timing [--limit N] [--worktree <path>] [--json]

Show recent fmix run telemetry from ~/.ct-fmix/logs/runs.jsonl and a
session-fragmentation summary (multiple sessions per worktree force full
recompiles of ~4.7k files each).

  --limit N       last N runs (default 20)
  --worktree PATH filter runs/sessions to this realpath
  --json          emit raw JSON lines for the selected runs
EOF
                return 0
                ;;
            *)
                fmix_error "Unknown option: $1"
                return 2
                ;;
        esac
    done
    if [[ ! "$limit" =~ ^[0-9]+$ ]] || (( limit < 1 )); then
        fmix_error "--limit must be a positive integer."
        return 2
    fi

    local path real_filter=""
    path="$(fmix_run_telemetry_jsonl_path)"
    if [[ -n "$worktree_filter" ]]; then
        real_filter="$(fmix_realpath "$worktree_filter" 2>/dev/null || printf '%s' "$worktree_filter")"
    fi

    local py_bin
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"

    echo "=== fmix timing (v${FMIX_VERSION}) ==="
    echo "Telemetry log: $path"
    echo ""

    "$py_bin" - "$path" "$limit" "$real_filter" "$json_mode" "$FMIX_HOME" <<'PY'
import json, os, sys
from collections import Counter, defaultdict
from pathlib import Path

path, limit_s, worktree_filter, json_mode_s, fmix_home = sys.argv[1:6]
limit = int(limit_s)
json_mode = json_mode_s == "1"
home = Path(fmix_home)

# --- recent runs ---
runs = []
if Path(path).is_file():
    with open(path, encoding="utf-8") as fh:
        for line in fh:
            line = line.strip()
            if not line:
                continue
            try:
                rec = json.loads(line)
            except json.JSONDecodeError:
                continue
            if worktree_filter and rec.get("worktree") != worktree_filter:
                continue
            runs.append(rec)
else:
    print("(no runs.jsonl yet — run fmix test once after upgrading to 2.1.2+)")

selected = runs[-limit:]
if json_mode:
    for rec in selected:
        print(json.dumps(rec, separators=(",", ":")))
else:
    print(f"--- Last {len(selected)} run(s) ---")
    if not selected:
        print("  (none)")
    for rec in selected:
        phases = rec.get("phases") or {}
        phase_s = " ".join(f"{k}={v}s" for k, v in phases.items())
        print(
            f"  {rec.get('ts','?'):20s}  total={rec.get('total_s','?'):>4}s  rc={rec.get('rc','?')}  "
            f"compile={rec.get('compile_outcome','?'):16s} files={rec.get('compile_files',0):>5}  "
            f"sess={str(rec.get('session_hash',''))[:12]}({rec.get('session_source','?')})"
        )
        print(f"    wt={rec.get('worktree','?')}")
        if phase_s:
            print(f"    phases: {phase_s}")
        if rec.get("compile_log"):
            print(f"    compile_log: {rec['compile_log']}")
    print()

# --- session fragmentation ---
print("--- Session fragmentation (multi-session per worktree = full recompiles) ---")
by_wt = defaultdict(list)
sessions_root = home / "sessions" / "v1"
if sessions_root.is_dir():
    for meta in sessions_root.glob("*/*/*/meta.json"):
        try:
            d = json.loads(meta.read_text(encoding="utf-8"))
        except Exception:
            continue
        wt = d.get("worktree") or "?"
        if worktree_filter and wt != worktree_filter:
            continue
        by_wt[wt].append({
            "session_id": d.get("session_id") or d.get("session_hash") or meta.parent.parent.name,
            "source": d.get("source", "?"),
            "last": d.get("last_accessed") or d.get("last_used") or "?",
            "root": str(meta.parent),
        })

if not by_wt:
    print("  (no session meta.json found)")
else:
    ranked = sorted(by_wt.items(), key=lambda kv: (-len(kv[1]), kv[0]))
    multi = 0
    for wt, items in ranked[:30]:
        sources = Counter(i["source"] for i in items)
        flag = " !! MULTI" if len(items) > 1 else ""
        if len(items) > 1:
            multi += 1
        print(f"  {len(items):2d} session(s){flag}  sources={dict(sources)}")
        print(f"     worktree={wt}")
        for it in sorted(items, key=lambda x: x["last"], reverse=True)[:6]:
            print(f"       - {it['session_id']}  source={it['source']}  last={it['last']}")
        if len(items) > 6:
            print(f"       … +{len(items)-6} more")
    print()
    print(f"  worktrees with >1 session: {multi}/{len(by_wt)}")
    if multi:
        print("  Hint: prefer ONE stable identity per checkout.")
        print("        Default (no --session) is worktree-stable.")
        print("        Avoid unique --session / FMIX_SESSION_ID / CODEX_THREAD_ID per tool call.")
        print("        Each new session clones template + often recompiles ~4700 files.")

# --- recent compile logs summary ---
print()
print("--- Recent compile logs (last 15) ---")
logs = sorted((home / "logs").glob("compile-*.log"), key=lambda p: p.stat().st_mtime, reverse=True)[:15]
import re
pat = re.compile(r"Compiling (\d+) files?")
if not logs:
    print("  (none)")
else:
    for p in logs:
        try:
            text = p.read_text(encoding="utf-8", errors="replace")
        except Exception:
            continue
        nums = [int(x) for x in pat.findall(text)]
        total = sum(nums)
        heal = "heal" if "Healed" in text else "-"
        kind = "FULL" if total >= 1000 else ("PART" if total > 0 else "NONE")
        print(f"  {p.name}  files={total:5d}  {kind:4s}  {heal}")
PY
}

# ---------------------------------------------------------------------------
# cmd: fmix gc
# ---------------------------------------------------------------------------

fmix_session_worktree_from_meta() {
    local meta="$1"
    grep -o '"worktree"[[:space:]]*:[[:space:]]*"[^"]*"' "$meta" 2>/dev/null \
        | head -1 | sed 's/.*: *"\(.*\)".*/\1/'
}

fmix_session_source_from_meta() {
    local meta="$1"
    grep -o '"source"[[:space:]]*:[[:space:]]*"[^"]*"' "$meta" 2>/dev/null \
        | head -1 | sed 's/.*: *"\(.*\)".*/\1/'
}

fmix_session_last_from_meta() {
    local meta="$1" last
    last="$(grep -o '"last_accessed"[[:space:]]*:[[:space:]]*"[^"]*"' "$meta" 2>/dev/null \
        | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
    if [[ -z "$last" ]]; then
        last="$(grep -o '"last_used"[[:space:]]*:[[:space:]]*"[^"]*"' "$meta" 2>/dev/null \
            | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
    fi
    printf '%s\n' "${last:-}"
}

# Keep one warm session per worktree realpath (prefer worktree-default source,
# then newest last_accessed). Reap the rest when do_reap=1.
fmix_gc_consolidate_sessions() {
    local do_reap="$1" skip_prompts="$2" worktree_filter="${3:-}"
    local real_filter="" py_bin
    local -a victims=()
    local actions=0

    if [[ -n "$worktree_filter" ]]; then
        real_filter="$(fmix_realpath "$worktree_filter" 2>/dev/null || printf '%s' "$worktree_filter")"
    fi

    echo ""
    echo "--- Session consolidate (one warm overlay per worktree) ---"

    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    local plan
    plan="$(
        FMIX_HOME_FOR_GC="$FMIX_HOME" \
        WORKTREE_FILTER="$real_filter" \
        "$py_bin" - <<'PY'
import json, os
from pathlib import Path
from collections import defaultdict

home = Path(os.environ["FMIX_HOME_FOR_GC"])
filt = os.environ.get("WORKTREE_FILTER") or ""
by_wt = defaultdict(list)
root = home / "sessions" / "v1"
if not root.is_dir():
    raise SystemExit(0)
for meta in root.glob("*/*/*/meta.json"):
    try:
        d = json.loads(meta.read_text(encoding="utf-8"))
    except Exception:
        continue
    wt = d.get("worktree") or ""
    if filt and wt != filt:
        continue
    source = d.get("source") or ""
    last = d.get("last_accessed") or d.get("last_used") or ""
    session_root = str(meta.parent)
    session_hash = d.get("session_hash") or d.get("session_id") or meta.parent.parent.name
    # Prefer worktree-default, then highest last_accessed lexicographically (ISO-8601 ok)
    rank_source = 0 if source == "worktree-default" else 1
    has_stamp = 0 if (meta.parent / "compile-stamp.json").is_file() else 1
    by_wt[wt].append((rank_source, has_stamp, last, session_hash, session_root, source))

for wt, items in sorted(by_wt.items()):
    if len(items) <= 1:
        continue
    items_sorted = sorted(items)  # keep best (lowest rank_source, has_stamp, then last)
    # Actually keep NEWEST last among preferred source: sort by (rank_source, has_stamp, -last)
    items_sorted = sorted(items, key=lambda t: (t[0], t[1], t[2]), reverse=False)
    # Prefer lowest rank_source and has_stamp=0, then max last → custom
    def keep_key(t):
        rank_source, has_stamp, last, *_ = t
        return (rank_source, has_stamp, last)
    # best = min rank_source, min has_stamp, max last
    best = sorted(items, key=lambda t: (t[0], t[1], t[2]))[0]
    # Fix: among rank_source=0 and has_stamp=0, want newest last
    best = max(items, key=lambda t: (
        1 if t[0] == 0 else 0,
        1 if t[1] == 0 else 0,
        t[2],
    ))
    print(f"KEEP\t{wt}\t{best[3]}\t{best[5]}\t{best[4]}")
    for t in items:
        if t[4] == best[4]:
            continue
        print(f"DROP\t{wt}\t{t[3]}\t{t[5]}\t{t[4]}")
PY
    )" || plan=""

    if [[ -z "$plan" ]]; then
        echo "  (no multi-session worktrees to consolidate)"
        return 0
    fi

    local line op wt shash source sroot
    while IFS=$'\t' read -r op wt shash source sroot; do
        [[ -n "$op" ]] || continue
        if [[ "$op" == "KEEP" ]]; then
            echo "  KEEP  session=$shash source=$source"
            echo "        worktree=$wt"
            echo "        root=$sroot"
            continue
        fi
        [[ "$op" == "DROP" ]] || continue
        actions=$(( actions + 1 ))
        echo "  DROP  session=$shash source=$source"
        echo "        worktree=$wt"
        echo "        root=$sroot"
        if (( do_reap != 1 )); then
            continue
        fi
        local confirm="y"
        if (( skip_prompts == 0 )); then
            printf '  Reap session %s? [y/N] ' "$shash"
            read -r confirm
        fi
        [[ "$confirm" =~ ^[Yy]$ ]] || continue
        # Drop scratch DB then directory (lease-aware: refuse if lock held)
        local lock_name="session-$shash"
        if fmix_lock_acquire "$lock_name" 0 "session GC consolidate" >/dev/null 2>&1; then
            :
        else
            local acquire_rc=$?
            fmix_lock_failure_is_fatal "$acquire_rc" && return 70
            fmix_warn "Skipping live session $shash (lock held by active process or clone)."
            continue
        fi
        if [[ -d "$FMIX_HOME/locks/$lock_name" ]]; then
            local pid
            pid="$(cat "$FMIX_HOME/locks/$lock_name/pid" 2>/dev/null || true)"
            if [[ "$pid" =~ ^[0-9]+$ ]] && (( pid != $$ )) && kill -0 "$pid" 2>/dev/null; then
                fmix_lock_release_optional "$lock_name" || {
                    local release_rc=$?
                    fmix_lock_failure_is_fatal "$release_rc" && return 70
                    true
                }
                fmix_warn "Skipping live session $shash (pid=$pid holds lock)."
                continue
            fi
        fi
        local db_name
        db_name="ct_fmix_s_${shash}"
        if fmix_guard_db_name "$db_name" 2>/dev/null && fmix_db_exists "$db_name" 2>/dev/null; then
            if fmix_drop_db "$db_name" 1 2>/dev/null; then
                echo "    dropped db $db_name"
            else
                local drop_rc=$?
                if fmix_lock_failure_is_fatal "$drop_rc"; then
                    fmix_command_lock_finish "$lock_name" "$drop_rc"
                    return $?
                fi
                fmix_warn "Could not drop $db_name"
            fi
        fi
        if fmix_guard_path "$sroot" 2>/dev/null; then
            rm -rf "$sroot" && echo "    removed $sroot" || fmix_warn "Could not remove $sroot"
            # Remove empty parent session_hash dir
            rmdir "$(dirname "$sroot")" 2>/dev/null || true
        else
            fmix_warn "Refusing to remove path outside FMIX_HOME: $sroot"
        fi
        fmix_lock_release_optional "$lock_name" || {
            local release_rc=$?
            fmix_lock_failure_is_fatal "$release_rc" && return 70
            true
        }
    done <<<"$plan"

    if (( actions == 0 )); then
        echo "  (no multi-session worktrees to consolidate)"
    elif (( do_reap == 0 )); then
        echo "  $actions session(s) eligible. Re-run with: fmix gc --consolidate --yes"
    else
        echo "  consolidate complete ($actions candidate(s) processed)."
    fi
    return 0
}

fmix_gc_artifact_retirement_requested() {
    local arg
    for arg in "$@"; do
        case "$arg" in
            --adopt|--plan|--retire-plan|--pin|--unpin|--resume|--auto-expire) return 0 ;;
        esac
    done
    return 1
}

cmd_gc_artifact_retirement() {
    local mode="" artifact_id="" consumer="" pin_id="" arg py_bin dependency_ttl template_ttl runner
    while (( $# > 0 )); do
        case "$1" in
            --artifacts-only|--json) shift ;;
            --help|-h)
                printf '%s\n' 'fmix gc --artifacts-only [--adopt ID|--plan ID|--retire-plan ID|--pin ID --consumer NAME|--unpin PIN|--auto-expire]'
                return 0 ;;
            --adopt|--plan|--retire-plan|--pin|--unpin|--resume)
                [[ -z "$mode" && $# -ge 2 ]] || return 2
                mode="${1#--}"
                case "$mode" in
                    unpin|retire-plan|resume) pin_id="$2" ;;
                    *) artifact_id="$2" ;;
                esac
                shift 2 ;;
            --auto-expire)
                [[ -z "$mode" ]] || return 2
                mode="auto-expire"
                shift ;;
            --consumer)
                [[ $# -ge 2 && -z "$consumer" ]] || return 2
                consumer="$2"
                shift 2 ;;
            *)
                printf '%s\n' '{"error":"unsupported_artifact_retirement_option"}'
                return 2 ;;
        esac
    done
    [[ -n "$mode" ]] || return 2
    case "$mode" in
        adopt|plan|pin)
            [[ "$artifact_id" =~ ^(template|template-v2):[0-9a-f]{16}$|^(dependency|dependency-v2|app-compile-v2):[0-9a-f]{64}/[0-9a-f]{64}$ ]] || return 2 ;;
        retire-plan|resume)
            [[ "$pin_id" =~ ^[0-9a-f]{64}$ ]] || return 2 ;;
        unpin) [[ "$pin_id" =~ ^[0-9a-f]{32}$ ]] || return 2 ;;
        auto-expire) ;;
        *) return 2 ;;
    esac
    if [[ "$mode" == "pin" || "$mode" == "unpin" ]]; then
        [[ "$consumer" =~ ^[A-Za-z0-9._-]{1,80}$ ]] || return 2
    elif [[ -n "$consumer" ]]; then return 2
    fi
    if [[ "$mode" == "auto-expire" || "$mode" == "unpin" \
        || "$mode" == "retire-plan" || "$mode" == "resume" \
        || "$artifact_id" == template-v2:* || "$artifact_id" == dependency-v2:* \
        || "$artifact_id" == app-compile-v2:* ]]; then
        local handoff_reason
        handoff_reason="$(fmix_artifact_v2_managed_entrypoint 2>&1)" || {
            case "$handoff_reason" in
                unsafe_launcher_parent|unsafe_runner_runtime) ;;
                *) handoff_reason="managed_launcher_handoff_unproven" ;;
            esac
            printf '{"schema":"fmix-artifact-retirement.v2","status":"held","reason":"%s"}\n' "$handoff_reason"
            return 1
        }
    fi
    fmix_prepare_command_home || return 1
    dependency_ttl="$(fmix_effective_artifact_ttl_hours dependency)" || return 2
    template_ttl="$(fmix_effective_artifact_ttl_hours template)" || return 2
    auto_expire_max="$(fmix_auto_expire_batch_limit)"
    py_bin="$(fmix_python_bin)" || return 1
    runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || return 1
    "$py_bin" -I -B - "$FMIX_HOME" "$runner" "$0" "$$" "$mode" "$artifact_id" "$consumer" "$pin_id" "$dependency_ttl" "$template_ttl" "$auto_expire_max" <<'PY'
import contextlib, ctypes, datetime, hashlib, json, os, re, select, stat, subprocess, sys, time

home, runner, entrypoint, entrypoint_pid, mode, artifact_id, consumer, object_id, dep_ttl, template_ttl, auto_expire_max = sys.argv[1:]
home = os.path.abspath(home)
entrypoint = os.path.abspath(entrypoint)
entrypoint_pid = int(entrypoint_pid)
if entrypoint_pid <= 0: raise ValueError("invalid FMix entrypoint PID")
uid = os.getuid()
if uid == 0 or os.geteuid() != uid:
    raise ValueError("privileged_cleaner_forbidden")
now = datetime.datetime.now(datetime.timezone.utc)
sha = lambda value: hashlib.sha256(value).hexdigest()
hexkey = lambda value, width: (
    isinstance(value, str)
    and re.fullmatch(r"[0-9a-f]{%d}" % width, value) is not None
)
retirement_deadline=time.monotonic()+45
retirement_bytes_remaining=8*1024*1024*1024
retirement_entries_remaining=4000000
def retirement_bound(byte_count=0,entry_count=0):
    global retirement_bytes_remaining,retirement_entries_remaining
    if time.monotonic()>retirement_deadline: raise ValueError("retirement_work_deadline")
    retirement_bytes_remaining-=byte_count
    retirement_entries_remaining-=entry_count
    if retirement_bytes_remaining<0: raise ValueError("retirement_byte_budget")
    if retirement_entries_remaining<0: raise ValueError("retirement_entry_budget")
def bounded_names(fd):
    names=[]
    with os.scandir(fd) as iterator:
        for entry in iterator:
            retirement_bound(entry_count=1)
            names.append(entry.name)
    return sorted(names)
def fail(reason, status=2):
    print(json.dumps({"schema":"fmix-artifact-retirement.v2","status":"held","reason":reason},sort_keys=True))
    raise SystemExit(status)
if not re.fullmatch(r"[0-9]{1,4}", auto_expire_max) or not 1 <= int(auto_expire_max) <= 10:
    fail("invalid_auto_expire_batch_limit")
auto_expire_max = int(auto_expire_max)
def canonical(value):
    return json.dumps(value,sort_keys=True,separators=(",",":"),ensure_ascii=True).encode()
def identity(st):
    return {"device":st.st_dev,"inode":st.st_ino,"uid":st.st_uid,"mode":st.st_mode,
            "size":st.st_size,"mtime_ns":st.st_mtime_ns,"ctime_ns":st.st_ctime_ns,
            "nlink":st.st_nlink,"flags":getattr(st,"st_flags",0)}
def safe_parts(value):
    if not isinstance(value,str) or value.startswith("/") or "\\" in value:
        raise ValueError("unsafe relative path")
    parts=value.split("/")
    if not parts or any(part in ("",".","..") for part in parts):
        raise ValueError("unsafe path component")
    return parts
dir_flags=os.O_RDONLY|getattr(os,"O_DIRECTORY",0)|getattr(os,"O_NOFOLLOW",0)
rootfd=os.open(home,dir_flags)
home_st=os.fstat(rootfd)
if os.path.realpath(home)!=home or home_st.st_uid!=uid:
    fail("unavailable_or_unsafe_home")
def open_dir(rel):
    fd=os.dup(rootfd)
    try:
        for part in safe_parts(rel):
            nxt=os.open(part,dir_flags,dir_fd=fd)
            os.close(fd)
            fd=nxt
            st=os.fstat(fd)
            if st.st_uid!=uid or st.st_dev!=home_st.st_dev:
                raise ValueError("foreign directory")
        return fd
    except Exception:
        os.close(fd)
        raise
def parent_and_name(rel):
    parts=safe_parts(rel)
    parent="/".join(parts[:-1])
    return (open_dir(parent) if parent else os.dup(rootfd)),parts[-1]
def read_file(rel,limit=16*1024*1024):
    parent,name=parent_and_name(rel)
    try:
        fd=os.open(name,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0)|getattr(os,"O_NONBLOCK",0),dir_fd=parent)
    finally: os.close(parent)
    try:
        before=os.fstat(fd)
        if not stat.S_ISREG(before.st_mode) or before.st_uid!=uid or before.st_dev!=home_st.st_dev or before.st_nlink!=1 or before.st_size>limit:
            raise ValueError("unsafe metadata file")
        data=bytearray()
        while True:
            block=os.read(fd,min(65536,limit+1-len(data)))
            if not block: break
            retirement_bound(len(block))
            data.extend(block)
            if len(data)>limit: raise ValueError("oversize metadata")
        after=os.fstat(fd)
        if identity(before)!=identity(after): raise ValueError("changed metadata")
        return bytes(data),identity(after)
    finally: os.close(fd)
def no_markers(path,st):
    if getattr(st,"st_flags",0): raise ValueError("protected filesystem flags")
    if hasattr(os,"listxattr"):
        if os.path.isabs(path): raise ValueError("unsafe marker path")
        attrs=os.listxattr(os.path.join(home,path),follow_symlinks=False)
        if attrs: raise ValueError("protected extended attributes")
def run_audit():
    result=subprocess.run(["/bin/bash",runner,"gc","--artifacts-only","--json"],
        env=os.environ.copy(),capture_output=True,timeout=10)
    retirement_bound(len(result.stdout)+len(result.stderr))
    if result.returncode or result.stderr: raise ValueError("artifact audit incomplete")
    report=strict_load(result.stdout)
    required={"schema","mutation_supported","idle_ttl_hours","observed_at","source_sha256",
              "home","holds","entries","observations","report_truncated"}
    if (not isinstance(report,dict) or set(report)!=required
            or report.get("schema")!="fmix-artifact-audit.v1" or report.get("mutation_supported") is not False
            or report.get("home")!=home or report.get("report_truncated") is not False):
        raise ValueError("artifact audit schema or output incomplete")
    if (not isinstance(report.get("holds"),list) or any(not isinstance(v,str) for v in report["holds"])
            or not isinstance(report.get("entries"),list) or not isinstance(report.get("observations"),list)):
        raise ValueError("artifact audit observation schema")
    with open(runner,"rb") as handle: runner_sha=sha(handle.read())
    if report.get("source_sha256")!=runner_sha: raise ValueError("runner digest mismatch")
    return report,runner_sha
LEGACY_HOLDS={"external_consumers_unknown","liveness_unproven",
    "consumer_coverage_unproven","fallback_preservation_unproven",
    "missing_ps","missing_lsof"}
def known_global_holds(report):
    # Historical/external coverage stays held until an independent owner witness exists.
    return set(report.get("holds",[]))
def managed_launcher_paths():
    user_home=os.path.abspath(os.environ.get("HOME",""))
    if not user_home or os.path.realpath(user_home)!=user_home: raise ValueError("noncanonical_user_home")
    known={user_home+"/.local/bin/fmix",user_home+"/.local/share/fmix/bin/fmix"}
    custom=os.environ.get("FMIX_INSTALL_DIR")
    if custom:
        custom=os.path.abspath(custom)
        if os.path.commonpath((user_home,custom))!=user_home: raise ValueError("unsafe_install_root")
        known.add(os.path.join(custom,"fmix"))
    paths=[]
    for path in sorted(known):
        try: link=os.lstat(path)
        except FileNotFoundError: continue
        parent=os.path.dirname(path)
        if os.path.commonpath((user_home,parent))!=user_home: raise ValueError("launcher_outside_home")
        rel=os.path.relpath(parent,user_home); current=user_home
        for part in (() if rel=="." else rel.split(os.sep)):
            current=os.path.join(current,part); st=os.lstat(current)
            if not stat.S_ISDIR(st.st_mode) or st.st_uid!=uid or stat.S_ISLNK(st.st_mode) or st.st_mode&0o022: raise ValueError("unsafe_launcher_parent")
        if not stat.S_ISLNK(link.st_mode) or link.st_uid!=uid or link.st_nlink!=1 or os.path.realpath(path)!=runner:
            raise ValueError("managed_launcher_downgrade")
        paths.append(path)
    return user_home,paths
def require_managed_handoff():
    if uid==0 or os.geteuid()!=uid: raise ValueError("privileged_cleaner_forbidden")
    user_home,paths=managed_launcher_paths()
    if not paths or (entrypoint not in paths and entrypoint!=runner): raise ValueError("managed_launcher_handoff_unproven")
    runtime=home+"/runtime"; st=os.lstat(runtime)
    if not stat.S_ISDIR(st.st_mode) or st.st_uid!=uid or st.st_mode&0o022 or os.path.realpath(runtime)!=runtime:
        raise ValueError("unsafe_runner_runtime")
    fd=os.open(runner,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0))
    try:
        info=os.fstat(fd)
        if not stat.S_ISREG(info.st_mode) or info.st_uid!=uid or info.st_nlink!=1 or info.st_mode&0o222 or not info.st_mode&0o111 or info.st_size>4*1024*1024:
            raise ValueError("unsafe_runner_identity")
        hasher=hashlib.sha256()
        for block in iter(lambda:os.read(fd,65536),b""):
            retirement_bound(len(block)); hasher.update(block)
        if identity(info)!=identity(os.fstat(fd)): raise ValueError("runner_identity_changed")
        digest=hasher.hexdigest()
        if runner!=runtime+"/fmix-"+digest or any(os.path.realpath(path)!=runner for path in paths):
            raise ValueError("managed_launcher_runner_mismatch")
    finally: os.close(fd)
    return digest
def process_snapshot(candidate):
    command=["ps","-axo","pid=,ppid=,uid=,command="] if sys.platform=="darwin" else ["ps","-eo","pid=,ppid=,uid=,args="]
    result=subprocess.run(command,capture_output=True,timeout=4)
    retirement_bound(len(result.stdout)+len(result.stderr))
    if result.returncode or result.stderr: raise ValueError("process census incomplete")
    rows={}
    for line in result.stdout.decode("utf-8","strict").splitlines():
        fields=line.strip().split(None,3)
        if len(fields)!=4 or not all(fields[i].isdigit() for i in range(3)):
            raise ValueError("process row schema")
        pid,ppid,process_uid=map(int,fields[:3])
        rows[pid]=(ppid,process_uid,fields[3])
    foreign=[pid for pid,(_,process_uid,_) in rows.items() if process_uid!=uid]
    if foreign:
        raise ValueError(f"foreign_consumer_unknown:uid_scope={uid}:foreign_processes={len(foreign)}")
    entrypoint_row=rows.get(entrypoint_pid)
    entrypoint_command=entrypoint_row[2] if entrypoint_row else ""
    exact_entrypoint=(entrypoint_pid==os.getppid() and entrypoint in entrypoint_command
        and re.search(r"(?:^|\s)gc\s+--artifacts-only(?:\s|$)",entrypoint_command) is not None)
    for pid,(_,process_uid,command_line) in rows.items():
        if re.search(r"(^|/)fmix(?:\s|$)",command_line,re.I) and pid!=os.getpid():
            if pid!=entrypoint_pid or not exact_entrypoint:
                raise ValueError("active_fmix_process")
        if candidate in command_line:
            raise ValueError("process_reference")
    return {"sha256":sha(result.stdout),"uid_scope":uid,"coverage":"same-uid-only;foreign-uid-presence-holds",
            "process_count":len(rows),"foreign_process_count":0}
def open_file_snapshot(candidate):
    command=["lsof","-nP","-a","-u",str(uid),"+D",candidate,"-Fpcfn"]
    proc=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    observer_pid=proc.pid
    try: output,error=proc.communicate(timeout=5)
    except subprocess.TimeoutExpired:
        proc.kill(); proc.communicate(); raise ValueError("open_file_census_timeout")
    retirement_bound(len(output)+len(error))
    if proc.returncode not in (0,1) or error: raise ValueError("open_file_census_incomplete")
    pid=None; names=[]; count=0
    for line in output.decode("utf-8","strict").splitlines():
        if line.startswith("p") and line[1:].isdigit(): pid=int(line[1:])
        elif line.startswith("n"):
            path=line[1:]
            if pid!=observer_pid and (path==candidate or path.startswith(candidate+os.sep)): count+=1
    return {"sha256":sha(output),"open_count":count,"uid_scope":uid,"coverage":"uid-only",
            "system_open_files_observer":"unsupported"}
def liveness(candidate):
    process=process_snapshot(candidate)
    opened=open_file_snapshot(candidate)
    if opened["open_count"]: raise ValueError("open_file_reference")
    return {"process":process,"open_files":opened}
def strict_load(raw):
    def pairs(items):
        result={}
        for key,value in items:
            if key in result: raise ValueError("duplicate JSON key")
            result[key]=value
        return result
    return json.loads(raw,object_pairs_hook=pairs,parse_constant=lambda _: (_ for _ in ()).throw(ValueError()))
def mkdirs_safe(rel):
    parts=safe_parts(rel); fd=os.dup(rootfd)
    try:
        for part in parts:
            try: os.mkdir(part,0o700,dir_fd=fd)
            except FileExistsError: pass
            nxt=os.open(part,dir_flags,dir_fd=fd)
            st=os.fstat(nxt)
            if not stat.S_ISDIR(st.st_mode) or st.st_uid!=uid or st.st_dev!=home_st.st_dev:
                os.close(nxt); raise ValueError("unsafe retirement directory")
            os.close(fd); fd=nxt
        os.fsync(fd)
    finally: os.close(fd)
def rename_noreplace(srcfd,src,dstfd,dst):
    libc=ctypes.CDLL(None,use_errno=True)
    if sys.platform=="darwin":
        fn=getattr(libc,"renameatx_np",None); flags=0x4
    elif sys.platform.startswith("linux"):
        fn=getattr(libc,"renameat2",None); flags=1
    else: fn=None; flags=0
    if fn is None: raise ValueError("atomic_noreplace_unavailable")
    fn.argtypes=[ctypes.c_int,ctypes.c_char_p,ctypes.c_int,ctypes.c_char_p,ctypes.c_uint]
    fn.restype=ctypes.c_int
    rc=fn(srcfd,os.fsencode(src),dstfd,os.fsencode(dst),flags)
    if rc:
        error=ctypes.get_errno()
        raise OSError(error,os.strerror(error))
def write_json(rel,value,replace=False):
    parent,name=parent_and_name(rel)
    temp=f".{name}.tmp.{os.getpid()}.{time.time_ns()}"
    data=canonical(value)
    fd=os.open(temp,os.O_WRONLY|os.O_CREAT|os.O_EXCL|getattr(os,"O_NOFOLLOW",0),0o600,dir_fd=parent)
    try:
        view=memoryview(data)
        while view:
            count=os.write(fd,view); view=view[count:]
        os.fsync(fd)
    finally: os.close(fd)
    try:
        if replace:
            old=os.stat(name,dir_fd=parent,follow_symlinks=False)
            if not stat.S_ISREG(old.st_mode) or old.st_uid!=uid or old.st_dev!=home_st.st_dev or old.st_nlink!=1:
                raise ValueError("unsafe replacement target")
        else:
            try: os.stat(name,dir_fd=parent,follow_symlinks=False)
            except FileNotFoundError: pass
            else: raise FileExistsError(name)
        os.rename(temp,name,src_dir_fd=parent,dst_dir_fd=parent)
        os.fsync(parent)
    except Exception:
        try: os.unlink(temp,dir_fd=parent)
        except OSError: pass
        raise
    finally: os.close(parent)
def read_json(rel):
    raw,identity_value=read_file(rel)
    return strict_load(raw),raw,identity_value
def artifact_id_for(row):
    pool=row["pool"]
    prefix=("template-v2" if pool=="template-v2" else "template" if pool=="template"
            else "app-compile-v2" if pool=="app-compile-v2"
            else "dependency-v2" if pool=="dependency-v2" else "dependency")
    return prefix+":"+row["key"] if pool.startswith("template") else prefix+":"+row["lane"]+"/"+row["key"]
def parse_artifact_id(value):
    for prefix,pool in (("template-v2","template-v2"),("template","template"),
                        ("app-compile-v2","app-compile-v2"),
                        ("dependency-v2","dependency-v2"),("dependency","dependency")):
        if pool.startswith("template"):
            match=re.fullmatch(prefix+r":([0-9a-f]{16})",value or "")
            if match: return pool,None,match.group(1)
        else:
            match=re.fullmatch(prefix+r":([0-9a-f]{64})/([0-9a-f]{64})",value or "")
            if match: return pool,match.group(1),match.group(2)
    raise ValueError("invalid artifact identifier")
def pool_kind(pool):
    return "template" if pool.startswith("template") else "app" if pool.startswith("app") else "dependency"
def pool_v2(pool): return pool.endswith("-v2")
def cache_rel(pool,lane,key):
    if pool=="template": return "templates/"+key
    if pool=="template-v2": return "artifacts/v2/templates/"+key
    if pool=="dependency": return "dependency-artifacts/v1/"+lane+"/"+key
    if pool=="dependency-v2": return "artifacts/v2/dependencies/"+lane+"/"+key
    if pool=="app-compile-v2": return "artifacts/v2/app-compiles/"+lane+"/"+key
    raise ValueError("unknown artifact pool")
def candidate_row(report,artifact_id):
    pool,lane,key=parse_artifact_id(artifact_id)
    matches=[row for row in report["entries"]
             if isinstance(row,dict) and row.get("pool")==pool and row.get("lane")==lane and row.get("key")==key]
    if len(matches)!=1: raise ValueError("candidate inventory is incomplete")
    row=matches[0]
    fields={"path","pool","key","lane","status","metadata_sha256","inspection","holds","identity",
            "manifest_sha256","reference_count","references","references_truncated"}
    if (set(row)!=fields or row.get("status")!="held" or row.get("inspection")!="metadata_and_manifest_shape_checked"
            or not isinstance(row.get("holds"),list) or any(not isinstance(v,str) for v in row["holds"])
            or type(row.get("reference_count")) is not int or not isinstance(row.get("references"),list)
            or not all(isinstance(v,str) for v in row["references"]) or type(row.get("references_truncated")) is not bool):
        raise ValueError("candidate inventory schema incomplete")
    if pool_kind(pool)=="template" and row["lane"] is not None: raise ValueError("template lane schema")
    if pool_kind(pool)!="template" and not hexkey(row["lane"],64): raise ValueError("dependency lane schema")
    expected=home+"/"+cache_rel(pool,lane,key)
    if row.get("path")!=expected: raise ValueError("candidate path identity mismatch")
    if pool_v2(pool): require_managed_handoff()
    return row,pool,lane,key,cache_rel(pool,lane,key)
def candidate_holds(report,row):
    holds=set(row.get("holds",[]))-{"payload_verification_unproven"}
    if pool_v2(row["pool"]):
        meta,_=read_meta(row)
        if meta.get("consumer_protocol")!="fmix-native-artifacts.v2":
            holds.add("unknown_v2_consumer_protocol")
        holds-={"external_consumers_unknown","consumer_coverage_unproven",
                "fallback_preservation_unproven","liveness_unproven"}
    else:
        holds|=known_global_holds(report)
        holds.add("legacy_generation_unenrolled")
    if report.get("report_truncated"): holds.add("report_truncated")
    if row.get("reference_count")!=0 or row.get("references_truncated"):
        holds.add("native_workspace_reference")
    if row.get("status")!="held": holds.add("unexpected_inventory_state")
    if holds: raise ValueError(",".join(sorted(holds)))
def lock_name(pool,lane,key):
    kind=pool_kind(pool)
    if kind=="template": return "build-"+key
    if kind=="app": return "app-compile-"+lane[:16]+"-"+key[:16]
    return "dependency-artifact-"+lane[:16]+"-"+key[:16]
LEASE_PROVIDER = """source "$FMIX_RETIREMENT_PROVIDER_RUNNER" || exit 70
lock_name="$1"
fmix_lock_acquire "$lock_name" 0 "artifact retirement" 1 || exit $?
printf 'READY\\n'
IFS= read -r request || request=""
protocol_rc=0
[[ "$request" == "release" ]] || protocol_rc=1
release_rc=0
fmix_lock_release "$lock_name" || release_rc=$?
printf 'RELEASED %s\\n' "$release_rc"
(( protocol_rc == 0 && release_rc == 0 ))"""
def acquire_named_lease(name):
    child_env=os.environ.copy()
    child_env["FMIX_RETIREMENT_PROVIDER_RUNNER"]=runner
    proc=subprocess.Popen(["/bin/bash","-c",LEASE_PROVIDER,"fmix-artifact-lease",name],
        env=child_env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,
        text=True,bufsize=1)
    ready,_,_=select.select([proc.stdout],[],[],15)
    if not ready:
        try:
            proc.stdin.write("release\n"); proc.stdin.flush()
        except (BrokenPipeError,OSError): pass
        try: proc.wait(timeout=15)
        except subprocess.TimeoutExpired: raise ValueError("artifact_lease_acquire_unconfirmed")
        raise ValueError("artifact_lease_ready_timeout")
    line=proc.stdout.readline()
    if line!="READY\n":
        try: proc.wait(timeout=15)
        except subprocess.TimeoutExpired: raise ValueError("artifact_lease_acquire_unconfirmed")
        raise ValueError("artifact_lease_acquire_failed:"+str(proc.returncode))
    return proc
def acquire_lease(pool,lane,key):
    return acquire_named_lease(lock_name(pool,lane,key))
RETIRE_ROOT="artifact-retirement/v2"
def ensure_retirement_dirs():
    for rel in ("artifact-retirement","artifact-retirement/v2",
                "artifact-retirement/v2/pins","artifact-retirement/v2/adoptions",
                "artifact-retirement/v2/plans","artifact-retirement/v2/journals",
                "artifact-retirement/v2/receipts"):
        mkdirs_safe(rel)
def list_names(rel):
    fd=open_dir(rel)
    try: return bounded_names(fd)
    finally: os.close(fd)
def pin_path(pin_id):
    return RETIRE_ROOT+"/pins/"+pin_id+".json"
def load_pins():
    pins=[]
    try: names=list_names(RETIRE_ROOT+"/pins")
    except FileNotFoundError: return pins
    for name in names:
        match=re.fullmatch(r"([0-9a-f]{32})\.json",name)
        if not match: raise ValueError("unknown_consumer_pin_layout")
        doc,raw,_=read_json(RETIRE_ROOT+"/pins/"+name)
        required={"schema","pin_id","artifact_id","consumer","created_at","uid"}
        if not isinstance(doc,dict) or set(doc)!=required or doc["schema"]!="fmix-artifact-pin.v2":
            raise ValueError("unknown_consumer_pin_schema")
        if (doc["pin_id"]!=match.group(1) or type(doc["uid"]) is not int
                or doc["uid"]!=uid or not re.fullmatch(r"[A-Za-z0-9._-]{1,80}",doc["consumer"])):
            raise ValueError("invalid_consumer_pin")
        parse_artifact_id(doc["artifact_id"])
        datetime.datetime.fromisoformat(doc["created_at"].replace("Z","+00:00"))
        pins.append(doc)
    return pins
def pins_for(pins,artifact_id):
    return [pin["pin_id"] for pin in pins if pin["artifact_id"]==artifact_id]
def adoption_path(artifact_id,identity_sha,runner_sha):
    key=sha((artifact_id+":"+identity_sha+":"+runner_sha).encode())
    return RETIRE_ROOT+"/adoptions/"+key+".json"
def plan_path(plan_id):
    return RETIRE_ROOT+"/plans/"+plan_id+".json"
def journal_path(plan_id):
    return RETIRE_ROOT+"/journals/"+plan_id+".json"
def receipt_path(plan_id):
    return RETIRE_ROOT+"/receipts/"+plan_id+".json"
def read_meta(row):
    pool=row["pool"]; kind=pool_kind(pool); v2=pool_v2(pool); lane=row.get("lane"); key=row["key"]
    if v2: require_managed_handoff()
    rel=cache_rel(pool,lane,key)+"/meta.json"
    raw,_=read_file(rel,1024*1024)
    if sha(raw)!=row.get("metadata_sha256"): raise ValueError("metadata digest changed")
    meta=strict_load(raw)
    dep_v1={"schema","lane","dependency_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
    app_v1={"schema","lane","compile_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
    template_v1={"schema","status","template_key","manifest_sha256","built_at","toolchain","source_commit"}
    expected=(app_v1 if kind=="app" else dep_v1 if kind=="dependency" else template_v1)
    if v2: expected=expected|{"producer_runner_sha256","consumer_protocol"}
    if not isinstance(meta,dict) or set(meta)!=expected or meta.get("schema")!=("2" if v2 else "1"):
        raise ValueError("metadata schema")
    if kind=="template" and (meta["status"]!="complete" or meta["template_key"]!=key
            or not meta["toolchain"] or not re.fullmatch(r"[0-9a-f]{7,40}",meta["source_commit"])):
        raise ValueError("template identity")
    if kind=="app" and (meta["lane"]!=lane or meta["compile_fingerprint"]!=key
            or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
            or meta["source_clean"] not in ("true","false")):
        raise ValueError("app compile identity")
    if kind=="dependency" and (meta["lane"]!=lane or meta["dependency_fingerprint"]!=key
            or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
            or meta["source_clean"] not in ("true","false")):
        raise ValueError("dependency identity")
    if v2:
        digest=meta.get("producer_runner_sha256")
        if not hexkey(digest,64) or meta.get("consumer_protocol")!="fmix-native-artifacts.v2":
            raise ValueError("unknown_v2_consumer_protocol")
        producer,producer_id=read_file("runtime/fmix-"+digest,4*1024*1024)
        if sha(producer)!=digest or producer_id["mode"]&0o222 or not producer_id["mode"]&0o111:
            raise ValueError("producer_runner_identity")
    if not hexkey(meta["manifest_sha256"],64): raise ValueError("manifest digest")
    built=datetime.datetime.fromisoformat(meta["built_at"].replace("Z","+00:00"))
    if built.tzinfo is None: raise ValueError("timestamp timezone")
    return meta,built
def last_access(row,pool,lane,key,built):
    if pool_v2(pool):
        rel=("artifact-access/v2/templates/"+key if pool_kind(pool)=="template"
             else "artifact-access/v2/app-compiles/"+lane+"/"+key if pool_kind(pool)=="app"
             else "artifact-access/v2/dependencies/"+lane+"/"+key)
    else:
        rel=("template-access/"+key if pool_kind(pool)=="template"
             else "dependency-artifact-access/"+lane+"/"+key)
    try: raw,_=read_file(rel,128)
    except FileNotFoundError: return built
    value=raw.decode("ascii").strip()
    try: access=datetime.datetime.fromisoformat(value.replace("Z","+00:00"))
    except ValueError: raise ValueError("invalid access timestamp")
    if access.tzinfo is None: raise ValueError("access timestamp timezone")
    return max(built,access)
def fallbacks(report):
    groups={}; broken=set(); unknown_template=False
    for row in report.get("entries",[]):
        try:
            meta,built=read_meta(row)
            kind=pool_kind(row["pool"])
            group=(kind,meta["toolchain"] if kind=="template" else row["lane"])
            groups.setdefault(group,[]).append((built,artifact_id_for(row)))
        except Exception:
            if pool_kind(row["pool"])=="template": unknown_template=True
            else: broken.add(row.get("lane"))
    protected=set()
    for group,items in groups.items():
        newest=max(value for value,_ in items)
        protected.update(artifact_id for value,artifact_id in items if value==newest)
    return protected,broken,unknown_template
def retirement_fallback_recheck(report,journal):
    pool,lane,key=parse_artifact_id(journal["artifact_id"]); kind=pool_kind(pool)
    meta=journal["snapshot"]["meta"]
    built=datetime.datetime.fromisoformat(meta["built_at"].replace("Z","+00:00"))
    protected,broken,unknown=fallbacks(report)
    if kind=="template" and unknown: raise ValueError("fallback_lane_unknown")
    if lane in broken: raise ValueError("fallback_lane_incomplete")
    group=meta["toolchain"] if kind=="template" else lane
    remaining=[]
    for row in report.get("entries",[]):
        if pool_kind(row["pool"])!=kind: continue
        try:
            other,built_other=read_meta(row)
            if (other["toolchain"] if kind=="template" else row["lane"])==group:
                remaining.append(built_other)
        except Exception: raise ValueError("fallback_lane_incomplete")
    if not remaining or max(remaining)<=built: raise ValueError("fallback_became_newest")
def verify_tree(row,base_rel=None,allow_owner_write=False):
    pool=row["pool"]; kind=pool_kind(pool); v2=pool_v2(pool); lane=row.get("lane"); key=row["key"]
    if v2: require_managed_handoff()
    base_rel=base_rel or cache_rel(pool,lane,key)
    rootfd_cache=open_dir(base_rel); rootst=os.fstat(rootfd_cache)
    if rootst.st_uid!=uid or rootst.st_dev!=home_st.st_dev: raise ValueError("foreign cache identity")
    no_markers(base_rel,rootst)
    if rootst.st_mode&0o222 and not (allow_owner_write and rootst.st_mode&0o200 and not rootst.st_mode&0o022):
        raise ValueError("writable cache root")
    reported=row.get("identity",{})
    audit_fields={"device","inode","uid","mode","mtime_ns","ctime_ns"}
    if set(reported)!=audit_fields or any(reported.get(k)!=identity(rootst).get(k) for k in audit_fields):
        os.close(rootfd_cache); raise ValueError("candidate identity incomplete or changed")
    try:
        names=bounded_names(rootfd_cache)
        expected_names=(["_build","manifest.sha256","manifest.tsv","meta.json"] if kind=="app"
                        else ["_build","deps","manifest.sha256","manifest.tsv","meta.json"])
        if names!=expected_names:
            raise ValueError("unexpected cache contents")
        meta_raw,meta_id=read_file(base_rel+"/meta.json",1024*1024)
        meta=strict_load(meta_raw)
        app_fields={"schema","lane","compile_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
        dep_fields={"schema","lane","dependency_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
        template_fields={"schema","status","template_key","manifest_sha256","built_at","toolchain","source_commit"}
        if v2:
            app_fields|={"producer_runner_sha256","consumer_protocol"}
            dep_fields|={"producer_runner_sha256","consumer_protocol"}
            template_fields|={"producer_runner_sha256","consumer_protocol"}
        expected_fields=(app_fields if kind=="app"
                         else dep_fields if kind=="dependency" else template_fields)
        if not isinstance(meta,dict) or set(meta)!=expected_fields or meta.get("schema")!=("2" if v2 else "1"):
            raise ValueError("metadata schema")
        if kind=="app" and (meta["lane"]!=lane or meta["compile_fingerprint"]!=key
                or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
                or meta["source_clean"] not in ("true","false")):
            raise ValueError("app compile metadata identity")
        if kind=="dependency" and (meta["lane"]!=lane or meta["dependency_fingerprint"]!=key
                or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
                or meta["source_clean"] not in ("true","false")):
            raise ValueError("dependency metadata identity")
        if kind=="template" and (meta["status"]!="complete" or meta["template_key"]!=key
                or not meta["toolchain"] or not re.fullmatch(r"[0-9a-f]{7,40}",meta["source_commit"])):
            raise ValueError("template metadata identity")
        if v2:
            digest=meta.get("producer_runner_sha256")
            if not hexkey(digest,64) or meta.get("consumer_protocol")!="fmix-native-artifacts.v2":
                raise ValueError("unknown_v2_consumer_protocol")
            producer,producer_id=read_file("runtime/fmix-"+digest,4*1024*1024)
            if sha(producer)!=digest or producer_id["mode"]&0o222 or not producer_id["mode"]&0o111:
                raise ValueError("producer_runner_identity")
        manifest,manifest_id=read_file(base_rel+"/manifest.tsv",8*1024*1024)
        recorded,recorded_id=read_file(base_rel+"/manifest.sha256",256)
        if sha(meta_raw)!=row.get("metadata_sha256"): raise ValueError("metadata digest changed")
        if sha(manifest)!=meta.get("manifest_sha256") or recorded!=(meta["manifest_sha256"]+"\n").encode():
            raise ValueError("manifest digest mismatch")
        fields=meta
        if not isinstance(fields,dict): raise ValueError("metadata object")
        records={}
        for line in manifest.decode("utf-8","strict").splitlines():
            retirement_bound(entry_count=1)
            parts=line.split("\t")
            if len(parts)<3: raise ValueError("manifest row")
            kind,path=parts[:2]; safe_parts(path)
            if (path.split("/")[0] not in (("_build",) if kind=="app" else ("deps","_build"))
                    or path in records):
                raise ValueError("manifest path")
            if kind=="D" and parts==["D",path,"-"]: pass
            elif kind=="F" and len(parts)==4 and parts[2].isdigit() and re.fullmatch(r"[0-9a-f]{64}",parts[3]): pass
            elif kind=="L" and len(parts)==3: pass
            else: raise ValueError("manifest entry")
            records[path]=parts
        seen=set(); nodes={"":identity(rootst)}
        directories=[]
        def walk(fd,prefix):
            for name in bounded_names(fd):
                rel=prefix+"/"+name
                st=os.stat(name,dir_fd=fd,follow_symlinks=False)
                if st.st_uid!=uid or st.st_dev!=home_st.st_dev: raise ValueError("foreign payload")
                if (not stat.S_ISLNK(st.st_mode) and st.st_mode&0o222
                        and not (allow_owner_write and stat.S_ISDIR(st.st_mode)
                            and st.st_mode&0o200 and not st.st_mode&0o022)):
                    raise ValueError("writable payload")
                no_markers(base_rel+"/"+rel,st)
                entry=records.get(rel)
                if entry is None: raise ValueError("unmanifested payload")
                seen.add(rel); nodes[rel]=identity(st)
                if stat.S_ISLNK(st.st_mode):
                    target=os.readlink(name,dir_fd=fd)
                    normalized=os.path.normpath(os.path.join(prefix,target))
                    if entry!=["L",rel,target] or os.path.isabs(target) or normalized==".." or normalized.startswith("../"):
                        raise ValueError("unsafe manifest link")
                elif stat.S_ISDIR(st.st_mode):
                    if entry!=["D",rel,"-"]: raise ValueError("directory manifest mismatch")
                    directories.append(rel)
                    child=os.open(name,dir_flags,dir_fd=fd)
                    try: walk(child,rel)
                    finally: os.close(child)
                elif stat.S_ISREG(st.st_mode):
                    if len(entry)!=4 or entry[0]!="F" or st.st_nlink!=1:
                        raise ValueError("file manifest mismatch")
                    filefd=os.open(name,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0),dir_fd=fd)
                    try:
                        before=os.fstat(filefd)
                        if identity(before)!=identity(st): raise ValueError("payload changed")
                        digest=hashlib.sha256(); size=0
                        while True:
                            data=os.read(filefd,1024*1024)
                            if not data: break
                            retirement_bound(len(data))
                            size+=len(data); digest.update(data)
                        if size!=int(entry[2]) or digest.hexdigest()!=entry[3]:
                            raise ValueError("payload digest mismatch")
                        if identity(before)!=identity(os.fstat(filefd)): raise ValueError("payload changed while hashing")
                    finally: os.close(filefd)
                else: raise ValueError("special payload")
        for top in (("_build",) if kind=="app" else ("deps","_build")):
            topfd=os.open(top,dir_flags,dir_fd=rootfd_cache)
            try:
                topst=os.fstat(topfd)
                if topst.st_uid!=uid or topst.st_dev!=home_st.st_dev: raise ValueError("unsafe payload root")
                if topst.st_mode&0o222 and not (allow_owner_write and topst.st_mode&0o200 and not topst.st_mode&0o022):
                    raise ValueError("writable payload root")
                no_markers(base_rel+"/"+top,topst)
                nodes[top]=identity(topst); directories.append(top)
                walk(topfd,top)
            finally: os.close(topfd)
        if seen!=set(records): raise ValueError("manifest path set mismatch")
        for name,info_value in (("meta.json",meta_id),("manifest.tsv",manifest_id),
                                ("manifest.sha256",recorded_id)):
            st=os.stat(name,dir_fd=rootfd_cache,follow_symlinks=False)
            if st.st_uid!=uid or st.st_dev!=home_st.st_dev or st.st_nlink!=1 or not stat.S_ISREG(st.st_mode):
                raise ValueError("unsafe metadata identity")
            if st.st_mode&0o222: raise ValueError("writable metadata file")
            if identity(st)!=info_value: raise ValueError("metadata changed during inventory")
            no_markers(base_rel+"/"+name,st); nodes[name]=info_value
        snapshot={"nodes":nodes,"manifest_sha256":sha(manifest),"metadata_sha256":sha(meta_raw),
                  "directories":sorted(directories),"meta":meta,"records":records}
        snapshot["identity_sha256"]=sha(canonical(nodes))
        return snapshot
    finally: os.close(rootfd_cache)
def check_aliases(report,row):
    root_id=row.get("identity",{})
    seen=set()
    for other in report.get("entries",[]):
        ident=other.get("identity",{})
        key=(ident.get("device"),ident.get("inode"))
        if key[0] is None or key[1] is None: raise ValueError("alias census incomplete")
        if key in seen: raise ValueError("candidate alias")
        seen.add(key)
        if other is not row and key==(root_id.get("device"),root_id.get("inode")):
            raise ValueError("candidate alias")
def evidence(report,row,artifact_id,runner_sha,allow_references=False):
    require_managed_handoff()
    if not allow_references and row.get("reference_count")!=0:
        raise ValueError("native_workspace_reference")
    pins=load_pins()
    if pins_for(pins,artifact_id): raise ValueError("consumer_pin")
    check_aliases(report,row)
    full=verify_tree(row)
    live=liveness(row["path"])
    if live["open_files"]["open_count"]: raise ValueError("open_file_reference")
    require_managed_handoff()
    return {"row":row,"pins_sha256":sha(canonical(pins)),"liveness":live,
            "full":full,"report_sha256":sha(canonical(report)),
            "runner_sha256":runner_sha}
def adoption_record(artifact_id,proof,runner_sha):
    return {"schema":"fmix-artifact-adoption.v2","artifact_id":artifact_id,
        "uid_scope":uid,"coverage":"fmix-native-artifacts.v2+uid-only-open-files",
        "adopted_at":now.isoformat(),"runner_sha256":runner_sha,
        "report_sha256":proof["report_sha256"],
        "manifest_sha256":proof["full"]["manifest_sha256"],
        "metadata_sha256":proof["full"]["metadata_sha256"],
        "identity_sha256":proof["full"]["identity_sha256"],
        "pins_sha256":proof["pins_sha256"],
        "process_sha256":proof["liveness"]["process"]["sha256"],
        "openfile_sha256":proof["liveness"]["open_files"]["sha256"]}
def load_adoption(artifact_id,proof,runner_sha):
    rel=adoption_path(artifact_id,proof["full"]["identity_sha256"],runner_sha)
    try: doc,raw,_=read_json(rel)
    except FileNotFoundError: return None
    required={"schema","artifact_id","uid_scope","coverage","adopted_at","runner_sha256",
              "report_sha256","manifest_sha256","metadata_sha256","identity_sha256",
              "pins_sha256","process_sha256","openfile_sha256"}
    if not isinstance(doc,dict) or set(doc)!=required or doc["schema"]!="fmix-artifact-adoption.v2":
        raise ValueError("unknown_adoption_schema")
    if doc["artifact_id"]!=artifact_id or doc["uid_scope"]!=uid or doc["coverage"]!="fmix-native-artifacts.v2+uid-only-open-files":
        raise ValueError("adoption_identity_mismatch")
    for key,value in (("runner_sha256",runner_sha),("manifest_sha256",proof["full"]["manifest_sha256"]),
                     ("metadata_sha256",proof["full"]["metadata_sha256"]),
                     ("identity_sha256",proof["full"]["identity_sha256"]),
                     ("pins_sha256",proof["pins_sha256"])):
        if doc[key]!=value: raise ValueError("stale_adoption")
    datetime.datetime.fromisoformat(doc["adopted_at"].replace("Z","+00:00"))
    return doc
def store_adoption(artifact_id,proof,runner_sha):
    if not pool_v2(parse_artifact_id(artifact_id)[0]): raise ValueError("legacy_generation_unenrolled")
    require_managed_handoff()
    doc=adoption_record(artifact_id,proof,runner_sha)
    require_managed_handoff()
    write_json(adoption_path(artifact_id,doc["identity_sha256"],runner_sha),doc)
    return doc
def access_baseline(row,pool,lane,key,proof):
    meta,built=read_meta(row)
    access=last_access(row,pool,lane,key,built)
    adoption=load_adoption(artifact_id_for(row),proof,proof["runner_sha256"])
    adopted=datetime.datetime.fromisoformat(adoption["adopted_at"].replace("Z","+00:00")) if adoption else now
    return max(built,access,adopted),adoption
def ttl_hours(pool):
    return int(dep_ttl if pool_kind(pool) in ("dependency","app") else template_ttl)
def make_owned_directories_writable(base_rel,snapshot):
    changes=[]
    for rel in sorted([""]+snapshot["directories"],key=lambda value:value.count("/")):
        target=base_rel+("/"+rel if rel else "")
        fd=open_dir(target)
        try:
            st=os.fstat(fd); expected=snapshot["nodes"].get(rel)
            if expected is None or st.st_uid!=uid or st.st_dev!=home_st.st_dev:
                raise ValueError("directory ownership changed")
            if (st.st_ino!=expected["inode"] or stat.S_IFMT(st.st_mode)!=stat.S_IFMT(expected["mode"])
                    or st.st_mtime_ns!=expected["mtime_ns"] or st.st_size!=expected["size"]):
                raise ValueError("directory identity changed")
            no_markers(target,st)
            baseline=stat.S_IMODE(expected["mode"]); old=stat.S_IMODE(st.st_mode)
            new=baseline|stat.S_IWUSR
            if old not in (baseline,new): raise ValueError("directory permissions changed")
            if old!=new: os.fchmod(fd,new)
            after=os.fstat(fd)
            if after.st_ino!=st.st_ino or after.st_uid!=uid or stat.S_IMODE(after.st_mode)!=new:
                raise ValueError("owner-write restoration mismatch")
            changes.append({"path":rel,"from":old,"to":new})
        finally: os.close(fd)
    return changes
def remove_verified_tree(base_rel,snapshot,delete=True):
    parent,name=parent_and_name(base_rel)
    root=os.open(name,dir_flags,dir_fd=parent)
    try:
        rootst=os.fstat(root); expected=snapshot["nodes"][""]
        if rootst.st_dev!=expected["device"] or rootst.st_ino!=expected["inode"] or rootst.st_uid!=uid:
            raise ValueError("quarantine root identity changed")
        def exact_file(fd,leaf,rel,expected_stat,digest):
            filefd=os.open(leaf,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0),dir_fd=fd)
            try:
                st=os.fstat(filefd)
                if identity(st)!=expected_stat or not stat.S_ISREG(st.st_mode) or st.st_nlink!=1:
                    raise ValueError("file identity changed before unlink")
                value=hashlib.sha256()
                while True:
                    data=os.read(filefd,1024*1024)
                    if not data: break
                    retirement_bound(len(data))
                    value.update(data)
                if value.hexdigest()!=digest: raise ValueError("file content changed before unlink")
            finally: os.close(filefd)
            if identity(os.stat(leaf,dir_fd=fd,follow_symlinks=False))!=expected_stat:
                raise ValueError("file replaced before unlink")
            if delete: os.unlink(leaf,dir_fd=fd)
        def walk(fd,prefix):
            for leaf in bounded_names(fd):
                rel=prefix+"/"+leaf if prefix else leaf
                expected_stat=snapshot["nodes"].get(rel)
                if expected_stat is None: raise ValueError("unreceipted quarantine entry")
                st=os.stat(leaf,dir_fd=fd,follow_symlinks=False)
                if st.st_dev!=expected_stat["device"] or st.st_ino!=expected_stat["inode"] or st.st_uid!=uid:
                    raise ValueError("quarantine entry identity changed")
                no_markers(base_rel+"/"+rel,st)
                if stat.S_ISDIR(st.st_mode) and stat.S_ISDIR(expected_stat["mode"]):
                    if stat.S_IMODE(st.st_mode)!=expected_stat["mode"]&0o7777:
                        raise ValueError("directory mode changed")
                    child=os.open(leaf,dir_flags,dir_fd=fd)
                    try: walk(child,rel)
                    finally: os.close(child)
                    checkfd=os.open(leaf,dir_flags,dir_fd=fd)
                    try:
                        if delete and bounded_names(checkfd): raise ValueError("directory gained entries during removal")
                    finally: os.close(checkfd)
                    current=os.stat(leaf,dir_fd=fd,follow_symlinks=False)
                    if current.st_dev!=st.st_dev or current.st_ino!=st.st_ino or current.st_uid!=uid:
                        raise ValueError("directory replaced during removal")
                    if delete: os.rmdir(leaf,dir_fd=fd)
                elif stat.S_ISREG(st.st_mode):
                    if rel in snapshot["records"]:
                        expected_digest=snapshot["records"][rel][3]
                    elif rel=="meta.json": expected_digest=snapshot["metadata_sha256"]
                    elif rel=="manifest.tsv": expected_digest=snapshot["manifest_sha256"]
                    elif rel=="manifest.sha256": expected_digest=sha((snapshot["meta"]["manifest_sha256"]+"\n").encode())
                    else: raise ValueError("unreceipted file")
                    exact_file(fd,leaf,rel,expected_stat,expected_digest)
                elif stat.S_ISLNK(st.st_mode):
                    row=snapshot["records"].get(rel)
                    if not row or row[0]!="L" or os.readlink(leaf,dir_fd=fd)!=row[2]:
                        raise ValueError("symlink identity changed")
                    if identity(os.stat(leaf,dir_fd=fd,follow_symlinks=False))!=expected_stat:
                        raise ValueError("symlink replaced before unlink")
                    if delete: os.unlink(leaf,dir_fd=fd)
                else: raise ValueError("special quarantine entry")
        walk(root,"")
        if delete:
            if bounded_names(root): raise ValueError("quarantine gained entries")
            os.close(root); root=None
            current=os.stat(name,dir_fd=parent,follow_symlinks=False)
            if current.st_dev!=expected["device"] or current.st_ino!=expected["inode"] or current.st_uid!=uid:
                raise ValueError("quarantine root replaced before rmdir")
            os.rmdir(name,dir_fd=parent); os.fsync(parent)
        else:
            os.close(root); root=None
    finally:
        if root is not None: os.close(root)
        os.close(parent)
def policy_sha(execution_mode):
    # Frozen policy digest: plan/journal validation recomputes it live, so its
    # content must never change or in-flight journals lose forward-only
    # resume. The FMIX_AUTO_EXPIRE_MAX batch bound is per-pass scheduling and
    # deliberately not part of this per-artifact policy identity.
    return sha(canonical({"schema":"fmix-artifact-retirement-policy.v2",
        "dependency_ttl_hours":int(dep_ttl),"template_ttl_hours":int(template_ttl),
        "max_candidates_per_preparation":1,"max_work_seconds":45,
        "max_read_bytes":8*1024*1024*1024,"max_tree_entries":4000000,
        "execution_mode":execution_mode,"uid_scope":uid,
        "fallback":"newest-per-compatible-lane"}))
def create_plan(artifact_id,report,row,proof,runner_sha,protected,broken,unknown_template,execution_mode):
    if not pool_v2(row["pool"]): raise ValueError("legacy_generation_unenrolled")
    require_managed_handoff()
    if artifact_id in protected: raise ValueError("fallback_preserved")
    if pool_kind(row["pool"])=="template" and unknown_template: raise ValueError("fallback_lane_unknown")
    if row.get("lane") in broken: raise ValueError("fallback_lane_incomplete")
    if execution_mode not in ("manual","automatic"): raise ValueError("invalid_retirement_mode")
    adoption=load_adoption(artifact_id,proof,runner_sha)
    if adoption is None:
        adoption=store_adoption(artifact_id,proof,runner_sha)
        if execution_mode=="automatic": return None
    age=0.0
    if execution_mode=="automatic":
        baseline,_=access_baseline(row,row["pool"],row.get("lane"),row["key"],proof)
        age=(now-baseline).total_seconds()
        if age<int(ttl_hours(row["pool"]))*3600: raise ValueError("idle_ttl_not_elapsed")
    doc={"schema":"fmix-artifact-retirement-plan.v2","artifact_id":artifact_id,
         "home":home,"uid_scope":uid,"runner_sha256":runner_sha,
         "execution_mode":execution_mode,"policy_sha256":policy_sha(execution_mode),
         "report_sha256":proof["report_sha256"],"manifest_sha256":proof["full"]["manifest_sha256"],
         "metadata_sha256":proof["full"]["metadata_sha256"],
         "identity_sha256":proof["full"]["identity_sha256"],
         "pins_sha256":proof["pins_sha256"],"adoption_sha256":sha(canonical(adoption)),
         "process_sha256":proof["liveness"]["process"]["sha256"],
         "openfile_sha256":proof["liveness"]["open_files"]["sha256"],
         "created_at":now.isoformat(),"idle_hours":age/3600}
    plan_id=sha(canonical(doc)); doc["plan_id"]=plan_id
    require_managed_handoff()
    write_json(plan_path(plan_id),doc)
    return doc
def read_plan(plan_id,allow_stale=False):
    doc,raw,_=read_json(plan_path(plan_id))
    expected={"schema","artifact_id","home","uid_scope","runner_sha256","execution_mode","policy_sha256",
        "report_sha256","manifest_sha256","metadata_sha256","identity_sha256","pins_sha256",
        "adoption_sha256","process_sha256","openfile_sha256","created_at","idle_hours","plan_id"}
    if not isinstance(doc,dict) or set(doc)!=expected or doc.get("schema")!="fmix-artifact-retirement-plan.v2":
        raise ValueError("unknown_retirement_plan_schema")
    stored=dict(doc); actual=stored.pop("plan_id",None)
    if actual!=plan_id or sha(canonical(stored))!=plan_id: raise ValueError("retirement_plan_digest_mismatch")
    if (doc.get("home")!=home or type(doc.get("uid_scope")) is not int or doc.get("uid_scope")!=uid
            or doc.get("execution_mode") not in ("manual","automatic")
            or doc.get("policy_sha256")!=policy_sha(doc["execution_mode"])):
        raise ValueError("retirement_plan_context_mismatch")
    for field in ("runner_sha256","policy_sha256","report_sha256","manifest_sha256","metadata_sha256","identity_sha256","pins_sha256","adoption_sha256","process_sha256","openfile_sha256"):
        if not hexkey(doc.get(field),64): raise ValueError("retirement_plan_digest")
    created=datetime.datetime.fromisoformat(doc["created_at"].replace("Z","+00:00"))
    if created.tzinfo is None or created>now+datetime.timedelta(seconds=30): raise ValueError("retirement_plan_timestamp")
    if (now-created).total_seconds()>600 and not allow_stale: raise ValueError("retirement_plan_stale")
    return doc
def register_pin(artifact_id,consumer):
    require_managed_handoff()
    report,runner_sha=run_audit()
    row,pool,lane,key,rel=candidate_row(report,artifact_id)
    if not pool_v2(pool): raise ValueError("legacy_generation_unenrolled")
    verify_tree(row)
    require_managed_handoff()
    pins=load_pins()
    pin_id=sha((str(uid)+":"+artifact_id+":"+consumer).encode())[:32]
    doc={"schema":"fmix-artifact-pin.v2","pin_id":pin_id,"artifact_id":artifact_id,
         "consumer":consumer,"created_at":now.isoformat(),"uid":uid}
    for pin in pins:
        if pin["pin_id"]==pin_id:
            stable=("schema","pin_id","artifact_id","consumer","uid")
            if any(pin[field]!=doc[field] for field in stable):
                raise ValueError("consumer pin identity conflict")
            return {"status":"already_pinned","pin_id":pin_id,"artifact_id":artifact_id}
    write_json(pin_path(pin_id),doc)
    return {"status":"pinned","pin_id":pin_id,"artifact_id":artifact_id}
def unregister_pin(pin_id,artifact_id,consumer):
    require_managed_handoff()
    pins=load_pins()
    matches=[pin for pin in pins if pin["pin_id"]==pin_id]
    if len(matches)!=1: raise ValueError("pin_not_found_or_ambiguous")
    if matches[0]["artifact_id"]!=artifact_id: raise ValueError("pin_target_changed")
    if matches[0]["consumer"]!=consumer: raise ValueError("pin_owner_mismatch")
    require_managed_handoff()
    parent,name=parent_and_name(pin_path(pin_id))
    try:
        st=os.stat(name,dir_fd=parent,follow_symlinks=False)
        if not stat.S_ISREG(st.st_mode) or st.st_uid!=uid or st.st_nlink!=1:
            raise ValueError("unsafe pin file")
        os.unlink(name,dir_fd=parent); os.fsync(parent)
    finally: os.close(parent)
    return {"status":"unpinned","pin_id":pin_id,"artifact_id":artifact_id}
def fresh_proof(artifact_id):
    report,runner_sha=run_audit()
    row,pool,lane,key,rel=candidate_row(report,artifact_id)
    protected,broken,unknown_template=fallbacks(report)
    proof=evidence(report,row,artifact_id,runner_sha)
    if artifact_id in protected: raise ValueError("fallback_preserved")
    if pool_kind(pool)=="template" and unknown_template: raise ValueError("fallback_lane_unknown")
    if lane in broken: raise ValueError("fallback_lane_incomplete")
    candidate_holds(report,row)
    return report,runner_sha,row,pool,lane,key,rel,proof,protected
def snapshots_match(before,after,phase="rename"):
    if (before["manifest_sha256"]!=after["manifest_sha256"]
            or before["metadata_sha256"]!=after["metadata_sha256"]
            or before["records"]!=after["records"]
            or set(before["nodes"])!=set(after["nodes"])):
        raise ValueError("quarantine manifest changed")
    directories=set(before["directories"])|{""}
    for path,old in before["nodes"].items():
        new=after["nodes"][path]
        stable=("device","inode","uid","size","mtime_ns","nlink","flags")
        if any(old.get(key)!=new.get(key) for key in stable):
            raise ValueError("quarantine identity changed")
        if path in directories and phase=="permissions":
            if new["mode"] not in (old["mode"],old["mode"]|stat.S_IWUSR):
                raise ValueError("unexpected directory mode change")
        elif old["mode"]!=new["mode"]:
            raise ValueError("unexpected payload mode change")
        if path not in directories and old.get("ctime_ns")!=new.get("ctime_ns"):
            raise ValueError("unexpected file metadata change")
def late_references(report,pool,lane,key):
    field=("template_key" if pool_kind(pool)=="template"
           else "fingerprint" if pool_kind(pool)=="app" else "dependency_fingerprint")
    for observation in report.get("observations",[]):
        refs=observation.get("references",{})
        if refs.get(field)==key: raise ValueError("late_native_workspace_reference")
def exists_rel(rel):
    parent,name=parent_and_name(rel)
    try:
        try: os.stat(name,dir_fd=parent,follow_symlinks=False); return True
        except FileNotFoundError: return False
    finally: os.close(parent)
def validate_journal(doc,plan_id):
    base={"schema","plan_id","artifact_id","home","uid_scope","state","source_rel",
          "quarantine_rel","runner_sha256","report_sha256","plan_sha256",
          "original_identity_sha256","original_manifest_sha256",
          "original_metadata_sha256","snapshot","created_at"}
    tails={"intent":set(),"quarantined":{"quarantined_at"},
           "permissions_pending":{"quarantined_at","permission_started_at"},
           "deleting":{"quarantined_at","permission_started_at","permission_changes","delete_started_at"},
           "complete":{"quarantined_at","permission_started_at","permission_changes","delete_started_at","completed_at"},
           "restored_hold":{"hold_reason","restored_at"}}
    if not isinstance(doc,dict) or doc.get("schema")!="fmix-artifact-retirement-journal.v2":
        raise ValueError("unknown_retirement_journal_schema")
    state=doc.get("state")
    expected=base|tails.get(state,set())
    if state=="restored_hold" and "quarantined_at" in doc: expected.add("quarantined_at")
    if state not in tails or set(doc)!=expected: raise ValueError("unknown_retirement_journal_fields")
    if doc.get("plan_id")!=plan_id or not re.fullmatch(r"[0-9a-f]{64}",plan_id):
        raise ValueError("retirement_journal_identity")
    pool,lane,key=parse_artifact_id(doc["artifact_id"])
    source_rel=cache_rel(pool,lane,key)
    quarantine_rel=source_rel.rsplit("/",1)[0]+"/.fmix-retire-"+plan_id
    if doc["source_rel"]!=source_rel or doc["quarantine_rel"]!=quarantine_rel:
        raise ValueError("retirement_journal_paths")
    if type(doc.get("uid_scope")) is not int or doc["uid_scope"]!=uid or doc.get("home")!=home or doc.get("plan_sha256")!=plan_id:
        raise ValueError("retirement_journal_context")
    for field in ("runner_sha256","report_sha256","original_identity_sha256","original_manifest_sha256","original_metadata_sha256"):
        if not hexkey(doc.get(field),64): raise ValueError("retirement_journal_digest")
    for field,value in doc.items():
        if field.endswith("_at"):
            timestamp=datetime.datetime.fromisoformat(value.replace("Z","+00:00"))
            if timestamp.tzinfo is None: raise ValueError("retirement_journal_timestamp")
    snapshot=doc.get("snapshot")
    fields={"nodes","manifest_sha256","metadata_sha256","directories","meta","records","identity_sha256"}
    if (not isinstance(snapshot,dict) or set(snapshot)!=fields or not isinstance(snapshot["nodes"],dict)
            or not isinstance(snapshot["directories"],list) or sha(canonical(snapshot["nodes"]))!=snapshot["identity_sha256"]):
        raise ValueError("retirement_journal_snapshot")
    if state in ("deleting","complete"):
        allowed=set([""]+snapshot["directories"]); changed=set()
        for item in doc["permission_changes"]:
            if not isinstance(item,dict) or set(item)!={"path","from","to"}: raise ValueError("retirement_journal_permissions")
            path=item["path"]
            if path not in allowed or path in changed or type(item["from"]) is not int or type(item["to"]) is not int:
                raise ValueError("retirement_journal_permissions")
            original=snapshot["nodes"].get(path)
            if not isinstance(original,dict) or item["from"]!=original["mode"]&0o7777 or item["to"]!=item["from"]|stat.S_IWUSR:
                raise ValueError("retirement_journal_permissions")
            changed.add(path)
        if changed!=allowed: raise ValueError("retirement_journal_permissions")
    return doc
def load_journal(plan_id):
    doc,raw,_=read_json(journal_path(plan_id))
    return validate_journal(doc,plan_id)
def validate_journal_plan(journal):
    plan=read_plan(journal["plan_id"],allow_stale=True)
    snapshot=journal["snapshot"]
    if (plan["artifact_id"]!=journal["artifact_id"] or plan["runner_sha256"]!=journal["runner_sha256"]
            or plan["report_sha256"]!=journal["report_sha256"]
            or plan["identity_sha256"]!=journal["original_identity_sha256"]
            or plan["manifest_sha256"]!=journal["original_manifest_sha256"]
            or plan["metadata_sha256"]!=journal["original_metadata_sha256"]
            or snapshot["identity_sha256"]!=journal["original_identity_sha256"]
            or snapshot["manifest_sha256"]!=journal["original_manifest_sha256"]
            or snapshot["metadata_sha256"]!=journal["original_metadata_sha256"]):
        raise ValueError("retirement_journal_plan_mismatch")
    return plan
def update_journal(doc):
    write_json(journal_path(doc["plan_id"]),doc,replace=True)
def report_clear(report,row):
    holds=known_global_holds(report)
    if pool_v2(row["pool"]):
        holds-={"external_consumers_unknown","consumer_coverage_unproven",
                "fallback_preservation_unproven","liveness_unproven"}
    if holds: raise ValueError("incomplete_observation:"+",".join(sorted(holds)))
def persist_absence(journal,permission_changes):
    plan_id=journal["plan_id"]
    source_absent=not exists_rel(journal["source_rel"])
    quarantine_absent=not exists_rel(journal["quarantine_rel"])
    if not source_absent or not quarantine_absent: raise ValueError("absence_not_verified")
    receipt={"schema":"fmix-artifact-absence.v2","plan_id":plan_id,
        "artifact_id":journal["artifact_id"],"home":home,"uid_scope":uid,
        "source_rel":journal["source_rel"],"quarantine_rel":journal["quarantine_rel"],
        "source_absent":True,"quarantine_absent":True,
        "manifest_sha256":journal["original_manifest_sha256"],
        "identity_sha256":journal["original_identity_sha256"],
        "runner_sha256":journal["runner_sha256"],
        "report_sha256":journal["report_sha256"],
        "permission_changes_count":len(permission_changes),
        "permission_changes_sha256":sha(canonical(permission_changes)),
        "removed_at":now.isoformat()}
    receipt_rel=receipt_path(plan_id)
    try: previous,_,_=read_json(receipt_rel)
    except FileNotFoundError: write_json(receipt_rel,receipt)
    else:
        if set(previous)!=set(receipt) or any(previous[key]!=value for key,value in receipt.items() if key!="removed_at"):
            raise ValueError("absence_receipt_conflict")
        receipt=previous
    journal["state"]="complete"
    journal["completed_at"]=now.isoformat()
    update_journal(journal)
    return {"status":"retired","plan_id":plan_id,"artifact_id":journal["artifact_id"],
            "absence_receipt":receipt_path(plan_id)}
def row_from_journal(journal,base_rel):
    pool,lane,key=parse_artifact_id(journal["artifact_id"])
    parent,name=parent_and_name(base_rel)
    try: rootst=os.stat(name,dir_fd=parent,follow_symlinks=False)
    finally: os.close(parent)
    root_identity=identity(rootst)
    audit_fields=("device","inode","uid","mode","mtime_ns","ctime_ns")
    return {"pool":pool,"lane":lane,"key":key,"path":home+"/"+journal["source_rel"],
            "metadata_sha256":journal["original_metadata_sha256"],
            "identity":{field:root_identity[field] for field in audit_fields}}
def restore_quarantine(journal,reason):
    source=journal["source_rel"]; quarantine=journal["quarantine_rel"]
    if exists_rel(source) or not exists_rel(quarantine): raise ValueError("restore_path_ambiguous")
    row=row_from_journal(journal,quarantine)
    snapshot=verify_tree(row,quarantine)
    snapshots_match(journal["snapshot"],snapshot,"rename")
    src_parent,src_name=parent_and_name(source)
    dst_parent,dst_name=parent_and_name(quarantine)
    try:
        if src_name and exists_rel(source): raise ValueError("restore_target_appeared")
        rename_noreplace(dst_parent,dst_name,src_parent,src_name)
        os.fsync(dst_parent); os.fsync(src_parent)
    finally: os.close(src_parent); os.close(dst_parent)
    journal["state"]="restored_hold"; journal["hold_reason"]=reason
    journal["restored_at"]=now.isoformat()
    update_journal(journal)
    return {"status":"held","reason":reason,"restored":True,"plan_id":journal["plan_id"]}
def journal_for_plan(plan,row,proof):
    plan_id=plan["plan_id"]
    return {"schema":"fmix-artifact-retirement-journal.v2","plan_id":plan_id,
        "artifact_id":plan["artifact_id"],"home":home,"uid_scope":uid,"state":"intent",
        "source_rel":cache_rel(row["pool"],row.get("lane"),row["key"]),
        "quarantine_rel":cache_rel(row["pool"],row.get("lane"),row["key"]).rsplit("/",1)[0]+"/.fmix-retire-"+plan_id,
        "runner_sha256":proof["runner_sha256"],"report_sha256":plan["report_sha256"],
        "plan_sha256":plan_id,"original_identity_sha256":proof["full"]["identity_sha256"],
        "original_manifest_sha256":proof["full"]["manifest_sha256"],
        "original_metadata_sha256":proof["full"]["metadata_sha256"],
        "snapshot":proof["full"],"created_at":now.isoformat()}
def deleting_snapshot(journal):
    original=journal["snapshot"]
    expected=set([""]+original["directories"])
    snapshot=json.loads(canonical(original))
    seen=set()
    for item in journal["permission_changes"]:
        path=item["path"]
        if path not in expected or path in seen: raise ValueError("retirement_permission_receipt")
        mode=snapshot["nodes"][path]["mode"]
        snapshot["nodes"][path]["mode"]=(mode&~0o7777)|item["to"]
        seen.add(path)
    if seen!=expected: raise ValueError("retirement_permission_receipt")
    snapshot["identity_sha256"]=sha(canonical(snapshot["nodes"]))
    return snapshot
def finish_journal(journal):
    state=journal.get("state"); source=journal["source_rel"]; quarantine=journal["quarantine_rel"]
    source_exists=exists_rel(source); quarantine_exists=exists_rel(quarantine)
    if state in ("complete","restored_hold"):
        return {"status":"held" if state=="restored_hold" else "already_retired",
                "reason":journal.get("hold_reason",""),"plan_id":journal["plan_id"]}
    validate_journal_plan(journal)
    if state=="intent" and source_exists and not quarantine_exists:
        return execute_plan_locked(journal["plan_id"])
    if source_exists and not quarantine_exists:
        return {"status":"held","reason":"quarantine_not_started","plan_id":journal["plan_id"]}
    if source_exists or not quarantine_exists:
        if state=="deleting" and not source_exists and not quarantine_exists:
            return persist_absence(journal,journal.get("permission_changes",[]))
        raise ValueError("quarantine_path_ambiguous")
    committed=state in ("permissions_pending","deleting")
    row=row_from_journal(journal,quarantine)
    if state=="deleting":
        current_snapshot=deleting_snapshot(journal)
        remove_verified_tree(quarantine,current_snapshot,delete=False)
    else:
        current_snapshot=verify_tree(row,quarantine,allow_owner_write=committed)
        snapshots_match(journal["snapshot"],current_snapshot,"permissions" if committed else "rename")
    try:
        report,runner_sha=run_audit()
        require_managed_handoff()
        report_clear(report,row)
        retirement_fallback_recheck(report,journal)
        if pins_for(load_pins(),journal["artifact_id"]): raise ValueError("consumer_pin")
        late_references(report,row["pool"],row.get("lane"),row["key"])
        live=liveness(home+"/"+quarantine)
    except Exception as exc:
        reason=str(exc)
        if not committed: return restore_quarantine(journal,reason)
        raise
    if state=="deleting":
        remove_verified_tree(quarantine,current_snapshot,delete=True)
        return persist_absence(journal,journal.get("permission_changes",[]))
    if state not in ("intent","quarantined","permissions_pending"):
        raise ValueError("unknown_retirement_state")
    if not committed:
        try:
            liveness(home+"/"+quarantine)
        except Exception as exc:
            return restore_quarantine(journal,str(exc))
        journal["state"]="permissions_pending"
        journal["permission_started_at"]=now.isoformat()
        update_journal(journal)
    changes=make_owned_directories_writable(quarantine,journal["snapshot"])
    after_row=row_from_journal(journal,quarantine)
    after_snapshot=verify_tree(after_row,quarantine,allow_owner_write=True)
    snapshots_match(journal["snapshot"],after_snapshot,"permissions")
    require_managed_handoff()
    fresh_report,_=run_audit()
    report_clear(fresh_report,after_row)
    retirement_fallback_recheck(fresh_report,journal)
    late_references(fresh_report,after_row["pool"],after_row.get("lane"),after_row["key"])
    if pins_for(load_pins(),journal["artifact_id"]): raise ValueError("consumer_pin")
    if liveness(home+"/"+quarantine)["open_files"]["open_count"]:
        raise ValueError("open_file_reference")
    permission_changes=[]
    for path in [""]+journal["snapshot"]["directories"]:
        old=journal["snapshot"]["nodes"][path]["mode"]&0o7777
        new=after_snapshot["nodes"][path]["mode"]&0o7777
        if old!=new: permission_changes.append({"path":path,"from":old,"to":new})
    journal["state"]="deleting"
    journal["permission_changes"]=permission_changes
    journal["delete_started_at"]=now.isoformat()
    update_journal(journal)
    remove_verified_tree(quarantine,after_snapshot,delete=False)
    remove_verified_tree(quarantine,after_snapshot,delete=True)
    return persist_absence(journal,permission_changes)
def execute_plan_locked(plan_id):
    existing=None
    try: existing=load_journal(plan_id)
    except FileNotFoundError: pass
    resume_intent=(existing is not None and existing["state"]=="intent"
        and exists_rel(existing["source_rel"]) and not exists_rel(existing["quarantine_rel"]))
    if existing is not None and not resume_intent:
        raise ValueError("retirement_journal_already_started")
    plan=read_plan(plan_id,allow_stale=resume_intent)
    artifact_id=plan["artifact_id"]
    report,runner_sha,row,pool,lane,key,source_rel,proof,protected=fresh_proof(artifact_id)
    if runner_sha!=plan["runner_sha256"] or proof["full"]["manifest_sha256"]!=plan["manifest_sha256"]:
        raise ValueError("retirement_plan_manifest_changed")
    if (proof["full"]["metadata_sha256"]!=plan["metadata_sha256"]
            or proof["full"]["identity_sha256"]!=plan["identity_sha256"]
            or proof["pins_sha256"]!=plan["pins_sha256"]):
        raise ValueError("retirement_plan_evidence_changed")
    adoption=load_adoption(artifact_id,proof,runner_sha)
    if adoption is None or sha(canonical(adoption))!=plan["adoption_sha256"]:
        raise ValueError("retirement_adoption_changed")
    protected,broken,unknown_template=fallbacks(report)
    if artifact_id in protected or (pool=="template" and unknown_template) or lane in broken:
        raise ValueError("fallback_preserved_or_unknown")
    if plan["execution_mode"]=="automatic":
        baseline,_=access_baseline(row,pool,lane,key,proof)
        if (now-baseline).total_seconds()<ttl_hours(pool)*3600:
            raise ValueError("idle_ttl_not_elapsed")
    journal=existing or journal_for_plan(plan,row,proof)
    if len(canonical(journal))>16*1024*1024: raise ValueError("retirement_journal_budget")
    if existing is not None:
        if (journal["artifact_id"]!=artifact_id or journal["runner_sha256"]!=runner_sha
                or journal["original_identity_sha256"]!=proof["full"]["identity_sha256"]
                or journal["original_manifest_sha256"]!=proof["full"]["manifest_sha256"]
                or journal["original_metadata_sha256"]!=proof["full"]["metadata_sha256"]):
            raise ValueError("retirement_intent_evidence_changed")
        snapshots_match(journal["snapshot"],proof["full"],"rename")
    ensure_retirement_dirs()
    if existing is None: write_json(journal_path(plan_id),journal)
    source=journal["source_rel"]; quarantine=journal["quarantine_rel"]
    require_managed_handoff()
    if exists_rel(quarantine): raise ValueError("quarantine_destination_exists")
    source_parent,source_name=parent_and_name(source)
    quarantine_parent,quarantine_name=parent_and_name(quarantine)
    try:
        source_st=os.stat(source_name,dir_fd=source_parent,follow_symlinks=False)
        parent_st=os.fstat(quarantine_parent)
        if source_st.st_dev!=home_st.st_dev or parent_st.st_dev!=source_st.st_dev:
            raise ValueError("quarantine_not_same_filesystem")
        if source_st.st_ino!=proof["full"]["nodes"][""]["inode"] or source_st.st_uid!=uid:
            raise ValueError("candidate_identity_changed_before_quarantine")
        rename_noreplace(source_parent,source_name,quarantine_parent,quarantine_name)
        os.fsync(source_parent); os.fsync(quarantine_parent)
    finally:
        os.close(source_parent); os.close(quarantine_parent)
    if exists_rel(source): raise ValueError("source_path_reappeared_after_quarantine")
    journal["state"]="quarantined"
    journal["quarantined_at"]=now.isoformat()
    row_after=row_from_journal(journal,quarantine)
    moved=verify_tree(row_after,quarantine)
    snapshots_match(proof["full"],moved,"rename")
    update_journal(journal)
    return finish_journal(journal)
def release_lease(proc):
    try:
        proc.stdin.write("release\n")
        proc.stdin.flush()
        proc.stdin.close()
        proc.wait(timeout=15)
    except (BrokenPipeError,OSError,subprocess.TimeoutExpired) as exc:
        raise ValueError("artifact_lease_release_unconfirmed") from exc
    output=proc.stdout.read()
    error=proc.stderr.read()
    proc.stdout.close()
    proc.stderr.close()
    if proc.returncode!=0 or output!="RELEASED 0\n" or error:
        raise ValueError("artifact_lease_release_failed")
def run_locked_candidate(artifact_id,operation):
    pool,lane,key=parse_artifact_id(artifact_id)
    lease=acquire_lease(pool,lane,key)
    result=None
    operation_error=None
    try: result=operation()
    except BaseException as exc: operation_error=exc
    release_error=None
    try: release_lease(lease)
    except Exception as exc: release_error=exc
    if release_error is not None:
        reason="artifact_lease_release_failed"
        if operation_error is not None: reason+=";operation_failed:"+str(operation_error)
        raise ValueError(reason)
    if operation_error is not None: raise operation_error
    return result
def run_locked(artifact_id,operation):
    global_lease=acquire_named_lease("artifact-retirement-v2")
    operation_error=None; result=None
    try: result=run_locked_candidate(artifact_id,operation)
    except BaseException as exc: operation_error=exc
    release_error=None
    try: release_lease(global_lease)
    except Exception as exc: release_error=exc
    if release_error is not None: raise ValueError("artifact_lease_release_failed") from release_error
    if operation_error is not None: raise operation_error
    return result
def adopt_or_plan(artifact_id,make_plan):
    report,runner_sha,row,pool,lane,key,rel,proof,protected=fresh_proof(artifact_id)
    if not make_plan:
        adoption=load_adoption(artifact_id,proof,runner_sha)
        if adoption: return {"status":"already_adopted","artifact_id":artifact_id}
        doc=store_adoption(artifact_id,proof,runner_sha)
        return {"status":"adopted","artifact_id":artifact_id,
                "adoption_sha256":sha(canonical(doc)),"uid_scope":uid}
    plan=create_plan(artifact_id,report,row,proof,runner_sha,protected,*fallbacks(report)[1:],"manual")
    if plan is None: raise ValueError("manual_plan_unexpectedly_deferred")
    return {"status":"planned","plan_id":plan["plan_id"],"artifact_id":artifact_id,
            "execution_mode":plan["execution_mode"],"idle_hours":plan["idle_hours"]}
def pin_operation():
    report,runner_sha=run_audit()
    row,pool,lane,key,rel=candidate_row(report,artifact_id)
    verify_tree(row)
    return register_pin(artifact_id,consumer)
def unpin_operation():
    require_managed_handoff()
    pins=load_pins()
    matches=[pin for pin in pins if pin["pin_id"]==object_id]
    if len(matches)!=1: raise ValueError("pin_not_found_or_ambiguous")
    artifact_id=matches[0]["artifact_id"]
    return run_locked(artifact_id,lambda:unregister_pin(object_id,artifact_id,consumer))
def mode_operation():
    ensure_retirement_dirs()
    if mode=="auto-expire": return auto_expire_one()
    if mode=="pin": return run_locked(artifact_id,pin_operation)
    if mode=="unpin": return unpin_operation()
    if mode=="adopt":
        return run_locked(artifact_id,lambda:adopt_or_plan(artifact_id,False))
    if mode=="plan":
        return run_locked(artifact_id,lambda:adopt_or_plan(artifact_id,True))
    if mode=="retire-plan":
        plan=read_plan(object_id)
        return run_locked(plan["artifact_id"],lambda:execute_plan_locked(object_id))
    if mode=="resume":
        journal=load_journal(object_id)
        return run_locked(journal["artifact_id"],lambda:finish_journal(load_journal(object_id)))
    raise ValueError("unsupported_retirement_mode")
def auto_expire_summary(results,error=None):
    # One JSON result per pass. A single completed operation keeps its exact
    # historical shape (its keys surface at the top level) so consumers read
    # it unchanged; multi-operation passes carry a results list and an
    # aggregate status.
    if not results:
        if error is not None: return {"status":"skipped","reason":str(error)}
        return {"status":"skipped","reason":"no_unreferenced_nonfallback_candidate"}
    if error is not None:
        return {"status":"skipped","reason":str(error),"results":results}
    statuses={item.get("status") for item in results}
    if statuses<={"retired","already_retired"}: status="retired"
    elif "held" in statuses: status="held"
    else: status="adopted_waiting_ttl"
    summary={"status":status,"results":results}
    if len(results)==1:
        summary.update({key:value for key,value in results[0].items()
                        if key not in ("schema","results")})
    return summary
def auto_expire_one():
    # Batched auto-expire: one preparation pass runs at most
    # FMIX_AUTO_EXPIRE_MAX retirement operations (default 3, bounded 1-10) —
    # pending journals first (forward-only resume, never restarted), then the
    # oldest fresh candidates; legacy/global uncertainty stays held. The
    # per-artifact lease is held only for each artifact's destructive
    # rename->graveyard + rmtree phase, never across the batch or the shared
    # audit. Any failing step halts the pass fail-closed; completed work stays
    # journaled and resumes forward-only on a later pass.
    require_managed_handoff()
    results=[]
    try:
        budget=auto_expire_max
        journals=list_names(RETIRE_ROOT+"/journals")
        for name in journals:
            if budget<=0: break
            match=re.fullmatch(r"([0-9a-f]{64})\.json",name)
            if not match: raise ValueError("unknown_retirement_journal_layout")
            journal=load_journal(match.group(1))
            if journal.get("state") in ("intent","quarantined","permissions_pending","deleting"):
                results.append(run_locked(journal["artifact_id"],
                    lambda:finish_journal(load_journal(match.group(1)))))
                budget-=1
        if budget>0:
            report,runner_sha=run_audit()
            protected,broken,unknown_template=fallbacks(report)
            candidates=[]
            for row in report.get("entries",[]):
                if row.get("reference_count") or row.get("references_truncated"): continue
                artifact_id=artifact_id_for(row)
                if not pool_v2(row["pool"]): continue
                try: candidate_holds(report,row)
                except Exception: continue
                if artifact_id in protected or (pool_kind(row["pool"])=="template" and unknown_template) or row.get("lane") in broken: continue
                try:
                    meta,built=read_meta(row)
                    access=last_access(row,row["pool"],row.get("lane"),row["key"],built)
                except Exception: continue
                candidates.append((access,artifact_id))
            for access,artifact_id in sorted(candidates):
                if budget<=0: break
                results.append(run_locked(artifact_id,lambda:auto_candidate_locked(artifact_id)))
                budget-=1
    except Exception as exc:
        return auto_expire_summary(results,exc)
    return auto_expire_summary(results)
def auto_candidate_locked(artifact_id):
    report,runner_sha,row,pool,lane,key,rel,proof,protected=fresh_proof(artifact_id)
    try:
        plan=create_plan(artifact_id,report,row,proof,runner_sha,protected,*fallbacks(report)[1:],"automatic")
    except ValueError as exc:
        # A candidate that has not yet aged past its idle TTL is an expected
        # per-artifact deferral (same waiting status a first sighting gets),
        # not a step failure: the batch keeps moving. Every other failure
        # stays fail-closed and halts the pass.
        if str(exc)!="idle_ttl_not_elapsed": raise
        return {"status":"adopted_waiting_ttl","artifact_id":artifact_id}
    if plan is None: return {"status":"adopted_waiting_ttl","artifact_id":artifact_id}
    return execute_plan_locked(plan["plan_id"])
try:
    ensure_retirement_dirs()
    result=mode_operation()
    if not isinstance(result,dict): fail("invalid_retirement_result")
    result.setdefault("schema","fmix-artifact-retirement.v2")
    result.setdefault("uid_scope",uid)
    print(json.dumps(result,sort_keys=True))
except SystemExit:
    raise
except Exception as exc:
    fail(str(exc),1)
finally:
    os.close(rootfd)
PY
}

cmd_gc_artifact_audit() {
    local arg py_bin dependency_ttl template_ttl runner
    for arg in "$@"; do
        case "$arg" in
            --artifacts-only|--json) ;;
            --help|-h)
                printf '%s\n' 'fmix gc --artifacts-only [--json]: read-only inventory; mutation unsupported'
                return 0 ;;
            *)
                printf '%s\n' '{"error":"unsupported_artifact_audit_option","mutation_supported":false}'
                return 2 ;;
        esac
    done
    dependency_ttl="$(fmix_effective_artifact_ttl_hours dependency)" || return 2
    template_ttl="$(fmix_effective_artifact_ttl_hours template)" || return 2
    py_bin="$(fmix_python_bin)" || return 1
    runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || return 1
    "$py_bin" -I -B - "$FMIX_HOME" "$runner" "$dependency_ttl" "$template_ttl" <<'PY'
import contextlib, datetime, hashlib, json, math, os, re, shutil, stat, sys, time

home = os.path.abspath(sys.argv[1])
sha = lambda b: hashlib.sha256(b).hexdigest()
hexkey = lambda v, n: isinstance(v, str) and re.fullmatch("[0-9a-f]{%d}" % n, v)
holds = {"external_consumers_unknown", "liveness_unproven",
         "consumer_coverage_unproven", "fallback_preservation_unproven"}
for tool in ("lsof", "ps"):
    if shutil.which(tool) is None:
        holds.add("missing_" + tool)
entries, observations = [], []
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
rootfd = None
deadline = time.monotonic() + 10
budgets = dict(entries=25000, metadata_bytes=64 * 1024 * 1024, manifest_rows=250000)

def bounded(kind=None, count=0):
    if time.monotonic() > deadline:
        holds.add("audit_deadline_reached")
        raise ValueError("audit deadline reached")
    if kind:
        budgets[kind] -= count
        if budgets[kind] < 0:
            holds.add("audit_budget_reached:" + kind)
            raise ValueError("audit budget reached")

def identity(s):
    return dict(device=s.st_dev, inode=s.st_ino, uid=s.st_uid,
                mode=s.st_mode, mtime_ns=s.st_mtime_ns, ctime_ns=s.st_ctime_ns)

@contextlib.contextmanager
def directory(rel=""):
    fd = os.dup(rootfd)
    try:
        for part in rel.split("/") if rel else ():
            if part in ("", ".", ".."):
                raise ValueError("unsafe component")
            child = os.open(part, flags, dir_fd=fd)
            os.close(fd)
            fd = child
            if os.fstat(fd).st_uid != os.getuid():
                raise ValueError("foreign directory")
        yield fd
    finally:
        os.close(fd)

def children(rel):
    with directory(rel) as fd:
        names = []
        with os.scandir(fd) as iterator:
            for entry in iterator:
                bounded("entries", 1)
                names.append(entry.name)
        return sorted(names)

def info(rel, allow_link=False):
    bounded()
    parent, name = os.path.split(rel)
    with directory(parent) as fd:
        s = os.stat(name, dir_fd=fd, follow_symlinks=False)
    if s.st_uid != os.getuid() or (stat.S_ISLNK(s.st_mode) and not allow_link):
        raise ValueError("foreign or symlink")
    return s

def read(rel, limit=1024 * 1024):
    parent, name = os.path.split(rel)
    with directory(parent) as parentfd:
        fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
                     dir_fd=parentfd)
    try:
        before = os.fstat(fd)
        if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid()
                or before.st_nlink != 1 or before.st_size > limit):
            raise ValueError("unsafe metadata")
        chunks, size = [], 0
        while True:
            bounded()
            chunk = os.read(fd, min(65536, limit + 1 - size))
            if not chunk:
                break
            chunks.append(chunk)
            size += len(chunk)
            bounded("metadata_bytes", len(chunk))
            if size > limit:
                raise ValueError("oversize metadata")
        if identity(before) != identity(os.fstat(fd)):
            raise ValueError("changed metadata")
        return b"".join(chunks), identity(before)
    finally:
        os.close(fd)

def strict_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate JSON key")
        result[key] = value
    return result

def decode(raw):
    try:
        return json.loads(raw, object_pairs_hook=strict_object,
                          parse_constant=lambda _: (_ for _ in ()).throw(ValueError()))
    except RecursionError:
        raise ValueError("JSON nesting limit") from None

specs = {
    "state.json": "path template_key db_name db_schema_key db_source_schema_key db_base_id last_migration_stamp last_used",
    "artifact-state.json": "schema path template_key verified_at",
    "dependency-stamp.json": "path build_root dependency_fingerprint reconciliation_guard lock_identity source_guard resolved_at",
    "compile-stamp.json": "schema_version path build_root template_key git_tree_hash compile_env_hash dirty_hash ignored_compile_hash fingerprint manifest_guard dependency_source_guard quick_guard source_stability_identity compiled_at",
    "meta.json": "schema session_id session_hash app_name source worktree deps_path build_path creation_time created_at last_accessed last_used ttl_days ttl_hours lockfile_hash status",
}

def reference(rel, kind):
    row = {"path": rel, "status": "unknown", "sha256": None}
    observations.append(row)
    try:
        raw, row["identity"] = read(rel)
        row["sha256"] = sha(raw)
        d = decode(raw)
        expected = set(specs[kind].split())
        if not isinstance(d, dict) or set(d) != expected:
            raise ValueError("unknown schema")
        numeric = {"schema_version", "ttl_days", "ttl_hours"} & expected
        if "schema_version" in d and type(d["schema_version"]) is not int:
            raise ValueError("numeric field")
        if any(type(d[k]) not in (int, float) or d[k] < 0
               or (type(d[k]) is float and not math.isfinite(d[k]))
               for k in {"ttl_days", "ttl_hours"} & expected):
            raise ValueError("TTL field")
        if any(not isinstance(d[k], str) for k in expected - numeric):
            raise ValueError("string field")
        if kind == "artifact-state.json" and d["schema"] != "fmix-artifacts-v1":
            raise ValueError("artifact schema")
        if kind == "compile-stamp.json" and d["schema_version"] != 2:
            raise ValueError("compile schema")
        if kind == "meta.json":
            if (d["schema"] != "1" or d["session_hash"] != rel.split("/")[3]
                    or d["session_id"] != d["session_hash"]
                    or min(d["ttl_days"], d["ttl_hours"]) < 0):
                raise ValueError("session identity")
        source = d.get("path", d.get("worktree", ""))
        if not os.path.isabs(source) or os.path.normpath(source) != source:
            raise ValueError("source path")
        refs = {}
        for field, width in (("template_key", 16), ("dependency_fingerprint", 64)):
            if field in d:
                if not hexkey(d[field], width):
                    raise ValueError("reference identity")
                refs[field] = d[field]
        # Compile stamps also carry the app-compile pool's exact key. Extract
        # it tolerantly so legacy/garbage stamps keep their existing holds.
        if "fingerprint" in d and hexkey(d["fingerprint"], 64):
            refs["fingerprint"] = d["fingerprint"]
        row.update(status="observed", references=refs,
                   declared_source_path_sha256=sha(source.encode()))
    except (OSError, ValueError, UnicodeError):
        holds.add("unknown_native_reference")

def census(rel, depth=0):
    try:
        names = children(rel)
        if rel == "sessions/v1" or rel.startswith("sessions/v1/"):
            if depth < 3:
                for name in names:
                    if depth == 1 and not hexkey(name, 16):
                        holds.add("unknown_session_layout")
                    else:
                        census(rel + "/" + name, depth + 1)
            else:
                for kind in specs:
                    if kind in names:
                        reference(rel + "/" + kind, kind)
                    else:
                        holds.add("incomplete_session_references")
        else:
            kind = {"worktrees": "state.json", "artifact-states": "artifact-state.json",
                    "dependency-stamps": "dependency-stamp.json",
                    "compile-stamps": "compile-stamp.json"}[rel]
            for name in names:
                if re.fullmatch("[0-9a-f]{8}\\.json", name):
                    reference(rel + "/" + name, kind)
                else:
                    holds.add("unknown_native_reference_layout")
    except (OSError, ValueError):
        holds.add("unavailable_native_reference_inventory")

def discover(rel, pool, key, lane=None):
    # Enumerate both pools before detailed manifest checks can consume the
    # deadline. A discovered row is not validated and never authorizes action.
    row = dict(path=home + "/" + rel, pool=pool, key=key, lane=lane,
               status="held", metadata_sha256=None, inspection="not_started",
               holds=["payload_verification_unproven", "cache_inspection_pending"])
    entries.append(row)
    try:
        row["identity"] = identity(info(rel))
    except (OSError, ValueError):
        row["holds"].append("unverifiable_cache")

def known_retirement_quarantine(rel,pool,lane=None):
    match=re.fullmatch(r"\.fmix-retire-([0-9a-f]{64})",rel.rsplit("/",1)[-1])
    if not pool.endswith("-v2") or not match: return False
    plan_id=match.group(1); base="artifact-retirement/v2/"
    try:
        journal=decode(read(base+"journals/"+plan_id+".json",16*1024*1024)[0])
        plan=decode(read(base+"plans/"+plan_id+".json",16*1024*1024)[0])
        if not isinstance(journal,dict) or not isinstance(plan,dict): return False
    except (OSError,ValueError,UnicodeError): return False
    state=journal.get("state"); required={"schema","plan_id","artifact_id","home","uid_scope","state","source_rel","quarantine_rel","runner_sha256","report_sha256","plan_sha256","original_identity_sha256","original_manifest_sha256","original_metadata_sha256","snapshot","created_at"}
    tails={"intent":set(),"quarantined":{"quarantined_at"},"permissions_pending":{"quarantined_at","permission_started_at"},"deleting":{"quarantined_at","permission_started_at","permission_changes","delete_started_at"}}
    if journal.get("schema")!="fmix-artifact-retirement-journal.v2" or state not in tails or set(journal)!=required|tails[state]: return False
    plan_fields={"schema","artifact_id","home","uid_scope","runner_sha256","execution_mode","policy_sha256","report_sha256","manifest_sha256","metadata_sha256","identity_sha256","pins_sha256","adoption_sha256","process_sha256","openfile_sha256","created_at","idle_hours","plan_id"}
    if set(plan)!=plan_fields or plan.get("schema")!="fmix-artifact-retirement-plan.v2": return False
    stored=dict(plan); actual=stored.pop("plan_id",None)
    if actual!=plan_id or sha(json.dumps(stored,sort_keys=True,separators=(",",":"),ensure_ascii=True).encode())!=plan_id: return False
    if plan.get("home")!=home or type(plan.get("uid_scope")) is not int or plan["uid_scope"]!=os.getuid(): return False
    snapshot=journal.get("snapshot")
    snap_fields={"nodes","manifest_sha256","metadata_sha256","directories","meta","records","identity_sha256"}
    if not isinstance(snapshot,dict) or set(snapshot)!=snap_fields or not isinstance(snapshot["nodes"],dict): return False
    if sha(json.dumps(snapshot["nodes"],sort_keys=True,separators=(",",":"),ensure_ascii=True).encode())!=snapshot.get("identity_sha256"): return False
    if (journal.get("plan_sha256")!=plan_id or journal.get("home")!=home or journal.get("uid_scope")!=os.getuid()
            or plan.get("artifact_id")!=journal.get("artifact_id") or plan.get("runner_sha256")!=journal.get("runner_sha256")
            or plan.get("report_sha256")!=journal.get("report_sha256") or plan.get("identity_sha256")!=journal.get("original_identity_sha256")
            or plan.get("manifest_sha256")!=journal.get("original_manifest_sha256") or plan.get("metadata_sha256")!=journal.get("original_metadata_sha256")
            or snapshot.get("identity_sha256")!=journal.get("original_identity_sha256")
            or snapshot.get("manifest_sha256")!=journal.get("original_manifest_sha256")
            or snapshot.get("metadata_sha256")!=journal.get("original_metadata_sha256")): return False
    aid=plan.get("artifact_id","")
    if pool=="template-v2" and re.fullmatch(r"template-v2:[0-9a-f]{16}",aid): source="artifacts/v2/templates/"+aid.split(":")[1]
    elif pool=="dependency-v2" and re.fullmatch(r"dependency-v2:[0-9a-f]{64}/[0-9a-f]{64}",aid): source="artifacts/v2/dependencies/"+aid.split(":")[1]
    elif pool=="app-compile-v2" and re.fullmatch(r"app-compile-v2:[0-9a-f]{64}/[0-9a-f]{64}",aid): source="artifacts/v2/app-compiles/"+aid.split(":")[1]
    else: return False
    parent=source.rsplit("/",1)[0]
    if journal.get("home")!=home or journal.get("uid_scope")!=os.getuid() or journal.get("artifact_id")!=aid or journal.get("source_rel")!=source or journal.get("quarantine_rel")!=rel or rel!=parent+"/.fmix-retire-"+plan_id: return False
    try:
        root=identity(info(rel))
        info(source)
        return False
    except FileNotFoundError:
        pass
    expected_root=journal["snapshot"]["nodes"].get("")
    if not isinstance(expected_root,dict) or root["inode"]!=expected_root.get("inode") or root["device"]!=expected_root.get("device"): return False
    try:
        phase="permissions" if state in ("permissions_pending","deleting") else "rename"
        return audit_quarantine_tree(rel,pool,lane,journal,phase)
    except Exception:
        return False
def audit_quarantine_tree(rel,pool,lane,journal,phase):
    snapshot=journal["snapshot"]
    row={"path":home+"/"+rel,"pool":pool,"key":journal["artifact_id"].split(":")[1].split("/")[-1],
         "lane":lane,"status":"held","metadata_sha256":None,"inspection":"not_started",
         "holds":["payload_verification_unproven","cache_inspection_pending"],"identity":identity(info(rel))}
    inventory(row,allow_owner_write=phase=="permissions")
    if (row["inspection"]!="metadata_and_manifest_shape_checked"
            or row.get("metadata_sha256")!=snapshot["metadata_sha256"]
            or row.get("manifest_sha256")!=snapshot["manifest_sha256"]): return False
    directories=snapshot.get("directories")
    if not isinstance(directories,list) or directories!=sorted(set(directories)): return False
    nodes=snapshot.get("nodes")
    if not isinstance(nodes,dict): return False
    paths={""}
    for directory in [""]+directories:
        prefix=directory+"/" if directory else ""
        base=rel+"/"+directory if directory else rel
        paths.update(prefix+name for name in children(base))
    if paths!=set(nodes): return False
    return audit_quarantine_nodes(rel,snapshot,phase)

def audit_quarantine_nodes(rel,snapshot,phase):
    fields={"device","inode","uid","mode","size","mtime_ns","ctime_ns","nlink","flags"}
    stable=("device","inode","uid","size","mtime_ns","nlink","flags")
    directories=set(snapshot["directories"])
    for path,expected in snapshot["nodes"].items():
        target=rel+("/"+path if path else "")
        st=info(target,allow_link=True)
        current=identity(st)
        current.update(size=st.st_size,nlink=st.st_nlink,flags=getattr(st,"st_flags",0))
        if not isinstance(expected,dict) or set(expected)!=fields: return False
        if any(current[key]!=expected[key] for key in stable): return False
        is_directory=path=="" or path in directories
        if is_directory and phase=="permissions":
            if current["mode"] not in (expected["mode"],expected["mode"]|stat.S_IWUSR): return False
        elif current["mode"]!=expected["mode"]: return False
        if not is_directory and current["ctime_ns"]!=expected["ctime_ns"]: return False
        if hasattr(os,"listxattr") and os.listxattr(home+"/"+target,follow_symlinks=False): return False
    return True

def inventory(row, allow_owner_write=False):
    rel = row["path"][len(home) + 1:]
    pool, key, lane = row["pool"], row["key"], row["lane"]
    row["inspection"] = "incomplete"
    try:
        before = info(rel)
        if row.get("identity") != identity(before):
            raise ValueError("changed discovered identity")
        if not stat.S_ISDIR(before.st_mode) or (before.st_mode & 0o222 and not
                (allow_owner_write and before.st_mode & 0o200 and not before.st_mode & 0o022)):
            raise ValueError("unsafe cache root")
        app = pool.startswith("app")
        dependency_pool = pool.startswith("dependency")
        expected_contents = ({"_build", "meta.json", "manifest.tsv", "manifest.sha256"}
                             if app else
                             {"deps", "_build", "meta.json", "manifest.tsv", "manifest.sha256"})
        if set(children(rel)) != expected_contents:
            raise ValueError("unexpected cache contents")
        for child in (("_build", "_build/test", "_build/test/lib") if app else
                      ("deps", "_build", "_build/test", "_build/test/lib")):
            if not stat.S_ISDIR(info(rel + "/" + child).st_mode):
                raise ValueError("missing cache directory")
        if (dependency_pool or app) and (children(rel + "/_build") != ["test"]
                                          or children(rel + "/_build/test") != ["lib"]):
            raise ValueError("unexpected build environment")
        if app and children(rel + "/_build/test/lib") != ["cdrcisco"]:
            raise ValueError("unexpected app payload")
        raw, _ = read(rel + "/meta.json")
        row["metadata_sha256"] = sha(raw)
        d = decode(raw)
        dependency = pool.startswith("dependency")
        v2 = pool.endswith("-v2")
        fields = (("schema lane compile_fingerprint producer_sha source_clean manifest_sha256 built_at producer_runner_sha256 consumer_protocol"
                   if app else
                   "schema lane dependency_fingerprint producer_sha source_clean manifest_sha256 built_at producer_runner_sha256 consumer_protocol"
                   if v2 else "schema lane dependency_fingerprint producer_sha source_clean manifest_sha256 built_at")
                  if (dependency or app) else
                  ("schema status template_key manifest_sha256 built_at toolchain source_commit producer_runner_sha256 consumer_protocol"
                   if v2 else "schema status template_key manifest_sha256 built_at toolchain source_commit"))
        if not isinstance(d, dict) or set(d) != set(fields.split()) or any(
                not isinstance(v, str) for v in d.values()):
            raise ValueError("metadata schema")
        if d["schema"] != ("2" if v2 else "1") or not hexkey(d["manifest_sha256"], 64):
            raise ValueError("metadata identity")
        if v2 and (d["consumer_protocol"] != "fmix-native-artifacts.v2"
                   or not hexkey(d["producer_runner_sha256"],64)):
            raise ValueError("consumer protocol identity")
        if v2:
            producer_runner, producer_id = read("runtime/fmix-"+d["producer_runner_sha256"], 4*1024*1024)
            if (sha(producer_runner) != d["producer_runner_sha256"] or producer_id["mode"]&0o222
                    or not producer_id["mode"]&0o111):
                raise ValueError("producer runner identity")
        if app:
            if (d["lane"] != lane or d["compile_fingerprint"] != key
                    or not hexkey(d["producer_sha"], 40)
                    or d["source_clean"] not in ("true", "false")):
                raise ValueError("app compile identity")
        elif dependency:
            if (d["lane"] != lane or d["dependency_fingerprint"] != key
                    or not hexkey(d["producer_sha"], 40)
                    or d["source_clean"] not in ("true", "false")):
                raise ValueError("dependency identity")
        else:
            if (d["status"] != "complete" or d["template_key"] != key
                    or not d["toolchain"] or not re.fullmatch("[0-9a-f]{7,40}", d["source_commit"])):
                raise ValueError("template identity")
        if datetime.datetime.fromisoformat(d["built_at"].replace("Z", "+00:00")).tzinfo is None:
            raise ValueError("timestamp timezone")
        manifest, _ = read(rel + "/manifest.tsv", 8 * 1024 * 1024)
        recorded, _ = read(rel + "/manifest.sha256")
        row["manifest_sha256"] = sha(manifest)
        if recorded != (d["manifest_sha256"] + "\n").encode() or sha(manifest) != d["manifest_sha256"]:
            raise ValueError("corrupt manifest")
        seen = set()
        for line in manifest.decode().splitlines():
            bounded("manifest_rows", 1)
            parts = line.split("\t")
            if len(parts) < 3:
                raise ValueError("manifest row")
            kind, path = parts[:2]
            if (path in seen or any(p in ("", ".", "..") for p in path.split("/"))
                    or path.split("/")[0] not in ("deps", "_build")):
                raise ValueError("manifest path")
            seen.add(path)
            s = info(rel + "/" + path, allow_link=kind == "L")
            if kind == "L" and len(parts) == 3 and stat.S_ISLNK(s.st_mode):
                parent, name = os.path.split(rel + "/" + path)
                with directory(parent) as fd:
                    target = os.readlink(name, dir_fd=fd)
                    if (target != parts[2] or os.path.isabs(target)
                            or not os.path.normpath(parent + "/" + target).startswith(rel + "/")
                            or identity(s) != identity(os.stat(name, dir_fd=fd, follow_symlinks=False))):
                        raise ValueError("unsafe manifest link")
                continue
            if not stat.S_ISLNK(s.st_mode) and s.st_mode & 0o222 and not (
                    allow_owner_write and stat.S_ISDIR(s.st_mode)
                    and s.st_mode & 0o200 and not s.st_mode & 0o022):
                raise ValueError("writable payload")
            if kind == "D" and len(parts) == 3 and parts[2] == "-" and stat.S_ISDIR(s.st_mode):
                continue
            if not (kind == "F" and len(parts) == 4 and parts[2].isdigit()
                    and hexkey(parts[3], 64) and stat.S_ISREG(s.st_mode)
                    and s.st_size == int(parts[2])):
                raise ValueError("manifest entry")
        if identity(before) != identity(info(rel)):
            raise ValueError("changed cache identity")
        row["inspection"] = "metadata_and_manifest_shape_checked"
        row["holds"].remove("cache_inspection_pending")
    except (OSError, ValueError, UnicodeError):
        row["holds"].append("unverifiable_cache")

try:
    if os.path.realpath(home) != home:
        raise ValueError("noncanonical home")
    rootfd = os.open(home, flags)
    if os.fstat(rootfd).st_uid != os.getuid():
        raise ValueError("foreign home")
    for pool, base, width in (("template", "templates", 16),
                              ("dependency", "dependency-artifacts/v1", 64),
                              ("template-v2", "artifacts/v2/templates", 16),
                              ("dependency-v2", "artifacts/v2/dependencies", 64),
                              ("app-compile-v2", "artifacts/v2/app-compiles", 64)):
        try:
            for name in children(base):
                if not hexkey(name, width):
                    rel=base+"/"+name
                    if not known_retirement_quarantine(rel,pool): holds.add("unknown_pool_entry")
                elif pool.startswith("template"):
                    discover(base + "/" + name, pool, name)
                else:
                    for key in children(base + "/" + name):
                        if hexkey(key, 64):
                            discover(base + "/" + name + "/" + key, pool, key, name)
                        else:
                            rel=base+"/"+name+"/"+key
                            if not known_retirement_quarantine(rel,pool,name): holds.add("unknown_pool_entry")
        except FileNotFoundError:
            pass
        except (OSError, ValueError):
            holds.add("unavailable_pool_inventory")
    # References may consume the entire inspection budget. Preserve both
    # bounded pool inventories before that happens; untouched rows stay held.
    for rel in ("worktrees", "artifact-states", "dependency-stamps", "compile-stamps", "sessions/v1"):
        census(rel)
    for row in entries:
        if time.monotonic() > deadline:
            holds.add("audit_deadline_reached")
            break
        inventory(row)
except (OSError, ValueError):
    holds.add("unavailable_or_unsafe_home")
finally:
    if rootfd is not None:
        os.close(rootfd)
index = {}
for observation in observations:
    for field, key in observation.get("references", {}).items():
        index.setdefault((field, key), []).append(observation["path"])
for row in entries:
    field = ("template_key" if row["pool"].startswith("template")
             else "fingerprint" if row["pool"].startswith("app")
             else "dependency_fingerprint")
    references = index.get((field, row["key"]), [])
    row["reference_count"] = len(references)
    row["references"] = references[:16]
    row["references_truncated"] = len(references) > 16
    if row["references_truncated"]:
        row["holds"].append("reference_preview_truncated")
    row["holds"] = sorted(set(row["holds"]) | holds)
source_sha256 = None
try:
    fd = os.open(sys.argv[2], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    with os.fdopen(fd, "rb") as runner:
        before = os.fstat(runner.fileno())
        if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid()
                or before.st_size > 4 * 1024 * 1024):
            raise ValueError("unsafe runner identity")
        source_sha256 = sha(runner.read(4 * 1024 * 1024 + 1))
        if identity(before) != identity(os.fstat(runner.fileno())):
            raise ValueError("runner changed")
except (OSError, ValueError):
    holds.add("unverified_runner_identity")
    for row in entries:
        row["holds"] = sorted(set(row["holds"]) | holds)
report = dict(schema="fmix-artifact-audit.v1", mutation_supported=False,
                      idle_ttl_hours=dict(dependency=int(sys.argv[3]), template=int(sys.argv[4])),
                      observed_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
                      source_sha256=source_sha256, home=home, holds=sorted(holds),
                      entries=entries, observations=observations, report_truncated=False)
# Bound serialization itself, not just scan inputs. iterencode avoids building
# an unbounded JSON string when many lanes repeat the same reference cohort.
max_report_bytes = 16 * 1024 * 1024
chunks, serialized_bytes = [], 0
for chunk in json.JSONEncoder(sort_keys=True).iterencode(report):
    serialized_bytes += len(chunk.encode("utf-8"))
    if serialized_bytes + 1 > max_report_bytes:
        report.update(entries=[], observations=[], report_truncated=True,
                      discovered_counts=dict(entries=len(entries), observations=len(observations)),
                      holds=sorted(holds | {"report_output_budget_reached"}))
        print(json.dumps(report, sort_keys=True))
        break
    chunks.append(chunk)
else:
    print("".join(chunks))
PY
}

cmd_gc() {
    local do_reap=0 skip_prompts=0 do_consolidate=0 worktree_filter=""
    while (( $# > 0 )); do
        case "$1" in
            --reap) do_reap=1; shift ;;
            --yes) skip_prompts=1; do_reap=1; shift ;;
            --consolidate) do_consolidate=1; shift ;;
            --worktree)
                [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path."; return 2; }
                worktree_filter="$2"
                shift 2
                ;;
            --worktree=*) worktree_filter="${1#--worktree=}"; shift ;;
            *) fmix_error "Unknown gc option: $1. Usage: fmix gc [--reap|--consolidate] [--worktree PATH] [--yes]"; return 1 ;;
        esac
    done

    fmix_run_observability_purge

    if (( do_consolidate == 1 )); then
        echo "=== fmix gc --consolidate$([ $do_reap -eq 0 ] && echo " (read-only — pass --yes to act)" || echo " --yes") ==="
        fmix_gc_consolidate_sessions "$do_reap" "$skip_prompts" "$worktree_filter"
        return $?
    fi

    echo "=== fmix gc$([ $do_reap -eq 0 ] && echo " (read-only — pass --reap to act)" || echo " --reap") ==="
    local actions=0 session_state_paths session_meta_paths
    local recorded_dbs=()
    if ! session_state_paths="$(fmix_session_files state.json)" \
        || ! session_meta_paths="$(fmix_session_files meta.json)"; then
        fmix_error "Could not enumerate session state; refusing GC cleanup."
        return 1
    fi

    # 1. Scratch DBs with gone worktrees
    echo ""
    echo "--- Scratch DBs with missing worktrees ---"
    if [[ -d "$FMIX_HOME/worktrees" ]]; then
        for sf in "$FMIX_HOME/worktrees"/*.json; do
            [[ -f "$sf" ]] || continue
            local path db
            path="$(fmix_read_state "$sf" "path")"
            db="$(fmix_read_state "$sf" "db_name")"
            [[ -z "$path" || -z "$db" ]] && continue
            if [[ ! -d "$path" ]]; then
                fmix_guard_db_name "$db" || continue
                if fmix_db_exists "$db"; then
                    echo "  ORPHAN: $db  (worktree gone: $path)"
                    actions=$(( actions + 1 ))
                    if (( do_reap == 1 )); then
                        local confirm="y"
                        if (( skip_prompts == 0 )); then
                            printf '  Drop %s? [y/N] ' "$db"
                            read -r confirm
                        fi
                        if [[ "$confirm" =~ ^[Yy]$ ]]; then
                            # db came from a state file — re-validate before SQL (codex P1)
                            fmix_guard_db_name "$db" || continue
                            if fmix_drop_db "$db" 1; then
                                echo "  Dropped: $db"
                                rm -f "$FMIX_HOME/compile-stamps/$(basename "$sf")"
                                rm -f "$sf"
                            else
                                local drop_rc=$?
                                fmix_lock_failure_is_fatal "$drop_rc" && return 70
                                fmix_warn "Keeping state for $db because bounded cleanup failed."
                            fi
                        fi
                    fi
                fi
            fi
        done
    fi
    while IFS= read -r sf; do
        [[ -f "$sf" ]] || continue
        local _session_db
        _session_db="$(fmix_read_state "$sf" "db_name")"
        [[ -n "$_session_db" ]] && recorded_dbs+=("$_session_db")
    done <<<"$session_state_paths"
    # A session publishes meta.json before it creates its scratch DB and may
    # not publish state.json until preparation completes. Treat every valid
    # session identity as a live DB reference so GC cannot drop a database
    # from an in-progress first setup.
    while IFS= read -r sf; do
        [[ -f "$sf" ]] || continue
        local _session_hash
        _session_hash="$(fmix_session_hash_from_metadata_path "$sf" 2>/dev/null)" || continue
        [[ "$_session_hash" =~ ^[0-9a-f]{16}$ ]] \
            && recorded_dbs+=("ct_fmix_s_$_session_hash")
    done <<<"$session_meta_paths"

    # 1b. P1-4 FIX: Orphan DBs — ct_fmix_* databases in postgres with no matching state file.
    # Walk ALL ct_fmix_* DB names from postgres, cross-reference against state files.
    echo ""
    echo "--- Orphan DBs (ct_fmix_* in postgres with no state file) ---"
    local all_fmix_dbs
    all_fmix_dbs="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
        -t -c "SELECT datname FROM pg_database WHERE datname LIKE 'ct_fmix_%' ORDER BY datname" \
        2>/dev/null)" || all_fmix_dbs=""

    # Add DB names recorded by legacy worktree state. Session references were
    # already added above and must not be reset before orphan classification.
    if [[ -d "$FMIX_HOME/worktrees" ]]; then
        for sf in "$FMIX_HOME/worktrees"/*.json; do
            [[ -f "$sf" ]] || continue
            local _rdb
            _rdb="$(fmix_read_state "$sf" "db_name")"
            [[ -n "$_rdb" ]] && recorded_dbs+=("$_rdb")
        done
    fi

    if [[ -n "$all_fmix_dbs" ]]; then
        while IFS= read -r pgdb; do
            pgdb="$(printf '%s' "$pgdb" | tr -d ' \t')"
            [[ -z "$pgdb" ]] && continue
            # Safety: only touch ct_fmix_* names
            fmix_guard_db_name "$pgdb" 2>/dev/null || continue
            # Shared infrastructure, NOT per-worktree scratch DBs: snapshot
            # templates (ct_fmix_snap_*) and ecto-load templates (ct_fmix_tmpl_*)
            # are intentionally not referenced by any worktree state file. The
            # orphan-DB sweep must never reap them, or it would drop the live
            # snapshot every other worktree clones from. (A snapshot for a stale
            # structure.sql hash is harmless; it is reused only when that exact
            # dump returns, and costs ~135 MB.)
            case "$pgdb" in ct_fmix_snap_*|ct_fmix_tmpl_*) continue ;; esac
            # Check if it appears in any state file
            local found_in_state=0
            for rdb in "${recorded_dbs[@]+"${recorded_dbs[@]}"}"; do
                if [[ "$rdb" == "$pgdb" ]]; then
                    found_in_state=1
                    break
                fi
            done
            if (( found_in_state == 0 )); then
                echo "  ORPHAN-DB: $pgdb  (no state file references this DB)"
                actions=$(( actions + 1 ))
                if (( do_reap == 1 )); then
                    local confirm_odb="y"
                    if (( skip_prompts == 0 )); then
                        printf '  Drop orphan DB %s? [y/N] ' "$pgdb"
                        read -r confirm_odb
                    fi
                    if [[ "$confirm_odb" =~ ^[Yy]$ ]]; then
                        local orphan_drop_rc=0
                        if [[ "$pgdb" =~ ^ct_fmix_s_[0-9a-f]{16}$ ]]; then
                            fmix_drop_orphan_session_db "$pgdb" "GC orphan DB sweep" \
                                || orphan_drop_rc=$?
                        elif [[ "$pgdb" == ct_fmix_s_* ]]; then
                            # Never route an unrecognized session-shaped name
                            # through the unleased legacy cleanup path.
                            fmix_warn "Refusing unleased cleanup for malformed session DB name: $pgdb"
                            orphan_drop_rc=2
                        else
                            # Legacy non-session scratch names have no session
                            # lease to coordinate with; retain the strict name
                            # guard immediately before the bounded drop.
                            fmix_guard_db_name "$pgdb" || orphan_drop_rc=1
                            if (( orphan_drop_rc == 0 )); then
                                fmix_drop_db "$pgdb" || orphan_drop_rc=$?
                            fi
                        fi
                        fmix_lock_failure_is_fatal "$orphan_drop_rc" && return 70
                        if (( orphan_drop_rc == 0 )); then
                            echo "  Dropped: $pgdb"
                        elif (( orphan_drop_rc == 1 )); then
                            fmix_warn "Bounded cleanup failed for orphan DB $pgdb; leaving it for a later gc run."
                        else
                            fmix_warn "Orphan status changed or its session lease is active; keeping $pgdb."
                        fi
                    fi
                fi
            fi
        done <<<"$all_fmix_dbs"
    fi

    # Incomplete producer staging can still be a recovery/verifier input.
    # Age alone never releases it, including through the legacy mixed GC.
    echo ""
    echo "--- Template staging: HELD (producer/recovery release unproven) ---"

    # 3. Retired lock metadata. Kernel lock files persist by design, but the
    # directory-shaped mixed-version records are diagnostic snapshots only.
    local lock_metadata_ttl_days lock_metadata_ttl_seconds
    lock_metadata_ttl_days="$(
        fmix_uint_or_default \
            "$FMIX_LOCK_METADATA_TTL_DAYS" 7 FMIX_LOCK_METADATA_TTL_DAYS
    )"
    lock_metadata_ttl_seconds=$(( lock_metadata_ttl_days * 86400 ))
    echo ""
    echo "--- Retired lock metadata older than ${lock_metadata_ttl_days} days ---"
    local metadata_class metadata_entry metadata_mtime metadata_age
    for metadata_class in released stale; do
        [[ -d "$FMIX_HOME/lock-metadata/$metadata_class" ]] || continue
        for metadata_entry in "$FMIX_HOME/lock-metadata/$metadata_class"/*; do
            [[ -d "$metadata_entry" && ! -L "$metadata_entry" ]] || continue
            metadata_mtime="$(fmix_stat_mtime "$metadata_entry" 2>/dev/null || echo 0)"
            metadata_age=$(( $(fmix_epoch) - metadata_mtime ))
            (( metadata_age > lock_metadata_ttl_seconds )) || continue
            echo "  OLD: $metadata_entry (age=$(( metadata_age / 86400 ))d)"
            actions=$(( actions + 1 ))
            if (( do_reap == 1 )); then
                fmix_guard_path "$metadata_entry" \
                    && rm -rf "$metadata_entry" \
                    && echo "  Deleted: $metadata_entry"
            fi
        done
    done

    # Published artifacts are not released by age or --yes. The former
    # template path lacked reader coordination; the dependency path lacked
    # complete consumers, fresh identity and fallback preservation. Keep both
    # classes outside mixed mutation until the native exact retirement ledger
    # can prove all of those invariants. The isolated inventory is bounded and
    # reports four-hour idle policy without database/session/telemetry effects.
    echo ""
    echo "--- Templates and dependency artifacts: HELD (consumer release unproven) ---"
    echo "  Inventory separately: fmix gc --artifacts-only --json"

    # 6. Expired session overlays. Reaping is lease-aware: the exact session
    # lock must be acquired before its artifacts or scratch DB are touched.
    local session_ttl_hours session_ttl_seconds
    session_ttl_hours="$(fmix_effective_session_ttl_hours)"
    session_ttl_seconds="$(fmix_session_ttl_seconds "$session_ttl_hours")"
    echo ""
    echo "--- Sessions unused > ${session_ttl_hours} hours ---"
    local session_meta session_root session_hash session_last session_epoch
    local session_age session_lock session_db session_reap_ok
    while IFS= read -r session_meta; do
        [[ -f "$session_meta" ]] || continue
        session_root="$(dirname "$session_meta")"
        if ! session_hash="$(fmix_session_hash_from_metadata_path "$session_meta")"; then
            fmix_warn "Refusing GC for malformed session metadata path: $session_meta"
            continue
        fi
        if ! fmix_session_metadata_identity_matches_path "$session_meta"; then
            fmix_warn "Refusing GC for mismatched session metadata identity: $session_meta"
            continue
        fi
        session_last="$(grep -o '"last_accessed"[[:space:]]*:[[:space:]]*"[^"]*"' \
            "$session_meta" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
        [[ -n "$session_last" ]] || session_last="$(grep -o '"last_used"[[:space:]]*:[[:space:]]*"[^"]*"' \
            "$session_meta" 2>/dev/null | head -1 | sed 's/.*: *"\(.*\)".*/\1/')"
        [[ -n "$session_last" ]] || session_last="$(grep -o '"last_accessed"[[:space:]]*:[[:space:]]*[0-9.]*' \
            "$session_meta" 2>/dev/null | head -1 | sed 's/.*:[[:space:]]*//')"
        [[ -n "$session_last" ]] || session_last="$(grep -o '"last_used"[[:space:]]*:[[:space:]]*[0-9.]*' \
            "$session_meta" 2>/dev/null | head -1 | sed 's/.*:[[:space:]]*//')"
        [[ "$session_hash" =~ ^[0-9a-f]{16}$ && -n "$session_last" ]] || continue
        if [[ "$session_last" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
            session_epoch="${session_last%.*}"
        else
            session_epoch="$(fmix_iso_epoch "$session_last" 2>/dev/null)" || continue
        fi
        [[ "$session_epoch" =~ ^[0-9]+$ ]] || continue
        session_age=$(( $(fmix_epoch) - session_epoch ))
        (( session_age > session_ttl_seconds )) || continue
        session_lock="session-$session_hash"
        if [[ -f "$FMIX_HOME/locks/$session_lock/pid" ]]; then
            local session_pid
            session_pid="$(cat "$FMIX_HOME/locks/$session_lock/pid" 2>/dev/null || true)"
            if [[ "$session_pid" =~ ^[0-9]+$ ]] && kill -0 "$session_pid" 2>/dev/null; then
                echo "  LEASED: $session_hash (pid=$session_pid, last_used=$session_last)"
                continue
            fi
        fi
        echo "  STALE: $session_hash (last_used=$session_last, age=$(( session_age / 3600 ))h)"
        actions=$(( actions + 1 ))
        if (( do_reap == 1 )); then
            local confirm_session="y"
            if (( skip_prompts == 0 )); then
                printf '  Reap session %s? [y/N] ' "$session_hash"
                read -r confirm_session
            fi
            if [[ "$confirm_session" =~ ^[Yy]$ ]]; then
                if fmix_lock_acquire "$session_lock" 0 "session GC lease" \
                    >/dev/null 2>&1; then
                    :
                else
                    local acquire_rc=$?
                    fmix_lock_failure_is_fatal "$acquire_rc" && return 70
                    fmix_warn "Session $session_hash became active; keeping it."
                    continue
                fi
                if ! fmix_session_meta_is_expired "$session_meta" "$session_hash" \
                    "$session_ttl_seconds"; then
                    fmix_warn "Session $session_hash was refreshed; keeping it."
                    fmix_lock_release_optional "$session_lock" || {
                        local release_rc=$?
                        fmix_lock_failure_is_fatal "$release_rc" && return 70
                        fmix_warn "Session GC lease metadata could not be retired."
                    }
                    continue
                fi
                session_reap_ok=1
                session_db="$(fmix_read_state "$session_root/state.json" db_name 2>/dev/null)"
                [[ -n "$session_db" ]] || session_db="ct_fmix_s_$session_hash"
                if fmix_db_exists "$session_db"; then
                    fmix_drop_db "$session_db" 1 || {
                        local drop_rc=$?
                        if fmix_lock_failure_is_fatal "$drop_rc"; then
                            fmix_command_lock_finish "$session_lock" "$drop_rc"
                            return $?
                        fi
                        session_reap_ok=0
                    }
                fi
                if (( session_reap_ok == 1 )); then
                    if fmix_guard_path "$session_root" && rm -rf "$session_root"; then
                        echo "  Reaped session: $session_hash"
                    else
                        session_reap_ok=0
                    fi
                fi
                fmix_lock_release_optional "$session_lock" || {
                    local release_rc=$?
                    fmix_lock_failure_is_fatal "$release_rc" && return 70
                    fmix_warn "Session GC lease metadata could not be retired."
                }
                (( session_reap_ok == 1 )) \
                    || fmix_warn "Session $session_hash cleanup was incomplete; retained artifacts require review."
            fi
        fi
    done < <(printf '%s\n' "$session_meta_paths" | LC_ALL=C sort)

    # 6. Legacy _build.fmix-stale.* dirs in known worktrees
    echo ""
    echo "--- Stale _build dirs in worktrees ---"
    if [[ -d "$FMIX_HOME/worktrees" ]]; then
        for sf in "$FMIX_HOME/worktrees"/*.json; do
            [[ -f "$sf" ]] || continue
            local path
            path="$(fmix_read_state "$sf" "path")"
            [[ -d "$path" ]] || continue
            for stale_dir in "$path"/_build.fmix-stale.*/; do
                [[ -d "$stale_dir" ]] || continue
                local size
                size="$(du -sh "$stale_dir" 2>/dev/null | awk '{print $1}')" || size="?"
                echo "  STALE: $stale_dir ($size)"
                actions=$(( actions + 1 ))
                if (( do_reap == 1 )); then
                    fmix_guard_stale_build "$stale_dir" && \
                        rm -rf "$stale_dir" && echo "  Deleted: $stale_dir"
                fi
            done
        done
    fi

    echo ""
    if (( actions == 0 )); then
        echo "  gc: nothing to clean up."
    elif (( do_reap == 0 )); then
        echo "  gc: $actions item(s) found. Re-run with --reap to clean up."
    else
        echo "  gc: done."
    fi
}

# ---------------------------------------------------------------------------
# cmd: fmix self-test
# ---------------------------------------------------------------------------

cmd_self_test() {
    if ! fmix_artifact_v2_managed_entrypoint >/dev/null 2>&1; then
        if [[ "${FMIX_SELF_TEST_MANAGED_REEXEC:-0}" == "1" ]]; then
            fmix_error "Self-test could not establish a private managed runner."
            return 1
        fi
        (
            local fixture_root fixture_home fixture_bin source_runner launcher rc
            fixture_root="$(mktemp -d)" || exit 1
            fixture_root="$(fmix_realpath "$fixture_root")" || exit 1
            trap 'rm -rf "$fixture_root"' EXIT INT TERM
            fixture_home="$fixture_root/home"
            fixture_bin="$fixture_home/.local/bin"
            source_runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || exit 1
            mkdir -p "$fixture_home" "$fixture_bin" || exit 1
            HOME="$fixture_home" FMIX_HOME="$fixture_root/fmix-home" \
                FMIX_INSTALL_DIR="$fixture_bin" \
                fmix_install_snapshot "$source_runner" "$fixture_bin" \
                >/dev/null || exit 1
            launcher="$fixture_bin/fmix"
            [[ -L "$launcher" ]] || exit 1
            HOME="$fixture_home" FMIX_HOME="$fixture_root/fmix-home" \
                FMIX_INSTALL_DIR="$fixture_bin" FMIX_SELF_TEST_MANAGED_REEXEC=1 \
                FMIX_SELF_TEST_RUNNER_HOME="$fixture_root/fmix-home" \
                "$launcher" self-test
            rc=$?
            exit "$rc"
        )
        return $?
    fi

    local pass=0 fail=0 skip=0

    # Keep a pristine definition for the long self-test. Several fixtures
    # monkeypatch stamp writers to exercise rollback paths; restore the
    # production implementation before the independent compile-stamp lane so
    # one fixture cannot leak a stub into later assertions.
    local fmix_write_dependency_stamp_self_test_definition
    fmix_write_dependency_stamp_self_test_definition="$(
        declare -f fmix_write_dependency_stamp
    )"
    eval "${fmix_write_dependency_stamp_self_test_definition/fmix_write_dependency_stamp/fmix_write_dependency_stamp_self_test_orig}"

    st_pass() { echo "  PASS: $*"; pass=$(( pass + 1 )); }
    st_fail() { echo "  FAIL: $*"; fail=$(( fail + 1 )); }
    st_skip() { echo "  SKIP: $*"; skip=$(( skip + 1 )); }

    echo "=== fmix self-test (v${FMIX_VERSION}) ==="
    echo "  OS: $FMIX_OS $FMIX_ARCH"
    echo ""

    echo "--- Session retention configuration ---"
    local self_script ttl_default ttl_legacy ttl_explicit ttl_hours_default ttl_hours_explicit ttl_fractional_seconds
    self_script="$(fmix_realpath "${BASH_SOURCE[0]}")"
    ttl_default="$(env -u FMIX_SESSION_TTL_DAYS -u FMIX_CACHE_TTL_DAYS \
        /bin/bash -c 'source "$1"; fmix_effective_session_ttl_days' \
        _ "$self_script")"
    ttl_legacy="$(env -u FMIX_SESSION_TTL_DAYS FMIX_CACHE_TTL_DAYS=3 \
        /bin/bash -c 'source "$1"; fmix_effective_session_ttl_days' \
        _ "$self_script")"
    ttl_explicit="$(env FMIX_SESSION_TTL_DAYS=2 FMIX_CACHE_TTL_DAYS=3 \
        /bin/bash -c 'source "$1"; fmix_effective_session_ttl_days' \
        _ "$self_script")"
    ttl_hours_default="$(env -u FMIX_SESSION_TTL_HOURS -u FMIX_SESSION_TTL_DAYS -u FMIX_CACHE_TTL_DAYS \
        /bin/bash -c 'source "$1"; fmix_effective_session_ttl_hours' \
        _ "$self_script")"
    ttl_hours_explicit="$(env FMIX_SESSION_TTL_HOURS=2 FMIX_SESSION_TTL_DAYS=3 \
        /bin/bash -c 'source "$1"; fmix_effective_session_ttl_hours' \
        _ "$self_script")"
    ttl_fractional_seconds="$(FMIX_SESSION_TTL_DAYS=0.5 fmix_session_ttl_seconds)"
    if [[ "$ttl_default" == "1" && "$ttl_legacy" == "3" \
        && "$ttl_explicit" == "2" && "$ttl_hours_default" == "4" \
        && "$ttl_hours_explicit" == "2" && "$ttl_fractional_seconds" == "43200" ]]; then
        st_pass "session retention shares legacy compatibility, four-hour default, override precedence, and fractional conversion"
    else
        st_fail "session retention config days_default=$ttl_default days_legacy=$ttl_legacy days_explicit=$ttl_explicit hours_default=$ttl_hours_default hours_explicit=$ttl_hours_explicit fractional_seconds=$ttl_fractional_seconds"
    fi
    echo ""

    # 1. OS dispatch helpers
    echo "--- OS dispatch helpers ---"

    # fmix_realpath
    local rp
    rp="$(fmix_realpath /tmp 2>/dev/null)" && [[ -n "$rp" ]] \
        && st_pass "fmix_realpath: /tmp → $rp" \
        || st_fail "fmix_realpath failed"

    # fmix_stat_mtime
    local ts
    ts="$(fmix_stat_mtime /tmp 2>/dev/null)" && [[ "$ts" =~ ^[0-9]+$ ]] \
        && st_pass "fmix_stat_mtime: /tmp → $ts" \
        || st_fail "fmix_stat_mtime failed or non-numeric output: '$ts'"

    # fmix_epoch
    local ep
    ep="$(fmix_epoch)" && [[ "$ep" =~ ^[0-9]+$ ]] \
        && st_pass "fmix_epoch: $ep" \
        || st_fail "fmix_epoch failed"

    # fmix_hash_stdin
    local h
    h="$(printf 'hello\n' | fmix_hash_stdin 2>/dev/null)" && [[ ${#h} -eq 64 ]] \
        && st_pass "fmix_hash_stdin: sha256 of 'hello' → ${h:0:16}…" \
        || st_fail "fmix_hash_stdin failed or wrong length: '${h:-empty}'"

    # Native dep NIF verification: the toolchain heal purges .so files and Mix
    # will not rebuild deps it thinks are compiled, so a missing priv library
    # must be detected and rebuilt via a forced mix deps.compile.
    local nif_wt nif_stub nif_missing nif_old_path
    nif_wt="$(mktemp -d)"
    nif_wt="$(fmix_realpath "$nif_wt")"
    nif_stub="$(mktemp -d)"
    mkdir -p "$nif_wt/deps/sippet/c_src" "$nif_wt/deps/sippet/priv" \
        "$nif_wt/deps/pure_elixir" "$nif_wt/deps/has_so/c_src" "$nif_wt/deps/has_so/priv"
    printf 'compilers: [:elixir_make]\n' >"$nif_wt/deps/sippet/mix.exs"
    : >"$nif_wt/deps/sippet/Makefile"
    printf 'compilers: [:elixir_make]\n' >"$nif_wt/deps/has_so/mix.exs"
    : >"$nif_wt/deps/has_so/Makefile"
    : >"$nif_wt/deps/has_so/priv/has_so.so"
    nif_missing="$(fmix_native_deps_missing_so "$nif_wt/deps")"
    if [[ "$nif_missing" == "sippet" ]]; then
        # Fake `mix` that "rebuilds" the NIF for the requested deps.
        cat >"$nif_stub/mix" <<'NIFSTUB'
#!/bin/sh
[ "$1" = "deps.compile" ] || exit 1
shift
for dep in "$@"; do
    case "$dep" in --*) continue ;; esac
    : >"$MIX_DEPS_PATH/$dep/priv/$dep.so"
done
NIFSTUB
        chmod +x "$nif_stub/mix"
        nif_old_path="$PATH"
        PATH="$nif_stub:$PATH"
        MIX_DEPS_PATH="$nif_wt/deps" fmix_repair_missing_native_deps "$nif_wt" >/dev/null 2>&1
        PATH="$nif_old_path"
        if [[ -f "$nif_wt/deps/sippet/priv/sippet.so" \
            && -z "$(fmix_native_deps_missing_so "$nif_wt/deps")" ]]; then
            st_pass "native dep verify: purged sippet NIF detected and rebuilt via mix deps.compile"
        else
            st_fail "native dep verify: sippet NIF was not rebuilt"
        fi
    else
        st_fail "native dep verify: expected only 'sippet' missing, got '$nif_missing'"
    fi
    rm -rf "$nif_wt" "$nif_stub"

    # Worktree discovery is consumed through command substitution. Any
    # initialization diagnostics must stay on stderr so they cannot become
    # part of the resolved path.
    local submodule_wt submodule_stderr submodule_stdout git_bin
    submodule_wt="$(mktemp -d)"
    submodule_wt="$(fmix_realpath "$submodule_wt")"
    submodule_stderr="$(mktemp)"
    git init -q "$submodule_wt"
    printf 'defmodule Fixture.MixProject do\n  use Mix.Project\n  def project, do: [app: :cdrcisco]\nend\n' \
        >"$submodule_wt/mix.exs"
    printf '[submodule "proto"]\n\tpath = proto\n\turl = https://example.invalid/proto.git\n' \
        >"$submodule_wt/.gitmodules"
    mkdir -p "$submodule_wt/proto"
    git_bin="$(command -v git)"
    if submodule_stdout="$({
        git() {
            if [[ " $* " == *" submodule update --init --recursive "* ]]; then
                printf "Submodule path 'proto': checked out 'fixture'\n"
                printf "submodule stderr diagnostic\n" >&2
                return 0
            fi
            "$git_bin" "$@"
        }
        fmix_find_worktree "$submodule_wt"
    } 2>"$submodule_stderr")" \
        && [[ "$submodule_stdout" == "$submodule_wt" ]] \
        && grep -q "Submodule path 'proto'" "$submodule_stderr" \
        && grep -q "submodule stderr diagnostic" "$submodule_stderr"; then
        st_pass "submodule initialization output cannot contaminate worktree resolution"
    else
        st_fail "submodule initialization contaminated worktree resolution: '$submodule_stdout'"
    fi
    rm -rf "$submodule_wt"
    rm -f "$submodule_stderr"

    # Also cover a top-level cisco-cdr submodule that has not materialized its
    # mix.exs yet. The mocked update creates the checkout while keeping every
    # initialization diagnostic off command-substitution stdout.
    local submodule_parent top_level_wt top_level_stderr top_level_stdout top_level_fixture_sha
    submodule_parent="$(mktemp -d)"
    submodule_parent="$(fmix_realpath "$submodule_parent")"
    top_level_wt="$submodule_parent/cisco-cdr"
    top_level_stderr="$(mktemp)"
    git init -q "$submodule_parent"
    mkdir -p "$top_level_wt"
    printf '[submodule "cisco-cdr"]\n\tpath = cisco-cdr\n\turl = https://github.com/calltelemetry/cisco-cdr.git\n' \
        >"$submodule_parent/.gitmodules"
    git -C "$submodule_parent" -c user.name=fmix-self-test \
        -c user.email=fmix-self-test@example.invalid -c commit.gpgsign=false \
        commit --allow-empty -qm 'owned cold Gitlink fixture'
    top_level_fixture_sha="$(git -C "$submodule_parent" rev-parse HEAD)"
    git -C "$submodule_parent" add .gitmodules
    git -C "$submodule_parent" update-index --add --cacheinfo \
        "160000,$top_level_fixture_sha,cisco-cdr"
    if top_level_stdout="$({
        git() {
            if [[ " $* " == *" submodule update --init --recursive "* ]]; then
                printf "Submodule path 'cisco-cdr': checked out 'fixture'\n"
                printf "top-level submodule stderr diagnostic\n" >&2
                printf 'defmodule Fixture.MixProject do\n  use Mix.Project\n  def project, do: [app: :cdrcisco]\nend\n' \
                    >"$top_level_wt/mix.exs"
                return 0
            fi
            "$git_bin" "$@"
        }
        fmix_find_worktree "$top_level_wt"
    } 2>"$top_level_stderr")" \
        && [[ "$top_level_stdout" == "$top_level_wt" ]] \
        && grep -q "Detected uninitialized submodules" "$top_level_stderr" \
        && grep -q "Submodule path 'cisco-cdr'" "$top_level_stderr" \
        && grep -q "top-level submodule stderr diagnostic" "$top_level_stderr"; then
        st_pass "top-level submodule initialization cannot contaminate worktree resolution"
    else
        st_fail "top-level submodule initialization contaminated worktree resolution: '$top_level_stdout'"
    fi
    rm -rf "$submodule_parent"
    rm -f "$top_level_stderr"

    # 2. Template key stability (same inputs → same key)
    echo ""
    echo "--- Template key stability ---"
    local tmp_wt
    tmp_wt="$(mktemp -d)"
    printf 'erlang 28.4.1\nelixir 1.19.5-otp-28\n' >"$tmp_wt/.tool-versions"
    printf 'defmodule Fixture.MixProject, do: nil\n' >"$tmp_wt/mix.exs"
    printf 'LOCKFILE_V1\n' >"$tmp_wt/mix.lock"
    mkdir -p "$tmp_wt/config"
    printf '# config\n' >"$tmp_wt/config/config.exs"
    printf '# test\n' >"$tmp_wt/config/test.exs"

    local exact_identity self_test_saved_identity self_test_synthetic_toolchain=0
    exact_identity=$'otp=28.4.1\nerts=16.3\nelixir=1.19.5-otp-28\nmix=1.19.5'
    self_test_saved_identity="${FMIX_TOOLCHAIN_IDENTITY-__fmix_unset__}"
    eval "$(declare -f fmix_activate_toolchain |
        sed '1s/fmix_activate_toolchain/fmix_activate_toolchain_self_test_orig/')"

    if fmix_activate_toolchain "$tmp_wt" >/dev/null 2>&1 &&
        [[ "$FMIX_TOOLCHAIN_IDENTITY" == *"otp=28.4.1"* ]] &&
        [[ "$FMIX_TOOLCHAIN_IDENTITY" == *"elixir=1.19.5-otp-28"* ]]; then
        st_pass "exact active BEAM ABI matches .tool-versions"
    else
        # The portability smoke test is documented to run in a bare container
        # without Erlang, Elixir, or asdf. Keep production activation strict,
        # but let the remainder of this self-contained harness exercise
        # identity-keyed behavior with a synthetic fixture identity.
        st_skip "pinned BEAM runtime unavailable; using a synthetic ABI fixture"
        self_test_synthetic_toolchain=1
        FMIX_TOOLCHAIN_IDENTITY="$exact_identity"
        export FMIX_TOOLCHAIN_IDENTITY
        fmix_activate_toolchain() {
            FMIX_TOOLCHAIN_IDENTITY="$exact_identity"
            export FMIX_TOOLCHAIN_IDENTITY
            return 0
        }
    fi

    local key1 key2
    key1="$(fmix_compute_template_key "$tmp_wt" 2>/dev/null)"
    key2="$(fmix_compute_template_key "$tmp_wt" 2>/dev/null)"

    if [[ -n "$key1" && "$key1" == "$key2" ]]; then
        st_pass "template key stable: $key1"
    else
        st_fail "template key unstable: '$key1' != '$key2'"
    fi
    eval "$(declare -f fmix_stable_seed_path_dependency_manifests \
        | sed '1s/fmix_stable_seed_path_dependency_manifests/fmix_stable_seed_path_dependency_manifests_manifest_orig/')"
    fmix_stable_seed_path_dependency_manifests() { return 1; }
    if ! fmix_compute_template_key "$tmp_wt" >/dev/null 2>&1; then
        st_pass "template key propagates manifest-generation failures"
    else
        st_fail "template key masked a manifest-generation failure"
    fi
    eval "$(declare -f fmix_stable_seed_path_dependency_manifests_manifest_orig \
        | sed '1s/fmix_stable_seed_path_dependency_manifests_manifest_orig/fmix_stable_seed_path_dependency_manifests/')"
    eval "$(declare -f fmix_hash_compile_paths \
        | sed '1s/fmix_hash_compile_paths/fmix_hash_compile_paths_manifest_orig/')"
    fmix_hash_compile_paths() { return 1; }
    if ! fmix_compute_compile_fingerprint "$tmp_wt" >/dev/null 2>&1 \
        && ! fmix_compute_dependency_fingerprint "$tmp_wt" >/dev/null 2>&1; then
        st_pass "compile and dependency fingerprints propagate input-hash failures"
    else
        st_fail "compile or dependency fingerprint masked an input-hash failure"
    fi
    eval "$(declare -f fmix_hash_compile_paths_manifest_orig \
        | sed '1s/fmix_hash_compile_paths_manifest_orig/fmix_hash_compile_paths/')"

    # Mutating a file should change the key
    printf '# modified\n' >"$tmp_wt/mix.lock"
    local key3
    key3="$(fmix_compute_template_key "$tmp_wt" 2>/dev/null)"
    if [[ "$key3" != "$key1" ]]; then
        st_pass "template key changes on content mutation: $key3"
    else
        st_fail "template key did NOT change after content mutation"
    fi
    local mix_key
    printf 'defmodule Fixture.MixProject, do: :changed\n' >"$tmp_wt/mix.exs"
    mix_key="$(fmix_compute_template_key "$tmp_wt" 2>/dev/null)"
    if [[ -n "$mix_key" && "$mix_key" != "$key3" ]]; then
        st_pass "template key changes when dependency declarations in mix.exs change"
    else
        st_fail "template key ignored mix.exs dependency-declaration drift"
    fi

    local abi_key old_identity
    old_identity="$FMIX_TOOLCHAIN_IDENTITY"
    FMIX_TOOLCHAIN_IDENTITY=$'otp=29.0.3\nerts=17.0\nelixir=1.19.5-otp-29\nmix=1.19.5'
    abi_key="$(fmix_compute_template_key "$tmp_wt" 2>/dev/null)"
    FMIX_TOOLCHAIN_IDENTITY="$old_identity"
    if [[ -n "$abi_key" && "$abi_key" != "$mix_key" ]]; then
        st_pass "template key changes with resolved BEAM ABI"
    else
        st_fail "template key ignored resolved BEAM ABI drift"
    fi

    local fake_bin saved_path mismatch_output
    fake_bin="$tmp_wt/fake-bin"
    mkdir -p "$fake_bin"
    printf '#!/bin/sh\nprintf "29"\n' >"$fake_bin/erl"
    printf '#!/bin/sh\nprintf "Erlang/OTP 29 [erts-17.0]\\nElixir 1.19.5 (compiled with Erlang/OTP 29)\\n"\n' >"$fake_bin/elixir"
    printf '#!/bin/sh\nprintf "Mix 1.19.5 (compiled with Erlang/OTP 29)\\n"\n' >"$fake_bin/mix"
    chmod +x "$fake_bin/erl" "$fake_bin/elixir" "$fake_bin/mix"
    saved_path="$PATH"
    PATH="$fake_bin:$saved_path"
    FMIX_TOOLCHAIN_IDENTITY=""
    if (( self_test_synthetic_toolchain == 1 )); then
        st_skip "ambient-manager precedence requires the pinned host runtime"
    elif fmix_activate_toolchain "$tmp_wt" >/dev/null 2>&1 &&
        [[ "$FMIX_TOOLCHAIN_IDENTITY" == *"otp=28.4.1"* ]]; then
        st_pass "repo asdf toolchain outranks a wrong ambient manager"
    else
        st_fail "wrong ambient manager outranked the repo asdf toolchain"
    fi
    PATH="$fake_bin:/usr/bin:/bin"
    FMIX_TOOLCHAIN_IDENTITY=""
    if mismatch_output="$(fmix_resolved_toolchain_identity "$tmp_wt" 2>&1)"; then
        st_fail "wrong ambient OTP was accepted"
    elif [[ "$mismatch_output" == *"Erlang/OTP mismatch"* ]] &&
        [[ "$mismatch_output" == *"Refusing to read or write deps/_build"* ]]; then
        st_pass "wrong ambient OTP fails closed before artifact access"
    else
        st_fail "wrong ambient OTP failed without actionable ABI diagnostics"
    fi
    PATH="$saved_path"
    FMIX_TOOLCHAIN_IDENTITY="$exact_identity"

    echo ""
    echo "--- Session isolation and portable fingerprints ---"
    local session_test_home session_saved_home session_saved_build session_saved_deps
    local session_a_root session_b_root session_a_db session_b_db session_a_fingerprint
    local session_b_fingerprint session_a_repeat session_alias_home session_alias_real
    local session_alias_link session_alias_target session_alias_resolved
    local session_cache_real session_cache_alias session_cache_missing
    local session_cache_file session_cache_dangling
    local session_alias_python
    local activation_failure_root activation_failure_cleanup_marker
    session_test_home="$(mktemp -d)"
    session_saved_home="$FMIX_HOME"
    session_saved_build="${MIX_BUILD_PATH-__unset__}"
    session_saved_deps="${MIX_DEPS_PATH-__unset__}"
    FMIX_HOME="$session_test_home"
    mkdir -p "$tmp_wt/priv"
    unset MIX_BUILD_PATH MIX_DEPS_PATH
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    local activation_lock_marker="$session_test_home/activation-lock-held"
    local activation_housekeeping_marker="$session_test_home/activation-housekeeping-lock-held"
    eval "$(declare -f fmix_write_session_meta \
        | sed '1s/fmix_write_session_meta/fmix_write_session_meta_activation_orig/')"
    eval "$(declare -f fmix_purge_expired_sessions \
        | sed '1s/fmix_purge_expired_sessions/fmix_purge_expired_sessions_activation_orig/')"
    fmix_write_session_meta() {
        if fmix_lock_find_index "session-$FMIX_ACTIVE_SESSION_HASH" >/dev/null 2>&1; then
            : >"$activation_lock_marker"
        fi
        fmix_write_session_meta_activation_orig "$@"
    }
    fmix_purge_expired_sessions() {
        local held_name
        for held_name in "${FMIX_HELD_LOCK_NAMES[@]+"${FMIX_HELD_LOCK_NAMES[@]}"}"; do
            if [[ "$held_name" == session-* ]]; then
                : >"$activation_housekeeping_marker"
                break
            fi
        done
        fmix_purge_expired_sessions_activation_orig "$@"
    }
    if fmix_activate_session "$tmp_wt" agent-a >/dev/null 2>&1; then
        session_a_root="$FMIX_ACTIVE_SESSION_ROOT"
        session_a_db="$(fmix_db_name_for_worktree "$tmp_wt")"
        session_a_fingerprint="$(fmix_compute_dependency_fingerprint "$tmp_wt" 2>/dev/null)"
    else
        session_a_root=""
        session_a_db=""
        session_a_fingerprint=""
    fi
    eval "$(declare -f fmix_write_session_meta_activation_orig \
        | sed '1s/fmix_write_session_meta_activation_orig/fmix_write_session_meta/')"
    eval "$(declare -f fmix_purge_expired_sessions_activation_orig \
        | sed '1s/fmix_purge_expired_sessions_activation_orig/fmix_purge_expired_sessions/')"
    if [[ -e "$activation_lock_marker" && -e "$activation_housekeeping_marker" ]]; then
        st_pass "session activation serializes housekeeping and metadata publication under lease"
    else
        st_fail "session activation ran housekeeping or metadata publication without its exact lease"
    fi
    unset MIX_BUILD_PATH MIX_DEPS_PATH
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    if fmix_activate_session "$tmp_wt" agent-b >/dev/null 2>&1; then
        session_b_root="$FMIX_ACTIVE_SESSION_ROOT"
        session_b_db="$(fmix_db_name_for_worktree "$tmp_wt")"
        session_b_fingerprint="$(fmix_compute_dependency_fingerprint "$tmp_wt" 2>/dev/null)"
    else
        session_b_root=""
        session_b_db=""
        session_b_fingerprint=""
    fi
    if [[ -n "$session_a_root" && -n "$session_b_root" \
        && "$session_a_root" != "$session_b_root" \
        && "$session_a_db" != "$session_b_db" \
        && "$session_a_fingerprint" == "$session_b_fingerprint" \
        && ! -e "$tmp_wt/deps" && ! -e "$tmp_wt/_build" ]]; then
        st_pass "concurrent logical sessions isolate writable paths and DBs while sharing content identity"
    else
        st_fail "session namespaces collided, mutated the checkout, or made fingerprints path-bound"
    fi
    unset MIX_BUILD_PATH MIX_DEPS_PATH
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    fmix_activate_session "$tmp_wt" agent-a >/dev/null 2>&1 || true
    session_a_repeat="$FMIX_ACTIVE_SESSION_ROOT"
    if [[ -n "$session_a_root" && "$session_a_repeat" == "$session_a_root" ]]; then
        st_pass "explicit session identity is idempotent across FMix invocations"
    else
        st_fail "explicit session identity did not resolve idempotently"
    fi
    FMIX_ACTIVE_SESSION_HASH="stale-hash"
    FMIX_ACTIVE_SESSION_ROOT="stale-root"
    FMIX_ACTIVE_SESSION_SOURCE="stale-source"
    MIX_DEPS_PATH="/tmp/external-fmix-deps"
    MIX_BUILD_PATH="/tmp/external-fmix-build"
    if fmix_activate_session "$tmp_wt" external-path-failure >/dev/null 2>&1; then
        st_fail "session activation accepted caller-owned artifact paths"
    elif [[ -z "$FMIX_ACTIVE_SESSION_HASH" && -z "$FMIX_ACTIVE_SESSION_ROOT" \
        && -z "$FMIX_ACTIVE_SESSION_SOURCE" \
        && -z "${MIX_DEPS_PATH:-}" && -z "${MIX_BUILD_PATH:-}" ]]; then
        st_pass "pre-activation path rejection clears stale session state"
    else
        st_fail "pre-activation path rejection leaked stale session state"
    fi
    eval "$(declare -f fmix_resolve_session_identity \
        | sed '1s/fmix_resolve_session_identity/fmix_resolve_session_identity_failure_orig/')"
    fmix_resolve_session_identity() {
        printf 'explicit\tidentity-failure\n'
        return 1
    }
    FMIX_ACTIVE_SESSION_HASH="stale-hash"
    FMIX_ACTIVE_SESSION_ROOT="stale-root"
    FMIX_ACTIVE_SESSION_SOURCE="stale-source"
    if fmix_activate_session "$tmp_wt" identity-failure >/dev/null 2>&1; then
        st_fail "session activation accepted an identity resolution failure"
    elif [[ -z "$FMIX_ACTIVE_SESSION_HASH" && -z "$FMIX_ACTIVE_SESSION_ROOT" \
        && -z "$FMIX_ACTIVE_SESSION_SOURCE" \
        && -z "${MIX_DEPS_PATH:-}" && -z "${MIX_BUILD_PATH:-}" ]]; then
        st_pass "identity resolution failure clears stale session state"
    else
        st_fail "identity resolution failure leaked stale session state"
    fi
    eval "$(declare -f fmix_resolve_session_identity_failure_orig \
        | sed '1s/fmix_resolve_session_identity_failure_orig/fmix_resolve_session_identity/')"
    eval "$(declare -f fmix_lock_acquire \
        | sed '1s/fmix_lock_acquire/fmix_lock_acquire_activation_failure_orig/')"
    fmix_lock_acquire() { return 1; }
    if fmix_activate_session "$tmp_wt" lock-failure >/dev/null 2>&1; then
        st_fail "session activation accepted a lease acquisition failure"
    elif [[ -z "$FMIX_ACTIVE_SESSION_HASH" && -z "$FMIX_ACTIVE_SESSION_ROOT" \
        && -z "$FMIX_ACTIVE_SESSION_SOURCE" \
        && -z "${MIX_DEPS_PATH:-}" && -z "${MIX_BUILD_PATH:-}" ]]; then
        st_pass "lease acquisition failure clears resolved session identity"
    else
        st_fail "lease acquisition failure leaked resolved session identity"
    fi
    eval "$(declare -f fmix_lock_acquire_activation_failure_orig \
        | sed '1s/fmix_lock_acquire_activation_failure_orig/fmix_lock_acquire/')"
    eval "$(declare -f fmix_write_session_meta \
        | sed '1s/fmix_write_session_meta/fmix_write_session_meta_failure_orig/')"
    eval "$(declare -f fmix_lock_release \
        | sed '1s/fmix_lock_release/fmix_lock_release_activation_failure_orig/')"
    activation_failure_root=""
    activation_failure_cleanup_marker="$session_test_home/activation-failure-clean-before-unlock"
    fmix_write_session_meta() {
        activation_failure_root="$FMIX_ACTIVE_SESSION_ROOT"
        return 1
    }
    fmix_lock_release() {
        if [[ -n "$activation_failure_root" \
            && "$1" == "session-$FMIX_ACTIVE_SESSION_HASH" \
            && ! -e "$activation_failure_root" ]]; then
            : >"$activation_failure_cleanup_marker"
        fi
        fmix_lock_release_activation_failure_orig "$@"
    }
    if fmix_activate_session "$tmp_wt" activation-failure >/dev/null 2>&1; then
        st_fail "session activation accepted a metadata publication failure"
    elif [[ -z "$FMIX_ACTIVE_SESSION_HASH" && -z "$FMIX_ACTIVE_SESSION_ROOT" \
        && -z "$FMIX_ACTIVE_SESSION_SOURCE" \
        && -z "${MIX_DEPS_PATH:-}" && -z "${MIX_BUILD_PATH:-}" \
        && -n "$activation_failure_root" && ! -e "$activation_failure_root" \
        && -e "$activation_failure_cleanup_marker" ]]; then
        st_pass "failed session activation rolls back partial state under lease"
    else
        st_fail "failed session activation leaked mutable or partial state"
    fi
    eval "$(declare -f fmix_write_session_meta_failure_orig \
        | sed '1s/fmix_write_session_meta_failure_orig/fmix_write_session_meta/')"
    eval "$(declare -f fmix_lock_release_activation_failure_orig \
        | sed '1s/fmix_lock_release_activation_failure_orig/fmix_lock_release/')"

    local activation_create_failure_marker="$session_test_home/activation-create-failure-path"
    eval "$(declare -f fmix_create_session_root \
        | sed '1s/fmix_create_session_root/fmix_create_session_root_failure_orig/')"
    eval "$(declare -f fmix_guard_path \
        | sed '1s/fmix_guard_path/fmix_guard_path_activation_failure_orig/')"
    fmix_create_session_root() { printf 'untrusted-partial-output\n'; return 1; }
    fmix_guard_path() { printf '%s\n' "$1" >"$activation_create_failure_marker"; return 1; }
    if fmix_activate_session "$tmp_wt" create-failure >/dev/null 2>&1; then
        st_fail "session activation accepted a session-root creation failure"
    elif [[ -s "$activation_create_failure_marker" ]] \
        && [[ "$(cat "$activation_create_failure_marker")" == \
            "$session_test_home/sessions/v1/"*/*/* ]] \
        && [[ "$(cat "$activation_create_failure_marker")" != *"untrusted-partial-output"* ]]; then
        st_pass "session-root creation failure preserves the canonical rollback path"
    else
        st_fail "session-root creation failure replaced the canonical rollback path"
    fi
    eval "$(declare -f fmix_create_session_root_failure_orig \
        | sed '1s/fmix_create_session_root_failure_orig/fmix_create_session_root/')"
    eval "$(declare -f fmix_guard_path_activation_failure_orig \
        | sed '1s/fmix_guard_path_activation_failure_orig/fmix_guard_path/')"

    eval "$(declare -f fmix_lock_release \
        | sed '1s/fmix_lock_release/fmix_lock_release_activation_warning_orig/')"
    fmix_lock_release() {
        fmix_lock_release_activation_warning_orig "$@" || true
        return 1
    }
    if fmix_activate_session "$tmp_wt" release-warning >/dev/null 2>&1 \
        && [[ -n "$FMIX_ACTIVE_SESSION_ROOT" \
            && -f "$FMIX_ACTIVE_SESSION_ROOT/meta.json" ]]; then
        st_pass "activation preserves published state after lease metadata retirement failure"
    else
        st_fail "activation discarded published state after lease metadata retirement failure"
    fi
    eval "$(declare -f fmix_lock_release_activation_warning_orig \
        | sed '1s/fmix_lock_release_activation_warning_orig/fmix_lock_release/')"

    session_alias_home="$(mktemp -d /tmp/fmix-self-test.XXXXXX)"
    FMIX_HOME="$session_alias_home"
    unset MIX_BUILD_PATH MIX_DEPS_PATH
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    if fmix_prepare_home \
        && fmix_activate_session "$tmp_wt" tmp-alias >/dev/null 2>&1; then
        session_alias_real="$(fmix_realpath "$session_alias_home")"
        mkdir -p "$MIX_DEPS_PATH/jose/include" "$MIX_BUILD_PATH/lib/jose"
        session_alias_link="$MIX_BUILD_PATH/lib/jose/include"
        session_alias_python="$(fmix_python_bin)"
        session_alias_target="$(
            "$session_alias_python" -c 'import os,sys; print(os.path.relpath(os.path.realpath(sys.argv[2]), sys.argv[1]))' \
                "$(dirname "$session_alias_link")" "$MIX_DEPS_PATH/jose/include"
        )"
        ln -s "$session_alias_target" "$session_alias_link"
        session_alias_resolved="$(fmix_realpath "$session_alias_link" 2>/dev/null || true)"
        if [[ "$FMIX_HOME" == "$session_alias_real" \
            && "$MIX_DEPS_PATH" == "$session_alias_real/"* \
            && "$MIX_BUILD_PATH" == "$session_alias_real/"* \
            && "$session_alias_target" != /* \
            && "$session_alias_target" != *private/tmp* \
            && "$session_alias_resolved" == "$MIX_DEPS_PATH/jose/include" ]]; then
            st_pass "canonical FMIX_HOME keeps /tmp dependency include links portable"
        else
            st_fail "logical /tmp FMIX_HOME produced a non-portable dependency link: home=$FMIX_HOME target=$session_alias_target resolved=$session_alias_resolved"
        fi
    else
        st_fail "logical /tmp FMIX_HOME could not activate a canonical session"
    fi
    [[ -n "$session_alias_home" ]] && rm -rf "$session_alias_home"

    session_cache_real="$(mktemp -d)"
    session_cache_real="$(fmix_realpath "$session_cache_real")"
    session_cache_alias="$session_cache_real-link"
    ln -s "$session_cache_real" "$session_cache_alias"
    mkdir -p "$session_cache_real/templates"
    FMIX_HOME="$session_cache_alias"
    if fmix_prepare_home_readonly \
        && [[ "$FMIX_HOME" == "$session_cache_real" ]] \
        && [[ "$FMIX_HEX_HOME" == "$session_cache_real/hex" ]] \
        && fmix_guard_path "$session_cache_real/templates"; then
        st_pass "read-only cache inspection canonicalizes a symlinked FMIX_HOME"
    else
        st_fail "read-only cache inspection retained an aliased FMIX_HOME or broke path safety"
    fi
    session_cache_missing="$session_cache_real/missing"
    FMIX_HOME="$session_cache_missing"
    if fmix_prepare_home_readonly && [[ ! -e "$session_cache_missing" ]]; then
        st_pass "read-only cache inspection does not create a missing FMIX_HOME"
    else
        st_fail "read-only cache inspection created a missing FMIX_HOME"
    fi
    session_cache_file="$session_cache_real/not-a-directory"
    : >"$session_cache_file"
    FMIX_HOME="$session_cache_file"
    if ! fmix_prepare_home_readonly >/dev/null 2>&1; then
        st_pass "read-only cache inspection rejects a non-directory FMIX_HOME"
    else
        st_fail "read-only cache inspection accepted a non-directory FMIX_HOME"
    fi
    rm -f "$session_cache_file"
    session_cache_dangling="$session_cache_real/dangling-home"
    ln -s "$session_cache_real/missing-target" "$session_cache_dangling"
    FMIX_HOME="$session_cache_dangling"
    if ! fmix_prepare_home_readonly >/dev/null 2>&1; then
        st_pass "read-only cache inspection rejects a dangling FMIX_HOME symlink"
    else
        st_fail "read-only cache inspection accepted a dangling FMIX_HOME symlink"
    fi
    rm -f "$session_cache_dangling"
    rm -f "$session_cache_alias"
    rm -rf "$session_cache_real"
    FMIX_HOME="$session_test_home"
    FMIX_HEX_HOME="$FMIX_HOME/hex"
    unset MIX_BUILD_PATH MIX_DEPS_PATH
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    fmix_activate_session "$tmp_wt" agent-a >/dev/null 2>&1 || true
    if fmix_write_artifact_state "$tmp_wt" 0123456789abcdef \
        && [[ "$(fmix_read_state "$(fmix_artifact_state_file "$tmp_wt")" template_key)" \
            == "0123456789abcdef" ]] \
        && [[ ! -e "$(fmix_worktree_state_file "$tmp_wt")" ]]; then
        st_pass "artifact readiness commits independently from database state"
    else
        st_fail "artifact readiness remained coupled to database publication"
    fi
    FMIX_HOME="$session_saved_home"
    FMIX_HEX_HOME="$FMIX_HOME/hex"
    if [[ "$session_saved_build" == "__unset__" ]]; then
        unset MIX_BUILD_PATH
    else
        MIX_BUILD_PATH="$session_saved_build"
    fi
    if [[ "$session_saved_deps" == "__unset__" ]]; then
        unset MIX_DEPS_PATH
    else
        MIX_DEPS_PATH="$session_saved_deps"
    fi
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    rm -rf "$session_test_home"

    echo ""
    echo "--- Immutable template integrity ---"
    local cas_home cas_saved_home cas_key cas_stage cas_manifest cas_unsafe
    local cas_source cas_materialized cas_priv_target
    cas_home="$(mktemp -d)"
    cas_saved_home="$FMIX_HOME"
    FMIX_HOME="$cas_home"
    cas_key="0123456789abcdef"
    cas_stage="$FMIX_HOME/templates/${cas_key}.tmp-$$"
    mkdir -p "$cas_stage/deps/demo" "$cas_stage/_build/test/lib/demo/ebin"
    printf 'source\n' >"$cas_stage/deps/demo/mix.exs"
    printf 'beam\n' >"$cas_stage/_build/test/lib/demo/ebin/demo.beam"
    cas_manifest="$(fmix_template_write_manifest "$cas_stage" 2>/dev/null)" \
        || cas_manifest=""
    fmix_write_template_meta \
        "$cas_stage" complete now fixture fixture "$cas_key" "$cas_manifest"
    if [[ "$cas_manifest" =~ ^[0-9a-f]{64}$ ]] \
        && fmix_template_make_readonly "$cas_stage" \
        && mv "$cas_stage" "$FMIX_HOME/templates/$cas_key" \
        && chmod a-w "$FMIX_HOME/templates/$cas_key" \
        && fmix_template_verify_full "$cas_key"; then
        st_pass "content-addressed template publishes read-only and passes full verification"
    else
        st_fail "content-addressed template publication or verification failed"
    fi
    chmod u+w "$FMIX_HOME/templates/$cas_key/deps/demo/mix.exs" 2>/dev/null || true
    printf 'tampered\n' >"$FMIX_HOME/templates/$cas_key/deps/demo/mix.exs" 2>/dev/null || true
    if ! fmix_template_verify_full "$cas_key"; then
        st_pass "full cache verification detects post-publication mutation"
    else
        st_fail "full cache verification accepted mutated template content"
    fi
    cas_unsafe="$FMIX_HOME/templates/1111111111111111.tmp-$$"
    mkdir -p "$cas_unsafe/deps" "$cas_unsafe/_build/test/lib/demo"
    ln -s /tmp "$cas_unsafe/_build/test/lib/demo/priv"
    if ! fmix_template_write_manifest "$cas_unsafe" >/dev/null 2>&1 \
        && [[ ! -e "$cas_unsafe/manifest.tsv" ]]; then
        st_pass "template manifest rejects escaping links and propagates validation failure"
    else
        st_fail "template manifest hid an escaping-link validation failure"
    fi
    cas_source="$(mktemp -d)"
    mkdir -p "$cas_source/_build/test/lib/cdrcisco" "$tmp_wt/priv"
    printf 'app private asset\n' >"$tmp_wt/priv/fmix-self-test.txt"
    cas_priv_target="$(
        python3 -c 'import os,sys; print(os.path.relpath(sys.argv[2], sys.argv[1]))' \
            "$cas_source/_build/test/lib/cdrcisco" "$tmp_wt/priv"
    )"
    ln -s "$cas_priv_target" \
        "$cas_source/_build/test/lib/cdrcisco/priv"
    cas_materialized="$FMIX_HOME/templates/2222222222222222.tmp-$$"
    mkdir -p "$cas_materialized/deps"
    fmix_cow_clone "$cas_source/_build" "$cas_materialized/_build"
    if fmix_template_materialize_app_priv \
        "$cas_materialized" "$tmp_wt" "$cas_source/_build" \
        && [[ -d "$cas_materialized/_build/test/lib/cdrcisco/priv" ]] \
        && [[ ! -L "$cas_materialized/_build/test/lib/cdrcisco/priv" ]] \
        && fmix_template_write_manifest "$cas_materialized" >/dev/null 2>&1; then
        st_pass "template publication materializes the exact worktree app priv link"
    else
        st_fail "template publication retained or rejected the exact app priv link"
    fi
    cas_relink="$FMIX_HOME/sessions/relink-self-test-$$"
    mkdir -p "$cas_relink/_build/test/lib/cdrcisco/priv"
    printf 'publisher priv\n' >"$cas_relink/_build/test/lib/cdrcisco/priv/stale.txt"
    if fmix_session_relink_app_priv "$cas_relink/_build" \
        && [[ -L "$cas_relink/_build/test/lib/cdrcisco/priv" ]] \
        && [[ "$(readlink "$cas_relink/_build/test/lib/cdrcisco/priv")" == "../../../../priv" ]] \
        && fmix_session_relink_app_priv "$cas_relink/_build"; then
        st_pass "installed sessions relink the materialized app priv to the checkout"
    else
        st_fail "installed session kept a materialized app priv copy"
    fi
    rm -rf "$cas_relink"
    rm -rf "$cas_source"
    FMIX_HOME="$cas_saved_home"
    chmod -R u+w "$cas_home" 2>/dev/null || true
    rm -rf "$cas_home"
    rm -rf "$tmp_wt"

    echo ""
    echo "--- Stable seed identity ---"
    local self_test_old_home="$FMIX_HOME" self_test_seed_home
    self_test_seed_home="$(mktemp -d)" || return 1
    [[ -n "$self_test_seed_home" && -d "$self_test_seed_home" \
        && ! -L "$self_test_seed_home" ]] || return 1
    # macOS mktemp may return /var while the owned cache requires /private/var.
    # Canonicalize the isolated fixture, not the production safety check.
    self_test_seed_home="$(fmix_realpath "$self_test_seed_home")" || return 1
    FMIX_HOME="$self_test_seed_home"
    fmix_install_snapshot "$self_script" "$self_test_seed_home/.managed-bin" \
        >/dev/null || return 1
    local seed_repo seed_root seed_peer seed_outside producer_sha compat_a compat_b compat_peer
    local compat_absent_a compat_absent_peer
    local fake_seed expected_seed old_fixture_token
    seed_repo="$(mktemp -d)"
    seed_root="${seed_repo}-stable"
    seed_peer="${seed_repo}-peer"
    git -C "$seed_repo" init -q
    git -C "$seed_repo" config user.email fmix-self-test@example.invalid
    git -C "$seed_repo" config user.name fmix-self-test
    printf 'erlang 28.4.1\nelixir 1.19.5-otp-28\n' >"$seed_repo/.tool-versions"
    printf 'defmodule Demo.MixProject do\n  use Mix.Project\n  def project, do: [app: :cdrcisco, deps: deps()]\n  defp deps, do: [{:demo_dep, path: "vendor/demo_dep"}]\n  def token, do: System.get_env("FMIX_STABLE_FIXTURE_TOKEN")\nend\n' >"$seed_repo/mix.exs"
    printf 'LOCKFILE_V1\n' >"$seed_repo/mix.lock"
    mkdir -p "$seed_repo/vendor/demo_dep" "$seed_repo/dev_tools"
    printf 'deps\n_build\n' >"$seed_repo/.gitignore"
    printf 'defmodule DemoDep.MixProject, do: nil\n' >"$seed_repo/vendor/demo_dep/mix.exs"
    printf 'fixture tool\n' >"$seed_repo/dev_tools/tool.exs"
    git -C "$seed_repo" add .gitignore .tool-versions mix.exs mix.lock vendor dev_tools
    git -C "$seed_repo" commit -qm fixture
    git -C "$seed_repo" branch -m fixture-main
    git -C "$seed_repo" worktree add -q -b 0.8.7-stable "$seed_root"
    git -C "$seed_repo" worktree add -q --detach "$seed_peer" HEAD
    mkdir -p "$seed_root/deps/demo_dep" \
        "$seed_root/_build/test/lib/demo_dep/ebin" \
        "$seed_root/_build/test/lib/cdrcisco/.mix" \
        "$seed_root/_build/test/lib/cdrcisco/ebin" \
        "$seed_peer/deps" "$seed_peer/_build/test"
    printf 'demo dependency\n' >"$seed_root/deps/demo_dep/.hex"
    printf 'dependency beam\n' >"$seed_root/_build/test/lib/demo_dep/ebin/demo_dep.beam"
    printf 'compile manifest\n' >"$seed_root/_build/test/lib/cdrcisco/.mix/compile.app"
    printf 'application beam\n' >"$seed_root/_build/test/lib/cdrcisco/ebin/cdrcisco.beam"
    producer_sha="$(git -C "$seed_root" rev-parse HEAD)"

    if declare -F fmix_validate_stable_base >/dev/null \
        && fmix_validate_stable_base 0.8.7-stable \
        && ! fmix_validate_stable_base origin/0.8.7-stable; then
        st_pass "stable seed base accepts only local N.N.N-stable refs"
    else
        st_fail "stable seed base validation helper is missing or accepted a non-local ref"
    fi

    compat_a=""
    compat_peer=""
    if declare -F fmix_stable_seed_compatibility >/dev/null; then
        compat_a="$(fmix_stable_seed_compatibility "$seed_root" 2>/dev/null)" || compat_a=""
        compat_peer="$(fmix_stable_seed_compatibility "$seed_peer" 2>/dev/null)" || compat_peer=""
    fi
    if [[ "$compat_a" =~ ^[0-9a-f]{64}$ && "$compat_a" == "$compat_peer" ]]; then
        st_pass "stable seed compatibility is source-independent across worktree paths"
    else
        st_fail "stable seed compatibility helper is missing, invalid, or path-dependent"
    fi

    mv "$seed_root/dev_tools" "$seed_root/dev_tools.saved"
    mv "$seed_peer/dev_tools" "$seed_peer/dev_tools.saved"
    compat_absent_a="$(fmix_stable_seed_compatibility "$seed_root" 2>/dev/null)" \
        || compat_absent_a=""
    compat_absent_peer="$(fmix_stable_seed_compatibility "$seed_peer" 2>/dev/null)" \
        || compat_absent_peer=""
    if [[ "$compat_absent_a" =~ ^[0-9a-f]{64}$ \
        && "$compat_absent_a" == "$compat_absent_peer" \
        && "$compat_absent_a" != "$compat_a" ]]; then
        st_pass "stable seed compatibility fingerprints an absent optional dev_tools tree"
    else
        st_fail "stable seed compatibility rejected or ignored an absent optional dev_tools tree"
    fi
    mv "$seed_root/dev_tools.saved" "$seed_root/dev_tools"
    mv "$seed_peer/dev_tools.saved" "$seed_peer/dev_tools"

    printf 'changed\n' >>"$seed_root/mix.lock"
    compat_b=""
    if declare -F fmix_stable_seed_compatibility >/dev/null; then
        compat_b="$(fmix_stable_seed_compatibility "$seed_root" 2>/dev/null)" || compat_b=""
    fi
    if [[ -n "$compat_a" && "$compat_a" != "$compat_b" ]]; then
        st_pass "stable seed compatibility changes with dependency inputs"
    else
        st_fail "stable seed compatibility ignored a mix.lock mutation"
    fi
    git -C "$seed_root" checkout -q -- mix.lock

    echo ""
    echo "--- Fingerprinted dependency artifact identity ---"
    local dependency_lane_a dependency_lane_b dependency_lane_other_toolchain
    local dependency_exact_a dependency_exact_b
    local expected_dependency_artifact
    dependency_lane_a=""
    dependency_exact_a="$(fmix_compute_dependency_fingerprint "$seed_root" 2>/dev/null)" \
        || dependency_exact_a=""
    if declare -F fmix_dependency_lane_fingerprint >/dev/null; then
        dependency_lane_a="$(fmix_dependency_lane_fingerprint "$seed_root" 2>/dev/null)" \
            || dependency_lane_a=""
    fi
    printf 'dependency change\n' >>"$seed_root/mix.lock"
    dependency_lane_b=""
    dependency_exact_b="$(fmix_compute_dependency_fingerprint "$seed_root" 2>/dev/null)" \
        || dependency_exact_b=""
    if declare -F fmix_dependency_lane_fingerprint >/dev/null; then
        dependency_lane_b="$(fmix_dependency_lane_fingerprint "$seed_root" 2>/dev/null)" \
            || dependency_lane_b=""
    fi
    git -C "$seed_root" checkout -q -- mix.lock
    if [[ "$dependency_lane_a" =~ ^[0-9a-f]{64}$ \
        && "$dependency_lane_a" == "$dependency_lane_b" \
        && "$dependency_exact_a" =~ ^[0-9a-f]{64}$ \
        && "$dependency_exact_b" =~ ^[0-9a-f]{64}$ \
        && "$dependency_exact_a" != "$dependency_exact_b" ]]; then
        st_pass "dependency lane preserves exact toolchain while exact key tracks dependency changes"
    else
        st_fail "dependency artifact identity did not separate reconciliation lane from exact key"
    fi
    dependency_lane_other_toolchain="$(
        FMIX_TOOLCHAIN_IDENTITY=$'otp=28.4.1\nerts=16.3\nelixir=1.20.3-otp-28\nmix=1.20.4' \
            fmix_dependency_lane_fingerprint "$seed_root" 2>/dev/null
    )" || dependency_lane_other_toolchain=""
    if [[ "$dependency_lane_other_toolchain" =~ ^[0-9a-f]{64}$ \
        && "$dependency_lane_other_toolchain" != "$dependency_lane_a" ]]; then
        st_pass "dependency reconciliation lane fails closed across full toolchain changes"
    else
        st_fail "dependency reconciliation lane ignored a full toolchain change"
    fi

    expected_dependency_artifact="$FMIX_HOME/dependency-artifacts/v1/$dependency_lane_a/$dependency_exact_a"
    if declare -F fmix_dependency_artifact_dir >/dev/null \
        && [[ "$(fmix_dependency_artifact_dir "$dependency_lane_a" "$dependency_exact_a" 2>/dev/null)" \
            == "$expected_dependency_artifact" ]]; then
        st_pass "dependency artifact storage is immutable exact-fingerprint addressed"
    else
        st_fail "dependency artifact path is not lane and exact-fingerprint addressed"
    fi

    old_fixture_token="${FMIX_STABLE_FIXTURE_TOKEN-__unset__}"
    FMIX_STABLE_FIXTURE_TOKEN=changed
    export FMIX_STABLE_FIXTURE_TOKEN
    compat_b=""
    if declare -F fmix_stable_seed_compatibility >/dev/null; then
        compat_b="$(fmix_stable_seed_compatibility "$seed_root" 2>/dev/null)" || compat_b=""
    fi
    if [[ -n "$compat_a" && "$compat_a" != "$compat_b" ]]; then
        st_pass "stable seed compatibility hashes referenced dependency environment"
    else
        st_fail "stable seed compatibility ignored referenced dependency environment"
    fi
    if [[ "$old_fixture_token" == "__unset__" ]]; then
        unset FMIX_STABLE_FIXTURE_TOKEN
    else
        FMIX_STABLE_FIXTURE_TOKEN="$old_fixture_token"
        export FMIX_STABLE_FIXTURE_TOKEN
    fi

    compat_b="$(MIX_BUILD_PATH=/isolated/build MIX_DEPS_PATH=/isolated/deps \
        fmix_stable_seed_compatibility "$seed_root" 2>/dev/null)" || compat_b=""
    if declare -F fmix_stable_seed_compatibility >/dev/null \
        && [[ "$compat_b" == "$compat_a" ]] \
        && ! MIX_TARGET=embedded fmix_stable_seed_compatibility "$seed_root" >/dev/null 2>&1; then
        st_pass "stable seed compatibility ignores isolated storage paths and rejects non-host targets"
    else
        st_fail "stable seed compatibility remained path-bound or accepted a non-host target"
    fi

    compat_b="$(MIX_BUILD_PATH='' MIX_DEPS_PATH='' \
        fmix_stable_seed_compatibility "$seed_root" 2>/dev/null)" || compat_b=""
    if declare -F fmix_stable_seed_compatibility >/dev/null \
        && [[ "$compat_b" == "$compat_a" ]] \
        && ! MIX_TARGET='' fmix_stable_seed_compatibility "$seed_root" >/dev/null 2>&1; then
        st_pass "stable seed compatibility treats storage layout as transport-neutral"
    else
        st_fail "stable seed compatibility let storage location change identity or accepted an empty target"
    fi

    compat_b="$(MIX_BUILD_PATH=_build MIX_DEPS_PATH=deps MIX_TARGET=host \
        fmix_stable_seed_compatibility "$seed_root" 2>/dev/null)" || compat_b=""
    if [[ "$compat_b" == "$compat_a" ]]; then
        st_pass "stable seed compatibility accepts explicit exact-default artifact layouts"
    else
        st_fail "stable seed compatibility changed or rejected explicit exact-default artifact layouts"
    fi

    cp "$seed_root/mix.exs" "$seed_root/mix.exs.fixture"
    sed 's|path: "vendor/demo_dep"|path: "/tmp/demo_dep"|' \
        "$seed_root/mix.exs.fixture" >"$seed_root/mix.exs"
    if declare -F fmix_stable_seed_compatibility >/dev/null \
        && ! fmix_stable_seed_compatibility "$seed_root" >/dev/null 2>&1; then
        st_pass "stable seed compatibility rejects absolute path dependencies"
    else
        st_fail "stable seed compatibility helper is missing or accepted an absolute path dependency"
    fi
    sed 's|path: "vendor/demo_dep"|path: System.get_env("DEMO_DEP_PATH")|' \
        "$seed_root/mix.exs.fixture" >"$seed_root/mix.exs"
    if declare -F fmix_stable_seed_compatibility >/dev/null \
        && ! fmix_stable_seed_compatibility "$seed_root" >/dev/null 2>&1; then
        st_pass "stable seed compatibility rejects unparsable path dependencies"
    else
        st_fail "stable seed compatibility helper is missing or accepted an unparsable path dependency"
    fi

    seed_outside="${seed_repo}-outside"
    mkdir -p "$seed_outside"
    printf 'defmodule OutsideDep.MixProject, do: nil\n' >"$seed_outside/mix.exs"
    sed "s|path: \"vendor/demo_dep\"|path: \"../$(basename "$seed_outside")\"|" \
        "$seed_root/mix.exs.fixture" >"$seed_root/mix.exs"
    if declare -F fmix_stable_seed_compatibility >/dev/null \
        && ! fmix_stable_seed_compatibility "$seed_root" >/dev/null 2>&1; then
        st_pass "stable seed compatibility rejects relative path dependencies outside the worktree"
    else
        st_fail "stable seed compatibility accepted a relative path escape outside the worktree"
    fi

    ln -s "$seed_outside" "$seed_root/linked_dep"
    sed 's|path: "vendor/demo_dep"|path: "linked_dep"|' \
        "$seed_root/mix.exs.fixture" >"$seed_root/mix.exs"
    if declare -F fmix_stable_seed_compatibility >/dev/null \
        && ! fmix_stable_seed_compatibility "$seed_root" >/dev/null 2>&1; then
        st_pass "stable seed compatibility rejects symlinked path dependency traversal"
    else
        st_fail "stable seed compatibility accepted a symlinked path dependency"
    fi
    rm -f "$seed_root/linked_dep"
    mv "$seed_root/mix.exs.fixture" "$seed_root/mix.exs"

    expected_seed="$FMIX_HOME/stable-seeds/v1/cisco-cdr/0.8.7-stable/$producer_sha/$compat_a"
    if declare -F fmix_stable_seed_dir >/dev/null \
        && [[ "$(fmix_stable_seed_dir 0.8.7-stable "$producer_sha" "$compat_a")" == "$expected_seed" ]]; then
        st_pass "stable seed directory is versioned by base, producer, and compatibility"
    else
        st_fail "stable seed directory helper is missing or returned the wrong identity"
    fi

    fake_seed="$(mktemp -d)"
    mkdir -p "$fake_seed/deps" "$fake_seed/_build/test/lib"
    cat >"$fake_seed/meta.json" <<EOF
{
  "schema": "1",
  "base_ref": "0.8.7-stable",
  "producer_ref": "0.8.7-stable",
  "producer_sha": "$producer_sha",
  "compatibility": "$compat_a"
}
EOF
    if declare -F fmix_stable_seed_read_meta >/dev/null \
        && [[ "$(fmix_stable_seed_read_meta "$fake_seed" producer_sha 2>/dev/null)" == "$producer_sha" ]] \
        && declare -F fmix_stable_seed_is_complete >/dev/null \
        && fmix_stable_seed_is_complete "$fake_seed" 0.8.7-stable "$producer_sha" "$compat_a"; then
        st_pass "stable seed accepts a complete exact metadata sidecar"
    else
        st_fail "stable seed metadata helpers are missing or rejected a complete sidecar"
    fi

    ln -s "$fake_seed/deps" "$fake_seed/deps/linked-deps"
    if declare -F fmix_stable_seed_is_complete >/dev/null \
        && ! fmix_stable_seed_is_complete \
            "$fake_seed" 0.8.7-stable "$producer_sha" "$compat_a"; then
        st_pass "stable seed completeness rejects symlinked transport content"
    else
        st_fail "stable seed completeness accepted symlinked transport content"
    fi
    rm -f "$fake_seed/deps/linked-deps"

    mkdir -p "$fake_seed/_build/test/lib/cdrcisco/ebin"
    printf 'producer application beam\n' \
        >"$fake_seed/_build/test/lib/cdrcisco/ebin/cdrcisco.beam"
    printf 'producer dependency stamp\n' >"$fake_seed/dependency-stamp.json"
    printf 'producer compile stamp\n' >"$fake_seed/compile-stamp.json"
    if declare -F fmix_stable_seed_is_complete >/dev/null \
        && ! fmix_stable_seed_is_complete \
            "$fake_seed" 0.8.7-stable "$producer_sha" "$compat_a"; then
        st_pass "stable seed completeness rejects app artifacts and producer state"
    else
        st_fail "stable seed completeness accepted app artifacts or producer state"
    fi
    rm -rf "$fake_seed/_build/test/lib/cdrcisco"
    rm -f "$fake_seed/dependency-stamp.json" "$fake_seed/compile-stamp.json"

    sed "/\"producer_sha\"/a\\
  \"producer_sha\": \"$producer_sha\"," "$fake_seed/meta.json" >"$fake_seed/meta.json.duplicate"
    mv "$fake_seed/meta.json.duplicate" "$fake_seed/meta.json"
    if declare -F fmix_stable_seed_read_meta >/dev/null \
        && ! fmix_stable_seed_read_meta "$fake_seed" producer_sha >/dev/null 2>&1 \
        && declare -F fmix_stable_seed_is_complete >/dev/null \
        && ! fmix_stable_seed_is_complete "$fake_seed" 0.8.7-stable "$producer_sha" "$compat_a"; then
        st_pass "stable seed rejects duplicate metadata fields"
    else
        st_fail "stable seed metadata parser selected a duplicate producer_sha"
    fi

    echo ""
    echo "--- Stable seed publication ---"
    local publish_dep_fingerprint publish_compile_fingerprint publish_seed
    local collision_meta publish_symlink_target status_shim real_git
    local publish_diag publish_rc publish_seed_backup publish_source_deps
    local publish_worktree_lock publish_worktree_id lock_diag
    local snapshot_diag snapshot_rc snapshot_mutated status_diag status_seed_lock
    publish_dep_fingerprint="$(fmix_compute_dependency_fingerprint "$seed_root" 2>/dev/null)" || publish_dep_fingerprint=""
    publish_compile_fingerprint="$(fmix_compute_compile_fingerprint "$seed_root" 2>/dev/null)" || publish_compile_fingerprint=""
    if [[ -n "$publish_dep_fingerprint" && -n "$publish_compile_fingerprint" ]] \
        && fmix_write_dependency_stamp "$seed_root" "$publish_dep_fingerprint" \
        && fmix_write_compile_stamp "$seed_root" "$publish_compile_fingerprint"; then
        st_pass "stable seed publisher fixture has target-local dependency and compile stamps"
    else
        st_fail "stable seed publisher fixture could not create target-local stamps"
    fi

    local dependency_artifact_lane dependency_artifact_path dependency_artifact_file
    local dependency_artifact_access
    local dependency_publish_diag dependency_publish_rc=0
    dependency_artifact_lane="$(fmix_dependency_lane_fingerprint "$seed_root" 2>/dev/null)" \
        || dependency_artifact_lane=""
    dependency_artifact_path="$(fmix_dependency_artifact_dir \
        "$dependency_artifact_lane" "$publish_dep_fingerprint" 2>/dev/null)" \
        || dependency_artifact_path=""
    dependency_publish_diag="$(fmix_publish_dependency_artifact \
        "$seed_root" "$publish_dep_fingerprint" 2>&1)" || dependency_publish_rc=$?
    dependency_artifact_path="$(fmix_dependency_artifact_dir \
        "$dependency_artifact_lane" "$publish_dep_fingerprint" 2>/dev/null)" \
        || dependency_artifact_path=""
    dependency_artifact_access="$FMIX_HOME/artifact-access/v2/dependencies/$dependency_artifact_lane/$publish_dep_fingerprint"
    if [[ -n "$dependency_artifact_path" ]] \
        && (( dependency_publish_rc == 0 )) \
        && fmix_dependency_artifact_verify_full \
            "$dependency_artifact_path" "$dependency_artifact_lane" \
            "$publish_dep_fingerprint" \
        && [[ ! -e "$dependency_artifact_path/_build/test/lib/cdrcisco" ]] \
        && [[ -f "$dependency_artifact_access" ]]; then
        st_pass "exact dependency publisher excludes application artifacts and verifies content"
    else
        st_fail "exact dependency publisher did not produce a verified dependency-only artifact (rc=$dependency_publish_rc): $dependency_publish_diag"
    fi

    dependency_artifact_file="$dependency_artifact_path/deps/demo_dep/.hex"
    chmod u+w "$dependency_artifact_path" "$dependency_artifact_file" 2>/dev/null || true
    printf 'corrupt\n' >>"$dependency_artifact_file" 2>/dev/null || true
    if ! fmix_dependency_artifact_verify_full \
            "$dependency_artifact_path" "$dependency_artifact_lane" \
            "$publish_dep_fingerprint" >/dev/null 2>&1 \
        && fmix_publish_dependency_artifact \
            "$seed_root" "$publish_dep_fingerprint" >/dev/null 2>&1 \
        && fmix_dependency_artifact_verify_full \
            "$dependency_artifact_path" "$dependency_artifact_lane" \
            "$publish_dep_fingerprint"; then
        st_pass "corrupt exact dependency artifacts are quarantined and republished"
    else
        st_fail "dependency artifact corruption was accepted or could not be repaired"
    fi

    local dependency_reconcile_exact dependency_reconcile_lane dependency_reconciler
    git -C "$seed_peer" switch -q -c dependency-change-fixture
    printf 'LOCKFILE_V2\n' >"$seed_peer/mix.lock"
    git -C "$seed_peer" add mix.lock
    git -C "$seed_peer" -c user.email=fmix-self-test@example.invalid \
        -c user.name=fmix-self-test commit -qm 'dependency change fixture'
    dependency_reconcile_exact="$(fmix_compute_dependency_fingerprint \
        "$seed_peer" 2>/dev/null)" || dependency_reconcile_exact=""
    dependency_reconcile_lane="$(fmix_dependency_lane_fingerprint \
        "$seed_peer" 2>/dev/null)" || dependency_reconcile_lane=""
    dependency_reconciler="$(fmix_find_dependency_reconciler \
        "$seed_peer" "$dependency_reconcile_lane" \
        "$dependency_reconcile_exact" 2>/dev/null)" || dependency_reconciler=""
    if [[ "$dependency_reconcile_lane" == "$dependency_artifact_lane" \
        && "$dependency_reconcile_exact" != "$publish_dep_fingerprint" \
        && "$dependency_reconciler" == "$dependency_artifact_path" ]]; then
        st_pass "dependency miss selects the closest clean ancestor only as reconciler input"
    else
        st_fail "dependency reconciler did not select the proven ancestor generation"
    fi

    local saved_active_root="$FMIX_ACTIVE_SESSION_ROOT"
    local saved_mix_deps_path="${MIX_DEPS_PATH-__unset__}"
    local saved_mix_build_path="${MIX_BUILD_PATH-__unset__}"
    local reconcile_session
    reconcile_session="$(mktemp -d)"
    FMIX_ACTIVE_SESSION_ROOT="$reconcile_session"
    MIX_DEPS_PATH="$reconcile_session/deps"
    MIX_BUILD_PATH="$reconcile_session/_build/test"
    mkdir -p "$reconcile_session/deps/old" \
        "$reconcile_session/_build/test/lib/cdrcisco/ebin"
    printf 'old\n' >"$reconcile_session/deps/old/source"
    printf 'app beam\n' \
        >"$reconcile_session/_build/test/lib/cdrcisco/ebin/cdrcisco.beam"
    printf 'stale dependency stamp\n' >"$reconcile_session/dependency-stamp.json"
    printf 'stale compile stamp\n' >"$reconcile_session/compile-stamp.json"
    if [[ -n "$dependency_reconciler" ]] \
        && fmix_install_dependency_artifact \
            "$seed_peer" "$dependency_reconciler" 0 \
        && [[ -f "$reconcile_session/deps/demo_dep/.hex" ]] \
        && [[ -f "$reconcile_session/_build/test/lib/demo_dep/ebin/demo_dep.beam" ]] \
        && [[ -f "$reconcile_session/_build/test/lib/cdrcisco/ebin/cdrcisco.beam" ]] \
        && [[ ! -e "$reconcile_session/dependency-stamp.json" \
            && ! -e "$reconcile_session/compile-stamp.json" ]]; then
        st_pass "reconciler install preserves app candidate but removes every exact-hit claim"
    else
        st_fail "reconciler install was not dependency-only and unproven"
    fi

    local exact_session
    exact_session="$(mktemp -d)"
    FMIX_ACTIVE_SESSION_ROOT="$exact_session"
    MIX_DEPS_PATH="$exact_session/deps"
    MIX_BUILD_PATH="$exact_session/_build/test"
    mkdir -p "$exact_session/_build/test/lib"
    if fmix_install_dependency_artifact \
            "$seed_root" "$dependency_artifact_path" 1 \
        && [[ -f "$exact_session/deps/demo_dep/.hex" ]] \
        && [[ -f "$exact_session/_build/test/lib/demo_dep/ebin/demo_dep.beam" ]] \
        && [[ ! -e "$exact_session/_build/test/lib/cdrcisco" ]] \
        && fmix_dependency_stamp_matches \
            "$seed_root" "$publish_dep_fingerprint"; then
        st_pass "exact dependency consumer verifies dependency-only content and writes its exact stamp"
    else
        st_fail "exact dependency consumer did not establish exact dependency readiness"
    fi

    local interrupt_session interrupt_rc=0
    interrupt_session="$(mktemp -d)"
    FMIX_ACTIVE_SESSION_ROOT="$interrupt_session"
    MIX_DEPS_PATH="$interrupt_session/deps"
    MIX_BUILD_PATH="$interrupt_session/_build/test"
    mkdir -p "$interrupt_session/deps/old" \
        "$interrupt_session/_build/test/lib/cdrcisco/ebin"
    printf 'old\n' >"$interrupt_session/deps/old/source"
    printf 'app beam\n' \
        >"$interrupt_session/_build/test/lib/cdrcisco/ebin/cdrcisco.beam"
    printf 'stale dependency stamp\n' >"$interrupt_session/dependency-stamp.json"
    printf 'stale compile stamp\n' >"$interrupt_session/compile-stamp.json"
    mv() {
        command mv "$@" || return $?
        case "${2:-}" in
            "$interrupt_session"/.dependency-install.*/retired/deps)
                kill -INT $$
                ;;
        esac
    }
    fmix_install_dependency_artifact \
        "$seed_peer" "$dependency_reconciler" 0 \
        >/dev/null 2>&1 || interrupt_rc=$?
    unset -f mv
    if [[ "$interrupt_rc" == "130" \
        && -f "$interrupt_session/deps/old/source" \
        && -f "$interrupt_session/_build/test/lib/cdrcisco/ebin/cdrcisco.beam" \
        && -f "$interrupt_session/dependency-stamp.json" \
        && -f "$interrupt_session/compile-stamp.json" \
        && ! -e "$interrupt_session/deps/demo_dep" ]]; then
        st_pass "interrupted reconciler install rolls back prior session artifacts and stamps"
    else
        st_fail "interrupted reconciler install did not restore the prior session (rc=$interrupt_rc)"
    fi
    FMIX_ACTIVE_SESSION_ROOT="$saved_active_root"
    if [[ "$saved_mix_deps_path" == "__unset__" ]]; then
        unset MIX_DEPS_PATH
    else
        MIX_DEPS_PATH="$saved_mix_deps_path"
    fi
    if [[ "$saved_mix_build_path" == "__unset__" ]]; then
        unset MIX_BUILD_PATH
    else
        MIX_BUILD_PATH="$saved_mix_build_path"
    fi
    rm -rf "$reconcile_session"
    rm -rf "$exact_session"
    rm -rf "$interrupt_session"

    publish_seed="$(fmix_stable_seed_dir 0.8.7-stable "$producer_sha" "$compat_a" 2>/dev/null)" || publish_seed=""
    publish_diag=""
    if declare -F fmix_seed_publish >/dev/null \
        && publish_diag="$(fmix_seed_publish "$seed_root" 0.8.7-stable 2>&1)" \
        && [[ -d "$publish_seed/deps" && -d "$publish_seed/_build/test/lib/demo_dep" ]] \
        && [[ ! -e "$publish_seed/_build/test/lib/cdrcisco" ]] \
        && fmix_seed_publish "$seed_root" 0.8.7-stable; then
        st_pass "stable seed publisher writes immutable dependency-only seed idempotently"
    else
        st_fail "stable seed publisher is missing or did not publish dependency-only seed"
    fi

    if [[ "$publish_diag" != *"$producer_sha"* \
        && "$publish_diag" != *"$compat_a"* \
        && "$publish_diag" != *"$publish_dep_fingerprint"* \
        && "$publish_diag" != *"$publish_compile_fingerprint"* ]]; then
        st_pass "stable seed publish success diagnostics hide fingerprint-derived values"
    else
        st_fail "stable seed publish success diagnostics exposed a fingerprint-derived value"
    fi

    if declare -F cmd_seed >/dev/null && (
        fmix_seed_publish() {
            [[ "$1" == "$(fmix_realpath "$seed_root")" \
                && "$2" == "0.8.7-stable" \
                && -n "$FMIX_ACTIVE_SESSION_ROOT" ]]
        }
        cmd_seed publish --worktree "$seed_root" --session self-test-command \
            --cache-base 0.8.7-stable
    ); then
        st_pass "seed publish command dispatches immutable stable publication"
    else
        st_fail "seed publish command is missing or rejected stable publication"
    fi

    publish_worktree_id="$(fmix_worktree_id "$(fmix_realpath "$seed_root")")"
    publish_worktree_lock="worktree-$publish_worktree_id"
    lock_diag=""
    publish_rc=0
    if fmix_lock_acquire "$publish_worktree_lock" 0; then
        lock_diag="$(FMIX_WORKTREE_LOCK_TIMEOUT=0 \
            fmix_seed_publish "$seed_root" 0.8.7-stable 2>&1)" || publish_rc=$?
        fmix_lock_release "$publish_worktree_lock"
        if (( publish_rc != 0 )) \
            && [[ "$lock_diag" != *"$publish_worktree_id"* \
                && "$lock_diag" != *"$producer_sha"* \
                && "$lock_diag" != *"$compat_a"* ]]; then
            st_pass "stable seed publisher honors the canonical worktree lock without leaking lock fingerprints"
        else
            st_fail "stable seed publisher bypassed the canonical worktree lock or exposed its fingerprint"
        fi
    else
        st_fail "stable seed worktree-lock fixture could not acquire the canonical lock"
    fi

    status_seed_lock="stable-seed-0.8.7-stable-$producer_sha"
    status_diag=""
    if fmix_lock_acquire "$status_seed_lock" 0; then
        eval "$(declare -f fmix_control_psql \
            | sed '1s/fmix_control_psql/fmix_control_psql_seed_status_orig/')"
        fmix_control_psql() { return 1; }
        status_diag="$(cmd_status 2>&1)"
        eval "$(declare -f fmix_control_psql_seed_status_orig \
            | sed '1s/fmix_control_psql_seed_status_orig/fmix_control_psql/')"
        fmix_lock_release "$status_seed_lock"
        if [[ "$status_diag" == *"stable-seed-0.8.7-stable"* \
            && "$status_diag" != *"$producer_sha"* \
            && "$status_diag" != *"$compat_a"* ]]; then
            st_pass "fmix status redacts active stable seed lock fingerprints"
        else
            st_fail "fmix status exposed an active stable seed lock fingerprint"
        fi
    else
        st_fail "stable seed status-lock fixture could not acquire the seed lock"
    fi

    publish_seed_backup="${publish_seed}.source-fixture"
    publish_source_deps="$seed_peer/publish-source-deps"
    if mv "$publish_seed" "$publish_seed_backup" \
        && mv "$seed_root/deps" "$publish_source_deps" \
        && ln -s "$publish_source_deps" "$seed_root/deps"; then
        publish_rc=0
        fmix_seed_publish "$seed_root" 0.8.7-stable >/dev/null 2>&1 || publish_rc=$?
        if (( publish_rc != 0 )) && [[ ! -e "$publish_seed" && ! -L "$publish_seed" ]]; then
            st_pass "fresh stable seed publication rejects a symlinked deps source"
        else
            st_fail "fresh stable seed publication accepted a symlinked deps source"
        fi
        [[ -e "$publish_seed" || -L "$publish_seed" ]] && rm -rf "$publish_seed"
        rm -f "$seed_root/deps"
        mv "$publish_source_deps" "$seed_root/deps"
        mv "$publish_seed_backup" "$publish_seed"
    else
        st_fail "symlinked deps source fixture could not be created"
        [[ -L "$seed_root/deps" ]] && rm -f "$seed_root/deps"
        [[ -e "$publish_source_deps" ]] && mv "$publish_source_deps" "$seed_root/deps"
        [[ -e "$publish_seed_backup" ]] && mv "$publish_seed_backup" "$publish_seed"
    fi

    publish_seed_backup="${publish_seed}.child-fixture"
    if mv "$publish_seed" "$publish_seed_backup" \
        && ln -s "$seed_root/_build/test/lib/demo_dep" \
            "$seed_root/_build/test/lib/linked_dep"; then
        publish_rc=0
        fmix_seed_publish "$seed_root" 0.8.7-stable >/dev/null 2>&1 || publish_rc=$?
        if (( publish_rc != 0 )) && [[ ! -e "$publish_seed" && ! -L "$publish_seed" ]]; then
            st_pass "fresh stable seed publication rejects a symlinked build child"
        else
            st_fail "fresh stable seed publication accepted a symlinked build child"
        fi
        [[ -e "$publish_seed" || -L "$publish_seed" ]] && rm -rf "$publish_seed"
        rm -f "$seed_root/_build/test/lib/linked_dep"
        mv "$publish_seed_backup" "$publish_seed"
    else
        st_fail "symlinked build-child fixture could not be created"
        rm -f "$seed_root/_build/test/lib/linked_dep"
        [[ -e "$publish_seed_backup" ]] && mv "$publish_seed_backup" "$publish_seed"
    fi

    publish_seed_backup="${publish_seed}.build-ancestor-fixture"
    publish_source_deps="$seed_peer/publish-source-build"
    if mv "$publish_seed" "$publish_seed_backup" \
        && mv "$seed_root/_build" "$publish_source_deps" \
        && ln -s "$publish_source_deps" "$seed_root/_build"; then
        if ! fmix_stable_seed_artifacts_are_safe \
            "$seed_root/deps" "$publish_source_deps/test/lib" 1 \
            "$seed_root" "$seed_root/_build"; then
            st_pass "stable seed artifact guard directly rejects a symlinked _build ancestor"
        else
            st_fail "stable seed artifact guard accepted a symlinked _build ancestor"
        fi
        publish_rc=0
        fmix_seed_publish "$seed_root" 0.8.7-stable >/dev/null 2>&1 || publish_rc=$?
        if (( publish_rc != 0 )) && [[ ! -e "$publish_seed" && ! -L "$publish_seed" ]]; then
            st_pass "fresh stable seed publication rejects a symlinked _build ancestor"
        else
            st_fail "fresh stable seed publication accepted a symlinked _build ancestor"
        fi
        [[ -e "$publish_seed" || -L "$publish_seed" ]] && rm -rf "$publish_seed"
        rm -f "$seed_root/_build"
        mv "$publish_source_deps" "$seed_root/_build"
        mv "$publish_seed_backup" "$publish_seed"
    else
        st_fail "symlinked _build-ancestor fixture could not be created"
        [[ -L "$seed_root/_build" ]] && rm -f "$seed_root/_build"
        [[ -e "$publish_source_deps" ]] && mv "$publish_source_deps" "$seed_root/_build"
        [[ -e "$publish_seed_backup" ]] && mv "$publish_seed_backup" "$publish_seed"
    fi

    publish_seed_backup="${publish_seed}.test-ancestor-fixture"
    publish_source_deps="$seed_peer/publish-source-build-test"
    if mv "$publish_seed" "$publish_seed_backup" \
        && mv "$seed_root/_build/test" "$publish_source_deps" \
        && ln -s "$publish_source_deps" "$seed_root/_build/test"; then
        publish_rc=0
        fmix_seed_publish "$seed_root" 0.8.7-stable >/dev/null 2>&1 || publish_rc=$?
        if (( publish_rc != 0 )) && [[ ! -e "$publish_seed" && ! -L "$publish_seed" ]]; then
            st_pass "fresh stable seed publication rejects a symlinked _build/test ancestor"
        else
            st_fail "fresh stable seed publication accepted a symlinked _build/test ancestor"
        fi
        [[ -e "$publish_seed" || -L "$publish_seed" ]] && rm -rf "$publish_seed"
        rm -f "$seed_root/_build/test"
        mv "$publish_source_deps" "$seed_root/_build/test"
        mv "$publish_seed_backup" "$publish_seed"
    else
        st_fail "symlinked _build/test-ancestor fixture could not be created"
        [[ -L "$seed_root/_build/test" ]] && rm -f "$seed_root/_build/test"
        [[ -e "$publish_source_deps" ]] && mv "$publish_source_deps" "$seed_root/_build/test"
        [[ -e "$publish_seed_backup" ]] && mv "$publish_seed_backup" "$publish_seed"
    fi

    publish_seed_backup="${publish_seed}.priv-link-fixture"
    mkdir -p "$seed_root/deps/demo_dep/priv"
    printf 'dependency private asset\n' >"$seed_root/deps/demo_dep/priv/asset.txt"
    if mv "$publish_seed" "$publish_seed_backup" \
        && ln -s ../../../../deps/demo_dep/priv \
            "$seed_root/_build/test/lib/demo_dep/priv"; then
        publish_rc=0
        fmix_seed_publish "$seed_root" 0.8.7-stable >/dev/null 2>&1 || publish_rc=$?
        if (( publish_rc == 0 )) \
            && [[ -d "$publish_seed/_build/test/lib/demo_dep/priv" ]] \
            && [[ ! -L "$publish_seed/_build/test/lib/demo_dep/priv" ]] \
            && [[ "$(cat "$publish_seed/_build/test/lib/demo_dep/priv/asset.txt")" \
                == "dependency private asset" ]] \
            && fmix_stable_seed_is_complete \
                "$publish_seed" 0.8.7-stable "$producer_sha" "$compat_a"; then
            st_pass "stable seed publication materializes contained dependency priv links"
        else
            st_fail "stable seed publication rejected or preserved a contained dependency priv link"
        fi
        [[ -e "$publish_seed" || -L "$publish_seed" ]] && rm -rf "$publish_seed"
        rm -f "$seed_root/_build/test/lib/demo_dep/priv"
        rm -rf "$seed_root/deps/demo_dep/priv"
        mv "$publish_seed_backup" "$publish_seed"
    else
        st_fail "contained dependency priv-link fixture could not be created"
        rm -f "$seed_root/_build/test/lib/demo_dep/priv"
        rm -rf "$seed_root/deps/demo_dep/priv"
        [[ -e "$publish_seed_backup" ]] && mv "$publish_seed_backup" "$publish_seed"
    fi

    publish_seed_backup="${publish_seed}.snapshot-fixture"
    if mv "$publish_seed" "$publish_seed_backup"; then
        eval "$(declare -f fmix_cow_clone \
            | sed '1s/fmix_cow_clone/fmix_cow_clone_publish_snapshot_orig/')"
        snapshot_mutated=0
        fmix_cow_clone() {
            local clone_rc=0
            fmix_cow_clone_publish_snapshot_orig "$@" || clone_rc=$?
            if (( clone_rc == 0 && snapshot_mutated == 0 )); then
                printf 'mutated during publish\n' >>"$seed_root/mix.lock"
                snapshot_mutated=1
            fi
            return "$clone_rc"
        }
        snapshot_rc=0
        snapshot_diag="$(fmix_seed_publish "$seed_root" 0.8.7-stable 2>&1)" \
            || snapshot_rc=$?
        eval "$(declare -f fmix_cow_clone_publish_snapshot_orig \
            | sed '1s/fmix_cow_clone_publish_snapshot_orig/fmix_cow_clone/')"
        if (( snapshot_rc != 0 )) \
            && [[ ! -e "$publish_seed" && ! -L "$publish_seed" ]] \
            && [[ "$snapshot_diag" != *"$producer_sha"* \
                && "$snapshot_diag" != *"$compat_a"* \
                && "$snapshot_diag" != *"$publish_dep_fingerprint"* \
                && "$snapshot_diag" != *"$publish_compile_fingerprint"* ]]; then
            st_pass "stable seed publisher rejects producer mutation during snapshot copy"
        else
            st_fail "stable seed publisher published a raced snapshot or exposed its fingerprints"
        fi
        [[ -e "$publish_seed" || -L "$publish_seed" ]] && rm -rf "$publish_seed"
        git -C "$seed_root" checkout -q -- mix.lock
        mv "$publish_seed_backup" "$publish_seed"
    else
        st_fail "stable seed snapshot-race fixture could not preserve the published seed"
    fi

    mkdir -p "$publish_seed/_build/test/lib/cdrcisco/ebin"
    printf 'producer application beam\n' \
        >"$publish_seed/_build/test/lib/cdrcisco/ebin/cdrcisco.beam"
    printf 'producer dependency stamp\n' >"$publish_seed/dependency-stamp.json"
    publish_rc=0
    publish_diag="$(fmix_seed_publish "$seed_root" 0.8.7-stable 2>&1)" || publish_rc=$?
    if (( publish_rc != 0 )) \
        && ! fmix_stable_seed_is_complete \
            "$publish_seed" 0.8.7-stable "$producer_sha" "$compat_a" \
        && [[ -e "$publish_seed/dependency-stamp.json" ]] \
        && [[ "$publish_diag" != *"$producer_sha"* \
            && "$publish_diag" != *"$compat_a"* \
            && "$publish_diag" != *"$publish_dep_fingerprint"* \
            && "$publish_diag" != *"$publish_compile_fingerprint"* ]]; then
        st_pass "occupied stable seed validation rejects prohibited content without fingerprint diagnostics"
    else
        st_fail "occupied stable seed validation accepted prohibited content or exposed fingerprints"
    fi
    rm -rf "$publish_seed/_build/test/lib/cdrcisco"
    rm -f "$publish_seed/dependency-stamp.json"

    publish_symlink_target="${publish_seed}.symlink-target"
    if [[ -n "$publish_seed" && -d "$publish_seed" ]] \
        && mv "$publish_seed" "$publish_symlink_target" \
        && ln -s "$publish_symlink_target" "$publish_seed"; then
        publish_rc=0
        publish_diag="$(fmix_seed_publish "$seed_root" 0.8.7-stable 2>&1)" || publish_rc=$?
        if declare -F fmix_seed_publish >/dev/null \
            && (( publish_rc != 0 )) \
            && [[ -L "$publish_seed" ]] \
            && [[ "$publish_diag" != *"$producer_sha"* \
                && "$publish_diag" != *"$compat_a"* \
                && "$publish_diag" != *"$publish_dep_fingerprint"* \
                && "$publish_diag" != *"$publish_compile_fingerprint"* ]]; then
            st_pass "stable seed publisher rejects a symlink destination without fingerprint diagnostics"
        else
            st_fail "stable seed publisher accepted a symlink destination or exposed fingerprints"
        fi
        rm -f "$publish_seed"
        mv "$publish_symlink_target" "$publish_seed"
    else
        st_fail "stable seed symlink-destination fixture could not be created"
    fi

    status_shim="$(mktemp -d)"
    real_git="$(command -v git)"
    cat >"$status_shim/git" <<EOF
#!/usr/bin/env bash
if [[ "\${1:-}" == "-C" && "\${3:-}" == "status" ]]; then
    exit 1
fi
exec "$real_git" "\$@"
EOF
    chmod +x "$status_shim/git"
    if declare -F fmix_seed_publish >/dev/null \
        && ! PATH="$status_shim:$PATH" fmix_seed_publish "$seed_root" 0.8.7-stable >/dev/null 2>&1; then
        st_pass "stable seed publisher rejects a failed Git status probe"
    else
        st_fail "stable seed publisher treated a failed Git status probe as clean"
    fi
    rm -rf "$status_shim"

    printf 'dirty\n' >>"$seed_root/mix.lock"
    if declare -F fmix_seed_publish >/dev/null \
        && ! fmix_seed_publish "$seed_root" 0.8.7-stable >/dev/null 2>&1; then
        st_pass "stable seed publisher rejects dirty worktrees"
    else
        st_fail "stable seed publisher accepted a dirty worktree"
    fi
    git -C "$seed_root" checkout -q -- mix.lock

    if declare -F fmix_seed_publish >/dev/null \
        && ! fmix_seed_publish "$seed_peer" 0.8.7-stable >/dev/null 2>&1; then
        st_pass "stable seed publisher rejects detached worktrees"
    else
        st_fail "stable seed publisher accepted a detached worktree"
    fi

    git -C "$seed_root" branch -m 0.8.7-stable 0.8.7-renamed
    if declare -F fmix_seed_publish >/dev/null \
        && ! fmix_seed_publish "$seed_root" 0.8.7-stable >/dev/null 2>&1; then
        st_pass "stable seed publisher rejects a non-base branch"
    else
        st_fail "stable seed publisher accepted a non-base branch"
    fi
    git -C "$seed_root" branch -m 0.8.7-renamed 0.8.7-stable

    rm -f "$(fmix_compile_stamp_file "$seed_root")"
    if declare -F fmix_seed_publish >/dev/null \
        && ! fmix_seed_publish "$seed_root" 0.8.7-stable >/dev/null 2>&1; then
        st_pass "stable seed publisher requires a valid target-local compile stamp"
    else
        st_fail "stable seed publisher accepted a missing target-local compile stamp"
    fi
    fmix_write_compile_stamp "$seed_root" "$publish_compile_fingerprint" >/dev/null 2>&1 || true

    if [[ -n "$publish_seed" && -d "$publish_seed" ]]; then
        collision_meta="$(cat "$publish_seed/meta.json")"
        sed "s/$producer_sha/0000000000000000000000000000000000000000/" \
            "$publish_seed/meta.json" >"$publish_seed/meta.json.conflict"
        mv "$publish_seed/meta.json.conflict" "$publish_seed/meta.json"
        publish_rc=0
        publish_diag="$(fmix_seed_publish "$seed_root" 0.8.7-stable 2>&1)" || publish_rc=$?
        if declare -F fmix_seed_publish >/dev/null \
            && (( publish_rc != 0 )) \
            && ! fmix_stable_seed_is_complete "$publish_seed" 0.8.7-stable "$producer_sha" "$compat_a" \
            && [[ ! -d "${publish_seed}.tmp-$$" ]] \
            && [[ "$publish_diag" != *"$producer_sha"* \
                && "$publish_diag" != *"$compat_a"* \
                && "$publish_diag" != *"$publish_dep_fingerprint"* \
                && "$publish_diag" != *"$publish_compile_fingerprint"* ]]; then
            st_pass "stable seed publisher fails closed on a conflicting destination without fingerprint diagnostics"
        else
            st_fail "stable seed publisher replaced a conflicting destination or exposed fingerprints"
        fi
        printf '%s\n' "$collision_meta" >"$publish_seed/meta.json"
    else
        st_fail "stable seed collision fixture was not published"
    fi

    echo ""
    echo "--- Stable seed consumer restore ---"
    local seed_consumer unrelated_repo unrelated_consumer consumer_sha consumer_short
    local consumer_signature_before
    local explain_out explain_signature_before explain_signature_after saved_meta
    local deps_get_marker compile_marker rollback_consumer rollback_rc
    local rollback_session_root
    local late_interrupt_consumer late_interrupt_rc late_commit_ready
    local v2_fallback_marker recovery_dir

    st_artifact_signature() {
        local root="$1" path
        {
            for path in deps _build; do
                if [[ -L "$root/$path" ]]; then
                    printf 'link:%s:%s\n' "$path" "$(readlink "$root/$path")"
                elif [[ -d "$root/$path" ]]; then
                    find "$root/$path" -mindepth 0 -print 2>/dev/null \
                        | LC_ALL=C sort \
                        | while IFS= read -r file; do
                            if [[ -d "$file" ]]; then
                                printf 'dir:%s\n' "${file#"$root/"}"
                            elif [[ -L "$file" ]]; then
                                printf 'link:%s:%s\n' "${file#"$root/"}" "$(readlink "$file")"
                            elif [[ -f "$file" ]]; then
                                printf 'file:%s:' "${file#"$root/"}"
                                fmix_hash_files "$file"
                            fi
                        done
                else
                    printf 'missing:%s\n' "$path"
                fi
            done
        } | fmix_hash_stdin
    }

    st_restore_miss_untouched() {
        local root="$1" base="$2" before after
        before="$(st_artifact_signature "$root")" || return 1
        if fmix_restore_stable_seed "$root" "$base" >/dev/null 2>&1; then
            return 1
        fi
        after="$(st_artifact_signature "$root")" || return 1
        [[ "$before" == "$after" ]]
    }

    seed_consumer="${seed_repo}-consumer"
    git -C "$seed_repo" worktree add -q -b feature/stable-seed-consumer \
        "$seed_consumer" 0.8.7-stable
    mkdir -p "$seed_consumer/lib"
    printf 'defmodule ConsumerSource, do: :changed\n' >"$seed_consumer/lib/consumer_source.ex"
    git -C "$seed_consumer" add lib/consumer_source.ex
    git -C "$seed_consumer" commit -qm 'consumer source change'
    consumer_sha="$(git -C "$seed_consumer" rev-parse HEAD)"
    consumer_short="${consumer_sha:0:12}"

    # A published seed that gains app-layer or producer-local state after
    # publication is structurally invalid and must cold-miss without touching
    # the consumer.
    mkdir -p "$publish_seed/_build/test/lib/cdrcisco/ebin"
    printf 'producer application beam\n' \
        >"$publish_seed/_build/test/lib/cdrcisco/ebin/cdrcisco.beam"
    printf 'producer dependency stamp\n' >"$publish_seed/dependency-stamp.json"
    printf 'producer compile stamp\n' >"$publish_seed/compile-stamp.json"
    if st_restore_miss_untouched "$seed_consumer" 0.8.7-stable; then
        st_pass "consumer rejects a published seed containing prohibited producer state"
    else
        st_fail "consumer accepted prohibited app artifacts or producer state"
    fi
    rm -rf "$publish_seed/_build/test/lib/cdrcisco"
    rm -f "$publish_seed/dependency-stamp.json" "$publish_seed/compile-stamp.json"

    if declare -F fmix_restore_stable_seed >/dev/null \
        && fmix_restore_stable_seed "$seed_consumer" 0.8.7-stable \
        && [[ -d "$seed_consumer/deps" ]] \
        && [[ -d "$seed_consumer/_build/test/lib/demo_dep" ]] \
        && [[ ! -e "$seed_consumer/_build/test/lib/cdrcisco" ]] \
        && [[ ! -e "$(fmix_compile_stamp_file "$seed_consumer")" ]] \
        && [[ -f "$(fmix_dependency_stamp_file "$seed_consumer")" ]] \
        && [[ "$(fmix_read_state "$(fmix_dependency_stamp_file "$seed_consumer")" path)" == "$(fmix_realpath "$seed_consumer")" ]]; then
        st_pass "descendant restore installs dependency-only artifacts and consumer-local stamps"
    else
        st_fail "descendant restore path is missing or transferred app/producer state"
    fi

    deps_get_marker="$(mktemp -u)/deps-get-called"
    compile_marker="$(mktemp -u)/compile-called"
    eval "$(declare -f fmix_run_deps_get \
        | sed '1s/fmix_run_deps_get/fmix_run_deps_get_consumer_restore_orig/')"
    eval "$(declare -f fmix_run_compile_streamed \
        | sed '1s/fmix_run_compile_streamed/fmix_run_compile_streamed_consumer_restore_orig/')"
    fmix_run_deps_get() {
        mkdir -p "$(dirname "$deps_get_marker")"
        : >"$deps_get_marker"
        return 99
    }
    fmix_run_compile_streamed() {
        local root="$1" log_file="$4"
        mkdir -p "$root/_build/test/lib/cdrcisco/.mix" \
            "$root/_build/test/lib/cdrcisco/ebin" \
            "$(dirname "$compile_marker")"
        printf 'compile manifest\n' >"$root/_build/test/lib/cdrcisco/.mix/compile.app"
        printf 'consumer beam\n' >"$root/_build/test/lib/cdrcisco/ebin/cdrcisco.beam"
        printf 'Compiling 1 file (.ex)\n' >"$log_file"
        : >"$compile_marker"
        return 0
    }
    if [[ -f "$(fmix_dependency_stamp_file "$seed_consumer")" ]] \
        && fmix_ensure_compile "$seed_consumer" demo >/dev/null 2>&1 \
        && [[ ! -e "$deps_get_marker" && -e "$compile_marker" ]]; then
        st_pass "restored dependency stamp skips deps.get but still runs incremental app compile"
    else
        st_fail "restored consumer did not preserve dependency-hit/app-compile behavior"
    fi
    eval "$(declare -f fmix_run_deps_get_consumer_restore_orig \
        | sed '1s/fmix_run_deps_get_consumer_restore_orig/fmix_run_deps_get/')"
    eval "$(declare -f fmix_run_compile_streamed_consumer_restore_orig \
        | sed '1s/fmix_run_compile_streamed_consumer_restore_orig/fmix_run_compile_streamed/')"
    rm -rf "$(dirname "$deps_get_marker")" "$(dirname "$compile_marker")"

    unrelated_repo="$(mktemp -d)"
    unrelated_consumer="${unrelated_repo}-consumer"
    git -C "$unrelated_repo" init -q
    git -C "$unrelated_repo" config user.email fmix-self-test@example.invalid
    git -C "$unrelated_repo" config user.name fmix-self-test
    cp "$seed_consumer/.tool-versions" "$seed_consumer/mix.exs" \
        "$seed_consumer/mix.lock" "$unrelated_repo/"
    cp -R "$seed_consumer/vendor" "$seed_consumer/dev_tools" "$unrelated_repo/"
    printf 'deps\n_build\n' >"$unrelated_repo/.gitignore"
    git -C "$unrelated_repo" add .
    git -C "$unrelated_repo" commit -qm unrelated
    git -C "$unrelated_repo" branch -m 0.8.7-stable
    git -C "$unrelated_repo" worktree add -q -b feature/unrelated \
        "$unrelated_consumer" 0.8.7-stable
    mkdir -p "$unrelated_consumer/deps/sentinel" \
        "$unrelated_consumer/_build/test/lib/sentinel"
    printf 'keep deps\n' >"$unrelated_consumer/deps/sentinel/value"
    printf 'keep build\n' >"$unrelated_consumer/_build/test/lib/sentinel/value"
    if declare -F fmix_restore_stable_seed >/dev/null \
        && st_restore_miss_untouched "$unrelated_consumer" 0.8.7-stable; then
        st_pass "unrelated history is a cold miss and leaves consumer artifacts untouched"
    else
        st_fail "unrelated history restored a seed or mutated consumer artifacts"
    fi

    rm -rf "$seed_consumer/deps" "$seed_consumer/_build"
    mkdir -p "$seed_consumer/deps/sentinel" "$seed_consumer/_build/test/lib/sentinel"
    printf 'keep deps\n' >"$seed_consumer/deps/sentinel/value"
    printf 'keep build\n' >"$seed_consumer/_build/test/lib/sentinel/value"

    mkdir -p "$(dirname "$(fmix_dependency_stamp_file "$seed_consumer")")" \
        "$(dirname "$(fmix_compile_stamp_file "$seed_consumer")")"
    printf 'old consumer dependency stamp\n' \
        >"$(fmix_dependency_stamp_file "$seed_consumer")"
    printf 'old consumer compile stamp\n' \
        >"$(fmix_compile_stamp_file "$seed_consumer")"
    consumer_signature_before="$(st_artifact_signature "$seed_consumer")"

    mv "$seed_consumer/_build" "$seed_consumer/_build.fixture"
    ln -s "_build.fixture" "$seed_consumer/_build"
    consumer_signature_before="$(st_artifact_signature "$seed_consumer")"
    if ! fmix_restore_stable_seed "$seed_consumer" 0.8.7-stable \
        >/dev/null 2>&1 \
        && [[ "$(st_artifact_signature "$seed_consumer")" == "$consumer_signature_before" ]] \
        && [[ "$(cat "$(fmix_dependency_stamp_file "$seed_consumer")")" == "old consumer dependency stamp" ]] \
        && [[ "$(cat "$(fmix_compile_stamp_file "$seed_consumer")")" == "old consumer compile stamp" ]] \
        && [[ -z "$(find "$(dirname "$seed_consumer")" -maxdepth 1 \
            -name '.fmix-stable-restore.*' -print -quit 2>/dev/null)" ]]; then
        st_pass "early restore failure preserves untouched artifacts and stamps"
    else
        st_fail "early restore failure removed untouched artifacts, stamps, or staging"
    fi
    rm -f "$seed_consumer/_build"
    mv "$seed_consumer/_build.fixture" "$seed_consumer/_build"

    consumer_signature_before="$(st_artifact_signature "$seed_consumer")"
    local interrupt_case interrupt_signal expected_interrupt_rc
    local interrupt_rc interrupt_failed interrupt_v2_marker interrupt_failure_detail=""
    local interrupt_diag_file
    local interrupt_session_root interrupt_session_hash interrupt_signature_before
    eval "$(declare -f fmix_cow_clone \
        | sed '1s/fmix_cow_clone/fmix_cow_clone_restore_orig/')"
    interrupt_signal=TERM
    fmix_cow_clone() {
        # The interrupt fixture runs cmd_test in a subshell so a signal cannot
        # terminate the self-test parent. Bash 3.2 has no BASHPID, but that
        # branch skips these in-process signal assertions on macOS anyway.
        kill "-$interrupt_signal" "${BASHPID:-$$}"
        return 1
    }
    if ! fmix_restore_stable_seed "$seed_consumer" 0.8.7-stable \
        >/dev/null 2>&1 \
        && [[ "$(st_artifact_signature "$seed_consumer")" == "$consumer_signature_before" ]] \
        && [[ "$(cat "$(fmix_dependency_stamp_file "$seed_consumer")")" == "old consumer dependency stamp" ]] \
        && [[ "$(cat "$(fmix_compile_stamp_file "$seed_consumer")")" == "old consumer compile stamp" ]] \
        && [[ -z "$(find "$(dirname "$seed_consumer")" -maxdepth 1 \
            -name '.fmix-stable-restore.*' -print -quit 2>/dev/null)" ]]; then
        st_pass "interrupted staging restores traps and leaves consumer state untouched"
    else
        st_fail "interrupted staging leaked temporary or consumer state"
    fi

    interrupt_v2_marker="$(mktemp -u)/v2-fallback-called"
    eval "$(declare -f fmix_preflight \
        | sed '1s/fmix_preflight/fmix_preflight_interrupt_orig/')"
    eval "$(declare -f fmix_check_pg_connections \
        | sed '1s/fmix_check_pg_connections/fmix_check_pg_connections_interrupt_orig/')"
    eval "$(declare -f fmix_ensure_artifacts \
        | sed '1s/fmix_ensure_artifacts/fmix_ensure_artifacts_interrupt_orig/')"
    fmix_preflight() { return 0; }
    fmix_check_pg_connections() { return 0; }
    fmix_ensure_artifacts() {
        mkdir -p "$(dirname "$interrupt_v2_marker")"
        : >"$interrupt_v2_marker"
        return 1
    }
    unset MIX_BUILD_PATH MIX_DEPS_PATH
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    fmix_activate_session "$seed_consumer" restore-interrupt-test >/dev/null 2>&1
    interrupt_session_root="$FMIX_ACTIVE_SESSION_ROOT"
    interrupt_session_hash="$FMIX_ACTIVE_SESSION_HASH"
    cp -R "$seed_consumer/deps" "$interrupt_session_root/deps"
    cp -R "$seed_consumer/_build" "$interrupt_session_root/_build"
    printf 'old consumer dependency stamp\n' \
        >"$interrupt_session_root/dependency-stamp.json"
    printf 'old consumer compile stamp\n' \
        >"$interrupt_session_root/compile-stamp.json"
    interrupt_signature_before="$(st_artifact_signature "$interrupt_session_root")"
    interrupt_failed=0
    interrupt_diag_file="$(mktemp)"
    local interrupt_cases="" interrupt_case_count=0
    # Apple ships Bash 3.2, whose noninteractive signal/trap semantics can
    # terminate this in-process fixture before the restore handler records
    # its conventional status. Keep the full signal assertions on Linux and
    # modern Bash; report the legacy macOS shell gap as an explicit skip.
    if [[ "$FMIX_OS" == "Darwin" && "${BASH_VERSINFO[0]:-0}" -lt 4 ]]; then
        st_skip "restore interrupt assertions require Bash 4+ on macOS"
    else
        interrupt_cases="INT:130 TERM:143"
        interrupt_case_count=2
        # Bash on macOS can inherit an ignored SIGHUP disposition even on
        # newer installations. Keep HUP on Linux and skip only that case.
        if [[ "$FMIX_OS" != "Darwin" ]]; then
            interrupt_cases="$interrupt_cases HUP:129"
            interrupt_case_count=3
        else
            st_skip "HUP restore interrupt has non-deterministic semantics in macOS noninteractive Bash"
        fi
    fi
    for interrupt_case in $interrupt_cases; do
        interrupt_signal="${interrupt_case%%:*}"
        expected_interrupt_rc="${interrupt_case##*:}"
        rm -f "$interrupt_v2_marker"
        unset MIX_BUILD_PATH MIX_DEPS_PATH
        FMIX_ACTIVE_SESSION_HASH=""
        FMIX_ACTIVE_SESSION_ROOT=""
        FMIX_ACTIVE_SESSION_SOURCE=""
        interrupt_rc=0
        ( cmd_test --worktree "$seed_consumer" --session restore-interrupt-test \
            --cache-base 0.8.7-stable -- ) >"$interrupt_diag_file" 2>&1 \
            || interrupt_rc=$?
        if (( interrupt_rc != expected_interrupt_rc )) \
            || [[ -e "$interrupt_v2_marker" ]] \
            || [[ "$(st_artifact_signature "$interrupt_session_root")" != "$interrupt_signature_before" ]] \
            || [[ "$(cat "$interrupt_session_root/dependency-stamp.json")" != "old consumer dependency stamp" ]] \
            || [[ "$(cat "$interrupt_session_root/compile-stamp.json")" != "old consumer compile stamp" ]] \
            || [[ -e "$FMIX_HOME/locks/session-$interrupt_session_hash" ]]; then
            interrupt_failed=1
            interrupt_failure_detail="${interrupt_case}:rc=${interrupt_rc}:marker=$([[ -e "$interrupt_v2_marker" ]] && printf yes || printf no):signature=$([[ "$(st_artifact_signature "$interrupt_session_root")" == "$interrupt_signature_before" ]] && printf same || printf changed):dep=$([[ "$(cat "$interrupt_session_root/dependency-stamp.json" 2>/dev/null)" == "old consumer dependency stamp" ]] && printf same || printf changed):compile=$([[ "$(cat "$interrupt_session_root/compile-stamp.json" 2>/dev/null)" == "old consumer compile stamp" ]] && printf same || printf changed):lock=$([[ -e "$FMIX_HOME/locks/session-$interrupt_session_hash" ]] && printf present || printf clear):diag=$(tail -1 "$interrupt_diag_file")"
        fi
    done
    if (( interrupt_case_count == 0 )); then
        :
    elif (( interrupt_failed == 0 )); then
        st_pass "INT TERM and HUP abort cmd_test after rollback without V2 fallback"
    else
        st_fail "a restore interrupt became a cmd_test cold miss or leaked state ($interrupt_failure_detail)"
    fi
    eval "$(declare -f fmix_preflight_interrupt_orig \
        | sed '1s/fmix_preflight_interrupt_orig/fmix_preflight/')"
    eval "$(declare -f fmix_check_pg_connections_interrupt_orig \
        | sed '1s/fmix_check_pg_connections_interrupt_orig/fmix_check_pg_connections/')"
    eval "$(declare -f fmix_ensure_artifacts_interrupt_orig \
        | sed '1s/fmix_ensure_artifacts_interrupt_orig/fmix_ensure_artifacts/')"
    rm -rf "$(dirname "$interrupt_v2_marker")"
    rm -f "$interrupt_diag_file"
    unset MIX_BUILD_PATH MIX_DEPS_PATH
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    eval "$(declare -f fmix_cow_clone_restore_orig \
        | sed '1s/fmix_cow_clone_restore_orig/fmix_cow_clone/')"

    late_interrupt_consumer="${seed_repo}-late-interrupt-consumer"
    git -C "$seed_repo" worktree add -q --detach \
        "$late_interrupt_consumer" "$consumer_sha"
    eval "$(declare -f fmix_dependency_stamp_matches \
        | sed '1s/fmix_dependency_stamp_matches/fmix_dependency_stamp_matches_late_interrupt_orig/')"
    late_commit_ready=0
    fmix_dependency_stamp_matches() {
        local stamp_rc=0
        fmix_dependency_stamp_matches_late_interrupt_orig "$@" || stamp_rc=$?
        if (( stamp_rc == 0 )); then
            late_commit_ready=1
        fi
        return "$stamp_rc"
    }
    trap() {
        if (( late_commit_ready == 1 )) && [[ "${1:-}" == "-" ]]; then
            late_commit_ready=2
            kill -TERM "$$"
        fi
        # shellcheck disable=SC2064
        builtin trap "$@"
    }
    late_interrupt_rc=0
    fmix_restore_stable_seed "$late_interrupt_consumer" 0.8.7-stable \
        >/dev/null 2>&1 || late_interrupt_rc=$?
    unset -f trap
    eval "$(declare -f fmix_dependency_stamp_matches_late_interrupt_orig \
        | sed '1s/fmix_dependency_stamp_matches_late_interrupt_orig/fmix_dependency_stamp_matches/')"
    if (( late_interrupt_rc == 143 )) \
        && [[ ! -e "$late_interrupt_consumer/deps" ]] \
        && [[ ! -e "$late_interrupt_consumer/_build" ]] \
        && [[ ! -e "$(fmix_dependency_stamp_file "$late_interrupt_consumer")" ]] \
        && [[ ! -e "$(fmix_compile_stamp_file "$late_interrupt_consumer")" ]] \
        && [[ -z "$(find "$(dirname "$late_interrupt_consumer")" -maxdepth 1 \
            -name '.fmix-stable-restore.*' -print -quit 2>/dev/null)" ]]; then
        st_pass "late restore interrupt rolls back and returns a hard-abort status"
    else
        st_fail "late restore interrupt returned success or left committed consumer state"
    fi
    git -C "$seed_repo" worktree remove --force "$late_interrupt_consumer"

    eval "${fmix_write_dependency_stamp_self_test_definition/fmix_write_dependency_stamp/fmix_write_dependency_stamp_restore_orig}"
    fmix_write_dependency_stamp() { return 1; }
    if ! fmix_restore_stable_seed "$seed_consumer" 0.8.7-stable \
        >/dev/null 2>&1 \
        && [[ "$(st_artifact_signature "$seed_consumer")" == "$consumer_signature_before" ]] \
        && [[ "$(cat "$(fmix_dependency_stamp_file "$seed_consumer")")" == "old consumer dependency stamp" ]] \
        && [[ "$(cat "$(fmix_compile_stamp_file "$seed_consumer")")" == "old consumer compile stamp" ]]; then
        st_pass "failed post-selection restore rolls back artifacts and consumer stamps"
    else
        st_fail "failed post-selection restore left partial artifacts or stamp changes"
    fi
    eval "$fmix_write_dependency_stamp_self_test_definition"
    rm -f "$(fmix_dependency_stamp_file "$seed_consumer")" \
        "$(fmix_compile_stamp_file "$seed_consumer")"

    rollback_consumer="${seed_repo}-rollback-consumer"
    git -C "$seed_repo" worktree add -q --detach "$rollback_consumer" "$consumer_sha"
    mkdir -p "$rollback_consumer/deps/sentinel" \
        "$rollback_consumer/_build/test/lib/sentinel" \
        "$(dirname "$(fmix_dependency_stamp_file "$rollback_consumer")")" \
        "$(dirname "$(fmix_compile_stamp_file "$rollback_consumer")")"
    printf 'keep rollback deps\n' >"$rollback_consumer/deps/sentinel/value"
    printf 'keep rollback build\n' >"$rollback_consumer/_build/test/lib/sentinel/value"
    printf 'old rollback dependency stamp\n' \
        >"$(fmix_dependency_stamp_file "$rollback_consumer")"
    printf 'old rollback compile stamp\n' \
        >"$(fmix_compile_stamp_file "$rollback_consumer")"
    v2_fallback_marker="$(mktemp -u)/v2-fallback-called"
    unset MIX_BUILD_PATH MIX_DEPS_PATH
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    fmix_activate_session "$rollback_consumer" rollback-failure-test >/dev/null 2>&1
    rollback_session_root="$FMIX_ACTIVE_SESSION_ROOT"
    cp -R "$rollback_consumer/deps" "$rollback_session_root/deps"
    cp -R "$rollback_consumer/_build" "$rollback_session_root/_build"
    printf 'old rollback dependency stamp\n' \
        >"$rollback_session_root/dependency-stamp.json"
    printf 'old rollback compile stamp\n' \
        >"$rollback_session_root/compile-stamp.json"

    eval "${fmix_write_dependency_stamp_self_test_definition/fmix_write_dependency_stamp/fmix_write_dependency_stamp_rollback_failure_orig}"
    eval "$(declare -f fmix_preflight \
        | sed '1s/fmix_preflight/fmix_preflight_rollback_failure_orig/')"
    eval "$(declare -f fmix_check_pg_connections \
        | sed '1s/fmix_check_pg_connections/fmix_check_pg_connections_rollback_failure_orig/')"
    eval "$(declare -f fmix_ensure_artifacts \
        | sed '1s/fmix_ensure_artifacts/fmix_ensure_artifacts_rollback_failure_orig/')"
    fmix_write_dependency_stamp() { return 1; }
    fmix_preflight() { return 0; }
    fmix_check_pg_connections() { return 0; }
    fmix_ensure_artifacts() {
        mkdir -p "$(dirname "$v2_fallback_marker")"
        : >"$v2_fallback_marker"
        return 1
    }
    mv() {
        case "${1:-}" in
            */old-deps|*/old-lib) return 1 ;;
            *) command mv "$@" ;;
        esac
    }

    unset MIX_BUILD_PATH MIX_DEPS_PATH
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    local rollback_diag_file
    rollback_diag_file="$(mktemp)"
    rollback_rc=0
    if ( cmd_test --worktree "$rollback_consumer" --session rollback-failure-test \
        --cache-base 0.8.7-stable -- ) >"$rollback_diag_file" 2>&1; then
        rollback_rc=0
    else
        rollback_rc=$?
    fi
    recovery_dir="$(find "$rollback_session_root" -maxdepth 1 \
        -name '.fmix-stable-restore.*' -type d -print -quit 2>/dev/null)"
    if (( rollback_rc == 2 )) \
        && [[ ! -e "$v2_fallback_marker" ]] \
        && [[ -n "$recovery_dir" && -d "$recovery_dir" ]]; then
        st_pass "rollback failure aborts test preparation without V2 fallback"
    else
        st_fail "rollback failure was treated as a cold miss or entered V2 fallback (rc=$rollback_rc fallback=$([[ -e "$v2_fallback_marker" ]] && printf yes || printf no) recovery=${recovery_dir:-missing} diag=$(tail -1 "$rollback_diag_file"))"
    fi

    unset -f mv
    eval "$fmix_write_dependency_stamp_self_test_definition"
    eval "$(declare -f fmix_preflight_rollback_failure_orig \
        | sed '1s/fmix_preflight_rollback_failure_orig/fmix_preflight/')"
    eval "$(declare -f fmix_check_pg_connections_rollback_failure_orig \
        | sed '1s/fmix_check_pg_connections_rollback_failure_orig/fmix_check_pg_connections/')"
    eval "$(declare -f fmix_ensure_artifacts_rollback_failure_orig \
        | sed '1s/fmix_ensure_artifacts_rollback_failure_orig/fmix_ensure_artifacts/')"
    rm -f "$rollback_diag_file"
    unset MIX_BUILD_PATH MIX_DEPS_PATH
    FMIX_ACTIVE_SESSION_HASH=""
    FMIX_ACTIVE_SESSION_ROOT=""
    FMIX_ACTIVE_SESSION_SOURCE=""
    if [[ -n "$recovery_dir" && -d "$recovery_dir" ]]; then
        rm -rf "$rollback_consumer/deps" "$rollback_consumer/_build/test/lib"
        [[ -d "$recovery_dir/old-deps" ]] \
            && command mv "$recovery_dir/old-deps" "$rollback_consumer/deps"
        [[ -d "$recovery_dir/old-lib" ]] \
            && command mv "$recovery_dir/old-lib" "$rollback_consumer/_build/test/lib"
        rm -rf "$recovery_dir"
    fi
    rm -rf "$(dirname "$v2_fallback_marker")"
    git -C "$seed_repo" worktree remove --force "$rollback_consumer"

    saved_meta="$(cat "$publish_seed/meta.json")"

    sed 's/"base_ref": "0.8.7-stable"/"base_ref": "0.8.6-stable"/' \
        "$publish_seed/meta.json" >"$publish_seed/meta.json.wrong-base"
    mv "$publish_seed/meta.json.wrong-base" "$publish_seed/meta.json"
    if st_restore_miss_untouched "$seed_consumer" 0.8.7-stable; then
        st_pass "wrong producer/base metadata is a cold miss without artifact mutation"
    else
        st_fail "wrong producer/base metadata mutated consumer artifacts"
    fi
    printf '%s\n' "$saved_meta" >"$publish_seed/meta.json"

    mv "$publish_seed/meta.json" "$publish_seed/meta.json.missing"
    if st_restore_miss_untouched "$seed_consumer" 0.8.7-stable; then
        st_pass "missing metadata is a cold miss without artifact mutation"
    else
        st_fail "missing metadata mutated consumer artifacts"
    fi
    mv "$publish_seed/meta.json.missing" "$publish_seed/meta.json"

    sed "/\"producer_sha\"/a\\
  \"producer_sha\": \"$producer_sha\"," \
        "$publish_seed/meta.json" >"$publish_seed/meta.json.invalid"
    mv "$publish_seed/meta.json.invalid" "$publish_seed/meta.json"
    if st_restore_miss_untouched "$seed_consumer" 0.8.7-stable; then
        st_pass "invalid metadata is a cold miss without artifact mutation"
    else
        st_fail "invalid metadata mutated consumer artifacts"
    fi
    printf '%s\n' "$saved_meta" >"$publish_seed/meta.json"

    printf 'LOCKFILE_V2\n' >"$seed_consumer/mix.lock"
    if st_restore_miss_untouched "$seed_consumer" 0.8.7-stable; then
        st_pass "changed compatibility inputs are a cold miss without artifact mutation"
    else
        st_fail "compatibility miss mutated consumer artifacts"
    fi
    git -C "$seed_consumer" checkout -q -- mix.lock

    if MIX_BUILD_PATH=elsewhere \
        st_restore_miss_untouched "$seed_consumer" 0.8.7-stable; then
        st_pass "non-default artifact layout is a cold miss without artifact mutation"
    else
        st_fail "non-default artifact layout restored or mutated default artifacts"
    fi

    explain_signature_before="$(st_artifact_signature "$seed_consumer")"
    explain_out=""
    if declare -F cmd_cache >/dev/null; then
        explain_out="$(cmd_cache explain --worktree "$seed_consumer" \
            --cache-base 0.8.7-stable 2>/dev/null)" || explain_out=""
    fi
    explain_signature_after="$(st_artifact_signature "$seed_consumer")"
    if [[ "$explain_out" == *"base=0.8.7-stable"* \
        && "$explain_out" == *"consumer=$consumer_short"* \
        && "$explain_out" == *"candidates="* \
        && "$explain_out" == *"hit=ancestor"* \
        && "$explain_out" != *"$compat_a"* \
        && "$explain_out" != *"$producer_sha"* \
        && "$explain_signature_before" == "$explain_signature_after" ]]; then
        st_pass "cache explain reports an ancestor hit read-only without raw digests"
    else
        st_fail "cache explain hit is missing, mutating, or exposes raw seed hashes"
    fi

    explain_out=""
    if declare -F cmd_cache >/dev/null; then
        explain_out="$(cmd_cache explain --worktree "$unrelated_consumer" \
            --cache-base 0.8.7-stable 2>/dev/null)" || true
    fi
    if [[ "$explain_out" == *"miss=ancestry"* \
        && "$explain_out" != *"$compat_a"* \
        && "$explain_out" != *"$producer_sha"* ]]; then
        st_pass "cache explain names ancestry misses without raw digests"
    else
        st_fail "cache explain did not provide a safe named ancestry miss: ${explain_out//$'\n'/, }"
    fi

    unset -f st_artifact_signature st_restore_miss_untouched
    git -C "$seed_repo" worktree remove --force "$seed_consumer"
    git -C "$unrelated_repo" worktree remove --force "$unrelated_consumer"
    rm -rf "$unrelated_repo" "$unrelated_consumer"

    git -C "$seed_repo" worktree remove --force "$seed_root"
    git -C "$seed_repo" worktree remove --force "$seed_peer"
    rm -rf "$seed_repo" "$seed_outside" "$fake_seed"
    FMIX_HOME="$self_test_old_home"
    # Published dependency artifacts are intentionally sealed read-only. Make
    # the fixture tree writable before cleanup so macOS `rm -rf` under the
    # CI shell's inherited `errexit` cannot abort the self-test on teardown.
    chmod -R u+w "$self_test_seed_home" 2>/dev/null || true
    rm -rf "$self_test_seed_home" 2>/dev/null || true

    # 3. DB name guard (ct_fmix_ prefix enforcement)
    echo ""
    echo "--- DB name guard ---"
    if fmix_guard_db_name "ct_fmix_abc12345" 2>/dev/null; then
        st_pass "guard allows generated ct_fmix_<sha8> shape"
    else
        st_fail "guard rejected ct_fmix_abc12345 (should allow)"
    fi

    # strict-shape guard (codex P1): prefix alone is NOT enough — a name with
    # SQL-identifier metacharacters must be rejected even with the prefix
    if fmix_guard_db_name 'ct_fmix_x"; DROP DATABASE postgres;--' 2>/dev/null; then
        st_fail "guard allowed SQL-metachar name (injection risk)"
    else
        st_pass "guard rejects ct_fmix_-prefixed name with SQL metachars"
    fi

    if fmix_guard_db_name "ct_template_test_abc" 2>/tmp/fmix_selftest_guard_$$; then
        st_fail "guard allowed ct_template_test_ prefix (should reject)"
    else
        st_pass "guard rejects non-ct_fmix_ name (ct_template_test_…)"
    fi
    rm -f /tmp/fmix_selftest_guard_$$

    if fmix_guard_template_db_name "ct_template_test_abc" 2>/dev/null; then
        st_fail "template-source guard allowed ct-local-dev namespace"
    else
        st_pass "template-source guard isolates fmix from ct-local-dev databases"
    fi

    if fmix_guard_publish_source_db_name "ct_fmix_abc12345" 2>/dev/null; then
        st_pass "publish-source guard allows exact worktree scratch namespace"
    else
        st_fail "publish-source guard rejected exact worktree scratch namespace"
    fi

    if fmix_guard_publish_source_db_name "ct_fmix_tmpl_abcdef0123456789" 2>/dev/null; then
        st_fail "publish-source guard allowed a published-template name"
    else
        st_pass "publish-source guard rejects non-scratch namespaces"
    fi

    if fmix_guard_db_name "postgres" 2>/dev/null; then
        st_fail "guard allowed 'postgres' (should reject)"
    else
        st_pass "guard rejects 'postgres'"
    fi

    local gc_saved_home gc_home gc_output gc_saved_lock_ttl
    local session_files empty_session_dirs canonical_meta decoy_meta structural_empty artifact_empty
    gc_saved_home="$FMIX_HOME"
    gc_saved_lock_ttl="$FMIX_LOCK_METADATA_TTL_DAYS"
    gc_home="$(mktemp -d)"
    FMIX_HOME="$gc_home"
    mkdir -p "$FMIX_HOME/sessions"
    mkdir -p "$FMIX_HOME/sessions-ancestor-target"
    rmdir "$FMIX_HOME/sessions"
    ln -s "$FMIX_HOME/sessions-ancestor-target" "$FMIX_HOME/sessions"
    if fmix_session_files meta.json >/dev/null 2>&1 \
        || fmix_prepare_session_state_root >/dev/null 2>&1; then
        st_fail "session state accepted a symlinked sessions ancestor"
    else
        st_pass "session state rejects a symlinked sessions ancestor"
    fi
    rm -f "$FMIX_HOME/sessions"
    mkdir -p "$FMIX_HOME/sessions"
    if fmix_session_files meta.json >/dev/null 2>&1; then
        st_fail "session discovery treated a missing v1 state root as empty"
    else
        st_pass "session discovery fails closed when the v1 state root is missing"
    fi
    mkdir -p "$FMIX_HOME/session-root-target"
    ln -s "$FMIX_HOME/session-root-target" "$FMIX_HOME/sessions/v1"
    if fmix_session_files meta.json >/dev/null 2>&1; then
        st_fail "session discovery followed a symlinked v1 state root"
    else
        st_pass "session discovery rejects a symlinked v1 state root"
    fi
    rm -f "$FMIX_HOME/sessions/v1"
    mkdir -p "$FMIX_HOME/sessions/v1/host/1111111111111111/worktree"
    mkdir -p "$FMIX_HOME/session-component-target"
    ln -s "$FMIX_HOME/session-component-target" \
        "$FMIX_HOME/sessions/v1/aaaaaaaaaaaaaaaa"
    if fmix_create_session_root aaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbb cccccccccccccccc \
        >/dev/null 2>&1; then
        st_fail "session root creation followed a symlinked host component"
    else
        st_pass "session root creation rejects symlinked path components"
    fi
    if fmix_session_files meta.json >/dev/null 2>&1; then
        st_fail "session discovery silently skipped a symlinked structural component"
    else
        st_pass "session discovery rejects symlinked structural components"
    fi
    rm -f "$FMIX_HOME/sessions/v1/aaaaaaaaaaaaaaaa"
    cat >"$FMIX_HOME/sessions/v1/host/1111111111111111/worktree/meta.json" <<'EOF'
{
  "session_hash": "1111111111111111",
  "last_used": "2099-01-01T00:00:00Z"
}
EOF
    canonical_meta="$FMIX_HOME/sessions/v1/host/1111111111111111/worktree/meta.json"
    decoy_meta="$FMIX_HOME/sessions/v1/host/1111111111111111/worktree/deps/fixture/meta.json"
    structural_empty="$FMIX_HOME/sessions/v1/host/2222222222222222/worktree"
    artifact_empty="$FMIX_HOME/sessions/v1/host/1111111111111111/worktree/_build/test/lib/fixture/empty"
    mkdir -p "$(dirname "$decoy_meta")" "$structural_empty" "$artifact_empty"
    printf '{}\n' >"$decoy_meta"
    session_files="$(fmix_session_files meta.json)"
    empty_session_dirs="$(fmix_empty_session_dirs)"
    if [[ "$session_files" == *"$canonical_meta"* \
        && "$session_files" != *"$decoy_meta"* \
        && "$empty_session_dirs" == *"$structural_empty"* \
        && "$empty_session_dirs" != *"$artifact_empty"* ]]; then
        st_pass "session housekeeping stays within bounded structural depths"
    else
        st_fail "session housekeeping traversed artifacts or missed structural state"
    fi
    local session_collision_meta="$FMIX_HOME/sessions/v1/4444444444444444/5555555555555555/worktree/meta.json"
    mkdir -p "$(dirname "$session_collision_meta")"
    printf '{}\n' >"$session_collision_meta"
    if fmix_session_metadata_references_hash "$session_collision_meta" "4444444444444444"; then
        st_fail "session reference matching confused the host hash with the session hash"
    elif fmix_session_metadata_references_hash "$session_collision_meta" "5555555555555555"; then
        st_pass "session reference matching parses the exact session path component"
    else
        st_fail "session reference matching missed the exact session path component"
    fi
    local dot_component_meta="$FMIX_HOME/sessions/v1/5555555555555555/6666666666666666/worktree/meta.json"
    mkdir -p "$(dirname "$dot_component_meta")"
    printf '{}\n' >"$dot_component_meta"
    if fmix_session_hash_from_metadata_path \
        "$FMIX_HOME/sessions/v1/./5555555555555555/6666666666666666/worktree/meta.json" \
        >/dev/null 2>&1 \
        || fmix_session_hash_from_metadata_path \
            "$FMIX_HOME/sessions/v1/5555555555555555/6666666666666666/./meta.json" \
            >/dev/null 2>&1; then
        st_fail "session metadata path parsing accepted a dot component"
    else
        st_pass "session metadata path parsing rejects dot components"
    fi
    local legacy_meta="$FMIX_HOME/sessions/v1/host/3333333333333333/worktree/meta.json"
    mkdir -p "$(dirname "$legacy_meta")"
    cat >"$legacy_meta" <<'EOF'
{
  "session_id": "3333333333333333",
  "last_used": "2000-01-01T00:00:00Z"
}
EOF
    if fmix_session_meta_is_expired "$legacy_meta" "3333333333333333" 1; then
        st_pass "under-lease expiry revalidation accepts legacy session identity metadata"
    else
        st_fail "under-lease expiry revalidation rejected legacy session identity metadata"
    fi
    cat >"$legacy_meta" <<'EOF'
{
  "session_hash": "4444444444444444",
  "last_used": "2000-01-01T00:00:00Z"
}
EOF
    if fmix_session_metadata_identity_matches_path "$legacy_meta" \
        || fmix_session_meta_is_expired "$legacy_meta" "4444444444444444" 1; then
        st_fail "session cleanup trusted metadata identity over its canonical path"
    else
        st_pass "session cleanup derives its lease identity from the canonical path"
    fi
    cat >"$legacy_meta" <<'EOF'
{
  "session_hash": "3333333333333333",
  "session_id": "4444444444444444",
  "last_used": "2000-01-01T00:00:00Z"
}
EOF
    if fmix_session_metadata_identity_matches_path "$legacy_meta"; then
        st_fail "session cleanup ignored conflicting metadata identity fields"
    else
        st_pass "session cleanup rejects conflicting metadata identity fields"
    fi
    cat >"$legacy_meta" <<'EOF'
{
  "session_hash": "3333333333333333",
  "session_hash": "4444444444444444",
  "last_used": "2000-01-01T00:00:00Z"
}
EOF
    if fmix_session_metadata_identity_matches_path "$legacy_meta"; then
        st_fail "session cleanup accepted duplicate metadata identity fields"
    else
        st_pass "session cleanup rejects duplicate metadata identity fields"
    fi
    cat >"$legacy_meta" <<'EOF'
{
  "session_id": "3333333333333333",
  "last_used": 946684800
}
EOF
    if fmix_session_meta_is_expired "$legacy_meta" "3333333333333333" 1; then
        st_pass "under-lease expiry revalidation accepts numeric legacy timestamps"
    else
        st_fail "under-lease expiry revalidation rejected a numeric legacy timestamp"
    fi
    eval "$(declare -f fmix_session_files \
        | sed '1s/fmix_session_files/fmix_session_files_scan_orig/')"
    eval "$(declare -f fmix_empty_session_dirs \
        | sed '1s/fmix_empty_session_dirs/fmix_empty_session_dirs_scan_orig/')"
    eval "$(declare -f fmix_drop_db \
        | sed '1s/fmix_drop_db/fmix_drop_db_scan_orig/')"
    local cleanup_attempts=0
    fmix_session_files() { printf '%s\n' "$canonical_meta"; }
    fmix_empty_session_dirs() { return 1; }
    fmix_drop_db() { cleanup_attempts=$(( cleanup_attempts + 1 )); }
    if fmix_purge_expired_sessions 1 >/dev/null 2>&1 \
        || (( cleanup_attempts != 0 )); then
        st_fail "session purge did not fail closed on empty-directory discovery failure"
    else
        st_pass "session purge fails closed before cleanup when discovery fails"
    fi
    fmix_session_files() { return 1; }
    if cmd_gc --reap --yes >/dev/null 2>&1 \
        || (( cleanup_attempts != 0 )); then
        st_fail "GC did not fail closed on session metadata discovery failure"
    else
        st_pass "GC fails closed before cleanup when session discovery fails"
    fi
    eval "$(declare -f fmix_session_files_scan_orig \
        | sed '1s/fmix_session_files_scan_orig/fmix_session_files/')"
    eval "$(declare -f fmix_empty_session_dirs_scan_orig \
        | sed '1s/fmix_empty_session_dirs_scan_orig/fmix_empty_session_dirs/')"
    eval "$(declare -f fmix_drop_db_scan_orig \
        | sed '1s/fmix_drop_db_scan_orig/fmix_drop_db/')"
    eval "$(declare -f fmix_control_psql \
        | sed '1s/fmix_control_psql/fmix_control_psql_gc_orig/')"
    fmix_control_psql() {
        printf 'ct_fmix_s_1111111111111111\nct_fmix_deadbeef\n'
    }
    gc_output="$(cmd_gc 2>&1)"
    if [[ "$gc_output" == *"ORPHAN-DB: ct_fmix_deadbeef"* \
        && "$gc_output" != *"ORPHAN-DB: ct_fmix_s_1111111111111111"* ]]; then
        st_pass "GC preserves session DB references while identifying true orphans"
    else
        st_fail "GC reset or ignored active session DB references"
    fi

    # Reproduce a session publishing metadata after GC's initial snapshot but
    # before its destructive orphan action. The under-lease rescan must see the
    # new reference and preserve the database.
    local revalidate_marker="$FMIX_HOME/revalidate-session-scan"
    local revalidate_drop_marker="$FMIX_HOME/revalidate-session-drop"
    rm -f "$revalidate_marker" "$revalidate_drop_marker"
    fmix_session_files() {
        case "$1" in
            state.json) return 0 ;;
            meta.json)
                if [[ -e "$revalidate_marker" ]]; then
                    printf '%s\n' "$canonical_meta"
                else
                    : >"$revalidate_marker"
                fi
                ;;
        esac
    }
    fmix_control_psql() { printf 'ct_fmix_s_1111111111111111\n'; }
    fmix_drop_db() { : >"$revalidate_drop_marker"; }
    gc_output="$(cmd_gc --reap --yes 2>&1)"
    if [[ ! -e "$revalidate_drop_marker" ]] \
        && [[ "$gc_output" == *"keeping ct_fmix_s_1111111111111111"* ]]; then
        st_pass "GC revalidates session metadata under lease before orphan DB cleanup"
    else
        st_fail "GC dropped a session DB published after its initial metadata snapshot"
    fi
    eval "$(declare -f fmix_session_files_scan_orig \
        | sed '1s/fmix_session_files_scan_orig/fmix_session_files/')"
    eval "$(declare -f fmix_drop_db_scan_orig \
        | sed '1s/fmix_drop_db_scan_orig/fmix_drop_db/')"
    rm -f "$revalidate_marker" "$revalidate_drop_marker"

    fmix_control_psql() { printf 'ct_fmix_s_aaaaaaaaaaaaaaaaaaaa\n'; }
    fmix_drop_db() { : >"$revalidate_drop_marker"; }
    gc_output="$(cmd_gc --reap --yes 2>&1)"
    if [[ ! -e "$revalidate_drop_marker" ]] \
        && [[ "$gc_output" == *"Refusing unleased cleanup for malformed session DB name"* ]]; then
        st_pass "GC preserves malformed session-shaped DB names without an exact lease"
    else
        st_fail "GC routed a malformed session-shaped DB through unleased cleanup"
    fi

    fmix_control_psql() { printf 'ct_fmix_s_aaaaaaaaaaaaaaaa\n'; }
    fmix_drop_db() { : >"$revalidate_drop_marker"; return 1; }
    gc_output="$(cmd_gc --reap --yes 2>&1)"
    if [[ -e "$revalidate_drop_marker" ]] \
        && [[ "$gc_output" == *"Bounded cleanup failed for orphan DB ct_fmix_s_aaaaaaaaaaaaaaaa"* ]]; then
        st_pass "GC retains orphan DBs when bounded cleanup fails"
    else
        st_fail "GC did not preserve or report a failed bounded orphan DB cleanup"
    fi
    eval "$(declare -f fmix_drop_db_scan_orig \
        | sed '1s/fmix_drop_db_scan_orig/fmix_drop_db/')"
    rm -f "$revalidate_drop_marker"

    # Reproduce a stale-session scan racing with a real metadata touch. The
    # lease holder refreshes last_used immediately after GC acquires the lock;
    # GC must re-read it and preserve both the overlay and scratch database.
    cat >"$canonical_meta" <<'EOF'
{
  "session_hash": "1111111111111111",
  "last_used": "2000-01-01T00:00:00Z"
}
EOF
    eval "$(declare -f fmix_lock_acquire \
        | sed '1s/fmix_lock_acquire/fmix_lock_acquire_refresh_orig/')"
    eval "$(declare -f fmix_drop_db \
        | sed '1s/fmix_drop_db/fmix_drop_db_refresh_orig/')"
    fmix_lock_acquire() {
        fmix_lock_acquire_refresh_orig "$@" || return 1
        if [[ "$1" == "session-1111111111111111" ]]; then
            cat >"$canonical_meta" <<'EOF'
{
  "session_hash": "1111111111111111",
  "last_used": "2099-01-01T00:00:00Z"
}
EOF
        fi
    }
    fmix_control_psql() { return 0; }
    fmix_drop_db() { : >"$revalidate_drop_marker"; }
    gc_output="$(cmd_gc --reap --yes 2>&1)"
    if [[ ! -e "$revalidate_drop_marker" && -f "$canonical_meta" ]] \
        && [[ "$gc_output" == *"was refreshed; keeping it"* ]]; then
        st_pass "GC revalidates session expiry under lease before cleanup"
    else
        st_fail "GC deleted a session refreshed after its initial expiry snapshot"
    fi
    eval "$(declare -f fmix_lock_acquire_refresh_orig \
        | sed '1s/fmix_lock_acquire_refresh_orig/fmix_lock_acquire/')"
    eval "$(declare -f fmix_drop_db_refresh_orig \
        | sed '1s/fmix_drop_db_refresh_orig/fmix_drop_db/')"
    rm -f "$revalidate_drop_marker"

    fmix_control_psql() { return 0; }
    mkdir -p \
        "$FMIX_HOME/lock-metadata/released/old-lock" \
        "$FMIX_HOME/lock-metadata/stale/old-lock" \
        "$FMIX_HOME/lock-metadata/released/new-lock"
    touch -t 202001010000 \
        "$FMIX_HOME/lock-metadata/released/old-lock" \
        "$FMIX_HOME/lock-metadata/stale/old-lock"
    FMIX_LOCK_METADATA_TTL_DAYS=7
    local gc_cleanup_rc=0
    cmd_gc --reap --yes >/dev/null 2>&1 || gc_cleanup_rc=$?
    if [[ ! -e "$FMIX_HOME/lock-metadata/released/old-lock" \
        && ! -e "$FMIX_HOME/lock-metadata/stale/old-lock" \
        && -d "$FMIX_HOME/lock-metadata/released/new-lock" ]]; then
        st_pass "GC bounds released and stale lock-metadata retention"
    else
        st_fail "GC retained expired lock metadata or removed a fresh record (rc=$gc_cleanup_rc)"
    fi
    eval "$(declare -f fmix_control_psql_gc_orig \
        | sed '1s/fmix_control_psql_gc_orig/fmix_control_psql/')"
    FMIX_HOME="$gc_saved_home"
    FMIX_LOCK_METADATA_TTL_DAYS="$gc_saved_lock_ttl"
    rm -rf "$gc_home"

    # 4. Content-addressed DB schema manifest.
    echo ""
    echo "--- Content-addressed DB schema selection ---"
    eval "$(declare -f fmix_server_version_num | sed '1s/fmix_server_version_num/fmix_server_version_num_schema_orig/')"
    local schema_wt schema_home schema_manifest schema_manifest2 schema_key1 schema_key2
    schema_wt="$(mktemp -d)"
    schema_home="$(mktemp -d)"
    mkdir -p "$schema_wt/priv/repo/migrations" "$schema_home/db-index"
    git -C "$schema_wt" init -q
    printf 'one\n' >"$schema_wt/priv/repo/migrations/20260101000000_one.exs"
    printf 'two\n' >"$schema_wt/priv/repo/migrations/20260201000000_two.exs"
    schema_manifest="$(mktemp)"
    schema_manifest2="$(mktemp)"
    fmix_server_version_num() { printf '140000\n'; }
    fmix_write_schema_manifest "$schema_wt" "$schema_manifest"
    schema_key1="$(fmix_schema_key_from_manifest "$schema_manifest")"
    printf 'two changed\n' >"$schema_wt/priv/repo/migrations/20260201000000_two.exs"
    fmix_write_schema_manifest "$schema_wt" "$schema_manifest2"
    schema_key2="$(fmix_schema_key_from_manifest "$schema_manifest2")"
    if [[ -n "$schema_key1" && "$schema_key1" != "$schema_key2" ]]; then
        st_pass "DB schema key invalidates when a migration body changes"
    else
        st_fail "DB schema key ignored migration content"
    fi
    printf 'two\n' >"$schema_wt/priv/repo/migrations/20260201000000_two.exs"
    printf 'three\n' >"$schema_wt/priv/repo/migrations/20260301000000_three.exs"
    fmix_write_schema_manifest "$schema_wt" "$schema_manifest2"
    if fmix_manifest_is_prefix "$schema_manifest" "$schema_manifest2"; then
        st_pass "schema selector accepts a content-identical migration prefix"
    else
        st_fail "schema selector rejected a valid content prefix"
    fi
    printf 'one changed\n' >"$schema_wt/priv/repo/migrations/20260101000000_one.exs"
    fmix_write_schema_manifest "$schema_wt" "$schema_manifest2"
    if fmix_manifest_is_prefix "$schema_manifest" "$schema_manifest2"; then
        st_fail "schema selector accepted matching versions with changed SQL"
    else
        st_pass "schema selector rejects matching versions with changed SQL"
    fi
    printf 'one\n' >"$schema_wt/priv/repo/migrations/20260101000000_one.exs"
    fmix_write_schema_manifest "$schema_wt" "$schema_manifest2"
    local schema_old_home="$FMIX_HOME" base1_manifest base2_manifest base1_key base2_key selection_out selector_create_marker scratch_key
    base1_manifest="$(mktemp)"
    base2_manifest="$(mktemp)"
    head -n 1 "$schema_manifest2" >"$base1_manifest"
    head -n 2 "$schema_manifest2" >"$base2_manifest"
    base1_key="$(fmix_schema_key_from_manifest "$base1_manifest")"
    base2_key="$(fmix_schema_key_from_manifest "$base2_manifest")"
    FMIX_HOME="$schema_home"
    scratch_key="$(fmix_schema_key_from_manifest "$schema_manifest2")"
    if fmix_write_worktree_schema_manifest "$schema_wt" "$scratch_key"; then
        printf 'four\n' >"$schema_wt/priv/repo/migrations/20260401000000_four.exs"
        if fmix_worktree_schema_manifest_is_prefix "$schema_wt" "$scratch_key"; then
            st_pass "scratch provenance accepts a newly appended migration delta"
        else
            st_fail "scratch provenance rejected an appended migration delta"
        fi
        printf 'two changed after apply\n' >"$schema_wt/priv/repo/migrations/20260201000000_two.exs"
        if fmix_worktree_schema_manifest_is_prefix "$schema_wt" "$scratch_key"; then
            st_fail "scratch provenance accepted changed already-applied migration content"
        else
            st_pass "scratch provenance rejects changed already-applied migration content"
        fi
        printf 'two\n' >"$schema_wt/priv/repo/migrations/20260201000000_two.exs"
        rm -f "$schema_wt/priv/repo/migrations/20260401000000_four.exs"
    else
        st_fail "scratch provenance manifest could not be published"
    fi
    mkdir -p "$FMIX_HOME/db-index/$base1_key" "$FMIX_HOME/db-index/$base2_key"
    cp "$base1_manifest" "$FMIX_HOME/db-index/$base1_key/manifest.tsv"
    cp "$base2_manifest" "$FMIX_HOME/db-index/$base2_key/manifest.tsv"
    printf '{"base_id":"ct_fmix_tmpl_1111111111111111"}\n' >"$FMIX_HOME/db-index/$base1_key/meta.json"
    printf '{"base_id":"ct_fmix_tmpl_2222222222222222"}\n' >"$FMIX_HOME/db-index/$base2_key/meta.json"
    eval "$(declare -f fmix_base_record_ready | sed '1s/fmix_base_record_ready/fmix_base_record_ready_selector_orig/')"
    eval "$(declare -f fmix_create_database | sed '1s/fmix_create_database/fmix_create_database_selector_orig/')"
    fmix_base_record_ready() { [[ -s "$(fmix_db_index_dir "$1")/manifest.tsv" ]]; }
    selector_create_marker="$schema_home/selector-created-db"
    fmix_create_database() { : >"$selector_create_marker"; }
    selection_out="$(fmix_select_indexed_base "$schema_wt")"
    if [[ "$selection_out" == $'ct_fmix_tmpl_2222222222222222\t'"$base2_key"$'\t1' \
        && ! -e "$selector_create_marker" ]]; then
        st_pass "metadata selector picks the longest valid prefix with zero DB operations"
    else
        st_fail "metadata selector did not choose the longest prefix: '$selection_out'"
    fi

    eval "$(declare -f fmix_snapshot_ready | sed '1s/fmix_snapshot_ready/fmix_snapshot_ready_publish_orig/')"
    fmix_snapshot_ready() { return 0; }
    mv() {
        if [[ "${2:-}" == "$FMIX_HOME/db-index/feedfacefeedface" ]]; then
            return 1
        fi
        command mv "$@"
    }
    if fmix_write_base_record "$schema_wt" ct_fmix_tmpl_feedfacefeedface feedfacefeedface >/dev/null 2>&1; then
        st_fail "metadata publisher hid an atomic rename failure"
    elif [[ ! -e "$FMIX_HOME/db-index/feedfacefeedface" ]] \
        && ! find "$FMIX_HOME/db-index" -maxdepth 1 -name 'feedfacefeedface.tmp-*' -print -quit | grep -q .; then
        st_pass "metadata publisher propagates atomic rename failure and cleans staging"
    else
        st_fail "metadata publisher left partial state after rename failure"
    fi
    unset -f mv
    eval "$(declare -f fmix_snapshot_ready_publish_orig | sed '1s/fmix_snapshot_ready_publish_orig/fmix_snapshot_ready/')"

    eval "$(declare -f fmix_write_worktree_schema_manifest | sed '1s/fmix_write_worktree_schema_manifest/fmix_write_worktree_schema_manifest_state_orig/')"
    fmix_write_worktree_schema_manifest() { return 0; }
    cat() { printf '{\n'; return 1; }
    local partial_state_file
    partial_state_file="$(fmix_worktree_state_file "$schema_wt")"
    if fmix_write_worktree_state "$schema_wt" template db migration now "$scratch_key" base source >/dev/null 2>&1; then
        st_fail "worktree state publisher hid a failed JSON write"
    elif [[ ! -e "$partial_state_file" && ! -e "${partial_state_file}.tmp-$$" ]]; then
        st_pass "worktree state publisher rejects partial JSON and cleans staging"
    else
        st_fail "worktree state publisher left partial JSON after write failure"
    fi
    unset -f cat
    eval "$(declare -f fmix_write_worktree_schema_manifest_state_orig | sed '1s/fmix_write_worktree_schema_manifest_state_orig/fmix_write_worktree_schema_manifest/')"

    eval "$(declare -f fmix_base_record_ready_selector_orig | sed '1s/fmix_base_record_ready_selector_orig/fmix_base_record_ready/')"
    eval "$(declare -f fmix_create_database_selector_orig | sed '1s/fmix_create_database_selector_orig/fmix_create_database/')"
    FMIX_HOME="$schema_old_home"

    local freshness_wt
    freshness_wt="$(mktemp -d)"
    mkdir -p "$freshness_wt/priv/repo/migrations"
    git -C "$freshness_wt" init -q
    git -C "$freshness_wt" config user.email fmix-self-test@example.invalid
    git -C "$freshness_wt" config user.name fmix-self-test
    printf 'migration v1\n' >"$freshness_wt/priv/repo/migrations/20260101000000_one.exs"
    printf 'migration v1\n' >"$freshness_wt/priv/repo/migrations/20260102000000_two.exs"
    cat >"$freshness_wt/priv/repo/structure.sql" <<'EOF'
INSERT INTO public."schema_migrations" (version) VALUES (20260101000000);
INSERT INTO public."schema_migrations" (version) VALUES (20260102000000);
EOF
    git -C "$freshness_wt" add priv/repo
    git -C "$freshness_wt" commit -qm baseline
    if fmix_structure_matches_migration_history "$freshness_wt"; then
        st_pass "cold bootstrap accepts a structure whose recorded versions exactly match on-disk files"
    else
        st_fail "cold bootstrap rejected a structure that is a clean prefix of on-disk files"
    fi

    # API-2846: a migration BODY edit with an UNCHANGED filename/version must
    # still fail closed — this repo's forward-only-repair pattern makes an
    # already-applied migration's body changing (recorded version untouched)
    # a real risk, and #1066's set-based relaxation dropped detection of
    # exactly this case as an "accepted residual risk". The narrower content
    # check (fmix_structure_recorded_migrations_changed) restores it without
    # resurrecting the old ordered-ancestry false positive tested below.
    printf 'migration v2 - body edited, same version\n' \
        >"$freshness_wt/priv/repo/migrations/20260102000000_two.exs"
    git -C "$freshness_wt" add priv/repo/migrations
    git -C "$freshness_wt" commit -qm migration-body-edited-same-version
    if fmix_structure_matches_migration_history "$freshness_wt" >/dev/null 2>&1; then
        st_fail "cold bootstrap wrongly accepted a same-version migration body edit"
    else
        st_pass "cold bootstrap rejects a same-version migration body edit (API-2846 narrowing)"
    fi

    # Restore the original body (the ordinary remediation: revert the edit,
    # or regenerate structure.sql — exercised later below) so the remaining
    # append/backfill scenarios below exercise a clean baseline again, and
    # confirm the gate recovers once the body content matches the snapshot.
    printf 'migration v1\n' >"$freshness_wt/priv/repo/migrations/20260102000000_two.exs"
    git -C "$freshness_wt" add priv/repo/migrations
    git -C "$freshness_wt" commit -qm revert-body-edit
    if fmix_structure_matches_migration_history "$freshness_wt"; then
        st_pass "cold bootstrap recovers once the reverted body matches the snapshot again"
    else
        st_fail "cold bootstrap did not recover after the migration body edit was reverted"
    fi

    # A genuinely NEW migration file (the ordinary, constant state of the
    # repo — new migrations land far more often than structure.sql is
    # regenerated) must be accepted: every recorded version still has an
    # on-disk file.
    printf 'migration v1\n' >"$freshness_wt/priv/repo/migrations/20260103000000_three.exs"
    git -C "$freshness_wt" add priv/repo/migrations
    git -C "$freshness_wt" commit -qm new-migration-after-structure
    if fmix_structure_matches_migration_history "$freshness_wt"; then
        st_pass "cold bootstrap accepts a structure behind HEAD by a clean trailing delta"
    else
        st_fail "cold bootstrap rejected a structure behind HEAD by a clean trailing delta"
    fi

    # The other real-world case that motivated the subset (not ordered-prefix)
    # predicate: an out-of-order backfilled migration whose version number is
    # NUMERICALLY EARLIER than an already-recorded version, added after the
    # fact (exactly what's observed on this repo's real 0.8.7-stable
    # structure.sql — see fmix_structure_matches_migration_history). This is
    # not drift; Ecto.Migrator applies it as ordinary pending work regardless
    # of numeric position, so cold bootstrap must accept it too.
    printf 'migration v1\n' >"$freshness_wt/priv/repo/migrations/20260102500000_backfilled.exs"
    git -C "$freshness_wt" add priv/repo/migrations
    git -C "$freshness_wt" commit -qm backfilled-migration-interleaves-recorded-range
    if fmix_structure_matches_migration_history "$freshness_wt"; then
        st_pass "cold bootstrap accepts an out-of-order backfilled migration (not an ordered prefix)"
    else
        st_fail "cold bootstrap wrongly required an ordered prefix and rejected a backfilled migration"
    fi

    # A GAP — structure.sql records a version with no on-disk file and it is
    # not the one known orphan — must still fail closed.
    printf 'INSERT INTO public."schema_migrations" (version) VALUES (20260199000000);\n' \
        >>"$freshness_wt/priv/repo/structure.sql"
    git -C "$freshness_wt" add priv/repo/structure.sql
    git -C "$freshness_wt" commit -qm structure-records-unknown-version
    if fmix_structure_matches_migration_history "$freshness_wt" >/dev/null 2>&1; then
        st_fail "cold bootstrap accepted a structure recording an unknown, non-orphan version"
    else
        st_pass "cold bootstrap rejects a structure recording an unknown, non-orphan version"
    fi

    # Restore to a clean subset, then verify regeneration (a structure.sql
    # rewritten to record every current on-disk version) is still accepted.
    cat >"$freshness_wt/priv/repo/structure.sql" <<'EOF'
INSERT INTO public."schema_migrations" (version) VALUES (20260101000000);
INSERT INTO public."schema_migrations" (version) VALUES (20260102000000);
INSERT INTO public."schema_migrations" (version) VALUES (20260102500000);
INSERT INTO public."schema_migrations" (version) VALUES (20260103000000);
EOF
    git -C "$freshness_wt" add priv/repo/structure.sql
    git -C "$freshness_wt" commit -qm structure-regenerated
    if fmix_structure_matches_migration_history "$freshness_wt"; then
        st_pass "cold bootstrap accepts regenerated structure provenance"
    else
        st_fail "cold bootstrap rejected regenerated structure provenance"
    fi
    rm -rf "$freshness_wt"

    rm -f "$base1_manifest" "$base2_manifest"
    eval "$(declare -f fmix_server_version_num_schema_orig | sed '1s/fmix_server_version_num_schema_orig/fmix_server_version_num/')"
    rm -rf "$schema_wt" "$schema_home"
    rm -f "$schema_manifest" "$schema_manifest2"

    # 5. Worktree cache scope: aliases of one realpath share state, distinct
    # paths never share path-bound Mix manifests even when contents match.
    echo ""
    echo "--- Worktree cache path safety ---"
    local scope_root scope_a scope_b scope_link id_a id_b id_link
    scope_root="$(mktemp -d)"
    scope_a="$scope_root/a"
    scope_b="$scope_root/b"
    scope_link="$scope_root/a-link"
    mkdir -p "$scope_a" "$scope_b"
    ln -s "$scope_a" "$scope_link"
    id_a="$(fmix_worktree_id "$scope_a")"
    id_b="$(fmix_worktree_id "$scope_b")"
    id_link="$(fmix_worktree_id "$scope_link")"
    if [[ "$id_a" != "$id_b" && "$id_a" == "$id_link" ]]; then
        st_pass "cache identity is canonical-realpath scoped"
    else
        st_fail "cache identity crossed paths or split a realpath alias: a=$id_a b=$id_b link=$id_link"
    fi

    eval "$(declare -f fmix_template_is_complete | sed '1s/fmix_template_is_complete/fmix_template_is_complete_adopt_orig/')"
    eval "$(declare -f fmix_build_template | sed '1s/fmix_build_template/fmix_build_template_adopt_orig/')"
    local scope_old_home="$FMIX_HOME" adoption_marker="$scope_root/adoption-build-called"
    FMIX_HOME="$scope_root/home"
    mkdir -p "$scope_a/deps" "$scope_a/_build"
    fmix_template_is_complete() { return 1; }
    fmix_build_template() { : >"$adoption_marker"; }
    if ! fmix_ensure_artifacts "$scope_a" deadbeefdeadbeef 0 >/dev/null 2>&1 \
        && [[ ! -e "$adoption_marker" ]]; then
        st_pass "normal test rejects artifacts without ABI provenance"
    else
        st_fail "normal test accepted artifacts without ABI provenance"
    fi
    fmix_ensure_artifacts "$scope_a" deadbeefdeadbeef 1 >/dev/null 2>&1 || true
    if [[ -e "$adoption_marker" && -d "$scope_a/deps" && -d "$scope_a/_build" ]] \
        && ! compgen -G "$scope_a/_build.fmix-stale.*" >/dev/null; then
        st_pass "explicit setup never promotes or mutates unproven checkout artifacts"
    else
        st_fail "explicit setup promoted or moved unproven checkout artifacts"
    fi
    FMIX_HOME="$scope_old_home"
    eval "$(declare -f fmix_template_is_complete_adopt_orig | sed '1s/fmix_template_is_complete_adopt_orig/fmix_template_is_complete/')"
    eval "$(declare -f fmix_build_template_adopt_orig | sed '1s/fmix_build_template_adopt_orig/fmix_build_template/')"
    rm -rf "$scope_root"

    echo ""
    echo "--- Compile content/config stamp ---"
    eval "$fmix_write_dependency_stamp_self_test_definition"
    local compile_root compile_copy compile_home compile_external fp_before fp_after fp_changed fp_other gitfile_repo
    local dep_before dep_after source_deps_marker source_compile_marker source_compile_out
    local dependency_env_out dependency_env_before dependency_env_after space_root no_deps_root old_db_password
    local check_out
    local old_fmix_home="$FMIX_HOME" old_mix_build_path="${MIX_BUILD_PATH-__unset__}"
    local old_mix_deps_path="${MIX_DEPS_PATH-__unset__}"
    local old_unrelated_token="${FMIX_UNRELATED_SESSION_TOKEN-__unset__}"
    local old_compiler_workers="${ELIXIR_COMPILER_WORKERS-__unset__}"
    compile_root="$(mktemp -d)"
    compile_copy="$(mktemp -d)"
    compile_home="$(mktemp -d)"
    compile_external="$compile_home/external dependency"
    FMIX_HOME="$compile_home"
    MIX_BUILD_PATH="_build"
    mkdir -p "$compile_root/config" "$compile_root/lib" "$compile_root/test/support" \
        "$compile_root/test/ordinary" "$compile_root/priv/repo" \
        "$compile_root/_build/test/lib/cdrcisco/.mix" \
        "$compile_root/_build/test/lib/cdrcisco/ebin" \
        "$compile_root/deps/demo_dep"
    mkdir -p "$compile_external/lib"
    printf 'erlang 28.4.1\nelixir 1.19.5-otp-28\n' >"$compile_root/.tool-versions"
    printf 'defmodule Demo.MixProject, do: nil\n@build_path "_build"\n@deps_path "deps"\nSystem.get_env("2FA_KEY")\nSystem.get_env("FMIX_TEST_DEP_ENV")\nSystem.get_env("http_proxy")\nSystem.get_env "NO_PAREN_ENV"\nSystem.get_env(\n  "MULTILINE_ENV"\n)\n# System.get_env("COMMENTED_ENV")\n{:external_dep, path: "%s"}\n' \
        "$compile_external" >"$compile_root/mix.exs"
    printf 'defmodule ExternalDep.MixProject, do: nil\n' >"$compile_external/mix.exs"
    printf 'defmodule ExternalDep.Source, do: :original\n' >"$compile_external/lib/source.ex"
    printf 'lock\n' >"$compile_root/mix.lock"
    printf 'config\n' >"$compile_root/config/config.exs"
    printf 'defmodule DemoDep.MixProject, do: nil\n' >"$compile_root/deps/demo_dep/mix.exs"
    printf 'test hex marker\n' >"$compile_root/deps/demo_dep/.hex"

    dependency_env_out="$(fmix_dependency_environment "$compile_root")"
    if [[ "$dependency_env_out" == *"2FA_KEY="* \
        && "$dependency_env_out" == *"http_proxy="* ]]; then
        st_pass "dependency environment accepts digit-prefixed and lowercase names"
    else
        st_fail "dependency environment rejected a digit-prefixed name"
    fi
    if [[ "$dependency_env_out" == *"NO_PAREN_ENV="* \
        && "$dependency_env_out" == *"MULTILINE_ENV="* \
        && "$dependency_env_out" != *"COMMENTED_ENV="* ]]; then
        st_pass "environment discovery handles multiline and parenthesis-free calls"
    else
        st_fail "environment discovery missed formatted calls or included a full-line comment"
    fi
    dependency_env_before="$(fmix_compute_dependency_fingerprint "$compile_root")"
    FMIX_TEST_DEP_ENV=changed
    export FMIX_TEST_DEP_ENV
    dependency_env_after="$(fmix_compute_dependency_fingerprint "$compile_root")"
    unset FMIX_TEST_DEP_ENV
    if [[ "$dependency_env_before" != "$dependency_env_after" ]]; then
        st_pass "dependency fingerprint invalidates on a referenced environment change"
    else
        st_fail "dependency fingerprint ignored a referenced environment change"
    fi
    space_root="$compile_home/worktree with spaces"
    mkdir -p "$space_root"
    printf 'System.get_env("SPACE_PATH_ENV")\n' >"$space_root/mix.exs"
    if [[ "$(fmix_dependency_environment "$space_root")" == *"SPACE_PATH_ENV="* ]]; then
        st_pass "dependency environment handles worktree paths containing spaces"
    else
        st_fail "dependency environment split a worktree path containing spaces"
    fi
    old_db_password="$DB_PASSWORD"
    DB_PASSWORD=$'secret\nINJECTED_ENV_NAME'
    dependency_env_out="$(fmix_compile_environment "$compile_root")"
    DB_PASSWORD="$old_db_password"
    if [[ "$dependency_env_out" != *"secret"* \
        && "$dependency_env_out" != *"INJECTED_ENV_NAME"* ]]; then
        st_pass "compile environment hashes newline-bearing values without stream injection"
    else
        st_fail "compile environment leaked or reinterpreted a newline-bearing value"
    fi
    dep_before="$(fmix_compute_dependency_fingerprint "$compile_root")"
    printf 'defmodule ExternalDep.MixProject, do: :new_requirements\n' \
        >"$compile_external/mix.exs"
    dep_after="$(fmix_compute_dependency_fingerprint "$compile_root")"
    if [[ -n "$dep_before" && "$dep_before" != "$dep_after" ]]; then
        st_pass "dependency fingerprint invalidates on external path dependency manifest edits"
    else
        st_fail "dependency fingerprint ignored external path dependency requirements"
    fi
    printf 'defmodule ExternalDep.MixProject, do: nil\n' >"$compile_external/mix.exs"

    dep_before="$(fmix_compute_dependency_fingerprint "$compile_root")"
    fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    printf 'defmodule ExternalDep.Source, do: :changed\n' >"$compile_external/lib/source.ex"
    fp_after="$(fmix_compute_compile_fingerprint "$compile_root")"
    dep_after="$(fmix_compute_dependency_fingerprint "$compile_root")"
    if [[ -n "$fp_before" && "$fp_before" != "$fp_after" \
        && "$dep_before" == "$dep_after" ]]; then
        st_pass "external path source edits compile without re-resolving dependencies"
    else
        st_fail "external path source edit invalidation crossed the compile/dependency boundary"
    fi
    printf 'defmodule ExternalDep.Source, do: :original\n' >"$compile_external/lib/source.ex"

    no_deps_root="$compile_home/no-dependencies"
    mkdir -p "$no_deps_root"
    printf 'defmodule NoDeps.MixProject, do: nil\n' >"$no_deps_root/mix.exs"
    if [[ -n "$(fmix_dependency_source_guard "$no_deps_root")" ]]; then
        st_pass "dependency guard records a stable dependency-free state"
    else
        st_fail "dependency guard rejected a project with no dependencies"
    fi

    fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    FMIX_UNRELATED_SESSION_TOKEN="rotated-agent-session-value"
    fp_after="$(fmix_compute_compile_fingerprint "$compile_root")"
    if [[ "$fp_before" == "$fp_after" ]]; then
        st_pass "compile stamp ignores unrelated caller/session environment"
    else
        st_fail "compile stamp changed for unrelated caller/session environment"
    fi
    dep_before="$(fmix_compute_dependency_fingerprint "$compile_root")"
    ELIXIR_COMPILER_WORKERS=7
    fp_changed="$(fmix_compute_compile_fingerprint "$compile_root")"
    if [[ "$fp_changed" != "$fp_before" ]]; then
        st_pass "compile stamp invalidates on effective compiler environment"
    else
        st_fail "compile stamp ignored effective compiler environment"
    fi
    dep_after="$(fmix_compute_dependency_fingerprint "$compile_root")"
    if [[ "$dep_after" == "$dep_before" ]]; then
        st_pass "dependency stamp ignores compiler-only environment changes"
    else
        st_fail "dependency stamp changed for compiler-only environment"
    fi
    if [[ "$old_compiler_workers" == "__unset__" ]]; then
        unset ELIXIR_COMPILER_WORKERS
    else
        ELIXIR_COMPILER_WORKERS="$old_compiler_workers"
    fi
    printf 'defmodule Demo, do: nil\n' >"$compile_root/lib/demo.ex"
    printf 'support\n' >"$compile_root/test/support/support.ex"
    printf 'test only\n' >"$compile_root/test/ordinary/demo_test.exs"
    printf 'manifest\n' >"$compile_root/_build/test/lib/cdrcisco/.mix/compile.elixir"
    printf 'beam\n' >"$compile_root/_build/test/lib/cdrcisco/ebin/Elixir.Demo.beam"

    fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    touch "$compile_root/lib/demo.ex"
    printf 'test only changed\n' >"$compile_root/test/ordinary/demo_test.exs"
    fp_after="$(fmix_compute_compile_fingerprint "$compile_root")"
    if [[ -n "$fp_before" && "$fp_before" == "$fp_after" ]]; then
        st_pass "compile stamp ignores mtimes and ordinary test-file content"
    else
        st_fail "compile stamp changed for mtime/test-only edits"
    fi

    printf 'defmodule Demo, do: :changed\n' >"$compile_root/lib/demo.ex"
    fp_changed="$(fmix_compute_compile_fingerprint "$compile_root")"
    if [[ "$fp_changed" != "$fp_before" ]]; then
        st_pass "compile stamp invalidates on production source content"
    else
        st_fail "compile stamp ignored production source content"
    fi
    printf 'defmodule Demo, do: nil\n' >"$compile_root/lib/demo.ex"
    printf 'config changed\n' >"$compile_root/config/config.exs"
    fp_changed="$(fmix_compute_compile_fingerprint "$compile_root")"
    if [[ "$fp_changed" != "$fp_before" ]]; then
        st_pass "compile stamp invalidates on config content"
    else
        st_fail "compile stamp ignored config content"
    fi
    printf 'config\n' >"$compile_root/config/config.exs"

    cp -R "$compile_root/." "$compile_copy/"
    fp_other="$(fmix_compute_compile_fingerprint "$compile_copy")"
    if [[ "$fp_other" != "$fp_before" ]]; then
        st_pass "compile stamp refuses cross-realpath app reuse"
    else
        st_fail "compile stamp matched across distinct realpaths"
    fi

    fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    dep_before="$(fmix_compute_dependency_fingerprint "$compile_root")"
    if fmix_write_dependency_stamp "$compile_root" "$dep_before" \
        && fmix_write_compile_stamp "$compile_root" "$fp_before" \
        && fmix_compile_stamp_matches "$compile_root" "$fp_before"; then
        st_pass "compile stamp restores readiness for unchanged same-path artifacts"
    else
        st_fail "compile stamp did not match unchanged same-path artifacts"
    fi

    local current_template_key previous_template_key legacy_template_key
    local legacy_dependency_fingerprint legacy_compile_fingerprint
    # This compile-stamp fixture intentionally includes an absolute external
    # path dependency to exercise path-bound invalidation. Such a checkout is
    # correctly ineligible for a portable template key, so use a valid
    # synthetic storage key for the independent state-adoption tests below.
    current_template_key="bbbbbbbbbbbbbbbb"
    previous_template_key="aaaaaaaaaaaaaaaa"
    fmix_write_worktree_state \
        "$compile_root" "$previous_template_key" ct_fmix_deadbeef migration now
    local adoption_output adoption_rc=0 adoption_dep_match=0 adoption_compile_match=0
    adoption_output="$(fmix_ensure_artifacts \
        "$compile_root" "$current_template_key" 0 2>&1)" || adoption_rc=$?
    fmix_dependency_stamp_matches \
        "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")" \
        && adoption_dep_match=1
    fmix_compile_stamp_matches \
        "$compile_root" "$(fmix_compute_compile_fingerprint "$compile_root")" \
        && adoption_compile_match=1
    if (( adoption_rc == 0 )) \
        && [[ "$(fmix_read_state "$(fmix_artifact_state_file "$compile_root")" template_key)" \
            == "$current_template_key" ]] \
        && (( adoption_dep_match == 1 && adoption_compile_match == 1 )); then
        st_pass "template storage-key changes adopt current worktree stamps without cloning"
    else
        st_fail "template storage-key change invalidated compatible current artifacts (rc=$adoption_rc dep=$adoption_dep_match compile=$adoption_compile_match state=$(fmix_read_state "$(fmix_artifact_state_file "$compile_root")" template_key 2>/dev/null) output=${adoption_output//$'\n'/, })"
    fi

    legacy_template_key="$(fmix_compute_legacy_template_key_v2 "$compile_root")"
    legacy_dependency_fingerprint="$(
        fmix_compute_legacy_dependency_fingerprint_v1 "$compile_root"
    )"
    legacy_compile_fingerprint="$(
        fmix_compute_legacy_compile_fingerprint_v2 "$compile_root"
    )"
    fmix_write_dependency_stamp "$compile_root" "$legacy_dependency_fingerprint"
    fmix_write_compile_stamp "$compile_root" "$legacy_compile_fingerprint"
    fmix_update_worktree_template_key \
        "$compile_root" "$current_template_key" "$legacy_template_key"
    if fmix_ensure_artifacts \
        "$compile_root" "$current_template_key" 0 >/dev/null 2>&1 \
        && [[ "$(fmix_read_state "$(fmix_artifact_state_file "$compile_root")" template_key)" \
            == "$current_template_key" ]] \
        && fmix_dependency_stamp_matches \
            "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")" \
        && fmix_compile_stamp_matches \
            "$compile_root" "$(fmix_compute_compile_fingerprint "$compile_root")"; then
        st_pass "FMix 1.4 provenance upgrades in place without deps.get or compilation"
    else
        st_fail "FMix 1.4 provenance upgrade discarded compatible artifacts"
    fi

    fmix_write_dependency_stamp "$compile_root" "$legacy_dependency_fingerprint"
    fmix_write_compile_stamp "$compile_root" "$legacy_compile_fingerprint"
    fmix_update_worktree_template_key \
        "$compile_root" "$current_template_key" "$legacy_template_key"
    printf 'defmodule Demo, do: :not_compiled\n' >"$compile_root/lib/demo.ex"
    if ! fmix_ensure_artifacts \
        "$compile_root" "$current_template_key" 0 >/dev/null 2>&1 \
        && [[ "$(fmix_read_state "$(fmix_artifact_state_file "$compile_root")" template_key)" \
            == "$legacy_template_key" ]] \
        && [[ -d "$compile_root/_build" ]] \
        && ! compgen -G "$compile_root/_build.fmix-stale.*" >/dev/null; then
        st_pass "incompatible source fails closed without moving worktree artifacts"
    else
        st_fail "failed compatibility proof mutated or adopted stale worktree artifacts"
    fi
    printf 'defmodule Demo, do: nil\n' >"$compile_root/lib/demo.ex"
    fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    dep_before="$(fmix_compute_dependency_fingerprint "$compile_root")"
    fmix_write_dependency_stamp "$compile_root" "$dep_before"
    fmix_write_compile_stamp "$compile_root" "$fp_before"
    fmix_update_worktree_template_key \
        "$compile_root" "$legacy_template_key" "$current_template_key"

    if command -v elixir >/dev/null 2>&1; then
    local dep_change_old_key dep_change_new_key dep_change_output dep_change_log dep_change_rc=0
    local dep_change_saved_env="${FMIX_SELF_TEST_DEP_TOKEN-__unset__}"
    local dep_change_saved_active="${FMIX_ACTIVE_SESSION_ROOT-__unset__}"
    local dep_change_saved_deps="${MIX_DEPS_PATH-__unset__}"
    local dep_change_saved_build="${MIX_BUILD_PATH-__unset__}"
    FMIX_ACTIVE_SESSION_ROOT="$compile_root"
    MIX_DEPS_PATH="$compile_root/deps"
    MIX_BUILD_PATH="$compile_root/_build/test"
    FMIX_SELF_TEST_DEP_TOKEN="stable"
    cp "$compile_root/mix.exs" "$compile_root/mix.exs.dependency-change-fixture"
    printf 'defmodule Demo.MixProject do\n  @dep_token System.get_env("FMIX_SELF_TEST_DEP_TOKEN")\n  def project, do: [app: :demo, version: "0.1.0", build_path: "_build", deps_path: "deps", deps: deps()]\n  defp deps, do: [{:demo_dep, "~> 1.0"}]\nend\n' \
        >"$compile_root/mix.exs"
    mkdir -p "$compile_root/vendor/reconciliation-fixture"
    printf 'stable vendor input\n' \
        >"$compile_root/vendor/reconciliation-fixture/input.txt"
    printf 'lock\n' >"$compile_root/mix.lock"
    dep_change_old_key="$(fmix_compute_template_key "$compile_root")"
    dep_before="$(fmix_compute_dependency_fingerprint "$compile_root")"
    fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    fmix_write_dependency_stamp "$compile_root" "$dep_before"
    fmix_write_compile_stamp "$compile_root" "$fp_before"
    fmix_write_artifact_state "$compile_root" "$dep_change_old_key"
    sed 's/~> 1\.0/~> 1.1/' "$compile_root/mix.exs" \
        >"$compile_home/dependency-change-mix.exs"
    mv "$compile_home/dependency-change-mix.exs" "$compile_root/mix.exs"
    printf 'lock with one stable dependency bump\n' >"$compile_root/mix.lock"
    dep_change_new_key="$(fmix_compute_template_key "$compile_root")"
    dep_change_log="$compile_home/dependency-change-reconcile.log"
    fmix_ensure_artifacts "$compile_root" "$dep_change_new_key" 0 \
        >"$dep_change_log" 2>&1 || dep_change_rc=$?
    dep_change_output="$(cat "$dep_change_log")"
    if (( dep_change_rc == 0 )) \
        && [[ "$dep_change_old_key" != "$dep_change_new_key" ]] \
        && [[ "$FMIX_LAST_ARTIFACTS_OUTCOME" == "dependency_reconcile" ]] \
        && [[ "$(fmix_read_state "$compile_root/artifact-state.json" template_key)" \
            == "$dep_change_new_key" ]] \
        && [[ -f "$compile_root/_build/test/lib/cdrcisco/ebin/Elixir.Demo.beam" ]] \
        && [[ ! -e "$compile_root/dependency-stamp.json" \
            && ! -e "$compile_root/compile-stamp.json" ]] \
        && [[ "$dep_change_output" == *"preserving the app cache for incremental compile"* ]]; then
        st_pass "same-toolchain dependency change remains a cache hit and preserves the app build"
    else
        st_fail "dependency change discarded the app cache or bypassed incremental reconciliation (rc=$dep_change_rc outcome=${FMIX_LAST_ARTIFACTS_OUTCOME:-} output=${dep_change_output//$'\n'/, })"
    fi

    eval "$(declare -f fmix_run_deps_get | sed '1s/fmix_run_deps_get/fmix_run_deps_get_dependency_change_orig/')"
    eval "$(declare -f fmix_run_compile_streamed | sed '1s/fmix_run_compile_streamed/fmix_run_compile_streamed_dependency_change_orig/')"
    local dep_change_deps_marker="$compile_home/dependency-change-deps-get"
    local dep_change_compile_marker="$compile_home/dependency-change-compile"
    local dep_change_compile_rc=0
    fmix_run_deps_get() {
        : >"$dep_change_deps_marker"
        return 0
    }
    fmix_run_compile_streamed() {
        local dependency_change_log="$4"
        [[ -f "$compile_root/_build/test/lib/cdrcisco/ebin/Elixir.Demo.beam" ]] \
            || return 1
        printf 'Compiling 12 files (.ex)\n' >"$dependency_change_log"
        : >"$dep_change_compile_marker"
        return 0
    }
    fmix_ensure_compile "$compile_root" demo \
        >/dev/null 2>&1 || dep_change_compile_rc=$?
    if (( dep_change_compile_rc == 0 )) \
        && [[ -f "$dep_change_deps_marker" && -f "$dep_change_compile_marker" ]] \
        && [[ "$FMIX_LAST_COMPILE_OUTCOME" == "incremental" \
            && "$FMIX_LAST_COMPILE_FILES" == "12" ]] \
        && [[ "$FMIX_LAST_ARTIFACTS_OUTCOME" == "dependency_reconcile" ]] \
        && fmix_dependency_stamp_matches \
            "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")" \
        && fmix_compile_stamp_matches \
            "$compile_root" "$(fmix_compute_compile_fingerprint "$compile_root")"; then
        st_pass "dependency cache hit performs deps reconciliation and a bounded incremental compile"
    else
        st_fail "dependency cache hit did not complete incremental reconciliation (rc=$dep_change_compile_rc compile=${FMIX_LAST_COMPILE_OUTCOME:-} files=${FMIX_LAST_COMPILE_FILES:-})"
    fi
    eval "$(declare -f fmix_run_deps_get_dependency_change_orig | sed '1s/fmix_run_deps_get_dependency_change_orig/fmix_run_deps_get/')"
    eval "$(declare -f fmix_run_compile_streamed_dependency_change_orig | sed '1s/fmix_run_compile_streamed_dependency_change_orig/fmix_run_compile_streamed/')"

    # Only mix.lock may vary across this special cache-hit transition. A
    # simultaneous dependency-input change must fail the reconciliation proof
    # before it advances metadata or clears stamps.
    dep_change_old_key="$dep_change_new_key"
    cp "$compile_root/mix.exs" "$compile_home/reconciliation-mix.exs"
    printf 'lock with a second stable dependency bump\n' >"$compile_root/mix.lock"
    sed 's/version: "0\.1\.0"/version: "0.2.0"/' "$compile_root/mix.exs" \
        >"$compile_home/reconciliation-app-setting.exs"
    mv "$compile_home/reconciliation-app-setting.exs" "$compile_root/mix.exs"
    dep_change_new_key="$(fmix_compute_template_key "$compile_root")"
    if ! fmix_reconcile_same_toolchain_dependency_change \
        "$compile_root" "$dep_change_old_key" "$dep_change_new_key" \
        >/dev/null 2>&1 \
        && [[ "$(fmix_read_state "$compile_root/artifact-state.json" template_key)" \
            == "$dep_change_old_key" ]] \
        && [[ -f "$compile_root/dependency-stamp.json" \
            && -f "$compile_root/compile-stamp.json" ]]; then
        st_pass "dependency reconciliation rejects a simultaneous mix.exs app-setting change"
    else
        st_fail "dependency reconciliation admitted a simultaneous mix.exs app-setting change"
    fi
    mv "$compile_home/reconciliation-mix.exs" "$compile_root/mix.exs"
    printf 'lock with one stable dependency bump\n' >"$compile_root/mix.lock"

    printf 'lock with a third stable dependency bump\n' >"$compile_root/mix.lock"
    printf 'changed vendor input\n' \
        >"$compile_root/vendor/reconciliation-fixture/input.txt"
    dep_change_new_key="$(fmix_compute_template_key "$compile_root")"
    if ! fmix_reconcile_same_toolchain_dependency_change \
        "$compile_root" "$dep_change_old_key" "$dep_change_new_key" \
        >/dev/null 2>&1 \
        && [[ "$(fmix_read_state "$compile_root/artifact-state.json" template_key)" \
            == "$dep_change_old_key" ]] \
        && [[ -f "$compile_root/dependency-stamp.json" \
            && -f "$compile_root/compile-stamp.json" ]]; then
        st_pass "dependency reconciliation rejects a simultaneous vendor change"
    else
        st_fail "dependency reconciliation admitted a simultaneous vendor change"
    fi
    printf 'stable vendor input\n' \
        >"$compile_root/vendor/reconciliation-fixture/input.txt"
    printf 'lock with one stable dependency bump\n' >"$compile_root/mix.lock"

    printf 'lock with a fourth stable dependency bump\n' >"$compile_root/mix.lock"
    FMIX_SELF_TEST_DEP_TOKEN="changed"
    dep_change_new_key="$(fmix_compute_template_key "$compile_root")"
    if ! fmix_reconcile_same_toolchain_dependency_change \
        "$compile_root" "$dep_change_old_key" "$dep_change_new_key" \
        >/dev/null 2>&1 \
        && [[ "$(fmix_read_state "$compile_root/artifact-state.json" template_key)" \
            == "$dep_change_old_key" ]] \
        && [[ -f "$compile_root/dependency-stamp.json" \
            && -f "$compile_root/compile-stamp.json" ]]; then
        st_pass "dependency reconciliation rejects a dependency environment change"
    else
        st_fail "dependency reconciliation admitted a dependency environment change"
    fi
    FMIX_SELF_TEST_DEP_TOKEN="stable"
    printf 'lock with one stable dependency bump\n' >"$compile_root/mix.lock"

    rm -f "$compile_root/artifact-state.json" \
        "$compile_root/dependency-stamp.json" "$compile_root/compile-stamp.json"
    mv "$compile_root/mix.exs.dependency-change-fixture" "$compile_root/mix.exs"
    rm -rf "$compile_root/vendor/reconciliation-fixture"
    printf 'lock\n' >"$compile_root/mix.lock"
    if [[ "$dep_change_saved_active" == "__unset__" ]]; then
        unset FMIX_ACTIVE_SESSION_ROOT
    else
        FMIX_ACTIVE_SESSION_ROOT="$dep_change_saved_active"
    fi
    if [[ "$dep_change_saved_deps" == "__unset__" ]]; then
        unset MIX_DEPS_PATH
    else
        MIX_DEPS_PATH="$dep_change_saved_deps"
    fi
    if [[ "$dep_change_saved_build" == "__unset__" ]]; then
        unset MIX_BUILD_PATH
    else
        MIX_BUILD_PATH="$dep_change_saved_build"
    fi
    if [[ "$dep_change_saved_env" == "__unset__" ]]; then
        unset FMIX_SELF_TEST_DEP_TOKEN
    else
        FMIX_SELF_TEST_DEP_TOKEN="$dep_change_saved_env"
    fi
    else
        # The portable pre-toolchain stamp path deliberately binds all of
        # mix.exs. It may round-trip metadata, but cannot authorize the narrower
        # dependency-body exception without Elixir's AST parser.
        local raw_guard_before raw_guard_after
        cp "$compile_root/mix.exs" "$compile_home/raw-guard-mix.exs"
        raw_guard_before="$(
            fmix_compute_mix_project_reconciliation_guard "$compile_root"
        )"
        printf '\n# dependency declaration changed before toolchain activation\n' \
            >>"$compile_root/mix.exs"
        raw_guard_after="$(
            fmix_compute_mix_project_reconciliation_guard "$compile_root"
        )"
        mv "$compile_home/raw-guard-mix.exs" "$compile_root/mix.exs"
        if [[ "$raw_guard_before" =~ ^[0-9a-f]{64}$ \
            && "$raw_guard_after" =~ ^[0-9a-f]{64}$ \
            && "$raw_guard_before" != "$raw_guard_after" ]]; then
            st_pass "portable raw project guard fails closed before Elixir activation"
        else
            st_fail "portable raw project guard authorized a mix.exs change"
        fi
        st_skip "dependency-only reconciliation exercise requires an active Elixir AST parser"
    fi

    dep_before="$(fmix_compute_dependency_fingerprint "$compile_root")"

    eval "$(declare -f fmix_run_deps_get | sed '1s/fmix_run_deps_get/fmix_run_deps_get_repair_orig/')"
    eval "$(declare -f fmix_run_compile_streamed | sed '1s/fmix_run_compile_streamed/fmix_run_compile_streamed_repair_orig/')"
    local repair_deps_marker="$compile_home/deps-get-for-incomplete-tree"
    local repair_compile_marker="$compile_home/compile-after-dependency-repair"
    rm -f "$(fmix_dependency_stamp_file "$compile_root")"
    rm -rf "$compile_root/deps/demo_dep"
    printf 'defmodule Demo, do: :repair_incomplete_dependencies\n' >"$compile_root/lib/demo.ex"
    fmix_run_deps_get() {
        : >"$repair_deps_marker"
        mkdir -p "$compile_root/deps/demo_dep"
        printf 'defmodule DemoDep.MixProject, do: nil\n' >"$compile_root/deps/demo_dep/mix.exs"
        printf 'test hex marker\n' >"$compile_root/deps/demo_dep/.hex"
        return 0
    }
    fmix_run_compile_streamed() { : >"$repair_compile_marker"; return 0; }
    check_out="$(fmix_ensure_compile "$compile_root" demo 2>&1)"
    if [[ "$check_out" == *"Dependency stamp miss"* \
        && -e "$repair_deps_marker" && -e "$repair_compile_marker" ]] \
        && fmix_dependency_stamp_matches "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"; then
        st_pass "missing dependency stamp runs deps.get once and records its checkpoint"
    else
        st_fail "missing dependency stamp bypassed deps.get or missed its checkpoint"
    fi
    eval "$(declare -f fmix_run_deps_get_repair_orig | sed '1s/fmix_run_deps_get_repair_orig/fmix_run_deps_get/')"
    eval "$(declare -f fmix_run_compile_streamed_repair_orig | sed '1s/fmix_run_compile_streamed_repair_orig/fmix_run_compile_streamed/')"

    printf 'defmodule Demo, do: :source_only_change\n' >"$compile_root/lib/demo.ex"
    dep_after="$(fmix_compute_dependency_fingerprint "$compile_root")"
    if [[ "$dep_before" == "$dep_after" ]] \
        && fmix_dependency_stamp_matches "$compile_root" "$dep_after"; then
        st_pass "dependency stamp remains valid for source-only edits"
    else
        st_fail "dependency stamp invalidated on a source-only edit"
    fi

    eval "$(declare -f fmix_run_deps_get | sed '1s/fmix_run_deps_get/fmix_run_deps_get_source_orig/')"
    eval "$(declare -f fmix_run_compile_streamed | sed '1s/fmix_run_compile_streamed/fmix_run_compile_streamed_source_orig/')"
    source_deps_marker="$compile_home/source-deps-called"
    source_compile_marker="$compile_home/source-compile-called"
    fmix_run_deps_get() { : >"$source_deps_marker"; return 1; }
    fmix_run_compile_streamed() {
        : >"$source_compile_marker"
        mkdir -p "$compile_root/deps/demo_dep/lib"
        printf 'defmodule DemoDep.GeneratedAfterCompile, do: nil\n' \
            >"$compile_root/deps/demo_dep/lib/generated_after_compile.ex"
        return 0
    }
    source_compile_out="$(fmix_ensure_compile "$compile_root" demo 2>&1)"
    if [[ "$source_compile_out" == *"skipping deps.get for source-only compile"* \
        && ! -e "$source_deps_marker" && -e "$source_compile_marker" ]] \
        && fmix_dependency_stamp_matches \
            "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"; then
        st_pass "source-only compile bypasses deps.get and records final dependency provenance"
    else
        st_fail "source-only compile skipped work or left pre-compile dependency provenance"
    fi

    printf '{\"source_guard\":\"stale-pre-compile-guard\"}\n' \
        >"$(fmix_dependency_stamp_file "$compile_root")"
    rm -f "$source_deps_marker" "$source_compile_marker"
    source_compile_out="$(fmix_ensure_compile "$compile_root" demo 2>&1)"
    if [[ "$source_compile_out" == *"Repaired final dependency provenance"* \
        && ! -e "$source_deps_marker" && ! -e "$source_compile_marker" ]] \
        && fmix_dependency_stamp_matches \
            "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"; then
        st_pass "exact compile proof repairs a stale pre-compile dependency checkpoint"
    else
        st_fail "stale dependency checkpoint triggered redundant work or remained unproven"
    fi

    rm -f "$source_deps_marker" "$source_compile_marker"
    printf 'defmodule Demo, do: :source_compile_error\n' >"$compile_root/lib/demo.ex"
    fmix_run_compile_streamed() { : >"$source_compile_marker"; return 1; }
    source_compile_out="$(fmix_ensure_compile "$compile_root" demo 2>&1)"
    if [[ "$source_compile_out" == *"skipping deps.get for source-only compile"* \
        && ! -e "$source_deps_marker" && -e "$source_compile_marker" ]] \
        && fmix_dependency_stamp_matches "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"; then
        st_pass "failed source compile preserves resolved dependency checkpoint"
    else
        st_fail "failed source compile discarded dependency resolution or reran deps.get"
    fi
    eval "$(declare -f fmix_run_deps_get_source_orig | sed '1s/fmix_run_deps_get_source_orig/fmix_run_deps_get/')"
    eval "$(declare -f fmix_run_compile_streamed_source_orig | sed '1s/fmix_run_compile_streamed_source_orig/fmix_run_compile_streamed/')"

    printf 'defmodule Demo, do: nil\n' >"$compile_root/lib/demo.ex"
    fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    fmix_write_dependency_stamp "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"
    fmix_write_compile_stamp "$compile_root" "$fp_before"

    printf 'defmodule DemoDep.MixProject, do: :locally_changed\n' \
        >"$compile_root/deps/demo_dep/mix.exs"
    if ! fmix_compile_stamp_matches "$compile_root" "$fp_before" \
        && ! fmix_dependency_stamp_matches "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"; then
        st_pass "ordinary dependency source edits invalidate warm compile and dependency stamps"
    else
        st_fail "ordinary dependency source content was hidden behind a warm stamp"
    fi
    printf 'defmodule DemoDep.MixProject, do: nil\n' >"$compile_root/deps/demo_dep/mix.exs"
    fmix_write_dependency_stamp "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"
    fmix_write_compile_stamp "$compile_root" "$fp_before"

    rm -f "$compile_root/deps/demo_dep/mix.exs"
    if ! fmix_dependency_stamp_matches "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"; then
        st_pass "dependency stamp invalidates when an ordinary dependency source disappears"
    else
        st_fail "dependency stamp ignored a deleted dependency source file"
    fi
    printf 'defmodule DemoDep.MixProject, do: nil\n' >"$compile_root/deps/demo_dep/mix.exs"
    fmix_write_dependency_stamp "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"
    printf 'lock changed\n' >"$compile_root/mix.lock"
    dep_after="$(fmix_compute_dependency_fingerprint "$compile_root")"
    if ! fmix_dependency_stamp_matches "$compile_root" "$dep_after"; then
        st_pass "dependency stamp invalidates on mix.lock content"
    else
        st_fail "dependency stamp ignored mix.lock content"
    fi
    printf 'lock\n' >"$compile_root/mix.lock"
    fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    fmix_write_dependency_stamp "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"
    fmix_write_compile_stamp "$compile_root" "$fp_before"

    rm -rf "$compile_root/deps/demo_dep"
    if ! fmix_dependency_stamp_matches "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"; then
        st_pass "dependency stamp invalidates when resolved dependency sources disappear"
    else
        st_fail "dependency stamp ignored missing dependency sources"
    fi
    mkdir -p "$compile_root/deps/demo_dep"
    printf 'defmodule DemoDep.MixProject, do: nil\n' >"$compile_root/deps/demo_dep/mix.exs"
    printf 'test hex marker\n' >"$compile_root/deps/demo_dep/.hex"
    fmix_write_dependency_stamp "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"

    mkdir -p "$compile_root/alternate-deps/demo_dep"
    printf 'defmodule AlternateDemoDep.MixProject, do: nil\n' \
        >"$compile_root/alternate-deps/demo_dep/mix.exs"
    printf 'test alternate hex marker\n' >"$compile_root/alternate-deps/demo_dep/.hex"
    MIX_DEPS_PATH=alternate-deps
    dep_after="$(fmix_compute_dependency_fingerprint "$compile_root")"
    fmix_write_dependency_stamp "$compile_root" "$dep_after"
    rm -rf "$compile_root/alternate-deps/demo_dep"
    if ! fmix_dependency_stamp_matches "$compile_root" "$dep_after"; then
        st_pass "dependency guard follows MIX_DEPS_PATH and rejects a missing custom tree"
    else
        st_fail "dependency guard ignored the active MIX_DEPS_PATH tree"
    fi
    if [[ "$old_mix_deps_path" == "__unset__" ]]; then
        unset MIX_DEPS_PATH
    else
        MIX_DEPS_PATH="$old_mix_deps_path"
    fi
    fmix_write_dependency_stamp "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"

    mkdir -p "$compile_root/deps/path_real/lib" "$compile_root/path-target/lib"
    printf 'defmodule PathReal.MixProject, do: nil\n' >"$compile_root/deps/path_real/mix.exs"
    printf 'defmodule PathLink.MixProject, do: nil\n' >"$compile_root/path-target/mix.exs"
    printf 'defmodule PathReal.Source, do: :original\n' >"$compile_root/deps/path_real/lib/source.ex"
    printf 'defmodule PathLink.Source, do: :original\n' >"$compile_root/path-target/lib/source.ex"
    ln -s "$compile_root/path-target" "$compile_root/deps/path_link"
    dep_after="$(fmix_compute_dependency_fingerprint "$compile_root")"
    if fmix_write_dependency_stamp "$compile_root" "$dep_after" \
        && fmix_dependency_stamp_matches "$compile_root" "$dep_after"; then
        st_pass "dependency guard records real and symlinked path dependencies"
    else
        st_fail "dependency guard rejected a supported path dependency layout"
    fi
    printf 'defmodule PathLink.MixProject, do: :changed\n' >"$compile_root/path-target/mix.exs"
    if ! fmix_dependency_stamp_matches "$compile_root" "$dep_after"; then
        st_pass "dependency guard invalidates on path dependency manifest changes"
    else
        st_fail "dependency guard ignored a changed path dependency manifest"
    fi
    printf 'defmodule PathLink.MixProject, do: nil\n' >"$compile_root/path-target/mix.exs"
    if path_fp_before="$(fmix_compute_compile_fingerprint "$compile_root")" \
        && [[ -n "$path_fp_before" ]]; then
        st_pass "compile fingerprint succeeds when path dependencies are present"
    else
        st_fail "compile fingerprint returned failure for a valid path dependency"
    fi
    printf 'defmodule PathReal.Source, do: :changed\n' >"$compile_root/deps/path_real/lib/source.ex"
    path_fp_after="$(fmix_compute_compile_fingerprint "$compile_root")"
    if [[ -n "$path_fp_before" && "$path_fp_before" != "$path_fp_after" ]]; then
        st_pass "compile stamp invalidates on real path dependency source edits"
    else
        st_fail "compile stamp ignored a real path dependency source edit"
    fi
    printf 'defmodule PathReal.Source, do: :original\n' >"$compile_root/deps/path_real/lib/source.ex"
    path_fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    printf 'defmodule PathLink.Source, do: :changed\n' >"$compile_root/path-target/lib/source.ex"
    path_fp_after="$(fmix_compute_compile_fingerprint "$compile_root")"
    if [[ -n "$path_fp_before" && "$path_fp_before" != "$path_fp_after" ]]; then
        st_pass "compile stamp invalidates on symlinked path dependency source edits"
    else
        st_fail "compile stamp ignored a symlinked path dependency source edit"
    fi
    mkdir -p "$compile_root/deps/custom_path/src"
    printf 'custom source v1\n' >"$compile_root/deps/custom_path/src/custom.source"
    path_fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    printf 'custom source v2\n' >"$compile_root/deps/custom_path/src/custom.source"
    path_fp_after="$(fmix_compute_compile_fingerprint "$compile_root")"
    if [[ -n "$path_fp_before" && "$path_fp_before" != "$path_fp_after" ]]; then
        st_pass "compile stamp hashes custom path dependencies without standard manifests"
    else
        st_fail "compile stamp ignored a custom path dependency source edit"
    fi
    rm -rf "$compile_root/deps/path_real" "$compile_root/deps/path_link" \
        "$compile_root/deps/custom_path" "$compile_root/path-target"
    fmix_write_dependency_stamp "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"

    gitfile_repo="$compile_root/gitfile-source"
    git -C "$compile_root" init -q gitfile-source
    git -C "$gitfile_repo" config user.name fmix-test
    git -C "$gitfile_repo" config user.email fmix-test@example.invalid
    printf 'defmodule GitfileDep.MixProject, do: nil\n' >"$gitfile_repo/mix.exs"
    git -C "$gitfile_repo" add mix.exs
    git -C "$gitfile_repo" commit -qm initial
    git -C "$gitfile_repo" worktree add --detach -q "$compile_root/deps/gitfile_dep" HEAD
    dep_after="$(fmix_compute_dependency_fingerprint "$compile_root")"
    if fmix_write_dependency_stamp "$compile_root" "$dep_after" \
        && fmix_dependency_stamp_matches "$compile_root" "$dep_after"; then
        st_pass "dependency guard records gitfile worktree dependencies"
    else
        st_fail "dependency guard rejected a gitfile worktree dependency"
    fi
    path_fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    printf 'defmodule GitfileDep.MixProject, do: :dirty\n' \
        >"$compile_root/deps/gitfile_dep/mix.exs"
    path_fp_after="$(fmix_compute_compile_fingerprint "$compile_root")"
    if [[ -n "$path_fp_before" && "$path_fp_before" != "$path_fp_after" ]]; then
        st_pass "compile stamp invalidates on uncommitted Git dependency edits"
    else
        st_fail "compile stamp ignored an uncommitted Git dependency edit"
    fi
    git -C "$gitfile_repo" worktree remove --force "$compile_root/deps/gitfile_dep"
    rm -rf "$gitfile_repo"
    fmix_write_dependency_stamp "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"

    eval "$(declare -f fmix_compute_compile_fingerprint | sed '1s/fmix_compute_compile_fingerprint/fmix_compute_compile_fingerprint_hot_orig/')"
    eval "$(declare -f fmix_compile_stamp_matches | sed '1s/fmix_compile_stamp_matches/fmix_compile_stamp_matches_hot_orig/')"
    eval "$(declare -f fmix_run_compile_streamed | sed '1s/fmix_run_compile_streamed/fmix_run_compile_streamed_hot_orig/')"
    local hot_compile_marker="$compile_home/hot-compile-called" hot_compile_out
    fmix_compute_compile_fingerprint() { printf 'hot-fingerprint\n'; }
    fmix_compile_stamp_matches() { return 0; }
    fmix_run_compile_streamed() { : >"$hot_compile_marker"; return 1; }
    hot_compile_out="$(fmix_ensure_compile "$compile_root" demo 2>&1)"
    if [[ "$hot_compile_out" == *"skipping deps.get and mix compile"* && ! -e "$hot_compile_marker" ]]; then
        st_pass "warm compile stamp returns before deps.get and compilation"
    else
        st_fail "warm compile stamp entered dependency or compile work"
    fi
    eval "$(declare -f fmix_compute_compile_fingerprint_hot_orig | sed '1s/fmix_compute_compile_fingerprint_hot_orig/fmix_compute_compile_fingerprint/')"
    eval "$(declare -f fmix_compile_stamp_matches_hot_orig | sed '1s/fmix_compile_stamp_matches_hot_orig/fmix_compile_stamp_matches/')"
    eval "$(declare -f fmix_run_compile_streamed_hot_orig | sed '1s/fmix_run_compile_streamed_hot_orig/fmix_run_compile_streamed/')"

    printf 'defmodule Demo, do: nil\n' >"$compile_root/lib/demo.ex"
    fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    fmix_write_dependency_stamp "$compile_root" "$(fmix_compute_dependency_fingerprint "$compile_root")"
    fmix_write_compile_stamp "$compile_root" "$fp_before"
    rm -rf "$compile_root/deps"
    hot_compile_out="$(fmix_ensure_compile "$compile_root" demo 2>&1)"
    if [[ "$hot_compile_out" == *"skipping deps.get and mix compile"* ]]; then
        st_pass "warm compiled artifacts run without the dependency source tree"
    else
        st_fail "warm compiled artifacts unnecessarily entered dependency repair"
    fi

    eval "$(declare -f fmix_run_deps_get | sed '1s/fmix_run_deps_get/fmix_run_deps_get_warm_repair_orig/')"
    eval "$(declare -f fmix_run_compile_streamed | sed '1s/fmix_run_compile_streamed/fmix_run_compile_streamed_warm_repair_orig/')"
    local warm_repair_deps_marker="$compile_home/warm-repair-deps-called"
    fmix_run_deps_get() {
        : >"$warm_repair_deps_marker"
        mkdir -p "$compile_root/deps/demo_dep"
        printf 'defmodule DemoDep.MixProject, do: nil\n' >"$compile_root/deps/demo_dep/mix.exs"
        printf 'test hex marker\n' >"$compile_root/deps/demo_dep/.hex"
        return 0
    }
    fmix_run_compile_streamed() { return 0; }
    printf 'defmodule Demo, do: :source_changed\n' >"$compile_root/lib/demo.ex"
    hot_compile_out="$(fmix_ensure_compile "$compile_root" demo 2>&1)"
    if [[ "$hot_compile_out" == *"Dependency stamp miss"* \
        && -e "$warm_repair_deps_marker" ]]; then
        st_pass "source edit repairs missing dependency checkouts before compiling"
    else
        st_fail "source edit compiled without repairing missing dependency checkouts"
    fi
    eval "$(declare -f fmix_run_deps_get_warm_repair_orig | sed '1s/fmix_run_deps_get_warm_repair_orig/fmix_run_deps_get/')"
    eval "$(declare -f fmix_run_compile_streamed_warm_repair_orig | sed '1s/fmix_run_compile_streamed_warm_repair_orig/fmix_run_compile_streamed/')"

    fp_before="$(fmix_compute_compile_fingerprint "$compile_root")"
    fmix_write_compile_stamp "$compile_root" "$fp_before"
    printf 'manifest changed\n' >>"$compile_root/_build/test/lib/cdrcisco/.mix/compile.elixir"
    if fmix_compile_stamp_matches "$compile_root" "$fp_before"; then
        st_fail "compile stamp ignored a changed Mix manifest"
    else
        st_pass "compile stamp invalidates on Mix manifest changes"
    fi

    eval "$(declare -f _fmix_run_compile | sed '1s/_fmix_run_compile/_fmix_run_compile_stream_orig/')"
    local old_compile_heartbeat="$FMIX_COMPILE_HEARTBEAT" old_compile_timeout="$FMIX_COMPILE_TIMEOUT"
    local old_setup_compile_timeout="$FMIX_SETUP_COMPILE_TIMEOUT"
    local stream_log stream_out stream_rc
    stream_log="$compile_home/stream.log"
    FMIX_COMPILE_HEARTBEAT=1
    _fmix_run_compile() {
        printf 'Compiling 2 files (.ex)\n'
        sleep 5
        printf 'Generated demo app\n'
    }
    stream_out="$(fmix_run_compile_streamed "$compile_root" demo "" "$stream_log" 2>&1)"
    if [[ "$stream_out" == *"Compiling 2 files"* && "$stream_out" == *"Compile still running"* \
        && "$stream_out" == *"Generated demo app"* ]]; then
        st_pass "compile output streams with a silent-work heartbeat"
    else
        st_fail "compile streaming/heartbeat output was incomplete"
    fi
    FMIX_COMPILE_TIMEOUT=1
    _fmix_run_compile() { sleep 10; }
    stream_out="$(fmix_run_compile_streamed "$compile_root" demo "" "$stream_log" 2>&1)"
    stream_rc=$?
    if (( stream_rc == 124 )) && [[ "$stream_out" == *"Compile exceeded 1s"* ]]; then
        st_pass "compile wall-clock timeout cancels a silent compiler"
    else
        st_fail "compile timeout was not enforced: rc=$stream_rc out='$stream_out'"
    fi
    # What this proves is that passing the explicit 5th argument overrides the
    # 1s default set just above: a 2s compile survives only if the override
    # took effect. The override's value is scaffolding and must stay well clear
    # of the fixture, or a loaded runner trips it and the case fails for a
    # reason it is not testing. It was 3s against a 2s sleep -- one second of
    # headroom -- and it failed on macOS CI.
    FMIX_SETUP_COMPILE_TIMEOUT=30
    _fmix_run_compile() { sleep 2; }
    stream_out="$(fmix_run_compile_streamed "$compile_root" demo "" "$stream_log" "$FMIX_SETUP_COMPILE_TIMEOUT" 2>&1)"
    stream_rc=$?
    if (( stream_rc == 0 )); then
        st_pass "explicit setup compile uses its larger bounded timeout"
    else
        st_fail "explicit setup compile ignored its larger timeout: rc=$stream_rc out='$stream_out'"
    fi
    FMIX_COMPILE_HEARTBEAT="$old_compile_heartbeat"
    FMIX_COMPILE_TIMEOUT="$old_compile_timeout"
    FMIX_SETUP_COMPILE_TIMEOUT="$old_setup_compile_timeout"
    eval "$(declare -f _fmix_run_compile_stream_orig | sed '1s/_fmix_run_compile_stream_orig/_fmix_run_compile/')"

    eval "$(declare -f _fmix_run_deps_get | sed '1s/_fmix_run_deps_get/_fmix_run_deps_get_test_orig/')"
    local old_deps_heartbeat="$FMIX_DEPS_HEARTBEAT" old_deps_timeout="$FMIX_DEPS_TIMEOUT"
    local old_deps_stall_timeout="$FMIX_DEPS_STALL_TIMEOUT"
    local deps_timeout_out deps_timeout_rc deps_progress_out deps_progress_rc
    local deps_failure_out deps_failure_rc
    FMIX_DEPS_HEARTBEAT=0
    # The stall window is the discriminator: 1s against 5s of silence. The hard
    # limit is scaffolding and is kept far away so that if the stall watchdog
    # ever regressed, this case would fail on the stall assertion rather than
    # quietly become a hard-limit test.
    FMIX_DEPS_STALL_TIMEOUT=1
    FMIX_DEPS_TIMEOUT=60
    _fmix_run_deps_get() {
        sleep 5
    }
    deps_timeout_out="$(fmix_run_deps_get "$compile_root" 2>&1)"
    deps_timeout_rc=$?
    if (( deps_timeout_rc == 124 )) \
        && [[ "$deps_timeout_out" == *"made no logged progress for 1s"* ]]; then
        st_pass "deps.get no-progress timeout cancels a stalled resolver and reports its log"
    else
        st_fail "deps.get timeout was not enforced: rc=$deps_timeout_rc out='$deps_timeout_out'"
    fi

    # Leave one full sampling interval of slack: a printf followed by
    # `sleep 1` can land on the same epoch-second as the watchdog on macOS.
    #
    # The stall timeout is what is under test: progress every second must keep
    # extending it. The hard limit is incidental scaffolding and must stay well
    # clear of the fixture's ~4s runtime, or a loaded runner trips the hard
    # limit and the case fails for a reason it is not testing. It was 5s, which
    # left one second of headroom for four sleeps, and it failed on macOS CI.
    # Three numbers have to stay ordered: output gap < stall window < total
    # runtime. Below the gap the watchdog fires despite progress; above the
    # total it can never fire and the case passes vacuously even if extension
    # is broken. It was 1 < 2 < 4, one second of margin on each side, which a
    # loaded runner erases -- a `sleep 1` that takes 2s trips a 2s window.
    # 1 < 4 < 8 keeps the same claim with 4x and 2x margin.
    FMIX_DEPS_STALL_TIMEOUT=4
    FMIX_DEPS_TIMEOUT=60
    _fmix_run_deps_get() {
        local i
        for i in 1 2 3 4 5 6 7 8; do
            printf 'dependency progress %s\n' "$i"
            sleep 1
        done
    }
    deps_progress_out="$(fmix_run_deps_get "$compile_root" 2>&1)"
    deps_progress_rc=$?
    if (( deps_progress_rc == 0 )) && [[ "$deps_progress_out" != *"cancelling"* ]]; then
        st_pass "deps.get progress extends the stall watchdog"
    else
        st_fail "active deps.get was mistaken for a stall: rc=$deps_progress_rc out='$deps_progress_out'"
    fi

    FMIX_DEPS_STALL_TIMEOUT=5
    _fmix_run_deps_get() {
        printf 'dependency failure diagnostic\n'
        return 42
    }
    deps_failure_out="$(fmix_run_deps_get "$compile_root" 2>&1)"
    deps_failure_rc=$?
    if (( deps_failure_rc == 42 )) \
        && [[ "$deps_failure_out" == *"dependency failure diagnostic"* \
        && "$deps_failure_out" == *"Log:"* ]]; then
        st_pass "deps.get failures retain diagnostics and report the log path"
    else
        st_fail "deps.get failure diagnostics were lost: rc=$deps_failure_rc out='$deps_failure_out'"
    fi
    FMIX_DEPS_HEARTBEAT="$old_deps_heartbeat"
    FMIX_DEPS_STALL_TIMEOUT="$old_deps_stall_timeout"
    FMIX_DEPS_TIMEOUT="$old_deps_timeout"
    eval "$(declare -f _fmix_run_deps_get_test_orig | sed '1s/_fmix_run_deps_get_test_orig/_fmix_run_deps_get/')"

    FMIX_HOME="$old_fmix_home"
    if [[ "$old_mix_build_path" == "__unset__" ]]; then
        unset MIX_BUILD_PATH
    else
        MIX_BUILD_PATH="$old_mix_build_path"
    fi
    if [[ "$old_mix_deps_path" == "__unset__" ]]; then
        unset MIX_DEPS_PATH
    else
        MIX_DEPS_PATH="$old_mix_deps_path"
    fi
    if [[ "$old_unrelated_token" == "__unset__" ]]; then
        unset FMIX_UNRELATED_SESSION_TOKEN
    else
        FMIX_UNRELATED_SESSION_TOKEN="$old_unrelated_token"
    fi
    if [[ "$old_compiler_workers" == "__unset__" ]]; then
        unset ELIXIR_COMPILER_WORKERS
    else
        ELIXIR_COMPILER_WORKERS="$old_compiler_workers"
    fi
    rm -rf "$compile_root" "$compile_copy" "$compile_home"

    # 6. Compatible snapshot ledger contract.
    echo ""
    echo "--- Snapshot migration-ledger compatibility ---"
    eval "$(declare -f fmix_psql | sed '1s/fmix_psql/fmix_psql_ledger_orig/')"
    local ledger_wt
    ledger_wt="$(mktemp -d)"
    mkdir -p "$ledger_wt/priv/repo/migrations"
    : >"$ledger_wt/priv/repo/migrations/20260101000000_one.exs"
    : >"$ledger_wt/priv/repo/migrations/20260201000000_two.exs"
    : >"$ledger_wt/priv/repo/migrations/20260301000000_three.exs"

    fmix_psql() { printf '20260101000000\n20260201000000\n'; }
    if fmix_migration_ledger_is_prefix "$ledger_wt" ct_fmix_abc12345; then
        st_pass "compatible snapshot accepts an exact migration prefix"
    else
        st_fail "compatible snapshot rejected an exact migration prefix"
    fi

    fmix_psql() { printf '20260101000000\n20260201000000\n20260416223000\n'; }
    if fmix_migration_ledger_is_prefix "$ledger_wt" ct_fmix_abc12345; then
        st_pass "compatible base accepts the repository's one known ledger orphan"
    else
        st_fail "compatible base rejected the repository's known ledger orphan"
    fi

    fmix_psql() { printf '20260101000000\n20260301000000\n'; }
    if fmix_migration_ledger_is_prefix "$ledger_wt" ct_fmix_abc12345; then
        st_pass "compatible snapshot accepts a gapped-but-subset migration ledger"
    else
        st_fail "compatible snapshot rejected a gapped-but-subset migration ledger"
    fi

    # Interleaved ledger: {1,3} recorded, {1,2,3} on disk. is_prefix now
    # accepts this (subset), but is_current must still reject it until 2 is
    # applied — that's the invariant that actually protects hot-base reuse
    # now that is_prefix is a subset check.
    fmix_psql() { printf '20260101000000\n20260301000000\n'; }
    if fmix_migration_ledger_is_current "$ledger_wt" ct_fmix_abc12345; then
        st_fail "post-migration equality gate accepted an interleaved/incomplete ledger"
    else
        st_pass "post-migration equality gate still rejects an interleaved/incomplete ledger"
    fi

    fmix_psql() { printf '20260101000000\n20260201000000\n20260301000000\n20260401000000\n'; }
    if fmix_migration_ledger_is_prefix "$ledger_wt" ct_fmix_abc12345; then
        st_fail "compatible snapshot accepted an ahead migration ledger"
    else
        st_pass "compatible snapshot rejects an ahead migration ledger"
    fi

    fmix_psql() { printf '20260101000000\n20260201000000\n20260301000000\n'; }
    if fmix_migration_ledger_is_current "$ledger_wt" ct_fmix_abc12345; then
        st_pass "post-migration ledger requires exact equality"
    else
        st_fail "exact migration ledger was rejected"
    fi
    eval "$(declare -f fmix_psql_ledger_orig | sed '1s/fmix_psql_ledger_orig/fmix_psql/')"

    eval "$(declare -f fmix_db_exists | sed '1s/fmix_db_exists/fmix_db_exists_cold_orig/')"
    eval "$(declare -f fmix_schema_key | sed '1s/fmix_schema_key/fmix_schema_key_cold_orig/')"
    eval "$(declare -f fmix_select_indexed_base | sed '1s/fmix_select_indexed_base/fmix_select_indexed_base_cold_orig/')"
    eval "$(declare -f fmix_ensure_snapshot_template | sed '1s/fmix_ensure_snapshot_template/fmix_ensure_snapshot_template_cold_orig/')"
    eval "$(declare -f fmix_create_database | sed '1s/fmix_create_database/fmix_create_database_cold_orig/')"
    eval "$(declare -f fmix_migration_ledger_is_prefix | sed '1s/fmix_migration_ledger_is_prefix/fmix_migration_ledger_is_prefix_cold_orig/')"
    eval "$(declare -f fmix_validate_db_integrity | sed '1s/fmix_validate_db_integrity/fmix_validate_db_integrity_cold_orig/')"
    local cold_marker="$ledger_wt/cold-builder-called" create_log="$ledger_wt/create-log" cold_rc
    fmix_db_exists() { return 1; }
    fmix_schema_key() { printf 'abcdef0123456789\n'; }
    fmix_select_indexed_base() { return 1; }
    fmix_ensure_snapshot_template() { : >"$cold_marker"; printf 'ct_fmix_snap_abcdef0123456789\n'; }
    fmix_create_database() { printf '%s:%s\n' "$1" "${2:-}" >>"$create_log"; }
    fmix_migration_ledger_is_prefix() { return 0; }
    fmix_validate_db_integrity() { return 0; }

    fmix_ensure_db "$ledger_wt" ct_fmix_abc12345 0 0 0 >/dev/null 2>&1
    cold_rc=$?
    if (( cold_rc != 0 )) && [[ ! -e "$cold_marker" && ! -e "$create_log" ]]; then
        st_pass "normal test preparation performs no cold load or DB clone on metadata miss"
    else
        st_fail "normal metadata miss entered database preparation"
    fi
    rm -f "$cold_marker" "$create_log"
    fmix_ensure_db "$ledger_wt" ct_fmix_abc12345 1 0 1 >/dev/null 2>&1
    cold_rc=$?
    if (( cold_rc != 0 )) && [[ ! -e "$cold_marker" && ! -e "$create_log" ]]; then
        st_pass "snapshot-only rebuild performs no cold structure replay"
    else
        st_fail "snapshot-only rebuild entered cold database work"
    fi
    rm -f "$cold_marker" "$create_log"
    if fmix_ensure_db "$ledger_wt" ct_fmix_abc12345 1 1 1 >/dev/null 2>&1 \
        && [[ -e "$cold_marker" ]] && [[ "$(wc -l <"$create_log" | tr -d ' ')" == "1" ]] \
        && [[ "$FMIX_ACTIVE_DB_SCHEMA_KEY" == "abcdef0123456789" ]]; then
        st_pass "explicit cold maintenance performs one clone and records current provenance"
    else
        st_fail "explicit cold maintenance did not remain single-clone"
    fi

    rm -f "$cold_marker" "$create_log"
    fmix_select_indexed_base() { printf 'ct_fmix_tmpl_2222222222222222\t2222222222222222\t1\n'; }
    if fmix_ensure_db "$ledger_wt" ct_fmix_abc12345 0 0 0 >/dev/null 2>&1 \
        && [[ "$(wc -l <"$create_log" | tr -d ' ')" == "1" ]] \
        && [[ "$FMIX_ACTIVE_DB_SCHEMA_KEY" == "abcdef0123456789" ]] \
        && [[ "$FMIX_ACTIVE_DB_SOURCE_KEY" == "2222222222222222" ]]; then
        st_pass "indexed ordinary miss performs one clone and preserves source provenance"
    else
        st_fail "indexed ordinary miss did not remain single-clone"
    fi

    eval "$(declare -f fmix_db_exists_cold_orig | sed '1s/fmix_db_exists_cold_orig/fmix_db_exists/')"
    eval "$(declare -f fmix_schema_key_cold_orig | sed '1s/fmix_schema_key_cold_orig/fmix_schema_key/')"
    eval "$(declare -f fmix_select_indexed_base_cold_orig | sed '1s/fmix_select_indexed_base_cold_orig/fmix_select_indexed_base/')"
    eval "$(declare -f fmix_ensure_snapshot_template_cold_orig | sed '1s/fmix_ensure_snapshot_template_cold_orig/fmix_ensure_snapshot_template/')"
    eval "$(declare -f fmix_create_database_cold_orig | sed '1s/fmix_create_database_cold_orig/fmix_create_database/')"
    eval "$(declare -f fmix_migration_ledger_is_prefix_cold_orig | sed '1s/fmix_migration_ledger_is_prefix_cold_orig/fmix_migration_ledger_is_prefix/')"
    eval "$(declare -f fmix_validate_db_integrity_cold_orig | sed '1s/fmix_validate_db_integrity_cold_orig/fmix_validate_db_integrity/')"
    rm -rf "$ledger_wt"

    # 7. DB-create admission and server-version strategy selection.
    echo ""
    echo "--- Database-create admission and strategy ---"
    eval "$(declare -f fmix_db_create_pressure_details | sed '1s/fmix_db_create_pressure_details/fmix_db_create_pressure_details_orig/')"
    eval "$(declare -f fmix_wait_for_db_create_admission | sed '1s/fmix_wait_for_db_create_admission/fmix_wait_for_db_create_admission_orig/')"
    eval "$(declare -f fmix_server_version_num | sed '1s/fmix_server_version_num/fmix_server_version_num_orig/')"
    eval "$(declare -f fmix_psql | sed '1s/fmix_psql/fmix_psql_create_orig/')"
    local old_admission_timeout="$FMIX_DB_ADMISSION_TIMEOUT"
    local create_capture
    create_capture="$(mktemp)"

    if declare -f fmix_db_create_pressure_details \
        | grep -q "coalesce(query_start, backend_start)" \
        && declare -f fmix_db_create_pressure_details \
        | grep -q "backend_type IN ('checkpointer', 'background writer', 'walwriter')" \
        && declare -f fmix_db_create_pressure_details \
        | grep -q "wait_event_type = 'IO'"; then
        st_pass "database-create admission includes PostgreSQL background I/O workers"
    else
        st_fail "database-create admission excludes PostgreSQL background I/O workers"
    fi

    FMIX_DB_ADMISSION_TIMEOUT=0
    fmix_db_create_pressure_details() { printf 'pid=42 db=test wait=WALWrite age=600s\n'; }
    if fmix_wait_for_db_create_admission "self-test" 2>/dev/null; then
        st_fail "database-create admission allowed sustained WAL pressure"
    else
        st_pass "database-create admission rejects sustained WAL pressure without a long wait"
    fi
    fmix_db_create_pressure_details() { return 0; }
    if fmix_wait_for_db_create_admission "self-test" 2>/dev/null; then
        st_pass "database-create admission allows a clear server"
    else
        st_fail "database-create admission rejected a clear server"
    fi
    fmix_db_create_pressure_details() { return 1; }
    if fmix_wait_for_db_create_admission "self-test" 2>/dev/null; then
        st_fail "database-create admission allowed an unknown pressure state"
    else
        st_pass "database-create admission fails closed when pressure inspection fails"
    fi

    fmix_wait_for_db_create_admission() { return 0; }
    fmix_psql() { printf '%s\n' "$*" >"$create_capture"; }
    fmix_server_version_num() { printf '140023\n'; }
    if fmix_create_database ct_fmix_abc12345 ct_fmix_snap_abcdef0123456789 \
        && grep -q 'TEMPLATE "ct_fmix_snap_abcdef0123456789"' "$create_capture" \
        && ! grep -q 'STRATEGY' "$create_capture"; then
        st_pass "PostgreSQL 14 create is bounded without unsupported WAL_LOG syntax"
    else
        st_fail "PostgreSQL 14 create strategy was not generated safely"
    fi

    fmix_server_version_num() { printf '150000\n'; }
    if fmix_create_database ct_fmix_abc12345 ct_fmix_snap_abcdef0123456789 \
        && grep -q 'STRATEGY = WAL_LOG' "$create_capture"; then
        st_pass "PostgreSQL 15+ create explicitly selects WAL_LOG"
    else
        st_fail "PostgreSQL 15+ create omitted WAL_LOG"
    fi

    local old_drop_timeout="$FMIX_DB_DROP_TIMEOUT"
    FMIX_DB_DROP_TIMEOUT=7
    : >"$create_capture"
    fmix_psql() { printf 'pgoptions=%s args=%s\n' "${PGOPTIONS:-}" "$*" >>"$create_capture"; }
    if fmix_drop_db ct_fmix_abc12345 \
        && grep -q 'statement_timeout=7000' "$create_capture" \
        && grep -q 'DROP DATABASE IF EXISTS "ct_fmix_abc12345"' "$create_capture"; then
        st_pass "snapshot cleanup is statement-capped"
    else
        st_fail "snapshot cleanup omitted its statement timeout"
    fi
    FMIX_DB_DROP_TIMEOUT="$old_drop_timeout"

    FMIX_DB_ADMISSION_TIMEOUT="$old_admission_timeout"
    eval "$(declare -f fmix_db_create_pressure_details_orig | sed '1s/fmix_db_create_pressure_details_orig/fmix_db_create_pressure_details/')"
    eval "$(declare -f fmix_wait_for_db_create_admission_orig | sed '1s/fmix_wait_for_db_create_admission_orig/fmix_wait_for_db_create_admission/')"
    eval "$(declare -f fmix_server_version_num_orig | sed '1s/fmix_server_version_num_orig/fmix_server_version_num/')"
    eval "$(declare -f fmix_psql_create_orig | sed '1s/fmix_psql_create_orig/fmix_psql/')"
    rm -f "$create_capture"

    # 8. structure.sql replay timeout and wait-state evidence.
    echo ""
    echo "--- structure.sql replay cap ---"
    eval "$(declare -f fmix_psql | sed '1s/fmix_psql/fmix_psql_structure_orig/')"
    eval "$(declare -f fmix_structure_load_activity | sed '1s/fmix_structure_load_activity/fmix_structure_load_activity_orig/')"
    local old_structure_timeout="$FMIX_STRUCTURE_LOAD_TIMEOUT"
    local old_structure_heartbeat="$FMIX_STRUCTURE_LOAD_HEARTBEAT"
    local structure_output structure_rc structure_log structure_input structure_stdin structure_pid_file
    structure_log="$(mktemp)"
    structure_input="$(mktemp)"
    structure_stdin="$(mktemp)"
    structure_pid_file="$(mktemp)"
    printf 'SELECT 1;\n' >"$structure_input"
    fmix_psql() { cat >"$structure_stdin"; }
    if fmix_run_structure_load_once ct_fmix_abc12345 "$structure_input" "$structure_log" \
        && cmp -s "$structure_input" "$structure_stdin"; then
        st_pass "structure.sql replay streams host dump through psql stdin"
    else
        st_fail "structure.sql replay passed a host-only dump path to psql"
    fi
    FMIX_STRUCTURE_LOAD_TIMEOUT=1
    FMIX_STRUCTURE_LOAD_HEARTBEAT=1
    fmix_psql() {
        printf '%s\n' "${BASHPID:-$$}" >"$structure_pid_file"
        sleep 10
    }
    fmix_structure_load_activity() {
        if [[ -s "$structure_pid_file" ]] && kill -0 "$(cat "$structure_pid_file")" 2>/dev/null; then
            printf 'pid=42 wait=IO/DataFileImmediateSync age=90s sql=CREATE TABLE curri_events_20251117\n'
        else
            printf 'backend-already-gone\n'
        fi
    }
    structure_output="$(fmix_run_structure_load_once ct_fmix_abc12345 /dev/null "$structure_log" 2>&1)"
    structure_rc=$?
    if (( structure_rc == 124 )) \
        && [[ "$structure_output" == *"exceeded 1s"* ]] \
        && [[ "$structure_output" == *"IO/DataFileImmediateSync"* ]]; then
        st_pass "structure.sql replay is capped with current Postgres wait evidence"
    else
        st_fail "structure.sql replay cap failed: rc=$structure_rc out='$structure_output'"
    fi
    FMIX_STRUCTURE_LOAD_TIMEOUT="$old_structure_timeout"
    FMIX_STRUCTURE_LOAD_HEARTBEAT="$old_structure_heartbeat"
    eval "$(declare -f fmix_psql_structure_orig | sed '1s/fmix_psql_structure_orig/fmix_psql/')"
    eval "$(declare -f fmix_structure_load_activity_orig | sed '1s/fmix_structure_load_activity_orig/fmix_structure_load_activity/')"
    rm -f "$structure_log" "$structure_input" "$structure_stdin" "$structure_pid_file"

    # 9. Kernel-held operation locks with legacy metadata interoperability.
    echo ""
    echo "--- kernel lock acquire/contend/stale-reclaim ---"
    local test_lock_dir
    test_lock_dir="$(mktemp -d)"
    local orig_fmix_home="$FMIX_HOME"
    FMIX_HOME="$test_lock_dir"

    # Acquire
    if fmix_lock_acquire "selftest-lock" 2>/dev/null; then
        st_pass "lock acquire succeeded"
        local py_bin
        py_bin="$(fmix_python_bin)"
        if "$py_bin" - "$test_lock_dir/lock-kernel/selftest-lock" <<'PY'
import fcntl
import os
import sys

fd = os.open(sys.argv[1], os.O_RDWR)
try:
    fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
    raise SystemExit(1)
raise SystemExit(0)
PY
        then
            st_fail "kernel lock escaped when the acquisition helper exited"
        else
            st_pass "kernel lock remains held by the parent for the full operation"
        fi
        if fmix_lock_release "selftest-lock"; then
            st_pass "lock release succeeded"
        else
            st_fail "lock release failed"
        fi
    else
        st_fail "lock acquire failed"
    fi

    # Contend with dead pid
    mkdir -p "$test_lock_dir/locks/selftest-stale"
    printf '99999999\n' >"$test_lock_dir/locks/selftest-stale/pid"  # definitely dead pid
    if fmix_lock_acquire "selftest-stale" 2>/dev/null; then
        st_pass "stale-pid lock reclaim succeeded"
        fmix_lock_release "selftest-stale"
    else
        st_fail "stale-pid lock reclaim failed"
    fi

    local old_lock_init_grace="$FMIX_LOCK_INIT_GRACE"
    FMIX_LOCK_INIT_GRACE=0
    mkdir -p "$test_lock_dir/locks/selftest-pidless"
    if fmix_lock_acquire "selftest-pidless" 2>/dev/null; then
        st_pass "pid-less lock is reclaimed after initialization grace"
        fmix_lock_release "selftest-pidless"
    else
        st_fail "pid-less lock remained permanently orphaned"
    fi
    FMIX_LOCK_INIT_GRACE="$old_lock_init_grace"

    # Test that a live holder blocks (we spawn a subshell holding it)
    (
        mkdir -p "$test_lock_dir/locks/selftest-live"
        printf '%d\n' "$$" >"$test_lock_dir/locks/selftest-live/pid"
        sleep 5
    ) &
    local holder_pid=$!
    sleep 0.2  # Let the subshell write the pid

    # Try to acquire with 2s timeout — should fail
    local short_timeout=$FMIX_LOCK_TIMEOUT
    FMIX_LOCK_TIMEOUT=2
    if fmix_lock_acquire "selftest-live" 2>/dev/null; then
        st_fail "should have blocked on live lock but acquired it"
        fmix_lock_release "selftest-live"
    else
        st_pass "correctly blocked on live lock (timed out as expected)"
    fi
    FMIX_LOCK_TIMEOUT=$short_timeout
    kill "$holder_pid" 2>/dev/null || true
    wait "$holder_pid" 2>/dev/null || true
    rm -rf "$test_lock_dir/locks/selftest-live"

    FMIX_HOME="$orig_fmix_home"
    rm -rf "$test_lock_dir"

    # 10. API-2846 migrate-from-zero fallback lane: clean-miss build+publish,
    # already-published short-circuit, and genuine cross-process lock
    # protection (two real backgrounded processes, one shared FMIX_HOME).
    echo ""
    echo "--- migrate-from-zero fallback lane (API-2846) ---"
    local zero_home zero_wt zero_old_home
    zero_home="$(mktemp -d)"
    zero_wt="$(mktemp -d)"
    mkdir -p "$zero_wt/priv/repo/migrations"
    : >"$zero_wt/priv/repo/migrations/20260101000000_one.exs"
    : >"$zero_wt/priv/repo/migrations/20260102000000_two.exs"
    zero_old_home="$FMIX_HOME"
    FMIX_HOME="$zero_home"

    eval "$(declare -f fmix_schema_key | sed '1s/fmix_schema_key/fmix_schema_key_zero_orig/')"
    eval "$(declare -f fmix_snapshot_ready | sed '1s/fmix_snapshot_ready/fmix_snapshot_ready_zero_orig/')"
    eval "$(declare -f fmix_base_record_ready | sed '1s/fmix_base_record_ready/fmix_base_record_ready_zero_orig/')"
    eval "$(declare -f fmix_db_exists | sed '1s/fmix_db_exists/fmix_db_exists_zero_orig/')"
    eval "$(declare -f fmix_drop_db | sed '1s/fmix_drop_db/fmix_drop_db_zero_orig/')"
    eval "$(declare -f fmix_create_database | sed '1s/fmix_create_database/fmix_create_database_zero_orig/')"
    eval "$(declare -f fmix_run_migration_bounded | sed '1s/fmix_run_migration_bounded/fmix_run_migration_bounded_zero_orig/')"
    eval "$(declare -f fmix_validate_db_integrity | sed '1s/fmix_validate_db_integrity/fmix_validate_db_integrity_zero_orig/')"
    eval "$(declare -f fmix_migration_ledger_is_current | sed '1s/fmix_migration_ledger_is_current/fmix_migration_ledger_is_current_zero_orig/')"
    eval "$(declare -f fmix_control_psql | sed '1s/fmix_control_psql/fmix_control_psql_zero_orig/')"
    eval "$(declare -f fmix_write_base_record | sed '1s/fmix_write_base_record/fmix_write_base_record_zero_orig/')"

    local zero_state="$zero_home/state" zero_build_log zero_create_log
    mkdir -p "$zero_state"
    zero_build_log="$zero_state/build.log"
    zero_create_log="$zero_state/create.log"

    # Deterministic fixed schema key regardless of which worktree path is
    # passed — this section tests fmix_migrate_from_zero's control flow and
    # locking, not fmix_schema_key derivation (already covered above).
    fmix_schema_key() { printf '2222222222222222\n'; }
    fmix_snapshot_ready() { [[ "$1" == "ct_fmix_tmpl_2222222222222222" && -e "$zero_state/published" ]]; }
    fmix_base_record_ready() { [[ "$1" == "2222222222222222" && -e "$zero_state/published" ]]; }
    fmix_db_exists() { [[ -e "$zero_state/db-$1" ]]; }
    fmix_drop_db() { rm -f "$zero_state/db-$1"; return 0; }
    fmix_create_database() {
        printf '%s\t%s\t%s\n' "$1" "${2:-}" "${3:-}" >>"$zero_create_log"
        : >"$zero_state/db-$1"
        return 0
    }
    # The mock for the expensive step under test: every real call appends its
    # own pid, so the build_log line count is the ground truth for "how many
    # times did the full migration chain actually run".
    fmix_run_migration_bounded() {
        printf '%s\n' "$$" >>"$zero_build_log"
        sleep 0.3
        return 0
    }
    fmix_validate_db_integrity() { return 0; }
    fmix_migration_ledger_is_current() { return 0; }
    fmix_control_psql() { return 0; }
    fmix_write_base_record() { : >"$zero_state/published"; return 0; }

    # (a) Clean miss: builds, validates, and publishes.
    : >"$zero_build_log"; : >"$zero_create_log"
    if fmix_migrate_from_zero "$zero_wt" ct_fmix_deadbeef01 >/dev/null 2>&1 \
        && [[ "$(wc -l <"$zero_build_log" | tr -d ' ')" == "1" ]] \
        && [[ -e "$zero_state/published" ]] \
        && [[ -e "$zero_state/db-ct_fmix_deadbeef01" ]]; then
        st_pass "migrate-from-zero builds, validates, and publishes a hot base on a clean miss"
    else
        st_fail "migrate-from-zero single-caller smoke test failed"
    fi

    # (b) Already-published short-circuit: no rebuild, one clone, no lock
    # contention needed at all (the check happens before fmix_lock_acquire).
    : >"$zero_build_log"; : >"$zero_create_log"
    if fmix_migrate_from_zero "$zero_wt" ct_fmix_cafefeed01 >/dev/null 2>&1 \
        && [[ "$(wc -l <"$zero_build_log" | tr -d ' ')" == "0" ]] \
        && grep -qF "$(printf 'ct_fmix_cafefeed01\tct_fmix_tmpl_2222222222222222')" "$zero_create_log"; then
        st_pass "migrate-from-zero clones an already-published hot base instead of rebuilding"
    else
        st_fail "migrate-from-zero rebuilt despite an already-published hot base"
    fi

    # (c) Lock protection: two genuinely concurrent OS processes racing for
    # the SAME schema key must build exactly once. This is a real
    # fmix_lock_acquire/flock test, not a simulated one — both callers are
    # backgrounded subshells sharing $FMIX_HOME.
    rm -f "$zero_state"/db-* "$zero_state/published"
    : >"$zero_build_log"; : >"$zero_create_log"
    ( fmix_migrate_from_zero "$zero_wt" ct_fmix_facade01aa >/dev/null 2>&1 ) &
    local race_pid1=$!
    ( fmix_migrate_from_zero "$zero_wt" ct_fmix_facade01bb >/dev/null 2>&1 ) &
    local race_pid2=$!
    wait "$race_pid1"; local race_rc1=$?
    wait "$race_pid2"; local race_rc2=$?
    local build_count
    build_count="$(wc -l <"$zero_build_log" | tr -d ' ')"
    if (( race_rc1 == 0 && race_rc2 == 0 )) && [[ "$build_count" == "1" ]] \
        && [[ -e "$zero_state/db-ct_fmix_facade01aa" ]] \
        && [[ -e "$zero_state/db-ct_fmix_facade01bb" ]]; then
        st_pass "migrate-from-zero is lock-protected: two concurrent processes build exactly once"
    else
        st_fail "migrate-from-zero concurrency: build_count=$build_count rc1=$race_rc1 rc2=$race_rc2 (expected exactly one build)"
    fi

    eval "$(declare -f fmix_schema_key_zero_orig | sed '1s/fmix_schema_key_zero_orig/fmix_schema_key/')"
    eval "$(declare -f fmix_snapshot_ready_zero_orig | sed '1s/fmix_snapshot_ready_zero_orig/fmix_snapshot_ready/')"
    eval "$(declare -f fmix_base_record_ready_zero_orig | sed '1s/fmix_base_record_ready_zero_orig/fmix_base_record_ready/')"
    eval "$(declare -f fmix_db_exists_zero_orig | sed '1s/fmix_db_exists_zero_orig/fmix_db_exists/')"
    eval "$(declare -f fmix_drop_db_zero_orig | sed '1s/fmix_drop_db_zero_orig/fmix_drop_db/')"
    eval "$(declare -f fmix_create_database_zero_orig | sed '1s/fmix_create_database_zero_orig/fmix_create_database/')"
    eval "$(declare -f fmix_run_migration_bounded_zero_orig | sed '1s/fmix_run_migration_bounded_zero_orig/fmix_run_migration_bounded/')"
    eval "$(declare -f fmix_validate_db_integrity_zero_orig | sed '1s/fmix_validate_db_integrity_zero_orig/fmix_validate_db_integrity/')"
    eval "$(declare -f fmix_migration_ledger_is_current_zero_orig | sed '1s/fmix_migration_ledger_is_current_zero_orig/fmix_migration_ledger_is_current/')"
    eval "$(declare -f fmix_control_psql_zero_orig | sed '1s/fmix_control_psql_zero_orig/fmix_control_psql/')"
    eval "$(declare -f fmix_write_base_record_zero_orig | sed '1s/fmix_write_base_record_zero_orig/fmix_write_base_record/')"
    FMIX_HOME="$zero_old_home"
    rm -rf "$zero_wt" "$zero_home"

    # (d) fmix_ensure_db falls back to fmix_migrate_from_zero (not the
    # structure.sql snapshot path) when the freshness gate refuses, in the
    # explicit --cold-db/--from-zero maintenance lane. Mirrors the "6.
    # Compatible snapshot ledger contract" harness above.
    local zero_gate_wt zero_gate_marker
    zero_gate_wt="$(mktemp -d)"
    mkdir -p "$zero_gate_wt/priv/repo/migrations"
    : >"$zero_gate_wt/priv/repo/migrations/20260101000000_one.exs"
    eval "$(declare -f fmix_db_exists | sed '1s/fmix_db_exists/fmix_db_exists_gate_orig/')"
    eval "$(declare -f fmix_schema_key | sed '1s/fmix_schema_key/fmix_schema_key_gate_orig/')"
    eval "$(declare -f fmix_select_indexed_base | sed '1s/fmix_select_indexed_base/fmix_select_indexed_base_gate_orig/')"
    eval "$(declare -f fmix_ensure_snapshot_template | sed '1s/fmix_ensure_snapshot_template/fmix_ensure_snapshot_template_gate_orig/')"
    eval "$(declare -f fmix_migrate_from_zero | sed '1s/fmix_migrate_from_zero/fmix_migrate_from_zero_gate_orig/')"
    eval "$(declare -f fmix_migration_ledger_is_prefix | sed '1s/fmix_migration_ledger_is_prefix/fmix_migration_ledger_is_prefix_gate_orig/')"
    eval "$(declare -f fmix_validate_db_integrity | sed '1s/fmix_validate_db_integrity/fmix_validate_db_integrity_gate_orig/')"
    eval "$(declare -f fmix_db_name_for_worktree | sed '1s/fmix_db_name_for_worktree/fmix_db_name_for_worktree_gate_orig/')"
    local zero_gate_snap_marker="$zero_gate_wt/snap-called"
    zero_gate_marker="$zero_gate_wt/zero-called"
    fmix_db_exists() { return 1; }
    fmix_db_name_for_worktree() { printf 'ct_fmix_abc12345\n'; }
    fmix_schema_key() { printf 'abcdef0123456789\n'; }
    fmix_select_indexed_base() { return 1; }
    fmix_ensure_snapshot_template() { : >"$zero_gate_snap_marker"; fmix_error "structure.sql fails the freshness gate (mocked)"; return 1; }
    fmix_migrate_from_zero() { : >"$zero_gate_marker"; return 0; }
    fmix_migration_ledger_is_prefix() { return 0; }
    fmix_validate_db_integrity() { return 0; }
    if fmix_ensure_db "$zero_gate_wt" ct_fmix_abc12345 1 1 1 >/dev/null 2>&1 \
        && [[ -e "$zero_gate_marker" ]] \
        && [[ "$FMIX_ACTIVE_DB_BASE_ID" == "migrate-from-zero" ]]; then
        st_pass "cold maintenance falls back to migrate-from-zero when the snapshot path fails"
    else
        st_fail "cold maintenance did not fall back to migrate-from-zero on a snapshot failure"
    fi

    rm -f "$zero_gate_marker" "$zero_gate_snap_marker"
    if fmix_ensure_db "$zero_gate_wt" ct_fmix_abc12345 1 1 1 1 >/dev/null 2>&1 \
        && [[ -e "$zero_gate_marker" ]] && [[ ! -e "$zero_gate_snap_marker" ]]; then
        st_pass "--from-zero (force_from_zero=1) skips the snapshot attempt entirely"
    else
        st_fail "--from-zero still attempted the snapshot path before falling back"
    fi
    eval "$(declare -f fmix_db_exists_gate_orig | sed '1s/fmix_db_exists_gate_orig/fmix_db_exists/')"
    eval "$(declare -f fmix_schema_key_gate_orig | sed '1s/fmix_schema_key_gate_orig/fmix_schema_key/')"
    eval "$(declare -f fmix_select_indexed_base_gate_orig | sed '1s/fmix_select_indexed_base_gate_orig/fmix_select_indexed_base/')"
    eval "$(declare -f fmix_ensure_snapshot_template_gate_orig | sed '1s/fmix_ensure_snapshot_template_gate_orig/fmix_ensure_snapshot_template/')"
    eval "$(declare -f fmix_migrate_from_zero_gate_orig | sed '1s/fmix_migrate_from_zero_gate_orig/fmix_migrate_from_zero/')"
    eval "$(declare -f fmix_migration_ledger_is_prefix_gate_orig | sed '1s/fmix_migration_ledger_is_prefix_gate_orig/fmix_migration_ledger_is_prefix/')"
    eval "$(declare -f fmix_validate_db_integrity_gate_orig | sed '1s/fmix_validate_db_integrity_gate_orig/fmix_validate_db_integrity/')"
    eval "$(declare -f fmix_db_name_for_worktree_gate_orig | sed '1s/fmix_db_name_for_worktree_gate_orig/fmix_db_name_for_worktree/')"
    rm -rf "$zero_gate_wt"

    # 5. Clone mode detection
    echo ""
    echo "--- Clone mode detection ---"
    local src_dir dst_dir
    src_dir="$(mktemp -d)"
    dst_dir="${src_dir}_clone"
    printf 'test content\n' >"$src_dir/file.txt"

    if fmix_cow_clone "$src_dir" "$dst_dir" 2>/dev/null; then
        if [[ -f "$dst_dir/file.txt" ]]; then
            st_pass "fmix_cow_clone: file exists in clone"
        else
            st_fail "fmix_cow_clone: clone succeeded but file missing"
        fi
    else
        st_fail "fmix_cow_clone failed entirely"
    fi
    rm -rf "$src_dir" "$dst_dir"

    # FMIX_COPY_MODE=full fallback
    local src2 dst2
    src2="$(mktemp -d)"
    dst2="${src2}_fullcopy"
    printf 'full copy test\n' >"$src2/file.txt"
    if FMIX_COPY_MODE=full fmix_cow_clone "$src2" "$dst2" 2>/dev/null; then
        if [[ -f "$dst2/file.txt" ]]; then
            st_pass "FMIX_COPY_MODE=full clone: file exists in copy"
        else
            st_fail "FMIX_COPY_MODE=full: copy succeeded but file missing"
        fi
    else
        st_fail "FMIX_COPY_MODE=full clone failed"
    fi
    rm -rf "$src2" "$dst2"

    # 6. psql detection chain
    echo ""
    echo "--- psql detection chain ---"
    local psql_found
    psql_found="$(fmix_find_psql 2>/dev/null)"
    if [[ -n "$psql_found" ]]; then
        st_pass "psql detected: $psql_found"
    else
        st_skip "psql not found (docker fallback also unavailable) — OK in bare container"
    fi

    # 7. postgres connectivity (skip in bare container)
    echo ""
    echo "--- postgres connectivity ---"
    if nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null; then
        if fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1; then
            st_pass "postgres $DB_HOST:$DB_PORT auth OK (user=$DB_USER)"
        else
            st_fail "postgres reachable but auth failed for user=$DB_USER — check FMIX_DB_PASSWORD"
        fi
    else
        st_skip "postgres $DB_HOST:$DB_PORT not reachable — OK in bare container or without infra.sh up"
    fi

    # 8. asdf toolchain (skip in bare container)
    echo ""
    echo "--- asdf toolchain ---"
    fmix_prepend_toolchain_paths
    if command -v asdf >/dev/null 2>&1; then
        local asdf_v
        asdf_v="$(asdf --version 2>/dev/null | head -1)"
        st_pass "asdf available: $asdf_v"
        # Test elixir from HOME (may not have .tool-versions, so skip is OK)
        local elx_v
        elx_v="$(elixir --version 2>/dev/null | grep 'Elixir' | awk '{print $2}')" || true
        if [[ -n "$elx_v" ]]; then
            st_pass "elixir available: $elx_v"
        else
            st_skip "elixir not active from current dir (run from a worktree with .tool-versions, or: asdf install)"
        fi
    else
        st_skip "asdf not installed — OK in bare container; install from https://asdf-vm.com"
    fi

    # 9. Worktree ID stability
    echo ""
    echo "--- Worktree ID stability ---"
    local id1 id2
    id1="$(fmix_worktree_id /tmp 2>/dev/null)"
    id2="$(fmix_worktree_id /tmp 2>/dev/null)"
    if [[ -n "$id1" && "$id1" == "$id2" && ${#id1} -eq 8 ]]; then
        st_pass "worktree_id stable: /tmp → $id1"
    else
        st_fail "worktree_id unstable or wrong length: '$id1' != '$id2'"
    fi

    local isolation_a isolation_b isolation_id_a isolation_id_b
    isolation_a="$(mktemp -d)"
    isolation_b="$(mktemp -d)"
    isolation_id_a="$(fmix_worktree_id "$isolation_a" 2>/dev/null)"
    isolation_id_b="$(fmix_worktree_id "$isolation_b" 2>/dev/null)"
    if [[ -n "$isolation_id_a" && -n "$isolation_id_b" \
        && "$isolation_id_a" != "$isolation_id_b" \
        && "$(fmix_worktree_state_file "$isolation_a")" != "$(fmix_worktree_state_file "$isolation_b")" \
        && "$(fmix_compile_stamp_file "$isolation_a")" != "$(fmix_compile_stamp_file "$isolation_b")" \
        && "$(fmix_dependency_stamp_file "$isolation_a")" != "$(fmix_dependency_stamp_file "$isolation_b")" \
        && "$(fmix_db_name_for_worktree "$isolation_a")" != "$(fmix_db_name_for_worktree "$isolation_b")" ]]; then
        st_pass "distinct canonical worktrees isolate state, compile/dependency stamps, locks, and databases"
    else
        st_fail "distinct canonical worktrees shared an FMix cache or database identity"
    fi
    rm -rf "$isolation_a" "$isolation_b"

    echo ""
    echo "--- Coverage isolation guard ---"
    local coverage_guard_rc=0 coverage_guard_diag=""
    coverage_guard_diag="$(cmd_test -- --cover test/example_test.exs 2>&1)" || coverage_guard_rc=$?
    if (( coverage_guard_rc == 2 )) \
        && [[ "$coverage_guard_diag" == *"Raw mix --cover is disabled"* ]] \
        && [[ "$coverage_guard_diag" == *"fmix coverage"* ]]; then
        st_pass "raw whole-application --cover is rejected before worktree preparation"
    else
        st_fail "raw --cover did not fail fast with targeted coverage guidance"
    fi

    coverage_guard_rc=0
    coverage_guard_diag="$(cmd_coverage -- test/example_test.exs 2>&1)" || coverage_guard_rc=$?
    if (( coverage_guard_rc == 2 )) \
        && [[ "$coverage_guard_diag" == *"requires --base"* ]] \
        && grep -qF 'mix run --no-start --no-compile' "${BASH_SOURCE[0]}" \
        && grep -qF 'Mix.TasksServer.put({:task, "compile", Mix.Project.get()})' "${BASH_SOURCE[0]}"; then
        st_pass "targeted coverage requires an explicit base and hard-disables Mix compilation"
    else
        st_fail "targeted coverage base/no-compile guard is missing"
    fi

    echo ""
    echo "--- Immutable runtime install ---"
    local install_fixture install_source install_home install_bin install_link
    local first_snapshot first_hash first_mode second_snapshot
    install_fixture="$(mktemp -d)"
    install_source="$install_fixture/fmix-source"
    install_home="$install_fixture/home"
    install_bin="$install_fixture/bin"
    install_link="$install_bin/fmix"
    cp "${BASH_SOURCE[0]}" "$install_source"
    chmod u+w "$install_source"
    first_snapshot="$(FMIX_HOME="$install_home" fmix_install_snapshot "$install_source" "$install_bin" 2>/dev/null)" || first_snapshot=""
    first_hash="$(fmix_hash_files "$install_source" 2>/dev/null | awk 'NR == 1 {print $1}')"
    first_mode=""
    if [[ -n "$first_snapshot" && -f "$first_snapshot" ]]; then
        if [[ "$FMIX_OS" == "Darwin" ]]; then
            first_mode="$(stat -f '%Lp' "$first_snapshot" 2>/dev/null || true)"
        else
            first_mode="$(stat -c '%a' "$first_snapshot" 2>/dev/null || true)"
        fi
    fi
    if [[ -n "$first_snapshot" \
        && "$first_snapshot" == "$install_home/runtime/fmix-$first_hash" \
        && -L "$install_link" \
        && "$(readlink "$install_link")" == "$first_snapshot" \
        && "$first_mode" == "555" \
        && "$("$install_link" version 2>/dev/null)" == "fmix $FMIX_VERSION" ]]; then
        st_pass "install publishes a verified read-only content-addressed runtime snapshot"
    else
        st_fail "install did not publish the expected immutable runtime snapshot"
    fi

    printf '\n# checkout changed after install\n' >>"$install_source"
    if [[ -n "$first_snapshot" \
        && "$(readlink "$install_link")" == "$first_snapshot" \
        && "$("$install_link" version 2>/dev/null)" == "fmix $FMIX_VERSION" ]]; then
        st_pass "installed runtime survives source-checkout mutation"
    else
        st_fail "source-checkout mutation changed the installed runtime"
    fi

    second_snapshot="$(FMIX_HOME="$install_home" fmix_install_snapshot "$install_source" "$install_bin" 2>/dev/null)" || second_snapshot=""
    if [[ -n "$second_snapshot" \
        && "$second_snapshot" != "$first_snapshot" \
        && -f "$first_snapshot" \
        && -f "$second_snapshot" \
        && "$(readlink "$install_link")" == "$second_snapshot" ]]; then
        st_pass "reinstall atomically selects a new snapshot without replacing the prior runtime"
    else
        st_fail "reinstall did not preserve immutable runtime generations"
    fi
    rm -rf "$install_fixture"

    if (( self_test_synthetic_toolchain == 1 )); then
        eval "$(declare -f fmix_activate_toolchain_self_test_orig |
            sed '1s/fmix_activate_toolchain_self_test_orig/fmix_activate_toolchain/')"
    fi
    unset -f fmix_activate_toolchain_self_test_orig
    if [[ "$self_test_saved_identity" == "__fmix_unset__" ]]; then
        unset FMIX_TOOLCHAIN_IDENTITY
    else
        FMIX_TOOLCHAIN_IDENTITY="$self_test_saved_identity"
        export FMIX_TOOLCHAIN_IDENTITY
    fi

    # Summary
    echo ""
    echo "=== self-test summary: PASS=$pass  FAIL=$fail  SKIP=$skip ==="
    if (( fail > 0 )); then
        echo "  RESULT: FAILED"
        return 1
    else
        echo "  RESULT: PASS"
        return 0
    fi
}

# ---------------------------------------------------------------------------
# cmd: fmix install — install an immutable, content-addressed runtime snapshot
# and atomically repoint PATH to it. The executable must never read from a Git
# worktree after startup: a pull/checkout in that worktree can otherwise change
# the script while Bash is still reading it.
# ---------------------------------------------------------------------------

fmix_install_snapshot() {
    local src="$1"
    local target_dir="$2"
    local runtime_dir="${FMIX_HOME}/runtime"

    if [[ -z "$src" || ! -f "$src" ]]; then
        fmix_error "Could not resolve the fmix source path to install."
        return 1
    fi
    mkdir -p "$target_dir" "$runtime_dir" || {
        fmix_error "Could not create the FMix install/runtime directories."
        return 1
    }

    local source_hash
    source_hash="$(fmix_hash_files "$src" 2>/dev/null | awk 'NR == 1 {print $1}')"
    if [[ ! "$source_hash" =~ ^[0-9a-f]{64}$ ]]; then
        fmix_error "Could not compute the FMix source SHA-256."
        return 1
    fi

    local snapshot="${runtime_dir}/fmix-${source_hash}"
    if [[ -e "$snapshot" ]]; then
        if [[ ! -f "$snapshot" || -L "$snapshot" ]]; then
            fmix_error "Runtime snapshot path is not an ordinary file: $snapshot"
            return 1
        fi
        local installed_hash
        installed_hash="$(fmix_hash_files "$snapshot" 2>/dev/null | awk 'NR == 1 {print $1}')"
        if [[ "$installed_hash" != "$source_hash" ]]; then
            fmix_error "Runtime snapshot hash mismatch at $snapshot; refusing to replace it in place."
            return 1
        fi
        if ! chmod 0555 "$snapshot"; then
            fmix_error "Could not restore executable read-only permissions on $snapshot."
            return 1
        fi
    else
        local snapshot_tmp
        snapshot_tmp="$(mktemp "${runtime_dir}/.fmix-${source_hash}.XXXXXX")" || {
            fmix_error "Could not allocate an FMix runtime snapshot."
            return 1
        }
        if ! cp "$src" "$snapshot_tmp" || ! chmod 0555 "$snapshot_tmp"; then
            rm -f "$snapshot_tmp"
            fmix_error "Could not write the FMix runtime snapshot."
            return 1
        fi
        local copied_hash
        copied_hash="$(fmix_hash_files "$snapshot_tmp" 2>/dev/null | awk 'NR == 1 {print $1}')"
        if [[ "$copied_hash" != "$source_hash" ]]; then
            rm -f "$snapshot_tmp"
            fmix_error "FMix runtime snapshot verification failed before publication."
            return 1
        fi
        if ! mv "$snapshot_tmp" "$snapshot"; then
            rm -f "$snapshot_tmp"
            fmix_error "Could not publish the FMix runtime snapshot."
            return 1
        fi
    fi

    local dest="$target_dir/fmix"
    if [[ -e "$dest" && ! -L "$dest" ]]; then
        fmix_error "$dest exists and is not a symlink — refusing to overwrite. Remove it or set FMIX_INSTALL_DIR."
        return 1
    fi

    local link_tmp="${target_dir}/.fmix-link-$$-${RANDOM}"
    if ! ln -s "$snapshot" "$link_tmp"; then
        fmix_error "Could not create the atomic FMix install link."
        return 1
    fi
    if ! mv -f "$link_tmp" "$dest"; then
        rm -f "$link_tmp"
        fmix_error "Could not atomically publish $dest."
        return 1
    fi

    printf '%s\n' "$snapshot"
}

cmd_install() {
    local target_dir="${FMIX_INSTALL_DIR:-$HOME/.local/bin}"
    local src snapshot
    src="$(fmix_realpath "${BASH_SOURCE[0]}")"
    snapshot="$(fmix_install_snapshot "$src" "$target_dir")" || return 1
    local dest="$target_dir/fmix"
    fmix_info "Installed: $dest -> $snapshot"
    fmix_info "Runtime is a content-addressed snapshot; Git checkout changes cannot alter an active FMix process."
    case ":$PATH:" in
        *":$target_dir:"*)
            fmix_info "$target_dir is on PATH — run 'fmix test --worktree <cisco-cdr-path> -- <args>' from anywhere." ;;
        *)
            fmix_warn "$target_dir is NOT on PATH. Add this to your shell rc (~/.zshrc), then restart the shell:"
            echo "    export PATH=\"$target_dir:\$PATH\"" >&2 ;;
    esac
    return 0
}

# ---------------------------------------------------------------------------
# Automatic upgrade-on-invocation (fail-open; never touches the command)
#
# Every eligible fmix invocation makes one cheap, read-only TTL check before
# command dispatch; when an attempt is due it runs detached and finishes after
# the command returns. The attempt probes the published fmix-vX.Y.Z release on
# calltelemetry/fmix for a newer version and, when found, verifies and installs
# it through the existing content-addressed runtime path (fmix_install_snapshot).
# The new runtime is picked up by the NEXT invocation: the running process
# always finishes on its own snapshot and nothing is ever exec'd mid-run.
#
# Fail-open contract: every failure mode — no network, no curl, rate limiting,
# partial download, digest mismatch, parse error, install refusal — ends the
# attempt silently with success status. An upgrade attempt can never change
# the invoking command's exit code, output contract, or artifacts.
#
# Skip conditions (documented in fmix_usage and docs/fmix.md):
#   - FMIX_NO_AUTO_UPGRADE=1 (explicit opt-out)
#   - CI / GITHUB_ACTIONS (pinned environments must not mutate mid-job)
#   - observability worker re-entry (FMIX_OBSERVABILITY_WORKER=1)
#   - self-test, doctor, install, cache (measurement, diagnosis, explicit
#     install, and inspection verbs describe the running snapshot exactly)
#   - help/version identity probes and every other read-only entrypoint
#     (fmix_readonly_entrypoint: includes gc --artifacts-only)
#   - anything that is not an installed runtime: a source checkout (./fmix)
#     or a sourced test copy is an intentional development context and never
#     self-upgrades
# TTY state is deliberately NOT a skip condition: fmix's primary invokers are
# headless agents and the attempt is fully detached and silent; the unsafe
# non-interactive environments are CI, which is skipped above.
# ---------------------------------------------------------------------------

fmix_auto_upgrade_stamp_file() {
    printf '%s/auto-upgrade.stamp\n' "${FMIX_HOME:-${HOME:-}/.ct-fmix}"
}

fmix_auto_upgrade_ttl_seconds() {
    # Silent fallback (no fmix_warn): the auto-upgrade path must never add
    # output to the invoking command.
    local ttl="${FMIX_AUTO_UPGRADE_TTL_S:-3600}"
    [[ "$ttl" =~ ^[0-9]+$ ]] || ttl=3600
    printf '%s\n' "$ttl"
}

fmix_auto_upgrade_stamp_due() {
    # Pure read: the attempt is due unless a stamp records one within the TTL.
    local stamp epoch now ttl age
    stamp="$(fmix_auto_upgrade_stamp_file)" || return 0
    [[ -f "$stamp" ]] || return 0
    IFS= read -r epoch < "$stamp" || return 0
    [[ "$epoch" =~ ^[0-9]+$ ]] || return 0
    now="$(fmix_epoch)"
    [[ "$now" =~ ^[0-9]+$ ]] || return 0
    ttl="$(fmix_auto_upgrade_ttl_seconds)"
    age=$(( now - epoch ))
    (( age >= 0 && age < ttl )) && return 1
    return 0
}

fmix_auto_upgrade_installed_runtime() {
    # Auto-upgrade keeps an *installed* runtime current. A source checkout or
    # a sourced test copy is a development context: it must never spawn an
    # upgrade that could repoint the stable launcher underneath its operator.
    local self home runtime_dir install_dir
    self="$(fmix_realpath "${BASH_SOURCE[0]}" 2>/dev/null || printf '%s' "${BASH_SOURCE[0]}")"
    home="${FMIX_HOME:-${HOME:-}/.ct-fmix}"
    home="$(fmix_realpath "$home" 2>/dev/null || printf '%s' "$home")"
    runtime_dir="$home/runtime"
    case "$self" in
        "$runtime_dir"/fmix-*) return 0 ;;
    esac
    install_dir="${FMIX_INSTALL_DIR:-${HOME:-}/.local/bin}"
    [[ "$self" == "$(fmix_realpath "$install_dir/fmix" 2>/dev/null || printf '')" ]] && return 0
    return 1
}

fmix_auto_upgrade_eligible() {
    local cmd="$1"
    shift
    [[ "${FMIX_NO_AUTO_UPGRADE:-0}" == "1" ]] && return 1
    [[ -n "${CI:-}" || -n "${GITHUB_ACTIONS:-}" ]] && return 1
    [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]] && return 1
    case "$cmd" in
        self-test|doctor|install|cache) return 1 ;;
    esac
    fmix_readonly_entrypoint "$cmd" "$@" && return 1
    fmix_auto_upgrade_installed_runtime || return 1
    return 0
}

fmix_auto_upgrade_version_newer() {
    # Strict X.Y.Z comparison: succeeds only when $1 is newer than $2.
    local newer="$1" older="$2"
    [[ "$newer" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
    [[ "$older" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
    local n_major n_minor n_patch o_major o_minor o_patch
    IFS=. read -r n_major n_minor n_patch <<<"$newer"
    IFS=. read -r o_major o_minor o_patch <<<"$older"
    if (( 10#$n_major != 10#$o_major )); then
        (( 10#$n_major > 10#$o_major )) && return 0
        return 1
    fi
    if (( 10#$n_minor != 10#$o_minor )); then
        (( 10#$n_minor > 10#$o_minor )) && return 0
        return 1
    fi
    (( 10#$n_patch > 10#$o_patch )) && return 0
    return 1
}

fmix_auto_upgrade_parse_latest_tag() {
    # Extracts X.Y.Z from a GitHub Releases API "tag_name":"fmix-vX.Y.Z" field.
    # sed on purpose — no JSON tool dependency — and a malformed or ambiguous
    # payload simply yields no version, which fails the attempt open.
    local json="$1" tag count
    count="$(printf '%s' "$json" | grep -o '"tag_name"' | wc -l | tr -d ' ')"
    [[ "$count" == "1" ]] || return 1
    tag="$(printf '%s' "$json" \
        | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"fmix-v\([0-9]\{1,\}\.[0-9]\{1,\}\.[0-9]\{1,\}\)".*/\1/p')"
    [[ "$tag" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
    printf '%s\n' "$tag"
}

fmix_auto_upgrade_latest_version() {
    # Version source: the published fmix-vX.Y.Z release identity on
    # calltelemetry/fmix (release.yml publishes tag + GitHub release). Bounded
    # timeouts so a dead network retires the detached attempt, not the host.
    local json
    command -v curl >/dev/null 2>&1 || return 1
    json="$(curl -fsSL --connect-timeout 5 --max-time 30 \
        -H 'Accept: application/vnd.github+json' \
        'https://api.github.com/repos/calltelemetry/fmix/releases/latest' 2>/dev/null)" || return 1
    fmix_auto_upgrade_parse_latest_tag "$json"
}

fmix_auto_upgrade_fetch_release() {
    # Downloads the fmix-v<V> release assets and verifies the full chain before
    # anything can be installed: tarball digest against the published .sha256,
    # runner digest against fmix.runnerSha256 in the published package
    # manifest, and the runner's own FMIX_VERSION line against the tag.
    local version="$1" out="$2"
    [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
    [[ -n "$out" && -d "$out" ]] || return 1
    command -v curl >/dev/null 2>&1 || return 1
    command -v tar >/dev/null 2>&1 || return 1
    local base="https://github.com/calltelemetry/fmix/releases/download/fmix-v${version}"
    curl -fsSL --connect-timeout 5 --max-time 60 \
        -o "$out/fmix.tar.gz.sha256" "$base/fmix-${version}.tar.gz.sha256" || return 1
    curl -fsSL --connect-timeout 5 --max-time 300 \
        -o "$out/fmix.tar.gz" "$base/fmix-${version}.tar.gz" || return 1
    curl -fsSL --connect-timeout 5 --max-time 60 \
        -o "$out/package.json" "$base/fmix-${version}.package.json" || return 1
    local want_tar have_tar manifest_sha have_runner declared
    want_tar="$(awk 'NR == 1 {print $1}' "$out/fmix.tar.gz.sha256")"
    [[ "$want_tar" =~ ^[0-9a-f]{64}$ ]] || return 1
    have_tar="$(fmix_hash_stdin < "$out/fmix.tar.gz")" || return 1
    [[ "$have_tar" == "$want_tar" ]] || return 1
    tar -xzf "$out/fmix.tar.gz" -C "$out" || return 1
    [[ -f "$out/fmix" && ! -L "$out/fmix" ]] || return 1
    manifest_sha="$(sed -n 's/.*"runnerSha256"[[:space:]]*:[[:space:]]*"\([0-9a-f]\{64\}\)".*/\1/p' "$out/package.json")"
    [[ "$manifest_sha" =~ ^[0-9a-f]{64}$ ]] || return 1
    have_runner="$(fmix_hash_stdin < "$out/fmix")" || return 1
    [[ "$have_runner" == "$manifest_sha" ]] || return 1
    declared="$(awk -F'"' '/^FMIX_VERSION=/{print $2; exit}' "$out/fmix")"
    [[ "$declared" == "$version" ]] || return 1
    return 0
}

fmix_auto_upgrade_claim_stamp() {
    # Records the attempt start time so at most one attempt runs per TTL
    # window regardless of its outcome. The stamp is written before any
    # network work: a failed probe is not retried until the TTL expires.
    local home="${FMIX_HOME:-${HOME:-}/.ct-fmix}" stamp tmp now
    stamp="$home/auto-upgrade.stamp"
    mkdir -p "$home" 2>/dev/null || return 1
    fmix_auto_upgrade_stamp_due || return 1
    now="$(fmix_epoch)"
    [[ "$now" =~ ^[0-9]+$ ]] || return 1
    tmp="$stamp.tmp.$$"
    printf '%s\n' "$now" > "$tmp" 2>/dev/null || return 1
    mv -f "$tmp" "$stamp" 2>/dev/null || { rm -f "$tmp" 2>/dev/null; return 1; }
    return 0
}

fmix_auto_upgrade_run() {
    # Real attempt body. "Success" means "nothing needed or nothing happened":
    # every exit path returns 0 so even a synchronous caller cannot observe an
    # upgrade failure in its own status.
    local latest tmp target
    fmix_auto_upgrade_claim_stamp || return 0
    latest="$(fmix_auto_upgrade_latest_version)" || return 0
    fmix_auto_upgrade_version_newer "$latest" "$FMIX_VERSION" || return 0
    tmp="$(mktemp -d "${TMPDIR:-/tmp}/fmix-auto-upgrade.XXXXXX")" || return 0
    target="${FMIX_INSTALL_DIR:-${HOME:-}/.local/bin}"
    if fmix_auto_upgrade_fetch_release "$latest" "$tmp" \
        && fmix_install_snapshot "$tmp/fmix" "$target" >/dev/null; then
        :
    fi
    rm -rf "$tmp"
    return 0
}

fmix_auto_upgrade_attempt() {
    # Fail-open, silent boundary: the attempt always reports success and never
    # writes to the invoking command's output streams.
    fmix_auto_upgrade_run >/dev/null 2>&1 </dev/null || true
    return 0
}

fmix_auto_upgrade_spawn() {
    # Detached background job: returns immediately and completes after the
    # command has finished. Redirected to /dev/null on every stream so it can
    # never touch the command's output contract, and immune to hangup so an
    # exiting shell does not kill the attempt mid-install.
    (
        trap '' HUP
        fmix_auto_upgrade_attempt
    ) >/dev/null 2>&1 </dev/null &
    return 0
}

fmix_maybe_auto_upgrade() {
    # Hook for main: cheap read-only gate, then a detached attempt. Always
    # returns 0 and never prints — an upgrade attempt must never change the
    # invoking command's exit code, output contract, or artifacts.
    fmix_auto_upgrade_eligible "$@" || return 0
    fmix_auto_upgrade_stamp_due || return 0
    fmix_auto_upgrade_spawn
    return 0
}

# ---------------------------------------------------------------------------
# Main dispatch
# ---------------------------------------------------------------------------

# Per-verb help: `fmix help <verb>` (or fmix_error hints) prints the focused
# usage for one verb plus its examples, without the full --help wall.
fmix_verb_help() {
    local verb="$1"
    case "$verb" in
        test)
            cat <<'VERB'
fmix test — run ExUnit targets inside a provisioned session DB.

Usage:
  fmix test [--worktree <path>] [--session <id>] [--isolate]
            [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--no-auto-setup]
            [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>

Notes:
  - A missing artifact template is auto-bootstrapped by delegating to
    fmix setup, then the artifacts step retries. Opt out with --no-auto-setup
    or FMIX_NO_AUTO_SETUP=1 to fail fast instead. Missing DB snapshots still
    require an explicit fmix setup --cold-db.
  - One worktree → one warm overlay (SUPER-HOT): pass --session only with a
    stable name plus --isolate for true parallel Mix on one checkout.
  - Slow DB startup = local snapshot recovery (see fmix status / fmix timing).
  - Slow compiles ("Compiling 47xx files") = session fragmentation; inspect
    with fmix timing --worktree <path>.

Examples:
  fmix test -- test/cdrcisco/sip/replaces_test.exs
  fmix test --worktree ./cisco-cdr -- test/cdrcisco/sip/replaces_test.exs
  fmix test --worktree ./cisco-cdr --cache-base 0.8.7-stable -- test/cdrcisco/sip/replaces_test.exs
VERB
            ;;
        coverage)
            cat <<'VERB'
fmix coverage — targeted diff-coverage gate (ADR 0054).

Usage:
  fmix coverage --worktree <path> [--session <id>] [--no-auto-setup]
                --base <git-ref> [--source <lib/**/*.ex>]... [--threshold 80]
                -- <test paths>

Notes:
  --base is REQUIRED: it defines the changed-module set. --source scopes
  cover-compilation to explicit modules (default: every changed lib module).
  A missing artifact template is auto-bootstrapped via fmix setup like the
  test lane; opt out with --no-auto-setup or FMIX_NO_AUTO_SETUP=1.
  Cannot gate staged-but-uncommitted changes — the bootstrap diffs the
  committed base...HEAD range. For staged gates use:
    fmix task -- cdrcisco.diff_coverage --staged --staged-diff <patch>

Examples:
  fmix coverage --worktree ./cisco-cdr --base origin/0.8.7-stable -- test/cdrcisco/sip/replaces_test.exs
  fmix coverage --worktree . --base HEAD --threshold 80 -- test/cdrcisco/call_health/poller_test.exs
VERB
            ;;
        task)
            cat <<'VERB'
fmix task — run one mix task in a provisioned session DB.

Usage:
  fmix task --worktree <path> [--session <id>] [--database <name>]
            [--mix-env <env>] [--allow-run] -- <mix task> [args]

Notes:
  ExUnit tasks are rejected — use fmix test so database and test-lane
  isolation stay enforced. --allow-run is required for tasks that shell out
  to git or external processes (e.g. cdrcisco.diff_coverage --staged).

Examples:
  fmix task --worktree ./cisco-cdr -- openapi.gen --format all
  fmix task --worktree ./cisco-cdr --database ct_dev --mix-env dev -- ecto.migrate
  fmix task --worktree . --mix-env test --allow-run -- cdrcisco.diff_coverage --staged \
      --staged-diff test-logs/coverage/diff/staged.patch --threshold 80
VERB
            ;;
        format)
            cat <<'VERB'
fmix format - format Elixir sources with the exact pinned toolchain.

Usage:
  fmix format [--worktree <path>] [--session <id>] [--mix-env <env>]
              [--dot-formatter <path>] [--check] -- <files...>

Notes:
  Uses the repo's .tool-versions pin and the same session deps/_build as
  fmix test, so formatter plugins (.formatter.exs import_deps) resolve the
  way CI compiles them. Never uses an ambient mise/asdf/global Elixir, which
  can silently rewrite unrelated hunks when its version differs from the
  pin. --check is read-only (--check-formatted) for CI and pre-push gates.
  --dot-formatter <path> formats the passed files with a specific formatter
  configuration (e.g. priv/repo/migrations/.formatter.exs) while deps still
  resolve from the project root — the equivalent of the `subdirectories`
  entries in a root .formatter.exs.
  Formatting is DB-free: no database is provisioned or contacted.

Examples:
  fmix format --worktree ./cisco-cdr -- lib/cdrcisco/pipeline_data.ex
  fmix format -- lib/**/*.ex
  fmix format --check -- lib/cdrcisco/pipeline_data.ex
  fmix format --dot-formatter priv/repo/migrations/.formatter.exs -- priv/repo/migrations/*.exs
VERB
            ;;
        setup)
            cat <<'VERB'
fmix setup — provision the session DB and build artifacts.

Usage:
  fmix setup [--worktree <path>] [--session <id>]
             [--rebuild-db|--cold-db|--from-zero]

Notes:
  --rebuild-db  drop and re-clone the scratch DB from a published base; never replays structure.sql
  --cold-db     rebuild from structure.sql, ignoring published bases, and replace the published base
  --from-zero   full migration chain from an empty DB, replacing the published base (structure.sql stale)

Example:
  fmix setup --worktree ./cisco-cdr
VERB
            ;;
        seed)
            cat <<'VERB'
fmix seed publish — explicit clean-stable-only maintenance.

Usage:
  fmix seed publish --worktree <path> --cache-base <N.N.N-stable>

Example:
  fmix seed publish --worktree ./cisco-cdr --cache-base 0.8.7-stable
VERB
            ;;
        cache)
            cat <<'VERB'
fmix cache — explain or verify the template cache; key and move pool entries.

Usage:
  fmix cache explain --worktree <path> --cache-base <N.N.N-stable>   # read-only
  fmix cache verify [--key <16-hex-template-key>]
  fmix cache keys --worktree <path>        # JSON {lane, dependency, exact, runner}; read-only
  fmix cache export --kind dependency|app --lane <64-hex> --exact <64-hex> --archive <file.tar.zst>
  fmix cache import --kind dependency|app --lane <64-hex> --exact <64-hex> --archive <file.tar.zst>

Example:
  fmix cache explain --worktree ./cisco-cdr --cache-base 0.8.7-stable
VERB
            ;;
        ensure)
            cat <<'VERB'
fmix ensure — idempotent toolchain + artifact readiness check (no network
when stamps are current).

Example:
  fmix ensure
VERB
            ;;
        doctor)
            cat <<'VERB'
fmix doctor — read-only host diagnostic (toolchain, DB, NATS, FMix state).

Example:
  fmix doctor
VERB
            ;;
        status)
            cat <<'VERB'
fmix status — read-only session/artifact/lock diagnostics. Exits 1 when
session metadata discovery is incomplete, still printing remaining sections.

Example:
  fmix status
VERB
            ;;
        analyze)
            cmd_analyze --help
            ;;
        timing)
            cat <<'VERB'
fmix timing — phase timings + session fragmentation report.

Usage:
  fmix timing [--limit N] [--worktree <path>]

Example:
  fmix timing --worktree ./cisco-cdr
VERB
            ;;
        gc)
            cat <<'VERB'
fmix gc — read-only artifact inventory or mixed session/DB/metadata maintenance.

Usage:
  fmix gc --artifacts-only [--json]
  fmix gc [--reap|--consolidate] [--worktree <path>] [--yes]

Notes:
  --artifacts-only is bounded read-only inventory: no initialization or eviction.
  Mixed GC can mutate sessions, databases and metadata; it is not artifact-only cleanup.
  Published dependency/template artifacts and recovery staging remain held.
  Review the fmix status report before --reap --yes.

Examples:
  fmix gc --artifacts-only --json
  fmix gc
  fmix gc --consolidate --worktree ./cisco-cdr --yes
VERB
            ;;
        install)
            cat <<'VERB'
fmix install — immutable runtime snapshot + atomic PATH link (~/.local/bin).

Example:
  fmix install
VERB
            ;;
        self-test)
            cat <<'VERB'
fmix self-test — run the runner's internal correctness suite.

Example:
  fmix self-test
VERB
            ;;
        verify-push)
            cat <<'VERB'
fmix verify-push — pre-push circuit breaker enforcing local test proof and push rate-limiting.

Usage:
  fmix verify-push [--worktree <path>] [--cooldown-minutes <N>] [--require-receipt]

Notes:
  - Bypassed if CT_HUMAN=1 or FMIX_BYPASS_PUSH_GATE=1.
  - Bypassed for docs/workflow-only diffs (no Elixir files modified).
  - Bypassed for draft PRs or branches without an open PR.
  - Enforces ct-fmix-receipt.json match for open non-draft PRs.
  - Limits push frequency to max 2 pushes per cooldown window without a new passing test receipt.
VERB
            ;;
        hook)
            cat <<'VERB'
fmix hook — manage git hooks for fmix.

Usage:
  fmix hook install [--worktree <path>]

Notes:
  Installs a git pre-push hook invoking fmix verify-push.
VERB
            ;;
        runner)
            cat <<'VERB'
fmix runner — CLI surface for the distributed runner (submit, poll, receipts).

Usage:
  fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]
  fmix runner status <job-id>
  fmix runner logs <job-id> [--tail N]
  fmix runner cancel <job-id>
  fmix runner list [--worktree <name>] [--state <state>]
  fmix runner receipt <job-id> [--verify [--pubkey <path>]]
  fmix runner install-hooks [--worktree <path>] [--legacy] [--force]
  fmix runner gc-worktree <worktree>

Notes:
  - Transport is REST against the runner portal base URL (FMIX_RUNNER_URL);
    the portal signs the inner HMAC envelope for orchestrator hops itself.
  - Auth: Cloudflare Access service-token headers from
    CF_ACCESS_CLIENT_ID / CF_ACCESS_CLIENT_SECRET, falling back to the
    per-user pair MCP_ACCESS_CLIENT_ID_${USER} / MCP_ACCESS_CLIENT_SECRET_${USER},
    then FMIX_RUNNER_TOKEN as a bearer token. Missing credentials fail
    before any request is sent.
  - submit resolves the worktree (default: current git worktree), the repo
    from the origin remote (owner/name), and the ref (default: HEAD SHA);
    everything after `--` is the lane command plus its pass-through args.
  - receipt --verify checks the Ed25519 signature offline against the
    canonical JSON signing view; the key comes from --pubkey or
    FMIX_RUNNER_PUBKEY and verification is fail-closed (openssl pkeyutl,
    python3 fallback).
  - install-hooks wires the runner pre-push hook (core.hooksPath .githooks by
    default, .git/hooks with --legacy); it is idempotent and never clobbers a
    foreign hook without --force.

Examples:
  fmix runner submit --worktree . -- test
  fmix runner submit --worktree ./cisco-cdr --ref origin/main -- test test/cdrcisco/sip/replaces_test.exs
  fmix runner status job-7f3k2
  fmix runner logs job-7f3k2 --tail 200
  fmix runner receipt job-7f3k2 --verify --pubkey ~/.config/calltelemetry/fmix-runner.pub
  fmix runner install-hooks
  fmix runner gc-worktree cisco-cdr

Environment:
  FMIX_RUNNER_URL       Portal base URL (default: https://mcp.calltelemetry.com/fmix-runner)
  FMIX_RUNNER_TOKEN     Bearer token fallback (also used by the pre-push hook)
  FMIX_RUNNER_PUBKEY    Ed25519 receipt public key for `receipt --verify`
  CF_ACCESS_CLIENT_ID / CF_ACCESS_CLIENT_SECRET  Cloudflare Access service token
VERB
            ;;
        *)
            fmix_error "No focused help for '$verb'. Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, analyze, gc, install, self-test, verify-push, hook, runner, version, help"
            return 1
            ;;
    esac
}

fmix_usage() {
    cat <<'USAGE'
fmix — fast native Elixir test runner for cisco-cdr

Usage:
  ./fmix test [--worktree <path>] [--session <id>] [--no-auto-setup] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>
  ./fmix coverage [--worktree <path>] [--session <id>] [--no-auto-setup] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>
  ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
  ./fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--dot-formatter <path>] [--check] -- <files...>
  ./fmix setup [--worktree <path>] [--session <id>] [--rebuild-db|--cold-db|--from-zero]
  ./fmix seed publish --worktree <path> [--session <id>] --cache-base <N.N.N-stable>
  ./fmix cache explain --worktree <path> --cache-base <N.N.N-stable>
  ./fmix cache verify [--key <16-hex-template-key>]
  ./fmix verify-push [--worktree <path>] [--cooldown-minutes <N>] [--require-receipt]
  ./fmix hook install [--worktree <path>]
  ./fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]
  ./fmix runner <status|logs|cancel|receipt> <job-id>   # logs --tail N; receipt --verify
  ./fmix runner list [--worktree <name>] [--state <state>]
  ./fmix runner install-hooks [--worktree <path>] [--legacy] [--force]
  ./fmix runner gc-worktree <worktree>
  ./fmix ensure
  ./fmix doctor
  ./fmix status
  ./fmix timing [--limit N] [--worktree <path>]   # phase timings + session fragmentation
  ./fmix analyze report --run <UUID> --output <new-dir>
  ./fmix analyze hotspots --run <UUID> [--limit 20]   # ranked JSON, no test execution
  ./fmix gc --artifacts-only [--json]   # bounded read-only inventory; no eviction
  ./fmix gc [--reap|--consolidate] [--worktree <path>] [--yes]
  ./fmix install            # immutable snapshot + atomic PATH link (~/.local/bin)
  ./fmix self-test
  ./fmix --help             # display this help documentation

Examples:
  ./fmix test -- test/cdrcisco/sip/replaces_test.exs
  ./fmix test --worktree ./cisco-cdr -- test/cdrcisco/sip/replaces_test.exs
  ./fmix test --worktree ./cisco-cdr --cache-base 0.8.7-stable -- test/cdrcisco/sip/replaces_test.exs
  ./fmix coverage --worktree ./cisco-cdr --base origin/0.8.7-stable -- test/cdrcisco/sip/replaces_test.exs
  ./fmix task --worktree ./cisco-cdr -- openapi.gen --format all
  ./fmix task --worktree ./cisco-cdr --database ct_dev --mix-env dev -- ecto.migrate
  ./fmix setup --worktree ./cisco-cdr
  ./fmix setup --rebuild-db --worktree ./cisco-cdr # drop and re-clone the scratch DB from a published base; never replays structure.sql
  ./fmix setup --cold-db --worktree ./cisco-cdr  # rebuild from structure.sql, ignoring and replacing the published base
  ./fmix setup --from-zero --worktree ./cisco-cdr  # full migration chain from an empty DB, replacing the published base; structure.sql unusable/stale
  ./fmix seed publish --worktree ./cisco-cdr --cache-base 0.8.7-stable
  ./fmix cache explain --worktree ./cisco-cdr --cache-base 0.8.7-stable
  ./fmix doctor
  ./fmix timing --worktree ./cisco-cdr
  ./fmix gc
  ./fmix gc --consolidate --yes
  ./fmix gc --reap --yes
  ./fmix runner submit --worktree . -- test
  ./fmix runner logs job-7f3k2 --tail 200
  ./fmix runner install-hooks   # pre-push hook install for the runner lane

Operational notes:
  SUPER-HOT contract (2.2.0+): one worktree → one warm overlay by default.
  NEVER pass unique --session / FMIX_SESSION_ID per tool call.
  USE bare: fmix test --worktree <path> -- <tests>
  USE --session <stable-name> --isolate only for true parallel Mix on one checkout.
  CODEX_THREAD_ID is ignored unless FMIX_THREAD_SESSIONS=1.
  Ephemeral ids (UUID, pure hex, codex:/github: prefixes) remap to worktree-default
  unless FMIX_FORCE_SESSION=1.
  Slow DB startup usually means local snapshot recovery. Check ./fmix status,
  then use ./fmix gc --reap --yes only after reviewing the report.
  Slow compiles / "Compiling 47xx files" means session fragmentation or first
  compile. Inspect with: ./fmix timing --worktree <path>
  Reclaim multi-sessions: ./fmix gc --consolidate --worktree <path> --yes
  Every run appends one JSON line to $FMIX_HOME/logs/runs.jsonl and prints
  a greppable "timing total=… hot_path=yes|no" summary on stderr.
  fmix status exits 1 when session metadata discovery is incomplete, while
  still printing the remaining read-only diagnostic sections.
  Stable seeds are dependency-only; fmix test still validates app artifacts locally.
  Template cache reads are lock-free (no build lease); only producers,
  publication, quarantine, and retirement mutate the CAS under a lease.

Environment overrides:
  FMIX_HOME           State directory (default: ~/.ct-fmix)
  FMIX_SESSION_ID     Stable logical session identity (or pass --session)
  FMIX_ISOLATE        Set to 1 with a stable session name for parallel Mix
  FMIX_NO_AUTO_SETUP  Set to 1 to stop test/coverage lanes from auto-running
                      fmix setup on a missing artifact template (same effect
                      as --no-auto-setup)
  FMIX_NO_AUTO_UPGRADE  Set to 1 to disable automatic upgrade-on-invocation
  FMIX_AUTO_UPGRADE_TTL_S  Minimum seconds between background upgrade attempts
                      (default: 3600; invalid values silently fall back to 3600)
  FMIX_FORCE_SESSION  Set to 1 to allow ephemeral session ids (cold path)
  FMIX_THREAD_SESSIONS Set to 1 to restore CODEX_THREAD_ID session binding
  FMIX_HOT_PATH_BUDGET_S  hot_path overhead budget seconds excl mix_test (default: 25)
  FMIX_SCHEMA_READY_TTL_S Schema-ready stamp TTL; auto-expire ledger skip (default: 300)
  FMIX_AUTO_EXPIRE_MAX  Artifact auto-expire retirement operations per
                      preparation pass (default: 3; bounded 1-10; invalid
                      values fall back to the default)
  OBAN_LICENSE_KEY    Oban Pro license key override (or from ~/.config/calltelemetry/fmix.env / Doppler)
  FMIX_SESSION_TTL_HOURS Inactive-session auto-purge and GC threshold (default: 4)
  FMIX_SESSION_TTL_DAYS  Legacy compatibility override, converted to hours when FMIX_SESSION_TTL_HOURS is unset
  FMIX_CACHE_TTL_DAYS Legacy compatibility fallback used when the hour/day overrides are unset
  FMIX_CONFIG_HOME    Private configuration directory (default: ~/.config/calltelemetry)
  FMIX_ENV_FILE       Explicit credential file (default: <config-home>/fmix.env)
  FMIX_DOPPLER_PROJECT  Doppler project for credential fallback (default: ai-workspace)
  FMIX_DOPPLER_CONFIG   Doppler config for credential fallback (default: dev_personal)
  FMIX_SESSION_WARN_THRESHOLD  Per-host session count that triggers a gc warning (default: 24)
  FMIX_STABLE_BASE    Opt-in stable dependency base for fmix test (default: unset)
  FMIX_DB_HOST        Postgres host (default: localhost)
  FMIX_DB_PORT        Postgres port (default: 5432)
  FMIX_DB_USER        Postgres user (default: calltelemetry)
  FMIX_DB_PASSWORD    Postgres password (default: calltelemetry_dev_password)
  FMIX_NATS_HOST      NATS host (default: nats-dev if its JetStream answers, else a healthy localhost, else localhost)
  FMIX_TAILNET_NATS_HOST  Tailnet NATS host to probe (default: nats-dev)
  FMIX_NATS_PROBE_TIMEOUT  Seconds allowed per JetStream probe round trip (default: 3)
  FMIX_DISABLE_TAILNET_NATS  Set to 1 to skip Tailnet probing (default: 1 on CI)
  FMIX_NATS_PORT      NATS port (default: 4222)
  FMIX_COPY_MODE      Set to 'full' to disable CoW clone
  FMIX_LOCK_TIMEOUT   Lock wait timeout in seconds (default: 900)
  FMIX_LOCK_INIT_GRACE  Grace before reclaiming a pid-less lock (default: 5)
  FMIX_WORKTREE_LOCK_TIMEOUT  Same-worktree run wait cap in seconds (default: 360)
  FMIX_SESSION_LOCK_SPLIT  0 forces exclusive-only session locks (default: 1)
  FMIX_HOST_TEST_LOCK     Set to 0 only to bypass CREATE/DROP serialization
  FMIX_HOST_LOCK_TIMEOUT  Host database-DDL lock wait cap in seconds (default: 60)
  FMIX_DB_CREATE_ADMISSION  Set to 0 only to bypass DB pressure admission
  FMIX_DB_ADMISSION_TIMEOUT Admission wait in seconds (default: 20)
  FMIX_DB_PRESSURE_MIN_AGE  Sustained wait age in seconds (default: 10)
  FMIX_DB_CREATE_TIMEOUT    CREATE DATABASE statement cap in seconds (default: 60)
  FMIX_DB_DROP_TIMEOUT      DROP DATABASE statement cap in seconds (default: 30)
  FMIX_MIGRATION_DELTA_LIMIT  Maximum migrations applied from a selected base (default: 50)
  FMIX_COMPILE_HEARTBEAT    Silent compile heartbeat seconds (default: 30; 0 disables)
  FMIX_COMPILE_TIMEOUT      Per-attempt compile cap in seconds (default: 900)
  FMIX_SETUP_COMPILE_TIMEOUT  Explicit setup compile absolute ceiling in seconds (default: 7200)
  FMIX_SETUP_COMPILE_STALL_TIMEOUT  Explicit setup no-output stall budget in seconds (default: 600)
  FMIX_TIMING               Set to 1 to print per-phase timing lines during a run
  FMIX_MIGRATION_TIMEOUT    Migration delta cap in seconds (default: 120)
  FMIX_STRUCTURE_LOAD_TIMEOUT    explicit cold structure.sql replay cap in seconds (default: 120)
  FMIX_STRUCTURE_LOAD_HEARTBEAT  structure.sql replay heartbeat seconds (default: 30)
  FMIX_RUNNER_URL     Distributed runner portal base URL (default: https://mcp.calltelemetry.com/fmix-runner)
  FMIX_RUNNER_TOKEN   Bearer token for runner portal/hook endpoints (per-dev, revocable)
  FMIX_RUNNER_PUBKEY  Ed25519 receipt public key for 'fmix runner receipt --verify'
  CF_ACCESS_CLIENT_ID / CF_ACCESS_CLIENT_SECRET  Cloudflare Access service token for the runner portal
                      (per-user fallback: MCP_ACCESS_CLIENT_ID_${USER} / MCP_ACCESS_CLIENT_SECRET_${USER})
  FMIX_INSTALL_DIR    Target dir for 'fmix install' (default: ~/.local/bin)
USAGE
}

fmix_observability_supervisor_source() {
    command cat <<'PY'
import datetime
import errno
import fcntl
import hashlib
import json
import math
import os
import re
import select
import signal
import shutil
import stat
import subprocess
import sys
import time

RUNNER = os.path.realpath(sys.argv[1])
ARGS = sys.argv[2:]
RUN_ID = os.environ.get("FMIX_RUN_ID", "")
FMIX_VERSION = os.environ.get("FMIX_VERSION", "2.4.3")
MAX_HANDOFF = 65536
MAX_UPDATE_BUFFER = 32768
MAX_UPDATE_DRAIN_BYTES = 65536
MAX_UPDATE_FRAMES_PER_TURN = 1
MAX_UPDATE_FIELD = 4096
MANAGED = (signal.SIGHUP, signal.SIGINT, signal.SIGTERM)
SIGNAL_CODES = {signal.SIGHUP: 129, signal.SIGINT: 130, signal.SIGTERM: 143}
degraded = False
ARTIFACT_SCHEMA = "test-artifacts.v1"
ARTIFACT_MAX_BYTES = 64 * 1024 * 1024
ARTIFACT_MAX_JSON_LINE = 64 * 1024
ARTIFACT_TTL_SECONDS = 4 * 60 * 60
diagnostics_enabled = os.environ.get("FMIX_OBSERVABILITY_DIAGNOSTICS") == "1"
update_timings = []
active_update_timing = None
startup_signal_mask = signal.pthread_sigmask(
    signal.SIG_BLOCK, set(MANAGED) | {signal.SIGALRM}
)
previous_alarm_handler = signal.getsignal(signal.SIGALRM)
signal.setitimer(signal.ITIMER_REAL, 0)
while signal.SIGALRM in signal.sigpending():
    signal.sigwait({signal.SIGALRM})
supervisor_signal_mask = set(startup_signal_mask)
supervisor_signal_mask.add(signal.SIGALRM)


def fail(message, code=125):
    os.write(2, ("fmix: observability supervisor: " + message + "\n").encode())
    raise SystemExit(code)


def utc_now():
    return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def utc_after(value, seconds):
    parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
    return (parsed + datetime.timedelta(seconds=seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")


def lstat_safe(path, expected_mode, kind):
    info = os.lstat(path)
    if stat.S_ISLNK(info.st_mode):
        fail("refusing symlink " + path)
    if kind == "directory" and not stat.S_ISDIR(info.st_mode):
        fail("expected directory " + path)
    if kind == "file" and not stat.S_ISREG(info.st_mode):
        fail("expected regular file " + path)
    if info.st_uid != os.geteuid():
        fail("unsafe ownership " + path)
    if stat.S_IMODE(info.st_mode) != expected_mode:
        fail("unsafe mode " + path)
    return info


def ensure_dir(path):
    try:
        os.mkdir(path, 0o700)
    except FileExistsError:
        pass
    lstat_safe(path, 0o700, "directory")


home = os.path.abspath(os.environ.get("FMIX_HOME", os.path.expanduser("~/.ct-fmix")))
if home == "/" or not os.path.isabs(home):
    fail("unsafe FMIX_HOME")
ensure_dir(home)
telemetry_root = os.path.join(home, "telemetry")
runs_root = os.path.join(telemetry_root, "runs")
ensure_dir(telemetry_root)
ensure_dir(runs_root)


def safe_artifact_run_id(value):
    return bool(re.fullmatch(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", value))


artifact_root = telemetry_root
artifact_runs_root = runs_root


def purge_lstat(path, expected_mode, kind):
    """Return metadata only for a safe, still-present artifact path."""
    try:
        info = os.lstat(path)
    except OSError:
        return None
    if stat.S_ISLNK(info.st_mode):
        return None
    if kind == "directory" and not stat.S_ISDIR(info.st_mode):
        return None
    if kind == "file" and not stat.S_ISREG(info.st_mode):
        return None
    if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != expected_mode:
        return None
    return info


def finite_observed_write(path):
    """Return the newest finite mtime, or None when a safe scan is impossible."""
    observed = []
    pending = [path]
    while pending:
        current = pending.pop()
        try:
            info = os.lstat(current)
        except OSError:
            return None
        if stat.S_ISLNK(info.st_mode) or info.st_uid != os.geteuid():
            return None
        if stat.S_ISDIR(info.st_mode):
            if stat.S_IMODE(info.st_mode) != 0o700:
                return None
        elif not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600:
            return None
        mtime = info.st_mtime
        if not math.isfinite(mtime):
            return None
        observed.append(mtime)
        if stat.S_ISDIR(info.st_mode):
            try:
                children = list(os.scandir(current))
            except OSError:
                return None
            pending.extend(child.path for child in children)
    return max(observed) if observed else None


def artifact_manifest_expiry(manifest, run_id, now):
    """Trust expiresAt only when the complete local manifest shape is valid."""
    if not isinstance(manifest, dict):
        return None
    if manifest.get("version") != ARTIFACT_SCHEMA:
        return None
    if manifest.get("runId") != run_id or manifest.get("storage") != "local":
        return None
    if manifest.get("state") not in {"pending", "available", "degraded"}:
        return None
    if manifest.get("state") == "degraded" and not isinstance(manifest.get("degraded"), str):
        return None
    if not isinstance(manifest.get("artifacts"), list):
        return None
    for descriptor in manifest["artifacts"]:
        if not isinstance(descriptor, dict):
            return None
        required = {
            "name",
            "kind",
            "contentType",
            "sizeBytes",
            "sha256",
            "storage",
            "redacted",
            "truncated",
        }
        if not required.issubset(descriptor):
            return None
        name = descriptor["name"]
        if (
            not isinstance(name, str)
            or name.startswith("/")
            or any(part in {"", ".", ".."} for part in name.split("/"))
        ):
            return None
        if (
            descriptor["storage"] != "local"
            or descriptor["redacted"] is not True
            or descriptor["truncated"] is not False
            or not isinstance(descriptor["kind"], str)
            or not isinstance(descriptor["contentType"], str)
            or isinstance(descriptor["sizeBytes"], bool)
            or not isinstance(descriptor["sizeBytes"], int)
            or not 0 <= descriptor["sizeBytes"] <= ARTIFACT_MAX_BYTES
            or not isinstance(descriptor["sha256"], str)
            or not re.fullmatch(r"[0-9a-f]{64}", descriptor["sha256"])
        ):
            return None
    timestamps = []
    for field in ("createdAt", "expiresAt"):
        value = manifest.get(field)
        if not isinstance(value, str):
            return None
        try:
            parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
            if parsed.tzinfo is None:
                return None
            timestamp = parsed.timestamp()
        except (OverflowError, TypeError, ValueError):
            return None
        if not math.isfinite(timestamp):
            return None
        timestamps.append(timestamp)
    if (
        timestamps[0] > now
        or timestamps[1] < timestamps[0]
        or timestamps[1] - timestamps[0] > ARTIFACT_TTL_SECONDS
    ):
        return None
    return timestamps[1]


def purge_artifacts():
    """Remove only expired, UUID-addressed artifact namespaces."""
    now = datetime.datetime.now(datetime.timezone.utc).timestamp()
    try:
        entries = list(os.scandir(artifact_runs_root))
    except OSError:
        return
    for entry in entries:
        try:
            is_run_dir = entry.is_dir(follow_symlinks=False)
        except OSError:
            continue
        if not is_run_dir or not safe_artifact_run_id(entry.name):
            continue
        namespace = os.path.join(entry.path, "artifacts")
        manifest_path = os.path.join(namespace, "manifest.json")
        namespace_info = purge_lstat(namespace, 0o700, "directory")
        manifest_info = purge_lstat(manifest_path, 0o600, "file")
        if namespace_info is None:
            continue
        if manifest_info is None:
            try:
                manifest_present = os.path.lexists(manifest_path)
            except OSError:
                continue
            # An unsafe manifest path is never a reason to delete its parent;
            # only a genuinely absent manifest can use the namespace fallback.
            if manifest_present:
                continue
        expiry = None
        try:
            if manifest_info is not None:
                with open(manifest_path, "r", encoding="utf-8") as manifest_file:
                    manifest = json.load(manifest_file)
                expiry = artifact_manifest_expiry(manifest, entry.name, now)
        except (OSError, OverflowError, ValueError, TypeError, json.JSONDecodeError):
            expiry = None
        if expiry is None:
            observed_write = finite_observed_write(namespace)
            if observed_write is None:
                continue
            expiry = observed_write + ARTIFACT_TTL_SECONDS
        if now < expiry:
            continue
        try:
            shutil.rmtree(namespace)
        except OSError:
            # Another supervisor may be publishing or removing this namespace,
            # or local permissions may have changed. Preserve it for the next
            # bounded housekeeping pass; startup must remain usable.
            continue


purge_artifacts()
run_dir = os.path.join(runs_root, RUN_ID)
ensure_dir(run_dir)
if os.path.dirname(os.path.realpath(run_dir)) != os.path.realpath(runs_root):
    fail("run path escaped telemetry root")

snapshot_path = os.path.join(run_dir, "snapshot.json")
events_path = os.path.join(run_dir, "events.jsonl")
metrics_path = os.path.join(run_dir, "metrics.jsonl")
update_timing_path = os.path.join(run_dir, ".update-timing.jsonl")
stop_path = os.path.join(run_dir, ".sampler-stop")
artifact_run_dir = os.path.join(run_dir, "artifacts")
artifact_fmix_dir = os.path.join(artifact_run_dir, "fmix")
artifact_manifest_path = os.path.join(artifact_run_dir, "manifest.json")
artifact_created_at = utc_now()
artifact_expires_at = utc_after(artifact_created_at, ARTIFACT_TTL_SECONDS)
if os.path.lexists(artifact_run_dir):
    lstat_safe(artifact_run_dir, 0o700, "directory")
    if os.path.lexists(artifact_manifest_path):
        lstat_safe(artifact_manifest_path, 0o600, "file")
        try:
            with open(artifact_manifest_path, "r", encoding="utf-8") as existing_manifest_file:
                existing_manifest = json.load(existing_manifest_file)
        except (OSError, ValueError, TypeError, json.JSONDecodeError):
            fail("existing artifact manifest is malformed")
        if existing_manifest.get("state") != "pending":
            fail("run id already has terminal artifact evidence")
else:
    ensure_dir(artifact_run_dir)
ensure_dir(artifact_fmix_dir)
artifact_logs_dir = os.path.join(artifact_run_dir, "logs")
artifact_junit_dir = os.path.join(artifact_run_dir, "junit")
artifact_stats_dir = os.path.join(artifact_run_dir, "stats")
artifact_live_dir = os.path.join(artifact_run_dir, "live")
artifact_live_runs_dir = os.path.join(artifact_live_dir, "runs")
artifact_live_run_dir = os.path.join(artifact_live_runs_dir, RUN_ID)
for artifact_directory in (
    artifact_logs_dir, artifact_junit_dir, artifact_stats_dir,
    artifact_live_dir, artifact_live_runs_dir, artifact_live_run_dir,
):
    ensure_dir(artifact_directory)
for public_path in (snapshot_path, events_path, metrics_path):
    if os.path.lexists(public_path):
        lstat_safe(public_path, 0o600, "file")

nofollow = getattr(os, "O_NOFOLLOW", 0)
events_fd = os.open(events_path, os.O_RDWR | os.O_CREAT | os.O_APPEND | nofollow, 0o600)
events_info = os.fstat(events_fd)
if not stat.S_ISREG(events_info.st_mode) or events_info.st_uid != os.geteuid() or stat.S_IMODE(events_info.st_mode) != 0o600:
    fail("unsafe events file")
if events_info.st_size != 0:
    fail("run id already has event evidence")


def timed_fsync(fd, field):
    started_ns = time.monotonic_ns() if active_update_timing is not None else None
    try:
        os.fsync(fd)
    finally:
        if started_ns is not None and active_update_timing is not None:
            active_update_timing[field] += max(0, time.monotonic_ns() - started_ns)


def dir_fsync():
    flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
    directory_fd = os.open(run_dir, flags)
    try:
        timed_fsync(directory_fd, "snapshotDirectoryFsyncNs")
    finally:
        os.close(directory_fd)


def write_all(fd, payload):
    view = memoryview(payload)
    offset = 0
    while offset < len(view):
        written = os.write(fd, view[offset:])
        if not isinstance(written, int) or written <= 0:
            raise OSError(errno.EIO, "short write")
        offset += written


def artifact_dir_fsync(directory):
    flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
    directory_fd = os.open(directory, flags)
    try:
        os.fsync(directory_fd)
    finally:
        os.close(directory_fd)


def atomic_artifact_json(path, document):
    temporary = path + ".tmp-" + str(os.getpid())
    fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600)
    try:
        payload = json.dumps(document, separators=(",", ":")).encode() + b"\n"
        write_all(fd, payload)
        os.fsync(fd)
        os.close(fd)
        fd = None
        os.replace(temporary, path)
        artifact_dir_fsync(os.path.dirname(path))
    finally:
        if fd is not None:
            os.close(fd)
        try:
            os.unlink(temporary)
        except FileNotFoundError:
            pass


def artifact_read_bounded(source_fd, size):
    if size > ARTIFACT_MAX_BYTES:
        raise ValueError("artifact_too_large")
    remaining = size
    chunks = []
    while remaining:
        chunk = os.read(source_fd, min(65536, remaining))
        if not chunk:
            raise ValueError("artifact_truncated")
        chunks.append(chunk)
        remaining -= len(chunk)
    if os.read(source_fd, 1):
        raise ValueError("artifact_grew")
    return b"".join(chunks)


def artifact_project_snapshot(raw):
    if not isinstance(raw, dict):
        raise ValueError("invalid_snapshot")
    allowed = {
        "version", "runId", "fmixVersion", "launcherPid", "pid", "state", "phase",
        "command", "exitCode", "startedAt", "updatedAt", "finishedAt", "metrics",
        "resources", "telemetry", "termination", "phases", "durationSeconds", "cache",
        "compile", "session", "artifacts", "templateKey", "database", "worktree",
    }
    if set(raw) - allowed:
        raise ValueError("unknown_snapshot_field")
    projected = {key: value for key, value in raw.items() if key != "worktree"}
    if "session" in projected:
        if not isinstance(projected["session"], dict):
            raise ValueError("invalid_snapshot_session")
        session_allowed = {"hash", "source", "root"}
        if set(projected["session"]) - session_allowed:
            raise ValueError("unknown_snapshot_session_field")
        projected["session"] = {
            key: value for key, value in projected["session"].items() if key != "root"
        }
    if projected.get("version") != "fmix-session.v1" or projected.get("runId") != RUN_ID:
        raise ValueError("invalid_snapshot_identity")
    return projected


def artifact_project_jsonl_line(raw, kind):
    try:
        value = json.loads(raw)
    except (UnicodeDecodeError, json.JSONDecodeError):
        raise ValueError("invalid_artifact_json")
    if not isinstance(value, dict):
        raise ValueError("invalid_artifact_record")
    def valid_timestamp(candidate):
        if not isinstance(candidate, str) or len(candidate) > 64:
            return False
        try:
            return datetime.datetime.fromisoformat(candidate.replace("Z", "+00:00")).tzinfo is not None
        except (TypeError, ValueError):
            return False

    def valid_nonnegative_number(candidate):
        return (
            isinstance(candidate, (int, float))
            and not isinstance(candidate, bool)
            and math.isfinite(candidate)
            and candidate >= 0
        )

    if kind == "events":
        allowed = {"version", "runId", "seq", "type", "timestamp", "phase", "state", "exitCode"}
        if set(value) - allowed:
            raise ValueError("unknown_event_field")
        required = ("version", "runId", "seq", "type", "timestamp", "phase", "state")
        if (
            any(key not in value for key in required)
            or value["version"] != "fmix-event.v1"
            or value["runId"] != RUN_ID
            or not isinstance(value["seq"], int)
            or isinstance(value["seq"], bool)
            or value["seq"] <= 0
            or not valid_timestamp(value["timestamp"])
            or not isinstance(value["phase"], str)
            or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", value["phase"])
            or value["state"] not in {"starting", "running", "completed", "failed", "cancelled", "abandoned"}
        ):
            raise ValueError("invalid_event_identity")
        event_type = value["type"]
        if event_type not in {"run_started", "phase_changed", "run_finished", "run_abandoned"}:
            raise ValueError("invalid_event_type")
        if "exitCode" in value and value["exitCode"] is not None:
            if (
                not isinstance(value["exitCode"], int)
                or isinstance(value["exitCode"], bool)
                or not 0 <= value["exitCode"] <= 255
            ):
                raise ValueError("invalid_event_exit_code")
        if event_type in {"run_started", "phase_changed"}:
            if value["state"] not in {"starting", "running"} or "exitCode" in value:
                raise ValueError("invalid_event_lifecycle")
        elif event_type == "run_abandoned":
            if value["phase"] != "terminal" or value["state"] != "abandoned":
                raise ValueError("invalid_event_lifecycle")
        elif (
            value["phase"] != "terminal"
            or value["state"] not in {"completed", "failed", "cancelled"}
            or "exitCode" not in value
        ):
            raise ValueError("invalid_event_lifecycle")
        exit_code = value.get("exitCode")
        if value["state"] == "completed" and exit_code != 0:
            raise ValueError("invalid_event_lifecycle")
        if value["state"] == "failed" and (not isinstance(exit_code, int) or exit_code <= 0 or exit_code in {129, 130, 143}):
            raise ValueError("invalid_event_lifecycle")
        if value["state"] == "cancelled" and exit_code not in {129, 130, 143}:
            raise ValueError("invalid_event_lifecycle")
    elif kind == "metrics":
        allowed = {"version", "runId", "seq", "timestamp", "processCpuPercent", "processRssBytes", "hostAvailableMemoryBytes"}
        if (
            set(value) != allowed
            or value["version"] != "fmix-metric.v1"
            or value["runId"] != RUN_ID
            or not isinstance(value["seq"], int)
            or isinstance(value["seq"], bool)
            or value["seq"] <= 0
            or not valid_timestamp(value["timestamp"])
            or any(
                not valid_nonnegative_number(value[field])
                for field in ("processCpuPercent", "processRssBytes")
                if value[field] is not None
            )
            or value["hostAvailableMemoryBytes"] is not None
            and not valid_nonnegative_number(value["hostAvailableMemoryBytes"])
        ):
            raise ValueError("invalid_metric_identity")
    else:
        raise ValueError("invalid_artifact_kind")
    return value


def copy_artifact_file(source_path, destination_path, kind):
    source_info = lstat_safe(source_path, 0o600, "file")
    if source_info.st_size > ARTIFACT_MAX_BYTES:
        raise ValueError("artifact_too_large")
    source_fd = os.open(source_path, os.O_RDONLY | nofollow)
    temporary = destination_path + ".tmp-" + str(os.getpid())
    destination_fd = None
    digest = hashlib.sha256()
    written = 0
    try:
        destination_fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600)
        if kind == "snapshot":
            raw = artifact_read_bounded(source_fd, source_info.st_size)
            projected = artifact_project_snapshot(json.loads(raw))
            payload = json.dumps(projected, separators=(",", ":")).encode() + b"\n"
            write_all(destination_fd, payload)
            digest.update(payload)
            written = len(payload)
        else:
            pending = b""
            while True:
                chunk = os.read(source_fd, 65536)
                if not chunk:
                    break
                pending += chunk
                if len(pending) > ARTIFACT_MAX_JSON_LINE and b"\n" not in pending:
                    raise ValueError("artifact_line_too_large")
                while b"\n" in pending:
                    raw_line, pending = pending.split(b"\n", 1)
                    if len(raw_line) > ARTIFACT_MAX_JSON_LINE:
                        raise ValueError("artifact_line_too_large")
                    if not raw_line:
                        continue
                    projected = artifact_project_jsonl_line(raw_line, kind)
                    payload = json.dumps(projected, separators=(",", ":")).encode() + b"\n"
                    write_all(destination_fd, payload)
                    digest.update(payload)
                    written += len(payload)
                    if written > ARTIFACT_MAX_BYTES:
                        raise ValueError("artifact_too_large")
                if len(pending) > ARTIFACT_MAX_JSON_LINE:
                    raise ValueError("artifact_line_too_large")
            if pending:
                if len(pending) > ARTIFACT_MAX_JSON_LINE:
                    raise ValueError("artifact_line_too_large")
                projected = artifact_project_jsonl_line(pending, kind)
                payload = json.dumps(projected, separators=(",", ":")).encode() + b"\n"
                write_all(destination_fd, payload)
                digest.update(payload)
                written += len(payload)
        os.fsync(destination_fd)
        os.close(destination_fd)
        destination_fd = None
        after_info = os.fstat(source_fd)
        if (after_info.st_dev, after_info.st_ino, after_info.st_size) != (
            source_info.st_dev, source_info.st_ino, source_info.st_size
        ):
            raise ValueError("artifact_changed")
        os.replace(temporary, destination_path)
        os.chmod(destination_path, 0o600)
        return {
            "name": destination_path[len(artifact_run_dir) + 1:],
            "kind": "telemetry",
            "contentType": "application/json" if kind == "snapshot" else "application/x-ndjson",
            "sizeBytes": written,
            "sha256": digest.hexdigest(),
            "storage": "local",
            "redacted": True,
            "truncated": False,
        }
    finally:
        os.close(source_fd)
        if destination_fd is not None:
            os.close(destination_fd)
        try:
            os.unlink(temporary)
        except FileNotFoundError:
            pass


def publish_artifact_manifest(terminal_snapshot, terminal_state, terminal_degraded):
    descriptors = []
    failed = bool(terminal_degraded or terminal_state == "abandoned")
    sources = (
        ("snapshot.json", "snapshot", True),
        ("events.jsonl", "events", True),
        ("metrics.jsonl", "metrics", False),
    )
    for filename, kind, required in sources:
        source_path = os.path.join(run_dir, filename)
        destination_path = os.path.join(artifact_fmix_dir, filename)
        try:
            if not os.path.lexists(source_path):
                if required:
                    failed = True
                continue
            descriptors.append(copy_artifact_file(source_path, destination_path, kind))
        except (OSError, ValueError, TypeError, json.JSONDecodeError):
            failed = True
            try:
                os.unlink(destination_path)
            except FileNotFoundError:
                pass
    if not failed:
        try:
            # All payload renames are committed together before the terminal
            # manifest rename makes them visible to readers.
            artifact_dir_fsync(artifact_fmix_dir)
        except OSError:
            failed = True
    if failed:
        descriptors = []
        for filename, _kind, _required in sources:
            try:
                os.unlink(os.path.join(artifact_fmix_dir, filename))
            except FileNotFoundError:
                pass
        try:
            artifact_dir_fsync(artifact_fmix_dir)
        except OSError:
            pass
    manifest = {
        "version": ARTIFACT_SCHEMA,
        "runId": RUN_ID,
        "createdAt": artifact_created_at,
        "expiresAt": artifact_expires_at,
        "storage": "local",
        "state": "degraded" if failed else "available",
        "artifacts": descriptors,
    }
    if failed:
        manifest["degraded"] = "fmix_artifact_validation"
    try:
        atomic_artifact_json(artifact_manifest_path, manifest)
    except OSError:
        return False
    return not failed


atomic_artifact_json(artifact_manifest_path, {
    "version": ARTIFACT_SCHEMA,
    "runId": RUN_ID,
    "createdAt": artifact_created_at,
    "expiresAt": artifact_expires_at,
    "storage": "local",
    "state": "pending",
    "artifacts": [],
})


def atomic_snapshot(document):
    temporary = os.path.join(run_dir, ".snapshot.tmp-" + str(os.getpid()))
    fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600)
    try:
        try:
            payload = json.dumps(document, separators=(",", ":")).encode() + b"\n"
            write_all(fd, payload)
            timed_fsync(fd, "snapshotFileFsyncNs")
        finally:
            os.close(fd)
        os.replace(temporary, snapshot_path)
        dir_fsync()
    finally:
        try:
            os.unlink(temporary)
        except FileNotFoundError:
            pass


def read_events():
    size = os.fstat(events_fd).st_size
    data = os.pread(events_fd, size, 0) if size else b""
    result = []
    for raw in data.splitlines():
        try:
            result.append(json.loads(raw))
        except (UnicodeDecodeError, json.JSONDecodeError):
            pass
    return result


def append_event(document):
    write_all(events_fd, json.dumps(document, separators=(",", ":")).encode() + b"\n")
    timed_fsync(events_fd, "eventFileFsyncNs")


def next_sequence():
    return max([int(item.get("seq", 0)) for item in read_events()] or [0]) + 1


handoff_read, handoff_write = os.pipe()
updates_read, updates_write = os.pipe()
updates_ack_read, updates_ack_write = os.pipe()
updates_worker_flags = fcntl.fcntl(updates_write, fcntl.F_GETFL)
fcntl.fcntl(updates_write, fcntl.F_SETFL, updates_worker_flags | os.O_NONBLOCK)
updates_worker_info = os.fstat(updates_write)
updates_ack_worker_info = os.fstat(updates_ack_read)
updates_ack_flags = fcntl.fcntl(updates_ack_write, fcntl.F_GETFL)
fcntl.fcntl(updates_ack_write, fcntl.F_SETFL, updates_ack_flags | os.O_NONBLOCK)
gate_read, gate_write = os.pipe()
capability_read, capability_write = os.pipe()
sentinel_read, sentinel_write = os.pipe()
capability_token = os.urandom(32).hex()
worker_pid = os.fork()
if worker_pid == 0:
    try:
        os.close(handoff_read)
        os.close(updates_read)
        os.close(updates_ack_write)
        os.close(gate_write)
        os.close(capability_write)
        os.close(sentinel_read)
        os.close(sentinel_write)
        os.setpgid(0, 0)
        for managed_signal in MANAGED:
            signal.signal(managed_signal, signal.SIG_DFL)
        if os.read(gate_read, 1) != b"G":
            os._exit(125)
        os.close(gate_read)
        capability_source = fcntl.fcntl(capability_read, fcntl.F_DUPFD, 10)
        events_source = fcntl.fcntl(events_fd, fcntl.F_DUPFD, 10)
        handoff_source = fcntl.fcntl(handoff_write, fcntl.F_DUPFD, 10)
        updates_source = fcntl.fcntl(updates_write, fcntl.F_DUPFD, 10)
        updates_ack_source = fcntl.fcntl(updates_ack_read, fcntl.F_DUPFD, 10)
        for source in (capability_source, events_source, handoff_source, updates_source, updates_ack_source):
            os.set_inheritable(source, False)
        os.dup2(capability_source, 7)
        os.dup2(events_source, 8)
        os.dup2(handoff_source, 9)
        os.dup2(updates_source, 10)
        os.dup2(updates_ack_source, 11)
        for source in (capability_source, events_source, handoff_source, updates_source, updates_ack_source, capability_read, events_fd, handoff_write, updates_write, updates_ack_read):
            if source not in (7, 8, 9, 10, 11):
                try:
                    os.close(source)
                except OSError:
                    pass
        for fixed_fd in (7, 8, 9, 10, 11):
            os.set_inheritable(fixed_fd, True)
        worker_env = os.environ.copy()
        worker_env.update({
            "FMIX_OBSERVABILITY_WORKER": "1",
            "FMIX_OBSERVABILITY_SUPERVISOR_PID": str(os.getppid()),
            "FMIX_OBSERVABILITY_CAPABILITY_FD": "7",
            "FMIX_OBSERVABILITY_EVENTS_FD": "8",
            "FMIX_OBSERVABILITY_HANDOFF_FD": "9",
            "FMIX_OBSERVABILITY_UPDATES_FD": "10",
            "FMIX_OBSERVABILITY_UPDATES_ACK_FD": "11",
            "FMIX_OBSERVABILITY_EVENTS_DEV": str(events_info.st_dev),
            "FMIX_OBSERVABILITY_EVENTS_INODE": str(events_info.st_ino),
            "FMIX_OBSERVABILITY_UPDATES_DEV": str(os.fstat(10).st_dev),
            "FMIX_OBSERVABILITY_UPDATES_INODE": str(os.fstat(10).st_ino),
            "FMIX_OBSERVABILITY_UPDATES_ACK_DEV": str(os.fstat(11).st_dev),
            "FMIX_OBSERVABILITY_UPDATES_ACK_INODE": str(os.fstat(11).st_ino),
            "FMIX_OBSERVABILITY_CAPABILITY_TOKEN": capability_token,
            # Valid FMIX_RUN_ID executions get an isolated handoff surface for
            # the test harness. The paths are created and checked below before
            # any workload can inherit them; invalid/source-only invocations
            # never enter this supervisor.
            "FMIX_RUN_ARTIFACT_DIR": artifact_run_dir,
            "CT_TEST_RUN_ID": RUN_ID,
            "CT_TEST_LOGS_DIR": artifact_logs_dir,
            "CT_TEST_JUNIT_DIR": artifact_junit_dir,
            "CT_TEST_JUNIT_FILE": os.path.join(artifact_junit_dir, "results.xml"),
            "CT_TEST_RUN_LIVE_DIR": artifact_live_run_dir,
            "CT_TEST_STATS_DIR": artifact_stats_dir,
            "CT_TEST_STATS_FILE": os.path.join(artifact_stats_dir, "stats.json"),
            "CT_TEST_STATS_PATH": os.path.join(artifact_stats_dir, "stats.json"),
            "CT_TEST_CURRENT_PATH": os.path.join(artifact_live_dir, "current.json"),
            "CT_TEST_EVENTS_PATH": os.path.join(artifact_live_dir, "events.ndjson"),
            "CT_TEST_VM_EVENTS_PATH": os.path.join(artifact_live_dir, "vm_events.ndjson"),
            "CT_TEST_VM_STATS_PATH": os.path.join(artifact_stats_dir, "vm_stats.json"),
        })
        signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
        os.execve("/bin/bash", ["/bin/bash", RUNNER, "--fmix-observability-worker"] + ARGS, worker_env)
    except BaseException:
        os._exit(125)

os.close(handoff_write)
os.close(updates_write)
os.close(updates_ack_read)
os.close(gate_read)
os.close(capability_read)
try:
    os.setpgid(worker_pid, worker_pid)
except OSError as exc:
    if exc.errno not in (errno.EACCES, errno.EPERM):
        fail("could not create worker process group")
worker_pgid = os.getpgid(worker_pid)
supervisor_pgid = os.getpgrp()
if worker_pgid != worker_pid or worker_pgid == supervisor_pgid or worker_pgid <= 1:
    try:
        os.kill(worker_pid, signal.SIGKILL)
    except ProcessLookupError:
        pass
    fail("unsafe worker process group")

sentinel_pid = os.fork()
if sentinel_pid == 0:
    try:
        os.close(sentinel_write)
        os.close(handoff_read)
        os.close(updates_read)
        os.close(updates_ack_write)
        os.close(capability_write)
        os.close(gate_write)
        os.close(events_fd)
        os.setpgid(0, worker_pgid)
        for managed_signal in MANAGED:
            signal.signal(managed_signal, signal.SIG_IGN)
        signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
        while os.read(sentinel_read, 1):
            pass
    except BaseException:
        pass
    os._exit(0)
os.close(sentinel_read)
try:
    os.setpgid(sentinel_pid, worker_pgid)
except OSError as exc:
    if exc.errno not in (errno.EACCES, errno.EPERM):
        fail("could not join group sentinel")
if os.getpgid(sentinel_pid) != worker_pgid or sentinel_pid <= 1:
    fail("unsafe worker group sentinel")

capability = (
    "fmix-worker-capability.v3", RUN_ID, str(os.getpid()), str(worker_pid),
    str(worker_pgid), str(events_info.st_dev), str(events_info.st_ino),
    str(updates_worker_info.st_dev), str(updates_worker_info.st_ino),
    str(updates_ack_worker_info.st_dev), str(updates_ack_worker_info.st_ino),
    capability_token,
)
try:
    write_all(capability_write, ("\n".join(capability) + "\n").encode("ascii"))
except (BrokenPipeError, OSError):
    degraded = True
finally:
    os.close(capability_write)

first_pre_signal = None
first_post_signal = None
emergency_signal = None
reaped = False
worker_reaped_at = None
sentinel_reaped = False
cancellation_started = None
group_cleanup_attempted = False
group_kill_succeeded = False
group_access_closed = False
group_permission_denied = False
group_unverified = False
cleanup_verified = False


def emergency_native_delivery(_signum, _frame):
    if emergency_signal is None:
        os._exit(125)
    signal.signal(emergency_signal, signal.SIG_DFL)
    signal.pthread_sigmask(signal.SIG_UNBLOCK, {emergency_signal})
    os.kill(os.getpid(), emergency_signal)


def sentinel_valid():
    if (
        group_access_closed
        or sentinel_reaped
        or sentinel_pid <= 1
        or worker_pgid <= 1
        or worker_pgid == os.getpgrp()
    ):
        return False
    try:
        return os.getpgid(sentinel_pid) == worker_pgid
    except OSError:
        return False


def kill_pinned_worker_group(deadline):
    global degraded, group_access_closed, group_cleanup_attempted
    global group_kill_succeeded, group_permission_denied, group_unverified
    if group_cleanup_attempted or group_access_closed:
        return False
    group_cleanup_attempted = True
    if time.monotonic() >= deadline:
        group_unverified = True
        group_access_closed = True
        return False
    if not sentinel_valid():
        group_unverified = True
        group_access_closed = True
        return False
    try:
        os.killpg(worker_pgid, signal.SIGKILL)
    except OSError as exc:
        if exc.errno == errno.EPERM:
            group_permission_denied = True
            degraded = True
            group_access_closed = True
            try:
                os.kill(sentinel_pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
            except PermissionError:
                degraded = True
            return False
        if exc.errno == errno.ESRCH:
            group_unverified = True
            degraded = True
            group_access_closed = True
            return False
        raise
    group_kill_succeeded = True
    group_access_closed = True
    return True


def verify_group_absent(deadline):
    global degraded, group_permission_denied
    if not group_kill_succeeded or worker_pgid <= 1 or worker_pgid == os.getpgrp():
        return False
    permission_denied = False
    while time.monotonic() < deadline:
        try:
            os.killpg(worker_pgid, 0)
        except OSError as exc:
            if exc.errno == errno.ESRCH:
                return True
            if exc.errno == errno.EPERM:
                permission_denied = True
            else:
                raise
        time.sleep(min(0.02, max(0.0, deadline - time.monotonic())))
    if permission_denied:
        group_permission_denied = True
        degraded = True
    return False


def signal_worker_group(signum, deadline=None):
    global degraded
    if group_access_closed:
        return False
    if deadline is not None and time.monotonic() >= deadline:
        return False
    if not sentinel_valid():
        return False
    try:
        os.killpg(worker_pgid, signum)
    except OSError as exc:
        if exc.errno in (errno.EPERM, errno.ESRCH):
            degraded = True
            return False
        raise
    return True


def kill_sentinel_fallback():
    """Reap the trusted group sentinel even when group signaling is denied."""
    global degraded
    if sentinel_reaped or sentinel_pid <= 1:
        return
    try:
        os.kill(sentinel_pid, signal.SIGKILL)
    except ProcessLookupError:
        pass
    except PermissionError:
        degraded = True


def managed_signal(signum, _frame):
    global first_pre_signal, first_post_signal, cancellation_started, emergency_signal
    if not reaped:
        if first_pre_signal is None:
            first_pre_signal = signum
            cancellation_started = time.monotonic()
            emergency_signal = signum
            signal.signal(signal.SIGALRM, emergency_native_delivery)
            signal.setitimer(
                signal.ITIMER_REAL,
                max(
                    0.001,
                    cancellation_started + 5.0 - 0.25 - time.monotonic(),
                ),
            )
            signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGALRM})
        try:
            signal_worker_group(signum)
        except ProcessLookupError:
            pass
    elif first_post_signal is None:
        first_post_signal = signum


for managed in MANAGED:
    signal.signal(managed, managed_signal)

started_at = utc_now()
command = ARGS[0] if ARGS else "unknown"
snapshot = {
    "version": "fmix-session.v1",
    "runId": RUN_ID,
    "fmixVersion": FMIX_VERSION,
    "launcherPid": os.getpid(),
    "pid": worker_pid,
    "state": "running",
    "phase": "session",
    "command": command,
    "exitCode": None,
    "startedAt": started_at,
    "updatedAt": started_at,
}
atomic_snapshot(snapshot)
if not read_events():
    append_event({
        "version": "fmix-event.v1", "runId": RUN_ID, "seq": 1,
        "type": "run_started", "timestamp": started_at,
        "phase": "session", "state": "running",
    })

os.set_blocking(updates_read, False)
update_bytes = bytearray()
update_fields = []
update_expected = None
updates_invalid = False
updates_eof = False


def acknowledge_update(succeeded):
    global degraded
    try:
        os.write(updates_ack_write, b"A" if succeeded else b"D")
        return True
    except (BrokenPipeError, OSError):
        degraded = True
        return False


def publish_worker_update(fields):
    global degraded, snapshot, active_update_timing
    now = utc_now()
    try:
        kind = fields[0].decode("ascii")
        if kind == "P":
            phase = fields[1].decode("ascii")
            if not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", phase):
                raise ValueError
            if active_update_timing is not None:
                active_update_timing["kind"] = "phase"
                active_update_timing["phase"] = phase
            snapshot["phase"] = phase
            snapshot["updatedAt"] = now
            atomic_snapshot(snapshot)
            append_event({
                "version": "fmix-event.v1", "runId": RUN_ID,
                "seq": next_sequence(), "type": "phase_changed",
                "timestamp": now, "phase": phase, "state": "running",
            })
        elif kind == "M":
            raw_values = fields[1:]
            if len(raw_values) != 6 or any(len(value) > MAX_UPDATE_FIELD for value in raw_values):
                raise ValueError
            if active_update_timing is not None:
                active_update_timing["kind"] = "meta"
            values = [os.fsdecode(value) for value in raw_values]
            worktree, template_key, database, session_hash, session_source, session_root = values
            snapshot.update({
                "worktree": worktree or None,
                "templateKey": template_key or None,
                "database": database or None,
                "session": {
                    "hash": session_hash or None,
                    "source": session_source or None,
                    "root": session_root or None,
                },
                "updatedAt": now,
            })
            atomic_snapshot(snapshot)
        else:
            raise ValueError
    except (OSError, UnicodeError, ValueError):
        degraded = True
        return False
    return True


def consume_worker_updates():
    global degraded, update_bytes, update_fields, update_expected
    global updates_eof, updates_invalid, active_update_timing
    if updates_eof:
        return
    drained = 0
    processed_frames = 0
    while drained < MAX_UPDATE_DRAIN_BYTES:
        try:
            chunk = os.read(
                updates_read,
                min(8192, MAX_UPDATE_DRAIN_BYTES - drained),
            )
        except BlockingIOError:
            break
        except OSError:
            degraded = True
            updates_invalid = True
            updates_eof = True
            break
        if not chunk:
            updates_eof = True
            if update_bytes or update_fields:
                degraded = True
                updates_invalid = True
            break
        drained += len(chunk)
        if updates_invalid:
            continue
        update_bytes.extend(chunk)
        if len(update_bytes) > MAX_UPDATE_BUFFER:
            degraded = True
            updates_invalid = True
            update_bytes.clear()
            update_fields.clear()
            continue
        while not updates_invalid and b"\0" in update_bytes:
            raw, remainder = update_bytes.split(b"\0", 1)
            update_bytes = bytearray(remainder)
            if len(raw) > MAX_UPDATE_FIELD:
                degraded = True
                updates_invalid = True
                update_fields.clear()
                break
            update_fields.append(bytes(raw))
            if len(update_fields) == 1:
                update_expected = {b"P": 2, b"M": 7}.get(update_fields[0])
                if update_expected is None:
                    degraded = True
                    updates_invalid = True
                    update_fields.clear()
                    break
            if update_expected is not None and len(update_fields) == update_expected:
                update_received_ns = time.monotonic_ns()
                if diagnostics_enabled and len(update_timings) < 64:
                    active_update_timing = {
                        "version": "fmix-update-timing.v1",
                        "runId": RUN_ID,
                        "seq": len(update_timings) + 1,
                        "kind": "unknown",
                        "phase": None,
                        "receiveToAckNs": 0,
                        "snapshotFileFsyncNs": 0,
                        "snapshotDirectoryFsyncNs": 0,
                        "eventFileFsyncNs": 0,
                        "succeeded": False,
                    }
                succeeded = publish_worker_update(update_fields)
                acknowledged = acknowledge_update(succeeded)
                if active_update_timing is not None:
                    active_update_timing["receiveToAckNs"] = max(
                        0, time.monotonic_ns() - update_received_ns
                    )
                    active_update_timing["succeeded"] = bool(
                        succeeded and acknowledged
                    )
                    update_timings.append(active_update_timing)
                    active_update_timing = None
                update_fields = []
                update_expected = None
                processed_frames += 1
                if not succeeded or not acknowledged:
                    degraded = True
                    updates_invalid = True
                    update_bytes.clear()
                    break
                if processed_frames >= MAX_UPDATE_FRAMES_PER_TURN:
                    if update_bytes:
                        degraded = True
                        updates_invalid = True
                        update_bytes.clear()
                    return
        if not updates_invalid and len(update_bytes) > MAX_UPDATE_FIELD:
            degraded = True
            updates_invalid = True
            update_bytes.clear()
            update_fields.clear()

tty_fd = None
prior_foreground_pgid = None
for candidate_fd in (0, 1, 2):
    try:
        if os.isatty(candidate_fd) and os.tcgetpgrp(candidate_fd) == supervisor_pgid:
            tty_fd = candidate_fd
            prior_foreground_pgid = supervisor_pgid
            break
    except OSError:
        pass
if tty_fd is not None:
    previous_mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTTOU})
    try:
        os.tcsetpgrp(tty_fd, worker_pgid)
        if os.tcgetpgrp(tty_fd) != worker_pgid:
            fail("worker foreground transfer failed")
    finally:
        signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask)
try:
    os.write(gate_write, b"G")
except (BrokenPipeError, OSError):
    degraded = True
finally:
    os.close(gate_write)
signal.pthread_sigmask(signal.SIG_SETMASK, supervisor_signal_mask)


def parse_positive_int(name, default, maximum):
    try:
        value = int(os.environ.get(name, str(default)))
        if value < 1 or value > maximum:
            raise ValueError
        return value
    except ValueError:
        return default


sampler_pid = None
try:
    sample_interval = float(os.environ.get("FMIX_RESOURCE_SAMPLE_INTERVAL", "1"))
    if not math.isfinite(sample_interval) or sample_interval <= 0:
        raise ValueError
except ValueError:
    sample_interval = 1.0
    degraded = True
try:
    sampler_stop_timeout = float(
        os.environ.get("FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S", "2")
    )
    if not math.isfinite(sampler_stop_timeout) or sampler_stop_timeout < 0:
        raise ValueError
    sampler_stop_timeout = min(sampler_stop_timeout, 10.0)
except ValueError:
    sampler_stop_timeout = 2.0
    degraded = True
sample_limit = parse_positive_int("FMIX_RESOURCE_SAMPLE_MAX_SAMPLES", 14400, 86400)


def parse_sampler_process_rows(output, scoped_pgid=None, required_pids=()):
    rows = []
    seen = set()
    malformed = False
    for line in output.splitlines():
        fields = line.split()
        if len(fields) != 5:
            malformed = True
            continue
        try:
            row = (
                int(fields[0]),
                int(fields[1]),
                int(fields[2]),
                float(fields[3]),
                int(fields[4]),
            )
        except ValueError:
            malformed = True
            continue
        pid, ppid, pgid, cpu, rss = row
        if scoped_pgid is not None and (
            pid <= 0
            or ppid < 0
            or pgid != scoped_pgid
            or not math.isfinite(cpu)
            or rss < 0
            or pid in seen
        ):
            malformed = True
            continue
        rows.append(row)
        seen.add(pid)
    if scoped_pgid is not None and (
        malformed
        or not rows
        or not any(pid in required_pids for pid, _ppid, _pgid, _cpu, _rss in rows)
    ):
        raise ValueError("invalid scoped ps output")
    return rows


def sampler_process_rows():
    process_columns = "pid=,ppid=,pgid=,%cpu=,rss="
    process_env = dict(os.environ, LC_ALL="C")
    if sys.platform == "darwin":
        try:
            scoped_output = subprocess.run(
                ["ps", "-g", str(worker_pgid), "-o", process_columns],
                capture_output=True,
                text=True,
                timeout=2,
                check=True,
                env=process_env,
            ).stdout
            return parse_sampler_process_rows(
                scoped_output,
                worker_pgid,
                required_pids=(worker_pid,),
            )
        except (OSError, subprocess.SubprocessError, ValueError):
            pass
    output = subprocess.run(
        ["ps", "-axo", process_columns],
        capture_output=True,
        text=True,
        timeout=2,
        check=True,
        env=process_env,
    ).stdout
    return parse_sampler_process_rows(output)


def sampler_main():
    try:
        os.setpgid(0, 0)
        for managed_signal in MANAGED:
            signal.signal(managed_signal, signal.SIG_DFL)
        signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
        cadence_monotonic = time.monotonic
        cadence_sleep = time.sleep
        sequence = 0
        next_sample_at = cadence_monotonic()
        while not os.path.exists(stop_path) and sequence < sample_limit:
            rows = sampler_process_rows()
            excluded = {os.getpid()}
            changed = True
            while changed:
                changed = False
                for pid, ppid, _pgid, _cpu, _rss in rows:
                    if ppid in excluded and pid not in excluded:
                        excluded.add(pid)
                        changed = True
            selected = [row for row in rows if row[2] == worker_pgid and row[0] not in excluded]
            sequence += 1
            host_available = None
            if sys.platform.startswith("linux"):
                try:
                    for line in open("/proc/meminfo", encoding="utf-8"):
                        if line.startswith("MemAvailable:"):
                            host_available = int(line.split()[1]) * 1024
                            break
                except (OSError, ValueError):
                    pass
            elif sys.platform == "darwin":
                try:
                    memory_output = subprocess.run(
                        ["/usr/bin/memory_pressure", "-Q"],
                        capture_output=True, text=True, timeout=2, check=True,
                        env=dict(os.environ, LC_ALL="C"),
                    ).stdout
                    total_match = re.search(r"system has\s+([0-9]+)", memory_output, re.IGNORECASE)
                    free_match = re.search(r"memory free percentage:\s*([0-9]+)%", memory_output, re.IGNORECASE)
                    if total_match and free_match:
                        host_available = int(total_match.group(1)) * int(free_match.group(1)) // 100
                except (OSError, subprocess.SubprocessError, ValueError):
                    pass
            metric = {
                "version": "fmix-metric.v1", "runId": RUN_ID, "seq": sequence,
                "timestamp": utc_now(),
                "processCpuPercent": round(sum(max(0.0, row[3]) for row in selected), 3),
                "processRssBytes": sum(max(0, row[4]) for row in selected) * 1024,
                "hostAvailableMemoryBytes": host_available,
            }
            fd = os.open(metrics_path, os.O_WRONLY | os.O_CREAT | os.O_APPEND | nofollow, 0o600)
            try:
                os.write(fd, json.dumps(metric, separators=(",", ":")).encode() + b"\n")
            finally:
                os.close(fd)
            next_sample_at += sample_interval
            now = cadence_monotonic()
            if next_sample_at <= now:
                missed_ticks = math.floor(
                    (now - next_sample_at) / sample_interval
                ) + 1
                next_sample_at += missed_ticks * sample_interval
            while not os.path.exists(stop_path) and cadence_monotonic() < next_sample_at:
                cadence_sleep(
                    min(0.05, max(0.0, next_sample_at - cadence_monotonic()))
                )
        if sequence >= sample_limit:
            fd = os.open(os.path.join(run_dir, ".sampler-limit-reached"), os.O_WRONLY | os.O_CREAT, 0o600)
            os.close(fd)
    except BaseException:
        try:
            fd = os.open(os.path.join(run_dir, ".sampler-error"), os.O_WRONLY | os.O_CREAT, 0o600)
            os.close(fd)
        except OSError:
            pass
    os._exit(0)


sampler_fork_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set(MANAGED))
sampler_pid = os.fork()
if sampler_pid == 0:
    os.close(events_fd)
    os.close(handoff_read)
    os.close(updates_read)
    os.close(updates_ack_write)
    sampler_main()
signal.pthread_sigmask(signal.SIG_SETMASK, sampler_fork_mask)

os.set_blocking(handoff_read, False)
handoff_bytes = bytearray()
handoff_oversize = False
wait_status = None
cutoff_mask = None
sampler_stop_requested = False
sampler_forced = False
sampler_reaped = False


def reap_with_deadline(pid, deadline):
    if pid is None:
        return False
    while True:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            return False
        try:
            waited, _status = os.waitpid(pid, os.WNOHANG)
        except ChildProcessError:
            return False
        if waited == pid:
            return True
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            return False
        time.sleep(min(0.02, remaining))


def reap_worker_with_deadline(deadline):
    while True:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            return None
        try:
            waited, status = os.waitpid(worker_pid, os.WNOHANG)
        except ChildProcessError:
            return None
        if waited == worker_pid:
            return status
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            return None
        time.sleep(min(0.02, remaining))


def cleanup_sampler(deadline, immediate=False):
    global degraded, sampler_forced, sampler_reaped
    if sampler_reaped:
        return
    grace_deadline = time.monotonic() if immediate else min(
        deadline, time.monotonic() + sampler_stop_timeout
    )
    if time.monotonic() < grace_deadline:
        sampler_reaped = reap_with_deadline(sampler_pid, grace_deadline)
    if not sampler_reaped and time.monotonic() < deadline:
        sampler_forced = True
        degraded = True
        try:
            os.kill(sampler_pid, signal.SIGTERM)
        except ProcessLookupError:
            degraded = True
        except PermissionError:
            degraded = True
    if not sampler_reaped and time.monotonic() < deadline:
        term_deadline = min(deadline, time.monotonic() + (0.05 if immediate else 0.25))
        sampler_reaped = reap_with_deadline(sampler_pid, term_deadline)
    if not sampler_reaped and time.monotonic() < deadline:
        sampler_forced = True
        degraded = True
        try:
            os.kill(sampler_pid, signal.SIGKILL)
        except ProcessLookupError:
            degraded = True
        except PermissionError:
            degraded = True
    if not sampler_reaped and time.monotonic() < deadline:
        sampler_reaped = reap_with_deadline(sampler_pid, deadline)


while wait_status is None:
    consume_worker_updates()
    try:
        while True:
            chunk = os.read(handoff_read, 8192)
            if not chunk:
                break
            if len(handoff_bytes) + len(chunk) <= MAX_HANDOFF:
                handoff_bytes.extend(chunk)
            else:
                handoff_oversize = True
    except BlockingIOError:
        pass
    transition_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set(MANAGED))
    waited_pid, candidate_status = os.waitpid(worker_pid, os.WNOHANG)
    if waited_pid == worker_pid:
        wait_status = candidate_status
        reaped = True
        worker_reaped_at = time.monotonic()
        cutoff_mask = transition_mask
        break
    signal.pthread_sigmask(signal.SIG_SETMASK, transition_mask)
    if first_pre_signal is not None:
        if not sampler_stop_requested:
            try:
                stop_fd = os.open(stop_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | nofollow, 0o600)
                os.close(stop_fd)
                sampler_stop_requested = True
            except OSError:
                degraded = True
        if cancellation_started is None:
            cancellation_started = time.monotonic()
        cancellation_deadline = cancellation_started + 5.0
        # Finish cleanup 350ms before the unchanged deadline-250ms alarm.
        # Cleanup must not consume the terminal publication reserve.
        publication_cutoff = cancellation_deadline - 0.60
        now = time.monotonic()
        escalation_at = min(cancellation_started + 4.0, publication_cutoff)
        if now >= escalation_at:
            cutoff_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set(MANAGED))
            # Begin verified group termination before waiting on the sampler:
            # a slow sampler must not consume the worker/sentinel reap window.
            # Pinned-group proof, deadlines and abandonment criteria stay strict.
            kill_pinned_worker_group(publication_cutoff)
            sampler_deadline = min(publication_cutoff, time.monotonic() + 0.25)
            cleanup_sampler(sampler_deadline, immediate=True)
            worker_wait_deadline = min(
                publication_cutoff, time.monotonic() + 0.25
            )
            observed_status = reap_worker_with_deadline(worker_wait_deadline)
            if observed_status is not None:
                wait_status = observed_status
                reaped = True
                worker_reaped_at = time.monotonic()
            break
    poll_timeout = 0.02
    if cancellation_started is not None:
        poll_timeout = min(
            poll_timeout,
            max(0.0, cancellation_started + 5.0 - 0.20 - time.monotonic()),
        )
    readable = [handoff_read]
    if not updates_eof:
        readable.append(updates_read)
    select.select(readable, [], [], poll_timeout)

if (
    reaped
    and os.WIFSIGNALED(wait_status)
    and os.WTERMSIG(wait_status) in MANAGED
    and cancellation_started is None
):
    cancellation_started = worker_reaped_at

try:
    while True:
        chunk = os.read(handoff_read, 8192)
        if not chunk:
            break
        if len(handoff_bytes) + len(chunk) <= MAX_HANDOFF:
            handoff_bytes.extend(chunk)
        else:
            handoff_oversize = True
except BlockingIOError:
    pass
os.close(handoff_read)
consume_worker_updates()

blocked_previous = cutoff_mask
fd = os.open(stop_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | nofollow, 0o600)
os.close(fd)


cleanup_deadline = (
    cancellation_started + 5.0
    if cancellation_started is not None
    else worker_reaped_at + 5.0
)
# Reserve 350ms for terminal publication before emergency native delivery.
publication_cutoff = cleanup_deadline - 0.60

emergency_signal = first_pre_signal
if (
    emergency_signal is None
    and reaped
    and os.WIFSIGNALED(wait_status)
    and os.WTERMSIG(wait_status) in MANAGED
):
    emergency_signal = os.WTERMSIG(wait_status)


if emergency_signal is not None:
    signal.signal(signal.SIGALRM, emergency_native_delivery)
    signal.setitimer(
        signal.ITIMER_REAL,
        max(0.001, cleanup_deadline - 0.25 - time.monotonic()),
    )
    signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGALRM})

kill_pinned_worker_group(publication_cutoff)
kill_sentinel_fallback()
cleanup_sampler(publication_cutoff, immediate=cancellation_started is not None)
if not reaped and group_kill_succeeded:
    worker_wait_deadline = min(publication_cutoff, time.monotonic() + 0.25)
    observed_status = reap_worker_with_deadline(worker_wait_deadline)
    if observed_status is not None:
        wait_status = observed_status
        reaped = True
        worker_reaped_at = time.monotonic()

try:
    os.close(sentinel_write)
except OSError:
    pass
sentinel_waited = False
sentinel_reap_deadline = min(publication_cutoff, time.monotonic() + 0.25)
if time.monotonic() < sentinel_reap_deadline:
    sentinel_waited = reap_with_deadline(sentinel_pid, sentinel_reap_deadline)
if not sentinel_waited:
    degraded = True
sentinel_reaped = sentinel_waited

if not sampler_reaped and time.monotonic() < publication_cutoff:
    cleanup_sampler(publication_cutoff, immediate=True)

if reaped and sampler_reaped and sentinel_reaped and time.monotonic() < publication_cutoff:
    cleanup_verified = verify_group_absent(publication_cutoff)

if not reaped or not sampler_reaped or not sentinel_reaped or not cleanup_verified:
    degraded = True
if sampler_forced or os.path.exists(os.path.join(run_dir, ".sampler-error")):
    degraded = True

consume_worker_updates()
if not updates_eof or update_bytes or update_fields:
    degraded = True
for update_fd in (updates_read, updates_ack_write):
    try:
        os.close(update_fd)
    except OSError:
        degraded = True

if tty_fd is not None and prior_foreground_pgid is not None:
    tty_mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTTOU})
    try:
        os.tcsetpgrp(tty_fd, prior_foreground_pgid)
        if os.tcgetpgrp(tty_fd) != prior_foreground_pgid:
            degraded = True
    except OSError:
        degraded = True
    finally:
        signal.pthread_sigmask(signal.SIG_SETMASK, tty_mask)

worker_exit = None
native_signal = first_pre_signal
wait_exit_code = None
exact_exit_code = None
candidate_state = None
if reaped and os.WIFEXITED(wait_status):
    worker_exit = os.WEXITSTATUS(wait_status)
    wait_exit_code = worker_exit
    if first_pre_signal is not None:
        exact_exit_code = SIGNAL_CODES[first_pre_signal]
        candidate_state = "cancelled"
    else:
        exact_exit_code = wait_exit_code
        candidate_state = (
            "completed"
            if exact_exit_code == 0
            else (
                "cancelled"
                if exact_exit_code in (129, 130, 143)
                else "failed"
            )
        )
elif reaped:
    worker_signal = os.WTERMSIG(wait_status)
    wait_exit_code = 128 + worker_signal
    native_signal = first_pre_signal or worker_signal
    exact_exit_code = SIGNAL_CODES.get(native_signal, wait_exit_code)
    candidate_state = "cancelled" if native_signal in SIGNAL_CODES else "failed"

result_exact = reaped and sampler_reaped and sentinel_reaped and cleanup_verified
state = candidate_state if result_exact else "abandoned"
exit_code = exact_exit_code if result_exact else wait_exit_code

def parse_terminal_handoff(payload):
    fields = payload.split(b"\0")
    if not fields or fields[-1] != b"" or len(fields) != 21:
        raise ValueError
    fields.pop()
    if any(
        len(field) > (8192 if index == 4 else MAX_UPDATE_FIELD)
        for index, field in enumerate(fields)
    ):
        raise ValueError

    def ascii_field(index):
        return fields[index].decode("ascii")

    def integer_field(index):
        value = ascii_field(index)
        if not re.fullmatch(r"[0-9]+", value):
            raise ValueError
        return int(value)

    def optional_path(index):
        value = os.fsdecode(fields[index])
        return value or None

    if ascii_field(0) != "fmix-terminal-handoff.v2":
        raise ValueError
    run_id = ascii_field(1)
    worker = integer_field(2)
    exit_value = integer_field(3)
    phases = {}
    phase_payload = ascii_field(4)
    for item in phase_payload.split():
        if "=" not in item:
            raise ValueError
        name, raw_seconds = item.split("=", 1)
        if (
            name in phases
            or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", name)
            or not re.fullmatch(r"[0-9]+", raw_seconds)
        ):
            raise ValueError
        phases[name] = int(raw_seconds)
    cache_hot = ascii_field(6)
    hot_path = ascii_field(7)
    telemetry_degraded = ascii_field(19)
    if cache_hot not in ("yes", "no") or hot_path not in ("yes", "no"):
        raise ValueError
    if telemetry_degraded not in ("0", "1"):
        raise ValueError
    return {
        "version": "fmix-terminal-handoff.v2",
        "runId": run_id,
        "workerPid": worker,
        "workerPgid": worker_pgid,
        "exitCode": exit_value,
        "phaseSeconds": phases,
        "timing": {"durationSeconds": integer_field(5)},
        "cache": {
            "hot": cache_hot == "yes",
            "hotPath": hot_path == "yes",
            "overheadSeconds": integer_field(8),
        },
        "compile": {
            "outcome": optional_path(9),
            "fileCount": integer_field(10),
            "seconds": integer_field(11),
        },
        "session": {
            "hash": optional_path(12),
            "source": optional_path(13),
            "root": optional_path(14),
        },
        "worktree": optional_path(15),
        "templateKey": optional_path(16),
        "database": optional_path(17),
        "artifacts": {"outcome": optional_path(18)},
        "telemetryDegraded": telemetry_degraded == "1",
    }


handoff = None
allowed_keys = {"version", "runId", "workerPid", "workerPgid", "exitCode", "phaseSeconds", "cache", "compile", "session", "timing", "worktree", "templateKey", "database", "artifacts", "telemetryDegraded"}
required_keys = {"version", "runId", "workerPid", "workerPgid", "exitCode"}
if reaped and handoff_bytes and not handoff_oversize:
    try:
        candidate = parse_terminal_handoff(bytes(handoff_bytes))
        if set(candidate) - allowed_keys or not required_keys.issubset(candidate):
            raise ValueError
        if candidate["version"] != "fmix-terminal-handoff.v2" or candidate["runId"] != RUN_ID:
            raise ValueError
        if candidate["workerPid"] != worker_pid or candidate["workerPgid"] != worker_pgid:
            raise ValueError
        if (
            not isinstance(candidate["exitCode"], int)
            or isinstance(candidate["exitCode"], bool)
            or not 0 <= candidate["exitCode"] <= 255
        ):
            raise ValueError
        if os.WIFEXITED(wait_status) and first_pre_signal is None and candidate["exitCode"] != worker_exit:
            raise ValueError
        if not isinstance(candidate.get("telemetryDegraded", False), bool):
            raise ValueError
        phase_seconds = candidate.get("phaseSeconds", {})
        if not isinstance(phase_seconds, dict) or len(phase_seconds) > 64:
            raise ValueError
        for name, seconds in phase_seconds.items():
            if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", name):
                raise ValueError
            if not isinstance(seconds, int) or isinstance(seconds, bool) or not 0 <= seconds <= 31536000:
                raise ValueError
        object_contracts = {
            "cache": {"hot", "hotPath", "overheadSeconds"},
            "compile": {"outcome", "fileCount", "seconds"},
            "session": {"hash", "source", "root"},
            "timing": {"durationSeconds"},
            "artifacts": {"outcome"},
        }
        for key, object_keys in object_contracts.items():
            value = candidate.get(key, {})
            if not isinstance(value, dict) or set(value) - object_keys:
                raise ValueError
        for key in ("worktree", "templateKey", "database"):
            value = candidate.get(key)
            if value is not None and (not isinstance(value, str) or len(value) > 4096):
                raise ValueError
        cache = candidate.get("cache", {})
        if any(key in cache and not isinstance(cache[key], bool) for key in ("hot", "hotPath")):
            raise ValueError
        for container, integer_keys in (
            (cache, ("overheadSeconds",)),
            (candidate.get("compile", {}), ("fileCount", "seconds")),
            (candidate.get("timing", {}), ("durationSeconds",)),
        ):
            for key in integer_keys:
                if key in container and (
                    not isinstance(container[key], int)
                    or isinstance(container[key], bool)
                    or not 0 <= container[key] <= 31536000
                ):
                    raise ValueError
        for container, string_keys in (
            (candidate.get("compile", {}), ("outcome",)),
            (candidate.get("session", {}), ("hash", "source", "root")),
            (candidate.get("artifacts", {}), ("outcome",)),
        ):
            for key in string_keys:
                if key in container and container[key] is not None and (
                    not isinstance(container[key], str) or len(container[key]) > 4096
                ):
                    raise ValueError
        handoff = candidate
        if candidate.get("telemetryDegraded", False):
            degraded = True
    except (UnicodeError, TypeError, ValueError):
        degraded = True
else:
    degraded = True

try:
    lstat_safe(snapshot_path, 0o600, "file")
    fd = os.open(snapshot_path, os.O_RDONLY | nofollow)
    try:
        snapshot = json.loads(os.read(fd, os.fstat(fd).st_size))
    finally:
        os.close(fd)
except (OSError, ValueError, json.JSONDecodeError):
    snapshot = {
        "version": "fmix-session.v1", "runId": RUN_ID,
        "fmixVersion": FMIX_VERSION, "launcherPid": os.getpid(),
        "pid": worker_pid, "command": command, "startedAt": started_at,
    }
    degraded = True


def read_metrics():
    result = []
    if not os.path.exists(metrics_path):
        return result
    try:
        lstat_safe(metrics_path, 0o600, "file")
        data = open(metrics_path, encoding="utf-8").readlines()
        for index, line in enumerate(data):
            try:
                item = json.loads(line)
                expected_keys = {
                    "version", "runId", "seq", "timestamp",
                    "processCpuPercent", "processRssBytes", "hostAvailableMemoryBytes",
                }
                if set(item) != expected_keys:
                    raise ValueError
                if item["version"] != "fmix-metric.v1" or item["runId"] != RUN_ID:
                    raise ValueError
                sequence = item["seq"]
                timestamp = item["timestamp"]
                if not isinstance(sequence, int) or isinstance(sequence, bool) or not 1 <= sequence <= 86400:
                    raise ValueError
                if not isinstance(timestamp, str) or not 1 <= len(timestamp) <= 64:
                    raise ValueError
                normalized_timestamp = timestamp[:-1] + "+00:00" if timestamp.endswith("Z") else timestamp
                datetime.datetime.fromisoformat(normalized_timestamp)
                for metric_name in ("processCpuPercent", "processRssBytes"):
                    value = item[metric_name]
                    maximum = 1000000000 if metric_name == "processCpuPercent" else 9223372036854775807
                    if (
                        not isinstance(value, (int, float))
                        or isinstance(value, bool)
                        or (isinstance(value, float) and not math.isfinite(value))
                        or value < 0
                        or value > maximum
                    ):
                        raise ValueError
                host_value = item["hostAvailableMemoryBytes"]
                if host_value is not None and (
                    not isinstance(host_value, (int, float))
                    or isinstance(host_value, bool)
                    or (isinstance(host_value, float) and not math.isfinite(host_value))
                    or host_value < 0
                    or host_value > 9223372036854775807
                ):
                    raise ValueError
                result.append(item)
            except (json.JSONDecodeError, TypeError, ValueError):
                if index != len(data) - 1 or line.endswith("\n"):
                    global_degraded[0] = True
    except OSError:
        global_degraded[0] = True
    return result


global_degraded = [degraded]
metrics = read_metrics()
degraded = global_degraded[0]


def nearest(values, percentile):
    if not values:
        return None
    ordered = sorted(values)
    return ordered[max(0, math.ceil(percentile * len(ordered)) - 1)]


cpu = [item["processCpuPercent"] for item in metrics]
rss = [item["processRssBytes"] for item in metrics]
host_values = [item["hostAvailableMemoryBytes"] for item in metrics if item.get("hostAvailableMemoryBytes") is not None]
resources = {
    "sampleCount": len(metrics),
    "processCpuPercent": {"p50": nearest(cpu, .5), "p95": nearest(cpu, .95), "max": max(cpu) if cpu else None},
    "processRssBytes": {"p50": nearest(rss, .5), "p95": nearest(rss, .95), "max": max(rss) if rss else None},
    "hostAvailableMemoryBytes": {"min": min(host_values) if host_values else None},
}
if os.path.exists(os.path.join(run_dir, ".sampler-limit-reached")):
    resources.update({"sampleLimit": sample_limit, "truncated": True})

finished_at = utc_now()
snapshot.update({
    "version": "fmix-session.v1", "runId": RUN_ID,
    "fmixVersion": FMIX_VERSION, "launcherPid": os.getpid(), "pid": worker_pid,
    "state": state, "phase": "terminal", "exitCode": exit_code,
    "updatedAt": finished_at, "finishedAt": finished_at,
    "resources": resources, "telemetry": {"degraded": degraded},
})
snapshot.pop("termination", None)
if not result_exact:
    if not reaped:
        termination_reason = "worker_not_reaped"
    elif group_permission_denied:
        termination_reason = "group_permission_denied"
    elif group_unverified:
        termination_reason = "group_unverified"
    else:
        termination_reason = "deadline_exhausted"
    requested_signal = None
    requested_exit_code = None
    if native_signal in SIGNAL_CODES:
        requested_signal = {
            signal.SIGHUP: "HUP", signal.SIGINT: "INT", signal.SIGTERM: "TERM",
        }[native_signal]
        requested_exit_code = SIGNAL_CODES[native_signal]
    snapshot["termination"] = {
        "reason": termination_reason,
        "requestedSignal": requested_signal,
        "requestedExitCode": requested_exit_code,
        "resultExact": False,
        "workerReaped": reaped,
        "samplerReaped": sampler_reaped,
        "sentinelReaped": sentinel_reaped,
        "cleanup": "incomplete",
    }
if handoff is not None:
    snapshot["phases"] = handoff.get("phaseSeconds", {})
    snapshot["durationSeconds"] = handoff.get("timing", {}).get("durationSeconds", 0)
    for source_key, target_key in (("cache", "cache"), ("compile", "compile"), ("session", "session"), ("artifacts", "artifacts"), ("worktree", "worktree"), ("templateKey", "templateKey"), ("database", "database")):
        if source_key in handoff:
            snapshot[target_key] = handoff[source_key]

terminal_event = {
    "version": "fmix-event.v1", "runId": RUN_ID, "seq": next_sequence(),
    "type": "run_finished" if result_exact else "run_abandoned",
    "timestamp": finished_at, "phase": "terminal",
    "state": state, "exitCode": exit_code,
}
publication_succeeded = False
try:
    atomic_snapshot(snapshot)
    publication_succeeded = True
except OSError:
    degraded = True
if publication_succeeded:
    try:
        append_event(terminal_event)
        dir_fsync()
    except OSError:
        degraded = True
artifact_manifest_published = publish_artifact_manifest(
    snapshot, state, state == "abandoned"
)
if not artifact_manifest_published:
    degraded = True
os.close(events_fd)


def write_update_timings():
    if not diagnostics_enabled or not update_timings:
        return
    payload = b"".join(
        json.dumps(item, separators=(",", ":")).encode() + b"\n"
        for item in update_timings
    )
    fd = None
    try:
        fd = os.open(
            update_timing_path,
            os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow,
            0o600,
        )
        write_all(fd, payload)
        os.fsync(fd)
        os.close(fd)
        fd = None
        dir_fsync()
    except OSError:
        if fd is not None:
            try:
                os.close(fd)
            except OSError:
                pass
        try:
            os.unlink(update_timing_path)
        except OSError:
            pass


write_update_timings()

pending = signal.sigpending()
delivery_signal = native_signal or first_post_signal
if delivery_signal is None:
    for candidate in MANAGED:
        if candidate in pending:
            delivery_signal = candidate
            break
final_signal_mask = set(blocked_previous)
if signal.SIGALRM in startup_signal_mask:
    final_signal_mask.add(signal.SIGALRM)
else:
    final_signal_mask.discard(signal.SIGALRM)
signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGALRM})
signal.setitimer(signal.ITIMER_REAL, 0)
while signal.SIGALRM in signal.sigpending():
    signal.sigwait({signal.SIGALRM})
signal.signal(signal.SIGALRM, previous_alarm_handler)
if delivery_signal is not None:
    signal.signal(delivery_signal, signal.SIG_DFL)
    signal.pthread_sigmask(signal.SIG_SETMASK, final_signal_mask)
    if delivery_signal not in pending:
        os.kill(os.getpid(), delivery_signal)
    time.sleep(1)
    os._exit(128 + delivery_signal)

signal.pthread_sigmask(signal.SIG_SETMASK, final_signal_mask)
raise SystemExit(exit_code)
PY
}

fmix_run_embedded_supervisor() {
    local py_bin supervisor_source
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    supervisor_source="$(fmix_observability_supervisor_source)" || return 125
    FMIX_VERSION="$FMIX_VERSION" exec "$py_bin" -c "$supervisor_source" "$0" "$@"
}

fmix_observability_validate_worker_capability() {
    local LC_ALL=C
    [[ "${FMIX_OBSERVABILITY_CAPABILITY_FD:-}" == "7" \
        && "${FMIX_OBSERVABILITY_EVENTS_FD:-}" == "8" \
        && "${FMIX_OBSERVABILITY_HANDOFF_FD:-}" == "9" \
        && "${FMIX_OBSERVABILITY_UPDATES_FD:-}" == "10" \
        && "${FMIX_OBSERVABILITY_UPDATES_ACK_FD:-}" == "11" ]] || return 1
    [[ -p /dev/fd/7 && -f /dev/fd/8 && -p /dev/fd/9 \
        && -p /dev/fd/10 && -p /dev/fd/11 ]] || return 1

    local version run_id supervisor_pid worker_pid worker_pgid
    local events_dev events_inode updates_dev updates_inode
    local updates_ack_dev updates_ack_inode capability_token extra
    IFS= read -r version <&7 \
        && IFS= read -r run_id <&7 \
        && IFS= read -r supervisor_pid <&7 \
        && IFS= read -r worker_pid <&7 \
        && IFS= read -r worker_pgid <&7 \
        && IFS= read -r events_dev <&7 \
        && IFS= read -r events_inode <&7 \
        && IFS= read -r updates_dev <&7 \
        && IFS= read -r updates_inode <&7 \
        && IFS= read -r updates_ack_dev <&7 \
        && IFS= read -r updates_ack_inode <&7 \
        && IFS= read -r capability_token <&7 \
        || return 1
    if IFS= read -r extra <&7; then
        return 1
    fi
    [[ "$version" == "fmix-worker-capability.v3" \
        && "$run_id" == "$FMIX_RUN_ID" \
        && "$supervisor_pid" == "$PPID" \
        && "$supervisor_pid" == "${FMIX_OBSERVABILITY_SUPERVISOR_PID:-}" \
        && "$worker_pid" == "$$" \
        && "$worker_pgid" == "$$" \
        && "$events_dev" == "${FMIX_OBSERVABILITY_EVENTS_DEV:-}" \
        && "$events_inode" == "${FMIX_OBSERVABILITY_EVENTS_INODE:-}" \
        && "$updates_dev" == "${FMIX_OBSERVABILITY_UPDATES_DEV:-}" \
        && "$updates_inode" == "${FMIX_OBSERVABILITY_UPDATES_INODE:-}" \
        && "$updates_ack_dev" == "${FMIX_OBSERVABILITY_UPDATES_ACK_DEV:-}" \
        && "$updates_ack_inode" == "${FMIX_OBSERVABILITY_UPDATES_ACK_INODE:-}" \
        && "$capability_token" == "${FMIX_OBSERVABILITY_CAPABILITY_TOKEN:-}" \
        && "$capability_token" =~ ^[0-9a-f]{64}$ \
        && "$supervisor_pid" =~ ^[1-9][0-9]*$ \
        && "$worker_pid" =~ ^[1-9][0-9]*$ \
        && "$events_dev" =~ ^[0-9]+$ && "$events_inode" =~ ^[0-9]+$ \
        && "$updates_dev" =~ ^[0-9]+$ && "$updates_inode" =~ ^[0-9]+$ \
        && "$updates_ack_dev" =~ ^[0-9]+$ \
        && "$updates_ack_inode" =~ ^[0-9]+$ ]] || return 1
    unset FMIX_OBSERVABILITY_CAPABILITY_TOKEN
    exec 7<&-
}

# Offline analysis stays inside the self-contained distributed runner. It never
# initializes FMIX_HOME, resolves credentials, starts Mix, or changes run truth.
cmd_analyze() {
    local py_bin
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    "$py_bin" - "$@" <<'FMIX_ANALYZE_PY'
import argparse
import base64
from collections import Counter, defaultdict
import hashlib
import html
import json
import math
import os
from pathlib import Path
import re
import stat
import sys

MAX_BYTES = 256 * 1024 * 1024
MAX_LINE = 256 * 1024
MAX_EVENTS = 400000
STATES = ('passed', 'failed', 'skipped', 'excluded', 'invalid')
TAGS = {'unit', 'integration', 'benchmark', 'benchmark_heavy', 'heavy_benchmark',
        'performance', 'stress_test', 'slow', 'e2e', 'feature_e2e', 'uat',
        'external', 'manual_only', 'nightly_only', 'fmix_domain', 'fmix_level',
        'fmix_purpose', 'fmix_services', 'report_registry', 'regression', 'story',
        'requires_org', 'nats_required', 'nats_integration', 'timescaledb'}


def strict_json(value):
    def invalid(_):
        raise ValueError('non-finite JSON number')
    return json.loads(value, parse_constant=invalid)


def number(value):
    return value if type(value) in (int, float) and math.isfinite(value) and value >= 0 else None


def text(value, limit=500):
    return value[:limit] if isinstance(value, str) else ''


def safe_file(root, relative, optional=False):
    path = root
    for part in Path(relative).parts:
        path = path / part
        if path.is_symlink():
            raise ValueError('symlinked input: ' + relative)
    if optional and not path.exists():
        return None
    fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
    info = os.fstat(fd)
    if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_BYTES:
        os.close(fd)
        raise ValueError('input is not a bounded regular file: ' + relative)
    return os.fdopen(fd, encoding='utf-8')


def read_object(root, relative, optional=False):
    stream = safe_file(root, relative, optional)
    if stream is None:
        return None
    with stream:
        value = strict_json(stream.read(MAX_BYTES + 1))
    if not isinstance(value, dict):
        raise ValueError('expected JSON object: ' + relative)
    return value


def records(root, relative, issues, optional=False):
    stream = safe_file(root, relative, optional)
    if stream is None:
        issues.append('missing ' + relative)
        return
    size = 0
    with stream:
        for index in range(MAX_EVENTS):
            line = stream.readline(MAX_LINE + 1)
            if not line:
                return
            size += len(line.encode('utf-8'))
            if len(line) > MAX_LINE or size > MAX_BYTES:
                issues.append('input limit reached: ' + relative)
                return
            try:
                item = strict_json(line)
                if not isinstance(item, dict):
                    raise ValueError('record is not an object')
                yield item
            except (ValueError, TypeError):
                issues.append('invalid JSON record in ' + relative + ':' + str(index + 1))
        issues.append('event limit reached: ' + relative)


def source_view(source):
    source = source if isinstance(source, dict) else {}
    result = {}
    for key in ('commit_sha', 'tree_sha'):
        value = source.get(key)
        result[key] = value if isinstance(value, str) and re.fullmatch('[0-9a-f]{40}', value) else None
    result['dirty'] = source.get('dirty') if type(source.get('dirty')) is bool else None
    for key in ('elixir', 'otp', 'profile', 'partition'):
        result[key] = text(source.get(key), 80)
    return result


def classify(ref, tags, observed, queries):
    parts = ref['file'].split('/')
    domain = tags.get('fmix_domain')
    domain_basis = 'explicit tag'
    if not isinstance(domain, str):
        domain = parts[2] if len(parts) > 2 and parts[1] == 'cdrcisco' else (parts[1] if len(parts) > 1 else 'unknown')
        domain_basis = 'directory inference'
    level = tags.get('fmix_level')
    basis = 'explicit tag'
    if not isinstance(level, str):
        if observed and queries and queries > 0:
            level, basis = 'integration', 'observed SQL'
        elif tags.get('unit') is True:
            level = 'unit'
        elif tags.get('integration') is True:
            level = 'integration'
        elif '/unit/' in ref['file']:
            level, basis = 'unit', 'directory inference'
        elif '/integration/' in ref['file']:
            level, basis = 'integration', 'directory inference'
        else:
            level, basis = 'unknown', 'not classified'
    purpose = tags.get('fmix_purpose')
    if not isinstance(purpose, str):
        purpose = 'performance' if any(tags.get(t) is True for t in ('benchmark', 'benchmark_heavy', 'heavy_benchmark', 'performance')) else 'unclassified'
    return {'domain': domain, 'domain_basis': domain_basis, 'level': level,
            'level_basis': basis, 'purpose': purpose}


def measured_sections(raw, observed):
    if not observed or not isinstance(raw, list):
        return []
    result = []
    for row in raw[:256]:
        if not isinstance(row, dict):
            continue
        name, us = row.get('section'), number(row.get('time_us'))
        if isinstance(name, str) and re.fullmatch(r'[A-Za-z0-9_.:-]{1,100}', name) and us is not None:
            result.append({'section': name, 'duration_ms': us / 1000, 'inclusive': True})
    return result


def operation_view(raw, sequence):
    if not isinstance(raw, dict) or raw.get('name') != 'report_registry.load':
        return None
    duration = number(raw.get('duration_ms'))
    if duration is None or raw.get('scope') != 'run' or raw.get('status') not in ('ok', 'error'):
        return None
    initiator = raw.get('initiator')
    initiator = ({key: text(initiator.get(key)) for key in ('module', 'name')}
                 if isinstance(initiator, dict) else None)
    return {'name': raw['name'], 'scope': 'run', 'duration_ms': duration,
            'status': raw['status'], 'event_sequence': sequence,
            'trigger': raw.get('trigger') if raw.get('trigger') in ('first_use', 'refresh', 'manual_reload') else 'unknown',
            'report_count': number(raw.get('report_count')), 'initiator': initiator}


def focused_files(rows):
    files = sorted({t['file'] for t in rows if re.fullmatch(r'test/[A-Za-z0-9_./-]+\.exs', t['file'])
                    and '..' not in Path(t['file']).parts})
    return {'mode': 'focused_fmix', 'test_files': files[:50], 'test_files_truncated': len(files) > 50}


SQL_KINDS = ('select', 'insert', 'update', 'delete', 'ddl', 'transaction', 'other')
SIGNAL_SECTIONS = ('sql_breakdown', 'logs', 'oban', 'http', 'beam')
LOG_LEVELS = ('debug', 'info', 'notice', 'warning', 'error', 'total')


def count_time(raw):
    if not isinstance(raw, dict) or type(raw.get('count')) is not int or raw['count'] < 0:
        return None
    ms = number(raw.get('time_ms'))
    return {'count': raw['count'], 'time_ms': ms} if ms is not None else None


def counts(raw, keys):
    if not isinstance(raw, dict) or not all(type(raw.get(k)) is int and raw[k] >= 0 for k in keys):
        return None
    return {k: raw[k] for k in keys}


def signals_view(raw):
    """Strict ct-test-signals.v1 view. Unobserved or malformed sections stay absent, never zero."""
    if raw is None:
        return None, False
    if not isinstance(raw, dict) or raw.get('schema') != 'ct-test-signals.v1' or not isinstance(raw.get('observed'), dict):
        return None, True
    observed = {key: raw['observed'].get(key) is True for key in SIGNAL_SECTIONS}
    view, malformed = {'observed': observed}, False
    sql = raw.get('sql')
    if observed['sql_breakdown'] and isinstance(sql, dict):
        kinds = sql.get('by_kind') if isinstance(sql.get('by_kind'), dict) else {}
        repos = sql.get('by_repo') if isinstance(sql.get('by_repo'), dict) else {}
        sources = sql.get('top_sources') if isinstance(sql.get('top_sources'), list) else []
        view['sql'] = {
            'by_kind': {k: v for k in SQL_KINDS if (v := count_time(kinds.get(k)))},
            'by_repo': {k: v for k, item in list(repos.items())[:16]
                        if re.fullmatch('[a-z0-9_]{1,64}', k) and (v := count_time(item))},
            'top_sources': [{'source': s['source'], **v} for s in sources[:10]
                            if isinstance(s, dict) and isinstance(s.get('source'), str)
                            and re.fullmatch(r'[A-Za-z0-9_.()]{1,64}', s['source']) and (v := count_time(s))]}
    elif observed['sql_breakdown']:
        observed['sql_breakdown'], malformed = False, True
    sections = [('logs', LOG_LEVELS, ()), ('oban', ('jobs', 'failures'), ('time_ms',)), ('http', ('requests',), ('time_ms',))]
    for key, ints, floats in sections:
        if not observed[key]:
            continue
        value = counts(raw.get(key), ints)
        if value is not None and all(number((raw.get(key) or {}).get(f)) is not None for f in floats):
            view[key] = value | {f: number(raw[key][f]) for f in floats}
        else:
            observed[key], malformed = False, True
    beam = raw.get('beam')
    if observed['beam']:
        valid = (isinstance(beam, dict) and beam.get('scope') == 'sync_exclusive'
                 and all(type(beam.get(k)) is int for k in ('reductions', 'process_delta', 'memory_delta_bytes', 'gc_runs'))
                 and beam['reductions'] >= 0 and beam['gc_runs'] >= 0)
        if valid:
            view['beam'] = {k: beam[k] for k in ('scope', 'reductions', 'process_delta', 'memory_delta_bytes', 'gc_runs')}
        else:
            observed['beam'], malformed = False, True
    return view, malformed


def signals_summary(tests, started, malformed):
    raw = (started or {}).get('signals_collector')
    collector = None
    if isinstance(raw, dict):
        handlers = raw.get('handlers') if isinstance(raw.get('handlers'), list) else []
        collector = {'schema': text(raw.get('schema'), 40), 'logger_level': text(raw.get('logger_level'), 20),
                     'handlers': sorted({h for h in handlers if isinstance(h, str) and re.fullmatch('[a-z_]{1,40}', h)})}
    executed = [t for t in tests if t['status'] in ('passed', 'failed')]
    present = [t for t in executed if t['signals']]
    return {'collector': collector, 'executed_tests': len(executed), 'tests_with_signals': len(present),
            'observed_tests': {key: sum(1 for t in present if t['signals']['observed'][key]) for key in SIGNAL_SECTIONS},
            'malformed_records': malformed,
            'note': 'Signals are attributed through test process lineage. Work in processes outside that lineage, and HTTP clients without telemetry, are not counted. BEAM deltas are recorded only for sync tests.'}


BOOT_MARKS = ('vm_started', 'mix_task_entered', 'apps_started', 'helper_started', 'helper_finished',
              'suite_started', 'suite_finished', 'at_exit')
MFA = re.compile(r'[A-Za-z0-9_.?!]{1,160}/[0-9]{1,3}')


def epoch_ms(value):
    return value if type(value) is int and 10 ** 12 <= value < 10 ** 14 else None


def boot_view(root, startup, issues):
    """Join runner and VM wall-clock marks into consecutive measured boot segments."""
    runner = read_object(root, 'artifacts/live/mix_boundaries.json', optional=True)
    vm = read_object(root, 'artifacts/live/boot_timeline.json', optional=True)
    if runner is not None and runner.get('schema') != 'fmix-mix-boundaries.v1':
        issues.append('unknown mix boundary schema')
        runner = None
    if vm is not None and vm.get('schema') != 'ct-test-boot.v1':
        issues.append('unknown boot timeline schema')
        vm = None
    if runner is None and vm is None:
        return None
    runner = runner or {}
    raw_marks = vm.get('marks') if vm and isinstance(vm.get('marks'), dict) else {}
    marks = {'guard_pre_started': epoch_ms(runner.get('guard_pre_started_at')), 'spawned': epoch_ms(runner.get('spawned_at'))}
    marks.update({key: epoch_ms(raw_marks.get(key)) for key in BOOT_MARKS})
    marks.update({'exited': epoch_ms(runner.get('exited_at')), 'guard_post_finished': epoch_ms(runner.get('guard_post_finished_at'))})
    present = [(k, v) for k, v in marks.items() if v is not None]
    if any(b[1] < a[1] for a, b in zip(present, present[1:])):
        issues.append('boot timeline marks are out of order; segments omitted')
        present = []
    labels = {'spawned': 'Source check before Mix', 'vm_started': 'BEAM VM start',
              'mix_task_entered': 'Mix boot (load paths, config)',
              'apps_started': 'Application start (profiled)',
              'helper_started': 'Before test helper (Mix app.start)' if marks['apps_started'] is None else 'Before test helper',
              'helper_finished': 'Test helper', 'suite_started': 'Test file loading',
              'suite_finished': 'ExUnit run', 'at_exit': 'Suite teardown and exit hooks',
              'exited': 'VM shutdown', 'guard_post_finished': 'Source check after Mix'}
    # Without --profile-boot the apps_started mark is expected to be absent; any
    # other gap merges neighbors under a name that lists every covered interval.
    order = [k for k in marks if k != 'apps_started' or marks[k] is not None]
    segments = []
    for a, b in zip(present, present[1:]):
        covered = order[order.index(a[0]) + 1:order.index(b[0]) + 1]
        segments.append({'name': labels[b[0]] if len(covered) == 1 else 'Merged (missing marks): ' + ' + '.join(labels[k] for k in covered),
                         'from': a[0], 'to': b[0], 'start_ms': a[1] - present[0][1], 'duration_ms': b[1] - a[1],
                         'merged': len(covered) > 1, 'tests': covered == ['suite_finished']})
    window = present[-1][1] - present[0][1] if present else None

    def ranked(rows, fields):
        out = []
        for row in rows if isinstance(rows, list) else []:
            if not isinstance(row, dict) or number(row.get('duration_ms')) is None:
                continue
            item = {f: text(row.get(f), 160) for f in fields}
            if all(item.values()):
                out.append(item | {'duration_ms': number(row['duration_ms'])})
        return sorted(out, key=lambda r: -r['duration_ms'])[:50]

    return {'clock': 'os_time_ms', 'boot_profile': bool(vm and vm.get('boot_profile') is True),
            'runner_marks': runner != {}, 'vm_marks': vm is not None, 'marks': marks, 'segments': segments,
            'window_ms': window, 'helper_phases': startup,
            'apps': ranked(vm.get('apps') if vm else None, ('app',)),
            'children': ranked(vm.get('children') if vm else None, ('supervisor', 'child')),
            'note': 'Segments are consecutive wall-clock intervals between recorded marks on one host clock. A missing mark merges its neighbors; nothing is estimated.'}


def fixture_view(root, issues):
    raw = read_object(root, 'artifacts/live/fixture_prof.json', optional=True)
    if raw is None:
        return None
    if raw.get('schema') != 'ct-test-fixture-prof.v1' or not isinstance(raw.get('functions'), list):
        issues.append('unknown or malformed fixture profile')
        return None
    rows = []
    for row in raw['functions'][:200]:
        if (isinstance(row, dict) and isinstance(row.get('mfa'), str) and MFA.fullmatch(row['mfa'])
                and type(row.get('calls')) is int and row['calls'] >= 0 and number(row.get('inclusive_ms')) is not None):
            rows.append({'mfa': row['mfa'], 'calls': row['calls'], 'inclusive_ms': number(row['inclusive_ms']),
                         'max_ms': number(row.get('max_ms'))})
    return {'method': text(raw.get('method'), 60), 'truncated': raw.get('truncated') is True,
            'modules': number(raw.get('modules')), 'functions': sorted(rows, key=lambda r: -r['inclusive_ms'])[:100],
            'note': 'Inclusive time: nested fixture calls are counted in both the caller and the callee, so rows must not be summed.'}


def tag_profile(tests):
    rows = defaultdict(lambda: {'tests': 0, 'work_ms': 0})
    for t in tests:
        if t['status'] not in ('passed', 'failed'):
            continue
        keys = [k for k, v in t['tags'].items() if v is True]
        keys += [k + '=' + v for k, v in t['tags'].items() if isinstance(v, str)]
        keys += ['level=' + t['classification']['level'], 'async' if t['async'] else 'sync']
        for key in keys:
            rows[key]['tests'] += 1
            rows[key]['work_ms'] += t['total_time_ms'] or 0
    return sorted(({'tag': k, **v} for k, v in rows.items()), key=lambda r: -r['work_ms'])[:60]


def rank_hotspots(data):
    if not data['completeness']['complete']:
        return []
    tests = [t for t in data['tests'] if t['status'] in ('passed', 'failed')]
    rows = []

    def add(rule, scope, key, title, cost, affected, recommendation, retain, confidence='observed_cost', evidence=None):
        facts = {'run_id': data['run_id'], 'source_commit': data['source']['commit_sha'],
                 'sample_count': 1, 'affected_tests': len(affected),
                 'test_ids': sorted({t['id'] for t in affected})[:100]}
        facts.update(evidence or {})
        rows.append({'id': hashlib.sha256((rule + '\0' + key).encode()).hexdigest(),
                     'rule_id': rule, 'scope': scope, 'scope_key': key, 'title': title,
                     'observed_cost_ms': cost, 'estimated_savings_ms': None,
                     'cost_additive': False, 'confidence': confidence,
                     'recommendation': recommendation, 'retain': retain,
                     'verification': focused_files(affected), 'evidence': facts})

    timing = data['timing']
    prep = timing.get('runner_preparation_ms')
    execution_ms = timing.get('exunit_run_ms')
    if prep is not None and prep >= 1000:
        phases = timing['phases_seconds']
        components = sorted(((k, v) for k, v in phases.items() if k != 'mix_test' and v is not None), key=lambda x: -x[1])
        add('runner_preparation', 'run', 'runner_preparation',
            'Runner preparation dominates this selection' if execution_ms is not None and prep >= execution_ms else 'Runner preparation has measured cost', prep, tests,
            'Measure the largest preparation substeps through the normal installed runner before changing cache or lock policy.',
            'Source identity, database provenance, locking and cache verification',
            evidence={'comparison_available': execution_ms is not None, 'exunit_run_ms': execution_ms,
                      'components_seconds': dict(components), 'compile_seconds': timing['compile']['seconds'],
                      'compile_files': timing['compile']['file_count'],
                      'permit_wait_seconds': phases.get('compile_permit_wait'),
                      'compile_timing_note': 'compiler invocation timing can include permit wait; phase boundaries are consecutive', 'cost_scope': 'runner preparation envelope'})
    startup = timing['startup_phases']
    envelope = startup.get('test_helper_pre_exunit_total', {}).get('duration_ms')
    if envelope is not None and envelope >= 100:
        add('helper_startup', 'run', 'test_helper_pre_exunit_total', 'Helper startup is a shared cost', envelope, tests,
            'Check which selected test requirements need the largest startup phases; verify a narrower profile on the same selection.',
            'Required services, partitions, migrations and integration behavior',
            evidence={'components': {k: v for k, v in startup.items() if k != 'test_helper_pre_exunit_total'},
                      'cost_scope': 'helper envelope; child phases are included'})

    measured_first = defaultdict(float)
    if data['operation_evidence']['complete']:
        operations = defaultdict(list)
        for op in data['operations']:
            operations[op['name']].append(op)
        for name, spans in operations.items():
            modules = {s['initiator']['module'] for s in spans if s['initiator'] and s['initiator']['module']}
            for span in spans:
                if span['initiator'] and span['trigger'] == 'first_use':
                    measured_first[(span['initiator']['module'], span['initiator']['name'])] += span['duration_ms']
            affected = [t for t in tests if t['module'] in modules] or tests
            add('shared_initialization', 'operation', name, 'Shared registry loading was measured',
                sum(s['duration_ms'] for s in spans), affected,
                'Profile discovery and definition loading; preserve an explicit cold-load contract when reusing initialized state.',
                'Registry contents, refresh/restart behavior and metadata contracts', 'measured_operation',
                {'operations': spans, 'occurrences': len(spans), 'cost_scope': 'shared operation; overlaps triggering test time'})

    modules = defaultdict(list)
    for t in tests:
        modules[t['module']].append(t)
    for module, members in modules.items():
        if len(members) < 3:
            continue
        ordered = sorted(members, key=lambda t: t.get('start_sequence') or t['event_sequence'])
        first, rest = ordered[0], ordered[1:]
        total = sum(t['total_time_ms'] or 0 for t in members)
        others = sorted(t['total_time_ms'] or 0 for t in rest)
        median = others[len(others) // 2]
        cost = first['total_time_ms'] or 0
        if cost > 0 and measured_first[(module, first['name'])] >= cost * .5:
            continue
        if cost >= 50 and cost >= 5 * max(median, 0.001) and cost >= total * .5:
            add('first_use_concentration', 'module', module, 'First observed test dominates its module', cost, members,
                'Add a shared-load span and vary test order to check whether the cost follows the first lookup; do not remove the triggering test.',
                'Cold-start behavior and the triggering test assertions', 'hypothesis',
                {'first_test_id': first['id'], 'module_work_ms': total, 'other_median_ms': median,
                 'order_basis': 'test start event' if first.get('start_sequence') else 'first result observed',
                 'cost_scope': 'first test duration; shared-load contribution not yet attributed'})

    fixtures = defaultdict(list)
    for t in tests:
        if t['setup_time_ms'] is None:
            continue
        aggregates = [s['section'] for s in t['setup_sections'] if s['section'].endswith('.setup')]
        key = aggregates[0] if len(aggregates) == 1 else 'observed_setup:' + t['module']
        fixtures[key].append(t)
    for name, members in fixtures.items():
        heavy = [t for t in members if (t['setup_percent'] or 0) >= 50]
        cost = sum(t['setup_time_ms'] for t in members)
        if len(heavy) >= 3 and cost >= 10:
            sections = defaultdict(float)
            for t in members:
                for section in t['setup_sections']:
                    if section['section'] != name:
                        sections[section['section']] += section['duration_ms']
            add('repeated_setup', 'fixture', name, 'Repeated fixture cost hides below per-test thresholds', cost, members,
                'Inspect the setup-heavy subset for a focused case/fixture; use the breakdown to target common sandbox or service work.',
                'Database isolation, cleanup and each test public behavior',
                evidence={'setup_heavy_tests': len(heavy), 'setup_heavy_work_ms': sum(t['total_time_ms'] or 0 for t in heavy),
                          'setup_heavy_setup_ms': sum(t['setup_time_ms'] for t in heavy),
                          'nested_sections_ms': dict(sorted(sections.items(), key=lambda x: -x[1])[:20]),
                          'cost_scope': 'observed setup aggregate; nested sections are not added'})

    conflicts = defaultdict(list)
    query_heavy = defaultdict(list)
    for t in tests:
        if t['db_observed'] and (t['db_query_count'] or 0) > 0:
            if '/unit/' in t['file'] or t['tags'].get('unit') is True or t['classification']['level'] == 'unit':
                conflicts[t['file']].append(t)
            if (t['db_query_count'] or 0) >= 50:
                query_heavy[t['file']].append(t)
    for file, members in conflicts.items():
        declared = sorted({t['tags']['fmix_level'] if isinstance(t['tags'].get('fmix_level'), str) else 'unspecified' for t in members})
        action = ('The tests already declare integration; align the unit directory or acknowledge its legacy mapping.'
                  if declared == ['integration'] else 'Review the unit classification against observed persistence work.')
        add('classification_conflict', 'file', file, 'Unit naming and observed persistence disagree', None, members,
            action + ' This is a classification recommendation, not a measured speedup.',
            'Real persistence and tenant-scoping checks', 'classification',
            {'declared_levels': declared, 'queries': sum(t['db_query_count'] for t in members), 'cost_scope': 'classification only'})
    for file, members in query_heavy.items():
        add('sql_concentration', 'file', file, 'Attributed SQL work is concentrated',
            (sum(t['db_query_time_ms'] + t['db_queue_time_ms'] for t in members)
             if all(t['db_query_time_ms'] is not None and t['db_queue_time_ms'] is not None for t in members) else None), members,
            'Separate fixture SQL, repeated lookups and pool waiting before proposing query or concurrency changes.',
            'Persistence and transaction semantics',
            evidence={'queries': sum(t['db_query_count'] for t in members), 'cost_scope': 'attributed SQL execution plus queue time; overlaps test duration'})
    boot = data.get('boot') or {}
    for segment in boot.get('segments', []):
        # The helper interval is already ranked from its own measured phases.
        if not segment['tests'] and segment['to'] != 'helper_finished' and segment['duration_ms'] >= 2000:
            add('boot_segment', 'run', segment['to'], segment['name'] + ' is a measured startup cost', segment['duration_ms'], tests,
                'Inspect this interval first. Rerun with fmix test --profile-boot to split application and supervisor-child start time.',
                'Services and processes the selected tests actually exercise',
                evidence={'from_mark': segment['from'], 'to_mark': segment['to'], 'cost_scope': 'consecutive wall-clock interval'})
    for row in boot.get('apps', [])[:10]:
        if row['duration_ms'] >= 500:
            add('app_start', 'application', row['app'], 'Application start is slow', row['duration_ms'], tests,
                'Check whether selected tests need this application; start it lazily or stub it in the test profile.',
                'Behavior of tests that use this application', evidence={'cost_scope': 'Application.ensure_started duration'})
    for row in boot.get('children', [])[:15]:
        if row['duration_ms'] >= 500:
            add('child_start', 'supervisor_child', row['supervisor'] + ' > ' + row['child'], 'Supervisor child start is slow',
                row['duration_ms'], tests,
                'Defer this child (handle_continue, lazy connect) or exclude it from the test supervision tree.',
                'Behavior of tests that use this process', evidence={'cost_scope': 'supervisor child start call duration'})
    for row in (data.get('fixtures') or {}).get('functions', [])[:15]:
        if row['inclusive_ms'] >= 200:
            add('fixture_cost', 'fixture_function', row['mfa'], 'Fixture or helper function is expensive', row['inclusive_ms'], tests,
                'Cache it in setup_all, build structs instead of inserting, or trim the records it creates.',
                'Data shape that dependent tests assert on', 'observed_cost',
                {'calls': row['calls'], 'max_ms': row['max_ms'], 'cost_scope': 'inclusive call time; nested fixtures overlap'})
    write_only = defaultdict(list)
    for t in tests:
        kinds = (t.get('signals') or {}).get('sql', {}).get('by_kind')
        if kinds and 'insert' in kinds and not {'select', 'update', 'delete'} & set(kinds):
            write_only[t['file']].append(t)
    for file, members in write_only.items():
        if len(members) >= 3:
            add('insert_without_read', 'file', file, 'Tests persist rows they never read back', None, members,
                'Check whether these tests need the database. Building structs or using in-memory params avoids inserts the test never queries.',
                'Persistence assertions and constraint checks', 'hypothesis',
                {'inserts': sum(t['signals']['sql']['by_kind']['insert']['count'] for t in members), 'cost_scope': 'classification only'})
    ddl, noisy, http, leaks, perf = (defaultdict(list) for _ in range(5))
    for t in tests:
        if t['classification']['purpose'] == 'performance':
            perf[t['file']].append(t)
        s = t.get('signals')
        if not s:
            continue
        if 'ddl' in s.get('sql', {}).get('by_kind', {}):
            ddl[t['file']].append(t)
        logs = s.get('logs')
        if logs and t['status'] == 'passed' and (logs['error'] > 0 or logs['total'] >= 50):
            noisy[t['file']].append(t)
        if s.get('http', {}).get('requests', 0) > 0:
            http[t['file']].append(t)
        if s.get('beam', {}).get('process_delta', 0) >= 10:
            leaks[t['file']].append(t)
    for file, members in ddl.items():
        statements = [t['signals']['sql']['by_kind']['ddl'] for t in members]
        add('ddl_in_tests', 'file', file, 'Tests issue schema statements (DDL)', sum(s['time_ms'] for s in statements), members,
            'Move schema work into the template database or a once-per-run helper. DDL inside tests takes locks and defeats sandbox reuse.',
            'Behavior that genuinely depends on schema changes, such as migration tests',
            evidence={'ddl_statements': sum(s['count'] for s in statements), 'cost_scope': 'attributed DDL execution time; overlaps test duration'})
    for file, members in perf.items():
        add('performance_in_selection', 'file', file, 'Benchmark or performance tests ran in this selection',
            sum(t['total_time_ms'] or 0 for t in members), members,
            'Confirm these belong in an explicit performance lane (tag exclusion) rather than routine runs; keep thresholds that guard real regressions.',
            'Regression thresholds with a documented owner', 'classification',
            {'tags': sorted({k for t in members for k, v in t['tags'].items() if v is True}), 'cost_scope': 'test duration of performance-purpose tests'})
    for file, members in http.items():
        add('http_in_tests', 'file', file, 'Tests make telemetry-visible HTTP calls',
            sum(t['signals']['http']['time_ms'] for t in members), members,
            'Confirm each call targets a local stub. Replace live network calls with an adapter, Mox, or a recorded stub.',
            'Contract coverage against recorded or stubbed responses',
            evidence={'requests': sum(t['signals']['http']['requests'] for t in members), 'cost_scope': 'attributed HTTP request time; overlaps test duration'})
    for file, members in noisy.items():
        add('log_noise', 'file', file, 'Passing tests emit error or high-volume logs', None, members,
            'Assert expected logs with capture_log and quiet incidental logging. Error logs in passing tests hide real failures.',
            'Assertions on logged behavior', 'classification',
            {'error_logs': sum(t['signals']['logs']['error'] for t in members),
             'warning_logs': sum(t['signals']['logs']['warning'] for t in members),
             'total_logs': sum(t['signals']['logs']['total'] for t in members), 'cost_scope': 'classification only'})
    for file, members in leaks.items():
        add('process_leak', 'file', file, 'Sync tests leave processes running', None, members,
            'Start test processes with start_supervised! or stop them in on_exit. Leaked processes skew later tests.',
            'Process lifecycle behavior under test', 'classification',
            {'max_process_delta': max(t['signals']['beam']['process_delta'] for t in members), 'cost_scope': 'classification only'})
    rows.sort(key=lambda r: (r['observed_cost_ms'] is None, -(r['observed_cost_ms'] or 0), r['rule_id'], r['scope_key']))
    for i, row in enumerate(rows):
        row['rank'] = i + 1
    return rows


def analyze(root):
    issues = []
    snapshot = read_object(root, 'snapshot.json')
    run_id = text(snapshot.get('runId'), 80)
    if snapshot.get('version') != 'fmix-session.v1' or not re.fullmatch('[0-9a-fA-F-]{36}', run_id):
        raise ValueError('missing valid FMix snapshot identity')
    if snapshot.get('state') not in ('completed', 'failed', 'cancelled', 'abandoned'):
        issues.append('runner is not terminal')
    tests, identities, active_tests = [], set(), set()
    starts, operations, operation_issues = {}, [], []
    malformed_signals = 0
    boot_issues = []
    started = finished = None
    source = source_view(None)
    sequence = 0
    inputs = ['snapshot.json', 'artifacts/live/events.ndjson']
    for event in records(root, inputs[1], issues, optional=True):
        if event.get('run_id') != run_id:
            issues.append('mismatched run identity in test events')
            continue
        if event.get('schema') != 'ct-test-event.v2':
            issues.append('legacy or unknown event schema')
        seq = event.get('sequence')
        if type(seq) is not int or seq != sequence + 1:
            issues.append('duplicate or missing event sequence')
        if type(seq) is int:
            sequence = seq
        kind = event.get('event')
        if kind == 'test_started':
            ref = event.get('test', {})
            if not isinstance(ref, dict) or not ref.get('module') or not ref.get('name'):
                issues.append('missing started test identity')
            else:
                identity = text(ref.get('module')) + '\0' + text(ref.get('name'))
                if identity in active_tests or identity in identities:
                    issues.append('duplicate test start')
                active_tests.add(identity)
                starts[identity] = seq if type(seq) is int else None
        elif kind == 'max_failures_reached':
            issues.append('max failures reached; selection did not finish')
        elif kind == 'suite_started':
            if started is not None:
                issues.append('duplicate suite start')
            started = event
            source = source_view(event.get('source'))
        elif kind == 'suite_finished':
            if finished is not None:
                issues.append('duplicate suite terminal')
            finished = event
        elif kind == 'operation_finished':
            op = operation_view(event.get('operation'), seq)
            if op is None or len(operations) >= 1024 or finished is not None:
                operation_issues.append('invalid, late or over-limit operation record')
            else:
                operations.append(op)
        elif kind == 'test_finished':
            if finished is not None:
                issues.append('test result after suite terminal')
            ref = event.get('test')
            if not isinstance(ref, dict):
                issues.append('missing test identity')
                continue
            ref = {key: text(ref.get(key)) for key in ('module', 'name', 'file')} | {
                'line': number(ref.get('line')), 'async': event['test'].get('async') is True}
            if not ref['module'] or not ref['name']:
                issues.append('missing test identity')
                continue
            identity = ref['module'] + '\0' + ref['name']
            if identity in identities:
                issues.append('duplicate test result')
                continue
            identities.add(identity)
            active_tests.discard(identity)
            status = event.get('status')
            if status not in STATES:
                status = 'unknown'
                issues.append('test outcome is not explicit')
            total = number(event.get('total_time_ms'))
            if total is None:
                issues.append('missing or invalid test duration')
            raw_tags = event['test'].get('tags', {})
            tags = {key: value for key, value in raw_tags.items()
                    if key in TAGS and (type(value) is bool or (key in ("fmix_domain", "fmix_level", "fmix_purpose") and isinstance(value, str) and len(value) <= 128))} if isinstance(raw_tags, dict) else {}
            observed = event.get('db_observed') is True
            queries = number(event.get('db_query_count')) if observed else None
            setup = number(event.get('setup_time_ms')) if event.get('setup_observed') is True else None
            signals, malformed = signals_view(event.get('signals'))
            malformed_signals += malformed
            item = {**ref, 'id': hashlib.sha256(identity.encode()).hexdigest(), 'status': status,
                    'tags': tags, 'total_time_ms': total, 'setup_time_ms': setup,
                    'cleanup_time_ms': number(event.get('cleanup_time_ms')) if event.get('cleanup_observed') is True else None,
                    'setup_percent': (100 * setup / total) if setup is not None and total else None,
                    'db_observed': observed, 'db_query_count': queries,
                    'db_query_time_ms': number(event.get('db_query_time_ms')) if observed else None,
                    'db_queue_time_ms': number(event.get('db_queue_time_ms')) if observed else None,
                    'classification': classify(ref, tags, observed, queries),
                    'event_sequence': seq if type(seq) is int else 0, 'start_sequence': starts.get(identity),
                    'setup_observed': event.get('setup_observed') is True,
                    'cleanup_observed': event.get('cleanup_observed') is True,
                    'setup_sections': measured_sections(event.get('setup_sections'), event.get('setup_observed') is True),
                    'cleanup_sections': measured_sections(event.get('cleanup_sections'), event.get('cleanup_observed') is True),
                    'signals': signals}
            tests.append(item)
    if active_tests:
        issues.append('started tests without terminal outcomes: ' + str(len(active_tests)))
    if started is None:
        issues.append('missing suite start')
    if finished is None:
        issues.append('missing suite terminal')
    if not source['commit_sha'] or not source['tree_sha'] or source['dirty'] is None:
        issues.append('source identity unavailable')
    counts = dict(Counter(t['status'] for t in tests))
    expected = finished.get('counts') if finished else None
    if not isinstance(expected, dict):
        issues.append('missing suite counts')
    elif expected.get('tests') != len(tests) or any(expected.get(key) != counts.get(status, 0) for key, status in [('failures', 'failed'), ('invalid', 'invalid'), ('skipped', 'skipped'), ('excluded', 'excluded')]):
        issues.append('suite counts do not reconcile with result events')
    executed = [t for t in tests if t['status'] in ('passed', 'failed')]
    groups = defaultdict(lambda: {'count': 0, 'executed': 0, 'test_work_ms': 0, 'observed_setup_ms': 0})
    candidates = []
    for t in tests:
        group = groups[t['classification']['domain']]
        group['count'] += 1
        if t['status'] not in ('passed', 'failed'):
            continue
        group['executed'] += 1
        group['test_work_ms'] += t['total_time_ms'] or 0
        group['observed_setup_ms'] += t['setup_time_ms'] or 0
    resource_issues = []
    samples = []
    for row in records(root, 'metrics.jsonl', resource_issues, optional=True):
        if row.get('runId') != run_id or row.get('version') != 'fmix-metric.v1':
            resource_issues.append('resource identity or schema mismatch')
            continue
        samples.append({'at': text(row.get('timestamp'), 80), 'cpu_percent': number(row.get('processCpuPercent')),
                        'rss_bytes': number(row.get('processRssBytes'))})
    raw_resources = snapshot.get('resources', {})
    resources = {'scope': 'runner_process_tree', 'samples': samples, 'issues': sorted(set(resource_issues)),
                 'note': 'CPU/RSS include concurrent runner descendants. They are not per-test CPU, allocated memory, or external PostgreSQL CPU.'}
    if isinstance(raw_resources, dict):
        for key in ('processCpuPercent', 'processRssBytes'):
            val = raw_resources.get(key, {})
            resources[key] = {metric: number(val.get(metric)) for metric in ('p50', 'p95', 'max')} if isinstance(val, dict) else {}
        resources['sampleCount'] = number(raw_resources.get('sampleCount'))
        resources['truncated'] = raw_resources.get('truncated') is True
    vm = read_object(root, 'artifacts/stats/vm_stats.json', optional=True)
    resources['beam_peak_memory_bytes'] = number((((vm or {}).get('peak') or {}).get('memory') or {}).get('total'))
    exunit_times = (finished or {}).get('exunit_times_us', {})
    exunit_times = exunit_times if isinstance(exunit_times, dict) else {}
    exunit_ms = {key: number(exunit_times.get(key)) / 1000 if number(exunit_times.get(key)) is not None else None for key in ('run', 'load', 'async')}
    raw_startup = (started or {}).get('startup_phases', {})
    startup = {key: {'duration_ms': number(value.get('duration_ms')), 'status': text(value.get('status'), 20)}
               for key, value in raw_startup.items() if re.fullmatch('[a-zA-Z0-9_-]{1,80}', key) and isinstance(value, dict)} if isinstance(raw_startup, dict) else {}
    raw_phases = snapshot.get('phases', {})
    phases = {k: number(v) for k, v in raw_phases.items() if re.fullmatch('[a-zA-Z0-9_-]{1,64}', k)} if isinstance(raw_phases, dict) else {}
    compile_info = snapshot.get('compile', {})
    compile_info = compile_info if isinstance(compile_info, dict) else {}
    op_count = (finished or {}).get('operations_count')
    op_dropped = (finished or {}).get('operations_dropped')
    op_pending = (finished or {}).get('operations_pending')
    if operations and (type(op_count) is not int or op_count != len(operations)):
        operation_issues.append('operation count does not reconcile')
    if op_count is not None and (type(op_count) is not int or op_count != len(operations)):
        operation_issues.append('operation count does not reconcile')
    if op_count is not None and (type(op_dropped) is not int or op_dropped != 0):
        operation_issues.append('operation capture was truncated or unqualified')
    if op_count is not None and (type(op_pending) is not int or op_pending != 0):
        operation_issues.append('operation starts remain unfinished or are unqualified')
    cache = snapshot.get('cache', {})
    prep_seconds = number(cache.get('overheadSeconds')) if isinstance(cache, dict) else None
    data = {'schema': 'fmix-analysis.v1', 'run_id': run_id, 'source': source,
            'runner': {'state': text(snapshot.get('state'), 40), 'exit_code': snapshot.get('exitCode') if type(snapshot.get('exitCode')) is int else None},
            'completeness': {'complete': not issues, 'issues': sorted(set(issues)), 'scope': 'test results: one run, one shard, one attempt'},
            'counts': counts, 'timing': {'runner_elapsed_ms': (number(snapshot.get('durationSeconds')) or 0) * 1000,
                                       'suite_elapsed_ms': number((finished or {}).get('elapsed_ms')),
                                       'collector_elapsed_ms': number((finished or {}).get('elapsed_ms')),
                                       'runner_preparation_ms': prep_seconds * 1000 if prep_seconds is not None else None,
                                       'exunit_run_ms': exunit_ms['run'], 'exunit_load_ms': exunit_ms['load'], 'exunit_async_ms': exunit_ms['async'],
                                       'startup_phases': startup,
                                       'compile': {'outcome': text(compile_info.get('outcome'), 60), 'file_count': number(compile_info.get('fileCount')), 'seconds': number(compile_info.get('seconds'))},
                                       'test_work_ms': sum(t['total_time_ms'] or 0 for t in executed),
                                       'phases_seconds': phases},
            'domains': [{'domain': key, **value} for key, value in sorted(groups.items(), key=lambda x: -x[1]['test_work_ms'])],
            'tests': sorted(tests, key=lambda t: -(t['total_time_ms'] or 0)),
            'candidates': candidates, 'resources': resources,
            'signals': signals_summary(tests, started, malformed_signals),
            'boot': boot_view(root, startup, boot_issues), 'fixtures': fixture_view(root, boot_issues),
            'tag_profile': tag_profile(tests), 'profile_issues': boot_issues,
            'operations': operations, 'operation_evidence': {'available': op_count is not None, 'complete': not operation_issues and type(op_count) is int and op_count == len(operations) and op_dropped == 0 and op_pending == 0, 'issues': sorted(set(operation_issues))},
            'limitations': ['Single-run observations, not historical regression or flakiness estimates.',
                            'Unobserved setup and SQL remain unknown. Inferred classifications need review.',
                            'Concurrent test work cannot be summed into elapsed time. No savings are claimed.',
                            'Execution receipts and test exit status remain the authority for passing.']}
    data['hotspots'] = rank_hotspots(data)
    data['ranking_basis'] = 'Observed per-selection cost, descending; overlapping scopes are not additive. Savings and frequency are unmeasured.'
    data['candidates'] = [{'test_id': row['evidence']['test_ids'][0] if row['evidence']['test_ids'] else None,
                           'file': row['verification']['test_files'][0] if row['verification']['test_files'] else '',
                           'name': row['title'], 'action': row['recommendation'],
                           'observed_time_ms': row['observed_cost_ms'], 'savings_ms': None,
                           'confidence': row['confidence']} for row in data['hotspots']]
    return data



REPORT_ASSETS = {
    'echarts.min.js': ('https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.min.js',
                       'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD'),
    'pico.min.css': ('https://cdn.jsdelivr.net/npm/@picocss/pico@2.1.1/css/pico.min.css',
                     'sha384-L1dWfspMTHU/ApYnFiMz2QID/PlP1xCW9visvBdbEkOLkSSWsP6ZJWhPw6apiXxU'),
}


def vendored_assets(directory):
    """Read pinned report assets for offline viewing; every byte must match its SRI pin."""
    assets = {}
    for name, (_, sri) in REPORT_ASSETS.items():
        path = directory / name
        if path.is_symlink() or not path.is_file():
            raise ValueError('vendor directory is missing ' + name)
        content = path.read_bytes()
        if 'sha384-' + base64.b64encode(hashlib.sha384(content).digest()).decode() != sri:
            raise ValueError(name + ' does not match its pinned integrity hash')
        assets[name] = content
    return assets


def render(data):
    # Pico CSS styles light/dark from the viewer's scheme; Apache ECharts draws charts. Both load from
    # pinned, SRI-checked CDN URLs with an assets/ fallback, and every table renders without them.
    encoded = json.dumps(data, ensure_ascii=True, allow_nan=False).replace('<', '\\u003c').replace('>', '\\u003e').replace('&', '\\u0026')
    page = '''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>FMix test analysis</title>
+<link rel="stylesheet" href="PICO_URL" integrity="PICO_SRI" crossorigin="anonymous" onerror="this.onerror=null;this.removeAttribute('integrity');this.href='assets/pico.min.css'">
+<script src="ECHARTS_URL" integrity="ECHARTS_SRI" crossorigin="anonymous" defer></script>
+<style>
+:root{color-scheme:light dark;--series-1:#2a78d6;--series-2:#eb6834;--series-3:#1baf7a;--series-4:#eda100;--series-5:#e87ba4;--series-6:#008300;--series-7:#6250d6;--neutral:#8b8f96;--grid:#e2e5e9}
+@media (prefers-color-scheme:dark){:root:where(:not([data-theme=light])){--series-1:#3987e5;--series-2:#d95926;--series-3:#199e70;--series-4:#c98500;--series-5:#d55181;--series-6:#008300;--series-7:#9085e9;--neutral:#7a7f88;--grid:#2d323a}}
+:root[data-theme=dark]{--series-1:#3987e5;--series-2:#d95926;--series-3:#199e70;--series-4:#c98500;--series-5:#d55181;--series-6:#008300;--series-7:#9085e9;--neutral:#7a7f88;--grid:#2d323a}
+html,body{background-color:var(--pico-background-color,Canvas);color:var(--pico-color,CanvasText)}
+main.container{max-width:1240px;padding-top:1rem}
+.topbar{display:flex;justify-content:space-between;align-items:flex-start;gap:1rem;flex-wrap:wrap}.topbar label{width:11rem;margin:0}
+.tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:1rem;margin-bottom:1rem}.tiles article{margin:0;padding:1rem}
+.tile-value{font-size:1.7rem;font-weight:650;line-height:1.15;font-variant-numeric:tabular-nums}
+.chart{width:100%;height:340px}.chart.tall{height:520px}
+.grid2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}.grid2>article{margin:0;min-width:0}@media(max-width:860px){.grid2{grid-template-columns:1fr}}
+article h3{font-size:1rem;margin-bottom:.5rem}
+.legend{display:flex;gap:1rem;flex-wrap:wrap;font-size:.85rem;margin:.25rem 0 .5rem}.legend i{display:inline-block;width:.75rem;height:.75rem;border-radius:3px;margin-right:.35rem;vertical-align:-1px}
+.tablewrap{max-height:520px;overflow:auto}.tablewrap thead th{position:sticky;top:0;background-color:var(--pico-background-color);z-index:1}
+td.num,th.num{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums}
+table{font-size:.85rem}code{font-size:.75rem;overflow-wrap:break-word}.tablewrap table{min-width:640px}.tablewrap td:first-child{min-width:16rem}
+.muted{color:var(--pico-muted-color)}.small{font-size:.85rem}
+.fallback{display:flex;align-items:center;justify-content:center;height:100%;text-align:center;color:var(--pico-muted-color);border:1px dashed var(--pico-muted-border-color);border-radius:var(--pico-border-radius);padding:1rem}
+.chip{display:inline-block;padding:.1rem .5rem;border:1px solid var(--pico-muted-border-color);border-radius:999px;font-size:.75rem;margin-right:.35rem}
+.controls{display:grid;grid-template-columns:2fr 1fr 1fr 1fr;gap:.75rem}@media(max-width:860px){.controls{grid-template-columns:1fr 1fr}}
+.hotspot header{display:flex;justify-content:space-between;gap:1rem;flex-wrap:wrap}.hotspot p{margin-bottom:.4rem}
+</style></head><body><main class="container">
+<div class="topbar"><hgroup><h1>FMix test analysis</h1><p id="identity" class="small"></p></hgroup><label>Theme<select id="theme" aria-label="Theme"><option value="">Match system</option><option value="light">Light</option><option value="dark">Dark</option></select></label></div>
+<p id="status"></p><div id="issues"></div>
+<section><h2>Where the time went</h2><p id="time-story"></p><div id="tiles" class="tiles"></div><article><div id="chart-time" class="chart" role="img" aria-label="Runner time by phase"></div><p class="muted small" id="time-note"></p></article><div class="grid2" id="boot-detail"><article><h3>Application start</h3><div id="chart-apps" class="chart" role="img" aria-label="Application start durations"></div></article><article><h3>Slowest supervisor children</h3><div id="chart-children" class="chart" role="img" aria-label="Supervisor child start durations"></div></article></div><p class="muted small" id="boot-note"></p></section><section><h2>Fixtures and tags</h2><div class="grid2"><article><h3>Most expensive fixture functions</h3><div id="chart-fixtures" class="chart" role="img" aria-label="Fixture function inclusive time"></div><p class="muted small" id="fixture-note"></p></article><article><h3>Test work by tag</h3><div id="chart-tags" class="chart" role="img" aria-label="Test work by tag"></div><p class="muted small">A test counts under every tag it carries, so bars overlap and must not be summed.</p></article></div></section>
+<section><h2>Hot spots by domain</h2><p class="muted small">Tile area is test time. Domain, then file, then test. Click a tile to drill in. Color shows the test level.</p><div class="legend" id="level-legend"></div><article><div id="chart-treemap" class="chart tall" role="img" aria-label="Test time treemap"></div></article>
+<div class="grid2"><article><h3>Test work by domain</h3><div class="legend level-legend"></div><div id="chart-domains" class="chart" role="img" aria-label="Test work by domain"></div></article><article><h3>Test time vs SQL queries</h3><div class="legend level-legend"></div><div id="chart-scatter" class="chart" role="img" aria-label="Test time versus SQL queries"></div><p class="muted small" id="scatter-note"></p></article></div></section>
+<section><h2>Per-test signals</h2><p id="signals-note" class="small"></p>
+<div class="grid2"><article><h3>SQL time by statement kind</h3><div class="legend" id="kind-legend"></div><div id="chart-sqlkind" class="chart" role="img" aria-label="SQL time by statement kind and domain"></div></article><article><h3>Top tables by SQL time</h3><div id="chart-sources" class="chart" role="img" aria-label="Top tables by SQL time"></div><p class="muted small">Summed from each test's ten heaviest sources, so these are lower bounds.</p></article>
+<article><h3>Log volume by file</h3><div id="chart-logs" class="chart" role="img" aria-label="Log events by file"></div></article><article><h3>Side effects by file</h3><div class="tablewrap" style="max-height:340px"><table class="striped"><thead><tr><th>File</th><th class="num">DDL</th><th class="num">Error logs</th><th class="num">Oban jobs</th><th class="num">HTTP</th><th class="num">Leaked procs</th></tr></thead><tbody id="effects"></tbody></table></div></article></div></section>
+<section><h2>Runner resources</h2><div class="grid2"><article><h3>CPU · runner process tree</h3><div id="chart-cpu" class="chart" role="img" aria-label="CPU percent over time"></div></article><article><h3>RSS · runner process tree</h3><div id="chart-rss" class="chart" role="img" aria-label="Resident memory over time"></div></article></div><p id="resource-note" class="muted small"></p></section>
+<section><h2>Ranked hotspots</h2><p id="ranking-note" class="muted small"></p><div id="hotspots"></div></section>
+<section><h2>Test explorer</h2><div class="controls"><input id="search" type="search" aria-label="Search tests" placeholder="Filter by name, file, domain or tag"><select id="outcome" aria-label="Outcome"><option value="">All outcomes</option><option>passed</option><option>failed</option><option>invalid</option><option>skipped</option><option>excluded</option><option>unknown</option></select><select id="level" aria-label="Level"><option value="">All levels</option><option>unit</option><option>integration</option><option value="other">other</option></select><select id="sort" aria-label="Sort metric"><option value="time">Test time</option><option value="setup">Observed setup</option><option value="sql">SQL count</option><option value="sqlms">SQL time</option><option value="logs">Log events</option><option value="reductions">Reductions (sync)</option></select></div><p id="shown" class="muted small"></p>
+<div class="tablewrap"><table class="striped"><thead><tr><th>Test / classification</th><th>Outcome</th><th class="num">Time ms</th><th class="num">Setup ms</th><th class="num">SQL</th><th class="num">SQL ms</th><th class="num">Logs</th><th class="num">Reductions</th></tr></thead><tbody id="tests"></tbody></table></div></section>
+<details><summary>Phase timing details</summary><pre id="phases" class="small"></pre></details>
+<section><h2>Interpretation limits</h2><ul id="limits" class="muted small"></ul></section>
+</main><script>
+const d=REPORT_DATA;const $=s=>document.querySelector(s);
+const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
+const n=v=>v==null?'unknown':Number(v).toLocaleString(undefined,{maximumFractionDigits:2});
+const ms=v=>v==null?'unknown':v>=1000?n(v/1000)+' s':n(v)+' ms';
+const bytes=v=>v==null?'unknown':v>=1073741824?n(v/1073741824)+' GiB':v>=1048576?n(v/1048576)+' MiB':n(v/1024)+' KiB';
+const css=k=>getComputedStyle(document.documentElement).getPropertyValue(k).trim();
+const LEVELS=[['unit','Unit','--series-1'],['integration','Integration','--series-2'],['other','Other / unknown','--neutral']];
+const KINDS=['select','insert','update','delete','ddl','transaction','other'];
+const levelOf=t=>t.classification.level==='unit'||t.classification.level==='integration'?t.classification.level:'other';
+const levelColor=l=>css(LEVELS.find(x=>x[0]===l)[2]);
+const ran=d.tests.filter(t=>t.status==='passed'||t.status==='failed');
+const sig=t=>t.signals||null;
+const fold=(rows,key,limit,label)=>{const s=[...rows].sort((a,b)=>b[key]-a[key]);if(s.length<=limit)return s;const rest=s.slice(limit-1);const o={name:label+' ('+rest.length+')',other:true};for(const r of rest)for(const k in r)if(typeof r[k]==='number')o[k]=(o[k]||0)+r[k];return s.slice(0,limit-1).concat([o])};
+// Text and tables render first; charts are a progressive layer.
+$('#identity').textContent=`Run ${d.run_id} · source ${d.source.commit_sha||'unknown'} · ${d.source.dirty===true?'dirty worktree':d.source.dirty===false?'clean worktree':'cleanliness unknown'} · Elixir ${d.source.elixir||'?'} / OTP ${d.source.otp||'?'}`;
+$('#status').innerHTML=`<span class="chip">Evidence ${d.completeness.complete?'complete':'INCOMPLETE'}</span><span class="chip">Runner ${esc(d.runner.state)} · exit ${esc(d.runner.exit_code)}</span><span class="chip">${esc(d.completeness.scope)}</span>`;
+$('#issues').innerHTML=(d.completeness.issues.length?'<article><strong>Evidence gaps</strong><ul>'+d.completeness.issues.map(i=>'<li>'+esc(i)+'</li>').join('')+'</ul></article>':'')+(d.operation_evidence.issues.length?'<p class="muted small">Operation evidence incomplete: '+d.operation_evidence.issues.map(esc).join('; ')+'</p>':'');
+const T=d.timing,helper=T.startup_phases?.test_helper_pre_exunit_total?.duration_ms??null;
+const share=T.runner_elapsed_ms&&T.exunit_run_ms!=null?100*T.exunit_run_ms/T.runner_elapsed_ms:null;
+const BOOT=d.boot&&d.boot.segments&&d.boot.segments.length?d.boot:null;
+$('#time-story').textContent=share==null?'ExUnit run time was not recorded, so the overhead share is unknown.':`Tests ran for ${ms(T.exunit_run_ms)} of ${ms(T.runner_elapsed_ms)} runner time (${n(share)}%). Everything else is preparation and startup.`;
+$('#tiles').innerHTML=[['Results',n(d.tests.length)],['Runner elapsed',ms(T.runner_elapsed_ms)],['ExUnit run',ms(T.exunit_run_ms)],['Cumulative test work',ms(T.test_work_ms)],['Overhead share',share==null?'unknown':n(100-share)+'%']].map(([k,v])=>`<article><div class="tile-value">${esc(v)}</div><small class="muted">${esc(k)}</small></article>`).join('');
+$('#time-note').textContent=BOOT?`Measured boot timeline across ${ms(BOOT.window_ms)} (${BOOT.runner_marks?'runner':'no runner'} and ${BOOT.vm_marks?'VM':'no VM'} marks). ${BOOT.note}`:'No boot timeline in this run, so mix test is one block: runner phases are whole seconds, and anything not measured inside the VM shows as unattributed.';
+$('#boot-note').textContent=BOOT&&BOOT.boot_profile?'Application and supervisor-child starts come from fmix test --profile-boot. Child times include their own children.':'Run fmix test --profile-boot to split application start into per-application and per-supervisor-child durations.';
+$('#fixture-note').textContent=d.fixtures?d.fixtures.note+(d.fixtures.truncated?' The function list was truncated.':''):'Run fmix test --profile-fixtures to record calls and inclusive time for fixture and helper functions.';
+if(d.profile_issues&&d.profile_issues.length)$('#issues').innerHTML+='<p class="muted small">Profile data issues: '+d.profile_issues.map(esc).join('; ')+'</p>';
+const legendHtml=items=>items.map(([label,color])=>`<span><i style="background:${color}"></i>${esc(label)}</span>`).join('');
+function legends(){document.querySelectorAll('#level-legend,.level-legend').forEach(el=>el.innerHTML=legendHtml(LEVELS.map(l=>[l[1],css(l[2])])));$('#kind-legend').innerHTML=legendHtml(KINDS.map((k,i)=>[k,css('--series-'+(i+1))]))}
+const S=d.signals||{observed_tests:{},tests_with_signals:0,executed_tests:ran.length};
+const obs=S.observed_tests||{};
+$('#signals-note').innerHTML=S.tests_with_signals?`Signals were recorded for ${n(S.tests_with_signals)} of ${n(S.executed_tests)} executed tests. Coverage by collector: SQL ${n(obs.sql_breakdown||0)} · logs ${n(obs.logs||0)} · Oban ${n(obs.oban||0)} · HTTP ${n(obs.http||0)} · BEAM (sync tests) ${n(obs.beam||0)}.${S.collector?.logger_level?' Logger level: '+esc(S.collector.logger_level)+'; lower-level events are not counted.':''} <span class="muted">${esc(S.note||'')}</span>`:'<strong>No per-test signals in this run.</strong> <span class="muted">The collector (Cdrcisco.Test.TestSignals) was not attached, so SQL kinds, logs, Oban, HTTP and BEAM data are unknown, not zero.</span>';
+const byFile={};for(const t of ran){const s=sig(t);if(!s)continue;const f=byFile[t.file]||(byFile[t.file]={file:t.file,ddl:0,error:0,logs:0,warning:0,oban:0,http:0,leak:0});f.ddl+=s.sql?.by_kind?.ddl?.count||0;if(s.logs){f.error+=s.logs.error;f.logs+=s.logs.total;f.warning+=s.logs.warning}f.oban+=s.oban?.jobs||0;f.http+=s.http?.requests||0;f.leak=Math.max(f.leak,s.beam?.process_delta||0)}
+const effects=Object.values(byFile).filter(f=>f.ddl||f.error||f.oban||f.http||f.leak>0).sort((a,b)=>b.ddl-a.ddl||b.http-a.http||b.error-a.error||b.oban-a.oban).slice(0,100);
+$('#effects').innerHTML=effects.length?effects.map(f=>`<tr><td><code>${esc(f.file)}</code></td><td class="num">${n(f.ddl)}</td><td class="num">${n(f.error)}</td><td class="num">${n(f.oban)}</td><td class="num">${n(f.http)}</td><td class="num">${n(f.leak)}</td></tr>`).join(''):`<tr><td colspan="6" class="muted">${S.tests_with_signals?'No DDL, error logs, Oban jobs, HTTP calls or leaked processes were observed.':'Not observed.'}</td></tr>`;
+$('#resource-note').textContent=[d.resources.note,...d.resources.issues].join(' ');
+$('#ranking-note').textContent=d.ranking_basis;
+$('#hotspots').innerHTML=d.hotspots.length?d.hotspots.slice(0,30).map(c=>`<article class="hotspot"><header><strong>#${c.rank} ${esc(c.title)}</strong><span><span class="chip">${esc(c.scope)}</span><span class="chip">${esc(c.confidence)}</span><span class="chip">${c.observed_cost_ms==null?'classification only':ms(c.observed_cost_ms)}</span></span></header><p><code>${esc(c.scope_key)}</code></p><p>${esc(c.recommendation)}</p><p class="muted small">Keep: ${esc(c.retain)} · ${n(c.evidence.affected_tests)} affected tests</p><details><summary class="small">Evidence and focused verification</summary><pre class="small">${esc(JSON.stringify({files:c.verification.test_files,evidence:Object.fromEntries(Object.entries(c.evidence).filter(([k])=>k!=='test_ids'))},null,2))}</pre></details></article>`).join(''):'<p class="muted">No hotspot crossed a ranking threshold.</p>';
+const metric={time:t=>t.total_time_ms,setup:t=>t.setup_time_ms,sql:t=>t.db_query_count,sqlms:t=>t.db_query_time_ms,logs:t=>sig(t)?.logs?.total,reductions:t=>sig(t)?.beam?.reductions};
+function draw(){const term=$('#search').value.toLowerCase(),state=$('#outcome').value,level=$('#level').value,key=metric[$('#sort').value];const rows=d.tests.filter(t=>(!state||t.status===state)&&(!level||levelOf(t)===level)&&JSON.stringify([t.name,t.file,t.classification,t.tags]).toLowerCase().includes(term)).sort((a,b)=>(key(b)??-1)-(key(a)??-1));$('#shown').textContent=`${n(rows.length)} matching results; showing the first ${Math.min(200,rows.length)}. Full results are in report.json.`;$('#tests').innerHTML=rows.slice(0,200).map(t=>{const s=sig(t);return `<tr><td>${esc(t.name)}<br><code>${esc(t.file)}:${esc(t.line)}</code><br><small class="muted">${esc(t.classification.domain)} · ${esc(t.classification.level)} (${esc(t.classification.level_basis)}) · ${esc(t.classification.purpose)}${Object.keys(t.tags).length?' · '+esc(Object.keys(t.tags).join(', ')):''}</small></td><td>${esc(t.status)}</td><td class="num">${n(t.total_time_ms)}</td><td class="num">${n(t.setup_time_ms)}</td><td class="num">${n(t.db_query_count)}</td><td class="num">${n(t.db_query_time_ms)}</td><td class="num">${s?.logs?n(s.logs.total):'unknown'}</td><td class="num">${s?.beam?n(s.beam.reductions):'n/a'}</td></tr>`}).join('')}
+['search','outcome','level','sort'].forEach(id=>document.getElementById(id).addEventListener('input',draw));draw();
+$('#phases').textContent=JSON.stringify({runner_seconds:T.phases_seconds,compile:T.compile,helper_startup:T.startup_phases,exunit_run_ms:T.exunit_run_ms,exunit_load_ms:T.exunit_load_ms,collector_elapsed_ms:T.collector_elapsed_ms},null,2);
+$('#limits').innerHTML=d.limitations.map(x=>'<li>'+esc(x)+'</li>').join('');
+// Chart layer: Apache ECharts, styled from Pico tokens and a validated categorical palette.
+const charts={};
+function base(){const ink=css('--pico-color')||'CanvasText',muted=css('--pico-muted-color')||'GrayText',grid=css('--grid'),surface=css('--pico-background-color')||'Canvas',card=css('--pico-card-background-color')||surface;return{ink,muted,grid,surface,axis:{axisLine:{lineStyle:{color:grid}},axisTick:{show:false},axisLabel:{color:muted,fontSize:11},splitLine:{lineStyle:{color:grid}},nameTextStyle:{color:muted}},tooltip:{backgroundColor:card,borderColor:grid,textStyle:{color:ink,fontSize:12},confine:true,extraCssText:'box-shadow:none'},text:{color:ink,fontFamily:'inherit'}}}
+const bar=(b,color)=>({color,borderRadius:[0,4,4,0],borderColor:b.surface,borderWidth:1});
+function specs(){const b=base(),o=[];
+let rows=[];if(BOOT){let off=0;for(const[k,v]of Object.entries(T.phases_seconds||{}))if(k!=='mix_test'&&v!=null){rows.push({name:'runner: '+k,v:v*1000,start:off,tests:false});off+=v*1000}for(const g of BOOT.segments)rows.push({name:g.name,v:g.duration_ms,start:g.start_ms+off,tests:g.tests});rows=rows.reverse()}else{for(const[k,v]of Object.entries(T.phases_seconds||{}))if(k!=='mix_test'&&v!=null)rows.push({name:'runner: '+k,v:v*1000,tests:false});const mt=T.phases_seconds?.mix_test!=null?T.phases_seconds.mix_test*1000:null;if(helper!=null)rows.push({name:'test helper startup',v:helper,tests:false});if(T.exunit_run_ms!=null)rows.push({name:'ExUnit run (the tests)',v:T.exunit_run_ms,tests:true});if(mt!=null){const rest=mt-(helper||0)-(T.exunit_run_ms||0);if(rest>0)rows.push({name:'mix test: unattributed',v:rest,tests:false})}rows.sort((a,b2)=>a.v-b2.v)}
+document.getElementById('chart-time').style.height=Math.max(240,rows.length*26+50)+'px';
+o.push(['chart-time',rows.length,{textStyle:b.text,grid:{left:8,right:70,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>p.seriesIndex===0?'':esc(p.name)+'<br>'+ms(p.value)+(BOOT?'<br>starts at +'+ms(rows[p.dataIndex].start):'')},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:rows.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink,fontSize:12}},series:[{type:'bar',stack:'t',silent:true,itemStyle:{color:'transparent'},data:rows.map(r=>BOOT?r.start:0)},{type:'bar',stack:'t',barMaxWidth:22,data:rows.map(r=>({value:r.v,itemStyle:bar(b,r.tests?css('--series-1'):css('--neutral'))})),label:{show:true,position:'right',color:b.muted,formatter:p=>ms(p.value)}}]}]);
+const domains={};for(const t of ran){const dm=t.classification.domain||'unknown';const files=domains[dm]||(domains[dm]={});(files[t.file]||(files[t.file]=[])).push(t)}
+const tree=Object.entries(domains).map(([dm,files])=>({name:dm,children:Object.entries(files).map(([file,tests])=>{const lv={};for(const t of tests)lv[levelOf(t)]=(lv[levelOf(t)]||0)+(t.total_time_ms||0);const dom=Object.entries(lv).sort((a,b2)=>b2[1]-a[1])[0][0];const leaves=tests.filter(t=>(t.total_time_ms||0)>0).sort((a,b2)=>b2.total_time_ms-a.total_time_ms);const shown=leaves.slice(0,40).map(t=>({name:t.name,value:t.total_time_ms,itemStyle:{color:levelColor(levelOf(t))},meta:t.file+':'+t.line+' · '+t.classification.level}));const rest=leaves.slice(40);if(rest.length)shown.push({name:rest.length+' more tests',value:rest.reduce((s,t)=>s+t.total_time_ms,0),itemStyle:{color:css('--neutral')}});return{name:file.split('/').slice(-2).join('/'),children:shown,itemStyle:{color:levelColor(dom)},meta:file+' · '+tests.length+' tests'}}).filter(f=>f.children.length)})).filter(x=>x.children.length);
+o.push(['chart-treemap',tree.length,{textStyle:b.text,tooltip:{...b.tooltip,formatter:p=>`<strong>${esc(p.name)}</strong><br>${ms(p.value)}${p.data.meta?'<br><span style="opacity:.75">'+esc(p.data.meta)+'</span>':''}`},series:[{type:'treemap',data:tree,roam:false,nodeClick:'zoomToNode',leafDepth:2,width:'100%',height:'88%',top:0,breadcrumb:{show:true,bottom:0,itemStyle:{color:b.surface,borderColor:b.grid,textStyle:{color:b.ink}}},label:{show:true,color:'#fff',fontSize:11,overflow:'truncate'},upperLabel:{show:true,height:22,color:b.ink},levels:[{itemStyle:{borderColor:b.surface,borderWidth:2,gapWidth:2},upperLabel:{show:false}},{itemStyle:{borderColor:b.grid,borderWidth:4,gapWidth:2},upperLabel:{show:true,backgroundColor:'transparent'}},{itemStyle:{borderColor:b.surface,borderWidth:1,gapWidth:1}},{itemStyle:{borderColor:b.surface,borderWidth:1,gapWidth:1}}]}]}]);
+const dl=Object.entries(domains).map(([dm,files])=>{const r={name:dm,unit:0,integration:0,other:0};for(const ts of Object.values(files))for(const t of ts)r[levelOf(t)]+=t.total_time_ms||0;r.total=r.unit+r.integration+r.other;return r});const dr=fold(dl,'total',15,'Other domains').reverse();
+o.push(['chart-domains',dr.length,{textStyle:b.text,grid:{left:8,right:16,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'axis',axisPointer:{type:'shadow'},valueFormatter:v=>ms(v)},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:dr.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:LEVELS.map(([k,label,c])=>({name:label,type:'bar',stack:'w',barMaxWidth:22,data:dr.map(r=>r[k]),itemStyle:{color:css(c),borderColor:b.surface,borderWidth:1}}))}]);
+const pts=ran.filter(t=>t.db_observed&&t.total_time_ms!=null);$('#scatter-note').textContent=`${n(pts.length)} of ${n(ran.length)} executed tests had SQL observed. Time uses a log scale.`;
+o.push(['chart-scatter',pts.length,{textStyle:b.text,grid:{left:8,right:16,top:16,bottom:28,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>`<strong>${esc(p.data.t.name)}</strong><br>${esc(p.data.t.file)}<br>${ms(p.data.t.total_time_ms)} · ${n(p.data.t.db_query_count)} queries`},xAxis:{type:'log',name:'test time (ms)',nameLocation:'middle',nameGap:24,...b.axis,min:v=>Math.max(0.01,v.min)},yAxis:{type:'value',name:'SQL queries',...b.axis},series:LEVELS.map(([k,label,c])=>({name:label,type:'scatter',symbolSize:8,large:pts.length>3000,itemStyle:{color:css(c),opacity:.75,borderColor:b.surface,borderWidth:1},data:pts.filter(t=>levelOf(t)===k).map(t=>({value:[Math.max(0.01,t.total_time_ms),t.db_query_count],t}))}))}]);
+const kd={};for(const t of ran){const s=sig(t);if(!s?.sql)continue;const dm=t.classification.domain;const r=kd[dm]||(kd[dm]={name:dm,total:0});for(const[k,v]of Object.entries(s.sql.by_kind)){r[k]=(r[k]||0)+v.time_ms;r.total+=v.time_ms}}const kr=fold(Object.values(kd),'total',12,'Other domains').reverse();
+o.push(['chart-sqlkind',kr.length,{textStyle:b.text,grid:{left:8,right:16,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'axis',axisPointer:{type:'shadow'},valueFormatter:v=>ms(v)},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:kr.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:KINDS.map((k,i)=>({name:k,type:'bar',stack:'k',barMaxWidth:22,data:kr.map(r=>r[k]||0),itemStyle:{color:css('--series-'+(i+1)),borderColor:b.surface,borderWidth:1}}))}]);
+const src={};for(const t of ran)for(const s of sig(t)?.sql?.top_sources||[]){const r=src[s.source]||(src[s.source]={name:s.source,time:0,count:0});r.time+=s.time_ms;r.count+=s.count}const sr=Object.values(src).sort((a,b2)=>b2.time-a.time).slice(0,15).reverse();
+o.push(['chart-sources',sr.length,{textStyle:b.text,grid:{left:8,right:60,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>`<strong>${esc(p.name)}</strong><br>${ms(p.value)} · ${n(sr[p.dataIndex].count)} queries`},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:sr.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:[{type:'bar',barMaxWidth:18,data:sr.map(r=>r.time),itemStyle:bar(b,css('--series-1')),label:{show:true,position:'right',color:b.muted,formatter:p=>ms(p.value)}}]}]);
+const lr=Object.values(byFile).filter(f=>f.logs>0).sort((a,b2)=>b2.logs-a.logs).slice(0,15).reverse();
+o.push(['chart-logs',lr.length,{textStyle:b.text,grid:{left:8,right:50,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>{const f=lr[p.dataIndex];return `<strong>${esc(f.file)}</strong><br>${n(f.logs)} events · ${n(f.error)} error · ${n(f.warning)} warning`}},xAxis:{type:'value',...b.axis},yAxis:{type:'category',data:lr.map(f=>f.file.split('/').slice(-1)[0]),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:[{type:'bar',barMaxWidth:18,data:lr.map(f=>f.logs),itemStyle:bar(b,css('--series-1')),label:{show:true,position:'right',color:b.muted}}]}]);
+const line=(key,fmt,title)=>{const s=d.resources.samples.filter(x=>x[key]!=null&&x.at);return[s.length,{textStyle:b.text,grid:{left:8,right:16,top:16,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'axis',axisPointer:{type:'line',lineStyle:{color:b.muted}},valueFormatter:fmt},xAxis:{type:'time',...b.axis,splitLine:{show:false}},yAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:fmt}},series:[{name:title,type:'line',showSymbol:false,lineStyle:{width:2,color:css('--series-1')},itemStyle:{color:css('--series-1')},areaStyle:{color:css('--series-1'),opacity:.12},data:s.map(x=>[x.at,x[key]])}]}]};
+o.push(['chart-cpu',...line('cpu_percent',v=>n(v)+'%','CPU')]);o.push(['chart-rss',...line('rss_bytes',bytes,'RSS')]);
+const hbar=(id,rows,label,val,fmt,tip)=>o.push([id,rows.length,{textStyle:b.text,grid:{left:8,right:70,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>tip(rows[rows.length-1-p.dataIndex])},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:fmt}},yAxis:{type:'category',data:rows.map(label).reverse(),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink,width:220,overflow:'truncate'}},series:[{type:'bar',barMaxWidth:18,data:rows.map(val).reverse(),itemStyle:bar(b,css('--series-1')),label:{show:true,position:'right',color:b.muted,formatter:p=>fmt(p.value)}}]}]);
+const apps=(d.boot?.apps||[]).slice(0,15),kids=(d.boot?.children||[]).slice(0,15);
+hbar('chart-apps',apps,r=>r.app,r=>r.duration_ms,ms,r=>`<strong>${esc(r.app)}</strong><br>${ms(r.duration_ms)}`);
+hbar('chart-children',kids,r=>r.child.split('.').slice(-2).join('.'),r=>r.duration_ms,ms,r=>`<strong>${esc(r.child)}</strong><br>under ${esc(r.supervisor)}<br>${ms(r.duration_ms)}`);
+const fx=(d.fixtures?.functions||[]).slice(0,15);
+hbar('chart-fixtures',fx,r=>r.mfa.split('.').slice(-2).join('.'),r=>r.inclusive_ms,ms,r=>`<strong>${esc(r.mfa)}</strong><br>${ms(r.inclusive_ms)} inclusive · ${n(r.calls)} calls · max ${ms(r.max_ms)}`);
+const tg=(d.tag_profile||[]).slice(0,15);
+hbar('chart-tags',tg,r=>r.tag,r=>r.work_ms,ms,r=>`<strong>${esc(r.tag)}</strong><br>${ms(r.work_ms)} · ${n(r.tests)} tests`);
+return o}
+function fallback(id,msg){const el=document.getElementById(id);if(charts[id]){charts[id].dispose();delete charts[id]}el.innerHTML=`<div class="fallback">${esc(msg)}</div>`}
+function render(){legends();if(!window.echarts){for(const id of ['chart-time','chart-treemap','chart-domains','chart-scatter','chart-sqlkind','chart-sources','chart-logs','chart-cpu','chart-rss','chart-apps','chart-children','chart-fixtures','chart-tags'])fallback(id,'Chart library unavailable (offline?). The tables on this page and report.json hold the same data.');return}for(const[id,count,opt]of specs()){if(!count){fallback(id,'Not observed in this run.');continue}const el=document.getElementById(id);if(!charts[id]){el.innerHTML='';charts[id]=echarts.init(el,null,{renderer:'canvas'})}charts[id].setOption(opt,true)}}
+function boot(){if(window.echarts)return render();const s=document.createElement('script');s.src='assets/echarts.min.js';s.onload=render;s.onerror=render;document.head.appendChild(s)}
+const theme=$('#theme');try{theme.value=localStorage.getItem('fmix-theme')||''}catch(e){}
+const applyTheme=()=>{if(theme.value)document.documentElement.dataset.theme=theme.value;else delete document.documentElement.dataset.theme;try{localStorage.setItem('fmix-theme',theme.value)}catch(e){}};applyTheme();legends();
+theme.addEventListener('input',()=>{applyTheme();render()});matchMedia('(prefers-color-scheme: dark)').addEventListener('change',()=>render());
+window.addEventListener('resize',()=>Object.values(charts).forEach(c=>c.resize()));
+if(document.readyState==='complete')boot();else window.addEventListener('load',boot);
+</script></body></html>'''
    page = page.replace('\n+', '\n')
    for placeholder, name in (('PICO', 'pico.min.css'), ('ECHARTS', 'echarts.min.js')):
        page = page.replace(placeholder + '_URL', REPORT_ASSETS[name][0]).replace(placeholder + '_SRI', REPORT_ASSETS[name][1])
    return page.replace('REPORT_DATA', encoded)


def main():
    parser = argparse.ArgumentParser(prog='fmix analyze', description='Generate an offline single-run test report. Does not run tests.')
    parser.add_argument('command', choices=['report', 'hotspots'])
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--run')
    group.add_argument('--run-dir', type=Path)
    parser.add_argument('--output', type=Path, help='New output directory; existing paths are never overwritten')
    parser.add_argument('--limit', type=int, default=20, help='Hotspot JSON result limit (1-100)')
    parser.add_argument('--vendor-dir', type=Path, help='Directory with pinned echarts.min.js and pico.min.css; verified copies go to <output>/assets for offline viewing')
    args = parser.parse_args()
    if not 1 <= args.limit <= 100:
        parser.error('--limit must be between 1 and 100')
    if args.command == 'report' and not args.output:
        parser.error('report requires --output')
    if args.command == 'hotspots' and args.output:
        parser.error('hotspots writes JSON to stdout; omit --output')
    if args.vendor_dir and args.command != 'report':
        parser.error('--vendor-dir applies only to report')
    if args.run and not re.fullmatch('[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}', args.run):
        parser.error('--run must be a UUID')
    root = args.run_dir or Path(os.environ.get('FMIX_HOME', str(Path.home() / '.ct-fmix'))) / 'telemetry/runs' / args.run
    if root.is_symlink():
        raise ValueError('run directory must not be a symlink')
    root = root.resolve(strict=True)
    if args.output and (args.output.exists() or args.output.is_symlink()):
        raise ValueError('output already exists; choose a new directory')
    assets = vendored_assets(args.vendor_dir) if args.vendor_dir else {}
    data = analyze(root)
    if args.command == 'hotspots':
        print(json.dumps({'schema': 'fmix-hotspots.v1', 'run_id': data['run_id'], 'source': data['source'],
                          'completeness': data['completeness'], 'operation_evidence': data['operation_evidence'],
                          'runner': data['runner'], 'counts': data['counts'], 'limitations': data['limitations'],
                          'ranking_basis': data['ranking_basis'], 'total_items': len(data['hotspots']),
                          'truncated': len(data['hotspots']) > args.limit, 'items': data['hotspots'][:args.limit]}, allow_nan=False))
        return 0 if data['completeness']['complete'] else 2
    args.output.mkdir(mode=0o700, parents=True, exist_ok=False)
    for name, content in [('report.json', json.dumps(data, indent=2, allow_nan=False) + '\n'), ('index.html', render(data))]:
        fd = os.open(args.output / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, 'w') as stream:
            stream.write(content)
    if assets:
        (args.output / 'assets').mkdir(mode=0o700)
        for name, content in assets.items():
            fd = os.open(args.output / 'assets' / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
            with os.fdopen(fd, 'wb') as stream:
                stream.write(content)
    print(json.dumps({'report': str(args.output / 'index.html'), 'results': len(data['tests']), 'complete': data['completeness']['complete']}))
    return 0 if data['completeness']['complete'] else 2

try:
    sys.exit(main())
except (OSError, ValueError, TypeError, KeyError) as error:
    print('fmix analyze: ' + str(error), file=sys.stderr)
    sys.exit(2)
FMIX_ANALYZE_PY
}

main() {
    if (( $# == 0 )); then
        fmix_usage
        return 0
    fi

    local cmd="$1"
    shift
    if [[ "$cmd" == "analyze" ]]; then
        cmd_analyze "$@"
        return $?
    fi
    # Automatic upgrade-on-invocation: cheap read-only TTL gate before any
    # command dispatch; the check/install runs detached and can never affect
    # this command's exit code, output contract, or artifacts.
    fmix_maybe_auto_upgrade "$cmd" "$@" || true
    if [[ "$cmd" == "timing" ]] && fmix_timing_help_requested "$@"; then
        cmd_timing "$@"
        return $?
    fi
    case "$cmd" in
        help|--help|-h)
            # focused help: fmix help <verb> | fmix <verb> --help
            if [[ $# -ge 1 && "$1" != "--json" ]]; then
                fmix_verb_help "$1"
                return 0
            fi
            fmix_usage
            return 0
            ;;
        version|--version)
            # `version --json` reports identity a caller can verify: the version
            # string alone cannot distinguish two different runners, which is
            # exactly how a 15k-line workspace copy and the published release
            # both claimed 2.5.0. Installers compare the digest, not the path,
            # because any version manager (mise, asdf, nvm, volta) legitimately
            # interposes a shim that no path comparison can see through.
            if [[ "${1:-}" == "--json" ]]; then
                local self_path self_sha
                self_path="$(fmix_realpath "${BASH_SOURCE[0]}" 2>/dev/null || printf '%s' "${BASH_SOURCE[0]}")"
                self_sha="$(fmix_hash_stdin < "$self_path" 2>/dev/null || printf '')"
                printf '{"version":"%s","runnerSha256":"%s","runnerPath":"%s"}\n' \
                    "$FMIX_VERSION" "$self_sha" "$self_path"
                return 0
            fi
            echo "fmix $FMIX_VERSION"
            return 0
            ;;
    esac

    case "$cmd" in
        test|coverage|task|format|setup|seed|cache|ensure|doctor|status|timing|gc|install|self-test)
            if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
                fmix_verb_help "$cmd"
                return 0
            fi
            ;;
        verify-push|hook|runner)
            if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
                fmix_verb_help "$cmd"
                return 0
            fi
            ;;
    esac
    if [[ "$cmd" == "gc" ]] && fmix_readonly_entrypoint gc "$@"; then
        if fmix_gc_artifact_retirement_requested "$@"; then
            cmd_gc_artifact_retirement "$@"
        else
            cmd_gc_artifact_audit "$@"
        fi
        return $?
    fi

    if [[ "$cmd" == "cache" && ( "${1:-}" == "import" || "${1:-}" == "export" ) ]]; then
        fmix_prepare_command_home || return 1
    elif [[ "$cmd" == "cache" ]]; then
        fmix_prepare_home_readonly || return 1
    elif [[ "$cmd" != "test" && "$cmd" != "coverage" && "$cmd" != "verify-push" && "$cmd" != "hook" && "$cmd" != "runner" ]]; then
        fmix_prepare_command_home || return 1
    fi

    case "$cmd" in
        test|coverage|task|format|setup|seed|cache|ensure|doctor|status|timing|gc|install|self-test)
            if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
                fmix_verb_help "$cmd"
                return 0
            fi
            ;;
        verify-push|hook|runner)
            if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
                fmix_verb_help "$cmd"
                return 0
            fi
            ;;
    esac

    case "$cmd" in
        test)    cmd_test "$@" ;;
        coverage) cmd_coverage "$@" ;;
        task)    cmd_task "$@" ;;
        format)  cmd_format "$@" ;;
        setup)   cmd_setup "$@" ;;
        seed)    cmd_seed "$@" ;;
        cache)   cmd_cache "$@" ;;
        ensure)  cmd_ensure "$@" ;;
        doctor)  cmd_doctor "$@" ;;
        status)  cmd_status "$@" ;;
        timing)  cmd_timing "$@" ;;
        gc)      cmd_gc "$@" ;;
        install) cmd_install "$@" ;;
        self-test) cmd_self_test "$@" ;;
        verify-push) cmd_verify_push "$@" ;;
        hook)    cmd_hook "$@" ;;
        runner)  cmd_runner "$@" ;;
        *)
            fmix_error "Unknown command: $cmd"
            fmix_error "Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, analyze, gc, install, self-test, verify-push, hook, runner, version, help"
            fmix_error "Run 'fmix --help' for the full manual or 'fmix help <command>' for focused usage."
            return 1
            ;;
    esac
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    : # Keep source-only test extraction valid when it removes the next line.
if [[ "${1:-}" == "--fmix-observability-worker" ]]; then
    if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" != "1" \
        || ! "${FMIX_RUN_ID:-}" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ \
        ]] || ! fmix_observability_validate_worker_capability; then
        fmix_error "Reserved worker mode requires a validated supervisor handoff."
        exit 2
    fi
    shift
    main "$@"
    exit $?
fi
if ! fmix_readonly_entrypoint "$@" && [[ "${FMIX_RUN_ID:-}" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then
    fmix_run_embedded_supervisor "$@"
    exit $?
fi
main "$@"
fi
