#!/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>] [--unit] -- <mix test args>
#   ./fmix coverage --worktree <path> [--session <id>] --base <git-ref> -- <test paths>
#   ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
#   ./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 self-test
#

set -uo pipefail

# ---------------------------------------------------------------------------
# Constants & config
# ---------------------------------------------------------------------------
FMIX_VERSION="2.7.1"
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}"
FMIX_DB_SCHEMA_EPOCH="1"
FMIX_STABLE_SEED_SCHEMA="1"
FMIX_STABLE_SEED_COMPAT_VERSION="v1"
FMIX_DEPENDENCY_ARTIFACT_SCHEMA="1"
FMIX_DEPENDENCY_LANE_VERSION="v1"
FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS="${FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS:-30}"
FMIX_MIGRATION_DELTA_LIMIT="${FMIX_MIGRATION_DELTA_LIMIT:-50}"
FMIX_COMPILE_HEARTBEAT="${FMIX_COMPILE_HEARTBEAT:-30}"
FMIX_COMPILE_TIMEOUT="${FMIX_COMPILE_TIMEOUT:-900}"
FMIX_SETUP_COMPILE_TIMEOUT="${FMIX_SETUP_COMPILE_TIMEOUT:-900}"
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 inherited file descriptors for the full protected
# operation. 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_LOCK_FD_MIN=210
FMIX_LOCK_FD_MAX=239
FMIX_HELD_LOCK_NAMES=()
FMIX_HELD_LOCK_FDS=()
FMIX_HELD_LOCK_TOKENS=()

# 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_HOST="${FMIX_NATS_HOST:-localhost}"
NATS_PORT="${FMIX_NATS_PORT:-4222}"

# 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 -c "import os, sys; print(os.path.realpath(sys.argv[1]))" "$1"
    elif command -v python3 >/dev/null 2>&1; then
        python3 -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_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" "$@"
}

if [[ "${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_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
    t0=$(date +%s)
    cp -R "$src" "$dst"
    t1=$(date +%s)
    echo "  [fmix] full copy completed in $(( t1 - t0 ))s (FMIX_COPY_MODE=full)" >&2
}

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_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

    actual_otp_major="$(
        cd "$worktree" &&
            erl -noshell -eval 'io:format("~s", [erlang:system_info(otp_release)]), halt().' 2>/dev/null
    )" || actual_otp_major=""
    otp_root="$(
        cd "$worktree" &&
            erl -noshell -eval 'io:format("~s", [code:root_dir()]), halt().' 2>/dev/null
    )" || otp_root=""
    actual_erts="$(
        cd "$worktree" &&
            erl -noshell -eval 'io:format("~s", [erlang:system_info(version)]), halt().' 2>/dev/null
    )" || actual_erts=""
    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 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
}

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_now() {
    date -u +%Y-%m-%dT%H:%M:%SZ
}

