Skip to content

AI, fully local on your computer.

51.7 KB
Raw Blame
#requires -Version 5.1
<#
.SYNOPSIS
  Download + verify the llama.cpp sidecar binary onto a prepared drive (Phase 12).

.DESCRIPTION
  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). 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[.exe] 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. -AllowDowngrade 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.

.PARAMETER Target
  The prepared drive root (e.g. E:\). Required.

.PARAMETER Os
  Override the host OS (win/mac/linux).

.PARAMETER Arch
  Override the host arch (x64/arm64).

.PARAMETER Backend
  Override the backend (e.g. cpu, vulkan, metal) -- default is the first build listed
  for the os/arch (vulkan on win/linux, metal on mac). -Backend cpu fetches the pure-CPU
  safety net into runtime/llama.cpp/<os>/cpu/.

.PARAMETER Family
  Which asset family to fetch from runtime-sources.yaml: llama_cpp (default; the
  llama-server binary), whisper_cpp (the whisper-cli transcriber, Phase 36 -- 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 -WithAssets, 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).

.PARAMETER Commercial
  Drive-builder mode: refuse a placeholder hash before any download, re-fetch a hashless
  (legacy) install marker, and replace an engine newer than the pin with the pin.
  build-commercial-drive passes this on every run.

.PARAMETER AllowDowngrade
  Replace 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.

.PARAMETER DryRun
  Print the plan and download nothing (a -Commercial placeholder refusal still applies).

.EXAMPLE
  .\scripts\fetch-runtime.ps1 -Target E:\
  .\scripts\fetch-runtime.ps1 -Target E:\ -Os linux -Arch x64 -DryRun
  .\scripts\fetch-runtime.ps1 -Target E:\ -Family whisper_cpp
  .\scripts\fetch-runtime.ps1 -Target E:\ -Family kiwix_tools
  .\scripts\fetch-runtime.ps1 -Target E:\ -Family ocr -Commercial
#>
[CmdletBinding()]
param(
  [Parameter(Mandatory = $true)] [string] $Target,
  [string] $Os,
  [string] $Arch,
  [string] $Backend,
  [ValidateSet('llama_cpp', 'whisper_cpp', 'kiwix_tools', 'ocr')] [string] $Family = 'llama_cpp',
  [switch] $Commercial,
  [switch] $AllowDowngrade,
  [switch] $DryRun
)

$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot

# FAILURE REPORTING (AUD-05): every failure below is announced with
# `Write-Host -ForegroundColor Red` plus an explicit `exit`, never with `Write-Error`.
# Under $ErrorActionPreference = 'Stop' a Write-Error is promoted to a SCRIPT-TERMINATING
# exception, which has three consequences that silently break this script's control flow:
#   1. nothing after it on the same line runs -- `Write-Error ...; $failed++; continue`
#      does not continue, it aborts the whole loop at the FIRST failure;
#   2. a following `exit 2` never executes, so the process exits 1 and the documented
#      config-error code collapses into the download-failure code;
#   3. the exception propagates OUT through the `&` call of a parent script (prepare-drive)
#      and kills it before it can inspect $LASTEXITCODE, so a step the parent treats as
#      best-effort becomes fatal and the steps after it never run.
# Write-Host has none of those effects: the message is printed and control flow, exit codes
# and the parent's error handling stay exactly as written.

# Resilient download: 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 we wrap it in an OUTER loop that RESUMES the partial file (-C -) on each
# attempt. Combined flags: --retry 3 (transient HTTP), --retry-delay 2, --retry-connrefused
# (curl >=7.52, on Win10 1803+), --connect-timeout 30. --ssl-revoke-best-effort: schannel
# curl on Windows; corporate proxies block CRL/OCSP. Integrity is enforced by the SHA-256
# pin AFTER download, so resume can never weaken verification.
function Invoke-CurlResilient {
  param([Parameter(Mandatory = $true)] [string] $Url,
        [Parameter(Mandatory = $true)] [string] $Dest)
  $curlArgs = @('-L', '--fail', '--retry', '3', '--retry-delay', '2', '--retry-connrefused', '--connect-timeout', '30')
  if (Test-OnWindows) { $curlArgs += '--ssl-revoke-best-effort' }
  $curl = (Get-Curl).Source
  $attempts = 5
  for ($i = 1; $i -le $attempts; $i++) {
    & $curl @curlArgs -C - -o "$Dest" "$Url"
    if ($LASTEXITCODE -eq 0) { return $true }
    if ($i -lt $attempts) {
      $wait = $i * 3
      Write-Host ("    connection interrupted (curl exit {0}) -- retry {1}/{2} in {3}s, resuming…" -f $LASTEXITCODE, $i, $attempts, $wait) -ForegroundColor Yellow
      Start-Sleep -Seconds $wait
    }
  }
  return $false
}

function Test-OnWindows { return ($PSVersionTable.PSVersion.Major -lt 6 -or $IsWindows) }

# The downloader: curl.exe on Windows (5.1's bare `curl` is an alias for Invoke-WebRequest).
# PowerShell 7 on macOS/Linux has no such alias and names the same tool `curl`. The scripts carry
# no PowerShell download line of their own (#767): antivirus heuristics flag one.
function Get-Curl {
  $c = Get-Command curl.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
  if (-not $c -and -not (Test-OnWindows)) {
    $c = Get-Command curl -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
  }
  return $c
}

# 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.
function Test-StaysInside([string]$Rel) {
  $depth = 0
  foreach ($seg in ($Rel -split '[/\\]')) {
    if ($seg -eq '' -or $seg -eq '.') { continue }
    if ($seg -eq '..') { $depth--; if ($depth -lt 0) { return $false } } else { $depth++ }
  }
  return $true
}

