Skip to content

AI, fully local on your computer.

51.0 KB
Raw Blame
#!/usr/bin/env bash
# Download + verify the llama.cpp sidecar binary onto a prepared drive (Phase 12).
#
# Reads model-manifests/runtime-sources.yaml (on the drive, falling back to the repo),
# picks the build matching the host OS/arch (or --os/--arch/--backend overrides), downloads
# the release zip, SHA-256-verifies it, and extracts it into the build's extract_to dir
# (runtime/llama.cpp/<os>/ for the default build; runtime/llama.cpp/<os>/cpu/ for the
# pure-CPU safety net), then chmod +x the binary. After extraction a .hilbertraum-runtime.json
# install marker ({ version, backend, os, arch }) is written next to the binary.
#
# Mirrors apps/desktop/src/main/services/assets.ts (selectRuntimeBuild /
# planRuntimeDownload / runtimeInstallCurrent). Self-contained: needs no Node/npm.
# DEFAULT BACKEND = the FIRST build listed per OS in runtime-sources.yaml — since
# Phase 14 that is the Vulkan full build on win/linux (contains every CPU backend;
# degrades to CPU on GPU-less machines) and Metal on mac. --backend cpu fetches the
# pure-CPU safety net into <os>/cpu/.
#
# Verify-before-trust: a real-hash MISMATCH deletes the zip and exits non-zero. A
# placeholder zip hash extracts but reports UNVERIFIED and the marker then records NO
# binary hash (the sell gate refuses such an install). Idempotent via the MARKER, not
# mere binary presence: a present llama-server whose .hilbertraum-runtime.json matches the
# selected version + backend is skipped; a missing/stale marker re-fetches (so upgrading
# a CPU-era drive to the Vulkan default actually replaces the build).
#
# An engine NEWER than the drive's pin (#873) is kept: the app's in-app update (#516) installs
# its own pin and leaves the drive's runtime-sources.yaml as it was, so the marker can be ahead
# of the yaml. Versions are ordered the way the app orders them (assets.ts
# compareRuntimeVersions: `b<build>`, or dotted numbers with an optional `v`); a version that
# cannot be ordered against the pin is re-fetched as before. --allow-downgrade replaces it
# anyway; --commercial always does (a sold drive carries the pin of the app it ships with).
#
# --commercial (drive builders, #234): a placeholder hash is REFUSED before any download
# (exit 1, nothing extracted, no marker) and a hashless (legacy) marker is re-fetched
# instead of skipped, so a sold drive never carries an unverifiable sidecar.
#
# --allow-downgrade replaces an engine whose install marker is newer than the drive's pin (an
# engine the app updated, #873) with the pinned, older one. Without it such an engine is kept.
#
# --family selects the asset family: llama_cpp (default, llama-server), whisper_cpp
# (the whisper-cli transcriber, runtime/whisper.cpp/<os>/ — same verify + marker
# logic), kiwix_tools (#339 P8-3: the OPTIONAL knowledge-pack tools —
# kiwix-serve/kiwix-manage/kiwix-search plus the five ICU DLLs on Windows; never fetched
# by prepare-drive --with-assets, only by an explicit --family kiwix_tools), or ocr
# (Phase 38: the vendored OCR language files, plain sha256-verified downloads into ocr/ —
# no extraction, no marker; idempotency IS the hash).
#
# Usage:
#   scripts/fetch-runtime.sh --target /Volumes/HILBERTRAUM \
#       [--os linux] [--arch x64] [--backend cpu] [--family whisper_cpp|kiwix_tools|ocr] [--commercial] [--allow-downgrade] [--dry-run]
set -euo pipefail

TARGET=""; OS=""; ARCH=""; BACKEND=""; FAMILY="llama_cpp"; COMMERCIAL=0; ALLOW_DOWNGRADE=0; DRY_RUN=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --target) TARGET="${2:-}"; shift 2 ;;
    --target=*) TARGET="${1#*=}"; shift ;;
    --os) OS="${2:-}"; shift 2 ;;
    --os=*) OS="${1#*=}"; shift ;;
    --arch) ARCH="${2:-}"; shift 2 ;;
    --arch=*) ARCH="${1#*=}"; shift ;;
    --backend) BACKEND="${2:-}"; shift 2 ;;
    --backend=*) BACKEND="${1#*=}"; shift ;;
    --family) FAMILY="${2:-}"; shift 2 ;;
    --family=*) FAMILY="${1#*=}"; shift ;;
    --commercial) COMMERCIAL=1; shift ;;
    --allow-downgrade) ALLOW_DOWNGRADE=1; shift ;;
    --dry-run) DRY_RUN=1; shift ;;
    -h|--help) grep '^#' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    *) echo "Unknown argument: $1" >&2; exit 2 ;;
  esac
done
[[ -z "$TARGET" ]] && { echo "Error: --target <drive-root> is required" >&2; exit 2; }
case "$FAMILY" in
  llama_cpp|whisper_cpp|kiwix_tools|ocr) ;;
  *) echo "Error: --family must be llama_cpp, whisper_cpp, kiwix_tools, or ocr" >&2; exit 2 ;;
esac

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Resilient curl: a flaky link (beta-tester report — the connection dropped mid-curl) can
# fail repeatedly. curl's own --retry does not cover a mid-transfer DROP (exit 18/56/28) on
# older curl, so an OUTER loop RESUMES the partial file (-C -) on each attempt. $3 = extra
# flags (e.g. schannel's --ssl-revoke-best-effort). Integrity is enforced by the SHA-256 pin
# AFTER download, so resume can never weaken verification.
curl_resilient() {
  local url="$1" dest="$2" extra="${3:-}"
  local attempts=5 i wait
  for (( i = 1; i <= attempts; i++ )); do
    # shellcheck disable=SC2086 # $extra is an intentional word-split flag list (may be empty)
    if curl -L --fail --retry 3 --retry-delay 2 --retry-connrefused \
         --connect-timeout 30 $extra -C - -o "$dest" "$url"; then
      return 0
    fi
    if (( i < attempts )); then
      wait=$(( i * 3 ))
      echo "    connection interrupted -- retry $i/$attempts in ${wait}s, resuming…" >&2
      sleep "$wait"
    fi
  done
  return 1
}

SOURCES_FILE="$TARGET/model-manifests/runtime-sources.yaml"
[[ -f "$SOURCES_FILE" ]] || SOURCES_FILE="$REPO_ROOT/model-manifests/runtime-sources.yaml"
[[ -f "$SOURCES_FILE" ]] || { echo "No runtime-sources.yaml found under '$TARGET' or repo root." >&2; exit 2; }

# Host detection. When --os is explicitly overridden but --arch is not, we are
# cross-provisioning another OS's dir — the host arch is meaningless there, so the
# selection below takes that OS's first build instead.
OS_EXPLICIT=0; [[ -n "$OS" ]] && OS_EXPLICIT=1
ARCH_EXPLICIT=0; [[ -n "$ARCH" ]] && ARCH_EXPLICIT=1
if [[ -z "$OS" ]]; then
  case "$(uname -s)" in
    Darwin) OS="mac" ;;
    Linux) OS="linux" ;;
    MINGW*|MSYS*|CYGWIN*) OS="win" ;;
    *) OS="linux" ;;
  esac
fi
if [[ -z "$ARCH" ]]; then
  case "$(uname -m)" in
    arm64|aarch64) ARCH="arm64" ;;
    *) ARCH="x64" ;;
  esac
fi

is_real_sha() { [[ "$1" =~ ^[a-f0-9]{64}$ ]]; }