fmix_epoch() {
    date +%s
}

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_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)
            case "${FMIX_LAST_ARTIFACTS_OUTCOME:-}" in
                session_hit|adopt_stamps|adopt_compatible|ready|stable_seed|donor_clone)
                    cache_hot="yes"
                    ;;
            esac
            ;;
    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

    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_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]}"
    session_lock="session-$session_hash"
    if ! fmix_lock_acquire "$session_lock" 0 "$diagnostic_name" >/dev/null 2>&1; then
        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 "$session_lock" >/dev/null 2>&1 \
            || 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 "$session_lock" >/dev/null 2>&1 \
            || 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 )) && ! fmix_drop_db "$db_name"; then
        drop_rc=1
    fi
    fmix_lock_release "$session_lock" >/dev/null 2>&1 \
        || 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 "$session_lock" >/dev/null 2>&1 || true
                    continue
                fi
                session_db="ct_fmix_s_$session_hash"
                if fmix_db_exists "$session_db"; then
                    fmix_drop_db "$session_db" >/dev/null 2>&1 || true
                fi
                if fmix_guard_path "$session_root"; then
                    rm -rf "$session_root"
                    purged_count=$(( purged_count + 1 ))
                fi
                fmix_lock_release "$session_lock" >/dev/null 2>&1 || true
            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
}

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"

    if ! fmix_lock_acquire "$session_lock" "$FMIX_WORKTREE_LOCK_TIMEOUT" \
        "session activation"; then
        fmix_clear_active_session
        return 1
    fi
    if [[ -e "$session_root" || -L "$session_root" ]]; then
        session_root_preexisting=1
    fi
    if (( activation_rc == 0 )); 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 )) && ! fmix_purge_expired_sessions 1; then
        fmix_warn "Session housekeeping is degraded; activation will continue without destructive cleanup."
    fi
    if (( activation_rc == 0 )); 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

    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
        ln -s "$expected_priv" "$priv_link" || activation_rc=1
    fi

    if (( activation_rc == 0 )) && ! fmix_write_session_meta "$real"; then
        activation_rc=1
    fi
    if (( activation_rc != 0 && 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
    fmix_lock_release "$session_lock" >/dev/null 2>&1 \
        || fmix_warn "Session activation lease metadata could not be retired."
    if (( activation_rc != 0 )); then
        fmix_clear_active_session
        return 1
    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 [[ ! -f "$parent/mix.exs" ]] || ! grep -q 'app: :cdrcisco' "$parent/mix.exs" 2>/dev/null; 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 [[ ! -f "$parent/mix.exs" ]] || ! grep -q 'app: :cdrcisco' "$parent/mix.exs" 2>/dev/null; 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 (v4) = first 16 hex of sha256 over:
#   resolved BEAM ABI + dependency declarations/resolution + local dependency
#   source inputs + uname -sm.
# ---------------------------------------------------------------------------

fmix_compute_template_key() {
    # 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"
    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 'fmix-template-key-v4\n'
        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
    ) >"$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_dependency_artifact_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_touch_dependency_artifact_access() {
    local lane="${1:-}" exact="${2:-}" root access tmp
    [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
    root="$FMIX_HOME/dependency-artifact-access/$lane"
    access="$root/$exact"
    mkdir -p "$root" || return 1
    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_dependency_artifact_meta_matches() {
    local artifact="${1:-}" expected_lane="${2:-}" expected_exact="${3:-}"
    local py_bin
    (( $# == 3 )) || return 1
    py_bin="$(fmix_python_bin)"
    "$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)

required = {
    "schema", "lane", "dependency_fingerprint", "producer_sha",
    "source_clean", "manifest_sha256", "built_at",
}
if set(data) != required:
    raise SystemExit(1)
if data["schema"] != 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)
PY
}

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
    [[ -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_dependency_artifact_meta_matches "$artifact" "$lane" "$exact"
}

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" -perm -u+w -print -quit 2>/dev/null)" || return 1
        [[ -z "$writable" ]] || return 1
    fi
}

fmix_dependency_artifact_verify_full() {
    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_quarantine() {
    local artifact="${1:-}" reason="${2:-invalid dependency artifact}" destination
    [[ "$artifact" == "$FMIX_HOME/dependency-artifacts/v1/"* ]] || return 1
    [[ -e "$artifact" || -L "$artifact" ]] || return 0
    destination="$FMIX_HOME/quarantine/dependency-artifacts/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
    mkdir -p "$(dirname "$destination")" || return 1
    [[ ! -d "$artifact" || -L "$artifact" ]] || chmod u+w "$artifact" 2>/dev/null || return 1
    if mv "$artifact" "$destination"; then
        fmix_warn "Quarantined dependency 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_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

    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 release_rc=0

    (( $# == 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 1
    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_lock_release "$worktree_lock" >/dev/null 2>&1 \
                || fmix_error "Stable seed worktree lock release failed for '$base'."
            return 1
        }
    if [[ ! "$producer_sha" =~ ^[0-9a-f]{40}$ ]]; then
        fmix_lock_release "$worktree_lock" >/dev/null 2>&1 \
            || fmix_error "Stable seed worktree lock release failed for '$base'."
        return 1
    fi
    seed_lock="stable-seed-${base}-${producer_sha}"
    if ! fmix_lock_acquire \
        "$seed_lock" "$FMIX_LOCK_TIMEOUT" "stable seed for '$base'"; then
        fmix_lock_release "$worktree_lock" >/dev/null 2>&1 \
            || fmix_error "Stable seed worktree lock release failed for '$base'."
        return 1
    fi

    publish_rc=0
    _fmix_seed_publish_locked "$real" "$base" "$producer_sha" || publish_rc=$?
    fmix_lock_release "$seed_lock" >/dev/null 2>&1 || release_rc=1
    fmix_lock_release "$worktree_lock" >/dev/null 2>&1 || release_rc=1
    (( publish_rc == 0 )) || return "$publish_rc"
    if (( release_rc != 0 )); then
        fmix_error "Stable seed lock release failed for '$base'."
        return 1
    fi
    return 0
}

fmix_publish_dependency_artifact() {
    # 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.
    local worktree="${1:-}" expected_exact="${2:-}" real lane artifact parent tmp
    local deps_root build_root build_lib producer_sha source_clean source_status manifest_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_dir "$lane" "$expected_exact")" || return 1
    lock_name="dependency-artifact-${lane:0:16}-${expected_exact:0:16}"
    fmix_lock_acquire "$lock_name" "$FMIX_LOCK_TIMEOUT" \
        "exact dependency artifact" || return 1

    if fmix_dependency_artifact_verify_full "$artifact" "$lane" "$expected_exact"; then
        fmix_touch_dependency_artifact_access "$lane" "$expected_exact" \
            >/dev/null 2>&1 || true
        fmix_lock_release "$lock_name"
        return 0
    fi
    if [[ -e "$artifact" || -L "$artifact" ]]; then
        fmix_dependency_artifact_quarantine "$artifact" \
            "failed exact integrity verification" || {
            fmix_lock_release "$lock_name"
            return 1
        }
    fi

    deps_root="$(fmix_session_deps_root "$real")" || {
        fmix_lock_release "$lock_name"
        return 1
    }
    build_root="$(fmix_compile_build_root "$real")" || {
        fmix_lock_release "$lock_name"
        return 1
    }
    build_lib="$build_root/test/lib"
    if ! fmix_stable_seed_artifacts_are_safe \
        "$deps_root" "$build_lib" 1 "$real" "$build_root"; then
        fmix_lock_release "$lock_name"
        return 1
    fi
    producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
        || producer_sha=""
    [[ "$producer_sha" =~ ^[0-9a-f]{40}$ ]] || {
        fmix_lock_release "$lock_name"
        return 1
    }
    source_status="$(git -C "$real" status --porcelain --untracked-files=all 2>/dev/null)" \
        || {
            fmix_lock_release "$lock_name"
            return 1
        }
    if [[ -z "$source_status" ]]; then
        source_clean=true
    else
        source_clean=false
    fi

    parent="$(dirname "$artifact")"
    mkdir -p "$parent" || {
        fmix_lock_release "$lock_name"
        return 1
    }
    tmp="${artifact}.tmp-$$-${RANDOM}"
    if [[ -e "$tmp" || -L "$tmp" ]] || ! mkdir "$tmp"; then
        fmix_lock_release "$lock_name"
        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
        fmix_lock_release "$lock_name"
        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
            fmix_lock_release "$lock_name"
            return 1
        fi
    done
    manifest_sha="$(fmix_dependency_artifact_manifest_digest \
        "$tmp" "$tmp/manifest.tsv")" || {
        rm -rf "$tmp" 2>/dev/null || true
        fmix_lock_release "$lock_name"
        return 1
    }
    printf '%s\n' "$manifest_sha" >"$tmp/manifest.sha256" || {
        rm -rf "$tmp" 2>/dev/null || true
        fmix_lock_release "$lock_name"
        return 1
    }
    if ! cat >"$tmp/meta.json" <<EOF
{
  "schema": "$FMIX_DEPENDENCY_ARTIFACT_SCHEMA",
  "lane": "$lane",
  "dependency_fingerprint": "$expected_exact",
  "producer_sha": "$producer_sha",
  "source_clean": "$source_clean",
  "manifest_sha256": "$manifest_sha",
  "built_at": "$(fmix_now)"
}
EOF
    then
        rm -rf "$tmp" 2>/dev/null || true
        fmix_lock_release "$lock_name"
        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
        fmix_lock_release "$lock_name"
        return 1
    fi
    chmod -R a-w "$tmp" || {
        rm -rf "$tmp" 2>/dev/null || true
        fmix_lock_release "$lock_name"
        return 1
    }
    chmod u+w "$tmp" || {
        rm -rf "$tmp" 2>/dev/null || true
        fmix_lock_release "$lock_name"
        return 1
    }
    writable="$(find "$tmp" -mindepth 1 -perm -u+w -print -quit 2>/dev/null)" \
        || writable=invalid
    if [[ -n "$writable" || -e "$artifact" || -L "$artifact" ]] \
        || ! mv "$tmp" "$artifact"; then
        rm -rf "$tmp" 2>/dev/null || true
        fmix_lock_release "$lock_name"
        return 1
    fi
    chmod a-w "$artifact" || {
        fmix_dependency_artifact_quarantine "$artifact" \
            "could not seal exact publication" >/dev/null 2>&1 || true
        fmix_lock_release "$lock_name"
        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
        fmix_lock_release "$lock_name"
        return 1
    fi
    fmix_touch_dependency_artifact_access "$lane" "$expected_exact" \
        >/dev/null 2>&1 || true
    fmix_lock_release "$lock_name"
    fmix_info "Published immutable exact dependency artifact."
    return 0
}

fmix_find_dependency_reconciler() {
    local worktree="${1:-}" lane="${2:-}" exact="${3:-}" root head
    local candidate candidate_exact producer clean distance selected="" selected_distance=""
    (( $# == 3 )) || return 1
    root="$FMIX_HOME/dependency-artifacts/v1/$lane"
    [[ -d "$root" && ! -L "$root" ]] || return 1
    head="$(git -C "$worktree" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
        || return 1
    for candidate in "$root"/*; do
        [[ -d "$candidate" && ! -L "$candidate" ]] || continue
        candidate_exact="$(basename "$candidate")"
        [[ "$candidate_exact" =~ ^[0-9a-f]{64}$ && "$candidate_exact" != "$exact" ]] \
            || continue
        fmix_dependency_artifact_is_complete \
            "$candidate" "$lane" "$candidate_exact" || continue
        clean="$(fmix_read_state "$candidate/meta.json" source_clean)"
        [[ "$clean" == "true" ]] || continue
        producer="$(fmix_read_state "$candidate/meta.json" producer_sha)"
        [[ "$producer" =~ ^[0-9a-f]{40}$ ]] || continue
        git -C "$worktree" merge-base --is-ancestor "$producer" "$head" \
            >/dev/null 2>&1 || continue
        distance="$(git -C "$worktree" rev-list --count "$producer..$head" 2>/dev/null)" \
            || continue
        [[ "$distance" =~ ^[0-9]+$ ]] || continue
        if [[ -z "$selected_distance" || "$distance" -lt "$selected_distance" ]]; then
            selected="$candidate"
            selected_distance="$distance"
        fi
    done
    [[ -n "$selected" ]] || return 1
    printf '%s\n' "$selected"
}

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

fmix_install_dependency_artifact() {
    # 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 installed_deps=0 installed_lib=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
    [[ "$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="$FMIX_ACTIVE_SESSION_ROOT/.dependency-install-$$-${RANDOM}"
    retired="$stage/retired"
    mkdir -p "$stage/new-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-lib/$child_name"; then
            rm -rf "$stage" 2>/dev/null || true
            return 1
        fi
    done
    # 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-lib/cdrcisco"; then
            rm -rf "$stage" 2>/dev/null || true
            return 1
        fi
    fi
    chmod -R u+w "$stage/new-deps" "$stage/new-lib" || {
        rm -rf "$stage" 2>/dev/null || true
        return 1
    }

    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 )) \
        && mv "$stage/new-deps" "$deps_root"; then
        installed_deps=1
        if (( dependency_install_interrupted == 0 )) \
            && mv "$stage/new-lib" "$target_lib"; then
            installed_lib=1
            if [[ "$exact_mode" == "1" ]]; then
                if (( dependency_install_interrupted == 0 )) \
                    && fmix_write_dependency_stamp "$real" "$artifact_exact" \
                    && fmix_dependency_stamp_matches "$real" "$artifact_exact"; then
                    ok=1
                fi
            else
                if (( dependency_install_interrupted == 0 )) \
                    && [[ ! -e "$dep_stamp" && ! -e "$compile_stamp" ]]; then
                    ok=1
                fi
            fi
        fi
    fi

    if (( ok == 0 )); then
        (( installed_deps == 0 )) || rm -rf "$deps_root" 2>/dev/null || true
        (( installed_lib == 0 )) || rm -rf "$target_lib" 2>/dev/null || true
        (( had_deps == 0 )) || mv "$retired/deps" "$deps_root" 2>/dev/null || true
        (( had_lib == 0 )) || mv "$retired/lib" "$target_lib" 2>/dev/null || true
        rm -f "$dep_stamp" 2>/dev/null || true
        (( had_dep_stamp == 0 )) \
            || mv "$retired/dependency-stamp.json" "$dep_stamp" 2>/dev/null || true
        (( had_compile_stamp == 0 )) \
            || mv "$retired/compile-stamp.json" "$compile_stamp" 2>/dev/null || true
        rm -rf "$stage" 2>/dev/null || true
        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"
        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"
    return 0
}

fmix_prepare_dependency_artifacts() {
    local worktree="${1:-}" exact lane artifact reconciler reconciler_exact
    (( $# == 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_dependency_artifact_verify_full "$artifact" "$lane" "$exact"; then
            if fmix_install_dependency_artifact "$worktree" "$artifact" 1; then
                fmix_touch_dependency_artifact_access "$lane" "$exact" \
                    >/dev/null 2>&1 || true
                fmix_info "Exact dependency artifact hit — skipping dependency resolution and compilation."
                return 0
            fi
            fmix_warn "Exact dependency artifact could not be installed; rebuilding it."
        else
            fmix_dependency_artifact_quarantine "$artifact" \
                "consumer integrity verification failed" || return 1
        fi
    fi
    if reconciler="$(fmix_find_dependency_reconciler \
        "$worktree" "$lane" "$exact" 2>/dev/null)"; then
        reconciler_exact="$(basename "$reconciler")"
        if fmix_dependency_artifact_verify_full \
            "$reconciler" "$lane" "$reconciler_exact" \
            && fmix_install_dependency_artifact "$worktree" "$reconciler" 0; then
            fmix_touch_dependency_artifact_access "$lane" "$reconciler_exact" \
                >/dev/null 2>&1 || true
            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
        fi
        fmix_warn "Ancestor dependency seed was unusable; continuing with a cold dependency build."
    fi
    return 0
}

# ---------------------------------------------------------------------------
# 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"
    shift
    local path

    if git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
        local tmp_tracked tmp_diff tmp_staged
        tmp_tracked="$(mktemp)"
        tmp_diff="$(mktemp)"
        tmp_staged="$(mktemp)"

        git -C "$root" ls-files -s -- "$@" \
            | awk '$1 != "160000" { print $0 }' \
            | LC_ALL=C sort >"$tmp_tracked"

        git -C "$root" diff --binary -- "$@" >"$tmp_diff" 2>/dev/null
        git -C "$root" diff --cached --binary -- "$@" >"$tmp_staged" 2>/dev/null

        {
            cat "$tmp_tracked"
            if [[ -s "$tmp_diff" ]]; then
                printf 'unstaged-diff:%s\n' "$(fmix_hash_files "$tmp_diff" | awk '{print $1}')"
            fi
            if [[ -s "$tmp_staged" ]]; then
                printf 'staged-diff:%s\n' "$(fmix_hash_files "$tmp_staged" | awk '{print $1}')"
            fi
        }

        rm -f "$tmp_tracked" "$tmp_diff" "$tmp_staged"
    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() {
    local worktree="$1" template_key="$2" real state tmp
    [[ "$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
    if ! cat >"$tmp" <<EOF
{
  "schema": "fmix-artifacts-v1",
  "path": $(fmix_json_escape "$real"),
  "template_key": $(fmix_json_escape "$template_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 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 meta="$FMIX_HOME/templates/$key/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"
    mkdir -p "$dir"
    cat >"$meta" <<EOF
{
  "schema": "$FMIX_TEMPLATE_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"),
  "source_commit": $(fmix_json_escape "$source_commit")
}
EOF
}

fmix_template_access_file() {
    printf '%s/template-access/%s\n' "$FMIX_HOME" "$1"
}

fmix_update_template_last_used() {
    # 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
    [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
    access="$(fmix_template_access_file "$key")"
    mkdir -p "$(dirname "$access")" || return 1
    tmp="${access}.tmp-$$-${RANDOM}"
    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_allocate_fd() {
    local fd
    for (( fd = FMIX_LOCK_FD_MIN; fd <= FMIX_LOCK_FD_MAX; fd++ )); do
        if ! eval "true >&${fd}" 2>/dev/null; then
            printf '%s\n' "$fd"
            return 0
        fi
    done
    fmix_error "No FMix lock file descriptor is available (${FMIX_LOCK_FD_MIN}-${FMIX_LOCK_FD_MAX})."
    return 1
}

fmix_lock_close_fd() {
    local fd="$1"
    eval "exec ${fd}>&-"
}

fmix_lock_open_fd() {
    local fd="$1" path="$2"
    eval "exec ${fd}>>\"\$path\""
}

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

fmix_lock_kernel_try() {
    local fd="$1" timeout="$2" diagnostic_name="${3:-${lock_name:-lock}}" lock_name="${4:-${diagnostic_name:-lock}}" py_bin
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    "$py_bin" - "$fd" "$timeout" "$diagnostic_name" "$lock_name" "$FMIX_HOME" <<'PY'
import fcntl
import json
import os
import sys
import time
from pathlib import Path

fd = int(sys.argv[1])
timeout = int(sys.argv[2])
diag_name = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else "lock"
lock_name = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else diag_name
fmix_home = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else os.environ.get("FMIX_HOME", "")

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

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

while True:
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        raise SystemExit(0)
    except BlockingIOError:
        now = time.monotonic()
        if now >= deadline:
            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}' ({elapsed}s elapsed, timeout {timeout}s, holder PID: {holder_pid}, purpose: \"{purpose}\") ...\n")
            sys.stderr.flush()
            last_heartbeat = now
        time.sleep(0.05)
PY
}

fmix_lock_acquire() {
    local lock_name="${1:-}" timeout="${2:-$FMIX_LOCK_TIMEOUT}"
    local diagnostic_name="${3:-${1:-}}" lock_dir kernel_file deadline
    local fd token owner_start holder_pid holder_start recorded_start
    local lock_mtime lock_age grace printed_wait=0 index py_bin

    [[ "$lock_name" =~ ^[A-Za-z0-9._-]+$ ]] || {
        fmix_error "Invalid FMix lock name: '${lock_name:-empty}'."
        return 1
    }
    if index="$(fmix_lock_find_index "$lock_name")"; then
        fmix_error "Nested acquisition of FMix lock '$diagnostic_name' is not supported (fd=${FMIX_HELD_LOCK_FDS[$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"
    mkdir -p "$FMIX_HOME/locks" "$FMIX_HOME/lock-kernel" "$FMIX_HOME/lock-metadata" || return 1

    while true; do
        fd="$(fmix_lock_allocate_fd)" || return 1
        fmix_lock_open_fd "$fd" "$kernel_file" || return 1
        local remaining=$(( deadline - $(fmix_epoch) ))
        (( remaining >= 0 )) || remaining=0
        if ! fmix_lock_kernel_try "$fd" "$remaining" "$diagnostic_name" "$lock_name"; then
            fmix_lock_close_fd "$fd"
            fmix_error "Timed out waiting for kernel lock '$diagnostic_name' after ${timeout}s."
            fmix_error "Inspect with: fmix status"
            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_close_fd "$fd"
                            return 1
                        }
                else
                    fmix_lock_close_fd "$fd"
                    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_close_fd "$fd"
                        return 1
                    }
            else
                if (( printed_wait == 0 )); then
                    fmix_info "Waiting for mixed-version lock '$diagnostic_name' (pid=$holder_pid) …"
                    printed_wait=1
                fi
                fmix_lock_close_fd "$fd"
                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_close_fd "$fd"
            fmix_error "Lock metadata path is not a directory: $lock_dir"
            return 1
        fi

        if ! mkdir "$lock_dir" 2>/dev/null; then
            fmix_lock_close_fd "$fd"
            if (( $(fmix_epoch) >= deadline )); then
                fmix_error "Timed out publishing lock metadata for '$diagnostic_name'."
                return 1
            fi
            sleep 0.05
            continue
        fi

        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
session=${FMIX_ACTIVE_SESSION_HASH:-none}
command=${FMIX_INTERNAL_RUN_MODE:-${1:-fmix}}
EOF
        then
            fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
                "owner publication failed" >/dev/null 2>&1 || true
            fmix_lock_close_fd "$fd"
            fmix_error "Could not publish ownership for lock '$diagnostic_name'."
            return 1
        fi

        # Publish structured lock-metadata
        cat >"$FMIX_HOME/lock-metadata/${lock_name}.json" 2>/dev/null <<EOF
{
  "lock_name": $(fmix_json_escape "$lock_name"),
  "pid": $$,
  "start_time": $(fmix_json_escape "$(fmix_now)"),
  "purpose": $(fmix_json_escape "$diagnostic_name"),
  "worktree": $(fmix_json_escape "${FMIX_ACTIVE_WORKTREE:-}")
}
EOF
        true

        FMIX_HELD_LOCK_NAMES+=("$lock_name")
        FMIX_HELD_LOCK_FDS+=("$fd")
        FMIX_HELD_LOCK_TOKENS+=("$token")
        return 0
    done
}

fmix_lock_release() {
    local lock_name="${1:-}" index fd token lock_dir recorded_token destination
    [[ -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
    }
    fd="${FMIX_HELD_LOCK_FDS[$index]}"
    token="${FMIX_HELD_LOCK_TOKENS[$index]}"
    lock_dir="$FMIX_HOME/locks/$lock_name"
    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_lock_close_fd "$fd"
        FMIX_HELD_LOCK_NAMES[$index]=""
        FMIX_HELD_LOCK_FDS[$index]=""
        FMIX_HELD_LOCK_TOKENS[$index]=""
        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_lock_close_fd "$fd"
        FMIX_HELD_LOCK_NAMES[$index]=""
        FMIX_HELD_LOCK_FDS[$index]=""
        FMIX_HELD_LOCK_TOKENS[$index]=""
        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
    fmix_lock_close_fd "$fd"
    FMIX_HELD_LOCK_NAMES[$index]=""
    FMIX_HELD_LOCK_FDS[$index]=""
    FMIX_HELD_LOCK_TOKENS[$index]=""
    return 0
}

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"

    # 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
            git -C "$top_repo" submodule update --init --recursive >&2 || true
        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_find_worktree() {
    local path="$1"
    local search_from

    if [[ "$path" == "auto" ]]; then
        search_from="$(pwd)"
        # Walk up looking for mix.exs with app: :cdrcisco
        local dir="$search_from"
        while true; do
            if [[ -f "$dir/mix.exs" ]] && grep -q 'app: :cdrcisco' "$dir/mix.exs" 2>/dev/null; then
                fmix_ensure_worktree_submodules "$dir"
                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
            fmix_ensure_worktree_submodules "$search_from/cisco-cdr"
            if [[ -f "$search_from/cisco-cdr/mix.exs" ]] && grep -q 'app: :cdrcisco' "$search_from/cisco-cdr/mix.exs" 2>/dev/null; then
                printf '%s\n' "$search_from/cisco-cdr"
                return 0
            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

        local resolved_dir="$path"
        if [[ ! -f "$resolved_dir/mix.exs" && -d "$resolved_dir/cisco-cdr" ]]; then
            resolved_dir="$resolved_dir/cisco-cdr"
        fi

        fmix_ensure_worktree_submodules "$resolved_dir"

        if [[ ! -f "$resolved_dir/mix.exs" ]] || ! grep -q 'app: :cdrcisco' "$resolved_dir/mix.exs" 2>/dev/null; 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 "$@"
}

# ---------------------------------------------------------------------------
# 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
            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 TCP check (warn only — tests stub NATS)
    if ! nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
        fmix_warn "NATS not reachable at $NATS_HOST:$NATS_PORT."
        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_dir() {
    printf '%s/templates/%s\n' "$FMIX_HOME" "$1"
}

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_template_make_readonly() {
    local root="$1" writable
    [[ "$root" == "$FMIX_HOME/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 -perm -u+w -print -quit 2>/dev/null)" \
        || return 1
    [[ -z "$writable" ]]
}

fmix_template_quarantine() {
    local path="$1" reason="$2" destination
    [[ "$path" == "$FMIX_HOME/templates/"* ]] || return 1
    [[ -e "$path" || -L "$path" ]] || return 0
    destination="$FMIX_HOME/quarantine/templates/$(basename "$path").$(fmix_epoch).$$.${RANDOM}"
    mkdir -p "$(dirname "$destination")" || return 1
    [[ ! -d "$path" || -L "$path" ]] || chmod u+w "$path" 2>/dev/null || return 1
    if mv "$path" "$destination"; then
        fmix_warn "Quarantined template state ($reason): $destination"
        return 0
    fi
    return 1
}

fmix_template_is_complete() {
    local key="$1" tdir recorded_key recorded_schema manifest_sha recorded_sha
    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"
    [[ "$recorded_schema" == "$FMIX_TEMPLATE_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 -perm -u+w -print -quit 2>/dev/null)" \
        || return 1
    [[ -z "$writable" ]]
}

fmix_template_verify_full() {
    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" -perm -u+w -print -quit 2>/dev/null)" || return 1
    [[ -z "$writable" ]]
}

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_lock_release "$lock_name" 2>/dev/null || 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_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
    tdir="$(fmix_template_dir "$key")"
    tmp_dir="$FMIX_HOME/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" "$FMIX_HOME/templates"

    # 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.
    if ! fmix_prepare_dependency_artifacts "$worktree"; then
        fmix_error "Dependency artifact preparation failed closed."
        return 1
    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 1

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

    fmix_info "Building template $key …"
    mkdir "$tmp_dir" || {
        fmix_lock_release "$lock_name"
        return 1
    }
    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
            fmix_error "Session compile failed. See log: $log_file"
            fmix_surface_log_tail "$log_file" 15
            fmix_template_quarantine "$tmp_dir" "failed producer compile" >/dev/null 2>&1 || true
            fmix_lock_release "$lock_name"
            return 1
        fi
        dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" || {
            fmix_template_quarantine "$tmp_dir" "dependency fingerprint failed" >/dev/null 2>&1 || true
            fmix_lock_release "$lock_name"
            return 1
        }
        compile_fingerprint="$(fmix_compute_compile_fingerprint "$worktree")" || {
            fmix_template_quarantine "$tmp_dir" "compile fingerprint failed" >/dev/null 2>&1 || true
            fmix_lock_release "$lock_name"
            return 1
        }
        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_lock_release "$lock_name"
            return 1
        fi
    fi


    if ! fmix_publish_dependency_artifact \
        "$worktree" "$dependency_fingerprint"; then
        fmix_warn "Exact dependency artifact publication failed; the full template remains authoritative."
    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_lock_release "$lock_name"
        return 1
    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_lock_release "$lock_name"
        return 1
    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_lock_release "$lock_name"
        return 1
    }
    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_lock_release "$lock_name"
        return 1
    }
    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_lock_release "$lock_name"
        return 1
    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_lock_release "$lock_name"
        return 1
    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_lock_release "$lock_name"
        return 1
    }
    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_lock_release "$lock_name"
        return 1
    }

    fmix_info "Template $key ready. Build log: $log_file"
    FMIX_TEMPLATE_BUILT_FROM_ACTIVE_SESSION=1
    fmix_lock_release "$lock_name"
    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"

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

    fmix_build_template "$worktree" "$key" || return 1
    fmix_update_template_last_used "$key"
    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
    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
from pathlib import Path

home = Path(os.environ["FMIX_HOME_FOR_DONOR"])
wt = os.environ["DONOR_WORKTREE"]
key = os.environ["DONOR_TEMPLATE_KEY"]
exclude = os.environ["DONOR_EXCLUDE"]
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) == exclude:
        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
    # If cross-worktree, verify clean dirty_hash if schema_version 2
    if session_wt != wt:
        try:
            stamp_d = json.loads(stamp.read_text(encoding="utf-8"))
            if stamp_d.get("schema_version") == 2:
                if stamp_d.get("dirty_hash", "clean") != "clean":
                    continue
        except Exception:
            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_clone_donor_to_session() {
    local worktree="$1" donor="$2" deps_root build_root retired retired_used=0 real py_bin
    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
    [[ "$deps_root" == "$FMIX_ACTIVE_SESSION_ROOT/deps" \
        && "$build_root" == "$FMIX_ACTIVE_SESSION_ROOT/_build" ]] || 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)"

    # Lock-Then-Revalidate (LOCK_SH): acquire shared lock on donor session
    local donor_fd
    donor_fd="$(fmix_lock_allocate_fd)" || return 1
    if [[ -f "$donor/meta.json" ]]; then
        eval "exec ${donor_fd}<\"$donor/meta.json\""
    else
        fmix_lock_close_fd "$donor_fd"
        return 1
    fi

    if ! "$py_bin" - "$donor_fd" <<'PY' 2>/dev/null
import fcntl, sys
fd = int(sys.argv[1])
try:
    fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
    raise SystemExit(0)
except Exception:
    raise SystemExit(1)
PY
    then
        fmix_lock_close_fd "$donor_fd"
        fmix_warn "Could not acquire shared lock on donor session $donor."
        return 1
    fi

    # Revalidate donor artifacts under active LOCK_SH
    if [[ ! -d "$donor/deps" || ! -d "$donor/_build" || ! -f "$donor/compile-stamp.json" ]]; then
        fmix_lock_close_fd "$donor_fd"
        fmix_warn "Donor session $donor missing required artifacts during revalidation."
        return 1
    fi

    retired="$FMIX_ACTIVE_SESSION_ROOT/retired/$(date +%Y%m%dT%H%M%S)-$$-${RANDOM}"
    if [[ -e "$deps_root" || -L "$deps_root" \
        || -e "$build_root" || -L "$build_root" ]]; then
        mkdir -p "$retired" || { fmix_lock_close_fd "$donor_fd"; return 1; }
        retired_used=1
        [[ -e "$deps_root" || -L "$deps_root" ]] && mv "$deps_root" "$retired/deps"
        [[ -e "$build_root" || -L "$build_root" ]] && mv "$build_root" "$retired/_build"
    fi

    if ! fmix_cow_clone "$donor/deps" "$deps_root"; then
        fmix_lock_close_fd "$donor_fd"
        return 1
    fi
    if ! fmix_cow_clone "$donor/_build" "$build_root"; then
        mkdir -p "$retired" || true
        mv "$deps_root" "$retired/failed-deps" 2>/dev/null || true
        fmix_lock_close_fd "$donor_fd"
        return 1
    fi
    chmod -R u+w "$deps_root" "$build_root" || {
        fmix_error "Could not make donor clone writable."
        fmix_lock_close_fd "$donor_fd"
        return 1
    }

    # Import proven stamps so fmix_ensure_compile can stamp-hit when content matches.
    local f
    for f in dependency-stamp.json compile-stamp.json; do
        if [[ -f "$donor/$f" ]]; then
            cp -f "$donor/$f" "$FMIX_ACTIVE_SESSION_ROOT/$f" || true
        fi
    done

    # Rebind path and build_root in cloned stamps to target session's bound realpath
    "$py_bin" - "$FMIX_ACTIVE_SESSION_ROOT" "$real" "$build_root" <<'PY' 2>/dev/null
import json, sys
from pathlib import Path
sroot = Path(sys.argv[1])
r_path = sys.argv[2]
b_root = sys.argv[3]
for name in ("compile-stamp.json", "dependency-stamp.json"):
    p = sroot / name
    if p.is_file():
        try:
            d = json.loads(p.read_text(encoding="utf-8"))
            d["path"] = r_path
            d["build_root"] = b_root
            p.write_text(json.dumps(d, indent=2) + "\n", encoding="utf-8")
        except Exception:
            pass
PY
    true

    # Release LOCK_SH on donor
    fmix_lock_close_fd "$donor_fd"

    # Post-clone manifest synchronization: touch compile manifests to prevent full DAG recompiles
    find "$build_root" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true

    # Sanitize CMake / NIF artifacts
    find "$deps_root" -type f -name 'CMakeCache.txt' -delete 2>/dev/null || true
    find "$deps_root" -type d -name 'c_build' -exec rm -rf {} + 2>/dev/null || true
    find "$deps_root" -type d -name 'CMakeFiles' -exec rm -rf {} + 2>/dev/null || true

    # NIF path-drift heal after CoW into a new session path.
    fmix_check_known_nif_caches "$worktree" 2>/dev/null || true

    if (( retired_used == 1 )); then
        if fmix_guard_path "$retired" && rm -rf "$retired"; then
            rmdir "$(dirname "$retired")" 2>/dev/null || true
        else
            fmix_warn "Donor clone succeeded, but retired artifacts remain: $retired"
        fi
    fi
    fmix_info "Warm donor cloned into session."
    return 0
}

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

fmix_clone_template_to_worktree() {
    local worktree="$1" key="$2" tdir deps_root build_root retired
    local dependency_fingerprint retired_used=0
    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
    }
    fmix_template_is_complete "$key" || {
        fmix_error "Refusing to clone unverified template $key."
        return 1
    }

    fmix_info "Cloning immutable template into session overlay …"
    retired="$FMIX_ACTIVE_SESSION_ROOT/retired/$(date +%Y%m%dT%H%M%S)-$$-${RANDOM}"
    if [[ -e "$deps_root" || -L "$deps_root" \
        || -e "$build_root" || -L "$build_root" ]]; then
        mkdir -p "$retired" || return 1
        retired_used=1
        if [[ -e "$deps_root" || -L "$deps_root" ]]; then
            mv "$deps_root" "$retired/deps" || return 1
        fi
        if [[ -e "$build_root" || -L "$build_root" ]]; then
            mv "$build_root" "$retired/_build" || return 1
        fi
        fmix_info "Prior session artifacts held for transactional replacement."
    fi

    if ! fmix_cow_clone "$tdir/deps" "$deps_root"; then
        return 1
    fi
    if ! fmix_cow_clone "$tdir/_build" "$build_root"; then
        mkdir -p "$retired" || true
        mv "$deps_root" "$retired/failed-deps" 2>/dev/null || true
        return 1
    fi
    chmod -R u+w "$deps_root" "$build_root" || {
        fmix_error "Could not make session clone writable."
        return 1
    }

    # Post-clone manifest synchronization: touch compile manifests to prevent full DAG recompiles
    find "$build_root" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true

    dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
        || return 1
    fmix_write_dependency_stamp "$worktree" "$dependency_fingerprint" || return 1
    if (( retired_used == 1 )); then
        if fmix_guard_path "$retired" && rm -rf "$retired"; then
            rmdir "$(dirname "$retired")" 2>/dev/null || true
        else
            fmix_warn "Session replacement succeeded, but retired artifacts remain: $retired"
        fi
    fi
    fmix_info "Template cloned into session; dependency provenance established."
    return 0
}

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

fmix_ensure_artifacts() {
    local worktree="$1" template_key="$2" allow_template_build="${3:-0}"
    local state_file artifact_state_file
    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

    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
            [[ -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
        else
            fmix_info "Template key mismatch (recorded=$recorded_key, current=$template_key)."
            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
            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
        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_LAST_ARTIFACTS_OUTCOME="missing_template"
        return 1
    fi
    # Prefer a warm peer session for the same worktree+template over a cold
    # template clone (avoids ~4700-file recompile when isolate/new session).
    local donor=""
    if donor="$(fmix_find_warm_donor_session "$worktree" "$template_key")"; then
        if fmix_clone_donor_to_session "$worktree" "$donor"; then
            fmix_write_artifact_state "$worktree" "$template_key" || return 1
            FMIX_LAST_ARTIFACTS_OUTCOME="donor_clone"
            return 0
        fi
        fmix_warn "Warm donor clone failed; falling back to immutable template."
    fi

    FMIX_TEMPLATE_BUILT_FROM_ACTIVE_SESSION=0
    fmix_ensure_template "$worktree" "$template_key" || return 1
    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 1
    fmix_write_artifact_state "$worktree" "$template_key" || return 1
    FMIX_LAST_ARTIFACTS_OUTCOME="template_clone"
    return 0
}

# ---------------------------------------------------------------------------
# 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_db() {
    local db_name="$1"
    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 1
    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
    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 DATABASE IF EXISTS \"${db_name}\"" 2>&1)"
    rc=$?
    if (( rc != 0 )); then
        printf '%s\n' "$out" | tail -8 >&2
        fmix_error "DROP DATABASE $db_name failed or exceeded ${timeout}s."
        [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
        return 1
    fi
    [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
    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 1
    fi
    fmix_wait_for_db_create_admission "CREATE DATABASE $db_name" || {
        [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
        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."
        [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
        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."
        [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
        return 1
    fi
    [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
    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 1
    if fmix_snapshot_ready "$snap"; then fmix_lock_release "$lock"; 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"
    fi

    fmix_info "Building reusable snapshot template $snap from structure.sql (explicit maintenance, hard-capped) …"
    if ! fmix_create_database "$snap"; then
        fmix_lock_release "$lock"
        fmix_error "Failed to create snapshot template $snap."
        return 1
    fi
    if ! fmix_load_structure "$worktree" "$snap"; then
        fmix_drop_db "$snap"
        fmix_lock_release "$lock"
        return 1
    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"
        fmix_lock_release "$lock"
        return 1
    fi
    fmix_lock_release "$lock"
    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
    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 1

    if fmix_snapshot_ready "$target"; then
        if ! fmix_base_record_ready "$key"; then
            fmix_info "Hot base $target exists; publishing its missing metadata index."
            fmix_write_base_record "$worktree" "$target" "$key" >/dev/null || {
                fmix_lock_release "$lock"
                return 1
            }
        fi
        fmix_lock_release "$lock"
        printf '%s\n' "$target"
        return 0
    fi

    if fmix_db_exists "$target"; then
        fmix_warn "Removing incomplete hot base $target before a clean publication."
        fmix_drop_db "$target" || { fmix_lock_release "$lock"; return 1; }
    fi

    fmix_info "Publishing hot DB base $target from current scratch $db_name …"
    fmix_create_database "$target" "$db_name" scratch-publish || {
        fmix_lock_release "$lock"
        return 1
    }
    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"
        fmix_lock_release "$lock"
        return 1
    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_lock_release "$lock"
        return 1
    }
    fmix_lock_release "$lock"
    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 content-indexed hot base
    # exists either — i.e. genuinely no cached 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".
    local worktree="$1" db_name="$2" 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 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 1
        return 0
    fi

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

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

    if fmix_db_exists "$db_name"; then
        fmix_drop_db "$db_name" || { fmix_lock_release "$lock"; return 1; }
    fi
    if ! fmix_create_database "$db_name"; then
        fmix_lock_release "$lock"
        return 1
    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
        fmix_error "Full from-zero migration failed on $db_name."
        fmix_drop_db "$db_name"
        fmix_lock_release "$lock"
        return 1
    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"
        fmix_lock_release "$lock"
        return 1
    fi

    fmix_info "Publishing hot DB base $target from freshly from-zero-migrated $db_name …"
    if fmix_db_exists "$target"; then
        fmix_warn "Removing incomplete hot base $target before a clean publication."
        fmix_drop_db "$target" || { fmix_lock_release "$lock"; return 1; }
    fi
    if ! fmix_create_database "$target" "$db_name" scratch-publish; then
        fmix_error "Could not publish $target from the from-zero-migrated $db_name; the scratch DB itself remains usable."
        fmix_lock_release "$lock"
        return 0
    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"
        fmix_lock_release "$lock"
        return 0
    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_lock_release "$lock"
        return 0
    }
    fmix_lock_release "$lock"
    return 0
}

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 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
    local t0 t1 snap
    fmix_guard_db_name "$db_name" || return 1
    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=""

    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 )); 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 [[ "$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_drop_db "$db_name" || return 1
    fi

    fmix_info "Selecting one content-indexed DB base for $db_name …"
    t0="$(fmix_epoch)"
    selection="$(fmix_select_indexed_base "$worktree")" || selection=""
    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 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
        if [[ "$force_from_zero" != "1" ]] && snap="$(fmix_ensure_snapshot_template "$worktree")"; then
            fmix_warn "No indexed hot base exists; entering explicit, hard-capped cold maintenance."
            fmix_create_database "$db_name" "$snap" || return 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" || return 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"
        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")"
    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" \
            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_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 worktree="$1" db_name="$2" state_file="$3"
    fmix_prepend_toolchain_paths

    # 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" || {
            fmix_error "ecto.migrate failed on $db_name."
            fmix_error "Check migration files in priv/repo/migrations/ for errors."
            return 1
        }
        # 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" \
            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_hash_compile_paths() {
    local root="$1"
    shift
    if git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
        fmix_hash_source_paths "$root" "$@"
        local untracked
        untracked="$(git -C "$root" ls-files --others --exclude-standard -- "$@" 2>/dev/null)"
        if [[ -n "$untracked" ]]; then
            while IFS= read -r path; do
                [[ -f "$root/$path" ]] || continue
                printf 'untracked:%s:' "$path"
                fmix_hash_files "$root/$path"
            done <<<"$untracked"
        fi
        return 0
    fi

    local path file
    for path in "$@"; do
        if [[ -f "$root/$path" ]]; then
            printf 'file:%s:' "$path"
            fmix_hash_files "$root/$path"
        elif [[ -d "$root/$path" ]]; then
            while IFS= read -r file; do
                printf 'file:%s:' "${file#"$root/"}"
                fmix_hash_files "$file"
            done < <(find "$root/$path" -type f -print 2>/dev/null | LC_ALL=C sort)
        else
            printf 'missing:%s\n' "$path"
        fi
    done
}

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=()
    while IFS= read -r file; do
        repo_elixir_paths+=("${file#"$real/"}")
    done < <(find "$real/priv/repo" -type f -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_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_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=()
    while IFS= read -r file; do
        repo_elixir_paths+=("${file#"$real/"}")
    done < <(find "$real/priv/repo" -type f -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"
    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)
                # 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_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
                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

    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
    local -a untracked=()
    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"

    while IFS= read -r -d '' file; do
        untracked+=("$dependency/$file")
    done < <(git -C "$dependency" ls-files --others --exclude-standard -z 2>/dev/null)
    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" dependency_fingerprint="$2" real build_root guard stamp tmp
    real="$(fmix_realpath "$worktree")"
    build_root="$(fmix_compile_build_root "$real")"
    guard="$(fmix_dependency_source_guard "$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"),
  "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-v1\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)

# Newest mtime under compile roots — detects leaf edits without full content hash.
max_mtime = 0.0
file_count = 0
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:
            max_mtime = max(max_mtime, base.stat().st_mtime)
            file_count += 1
        except OSError:
            pass
        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
            try:
                st = os.stat(os.path.join(dirpath, name))
            except OSError:
                continue
            max_mtime = max(max_mtime, st.st_mtime)
            file_count += 1

h.update(f"max_mtime={max_mtime:.6f}\n".encode())
h.update(f"file_count={file_count}\n".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 || echo "$worktree")"
    if command -v git >/dev/null 2>&1 && { [[ -d "$real/.git" ]] || [[ -f "$real/.git" ]]; }; then
        tree_hash="$(git -C "$real" rev-parse HEAD^{tree} 2>/dev/null || true)"
        if [[ "$tree_hash" =~ ^[0-9a-f]{40}$ ]]; then
            printf '%s\n' "$tree_hash"
            return 0
        fi
    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
    real="$(fmix_realpath "$worktree" 2>/dev/null || echo "$worktree")"
    if ! command -v git >/dev/null 2>&1 || { [[ ! -d "$real/.git" ]] && [[ ! -f "$real/.git" ]]; }; then
        printf 'clean\n'
        return 0
    fi
    status="$(git -C "$real" status --porcelain=v1 2>/dev/null || true)"
    if [[ -z "$status" ]]; then
        printf 'clean\n'
        return 0
    fi
    (
        printf '%s\n' "$status"
        git -C "$real" ls-files --others --modified --exclude-standard 2>/dev/null | head -50 | while IFS= read -r f; do
            fmix_stat_mtime "$real/$f" 2>/dev/null || echo 0
        done
    ) | fmix_hash_stdin
}

fmix_write_compile_stamp() {
    local worktree="$1" fingerprint="$2" real build_root guard dependency_guard stamp tmp quick_guard
    local template_key tree_hash env_hash dirty_hash
    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")" || quick_guard=""
    template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
    tree_hash="$(fmix_get_git_tree_hash "$real")"
    env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
    dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null || echo "clean")"
    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"),
  "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"),
  "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 short-circuit: accept an existing stamp when the cheap invalidator
# matches and beams still exist. Skips full content fingerprint + deps walk.
fmix_try_compile_stamp_quick_hit() {
    local worktree="$1" real build_root stamp dependency_stamp dependency_fingerprint dependency_guard
    local recorded_path recorded_build recorded_quick current_quick
    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
    recorded_path="$(fmix_read_state "$stamp" path)"
    recorded_build="$(fmix_read_state "$stamp" build_root)"
    recorded_quick="$(fmix_read_state "$stamp" quick_guard)"
    [[ -n "$recorded_quick" ]] || return 1
    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
    # A quick hit must not accept a stale or partial dependency checkpoint.
    # Validate the cheap structural fields here; the full dependency/source
    # guard remains the responsibility of fmix_ensure_compile on a miss.
    dependency_stamp="$(fmix_dependency_stamp_file "$real")"
    [[ -f "$dependency_stamp" ]] || return 1
    dependency_fingerprint="$(fmix_read_state "$dependency_stamp" dependency_fingerprint)"
    dependency_guard="$(fmix_read_state "$dependency_stamp" source_guard)"
    [[ "$dependency_fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
    [[ -n "$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
    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)"

    # 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)"

        local current_template_key current_tree_hash current_env_hash current_dirty_hash
        current_template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
        current_tree_hash="$(fmix_get_git_tree_hash "$real")"
        current_env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
        current_dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null || echo "clean")"

        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" ]]; 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_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"
    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" ]]; 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_FD=""

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"
    local permits deadline_secs
    permits="$(fmix_compile_semaphore_permits)"
    deadline_secs="${FMIX_CALLER_DEADLINE_SECS:-}"

    local py_bin slot fd acquired_slot=-1 acquired_fd=""
    py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
    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}"
            fd="$(fmix_lock_allocate_fd)" || return 1
            fmix_lock_open_fd "$fd" "$kfile" || { fmix_lock_close_fd "$fd"; continue; }
            if "$py_bin" - "$fd" 0 <<'PY' 2>/dev/null
import fcntl, sys
fd = int(sys.argv[1])
try:
    fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    raise SystemExit(0)
except Exception:
    raise SystemExit(1)
PY
            then
                acquired_slot="$slot"
                acquired_fd="$fd"
                break
            fi
            fmix_lock_close_fd "$fd"
        done

        if (( acquired_slot >= 0 )); then
            FMIX_CURRENT_SEMAPHORE_SLOT="$acquired_slot"
            FMIX_CURRENT_SEMAPHORE_FD="$acquired_fd"
            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_FD" ]]; then
        rm -f "$FMIX_HOME/lock-metadata/compile-permit-${FMIX_CURRENT_SEMAPHORE_SLOT}.json" 2>/dev/null || true
        fmix_lock_close_fd "$FMIX_CURRENT_SEMAPHORE_FD" 2>/dev/null || true
        FMIX_CURRENT_SEMAPHORE_SLOT=""
        FMIX_CURRENT_SEMAPHORE_FD=""
    fi
}

fmix_run_compile_streamed() {
    # Stream new compiler output at two-second granularity and emit a heartbeat
    # when Mix is CPU-bound without producing lines. Returns the compiler rc.
    local worktree="$1" db_name="$2" extra="$3" log_file="$4"
    local timeout_override="${5:-}"
    local heartbeat timeout pid shown=0 lines now started last_output rc sem_rc=0
    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

    # Acquire host compilation semaphore permit (Patch 2)
    fmix_compile_semaphore_acquire "$worktree" || sem_rc=$?
    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"

    while kill -0 "$pid" 2>/dev/null; do
        now="$(fmix_epoch)"
        if (( timeout > 0 && now - started >= timeout )); then
            fmix_error "Compile exceeded ${timeout}s; cancelling instead of holding the fmix lane. 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
            return 124
        fi
        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)"
        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
        fi
        sleep 2
    done
    wait "$pid"
    rc=$?
    fmix_compile_semaphore_release
    lines="$(wc -l <"$log_file" | tr -d ' ')"
    if (( lines > shown )); then
        sed -n "$(( shown + 1 )),${lines}p" "$log_file" >&2
    fi
    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"
    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" \
            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
}

_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" \
            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 1
        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"
            (( private_repo_lock == 1 )) && fmix_lock_release "hex-private-repo"
            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"
            (( private_repo_lock == 1 )) && fmix_lock_release "hex-private-repo"
            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"
    (( private_repo_lock == 1 )) && fmix_lock_release "hex-private-repo"
    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 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=""

    # Warm-path short-circuit: cheap mtime/manifest guard before full
    # content fingerprint (which walked deps + lib and cost ~8–10s).
    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

    # 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 …"
        fmix_run_deps_get "$worktree" || {
            fmix_error "mix deps.get failed; refusing to compile against unresolved dependencies."
            FMIX_LAST_COMPILE_OUTCOME="error"
            return 1
        }
        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

    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=""
    if [[ "$compile_mode" == "setup" ]]; then
        compile_timeout="$FMIX_SETUP_COMPILE_TIMEOUT"
        fmix_info "Explicit setup compile budget: ${compile_timeout}s."
    fi
    fmix_run_compile_streamed "$worktree" "$db_name" "" "$log_file" "$compile_timeout"
    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 exceeded the hard wall-clock budget (${elapsed_compile}s)."
        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
    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_error "Compile succeeded, but final dependency provenance could not be recorded."
        FMIX_LAST_COMPILE_OUTCOME="error"
        return 1
    fi

    fingerprint="$(fmix_compute_compile_fingerprint "$worktree")" || fingerprint=""
    if [[ -z "$fingerprint" ]] \
        || ! fmix_write_compile_stamp "$worktree" "$fingerprint"; then
        fmix_error "Compile succeeded, but final content/config provenance could not be recorded."
        FMIX_LAST_COMPILE_OUTCOME="error"
        return 1
    fi
    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
    real="$(fmix_realpath "$worktree")" || return 1
    fmix_activate_toolchain "$real" || return 1
    fmix_activate_session "$real" "$session_arg" || return 1
    fmix_seed_publish "$real" "$cache_base"
}

# ---------------------------------------------------------------------------
# cmd: fmix cache
# ---------------------------------------------------------------------------

cmd_cache() {
    local action="${1:-}" worktree_arg="auto" cache_base="" key=""
    case "$action" in
        explain|verify) ;;
        *)
            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>]"
            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 ;;
            *)
                fmix_error "Unknown cache $action option: $1."
                return 2
                ;;
        esac
    done

    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
    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
# ---------------------------------------------------------------------------

cmd_setup() {
    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
    local real_worktree
    real_worktree="$(fmix_realpath "$worktree")"
    fmix_activate_toolchain "$real_worktree" || return 1
    fmix_activate_session "$real_worktree" "$session_arg" || return 1
    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"
    fmix_info "DB name: $db_name"

    fmix_preflight "$real_worktree" || return 1
    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 1

    fmix_ensure_artifacts "$real_worktree" "$template_key" 1 || {
        fmix_lock_release "$lock_name"
        return 1
    }
    local setup_compile_rc=0
    fmix_ensure_compile "$real_worktree" "$db_name" setup || setup_compile_rc=$?
    if (( setup_compile_rc != 0 )); then
        fmix_lock_release "$lock_name"
        return "$setup_compile_rc"
    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_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 || true
        else
            fmix_publish_dependency_artifact \
                "$real_worktree" "$setup_dependency_fingerprint" \
                || fmix_warn "Could not backfill the exact dependency artifact during setup."
        fi
    fi
    fmix_ensure_db "$real_worktree" "$db_name" "$rebuild_existing" "$allow_structure_build" 1 "$force_from_zero" || {
        fmix_lock_release "$lock_name"
        return 1
    }

    fmix_ensure_migrations "$real_worktree" "$db_name" "$state_file" || {
        fmix_lock_release "$lock_name"
        return 1
    }

    local mig_stamp schema_key published_base
    schema_key="$FMIX_ACTIVE_DB_SCHEMA_KEY"
    published_base="$(fmix_publish_hot_base "$real_worktree" "$db_name" "$schema_key")" || {
        fmix_lock_release "$lock_name"
        return 1
    }
    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_lock_release "$lock_name"
        return 1
    }
    fmix_update_template_last_used "$template_key"

    fmix_lock_release "$lock_name"
    fmix_info "=== setup complete; hot DB base: $published_base ==="
    fmix_info "Run: ./fmix test --worktree $real_worktree -- <test args>"
}

# ---------------------------------------------------------------------------
# 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
        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
# ---------------------------------------------------------------------------

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
    local isolate_mode=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 ;;
            --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
                ;;
            --) 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>] --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] -- <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[@]}"; 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

    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

    local worktree
    worktree="$(fmix_find_worktree "$worktree_arg")" || {
        fmix_run_telemetry_finish 1
        return 1
    }
    local real_worktree
    real_worktree="$(fmix_realpath "$worktree")"
    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" || {
        fmix_emit_phase_change "session" "failed"
        fmix_run_telemetry_finish 1
        return 1
    }
    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" || {
        fmix_emit_phase_change "preflight" "failed"
        fmix_run_telemetry_finish 1
        return 1
    }
    fmix_check_pg_connections
    fmix_run_telemetry_phase "preflight"
    fmix_emit_phase_change "preflight" "completed"

    # Per-worktree lock (serializes concurrent runs in same worktree)
    local lock_name
    lock_name="$(fmix_execution_lock_name "$real_worktree")"
    fmix_emit_phase_change "lock" "started"
    fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || {
        fmix_emit_phase_change "lock" "failed"
        fmix_run_telemetry_finish 1
        return 1
    }
    fmix_run_telemetry_phase "lock"
    fmix_emit_phase_change "lock" "completed"

    # 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_lock_release "$lock_name"
                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
        fmix_ensure_artifacts "$real_worktree" "$template_key" 0 || {
            fmix_lock_release "$lock_name"
            FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-error}"
            fmix_emit_phase_change "artifacts" "failed"
            fmix_run_telemetry_finish 1
            return 1
        }
        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_lock_release "$lock_name"
        fmix_emit_phase_change "compile" "failed"
        fmix_run_telemetry_finish "$compile_rc"
        return "$compile_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 || {
        fmix_lock_release "$lock_name"
        fmix_emit_phase_change "db" "failed"
        fmix_run_telemetry_finish 1
        return 1
    }
    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" || {
        fmix_lock_release "$lock_name"
        fmix_emit_phase_change "migrate" "failed"
        fmix_run_telemetry_finish 1
        return 1
    }
    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_write_worktree_state "$real_worktree" "$template_key" "$db_name" "$mig_stamp" "$(fmix_now)" "$schema_key" "$FMIX_ACTIVE_DB_BASE_ID" "$FMIX_ACTIVE_DB_SOURCE_KEY" || {
        fmix_lock_release "$lock_name"
        fmix_run_telemetry_finish 1
        return 1
    }
    fmix_update_template_last_used "$template_key"

    # 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")

    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")

    fmix_emit_phase_change "mix_test" "started"
    local test_rc=0
    (
        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"
            WORKER_NODE=TRUE
            ADMIN_NODE=TRUE
            ONPREM=TRUE
            SECRET_KEY_BASE="$SECRET_KEY_BASE"
            MEESEEKS_HTML5EVER_BUILD=0
            CT_SKIP_MIGRATION_TIMING=1
        )
        [[ -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")
        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[@]}"; 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=$?

    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

    # Update last_used after test run
    fmix_update_last_used "$state_file"
    fmix_update_template_last_used "$template_key"
    fmix_lock_release "$lock_name"

    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_run_telemetry_finish "$test_rc"
    return $test_rc
}

cmd_coverage() {
    FMIX_INTERNAL_RUN_MODE=coverage cmd_test "$@"
}

# ---------------------------------------------------------------------------
# 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
    real_worktree="$(fmix_realpath "$worktree")" || return 1
    fmix_activate_toolchain "$real_worktree" || return 1
    fmix_activate_session "$real_worktree" "$session_arg" || return 1
    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 1
    if ! fmix_ensure_artifacts "$real_worktree" "$template_key" 1 ||
        ! fmix_ensure_compile "$real_worktree" "$db_name" setup; then
        fmix_lock_release "$lock_name"
        return 1
    fi

    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 task_rc=0
    (
        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" \
            WORKER_NODE=TRUE \
            ADMIN_NODE=TRUE \
            ONPREM=TRUE \
            SECRET_KEY_BASE="$SECRET_KEY_BASE" \
            MEESEEKS_HTML5EVER_BUILD=0 \
            mix "${mix_args[@]}"
    ) || task_rc=$?

    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
            task_rc=1
        else
            template_key="$(fmix_compute_template_key "$real_worktree")" || task_rc=1
        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
        fmix_update_template_last_used "$template_key"
    fi
    fmix_lock_release "$lock_name"
    fmix_info "Mix task completed (rc=$task_rc)."
    return "$task_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() {
    nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null
}

fmix_infra_ready() {
    fmix_infra_postgres_ready && fmix_infra_nats_ready
}

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_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
    for name in "${FMIX_INFRA_PROJECT}-postgres-1" "${FMIX_INFRA_PROJECT}-nats-1"; 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
    docker compose -p "$FMIX_INFRA_PROJECT" -f "$FMIX_HOME/infra/compose-ensure.yml" up -d postgres nats
}

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
        sleep 1
    done
    return 1
}

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_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

    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

    echo "  starting shared $FMIX_INFRA_PROJECT (postgres + nats)..."
    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_compose_up_ensure; then
        fmix_error "docker compose could not start $FMIX_INFRA_PROJECT postgres/nats"
        return 1
    fi
    if ! fmix_wait_infra; then
        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)"
    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 [[ -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 TCP
    if nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
        echo "  [OK] NATS TCP $NATS_HOST:$NATS_PORT"
    else
        echo "  [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT — run: ./infra.sh up (some tests may fail)"
    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
                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"
        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
        echo "  [FAIL] session discovery failed; skipped orphan scratch DB cleanup"
        fail=$(( fail + 1 ))
        session_scan_ok=0
    elif ! 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 LIKE 'ct_fmix_s_%'" 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
                orphan_drop_rc=0
                fmix_drop_orphan_session_db "$db_name" "doctor orphan DB sweep" \
                    >/dev/null || orphan_drop_rc=$?
                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
# ---------------------------------------------------------------------------

cmd_status() {
    local scoped_run_id="" scoped_json=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 ;;
            *) fmix_error "Unknown status option: $1. Usage: fmix status [--run-id <uuid> --json]"; return 2 ;;
        esac
    done
    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
    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="$(du -sh "$tdir" 2>/dev/null | awk '{print $1}')" || true
            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="$(du -sh "$FMIX_HOME/dependency-artifacts/v1" \
            2>/dev/null | awk '{print $1}')" || dependency_artifact_bytes="?"
        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
            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 "$lock_name" >/dev/null 2>&1 || 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
            fmix_drop_db "$db_name" 2>/dev/null \
                && echo "    dropped db $db_name" \
                || fmix_warn "Could not drop $db_name"
        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 "$lock_name" >/dev/null 2>&1 || 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
}

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"; then
                                echo "  Dropped: $db"
                                rm -f "$FMIX_HOME/compile-stamps/$(basename "$sf")"
                                rm -f "$sf"
                            else
                                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 )) && ! fmix_drop_db "$pgdb"; then
                                orphan_drop_rc=1
                            fi
                        fi
                        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

    # 2. Stale tmp template dirs (older than 1 day)
    echo ""
    echo "--- Stale template build dirs (> 1 day old) ---"
    if [[ -d "$FMIX_HOME/templates" ]]; then
        local now_epoch
        now_epoch=$(fmix_epoch)
        for tdir in "$FMIX_HOME/templates"/*.tmp-*/; do
            [[ -d "$tdir" ]] || continue
            local mtime
            mtime=$(fmix_stat_mtime "$tdir" 2>/dev/null || echo 0)
            local age=$(( now_epoch - mtime ))
            if (( age > 86400 )); then
                echo "  STALE: $tdir (age: $(( age / 3600 ))h)"
                actions=$(( actions + 1 ))
                if (( do_reap == 1 )); then
                    fmix_guard_path "$tdir" \
                        && chmod -R u+w "$tdir" \
                        && rm -rf "$tdir" \
                        && echo "  Deleted: $tdir"
                fi
            fi
        done
    fi

    # 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

    # 4. Old templates (last_used > 30 days)
    echo ""
    echo "--- Templates unused > 30 days ---"
    if [[ -d "$FMIX_HOME/templates" ]]; then
        local now_epoch
        now_epoch=$(fmix_epoch)
        for tdir in "$FMIX_HOME/templates"/*/; do
            [[ -d "$tdir" ]] || continue
            local key
            key="$(basename "$tdir")"
            [[ "$key" == *.tmp-* ]] && continue
            local meta="$tdir/meta.json"
            [[ -f "$meta" ]] || continue
            local last_used_str
            last_used_str="$(fmix_read_template_last_used "$key")"
            if [[ -z "$last_used_str" ]]; then
                continue
            fi
            # Parse ISO date to epoch (python3 portable)
            local last_used_epoch
            last_used_epoch="$(fmix_iso_epoch "$last_used_str" 2>/dev/null)" \
                || last_used_epoch=0
            local age=$(( now_epoch - last_used_epoch ))
            if (( age > 2592000 )); then  # 30 days
                echo "  OLD: $key (last_used: $last_used_str, age: $(( age / 86400 ))d)"
                actions=$(( actions + 1 ))
                if (( do_reap == 1 )); then
                    local confirm="y"
                    if (( skip_prompts == 0 )); then
                        printf '  Delete template %s? [y/N] ' "$key"
                        read -r confirm
                    fi
                    if [[ "$confirm" =~ ^[Yy]$ ]]; then
                        fmix_guard_path "$tdir" \
                            && chmod -R u+w "$tdir" \
                            && rm -rf "$tdir" \
                            && echo "  Deleted: $tdir"
                    fi
                fi
            fi
        done
    fi

    # 5. Exact dependency artifacts have their own access sidecars because
    # the immutable artifact metadata must never be touched by consumers.
    local dependency_ttl_days dependency_ttl_seconds dependency_root
    dependency_ttl_days="$(fmix_uint_or_default \
        "$FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS" 30 \
        FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS)"
    dependency_ttl_seconds=$(( dependency_ttl_days * 86400 ))
    dependency_root="$FMIX_HOME/dependency-artifacts/v1"
    echo ""
    echo "--- Dependency artifacts unused > ${dependency_ttl_days} days ---"
    if [[ -d "$dependency_root" ]]; then
        local dependency_artifact lane exact access_file last_access last_epoch age
        local artifact_lock confirm
        for dependency_artifact in "$dependency_root"/*/*/; do
            [[ -d "$dependency_artifact" && ! -L "$dependency_artifact" ]] || continue
            lane="$(basename "$(dirname "${dependency_artifact%/}")")"
            exact="$(basename "${dependency_artifact%/}")"
            [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || continue
            access_file="$FMIX_HOME/dependency-artifact-access/$lane/$exact"
            last_access="$(cat "$access_file" 2>/dev/null || true)"
            if [[ -n "$last_access" ]]; then
                last_epoch="$(fmix_iso_epoch "$last_access" 2>/dev/null)" \
                    || last_epoch=0
            else
                last_epoch="$(fmix_stat_mtime "$dependency_artifact" 2>/dev/null)" \
                    || last_epoch=0
            fi
            age=$(( $(fmix_epoch) - last_epoch ))
            (( age > dependency_ttl_seconds )) || continue
            echo "  OLD: dependency artifact (age=$(( age / 86400 ))d, size=$(du -sh "$dependency_artifact" 2>/dev/null | awk '{print $1}'))"
            actions=$(( actions + 1 ))
            if (( do_reap == 1 )); then
                confirm="y"
                if (( skip_prompts == 0 )); then
                    printf '  Delete this dependency artifact? [y/N] '
                    read -r confirm
                fi
                if [[ "$confirm" =~ ^[Yy]$ ]]; then
                    artifact_lock="dependency-artifact-${lane:0:16}-${exact:0:16}"
                    if fmix_lock_acquire "$artifact_lock" 1 \
                        "dependency artifact GC" >/dev/null 2>&1; then
                        # A consumer may have refreshed the sidecar while GC
                        # was waiting. Recheck before the destructive step.
                        last_access="$(cat "$access_file" 2>/dev/null || true)"
                        if [[ -n "$last_access" ]]; then
                            last_epoch="$(fmix_iso_epoch "$last_access" 2>/dev/null)" \
                                || last_epoch=0
                        else
                            last_epoch="$(fmix_stat_mtime "$dependency_artifact" 2>/dev/null)" \
                                || last_epoch=0
                        fi
                        age=$(( $(fmix_epoch) - last_epoch ))
                        if (( age > dependency_ttl_seconds )) \
                            && fmix_guard_path "$dependency_artifact" \
                            && chmod -R u+w "$dependency_artifact" \
                            && rm -rf "$dependency_artifact"; then
                            rm -f "$access_file" 2>/dev/null || true
                            echo "  Deleted dependency artifact."
                        fi
                        fmix_lock_release "$artifact_lock" >/dev/null 2>&1 || true
                    else
                        fmix_warn "Dependency artifact is active; keeping it."
                    fi
                fi
            fi
        done
    fi

    # 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
                    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 "$session_lock" >/dev/null 2>&1 \
                        || 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" || 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 "$session_lock" >/dev/null 2>&1 \
                    || 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() {
    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}'"

    # 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
    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://example.invalid/cisco-cdr.git\n' \
        >"$submodule_parent/.gitmodules"
    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
    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)"
    FMIX_HOME="$self_test_seed_home"
    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
    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=""
    if [[ -n "$dependency_artifact_path" ]] \
        && 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" \
        && [[ ! -e "$dependency_artifact_path/_build/test/lib/cdrcisco" ]] \
        && [[ -f "$FMIX_HOME/dependency-artifact-access/$dependency_artifact_lane/$publish_dep_fingerprint" ]]; 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"
    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"

    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
    FMIX_DEPS_STALL_TIMEOUT=1
    FMIX_DEPS_TIMEOUT=10
    _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.
    FMIX_DEPS_STALL_TIMEOUT=2
    FMIX_DEPS_TIMEOUT=30
    _fmix_run_deps_get() {
        local i
        for i in 1 2 3 4; 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/')"
    local zero_gate_snap_marker="$zero_gate_wt/snap-called"
    zero_gate_marker="$zero_gate_wt/zero-called"
    fmix_db_exists() { return 1; }
    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/')"
    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
}

# ---------------------------------------------------------------------------
# Main dispatch
# ---------------------------------------------------------------------------

fmix_usage() {
    cat <<'USAGE'
fmix — fast native Elixir test runner for cisco-cdr

Usage:
  ./fmix test [--worktree <path>] [--session <id>] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] -- <mix test args>
  ./fmix coverage [--worktree <path>] [--session <id>] --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 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 ensure
  ./fmix doctor
  ./fmix status
  ./fmix timing [--limit N] [--worktree <path>]   # phase timings + session fragmentation
  ./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 # reuse snapshots only; never replays structure.sql
  ./fmix setup --cold-db --worktree ./cisco-cdr  # explicit one-time schema cache build
  ./fmix setup --from-zero --worktree ./cisco-cdr  # full migration chain from an empty DB; 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

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.

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_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)
  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: localhost)
  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_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 cap in seconds (default: 900)
  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_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"),
        })
        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
        publication_cutoff = cancellation_deadline - 0.20
        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))
            sampler_deadline = min(publication_cutoff, time.monotonic() + 0.25)
            cleanup_sampler(sampler_deadline, immediate=True)
            kill_pinned_worker_group(publication_cutoff)
            worker_wait_deadline = min(
                publication_cutoff - 0.10, 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
)
publication_cutoff = cleanup_deadline - 0.20

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})

cleanup_sampler(publication_cutoff, immediate=cancellation_started is not None)
kill_pinned_worker_group(publication_cutoff)
kill_sentinel_fallback()
if not reaped and group_kill_succeeded:
    worker_wait_deadline = min(publication_cutoff - 0.10, 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<&-
}

main() {
    if (( $# == 0 )); then
        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_usage
        return 0
    fi

    local cmd="$1"
    shift
    case "$cmd" in
        help|--help|-h)
            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

    if [[ "$cmd" == "cache" ]]; then
        fmix_prepare_home_readonly || return 1
    else
        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
    fi

    case "$cmd" in
        test)    cmd_test "$@" ;;
        coverage) cmd_coverage "$@" ;;
        task)    cmd_task "$@" ;;
        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 "$@" ;;
        *)
            fmix_error "Unknown command: $cmd"
            fmix_error "Valid commands: test, coverage, task, setup, seed publish, cache explain, cache verify, doctor, status, timing, gc, install, self-test, version, help"
            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_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