# #998: every file an install holds, relative to it with `/` (the app's markerBinaryKey form): the files
# the archive put there 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.
function Get-InstalledFileNames([string]$Dir, [string]$Prefix = '') {
  foreach ($e in @(Get-ChildItem -LiteralPath $Dir -Force)) {
    if (-not $Prefix -and @('.hilbertraum-runtime.json', 'cpu', 'cpu.new', 'cpu.old') -ccontains $e.Name) { continue }
    if (@('__MACOSX', '.DS_Store') -ccontains $e.Name -or $e.Name.StartsWith('._', [StringComparison]::Ordinal)) { continue }
    $rel = if ($Prefix) { "$Prefix/$($e.Name)" } else { $e.Name }
    if ($e.Attributes -band [IO.FileAttributes]::ReparsePoint) {
      if (Test-Path -LiteralPath $e.FullName -PathType Leaf) { $rel }
      else { Write-Host "  not recorded (a link that is not a file): $rel" }
    }
    elseif ($e.PSIsContainer) { Get-InstalledFileNames $e.FullName $rel }
    else { $rel }
  }
}

# #873: order two engine release tags of one family the way the app does (assets.ts
# compareRuntimeVersions): -1 older, 0 equal, 1 newer, $null 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. -cmatch and [0-9]: the app's patterns are case-sensitive
# and ASCII-only, PowerShell's -match and \d are neither. Numbers compare as numbers ('3.10' > '3.8').
function Get-RuntimeVersionParts([string]$Tag) {
  $t = "$Tag".Trim()
  if ($t -cmatch '^b([0-9]+)$') { return @{ Kind = 'build'; Parts = @([decimal]$Matches[1]) } }
  if ($t -cmatch '^v?([0-9]+(\.[0-9]+)*)$') { return @{ Kind = 'dotted'; Parts = @($Matches[1].Split('.') | ForEach-Object { [decimal]$_ }) } }
  return $null
}
function Compare-RuntimeVersion([string]$Installed, [string]$Pinned) {
  $a = Get-RuntimeVersionParts $Installed
  $b = Get-RuntimeVersionParts $Pinned
  if (-not $a -or -not $b -or $a.Kind -ne $b.Kind) { return $null }
  $n = [Math]::Max($a.Parts.Count, $b.Parts.Count)
  for ($i = 0; $i -lt $n; $i++) {
    $x = if ($i -lt $a.Parts.Count) { $a.Parts[$i] } else { [decimal]0 }
    $y = if ($i -lt $b.Parts.Count) { $b.Parts[$i] } else { [decimal]0 }
    if ($x -lt $y) { return -1 }
    if ($x -gt $y) { return 1 }
  }
  return 0
}

# #339 P8-3: parse a flow-sequence value ("[a, b, c]", or "[]"/empty) into a string array.
# Mirrors the flow-sequence shape runtime-sources.yaml uses for `executables:`/`runtime_files:`.
function Get-FlowListValue {
  param([string] $Raw)
  $inner = $Raw.Trim()
  if ($inner.StartsWith('[') -and $inner.EndsWith(']')) { $inner = $inner.Substring(1, $inner.Length - 2) }
  if ($inner.Trim() -eq '') { return @() }
  return @($inner -split ',' | ForEach-Object { $_.Trim().Trim('"').Trim("'") } | Where-Object { $_ -ne '' })
}

# #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
# (`executables:` alone, then `  - item` lines). Collapse any such block into the inline
# flow form BEFORE the line-by-line parser below runs, so it only ever has to handle one
# shape. Deliberately 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.
function ConvertTo-FlowListLines {
  param([string[]] $Lines)
  $out = New-Object System.Collections.Generic.List[string]
  $i = 0
  while ($i -lt $Lines.Count) {
    $line = $Lines[$i]
    if ($line -match '^(\s*)(executables|runtime_files)\s*:\s*$') {
      $indent = $Matches[1]
      $key = $Matches[2]
      $items = @()
      $j = $i + 1
      while ($j -lt $Lines.Count) {
        if ($Lines[$j] -match '^(\s+)-\s*(.+?)\s*$' -and $Matches[1].Length -gt $indent.Length) {
          $items += $Matches[2].Trim().Trim('"').Trim("'")
          $j++
        } else { break }
      }
      if ($items.Count -gt 0) {
        $out.Add("$indent$key`: [$($items -join ', ')]")
        $i = $j
        continue
      }
    }
    $out.Add($line)
    $i++
  }
  return $out.ToArray()
}

# Normalize -Target to a full path: curl.exe resolves relative paths against the PROCESS
# working directory, which does not follow Set-Location (audit M22).
if (-not [System.IO.Path]::IsPathRooted($Target)) { $Target = Join-Path (Get-Location).Path $Target }
$Target = [System.IO.Path]::GetFullPath($Target)

$SourcesFile = Join-Path $Target 'model-manifests/runtime-sources.yaml'
if (-not (Test-Path -LiteralPath $SourcesFile)) { $SourcesFile = Join-Path $RepoRoot 'model-manifests/runtime-sources.yaml' }
if (-not (Test-Path -LiteralPath $SourcesFile)) {
  Write-Host "No runtime-sources.yaml found under '$Target' or repo root." -ForegroundColor Red
  exit 2
}

# Host detection (PS 5.1 is always Windows; $IsWindows exists only on PS Core).
# When -Os is explicitly overridden but -Arch is not, we are cross-provisioning another
# OS's dir -- the host arch is meaningless there, so we take that OS's first build instead.
$OsExplicit = [bool]$Os
$ArchExplicit = [bool]$Arch
if (-not $Os) {
  if ($PSVersionTable.PSVersion.Major -ge 6) {
    $Os = if ($IsWindows) { 'win' } elseif ($IsMacOS) { 'mac' } else { 'linux' }
  } else { $Os = 'win' }
}
if (-not $Arch) {
  # PROCESSOR_ARCHITECTURE reports the (possibly emulated) PROCESS arch -- an x64
  # PowerShell on ARM64 Windows says AMD64. PROCESSOR_ARCHITEW6432 reveals the real OS
  # arch under WOW emulation.
  $procArch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
  $Arch = if ($procArch -match 'ARM64') { 'arm64' } else { 'x64' }
}