# #873: order two engine release tags of one family the way the app does (assets.ts
# compareRuntimeVersions). Prints -1 (older), 0 (equal) or 1 (newer), and NOTHING when either tag
# has an unknown shape or the two shapes differ. `b<digits>` is a build counter;
# `v?<digits>(.<digits>)*` a dotted release whose missing trailing parts count as zero. Numbers
# compare as numbers ('3.10' > '3.8'), read in base 10: bash takes a leading 0 for octal and
# fails on 08/09. Bash 3.2-safe (a Mac builder runs /bin/bash): the patterns held in variables,
# every test an if, so set -e never fires on a false one.
runtime_version_kind() {
  local tag="$1" re_build='^b([0-9]+)$' re_dotted='^v?([0-9]+(\.[0-9]+)*)$'
  tag="${tag#"${tag%%[![:space:]]*}"}"
  tag="${tag%"${tag##*[![:space:]]}"}"
  if [[ "$tag" =~ $re_build ]]; then echo "build ${BASH_REMATCH[1]}"
  elif [[ "$tag" =~ $re_dotted ]]; then echo "dotted ${BASH_REMATCH[1]}"
  fi
}
compare_runtime_versions() {
  local a b pa pb n i x y
  a="$(runtime_version_kind "$1")"
  b="$(runtime_version_kind "$2")"
  if [[ -z "$a" || -z "$b" || "${a%% *}" != "${b%% *}" ]]; then return 0; fi
  IFS='.' read -r -a pa <<< "${a#* }"
  IFS='.' read -r -a pb <<< "${b#* }"
  n=${#pa[@]}
  if [[ ${#pb[@]} -gt $n ]]; then n=${#pb[@]}; fi
  for (( i = 0; i < n; i++ )); do
    x=$((10#${pa[i]:-0}))
    y=$((10#${pb[i]:-0}))
    if [[ $x -lt $y ]]; then echo -1; return 0; fi
    if [[ $x -gt $y ]]; then echo 1; return 0; fi
  done
  echo 0
}

# Whether a relative path stays inside the extract dir once its `.` and `..` are resolved (#767): a
# link's `../lib/x` stays inside its archive, `a/../../x` leaves it.
stays_inside() {
  local parts seg depth=0
  IFS='/' read -r -a parts <<< "$1"
  for seg in ${parts[@]+"${parts[@]}"}; do
    case "$seg" in
      ''|.) ;;
      ..) depth=$((depth - 1)); if [[ $depth -lt 0 ]]; then return 1; fi ;;
      *) depth=$((depth + 1)) ;;
    esac
  done
  return 0
}
sha256_of() {
  # Hash from STDIN, never by filename: when the path contains a backslash (git-bash on
  # Windows, e.g. "$RUNNER_TEMP/…" = "D:\a\_temp/…"), GNU coreutils escapes the name and
  # prefixes the whole output line with "\\" — the extracted hash then never string-equals
  # the manifest value (v0.1.56 release run 31341651519, build-win: "expected ed6156…, got
  # \ed6156…"). Stdin has no filename, so nothing is ever escaped.
  if command -v sha256sum >/dev/null 2>&1; then sha256sum < "$1" | awk '{print $1}'
  else shasum -a 256 < "$1" | awk '{print $1}'; fi
}

# #339 P8-3: parse a flow-sequence string ("[a, b, c]", or "[]"/empty) into words on
# stdout, one per line. Mirrors the .ps1 Get-FlowListValue twin.
flow_list_items() {
  local raw="$1"
  raw="${raw#\[}"; raw="${raw%\]}"
  [[ -z "${raw//[[:space:]]/}" ]] && return 0
  local IFS=','
  local -a parts
  read -ra parts <<< "$raw"
  local p
  for p in "${parts[@]}"; do
    p="$(echo "$p" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' | tr -d '"'"'"'')"
    [[ -n "$p" ]] && echo "$p"
  done
}

# #339 P8-3: the committed yaml spells `executables:`/`runtime_files:` as a one-line flow
# sequence, but a hand-edited drive yaml might use a block sequence instead (`key:` alone,
# then indented `- item` lines). Collapse any such block into the inline flow form BEFORE
# the line-by-line parsers below run, so they only ever see one shape. Scoped to just these
# two keys — `builds:`/`files:` are lists of MAPPINGS ("- os: win"), not scalars, and are
# already handled by the per-item parsers below. Reads the global RAW_LINES array, writes
# the global PP_LINES array.
collapse_block_lists() {
  local n=${#RAW_LINES[@]} i=0
  PP_LINES=()
  while (( i < n )); do
    local line="${RAW_LINES[$i]%$'\r'}"
    if [[ "$line" =~ ^([[:space:]]*)(executables|runtime_files)[[:space:]]*:[[:space:]]*$ ]]; then
      local indent="${BASH_REMATCH[1]}" key="${BASH_REMATCH[2]}"
      local items="" found=0
      local j=$((i + 1))
      while (( j < n )); do
        local cand="${RAW_LINES[$j]%$'\r'}"
        if [[ "$cand" =~ ^([[:space:]]+)-[[:space:]]*(.+)$ ]] && (( ${#BASH_REMATCH[1]} > ${#indent} )); then
          local item
          item="$(echo "${BASH_REMATCH[2]}" | sed 's/[[:space:]]*$//' | tr -d '"'"'"'')"
          items="${items:+$items, }$item"
          found=1
          j=$((j + 1))
        else
          break
        fi
      done
      if [[ $found -eq 1 ]]; then
        PP_LINES+=("${indent}${key}: [${items}]")
        i=$j
        continue
      fi
    fi
    PP_LINES+=("$line")
    i=$((i + 1))
  done
}

# --- The ocr family (Phase 38, D32): plain verified FILES, not build archives -------
# Parses `ocr.files` (- lang/url/sha256/dest entries), downloads each into its dest,
# verifies the sha256 of the file AS DOWNLOADED, and skips files already present with
# a matching hash. Mirrors assets.ts planOcrDownloads.
if [[ "$FAMILY" == "ocr" ]]; then
  OCR_VERSION=""
  declare -a F_LANG F_URL F_SHA F_DEST
  fidx=-1
  TOP_KEY=""
  strip_value_ocr() { echo "$1" | sed 's/[[:space:]][[:space:]]*#.*$//' | tr -d '"'"'"'' | sed 's/[[:space:]]*$//'; }
  while IFS= read -r raw; do
    line="${raw%$'\r'}"
    [[ "$line" =~ ^[[:space:]]*# ]] && continue
    if [[ "$line" =~ ^([A-Za-z0-9_]+)[[:space:]]*:[[:space:]]*$ ]]; then
      TOP_KEY="${BASH_REMATCH[1]}"
      continue
    fi
    [[ "$TOP_KEY" == "ocr" ]] || continue
    if [[ -z "$OCR_VERSION" && "$line" =~ ^[[:space:]]*version[[:space:]]*:[[:space:]]*(.+)$ ]]; then
      OCR_VERSION="$(strip_value_ocr "${BASH_REMATCH[1]}")"; continue
    fi
    if [[ "$line" =~ ^[[:space:]]*-[[:space:]]*lang[[:space:]]*:[[:space:]]*(.+)$ ]]; then
      fidx=$((fidx + 1))
      F_LANG[$fidx]="$(strip_value_ocr "${BASH_REMATCH[1]}")"
      continue
    fi
    if [[ $fidx -ge 0 && "$line" =~ ^[[:space:]]+([A-Za-z0-9_]+)[[:space:]]*:[[:space:]]*(.+)$ ]]; then
      key="${BASH_REMATCH[1]}"
      val="$(strip_value_ocr "${BASH_REMATCH[2]}")"
      case "$key" in
        url) F_URL[$fidx]="$val" ;;
        sha256) F_SHA[$fidx]="$(echo "$val" | tr '[:upper:]' '[:lower:]')" ;;
        dest) F_DEST[$fidx]="$val" ;;
      esac
    fi
  done < "$SOURCES_FILE"
  if [[ -z "$OCR_VERSION" || $fidx -lt 0 ]]; then
    echo "runtime-sources.yaml: no ocr block (version + files) found." >&2; exit 2
  fi
  echo "Fetch OCR language files -> $TARGET (data $OCR_VERSION)"
  # --commercial: every file must be verifiable BEFORE the first download (#234).
  if [[ $COMMERCIAL -eq 1 ]]; then
    PLACEHOLDERS=""
    for (( i = 0; i <= fidx; i++ )); do
      sha_i="${F_SHA[$i]:-}"
      if [[ -n "$sha_i" ]] && ! is_real_sha "$sha_i"; then PLACEHOLDERS="${PLACEHOLDERS:+$PLACEHOLDERS, }${F_LANG[$i]}"; fi
    done
    if [[ -n "$PLACEHOLDERS" ]]; then
      echo "  commercial: placeholder sha256 for ocr file(s) $PLACEHOLDERS — refusing to fetch (nothing downloaded)" >&2
      exit 1
    fi
  fi
  FAILED=0
  for (( i = 0; i <= fidx; i++ )); do
    for required in url sha256 dest; do
      case "$required" in
        url) v="${F_URL[$i]:-}" ;;
        sha256) v="${F_SHA[$i]:-}" ;;
        dest) v="${F_DEST[$i]:-}" ;;
      esac
      [[ -z "$v" ]] && { echo "ocr.files (${F_LANG[$i]}): missing '$required'." >&2; exit 2; }
    done
    case "${F_DEST[$i]}" in
      *..*|/*|[A-Za-z]:*)
        echo "runtime-sources.yaml: ocr dest escapes the drive root: ${F_DEST[$i]}" >&2; exit 2 ;;
    esac
    DEST="$TARGET/${F_DEST[$i]}"
    SHA="${F_SHA[$i]}"
    echo "  ${F_LANG[$i]}: ${F_DEST[$i]}"
    if [[ $DRY_RUN -eq 1 ]]; then echo "    would fetch ${F_URL[$i]}"; continue; fi
    if [[ -f "$DEST" ]] && is_real_sha "$SHA"; then
      if [[ "$(sha256_of "$DEST")" == "$SHA" ]]; then echo "    skip (present + verified)"; continue; fi
      echo "    present but hash differs — re-fetching"
      # DELETE the bad file first (AUD-24). The download below resumes at the end of whatever
      # is already on disk (curl -C -), so re-fetching ONTO a complete-but-wrong file asks the
      # server for a byte range that starts at or past the resource's length — an
      # unsatisfiable range (HTTP 416), which fails every retry instead of replacing the file.
      # Starting from an empty destination makes the repair attempt an actual repair.
      # UNCONDITIONAL here, unlike fetch-models, and deliberately so — do not "harmonize" the
      # two: fetch-models guards the same delete behind a size test because it must preserve
      # cross-run resume of multi-GB weights, and its manifests carry a size_bytes to test
      # against. These OCR language files are a few MB, runtime-sources.yaml records no size
      # for them, and re-fetching one costs nothing — so there is no partial worth saving and
      # no field to distinguish one with.
      rm -f "$DEST"
    fi
    mkdir -p "$(dirname "$DEST")"
    if command -v curl >/dev/null 2>&1; then
      CURL_EXTRA=""
      curl --version 2>/dev/null | head -n1 | grep -qi schannel && CURL_EXTRA="--ssl-revoke-best-effort"
      curl_resilient "${F_URL[$i]}" "$DEST" "$CURL_EXTRA" || { echo "    curl failed after retries" >&2; FAILED=$((FAILED + 1)); continue; }
    elif command -v wget >/dev/null 2>&1; then
      wget -O "$DEST" "${F_URL[$i]}" || { echo "    wget failed" >&2; FAILED=$((FAILED + 1)); continue; }
    else
      echo "No downloader found (need curl or wget)." >&2; exit 3
    fi
    if is_real_sha "$SHA"; then
      ACTUAL="$(sha256_of "$DEST")"
      if [[ "$ACTUAL" != "$SHA" ]]; then
        echo "    FAIL: checksum mismatch (expected $SHA, got $ACTUAL) — deleting" >&2
        rm -f "$DEST"; FAILED=$((FAILED + 1)); continue
      fi
      echo "    VERIFIED"
    else
      echo "    UNVERIFIED (placeholder hash)"
    fi
  done
  [[ $FAILED -gt 0 ]] && exit 1
  exit 0
fi

# --- Parse runtime-sources.yaml (list of build maps under <family>.builds:) ---------
# BLOCK-AWARE since Phase 36: the file holds TWO top-level families (llama_cpp +
# whisper_cpp) with the same shape — only the selected --family's version/builds are
# collected, so the whisper builds can never leak into a llama selection or vice versa.
VERSION=""
declare -a B_OS B_ARCH B_BACKEND B_URL B_SHA B_EXTRACT B_RUNTIME
idx=-1
TOP_KEY=""
FAMILY_EXECUTABLES=""
# Strip an inline YAML comment (whitespace + '#' + rest) before unquoting (M17) — the
# committed `version: b9196   # PLACEHOLDER …` used to leak the comment into the value.
strip_value() { echo "$1" | sed 's/[[:space:]][[:space:]]*#.*$//' | tr -d '"'"'"'' | sed 's/[[:space:]]*$//'; }

# Read WITHOUT `mapfile` (a Bash 4+ builtin absent from macOS's stock Bash 3.2 — it broke
# the v0.1.60 release's mac leg). Blank lines are kept (as `mapfile -t` kept them), and
# `|| [[ -n … ]]` keeps a final line that has no trailing newline.
RAW_LINES=()
while IFS= read -r raw_line || [[ -n "$raw_line" ]]; do
  RAW_LINES+=("$raw_line")
done < "$SOURCES_FILE"
collapse_block_lists
for raw in "${PP_LINES[@]}"; do
  line="${raw%$'\r'}"
  [[ "$line" =~ ^[[:space:]]*# ]] && continue
  # A non-indented `key:` line starts a new top-level family block.
  if [[ "$line" =~ ^([A-Za-z0-9_]+)[[:space:]]*:[[:space:]]*$ ]]; then
    TOP_KEY="${BASH_REMATCH[1]}"
    continue
  fi
  [[ "$TOP_KEY" == "$FAMILY" ]] || continue
  if [[ -z "$VERSION" && "$line" =~ ^[[:space:]]*version[[:space:]]*:[[:space:]]*(.+)$ ]]; then
    VERSION="$(strip_value "${BASH_REMATCH[1]}")"; continue
  fi
  # #339 P8-3: the FAMILY-level `executables:` list (a family shipping more than one
  # executable, e.g. kiwix_tools: [kiwix-serve, kiwix-manage, kiwix-search]). Only
  # meaningful before the `builds:` list starts ($idx -lt 0).
  if [[ $idx -lt 0 && -z "$FAMILY_EXECUTABLES" && "$line" =~ ^[[:space:]]*executables[[:space:]]*:[[:space:]]*(.+)$ ]]; then
    FAMILY_EXECUTABLES="$(strip_value "${BASH_REMATCH[1]}")"; continue
  fi
  if [[ "$line" =~ ^[[:space:]]*-[[:space:]]*os[[:space:]]*:[[:space:]]*(.+)$ ]]; then
    idx=$((idx + 1))
    B_OS[$idx]="$(strip_value "${BASH_REMATCH[1]}")"
    continue
  fi
  if [[ $idx -ge 0 && "$line" =~ ^[[:space:]]+([A-Za-z0-9_]+)[[:space:]]*:[[:space:]]*(.+)$ ]]; then
    key="${BASH_REMATCH[1]}"
    val="$(strip_value "${BASH_REMATCH[2]}")"
    case "$key" in
      arch) B_ARCH[$idx]="$val" ;;
      backend) B_BACKEND[$idx]="$val" ;;
      url) B_URL[$idx]="$val" ;;
      sha256) B_SHA[$idx]="$(echo "$val" | tr '[:upper:]' '[:lower:]')" ;;
      extract_to) B_EXTRACT[$idx]="$val" ;;
      runtime_files) B_RUNTIME[$idx]="$val" ;;
    esac
  fi
done

[[ -z "$VERSION" ]] && { echo "runtime-sources.yaml: missing $FAMILY.version (is the $FAMILY block present?)" >&2; exit 2; }

# #516: the DRIVE's yaml wins over the repo's, so on a drive whose manifests predate a pin bump
# this re-installs the OLD pin. Say so: refreshing the drive's manifests (prepare-drive) comes first.
family_version() {
  local file="$1" fam="$2" top="" ln
  while IFS= read -r ln || [[ -n "$ln" ]]; do
    ln="${ln%$'\r'}"
    [[ "$ln" =~ ^[[:space:]]*# ]] && continue
    if [[ "$ln" =~ ^([A-Za-z0-9_]+)[[:space:]]*:[[:space:]]*$ ]]; then top="${BASH_REMATCH[1]}"; continue; fi
    if [[ "$top" == "$fam" && "$ln" =~ ^[[:space:]]+version[[:space:]]*:[[:space:]]*(.+)$ ]]; then
      strip_value "${BASH_REMATCH[1]}"; return
    fi
  done < "$file"
}
REPO_SOURCES="$REPO_ROOT/model-manifests/runtime-sources.yaml"
if [[ -f "$REPO_SOURCES" && ! "$SOURCES_FILE" -ef "$REPO_SOURCES" ]]; then
  REPO_VERSION="$(family_version "$REPO_SOURCES" "$FAMILY")"
  if [[ -n "$REPO_VERSION" && "$REPO_VERSION" != "$VERSION" ]]; then
    echo "Note: the drive's runtime-sources.yaml pins $FAMILY $VERSION; this repo pins $REPO_VERSION." >&2
    echo "      To move the drive to the repo's pin, refresh its manifests first (prepare-drive), then run fetch-runtime again." >&2
  fi
fi

# --- Select the build (os + arch [+ backend]); default = first os/arch match
# (vulkan on win/linux, metal on mac since Phase 14).
# Explicit --os without --arch = cross-provisioning: take that OS's first build (any arch).
SEL=-1
# A C-style loop, never `seq 0 $idx`: for a family with no build (idx=-1) BSD seq counts DOWN,
# 0 then -1, so macOS read an unset B_OS[0] and died under set -u with exit 1, not 2 (#767).
for (( i = 0; i <= idx; i++ )); do
  [[ "${B_OS[$i]}" == "$OS" ]] || continue
  if [[ $OS_EXPLICIT -eq 0 || $ARCH_EXPLICIT -eq 1 ]]; then
    [[ "${B_ARCH[$i]}" == "$ARCH" ]] || continue
  fi
  [[ -n "$BACKEND" && "${B_BACKEND[$i]}" != "$BACKEND" ]] && continue
  SEL=$i; break
done
if [[ $SEL -lt 0 ]]; then
  echo "No runtime build for os=$OS arch=$ARCH${BACKEND:+ backend=$BACKEND}. Try --os/--arch/--backend overrides." >&2
  exit 2
fi

# A selected build must carry every field the plan needs; a silent miss here would
# disable verification forever (the audited C1 bug), so fail loudly instead.
for required in url sha256 extract_to; do
  case "$required" in
    url) v="${B_URL[$SEL]:-}" ;;
    sha256) v="${B_SHA[$SEL]:-}" ;;
    extract_to) v="${B_EXTRACT[$SEL]:-}" ;;
  esac
  if [[ -z "$v" ]]; then
    echo "runtime-sources.yaml: selected build ($OS/$ARCH) is missing '$required'." >&2
    exit 2
  fi
done

# Escape guard (M18): runtime-sources.yaml on the DRIVE is user-writable; a tampered
# extract_to must not be able to write outside the drive root (mirrors TS planRuntimeDownload).
case "${B_EXTRACT[$SEL]}" in
  *..*|/*|[A-Za-z]:*)
    echo "runtime-sources.yaml: extract_to escapes the drive root: ${B_EXTRACT[$SEL]}" >&2
    exit 2
    ;;
esac

EXTRACT_TO="$TARGET/${B_EXTRACT[$SEL]}"
# #339 P8-3: EXECUTABLE LIST per family (mirrors assets.ts SIDECAR_FAMILY_SPECS +
# planRuntimeDownload) — the primary base name per family, plus the yaml's family-level
# `executables:` when present (its first entry is always the primary; llama_cpp/whisper_cpp
# declare no `executables:`, so their required set stays the single binary it always was).
PRIMARY_BASE="llama-server"
[[ "$FAMILY" == "whisper_cpp" ]] && PRIMARY_BASE="whisper-cli"
[[ "$FAMILY" == "kiwix_tools" ]] && PRIMARY_BASE="kiwix-serve"
# #729: executables the release archive carries that an install never keeps — the same list as
# assets.ts SIDECAR_FAMILY_SPECS `neverInstalled` (script-drift.test.ts). llama-connect is what
# `llama-server --connect` starts (a peer-to-peer tunnel, v0.8.0+); llama-server looks for it beside
# itself first. The list wins over the yaml's `executables:`, as in planRuntimeDownload.
declare -a NEVER_INSTALLED_BASES=()
[[ "$FAMILY" == "llama_cpp" ]] && NEVER_INSTALLED_BASES=(llama-connect)
# Names compare without case, as NTFS and APFS compare them (assets.ts and the .ps1 twin do the same).
lower() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }
# remove_never_installed — remove them from the install dir: after a fresh extraction, and on the skip
# path, so an install made before this rule (or copied by hand) loses its copy too. `-L` catches a
# dangling link, which `-e` follows and misses. A dry run only says what it would remove.
remove_never_installed() {
  local base left_out
  for base in ${NEVER_INSTALLED_BASES[@]+"${NEVER_INSTALLED_BASES[@]}"}; do
    left_out="$base"
    if [[ "${B_OS[$SEL]}" == "win" ]]; then left_out="$base.exe"; fi
    if [[ -e "$EXTRACT_TO/$left_out" || -L "$EXTRACT_TO/$left_out" ]]; then
      if [[ $DRY_RUN -eq 1 ]]; then echo "  would leave out: $left_out"; continue; fi
      rm -f "$EXTRACT_TO/$left_out" || { echo "  FAIL: could not remove $left_out from $EXTRACT_TO" >&2; exit 1; }
      echo "  left out: $left_out"
    fi
  done
}
declare -a EXEC_BASES=("$PRIMARY_BASE")
if [[ -n "$FAMILY_EXECUTABLES" ]]; then
  while IFS= read -r e; do
    already=0
    for existing in "${EXEC_BASES[@]}"; do [[ "$existing" == "$e" ]] && already=1 && break; done
    excluded=0
    for never in ${NEVER_INSTALLED_BASES[@]+"${NEVER_INSTALLED_BASES[@]}"}; do
      if [[ "$(lower "$never")" == "$(lower "$e")" ]]; then excluded=1; break; fi
    done
    [[ $already -eq 0 && $excluded -eq 0 ]] && EXEC_BASES+=("$e")
  done < <(flow_list_items "$FAMILY_EXECUTABLES")
fi
# Binary name(s) follow the SELECTED build's OS (mirrors assets.ts sidecarBinaryName).
# BIN_BASE/BIN_NAME/BIN_PATH keep referring to the PRIMARY only — the flatten step below
# locates the archive's nested folder by the primary executable, exactly as before.
BIN_BASE="$PRIMARY_BASE"
BIN_NAME="$BIN_BASE"; [[ "${B_OS[$SEL]}" == "win" ]] && BIN_NAME="$BIN_BASE.exe"
BIN_PATH="$EXTRACT_TO/$BIN_NAME"
declare -a EXEC_NAMES=()
for b in "${EXEC_BASES[@]}"; do
  if [[ "${B_OS[$SEL]}" == "win" ]]; then EXEC_NAMES+=("$b.exe"); else EXEC_NAMES+=("$b"); fi
done
declare -a RUNTIME_FILE_NAMES=()
RUNTIME_FILES_RAW="${B_RUNTIME[$SEL]:-}"
if [[ -n "$RUNTIME_FILES_RAW" ]]; then
  while IFS= read -r f; do RUNTIME_FILE_NAMES+=("$f"); done < <(flow_list_items "$RUNTIME_FILES_RAW")
fi
# Every file this install must produce: the executables, then the build's runtime_files
# (verbatim — they already carry their own extension). Mirrors assets.ts requiredInstallFiles.
declare -a REQUIRED_FILE_NAMES=("${EXEC_NAMES[@]}")
if [[ ${#RUNTIME_FILE_NAMES[@]} -gt 0 ]]; then REQUIRED_FILE_NAMES+=("${RUNTIME_FILE_NAMES[@]}"); fi
MARKER_PATH="$EXTRACT_TO/.hilbertraum-runtime.json"
URL="${B_URL[$SEL]}"
SHA="${B_SHA[$SEL]}"

echo "Fetch runtime -> $TARGET"
echo "  build: ${B_OS[$SEL]}/${B_ARCH[$SEL]} ${B_BACKEND[$SEL]} @ $VERSION"
echo "  url:   $URL"
echo "  into:  $EXTRACT_TO"
echo "  files: ${REQUIRED_FILE_NAMES[*]}"

# marker_hash_for KEY MARKER_PATH — the recorded hash for one marker key (parsed with sed,
# no jq dep; the marker is written by us as flat single-line JSON).
marker_hash_for() {
  sed -n 's/.*"binaries":{[^}]*"'"$1"'":"\([a-fA-F0-9]\{64\}\)".*/\1/p' "$2" | tr '[:upper:]' '[:lower:]'
}

# marker_recorded_names MARKER_PATH — every key of the marker's `binaries` map, one per line (#998; the
# marker is our own flat single-line JSON, whose keys hold no `"`, `,` or `}`). The markers end without a
# newline, so one is added: `read` drops a last line that has none.
marker_recorded_names() {
  { sed -n 's/.*"binaries":{\([^}]*\)}.*/\1/p' "$1"; printf '\n'; } | tr ',' '\n' | sed -n 's/^"\(.*\)":"[a-fA-F0-9]\{64\}"$/\1/p'
}

# marker_readable MARKER_PATH — #1028: is the install marker one the app can read? The app refuses a marker that is
# there but is no marker (cut short by an interrupted copy, garbled) as damaged engine files, so a re-run must fetch
# the engine again instead of skipping it, in any mode. The rule is the app's (assets.ts readRuntimeMarkerState):
#  - at most 64 KiB here (the app reads up to 1 MiB; no writer writes more than a few KB — the b12110 Windows copy
#    records 52 files in about 5 KB — and this reader is plain bash, slow on a large text, so a larger marker is fetched
#    again at once instead of read through), with no NUL byte (a bash variable cannot hold one, so the bytes are
#    counted first);
#  - after one leading UTF-8 byte-order mark, exactly ONE JSON object (RFC 8259), read by the small reader below:
#    nothing before or after it but blanks, no raw control byte inside a string, only JSON's escapes, numbers in
#    JSON's form, no trailing comma, no comment;
#  - its own (top-level) version, backend, os and arch are strings, and its own `binaries`, when there, is an object
#    whose every value is a SHA-256 (64 hex digits). As in JavaScript, the last of two same-named fields counts.
#    Any other field, nested objects and arrays included, is read past (a later release may add one).
# On any doubt it says no: a needless download is the safe side. Two such cases (both never written): a name written
# with a backslash-u escape is not taken for the plain one, and a map naming one file twice is judged by both.
# The reader runs in a subshell under LC_ALL=C (final review): bytes, not characters, whatever the caller's locale —
# under a UTF-8 locale [[:cntrl:]] also matches the C1 controls (U+0080-U+009F), which JSON and the app accept, and
# taking one character at a time costs a walk from the start — and the caller's locale and BASH_REMATCH stay as they
# were. Parameter expansion, `[[ == ]]` patterns and `case` only: no `=~` (#765), no sed (BSD sed on macOS differs), no
# character ranges, so macOS's bash 3.2 runs it as bash 5 does. Mirrored by fetch-runtime.ps1 ($ReadInstallMarker).
# It also leaves the object's own version and backend in MARKER_VERSION and MARKER_BACKEND (escapes as written), for
# the skip decision (code review CR-4: never the last `"version":"…"` on the line, which a field nested in a later one
# can be).
marker_readable() {
  local found
  MARKER_VERSION=''
  MARKER_BACKEND=''
  found="$(export LC_ALL=C; marker_read_bytes "$1")" || return 1
  # marker_read_bytes prints the version, a line break, the backend, a line break and a dot (so an empty backend
  # survives the command substitution's trimming).
  MARKER_VERSION="${found%%$'\n'*}"
  found="${found#*$'\n'}"
  MARKER_BACKEND="${found%%$'\n'*}"
  return 0
}

# marker_read_bytes MARKER_PATH — marker_readable's reader (#1028), run under LC_ALL=C in a subshell: 0 and the
# object's own version and backend on stdout when the marker is one the app reads, else 1.
marker_read_bytes() {
  local bytes kept text bom len pos=0 c state=value stack='' top where='' key='' str='' in_map=0 map=absent object=0
  local f_version=0 f_backend=0 f_os=0 f_arch=0 is_string
  bytes="$(wc -c < "$1")" || return 1
  kept="$(tr -d '\000' < "$1" | wc -c)" || return 1
  [[ $((bytes)) -le 65536 && $((bytes)) -eq $((kept)) ]] || return 1
  text="$(cat "$1")" || return 1
  bom=$'\xef\xbb\xbf'
  text="${text#"$bom"}"
  len=${#text}
  while [[ $pos -lt $len ]]; do
    c="${text:pos:1}"
    case "$c" in
      ' ' | $'\t' | $'\n' | $'\r')
        pos=$((pos + 1))
        continue
        ;;
    esac
    case "$state" in
      value | value-or-close)
        if [[ "$state" == value-or-close && "$c" == ']' ]]; then
          stack="${stack%?}"
          state=after
          pos=$((pos + 1))
          continue
        fi
        # Where this value sits: one of the object's own fields (`top`), an entry of its own map (`map`), or deeper.
        where=''
        if [[ "$stack" == '{' ]]; then
          where=top
        elif [[ "$stack" == '{{' && $in_map -eq 1 ]]; then
          where=map
        elif [[ -z "$stack" && "$c" != '{' ]]; then
          return 1 # the marker itself is not an object
        fi
        is_string=0
        case "$c" in
          '{')
            [[ -n "$stack" ]] || object=1
            stack="$stack{"
            state=key-or-close
            pos=$((pos + 1))
            ;;
          '[')
            stack="$stack["
            state=value-or-close
            pos=$((pos + 1))
            ;;
          '"')
            marker_json_string || return 1
            is_string=1
            state=after
            ;;
          t | f | n)
            case "$c" in
              t) [[ "${text:pos:4}" == true ]] || return 1; pos=$((pos + 4)) ;;
              f) [[ "${text:pos:5}" == false ]] || return 1; pos=$((pos + 5)) ;;
              n) [[ "${text:pos:4}" == null ]] || return 1; pos=$((pos + 4)) ;;
            esac
            state=after
            ;;
          - | [0123456789])
            marker_json_number || return 1
            state=after
            ;;
          *) return 1 ;;
        esac
        if [[ "$where" == top ]]; then
          case "$key" in
            version)
              f_version=$is_string
              MARKER_VERSION="$str"
              ;;
            backend)
              f_backend=$is_string
              MARKER_BACKEND="$str"
              ;;
            os) f_os=$is_string ;;
            arch) f_arch=$is_string ;;
            binaries)
              if [[ "$c" == '{' ]]; then
                map=ok
                in_map=1
              else
                map=bad
              fi
              ;;
          esac
        elif [[ "$where" == map ]]; then
          if [[ $is_string -ne 1 || ${#str} -ne 64 || "$str" == *[!0123456789abcdefABCDEF]* ]]; then map=bad; fi
        fi
        ;;
      key | key-or-close)
        if [[ "$state" == key-or-close && "$c" == '}' ]]; then
          if [[ "$stack" == '{{' && $in_map -eq 1 ]]; then in_map=0; fi
          stack="${stack%?}"
          state=after
          pos=$((pos + 1))
          continue
        fi
        [[ "$c" == '"' ]] || return 1
        marker_json_string || return 1
        key="$str"
        state=colon
        ;;
      colon)
        [[ "$c" == : ]] || return 1
        state=value
        pos=$((pos + 1))
        ;;
      after)
        [[ -n "$stack" ]] || return 1 # anything after the object
        top="${stack#"${stack%?}"}"
        case "$c" in
          ,)
            if [[ "$top" == '{' ]]; then state=key; else state=value; fi
            ;;
          '}')
            [[ "$top" == '{' ]] || return 1
            if [[ "$stack" == '{{' && $in_map -eq 1 ]]; then in_map=0; fi
            stack="${stack%?}"
            ;;
          ']')
            [[ "$top" == '[' ]] || return 1
            stack="${stack%?}"
            ;;
          *) return 1 ;;
        esac
        pos=$((pos + 1))
        ;;
    esac
  done
  [[ $object -eq 1 && -z "$stack" && "$state" == after ]] || return 1
  [[ $f_version -eq 1 && $f_backend -eq 1 && $f_os -eq 1 && $f_arch -eq 1 && "$map" != bad ]] || return 1
  printf '%s\n%s\n.' "$MARKER_VERSION" "$MARKER_BACKEND"
}

# marker_json_string — marker_readable's string reader (#1028): the JSON string that starts at $pos in $text, its
# text (escapes as written) into $str, $pos past its closing quote. Fails on a raw control byte, an escape JSON does
# not have, or no closing quote.
marker_json_string() {
  local rest run esc
  str=''
  pos=$((pos + 1))
  while :; do
    rest="${text:pos}"
    run=${rest%%[\"\\]*}
    [[ "$run" != "$rest" ]] || return 1
    [[ "$run" != *[[:cntrl:]]* ]] || return 1
    str="$str$run"
    pos=$((pos + ${#run}))
    if [[ "${text:pos:1}" == '"' ]]; then
      pos=$((pos + 1))
      return 0
    fi
    esc="${text:pos+1:1}"
    case "$esc" in
      '"' | '\' | / | b | f | n | r | t)
        str="$str\\$esc"
        pos=$((pos + 2))
        ;;
      u)
        [[ "${text:pos+2:4}" == [0123456789abcdefABCDEF][0123456789abcdefABCDEF][0123456789abcdefABCDEF][0123456789abcdefABCDEF] ]] || return 1
        str="$str\\u${text:pos+2:4}"
        pos=$((pos + 6))
        ;;
      *) return 1 ;;
    esac
  done
}

# marker_json_number — marker_readable's number reader (#1028): a JSON number at $pos (`-`? then `0` or a digit run
# without a leading zero, an optional fraction, an optional exponent), $pos past it.
marker_json_number() {
  if [[ "${text:pos:1}" == - ]]; then pos=$((pos + 1)); fi
  if [[ "${text:pos:1}" == 0 ]]; then
    pos=$((pos + 1))
  elif [[ "${text:pos:1}" == [123456789] ]]; then
    while [[ "${text:pos:1}" == [0123456789] ]]; do pos=$((pos + 1)); done
  else
    return 1
  fi
  if [[ "${text:pos:1}" == . ]]; then
    pos=$((pos + 1))
    [[ "${text:pos:1}" == [0123456789] ]] || return 1
    while [[ "${text:pos:1}" == [0123456789] ]]; do pos=$((pos + 1)); done
  fi
  if [[ "${text:pos:1}" == [eE] ]]; then
    pos=$((pos + 1))
    if [[ "${text:pos:1}" == [+-] ]]; then pos=$((pos + 1)); fi
    [[ "${text:pos:1}" == [0123456789] ]] || return 1
    while [[ "${text:pos:1}" == [0123456789] ]]; do pos=$((pos + 1)); done
  fi
  return 0
}

# installed_file_names DIR — #998: every file an install holds, relative to it with `/` (the app's
# markerBinaryKey form): the files and the links that resolve to a file (a link by its own name, never
# entered; a link to a folder or a dangling one is not recorded, with a line), without the marker, without
# macOS metadata (`._*`, `__MACOSX`, `.DS_Store`) and, at the top, without the cpu/ safety net or a net swap
# the app left inside (cpu.new, cpu.old), which carry markers of their own. Mirrors runtime-download.ts
# installedFileKeys. One per line, sorted.
installed_file_names() {
  local name
  ( cd "$1" && find . -mindepth 1 \( -path ./cpu -o -path ./cpu.new -o -path ./cpu.old -o -path ./.hilbertraum-runtime.json \) -prune -o \( -type f -o -type l \) -print ) |
    sed 's|^\./||' | LC_ALL=C sort | while IFS= read -r name; do
      case "/$name" in */__MACOSX/*|*/._*|*/.DS_Store) continue ;; esac
      if [[ -L "$1/$name" && ! -f "$1/$name" ]]; then
        echo "  not recorded (a link that is not a file): $name" >&2
        continue
      fi
      printf '%s\n' "$name"
    done
}

# Idempotent skip is MARKER-based (Phase 14, mirrors assets.ts runtimeInstallCurrent):
# "binary exists" alone would silently keep a CPU-era build in place after the default
# became vulkan. Skip only when EVERY required file is present (#339 P8-3 — a half-installed
# multi-file family is not "present", mirrors assets.ts runtimeBinaryPresent) and
# .hilbertraum-runtime.json matches the selected version+backend — and, under --commercial,
# records a hash for EVERY required file (a hashless legacy marker is re-fetched, #234).
if [[ -f "$BIN_PATH" ]]; then
  SKIP=0
  WHY="install marker is missing or differs"
  # #873: the marker's version when it is newer than the pin (kept unless --commercial / --allow-downgrade).
  NEWER_KEPT=""
  NEWER_REPLACED=""
  ALL_PRESENT=1
  for f in "${REQUIRED_FILE_NAMES[@]}"; do
    [[ -f "$EXTRACT_TO/$f" ]] || { ALL_PRESENT=0; break; }
  done
  if [[ $ALL_PRESENT -eq 0 ]]; then
    WHY="one or more required files are missing"
  # #1028: a marker that is there but is no marker the app can read is as good as none (the default WHY): the app
  # refuses that copy, so it is fetched again — never skipped, never kept as newer — before any field is read.
  elif [[ -f "$MARKER_PATH" ]] && marker_readable "$MARKER_PATH"; then
    # The object's own version and backend, as marker_readable read them (code review CR-4).
    m_version="$MARKER_VERSION"
    m_backend="$MARKER_BACKEND"
    if [[ "$(compare_runtime_versions "$m_version" "$VERSION")" == "1" ]]; then
      # Whatever its backend: the app's relation ignores the backend too (runtimeInstallRelation).
      if [[ $COMMERCIAL -eq 1 ]]; then NEWER_REPLACED="$m_version"
      elif [[ $ALLOW_DOWNGRADE -eq 0 ]]; then NEWER_KEPT="$m_version"
      fi
    elif [[ "$m_version" == "$VERSION" && "$m_backend" == "${B_BACKEND[$SEL]}" ]]; then
      SKIP=1
      # #998: a file the install's own marker records that is gone (an antivirus took it after the
      # install) makes it a damaged install: re-fetched, in any mode (the app's engineFolderComplete).
      RECORDED_MISSING=""
      while IFS= read -r key; do
        [[ -n "$key" ]] || continue
        [[ -f "$EXTRACT_TO/$key" ]] || RECORDED_MISSING="${RECORDED_MISSING:+$RECORDED_MISSING, }$key"
      done < <(marker_recorded_names "$MARKER_PATH")
      if [[ -n "$RECORDED_MISSING" ]]; then
        SKIP=0
        WHY="a file its install marker records is missing ($RECORDED_MISSING)"
      elif [[ $COMMERCIAL -eq 1 ]]; then
        for f in "${REQUIRED_FILE_NAMES[@]}"; do
          m_hash="$(marker_hash_for "$f" "$MARKER_PATH")"
          if ! is_real_sha "$m_hash"; then
            SKIP=0
            WHY="install marker records no binary hash for one or more required files (legacy) — commercial mode"
            break
          fi
        done
      fi
    fi
  fi
  if [[ $SKIP -eq 1 ]]; then
    echo "  skip ($BIN_NAME already installed: $VERSION/${B_BACKEND[$SEL]} per .hilbertraum-runtime.json)"
    remove_never_installed
    exit 0
  fi
  if [[ -n "$NEWER_KEPT" ]]; then
    echo "  skip ($BIN_NAME $NEWER_KEPT is newer than this drive's pin $VERSION, installed by the app; pass --allow-downgrade to replace it)"
    remove_never_installed
    exit 0
  fi
  if [[ -n "$NEWER_REPLACED" ]]; then
    echo "  commercial: replacing the newer $NEWER_REPLACED with the pinned $VERSION (a sold drive carries its app's pin)"
  fi
  echo "  $BIN_NAME present but $WHY — re-fetching $VERSION/${B_BACKEND[$SEL]}"
fi

# --commercial: refuse a placeholder hash BEFORE any download (#234) — an unverifiable
# archive must never be extracted onto a sold drive, dry run or not.
if [[ $COMMERCIAL -eq 1 ]] && ! is_real_sha "$SHA"; then
  echo "  commercial: placeholder sha256 for ${B_OS[$SEL]}/${B_ARCH[$SEL]} ${B_BACKEND[$SEL]} @ $VERSION — refusing to fetch (nothing downloaded, no marker written)" >&2
  exit 1
fi
[[ $DRY_RUN -eq 1 ]] && { echo "(dry run — nothing will be downloaded)"; exit 0; }

mkdir -p "$EXTRACT_TO"
# Archive name from the URL basename so a .tar.gz (the macOS/Linux release format) is
# not saved — and mis-extracted — as a .zip. Strip a trailing ?query / #fragment after the
# basename: an HF-style URL (`...file.tar.gz?download=true`, the convention the model manifests
# already use everywhere) would otherwise yield 'file.tar.gz?download=true', which fails the
# `*.tar.gz` extraction glob below and gets fed to unzip. fetch-runtime.ps1 ([uri].AbsolutePath)
# and assets.ts (split('?')[0]) already strip it; the sh variant had drifted (F-19, full audit
# 2026-07-16). All current runtime-sources URLs are query-free, so this is latent-until-edit.
ARCHIVE_NAME="$(basename "$URL")"
ARCHIVE_NAME="${ARCHIVE_NAME%%\?*}"
ARCHIVE_NAME="${ARCHIVE_NAME%%#*}"
[[ -z "$ARCHIVE_NAME" ]] && ARCHIVE_NAME="$BIN_BASE-$VERSION-${B_OS[$SEL]}-${B_ARCH[$SEL]}.zip"
ARCHIVE="$EXTRACT_TO/$ARCHIVE_NAME"

if command -v curl >/dev/null 2>&1; then
  # Schannel curl (Windows/git-bash): corporate proxies often block CRL/OCSP, failing
  # with CRYPT_E_NO_REVOCATION_CHECK. Best-effort revocation only on that backend;
  # artifact integrity is enforced by the SHA-256 pin below. curl_resilient retries +
  # resumes a dropped transfer so a flaky connection doesn't lose the whole archive.
  CURL_EXTRA=""
  curl --version 2>/dev/null | head -n1 | grep -qi schannel && CURL_EXTRA="--ssl-revoke-best-effort"
  curl_resilient "$URL" "$ARCHIVE" "$CURL_EXTRA" || { echo "curl failed after retries" >&2; exit 1; }
elif command -v wget >/dev/null 2>&1; then
  wget -c -O "$ARCHIVE" "$URL"
else
  echo "No downloader found (need curl or wget)." >&2; exit 3
fi

ARCHIVE_VERIFIED=0
if is_real_sha "$SHA"; then
  ACTUAL="$(sha256_of "$ARCHIVE")"
  if [[ "$ACTUAL" != "$SHA" ]]; then
    echo "  FAIL: archive checksum mismatch (expected $SHA, got $ACTUAL) — deleting" >&2
    rm -f "$ARCHIVE"; exit 1
  fi
  echo "  archive VERIFIED"
  ARCHIVE_VERIFIED=1
else
  echo "  archive UNVERIFIED (placeholder hash) — verify after a real release bump"
fi

# Remove the previous install (if any) BEFORE extracting. Extraction over an existing
# build must never mix files from two builds — and on the nesting mac/linux tarballs a
# stale root llama-server would satisfy the flatten guard below, leaving the OLD binary
# in place while a fresh marker claims the new build (audit fix: the cpu->vulkan upgrade
# path). The cpu/ safety net and the just-downloaded archive survive; the stale marker
# dies with the old build, so a failed extraction cannot leave a lying marker behind.
find "$EXTRACT_TO" -mindepth 1 -maxdepth 1 \
  ! -name "$ARCHIVE_NAME" ! -name cpu -exec rm -rf {} +

# Extract: tar.gz via tar; zip via unzip (linux) / ditto (macOS).
case "$ARCHIVE_NAME" in
  *.tar.gz|*.tgz)
    # The archive goes in on stdin (#767): GNU tar reads a `C:` in an archive NAME as a remote
    # host, so under Git Bash `tar -xzf 'C:\…'` extracts nothing; GNU and BSD tar both read `-f -`.
    # tar's messages are kept: for a failure the link copies below cannot repair, they are the
    # only account of it.
    TAR_EXIT=0
    TAR_MESSAGES="$(tar -xzf - -C "$EXTRACT_TO" < "$ARCHIVE" 2>&1)" || TAR_EXIT=$?
    # The llama.cpp tarballs contain version SYMLINKS (lib*.so -> lib*.so.X.Y.Z), which
    # an exFAT/FAT32 drive cannot hold. Materialize each missing link as a COPY of its
    # target — the dynamic loader only needs the name to exist. Multi-pass, because
    # links can chain (libllama.so -> libllama.so.0 -> ...0.14.0).
    # The archive names both ends of a link, so neither may leave the extract dir: the extract_to
    # rule (M18). tar itself refuses such a member; the copy must not do what tar would not (#767).
    LINK_PAIRS=()
    while IFS= read -r pair; do
      [[ -n "$pair" ]] && LINK_PAIRS+=("$pair")
    done < <(tar -tvzf - < "$ARCHIVE" 2>/dev/null | sed -n 's/^l.*[[:space:]]\([^[:space:]]*\)[[:space:]]->[[:space:]]\([^[:space:]]*\)$/\1|\2/p')
    if [[ ${#LINK_PAIRS[@]} -gt 0 ]]; then
      for _pass in 1 2 3 4; do
        UNRESOLVED=0
        for pair in "${LINK_PAIRS[@]}"; do
          lnk="${pair%%|*}"; tgt="${pair#*|}"
          [[ -e "$EXTRACT_TO/$lnk" ]] && continue
          # The link's name, and its target read from the link's own directory, once `..` is resolved.
          outside=0
          for end in "$lnk" "$tgt"; do
            case "$end" in /*|\\*|[A-Za-z]:*) outside=1 ;; esac
          done
          if [[ $outside -eq 1 ]] || ! stays_inside "$lnk" || ! stays_inside "$(dirname "$lnk")/$tgt"; then
            echo "  FAIL: archive link $lnk -> $tgt points outside $EXTRACT_TO — not copied" >&2
            exit 1
          fi
          src="$EXTRACT_TO/$(dirname "$lnk")/$tgt"
          if [[ -f "$src" ]]; then cp -f "$src" "$EXTRACT_TO/$lnk"; else UNRESOLVED=$((UNRESOLVED + 1)); fi
        done
        [[ $UNRESOLVED -eq 0 ]] && break
      done
    fi
    # Those links make tar fail on FAT/exFAT (and on Windows) for every such archive, and the copies
    # are the repair. Any other failure (an archive tar cannot read, a member it could not write) is
    # real, and used to pass unseen until the binary check blamed the archive layout (#767). After a
    # failed tar every member the archive lists must be on disk; if one is not, or tar cannot list
    # the archive at all, the run fails with tar's own words.
    if [[ $TAR_EXIT -ne 0 ]]; then
      LIST_EXIT=0
      MEMBERS="$(tar -tzf - < "$ARCHIVE" 2>/dev/null)" || LIST_EXIT=$?
      LISTED=0
      MISSING_MEMBERS=""
      while IFS= read -r member; do
        [[ -n "$member" ]] || continue
        LISTED=$((LISTED + 1))
        [[ -e "$EXTRACT_TO/$member" ]] || MISSING_MEMBERS="${MISSING_MEMBERS:+$MISSING_MEMBERS, }$member"
      done <<< "$MEMBERS"
      if [[ $LIST_EXIT -ne 0 || $LISTED -eq 0 || -n "$MISSING_MEMBERS" ]]; then
        echo "  FAIL: tar could not extract $ARCHIVE_NAME (exit $TAR_EXIT):" >&2
        printf '%s\n' "$TAR_MESSAGES" | sed -e '/^[[:space:]]*$/d' -e 's/^/    /' >&2
        [[ -n "$MISSING_MEMBERS" ]] && echo "    not on disk after extraction: $MISSING_MEMBERS" >&2
        exit 1
      fi
    fi
    ;;
  *)
    if command -v unzip >/dev/null 2>&1; then
      unzip -o -q "$ARCHIVE" -d "$EXTRACT_TO"
    elif command -v ditto >/dev/null 2>&1; then
      ditto -x -k "$ARCHIVE" "$EXTRACT_TO"
    else
      echo "No unzip tool found (need unzip or ditto)." >&2; exit 3
    fi
    ;;
esac
rm -f "$ARCHIVE"

# Flatten: the macOS/Linux tarballs nest everything under llama-<tag>/ — move the
# binary's directory contents up so llama-server sits at the extract_to root, where
# services/runtime/sidecar.ts resolves it.
if [[ ! -f "$BIN_PATH" ]]; then
  # Exclude the cpu/ safety-net subdir from the search: when the DEFAULT build is being
  # (re)fetched into <os>/ and <os>/cpu/ already holds its own llama-server, the flatten
  # must not mistake the safety net for the freshly extracted nested binary. Matched by a
  # quoted `case` prefix, not `find -path`: its pattern reads the `[` of a drive path such as
  # `Kit [1]` as a bracket expression, so the prune never fired and the flatten could move the
  # safety net's files up instead (#767).
  FOUND=""
  while IFS= read -r cand; do
    case "$cand" in "$EXTRACT_TO/cpu/"*) continue ;; esac
    FOUND="$cand"; break
  done < <(find "$EXTRACT_TO" -type f -name "$BIN_NAME")
  if [[ -n "$FOUND" ]]; then
    SRC_DIR="$(dirname "$FOUND")"
    if [[ "$SRC_DIR" != "$EXTRACT_TO" ]]; then
      find "$SRC_DIR" -mindepth 1 -maxdepth 1 -exec mv -f {} "$EXTRACT_TO"/ \;
      find "$EXTRACT_TO" -mindepth 1 -type d -empty -delete 2>/dev/null || true
    fi
  fi
fi

if [[ ! -f "$BIN_PATH" ]]; then
  echo "  FAIL: $BIN_NAME not found under $EXTRACT_TO after extraction — the release archive layout may have changed." >&2
  exit 1
fi

# #729: leave out what the family never keeps (mirrors runtime-download.ts install). A file that
# cannot be removed stops the run here, before a marker claims the install.
remove_never_installed

# #339 P8-3: post-extract completeness check — EVERY required file (every declared
# executable + runtime file), not just the primary. Mirrors assets.ts requiredInstallFiles /
# the app's own post-extract check (runtime-download.ts installOne). A half-installed
# multi-file family (e.g. the kiwix ICU DLLs left behind by a differently-shaped archive)
# must fail loudly instead of writing a marker that claims a complete install.
declare -a MISSING_REQUIRED=()
for f in "${REQUIRED_FILE_NAMES[@]}"; do
  [[ -f "$EXTRACT_TO/$f" ]] || MISSING_REQUIRED+=("$f")
done
if [[ ${#MISSING_REQUIRED[@]} -gt 0 ]]; then
  echo "  FAIL: required file(s) missing under $EXTRACT_TO after extraction: ${MISSING_REQUIRED[*]}" >&2
  exit 1
fi

for exe in "${EXEC_NAMES[@]}"; do
  chmod +x "$EXTRACT_TO/$exe" 2>/dev/null || true
done

# Record exactly which build is installed (mirrors assets.ts writeRuntimeMarker). The
# `binaries` map records the SHA-256 of EVERY file the install holds (#998: the required ones
# first, then every other file the archive put here, never cpu/, cpu.new or cpu.old), keyed
# exactly like markerBinaryKey — the path relative to the extract dir, `/` separators — so the
# app can re-hash each executable immediately before spawn (binary-verifier.ts, #234), judge
# the copy complete by its own list (engineFolderComplete) and the sell gate can check every
# file. ALL-OR-NOTHING (#339 P8-3, mirrors runtime-download.ts stageEngineInstall): only a
# VERIFIED archive earns hashes at all, and a hashing failure on ANY file drops the whole map
# rather than writing a partial one — the verifier and the sell gate must never disagree about
# one install.
declare -a RECORD_NAMES=("${REQUIRED_FILE_NAMES[@]}")
while IFS= read -r f; do
  [[ -n "$f" ]] || continue
  known=0
  for r in "${RECORD_NAMES[@]}"; do [[ "$r" == "$f" ]] && { known=1; break; }; done
  [[ $known -eq 1 ]] || RECORD_NAMES+=("$f")
done < <(installed_file_names "$EXTRACT_TO")
if [[ $ARCHIVE_VERIFIED -eq 1 ]]; then
  ALL_HASHED=1
  declare -a ENTRIES=()
  for f in "${RECORD_NAMES[@]}"; do
    if h="$(sha256_of "$EXTRACT_TO/$f" 2>/dev/null)"; then
      key="$(printf '%s' "$f" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')"
      ENTRIES+=("\"$key\":\"$h\"")
    else
      ALL_HASHED=0
      break
    fi
  done
  if [[ $ALL_HASHED -eq 1 ]]; then
    BIN_MAP="$(IFS=,; echo "${ENTRIES[*]}")"
    printf '{"version":"%s","backend":"%s","os":"%s","arch":"%s","binaries":{%s}}' \
      "$VERSION" "${B_BACKEND[$SEL]}" "${B_OS[$SEL]}" "${B_ARCH[$SEL]}" "$BIN_MAP" > "$MARKER_PATH"
  else
    printf '{"version":"%s","backend":"%s","os":"%s","arch":"%s"}' \
      "$VERSION" "${B_BACKEND[$SEL]}" "${B_OS[$SEL]}" "${B_ARCH[$SEL]}" > "$MARKER_PATH"
    echo "  marker written WITHOUT binary hashes (could not hash every installed file) — the sell gate refuses this install"
  fi
else
  printf '{"version":"%s","backend":"%s","os":"%s","arch":"%s"}' \
    "$VERSION" "${B_BACKEND[$SEL]}" "${B_OS[$SEL]}" "${B_ARCH[$SEL]}" > "$MARKER_PATH"
  echo "  marker written WITHOUT a binary hash (archive unverified) — the sell gate refuses this install"
fi
echo "  extracted + chmod +x ${EXEC_NAMES[*]} (+ .hilbertraum-runtime.json install marker)"
exit 0