# --- 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 -eq 'ocr') {
  $lines = (Get-Content -LiteralPath $SourcesFile) -split "`n"
  $ocrVersion = $null
  $files = @()
  $cur = $null
  $top = $null
  foreach ($raw in $lines) {
    $line = $raw.TrimEnd()
    if ($line -match '^\s*#') { continue }
    if ($line -match '^([A-Za-z0-9_]+)\s*:\s*$') {
      if ($cur) { $files += $cur; $cur = $null }
      $top = $Matches[1]
      continue
    }
    if ($top -ne 'ocr') { continue }
    if (-not $ocrVersion -and $line -match '^\s*version\s*:\s*(.+?)\s*$') {
      $ocrVersion = ($Matches[1] -replace '\s+#.*$', '').Trim().Trim('"').Trim("'"); continue
    }
    if ($line -match '^\s*-\s*lang\s*:\s*(.+?)\s*$') {
      if ($cur) { $files += $cur }
      $cur = [ordered]@{ lang = ($Matches[1] -replace '\s+#.*$', '').Trim().Trim('"').Trim("'") }
      continue
    }
    if ($cur -and $line -match '^\s+([A-Za-z0-9_]+)\s*:\s*(.+?)\s*$') {
      $cur[$Matches[1].Trim()] = ($Matches[2] -replace '\s+#.*$', '').Trim().Trim('"').Trim("'")
    }
  }
  if ($cur) { $files += $cur }
  if (-not $ocrVersion -or $files.Count -eq 0) {
    Write-Host 'runtime-sources.yaml: no ocr block (version + files) found.' -ForegroundColor Red
    exit 2
  }
  Write-Host "Fetch OCR language files -> $Target (data $ocrVersion)" -ForegroundColor Cyan
  $IsRealShaOcr = { param($h) $h -match '^[a-f0-9]{64}$' }
  # -Commercial: every file must be verifiable BEFORE the first download (#234).
  if ($Commercial) {
    $placeholders = @($files | Where-Object { $_.sha256 -and -not (& $IsRealShaOcr ([string]$_.sha256).ToLower()) } | ForEach-Object { $_.lang })
    if ($placeholders.Count -gt 0) {
      Write-Host ("  commercial: placeholder sha256 for ocr file(s) {0} -- refusing to fetch (nothing downloaded)" -f ($placeholders -join ', ')) -ForegroundColor Red
      exit 1
    }
  }
  $failed = 0
  foreach ($f in $files) {
    foreach ($required in @('url', 'sha256', 'dest')) {
      if (-not $f[$required]) { Write-Host "ocr.files ($($f.lang)): missing '$required'." -ForegroundColor Red; exit 2 }
    }
    if ($f.dest -match '\.\.' -or $f.dest -match '^[/\\]' -or $f.dest -match '^[A-Za-z]:') {
      Write-Host "runtime-sources.yaml: ocr dest escapes the drive root: $($f.dest)" -ForegroundColor Red
      exit 2
    }
    $dest = Join-Path $Target ($f.dest -replace '/', [IO.Path]::DirectorySeparatorChar)
    $sha = ([string]$f.sha256).ToLower()
    Write-Host ("  {0}: {1}" -f $f.lang, $f.dest)
    if ($DryRun) { Write-Host ("    would fetch {0}" -f $f.url) -ForegroundColor Yellow; continue }
    if ((Test-Path -LiteralPath $dest) -and (& $IsRealShaOcr $sha)) {
      $actual = (Get-FileHash -LiteralPath $dest -Algorithm SHA256).Hash.ToLower()
      if ($actual -eq $sha) { Write-Host '    skip (present + verified)' -ForegroundColor Green; continue }
      Write-Host '    present but hash differs -- re-fetching' -ForegroundColor Yellow
      # 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.
      Remove-Item -Force -LiteralPath $dest -ErrorAction SilentlyContinue
    }
    New-Item -ItemType Directory -Force -Path (Split-Path -Parent $dest) | Out-Null
    $Curl = Get-Curl
    if ($Curl) {
      if (-not (Invoke-CurlResilient -Url $f.url -Dest $dest)) {
        Write-Host '    download failed after retries' -ForegroundColor Red; $failed++; continue
      }
    } else {
      # No in-script downloader: a WebClient / Invoke-WebRequest download line is what antivirus
      # heuristics flag (Norton quarantined a copy carrying one, #767), and every Windows from
      # 10 1803 on ships curl.exe. Exit 3, as the .sh twin does with no downloader.
      Write-Host 'No downloader found (need curl.exe, built into Windows 10 1803 and later).' -ForegroundColor Red
      exit 3
    }
    if (& $IsRealShaOcr $sha) {
      $actual = (Get-FileHash -LiteralPath $dest -Algorithm SHA256).Hash.ToLower()
      if ($actual -ne $sha) {
        Write-Host ("    FAIL: checksum mismatch (expected {0}, got {1}) -- deleting" -f $sha, $actual) -ForegroundColor Red
        Remove-Item -Force -LiteralPath $dest -ErrorAction SilentlyContinue
        $failed++
        continue
      }
      Write-Host '    VERIFIED' -ForegroundColor Green
    } else {
      Write-Host '    UNVERIFIED (placeholder hash)' -ForegroundColor Yellow
    }
  }
  if ($failed -gt 0) { exit 1 }
  exit 0
}

# --- Parse runtime-sources.yaml: a 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.
$lines = ConvertTo-FlowListLines ((Get-Content -LiteralPath $SourcesFile) -split "`n")
$version = $null
$builds = @()
$current = $null
$topKey = $null
$familyExecutables = @()
$familyExecutablesSet = $false
foreach ($raw in $lines) {
  $line = $raw.TrimEnd()
  if ($line -match '^\s*#') { continue }
  # A non-indented `key:` line starts a new top-level family block.
  if ($line -match '^([A-Za-z0-9_]+)\s*:\s*$') {
    if ($current) { $builds += $current; $current = $null }
    $topKey = $Matches[1]
    continue
  }
  if ($topKey -ne $Family) { continue }
  # Strip inline YAML comments (whitespace + '#' + rest) before unquoting (M17) -- the
  # committed `version: b9196   # PLACEHOLDER ...` used to leak the comment into the value.
  if (-not $version -and $line -match '^\s*version\s*:\s*(.+?)\s*$') {
    $version = ($Matches[1] -replace '\s+#.*$', '').Trim().Trim('"').Trim("'"); continue
  }
  # #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 (-not $current).
  if (-not $current -and -not $familyExecutablesSet -and $line -match '^\s*executables\s*:\s*(.+?)\s*$') {
    $familyExecutables = Get-FlowListValue (($Matches[1] -replace '\s+#.*$', '').Trim())
    $familyExecutablesSet = $true
    continue
  }
  if ($line -match '^\s*-\s*os\s*:\s*(.+?)\s*$') {
    if ($current) { $builds += $current }
    $current = [ordered]@{ os = ($Matches[1] -replace '\s+#.*$', '').Trim().Trim('"').Trim("'") }
    continue
  }
  if ($current -and $line -match '^\s+([A-Za-z0-9_]+)\s*:\s*(.+?)\s*$') {
    $current[$Matches[1].Trim()] = ($Matches[2] -replace '\s+#.*$', '').Trim().Trim('"').Trim("'")
  }
}
if ($current) { $builds += $current }

if (-not $version) { Write-Host "runtime-sources.yaml: missing $Family.version (is the $Family block present?)" -ForegroundColor Red; 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.
function Get-FamilyVersion([string]$File, [string]$Fam) {
  $top = $null
  foreach ($raw in (Get-Content -LiteralPath $File)) {
    $l = $raw.TrimEnd()
    if ($l -match '^\s*#') { continue }
    if ($l -match '^([A-Za-z0-9_]+)\s*:\s*$') { $top = $Matches[1]; continue }
    if ($top -eq $Fam -and $l -match '^\s+version\s*:\s*(.+?)\s*$') {
      return ($Matches[1] -replace '\s+#.*$', '').Trim().Trim('"').Trim("'")
    }
  }
  return $null
}
$RepoSources = Join-Path $RepoRoot 'model-manifests/runtime-sources.yaml'
if ((Test-Path -LiteralPath $RepoSources) -and ((Resolve-Path -LiteralPath $SourcesFile).Path -ne (Resolve-Path -LiteralPath $RepoSources).Path)) {
  $repoVersion = Get-FamilyVersion $RepoSources $Family
  if ($repoVersion -and $repoVersion -ne $version) {
    Write-Host "Note: the drive's runtime-sources.yaml pins $Family $version; this repo pins $repoVersion." -ForegroundColor Yellow
    Write-Host "      To move the drive to the repo's pin, refresh its manifests first (prepare-drive), then run fetch-runtime again." -ForegroundColor Yellow
  }
}

# --- 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).
if ($OsExplicit -and -not $ArchExplicit) {
  $candidates = $builds | Where-Object { $_.os -eq $Os }
} else {
  $candidates = $builds | Where-Object { $_.os -eq $Os -and $_.arch -eq $Arch }
}
if ($Backend) { $candidates = $candidates | Where-Object { $_.backend -eq $Backend } }
$build = $candidates | Select-Object -First 1

if (-not $build) {
  Write-Host "No runtime build for os=$Os arch=$Arch$(if ($Backend) { " backend=$Backend" }). Try -Os/-Arch/-Backend overrides." -ForegroundColor Red
  exit 2
}

# 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.
foreach ($required in @('url', 'sha256', 'extract_to')) {
  if (-not $build[$required]) {
    Write-Host "runtime-sources.yaml: selected build ($Os/$Arch) is missing '$required'." -ForegroundColor Red
    exit 2
  }
}

# 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 (TS planRuntimeDownload
# already rejects this -- mirror it).
if ($build.extract_to -match '\.\.' -or $build.extract_to -match '^[/\\]' -or $build.extract_to -match '^[A-Za-z]:') {
  Write-Host "runtime-sources.yaml: extract_to escapes the drive root: $($build.extract_to)" -ForegroundColor Red
  exit 2
}

$IsRealSha = { param($h) $h -match '^[a-f0-9]{64}$' }
# #1028: read the install marker at $path as the app reads it (assets.ts readRuntimeMarkerState): the marker, or $null
# when it is no marker 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, never skip it. The rule:
#  - at most 64 KiB here (the app: 1 MiB; see below), its bytes read as UTF-8 (never UTF-16 by a byte-order mark, as
#    the app reads them);
#  - after one leading byte-order mark, exactly ONE JSON object (RFC 8259), checked by the small reader below, not by
#    ConvertFrom-Json, which takes single quotes, comments and trailing commas, and matches names in any case: nothing
#    before or after it but blanks, no raw control character inside a string, only JSON's escapes, numbers in JSON's
#    form;
#  - its own (top-level) version, backend, os and arch, by their exact names, 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. Such cases, all never written: a name written with an
# escape, a map naming one file twice, a DEL character, two names that differ only in case (ConvertFrom-Json refuses
# them). Only then is the text handed to ConvertFrom-Json, for the values the skip block reads. Mirrors fetch-runtime.sh
# marker_readable, step for step.
$ReadInstallMarker = {
  param($path)
  # The size before the read (final review), so an oversized file is never taken into memory. 64 KiB here, as in the
  # .sh twin: the app reads up to 1 MiB, but no writer writes more than a few KB (the b12110 Windows copy records 52
  # files in about 5 KB), and this reader is plain PowerShell; a larger marker is fetched again at once.
  if ((New-Object System.IO.FileInfo $path).Length -gt 65536) { return $null }
  $bytes = [System.IO.File]::ReadAllBytes($path)
  $text = (New-Object System.Text.UTF8Encoding($false)).GetString($bytes)
  if ($text.Length -gt 0 -and [int]$text[0] -eq 0xFEFF) { $text = $text.Substring(1) }
  $n = $text.Length
  $i = 0
  $state = 'value'
  $stack = ''
  $key = ''
  $str = ''
  $inMap = $false
  $map = 'absent'
  $object = $false
  $fields = @{ version = $false; backend = $false; os = $false; arch = $false }
  while ($i -lt $n) {
    $c = [int]$text[$i]
    if ($c -eq 0x20 -or $c -eq 0x09 -or $c -eq 0x0A -or $c -eq 0x0D) { $i++; continue }
    if ($state -eq 'value' -or $state -eq 'value-or-close') {
      if ($state -eq 'value-or-close' -and $c -eq 0x5D) {
        $stack = $stack.Substring(0, $stack.Length - 1); $state = 'after'; $i++; continue
      }
      # Where this value sits: one of the object's own fields (top), an entry of its own map (map), or deeper.
      $where = ''
      if ($stack -ceq '{') { $where = 'top' }
      elseif ($stack -ceq '{{' -and $inMap) { $where = 'map' }
      elseif ($stack.Length -eq 0 -and $c -ne 0x7B) { return $null }
      $isString = $false
      if ($c -eq 0x7B) {
        if ($stack.Length -eq 0) { $object = $true }
        $stack += '{'; $state = 'key-or-close'; $i++
      } elseif ($c -eq 0x5B) {
        $stack += '['; $state = 'value-or-close'; $i++
      } elseif ($c -eq 0x22) {
        $i++
        $str = ''
        while ($true) {
          $j = $text.IndexOfAny([char[]]@([char]0x22, [char]0x5C), $i)
          if ($j -lt 0) { return $null }
          $run = $text.Substring($i, $j - $i)
          if ($run -cmatch '[\x00-\x1F\x7F]') { return $null }
          $str += $run
          $i = $j
          if ([int]$text[$i] -eq 0x22) { $i++; break }
          if ($i + 1 -ge $n) { return $null }
          $e = [int]$text[$i + 1]
          if ($e -eq 0x22 -or $e -eq 0x5C -or $e -eq 0x2F -or $e -eq 0x62 -or $e -eq 0x66 -or $e -eq 0x6E -or $e -eq 0x72 -or $e -eq 0x74) {
            $str += $text.Substring($i, 2); $i += 2
          } elseif ($e -eq 0x75 -and $i + 6 -le $n -and $text.Substring($i + 2, 4) -cmatch '^[0-9a-fA-F]{4}\z') {
            $str += $text.Substring($i, 6); $i += 6
          } else { return $null }
        }
        $isString = $true; $state = 'after'
      } elseif ($c -eq 0x74 -or $c -eq 0x66 -or $c -eq 0x6E) {
        $word = if ($c -eq 0x74) { 'true' } elseif ($c -eq 0x66) { 'false' } else { 'null' }
        if ($i + $word.Length -gt $n -or -not ($text.Substring($i, $word.Length) -ceq $word)) { return $null }
        $i += $word.Length; $state = 'after'
      } elseif ($c -eq 0x2D -or ($c -ge 0x30 -and $c -le 0x39)) {
        # A JSON number: -? then 0 or a digit run without a leading zero, an optional fraction, an optional exponent.
        $m = [regex]::Match($text.Substring($i), '\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?')
        if (-not $m.Success -or $m.Length -eq 0) { return $null }
        $i += $m.Length; $state = 'after'
      } else { return $null }
      if ($where -ceq 'top') {
        if ($key -ceq 'version' -or $key -ceq 'backend' -or $key -ceq 'os' -or $key -ceq 'arch') { $fields[$key] = $isString }
        elseif ($key -ceq 'binaries') {
          if ($c -eq 0x7B) { $map = 'ok'; $inMap = $true } else { $map = 'bad' }
        }
      } elseif ($where -ceq 'map') {
        if (-not $isString -or -not ($str -cmatch '^[0-9a-fA-F]{64}\z')) { $map = 'bad' }
      }
    } elseif ($state -eq 'key' -or $state -eq 'key-or-close') {
      if ($state -eq 'key-or-close' -and $c -eq 0x7D) {
        if ($stack -ceq '{{' -and $inMap) { $inMap = $false }
        $stack = $stack.Substring(0, $stack.Length - 1); $state = 'after'; $i++; continue
      }
      if ($c -ne 0x22) { return $null }
      $i++
      $str = ''
      while ($true) {
        $j = $text.IndexOfAny([char[]]@([char]0x22, [char]0x5C), $i)
        if ($j -lt 0) { return $null }
        $run = $text.Substring($i, $j - $i)
        if ($run -cmatch '[\x00-\x1F\x7F]') { return $null }
        $str += $run
        $i = $j
        if ([int]$text[$i] -eq 0x22) { $i++; break }
        if ($i + 1 -ge $n) { return $null }
        $e = [int]$text[$i + 1]
        if ($e -eq 0x22 -or $e -eq 0x5C -or $e -eq 0x2F -or $e -eq 0x62 -or $e -eq 0x66 -or $e -eq 0x6E -or $e -eq 0x72 -or $e -eq 0x74) {
          $str += $text.Substring($i, 2); $i += 2
        } elseif ($e -eq 0x75 -and $i + 6 -le $n -and $text.Substring($i + 2, 4) -cmatch '^[0-9a-fA-F]{4}\z') {
          $str += $text.Substring($i, 6); $i += 6
        } else { return $null }
      }
      $key = $str
      $state = 'colon'
    } elseif ($state -eq 'colon') {
      if ($c -ne 0x3A) { return $null }
      $state = 'value'; $i++
    } else {
      # after a value: a comma, or the close of the object or array it sits in; nothing after the marker's own close.
      if ($stack.Length -eq 0) { return $null }
      $top = [int]$stack[$stack.Length - 1]
      if ($c -eq 0x2C) {
        $state = if ($top -eq 0x7B) { 'key' } else { 'value' }
      } elseif ($c -eq 0x7D -and $top -eq 0x7B) {
        if ($stack -ceq '{{' -and $inMap) { $inMap = $false }
        $stack = $stack.Substring(0, $stack.Length - 1)
      } elseif ($c -eq 0x5D -and $top -eq 0x5B) {
        $stack = $stack.Substring(0, $stack.Length - 1)
      } else { return $null }
      $i++
    }
  }
  if (-not $object -or $stack.Length -ne 0 -or $state -ne 'after') { return $null }
  if (-not ($fields['version'] -and $fields['backend'] -and $fields['os'] -and $fields['arch']) -or $map -ceq 'bad') { return $null }
  return ($text | ConvertFrom-Json)
}
$extractTo = Join-Path $Target ($build.extract_to -replace '/', [IO.Path]::DirectorySeparatorChar)
# #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).
$PrimaryBase = if ($Family -eq 'whisper_cpp') { 'whisper-cli' } elseif ($Family -eq 'kiwix_tools') { 'kiwix-serve' } else { 'llama-server' }
# #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.
$NeverInstalledBases = if ($Family -eq 'llama_cpp') { @('llama-connect') } else { @() }
# 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. Get-Item -Force sees a dangling link as well.
# -notcontains / -eq compare without case, as NTFS and APFS compare file names (assets.ts does the same).
function Remove-NeverInstalled {
  foreach ($base in $NeverInstalledBases) {
    $leftOut = if ($build.os -eq 'win') { "$base.exe" } else { $base }
    $leftOutPath = Join-Path $extractTo $leftOut
    if (Get-Item -LiteralPath $leftOutPath -Force -ErrorAction SilentlyContinue) {
      if ($DryRun) { Write-Host "  would leave out: $leftOut"; continue }
      Remove-Item -Force -LiteralPath $leftOutPath
      Write-Host "  left out: $leftOut"
    }
  }
}
$executableBases = @($PrimaryBase)
foreach ($e in $familyExecutables) { if ($executableBases -notcontains $e -and $NeverInstalledBases -notcontains $e) { $executableBases += $e } }
# Binary name(s) follow the SELECTED build's OS (we may be provisioning the mac/linux dir
# from a Windows build machine), mirroring assets.ts sidecarBinaryName. $binaryName/$binaryPath
# keep referring to the PRIMARY only -- the flatten step below locates the archive's nested
# folder by the primary executable, exactly as before.
$binaryBase = $PrimaryBase
$binaryName = if ($build.os -eq 'win') { "$binaryBase.exe" } else { $binaryBase }
$binaryPath = Join-Path $extractTo $binaryName
$requiredExecNames = @($executableBases | ForEach-Object { if ($build.os -eq 'win') { "$_.exe" } else { $_ } })
$runtimeFileNames = @()
if ($build.runtime_files) { $runtimeFileNames = Get-FlowListValue ([string]$build.runtime_files) }
# 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.
$requiredFileNames = @($requiredExecNames + $runtimeFileNames)
$markerPath = Join-Path $extractTo '.hilbertraum-runtime.json'
$sha = ([string]$build.sha256).ToLower()

Write-Host "Fetch runtime -> $Target" -ForegroundColor Cyan
Write-Host ("  build: {0}/{1} {2} @ {3}" -f $build.os, $build.arch, $build.backend, $version)
Write-Host ("  url:   {0}" -f $build.url)
Write-Host ("  into:  {0}" -f $extractTo)
Write-Host ("  files: {0}" -f ($requiredFileNames -join ', '))

# 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 (Test-Path -LiteralPath $binaryPath) {
  $skip = $false
  $why = 'install marker is missing or differs'
  # #873: the marker's version when it is newer than the pin (kept unless -Commercial / -AllowDowngrade).
  $newerKept = $null
  $newerReplaced = $null
  $allPresent = -not ($requiredFileNames | Where-Object { -not (Test-Path -LiteralPath (Join-Path $extractTo $_)) })
  if (-not $allPresent) {
    $why = 'one or more required files are missing'
  } elseif (Test-Path -LiteralPath $markerPath) {
    try {
      # #1028: a marker the app cannot read is as good as none: fetched again, never skipped or kept as newer.
      $marker = & $ReadInstallMarker $markerPath
      if ($null -eq $marker) { throw 'the install marker cannot be read as one' }
      if ((Compare-RuntimeVersion ([string]$marker.version) $version) -eq 1) {
        # Whatever its backend: the app's relation ignores the backend too (runtimeInstallRelation).
        if ($Commercial) { $newerReplaced = [string]$marker.version }
        elseif (-not $AllowDowngrade) { $newerKept = [string]$marker.version }
      } elseif ($marker.version -eq $version -and $marker.backend -eq $build.backend) {
        $skip = $true
        # #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).
        $recordedMissing = @()
        if ($marker.binaries) {
          foreach ($p in $marker.binaries.PSObject.Properties) {
            if (-not (Test-Path -LiteralPath (Join-Path $extractTo $p.Name) -PathType Leaf)) { $recordedMissing += $p.Name }
          }
        }
        if ($recordedMissing.Count -gt 0) {
          $skip = $false
          $why = 'a file its install marker records is missing (' + ($recordedMissing -join ', ') + ')'
        } elseif ($Commercial) {
          $allHashedMarker = $true
          foreach ($f in $requiredFileNames) {
            $recorded = $null
            if ($marker.binaries) { $recorded = $marker.binaries.PSObject.Properties[$f].Value }
            if (-not $recorded -or -not (& $IsRealSha ([string]$recorded).ToLower())) { $allHashedMarker = $false; break }
          }
          if (-not $allHashedMarker) {
            $skip = $false
            $why = 'install marker records no binary hash for one or more required files (legacy) -- commercial mode'
          }
        }
      }
    } catch { $skip = $false }
  }
  if ($skip) {
    Write-Host "  skip ($binaryName already installed: $version/$($build.backend) per .hilbertraum-runtime.json)" -ForegroundColor Green
    Remove-NeverInstalled
    exit 0
  }
  if ($newerKept) {
    Write-Host "  skip ($binaryName $newerKept is newer than this drive's pin $version, installed by the app; pass -AllowDowngrade to replace it)" -ForegroundColor Green
    Remove-NeverInstalled
    exit 0
  }
  if ($newerReplaced) {
    Write-Host "  commercial: replacing the newer $newerReplaced with the pinned $version (a sold drive carries its app's pin)" -ForegroundColor Yellow
  }
  Write-Host "  $binaryName present but $why -- re-fetching $version/$($build.backend)" -ForegroundColor Yellow
}

# -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 -and -not (& $IsRealSha $sha)) {
  Write-Host ("  commercial: placeholder sha256 for {0}/{1} {2} @ {3} -- refusing to fetch (nothing downloaded, no marker written)" -f $build.os, $build.arch, $build.backend, $version) -ForegroundColor Red
  exit 1
}
if ($DryRun) { Write-Host '(dry run -- nothing will be downloaded)' -ForegroundColor Yellow; exit 0 }

New-Item -ItemType Directory -Force -Path $extractTo | Out-Null
# Archive name from the URL basename so a .tar.gz (the macOS/Linux release format) is
# not saved -- and mis-extracted -- as a .zip.
$archiveName = [System.IO.Path]::GetFileName(([uri]$build.url).AbsolutePath)
if (-not $archiveName) { $archiveName = "{0}-{1}-{2}-{3}.zip" -f $binaryBase, $version, $build.os, $build.arch }
$archive = Join-Path $extractTo $archiveName

$Curl = Get-Curl
if ($Curl) {
  # Resilient curl (see Invoke-CurlResilient): retries + resumes a dropped transfer so a
  # flaky connection doesn't lose the whole archive. Integrity is enforced by the SHA-256
  # pin below, so resume can never weaken verification.
  if (-not (Invoke-CurlResilient -Url $build.url -Dest $archive)) {
    Write-Host 'curl failed after retries' -ForegroundColor Red; exit 1
  }
} else {
  # No in-script downloader (antivirus heuristics flag one, #767): exit 3, as the .sh twin does.
  Write-Host 'No downloader found (need curl.exe, built into Windows 10 1803 and later).' -ForegroundColor Red
  exit 3
}

$archiveVerified = $false
if (& $IsRealSha $sha) {
  $actual = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLower()
  if ($actual -ne $sha) {
    Write-Host ("  FAIL: archive checksum mismatch (expected {0}, got {1}) -- deleting" -f $sha, $actual) -ForegroundColor Red
    Remove-Item -Force -LiteralPath $archive -ErrorAction SilentlyContinue
    exit 1
  }
  Write-Host "  archive VERIFIED" -ForegroundColor Green
  $archiveVerified = $true
} else {
  Write-Host "  archive UNVERIFIED (placeholder hash) -- verify after a real release bump" -ForegroundColor Yellow
}

# 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.
Get-ChildItem -LiteralPath $extractTo -Force |
  Where-Object { $_.Name -ne $archiveName -and $_.Name -ne 'cpu' } |
  Remove-Item -Recurse -Force

if ($archiveName -match '\.(tar\.gz|tgz)$') {
  # Windows' own bsdtar (System32\tar.exe, Windows 10 1803+; it handles .tar.gz natively), by full
  # path (#767): in a PowerShell started from Git Bash the first `tar` on PATH is Git's GNU tar, which
  # reads the `C:` of the archive path as a remote host and extracts nothing. PowerShell 7 on a Mac
  # or Linux has no SystemRoot and takes the tar on PATH.
  $tarExe = 'tar'
  if ($env:SystemRoot) {
    $systemTar = Join-Path $env:SystemRoot 'System32\tar.exe'
    if (Test-Path -LiteralPath $systemTar) { $tarExe = $systemTar }
  }
  # NOTE: EAP must be Continue around native stderr redirects (PS 5.1 wraps redirected
  # stderr in error records, which would terminate under 'Stop'). tar's messages are kept (#767):
  # for a failure the link copies below cannot repair, they are the only account of it.
  $prevEap = $ErrorActionPreference
  $ErrorActionPreference = 'Continue'
  $tarMessages = @(& $tarExe -xzf "$archive" -C "$extractTo" 2>&1 | ForEach-Object {
      if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.Exception.Message } else { "$_" } })
  $tarExit = $LASTEXITCODE
  $listing = & $tarExe -tvzf "$archive" 2>$null
  $ErrorActionPreference = $prevEap

  # The llama.cpp tarballs contain version SYMLINKS (lib*.so -> lib*.so.X.Y.Z), which
  # cannot be created on Windows (or on an exFAT drive at all). 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).
  $links = @()
  foreach ($line in @($listing)) {
    if ($line -match '^l' -and $line -match '\s(\S+)\s->\s(\S+)\s*$') {
      $links += , @($Matches[1], $Matches[2])
    }
  }
  for ($pass = 0; $pass -lt 4; $pass++) {
    $unresolved = 0
    foreach ($l in $links) {
      $lnkPath = Join-Path $extractTo ($l[0] -replace '/', [IO.Path]::DirectorySeparatorChar)
      if (Test-Path -LiteralPath $lnkPath) { continue }
      # The link's name, and its target read from the link's own directory, once `..` is resolved.
      $absolute = @($l | Where-Object { $_ -match '^[/\\]' -or $_ -match '^[A-Za-z]:' }).Count -gt 0
      $linkDir = $l[0] -replace '[^/\\]*$', ''
      if ($absolute -or -not (Test-StaysInside $l[0]) -or -not (Test-StaysInside ($linkDir + $l[1]))) {
        Write-Host ("  FAIL: archive link {0} -> {1} points outside {2} -- not copied" -f $l[0], $l[1], $extractTo) -ForegroundColor Red
        exit 1
      }
      $srcPath = Join-Path (Split-Path -Parent $lnkPath) $l[1]
      if (Test-Path -LiteralPath $srcPath) { Copy-Item -Force -LiteralPath $srcPath -Destination $lnkPath }
      else { $unresolved++ }
    }
    if ($unresolved -eq 0) { break }
  }
  # Those links make tar fail on Windows and FAT/exFAT 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 ($tarExit -ne 0) {
    $ErrorActionPreference = 'Continue'
    $members = @(& $tarExe -tzf "$archive" 2>$null)
    $listExit = $LASTEXITCODE
    $ErrorActionPreference = $prevEap
    $missing = @($members | Where-Object { $_ -and -not (Test-Path -LiteralPath (Join-Path $extractTo $_)) })
    if ($listExit -ne 0 -or $members.Count -eq 0 -or $missing.Count -gt 0) {
      Write-Host "  FAIL: tar could not extract $archiveName (exit $tarExit):" -ForegroundColor Red
      foreach ($m in $tarMessages) { if ($m.Trim()) { Write-Host "    $m" -ForegroundColor Red } }
      if ($missing.Count -gt 0) { Write-Host ("    not on disk after extraction: {0}" -f ($missing -join ', ')) -ForegroundColor Red }
      exit 1
    }
  }
} else {
  # .NET's ZipFile, not Expand-Archive (#767): Windows PowerShell 5.1's Expand-Archive reads
  # -DestinationPath as a wildcard pattern, so on a drive path holding `[` it misses the existing
  # directory, tries to create it again and stops. The dir was emptied above (only the archive and
  # cpu/ remain), so nothing is overwritten.
  try {
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    [System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractTo)
  } catch {
    Write-Host ("  FAIL: could not extract {0}: {1}" -f $archiveName, $_.Exception.Message) -ForegroundColor Red
    exit 1
  }
}
Remove-Item -Force -LiteralPath $archive -ErrorAction SilentlyContinue

# 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 (-not (Test-Path -LiteralPath $binaryPath)) {
  $rootFull = [System.IO.Path]::GetFullPath($extractTo).TrimEnd('\', '/')
  # 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.
  $cpuSubdir = Join-Path $rootFull 'cpu'
  $found = Get-ChildItem -LiteralPath $extractTo -Recurse -File -Filter $binaryName -ErrorAction SilentlyContinue |
    Where-Object { -not $_.FullName.StartsWith($cpuSubdir + [IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase) } |
    Select-Object -First 1
  if ($found) {
    $srcFull = [System.IO.Path]::GetFullPath($found.DirectoryName).TrimEnd('\', '/')
    if ($srcFull -ne $rootFull) {
      Get-ChildItem -LiteralPath $found.DirectoryName -Force | Move-Item -Destination $extractTo -Force
      # Clean up the now-empty nesting dirs (deepest first).
      Get-ChildItem -LiteralPath $extractTo -Recurse -Directory -ErrorAction SilentlyContinue |
        Sort-Object FullName -Descending |
        Where-Object { -not (Get-ChildItem -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue) } |
        Remove-Item -Force -ErrorAction SilentlyContinue
    }
  }
}

if (-not (Test-Path -LiteralPath $binaryPath)) {
  Write-Host "  FAIL: $binaryName not found under $extractTo after extraction -- the release archive layout may have changed." -ForegroundColor Red
  exit 1
}

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

# #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.
$missingRequired = @($requiredFileNames | Where-Object { -not (Test-Path -LiteralPath (Join-Path $extractTo $_)) })
if ($missingRequired.Count -gt 0) {
  Write-Host ("  FAIL: required file(s) missing under {0} after extraction: {1}" -f $extractTo, ($missingRequired -join ', ')) -ForegroundColor Red
  exit 1
}

if ($build.os -ne 'win') {
  foreach ($f in $requiredExecNames) {
    Write-Host "  NOTE: exec bit for $f cannot be set from Windows; exFAT mounts are typically all-executable, otherwise chmod +x it on the target OS." -ForegroundColor Yellow
  }
}

# Record exactly which build is installed (UTF-8 without BOM -- PS 5.1 Set-Content
# would prepend one and break Node's JSON.parse). Mirrors assets.ts writeRuntimeMarker.
# `binaries` 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, posix 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.
$recordNames = New-Object System.Collections.Generic.List[string]
# Ordinal order, as the app and the bash twin sort (`Sort-Object` follows the culture).
[string[]]$installedNames = @(Get-InstalledFileNames $extractTo)
[Array]::Sort($installedNames, [System.StringComparer]::Ordinal)
foreach ($f in @($requiredFileNames) + @($installedNames)) {
  if (-not $recordNames.Contains($f)) { $recordNames.Add($f) }
}
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
$markerHead = '{"version":"' + $version + '","backend":"' + $build.backend + '","os":"' + $build.os + '","arch":"' + $build.arch + '"'
if ($archiveVerified) {
  $allHashed = $true
  $entries = @()
  foreach ($f in $recordNames) {
    try {
      $h = (Get-FileHash -LiteralPath (Join-Path $extractTo $f) -Algorithm SHA256).Hash.ToLower()
      $entries += ('"' + ($f -replace '\\', '\\' -replace '"', '\"') + '":"' + $h + '"')
    } catch {
      $allHashed = $false
      break
    }
  }
  if ($allHashed) {
    $markerJson = $markerHead + ',"binaries":{' + ($entries -join ',') + '}}'
  } else {
    $markerJson = $markerHead + '}'
    Write-Host "  marker written WITHOUT binary hashes (could not hash every installed file) -- the sell gate refuses this install" -ForegroundColor Yellow
  }
} else {
  $markerJson = $markerHead + '}'
  Write-Host "  marker written WITHOUT a binary hash (archive unverified) -- the sell gate refuses this install" -ForegroundColor Yellow
}
[System.IO.File]::WriteAllText($markerPath, $markerJson, $utf8NoBom)
Write-Host ("  extracted {0} (+ .hilbertraum-runtime.json install marker)" -f ($requiredFileNames -join ', ')) -ForegroundColor Green
exit 0