Skip to content

AI, fully local on your computer.

105 KB
Raw Blame
import { createHash, randomUUID } from 'node:crypto'
import { createReadStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
import { totalmem } from 'node:os'
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
import { parse as parseYaml } from 'yaml'
import {
  declaresUnknownRole,
  isRealSha256,
  manifestNeedsNewerApp,
  parseUnsupportedManifest,
  pickManifestForRole,
  validateManifest,
  type ModelManifest,
  type ModelRole,
  type UnsupportedManifest
} from '../../shared/manifest'
import type {
  AppSettings,
  GpuDevice,
  HardwareProfile,
  MemoryClass,
  ModelDownloadInfo,
  ModelFileVerdict,
  ModelInfo,
  ModelPlacement,
  ModelState,
  ModelVerifyProgress
} from '../../shared/types'
import { tMain } from './i18n'
import { log } from './logging'
import { perfEnabled, perfMark, perfMs } from './perf'
import { recordChecksumRead } from './read-speed'
import type { Db } from './db'
import { getSettings, updateSettings } from './settings'
import { SLOW_TOKENS_PER_SECOND } from '../../shared/performance-rules'

// Model manager (spec §7.4): discover manifests, verify checksums, compute model
// states, recommend by hardware profile, and select the active chat/embedding model.
// All offline — manifests are local YAML; weights are local files. No network.

/**
 * Runtime → formats this app can actually run (the spec §7.4 `unsupported` gate).
 * Support is a PAIR check — a manifest claiming `whisper_cpp` with `gguf` (or
 * `llama_cpp` with `ggml`) is still unsupported, never a silent pass.
 *
 * This is the CANONICAL support table. `drive.ts` verifyDriveModels (the sell gate) and
 * the self-contained `verify-models.{ps1,sh}` scripts re-spell the SAME pairs (asserted by
 * script-drift.test.ts M-A1) — so a bundled whisper weight (ggml/whisper_cpp) verifies by
 * SHA-256 on every path instead of being falsely reported UNSUPPORTED (which would fail the
 * ship gate for any drive that bundles Whisper).
 */
export const SUPPORTED_RUNTIME_FORMATS: ReadonlyMap<string, ReadonlySet<string>> = new Map([
  ['llama_cpp', new Set(['gguf'])],
  ['llama.cpp', new Set(['gguf'])],
  ['whisper_cpp', new Set(['ggml'])]
])

/** The §7.4 support gate as a predicate: is this (runtime, format) pair one the app ships +
 *  verifies? The single source of truth both `computeInstallState` and `verifyDriveModels` use. */
export function isSupportedRuntimeFormat(runtime: string, format: string): boolean {
  return SUPPORTED_RUNTIME_FORMATS.get(runtime)?.has(format) ?? false
}
const MANIFEST_EXTENSIONS = new Set(['.yaml', '.yml'])
/**
 * Reserved filenames under `model-manifests/` that are NOT model manifests.
 * `runtime-sources.yaml` describes the llama.cpp sidecar builds, not a model, and would
 * fail `validateManifest` — skip it during model discovery (it has its own validator).
 */
const RESERVED_MANIFEST_FILES = new Set(['runtime-sources.yaml', 'runtime-sources.yml'])

export interface DiscoveredManifest {
  manifest: ModelManifest
  sourceFile: string
}

/** #847: a manifest for a newer HilbertRaum found on the drive (display only; see `UnsupportedManifest`). */
export interface DiscoveredUnsupported {
  manifest: UnsupportedManifest
  sourceFile: string
}

export interface DiscoveryResult {
  manifests: DiscoveredManifest[]
  /**
   * #847: manifests for a newer HilbertRaum, listed instead of dropped. Never in `manifests`, so nothing that
   * selects, starts, verifies or downloads a model can reach one; the Models screen lists them, the sell gate
   * counts them as a defect. One id space with `manifests`, where a usable manifest always keeps its id
   * (F-847-4): a same-id entry here is reported in `errors` as a duplicate instead.
   */
  unsupported: DiscoveredUnsupported[]
  /** One human-readable line per file that failed to parse/validate. */
  errors: string[]
}

/**
 * #847 (a+): the app version a manifest's `min_app_version` is compared with. ONE module-level value, set
 * once at startup from `app.getVersion()` (main/index.ts) and by the sell gate from its `--app-version`,
 * instead of a parameter on 13 call sites, where one forgotten caller would treat a too-new manifest as
 * usable. Until it is set the version is unknown, and a manifest naming a `min_app_version` is listed as
 * needing a newer HilbertRaum (`manifestNeedsNewerApp` is fail-safe).
 */
let manifestAppVersion = ''

export function setManifestAppVersion(version: string): void {
  manifestAppVersion = version
}

/**
 * Find the `model-manifests/` directory by walking up from a starting dir.
 * Manifests are committed to git, so they sit at the repo/app root. Packaging places
 * them under resources; the drive launchers set HILBERTRAUM_MANIFESTS_DIR to the drive's copy
 * (one source of truth with the verify/fetch scripts). A set-but-missing override
 * falls back to the walk-up instead of blanking the model list. The override steers the model
 * list only: the engine pins come from {@link resolveBundledManifestsDir} (#842).
 */
export function resolveManifestsDir(startDir: string, override?: string): string | null {
  const env = override?.trim()
  if (env && existsSync(env)) return env

  let dir = startDir
  for (let i = 0; i < 8; i++) {
    const candidate = join(dir, 'model-manifests')
    if (existsSync(candidate) && statSync(candidate).isDirectory()) return candidate
    const parent = dirname(dir)
    if (parent === dir) break
    dir = parent
  }
  return null
}

/**
 * The app's OWN `model-manifests/` (#842): the engine pins, and the OCR installer's second list (per
 * file, #841). No override ever
 * reaches it. A packaged build takes exactly `<resources>/model-manifests` (the `extraResources` copy)
 * and null when that is missing: a walk-up could climb out of the app to a user-writable folder above
 * it, the drive's own copy included. A dev build takes the checkout's, by the walk-up.
 */
export function resolveBundledManifestsDir(opts: {
  isPackaged: boolean
  resourcesPath: string
  appPath: string
}): string | null {
  if (!opts.isPackaged) return resolveManifestsDir(opts.appPath)
  const dir = join(opts.resourcesPath, 'model-manifests')
  return existsSync(dir) && statSync(dir).isDirectory() ? dir : null
}

/**
 * Recursively collect manifest file paths under a directory, every folder's entries in CODE-UNIT order (#848).
 * The walk order is every first-of-role pick (the embedder, reranker, transcriber, translator), the ★ tie-breaks
 * and the winner of a duplicate id, and only NTFS lists a folder sorted: FAT/exFAT (a Kit), ext4 and APFS do not.
 * A plain `<` comparison, never `localeCompare` (ICU and locale dependent), so every OS and UI language agree.
 */
function collectManifestFiles(dir: string): string[] {
  const out: string[] = []
  const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
    a.name < b.name ? -1 : a.name > b.name ? 1 : 0
  )
  for (const entry of entries) {
    const full = join(dir, entry.name)
    if (entry.isDirectory()) {
      out.push(...collectManifestFiles(full))
    } else if (
      MANIFEST_EXTENSIONS.has(extname(entry.name)) &&
      !RESERVED_MANIFEST_FILES.has(entry.name.toLowerCase())
    ) {
      out.push(full)
    }
  }
  return out
}

function extname(name: string): string {
  const i = name.lastIndexOf('.')
  return i < 0 ? '' : name.slice(i).toLowerCase()
}

/**
 * Discover + parse + validate every manifest under `manifestsDir`.
 *
 * **Instrumented for issue #333** (`discover_manifests`, opt-in — `HILBERTRAUM_PERF_LOG=1`).
 * This runs on 13 call sites, `performance:get` among them, and the drive launchers point
 * `HILBERTRAUM_MANIFESTS_DIR` at the removable drive's own copy — so on the shipped path every
 * call is a real read off slow media, and nothing measured it there. The mark splits the cost
 * three ways so the media half and the CPU half can be told apart:
 *
 *   - `walkMs`  — `collectManifestFiles`: the recursive `readdirSync` (directory metadata),
 *   - `readMs`  — the `readFileSync` calls only (the file bytes),
 *   - the remainder (`ms − walkMs − readMs`) — YAML parse + `validateManifest`, pure CPU.
 *
 * The split matters because the OS page cache serves every call after the first from RAM,
 * which leaves the REPEAT cost — what the Performance screen's push-driven refetch actually
 * pays — floored by CPU that a faster drive never moves. A media-only measurement would
 * therefore not settle the cache question #333 asks; both halves have to be on record.
 *
 * All of it is gated on `perfEnabled()`: with the log off (every normal user) this costs one
 * env-var read and nothing else. Content rule holds — counts and durations, never a path.
 */
export function discoverManifests(manifestsDir: string): DiscoveryResult {
  const manifests: DiscoveredManifest[] = []
  const unsupported: DiscoveredUnsupported[] = []
  const errors: string[] = []
  const seenIds = new Map<string, string>() // the manifests this app can use
  const seenNewer = new Map<string, string>() // #847: the entries for a newer HilbertRaum
  const timed = perfEnabled()
  const startedAt = timed ? performance.now() : 0
  let readMs = 0
  let bytes = 0

  // Hoisted out of the `for` head so the walk can be timed apart from the per-file work; an
  // unreadable directory still throws from exactly here, which every caller already handles.
  const files = collectManifestFiles(manifestsDir)
  const walkMs = timed ? performance.now() - startedAt : 0

  for (const file of files) {
    let raw: unknown
    try {
      const readAt = timed ? performance.now() : 0
      const text = readFileSync(file, 'utf8')
      if (timed) {
        readMs += performance.now() - readAt
        bytes += Buffer.byteLength(text, 'utf8')
      }
      raw = parseYaml(text)
    } catch (err) {
      errors.push(`${file}: YAML parse error — ${String(err)}`)
      continue
    }
    // #847: a manifest for a newer HilbertRaum is listed, not validated (this build cannot know the rules a
    // later release applies) and not dropped. The (a+) `min_app_version` is read first: it overrides whatever
    // else the manifest says. Among these the first file in walk order wins; against a usable manifest of the
    // same id it always loses (F-847-4, after the loop).
    if (manifestNeedsNewerApp(raw, manifestAppVersion) || declaresUnknownRole(raw)) {
      const parsed = parseUnsupportedManifest(raw)
      if (!parsed.ok || !parsed.entry) {
        errors.push(`${file}: ${parsed.errors.join('; ')}`)
        continue
      }
      const dupOf = seenNewer.get(parsed.entry.id)
      if (dupOf) {
        errors.push(`${file}: duplicate id "${parsed.entry.id}" (also in ${dupOf})`)
        continue
      }
      seenNewer.set(parsed.entry.id, file)
      unsupported.push({ manifest: parsed.entry, sourceFile: file })
      continue
    }
    const result = validateManifest(raw)
    if (!result.ok || !result.manifest) {
      errors.push(`${file}: ${result.errors.join('; ')}`)
      continue
    }
    const dup = seenIds.get(result.manifest.id)
    if (dup) {
      errors.push(`${file}: duplicate id "${result.manifest.id}" (also in ${dup})`)
      continue
    }
    seenIds.set(result.manifest.id, file)
    manifests.push({ manifest: result.manifest, sourceFile: file })
  }
  if (timed) {
    perfMark('discover_manifests', {
      files: files.length,
      ok: manifests.length,
      bytes,
      ms: perfMs(startedAt),
      walkMs: Math.round(walkMs),
      readMs: Math.round(readMs)
    })
  }
  // #847 (F-847-4, frozen): a manifest this app can use ALWAYS keeps its id, whatever the walk order. A same-id
  // entry for a newer HilbertRaum (e.g. a later release's file for the same model) is the duplicate, never the
  // model's replacement: otherwise an earlier-sorting newer file would leave no usable manifest of that id (no
  // embedder: the mock fallback) where builds up to v0.1.65 keep the model. One id space: every loser is an error.
  const listed = unsupported.filter(({ manifest: entry, sourceFile }) => {
    const usable = seenIds.get(entry.id)
    if (usable) errors.push(`${sourceFile}: duplicate id "${entry.id}" (also in ${usable}, which this app can use)`)
    return !usable
  })
  return { manifests, unsupported: listed, errors }
}

/**
 * Resolve one manifest by id from `manifestsDir`. Never throws — no dir, no id, no match,
 * or an unreadable dir all read as null (the `resolveModelByRole` precedent).
 */
export function findManifestById(
  manifestsDir: string | null,
  modelId: string | null
): ModelManifest | null {
  if (!manifestsDir || !modelId) return null
  try {
    const { manifests } = discoverManifests(manifestsDir)
    return manifests.find((m) => m.manifest.id === modelId)?.manifest ?? null
  } catch {
    return null
  }
}

/**
 * The context window a chat-runtime start launches with (llama-server's `--ctx-size`):
 * the user's context-size pick (AI Model screen) wins; automatic (null) = the model's
 * recommended window, falling back to the legacy setting for a manifest without one
 * (`recommended_context_tokens: 0`) — or when no manifest resolves at all. This is the
 * ONE spelling of that precedence: `startModelRuntime` launches with it, and the
 * no-runtime window (`contextWindowOrNextLaunch` in chat.ts — the doc-task budget and, since
 * #779, the composer meter) mirrors it (full-audit 2026-07-10 BE-5 — the two
 * used to be spelled independently and disagreed, so with no runtime up the tree-build
 * size gate planned against the legacy 4096 default instead of the 32k+ window the next
 * start would actually use, over-marking documents `tree_status='pending'`).
 */
export function launchContextTokens(
  settings: { contextTokens: number; contextTokensOverride?: number | null },
  manifest: Pick<ModelManifest, 'recommendedContextTokens'> | null
): number {
  return (
    settings.contextTokensOverride ?? (manifest?.recommendedContextTokens || settings.contextTokens)
  )
}

/**
 * Thrown when a hash was stopped by its caller's `AbortSignal` (#420) — never by an I/O
 * failure, a missing file or a mismatch. Callers tell the two apart with `isHashAborted`:
 * a cancelled verification is a calm outcome (what finished is cached, the rest is simply
 * unchecked), an I/O failure is not.
 */
class HashAbortedError extends Error {
  constructor(filePath?: string) {
    super(filePath ? `Hashing was cancelled: ${filePath}` : 'Hashing was cancelled')
    this.name = 'HashAbortedError'
  }
}

/** Is this the #420 cancellation, as opposed to a real hashing failure? */
function isHashAborted(err: unknown): boolean {
  return (
    err instanceof HashAbortedError || (err as { name?: string } | null)?.name === 'HashAbortedError'
  )
}

/**
 * Stream a file through SHA-256 (large GGUF files never fully buffer in memory).
 * `onProgress` (optional) receives the running byte count, throttled to at most one call
 * per `PROGRESS_CHUNK_BYTES` (so the 64 KB read chunks of a multi-GB weight don't flood
 * IPC) — plus a final exact-total call. Used to drive the first-run verification bar.
 *
 * An unaborted hash settles only once the stream has CLOSED the file (#1033): when it resolves, the file is no longer
 * held open, so a caller may rename or delete it, or its folder, right away (Windows refuses a folder rename while a
 * file inside is open). A close that fails after the whole file was read still resolves the digest.
 *
 * `signal` (#420) stops the read. The promise then REJECTS with `HashAbortedError`; it must
 * never simply stop settling, because `computeInstallState`, `buildModelList`, the
 * `listModels` handler and the renderer's busy flag all park on it. That is why the abort
 * destroys the stream WITH an error: a bare `stream.destroy()` emits `close` and no
 * `error`, so a naive abort would leave every awaiting caller waiting forever. For an
 * unaborted hash every outcome waits for the file's close: `close` hands over the digest
 * after `end`, or rejects when it came without `end` or `error`, and a failed read reports
 * its `error` once the stream has closed the file. An abort that lands after `end` stops
 * nothing and settles at once with the digest, as before #1033; the close finishes in the
 * background. The parameter is OPTIONAL and trailing: every caller that does not pass one (the
 * ship-time gates, the asset/binary/drive/ingestion verifiers) stays uncancellable by
 * construction. The model download passes its job's signal (#752).
 */
export function sha256File(
  filePath: string,
  onProgress?: (bytesHashed: number) => void,
  signal?: AbortSignal
): Promise<string> {
  return new Promise((resolve, reject) => {
    // An already-aborted signal never opens the file.
    if (signal?.aborted) {
      reject(new HashAbortedError(filePath))
      return
    }
    const hash = createHash('sha256')
    const stream = createReadStream(filePath)
    let hashed = 0
    let lastReported = 0
    let settled = false
    /** Taken at `end`; handed over on `close` (#1033), or at once to an abort that lands after `end`. */
    let digest: string | null = null
    const onAbort = (): void => {
      // An abort once the whole file is read (from the final progress call, or while the file closes) stops nothing,
      // and must not wait for the close either: a saturated pool can hold it, and every caller parks on this promise
      // (#420). The finished hash settles at once, as when it resolved at `end`; the close finishes in the background.
      const finished = digest
      if (finished !== null) settle(() => resolve(finished))
      else stream.destroy(new HashAbortedError(filePath))
    }
    /** Settle exactly once and drop the signal listener — one pass hashes many files off
     *  ONE signal, so an un-removed listener per file would pile up on it. */
    const settle = (finish: () => void): void => {
      if (settled) return
      settled = true
      signal?.removeEventListener('abort', onAbort)
      finish()
    }
    signal?.addEventListener('abort', onAbort, { once: true })
    // A close that fails once the whole file was read does not undo the hash: it resolves, as before #1033.
    stream.on('error', (err) => settle(() => (digest !== null ? resolve(digest) : reject(err))))
    stream.on('data', (chunk) => {
      hash.update(chunk)
      hashed += chunk.length
      if (onProgress && hashed - lastReported >= PROGRESS_CHUNK_BYTES) {
        lastReported = hashed
        onProgress(hashed)
      }
    })
    // #1033: the digest is taken at `end`, but handed over on `close` (an abort after `end` takes it at once, above).
    // The stream closes its file after `end`, on libuv's thread pool, so under load a caller that renamed the file's
    // folder right after the hash still found the file open: Windows refuses that rename (EPERM).
    stream.on('end', () => {
      digest = hash.digest('hex')
      if (onProgress && hashed !== lastReported) onProgress(hashed)
    })
    stream.on('close', () =>
      settle(() => {
        if (digest !== null) resolve(digest)
        else
          reject(
            signal?.aborted
              ? new HashAbortedError(filePath)
              : new Error(`Read stream for ${filePath} closed before it finished`)
          )
      })
    )
  })
}

/** Throttle granularity for `sha256File` progress callbacks (64 MB). */
const PROGRESS_CHUNK_BYTES = 64 * 1024 * 1024

export interface ChecksumResult {
  exists: boolean
  /** null when there is no real expected hash to compare against (placeholder). */
  matched: boolean | null
  actual: string | null
}

// ---- checksum cache -----------------------------------------------------------------
// `listModels` runs on every Models-screen visit AND every Chat-screen mount. Without a
// cache that re-hashed every multi-GB GGUF on the drive each time — minutes of USB I/O
// per navigation. Hash once per (path, size, mtime); a changed/replaced file re-hashes.
// Two tiers: an in-memory map (L1) plus an optional injected persistent store (L2,
// `AppSettings.checksumCache`) so a restarted app does not re-hash unchanged weights.
// Limitation (accepted): a same-size, mtime-preserving in-place tamper is not re-detected
// while the cache entry lives — the Models screen's "Verify checksum" forces a real
// re-hash, the ship-time gates (verify-models --strict / assertCommercialDrive) always
// hash fully, and mtime can be forged by an attacker anyway.

export interface CachedHash {
  size: number
  mtimeMs: number
  actual: string
}

/** Persistent (L2) hash cache. `createSettingsHashStore` is the production impl. */
export interface HashStore {
  get(path: string): CachedHash | null
  set(path: string, entry: CachedHash): void
  delete(path: string): void
}

/** #933: a hash cache that can only be read (`checksumCacheView`): it has no way to write. */
export type HashStoreReader = Pick<HashStore, 'get'>

const hashCache = new Map<string, CachedHash>()

/** How many full-file hashes were actually computed (`install_state_done.cacheHit` reads it; tests too). */
export const checksumCacheStats = { computed: 0 }

// ---- checksum instrumentation (#106) -------------------------------------------------
// A real multi-GB hash is the dominant pre-start cost on slow media, and whichever path
// hashes FIRST (the unlock auto-start, a Models-screen visit, the runtime start, or the
// download verify) was invisible: `install_state_done` only covers the start path, and
// app.log had no line at all. One mark pair + one plain log line per PHYSICAL hash, fired
// at the single choke point where hashing actually happens — never at the (many) cache
// traversals above it.

/** Identity for a checksum instrumentation record. The perf-log content rule
 *  (services/perf.ts) allows model/backend ids but never file names or paths, so the
 *  file is named by its manifest slot, not its basename. */
export interface ChecksumLabel {
  modelId: string | null
  file: 'weight' | 'mmproj' | 'extra' | 'download' | null
}

/** Monotonic id pairing `checksum_start`/`checksum_done` marks: concurrent hashes of
 *  DIFFERENT files interleave in the log, so the pair carries a shared seq. */
let hashSeq = 0

/**
 * Begin one `checksum_start`/`checksum_done` mark + log pair around a real full-file
 * hash. Shared by `sha256FileCached` (the cached model-weight path) and the download
 * manager's verify-after-download (the one model-weight hash that bypasses the cache).
 * `end` never throws (perfMark and log both swallow their own failures).
 *
 * `filePath` (#392) is the absolute file being hashed, forwarded to `recordChecksumRead` so a
 * later model-load window over the same file records no page-cache-warm sample. It stays OUT of
 * `ChecksumLabel` deliberately: the label feeds `perfMark`, and the perf-log content rule
 * forbids file names and paths (see the label's own doc above). Callers pass null when the path
 * must not be remembered — the download verify's `.part` is renamed away afterwards.
 */
export function beginChecksumInstrumentation(
  label: ChecksumLabel,
  bytes: number | null,
  filePath?: string | null
): { end: (ok: boolean) => void } {
  const seq = ++hashSeq
  const t0 = performance.now()
  perfMark('checksum_start', { seq, modelId: label.modelId, file: label.file, bytes })
  return {
    end: (ok: boolean): void => {
      const ms = perfMs(t0)
      perfMark('checksum_done', { seq, modelId: label.modelId, file: label.file, bytes, ms, ok })
      // The issue asks for visibility WITHOUT the opt-in perf log: one app.log line per
      // real hash. app.log may carry model ids and byte counts (never chat/doc content).
      log.info('Model checksum hashed', { modelId: label.modelId, file: label.file, bytes, ms, ok })
      // #108: a completed full-file hash of a COLD file is also an honest
      // sequential-read sample. The 'download' verify is excluded: it hashes the .part
      // the app just WROTE, whose pages are still cache-resident (fsync flushes but
      // does not evict — the F-35 mechanism), so it would record hash-CPU speed as a
      // media figure and suppress the #110 warning on the exact slow-stick fresh
      // install the feature targets.
      if (ok && bytes != null && label.file !== 'download') {
        recordChecksumRead(bytes, ms, label.modelId, filePath)
      }
    }
  }
}

/**
 * In-flight full-file hashes keyed by absolute path (#106). Concurrent callers — the
 * unlock auto-start racing a Models-screen mount, or the Models screen's status poll
 * kicking off a full `listModels` every 2.5 s while a cold start is mid-hash — used to
 * EACH start their own multi-GB read of the SAME file (`hashCache.set` only lands after
 * the await, so every overlapping caller missed). Joiners now share the one physical
 * hash: progress sinks are multicast, each joiner still writes its own L2 store, and
 * `checksumCacheStats.computed` counts physical hashes only.
 */
interface InFlightHash {
  promise: Promise<string>
  sinks: Set<(bytesHashed: number) => void>
  /** The LEADER's stat identity — joiners persist exactly this entry (see below). */
  size: number
  mtimeMs: number
  /**
   * #420 refcount — one token per caller still waiting on this physical read. The rule the
   * whole cancellation design rests on: **the shared read is aborted only when EVERY waiter
   * has abandoned it.** A caller with an abort signal drops its token and rejects on its own
   * the moment that signal fires (so its loop stops at once), but the read itself continues
   * for anyone else. A caller with NO signal — the §7.4 start gate, `verifyModel`, the
   * ship-time gates — holds a token it never drops, so it can never be collateral damage of
   * a cancelled Models-screen pass that happened to join the same file.
   */
  waiters: Set<object>
  /**
   * Abort the shared physical read (only ever called with an empty `waiters`). The entry leaves
   * `inFlightHashes` here, not when the stream closes (#752): a caller arriving in between would
   * join a read nobody wants any more and reject, which is the collateral damage the rule above
   * rules out. That caller starts its own read instead.
   */
  abort: () => void
}

const inFlightHashes = new Map<string, InFlightHash>()

/**
 * Wait on a shared in-flight hash as ONE waiter (#420). Without `signal` this is the
 * pre-#420 behaviour plus a permanent token, i.e. an uncancellable wait that pins the read.
 * With `signal`, an abort settles THIS caller immediately — the physical read only stops if
 * this was the last waiter.
 */
function awaitInFlightHash(
  entry: InFlightHash,
  onProgress?: (bytesHashed: number) => void,
  signal?: AbortSignal
): Promise<string> {
  const token = {}
  entry.waiters.add(token)
  if (!signal) return entry.promise
  return new Promise<string>((resolve, reject) => {
    let settled = false
    const finish = (fn: () => void): void => {
      if (settled) return
      settled = true
      signal.removeEventListener('abort', onAbort)
      entry.waiters.delete(token)
      fn()
    }
    function onAbort(): void {
      if (settled) return
      // Stop feeding this caller's bar, then hand the read over to whoever is left.
      if (onProgress) entry.sinks.delete(onProgress)
      finish(() => {
        if (entry.waiters.size === 0) entry.abort()
        reject(new HashAbortedError())
      })
    }
    signal.addEventListener('abort', onAbort, { once: true })
    entry.promise.then(
      (actual) => finish(() => resolve(actual)),
      (err) => finish(() => reject(err))
    )
  })
}

/** Drop one file's cached hash everywhere — the "Verify checksum" forced re-hash. */
export function invalidateChecksum(filePath: string, store?: HashStore): void {
  hashCache.delete(filePath)
  store?.delete(filePath)
}

/**
 * Seed the checksum cache with a hash ALREADY computed for `filePath` (e.g. the in-app
 * downloader just SHA-256-verified the bytes it wrote). Keyed by the file's current
 * (size, mtimeMs) like every cache entry, so the next `computeInstallState` reports
 * `installed` WITHOUT re-hashing the multi-GB weight — this removes the invisible
 * post-download "Checking…" gap where the Models card briefly looked un-downloaded
 * (audit FE, download→verify UX). A no-op if the file has vanished.
 */
export function primeChecksum(filePath: string, actual: string, store?: HashStore): void {
  let st: ReturnType<typeof statSync>
  try {
    st = statSync(filePath)
  } catch {
    return // file moved/removed before we could prime — the next verify hashes normally
  }
  const entry: CachedHash = { size: st.size, mtimeMs: st.mtimeMs, actual }
  hashCache.set(filePath, entry)
  store?.set(filePath, entry)
}

/**
 * Drive-relative, OS-stable cache KEY for an absolute weight path (CODE-15, full-audit
 * 2026-07-11). The checksum cache was keyed by absolute path, so moving the drive between
 * machines (`E:\…` → `F:\…`, or `/Volumes/…` ↔ a Windows letter) forced a full multi-GB
 * re-hash and left the old absolute keys as permanent orphans in the settings blob. Keying by
 * the path RELATIVE to the drive root (with forward slashes, matching a manifest's own
 * `local_path`) makes the key independent of the mount point. A path that escapes the root
 * (should never happen — weight paths are `safeDrivePath`-guarded) falls back to the absolute
 * path verbatim, so behaviour never silently changes.
 */
function driveRelKey(rootPath: string, absPath: string): string {
  const rel = relative(rootPath, absPath)
  if (!rel || rel.startsWith('..') || isAbsolute(rel)) return absPath
  return rel.split(sep).join('/')
}

/**
 * HashStore over `AppSettings.checksumCache` (settings rows live inside the DB).
 *
 * Lock-aware (BE-2, full-audit 2026-07-10): takes a GETTER, not a raw handle — the stores are
 * created once at IPC registration, and locking an encrypted workspace CLOSES the DB handle a
 * multi-hour download job would otherwise still hold; the getter resolves the LIVE handle per
 * call. Every operation additionally catches DB errors (locked/closed workspace) and degrades
 * to a store-local in-memory fallback: the persistent cache is an optimization, and a store
 * fault must never throw into a caller's job/state machinery (a verified download that finished
 * while the workspace was locked must still report success). The fallback is consulted ONLY
 * when the DB is unreachable — a live DB read always wins, so cross-instance invalidations
 * ("Verify checksum") are never shadowed by a stale local entry.
 *
 * Keyed by drive-RELATIVE path (CODE-15, full-audit 2026-07-11), so a drive-letter move
 * re-hashes nothing. Callers still pass the absolute path (its size+mtime
 * is the validity check, unchanged); the store derives the relative key. Pre-migration entries
 * were keyed absolutely — on a relative-key miss the store lazily adopts a legacy absolute-key
 * entry (rewrites it under the relative key, drops the orphan), so old caches migrate as they
 * are read/written without a forced re-hash.
 */
export function createSettingsHashStore(getDb: () => Db, rootPath: string): HashStore {
  const fallback = new Map<string, CachedHash>()
  const keyFor = (path: string): string => driveRelKey(rootPath, path)
  return {
    get(path) {
      const key = keyFor(path)
      try {
        // Read-side belt (BE-1, full-audit 2026-07-10): a row corrupted to `checksumCache: null`
        // before the settings write gate rejected it must degrade to a cache miss, not throw out
        // of every checksum reader; the next set() rewrites a healthy object over it.
        const db = getDb()
        const cache = getSettings(db).checksumCache ?? {}
        let entry = cache[key]
        if (!entry && key !== path && cache[path]) {
          // Lazy migration (CODE-15): a legacy absolute-key entry survives a drive move — adopt it
          // under the relative key and drop the absolute orphan so it re-hashes nothing and the
          // stale key is cleaned as it is read. Best-effort — the read below still serves the value
          // even if the write can't land (locked/closed workspace).
          entry = cache[path]
          try {
            const next = { ...cache }
            next[key] = entry
            delete next[path]
            updateSettings(db, { checksumCache: next })
          } catch {
            /* migrate is best-effort; the value is still returned below */
          }
        }
        return entry ? { size: entry.size, mtimeMs: entry.mtimeMs, actual: entry.sha256 } : null
      } catch {
        return fallback.get(path) ?? null
      }
    },
    set(path, entry) {
      fallback.set(path, entry)
      const key = keyFor(path)
      try {
        const db = getDb()
        const cache = { ...getSettings(db).checksumCache }
        cache[key] = { size: entry.size, mtimeMs: entry.mtimeMs, sha256: entry.actual }
        // Drop any legacy absolute-key twin so the blob never carries both (CODE-15 orphan cleanup).
        if (key !== path && path in cache) delete cache[path]
        updateSettings(db, { checksumCache: cache })
      } catch {
        /* workspace locked/closed — the in-memory fallback above keeps the session served */
      }
    },
    delete(path) {
      fallback.delete(path)
      const key = keyFor(path)
      try {
        const db = getDb()
        const cache = { ...getSettings(db).checksumCache }
        let changed = false
        if (key in cache) {
          delete cache[key]
          changed = true
        }
        // Also evict a legacy absolute-key twin (CODE-15) so a forced re-hash starts fully clean.
        if (key !== path && path in cache) {
          delete cache[path]
          changed = true
        }
        if (changed) updateSettings(db, { checksumCache: cache })
      } catch {
        /* workspace locked/closed — nothing persisted is reachable to delete right now */
      }
    }
  }
}

/**
 * #933 (A S-A8): a READ-ONLY view of a `checksumCache` the caller has already read (the Performance snapshot's
 * `settings`), keyed like `createSettingsHashStore` (drive-relative, a legacy absolute key still honoured). Unlike
 * that store's `get`, it never reads settings again and never writes: the store adopts a legacy key with a settings
 * write, which a display getter must not do.
 */
export function checksumCacheView(
  cache: AppSettings['checksumCache'] | null | undefined,
  rootPath: string
): HashStoreReader {
  return {
    get(path) {
      // A row corrupted to `checksumCache: null` reads as an empty cache (the store's BE-1 belt).
      const entry = cache?.[driveRelKey(rootPath, path)] ?? cache?.[path]
      return entry ? { size: entry.size, mtimeMs: entry.mtimeMs, actual: entry.sha256 } : null
    }
  }
}

/**
 * SHA-256 of a file, cached by (path, size, mtimeMs) — memory first, then `store`.
 * `onProgress` fires only on a real cache MISS (a cache hit does no I/O), so callers can
 * weight the verification bar by the bytes actually hashed. Concurrent calls for the
 * same path share ONE physical hash (single-flight, #106); a real hash emits one
 * `checksum_start`/`checksum_done` mark pair + one app.log line via
 * `beginChecksumInstrumentation`.
 */
async function sha256FileCached(
  filePath: string,
  store?: HashStore,
  onProgress?: (bytesHashed: number) => void,
  label?: ChecksumLabel,
  signal?: AbortSignal
): Promise<string> {
  // #420: an already-cancelled pass reads nothing at all, not even a cache entry.
  if (signal?.aborted) throw new HashAbortedError(filePath)
  const st = statSync(filePath)
  const hit = hashCache.get(filePath)
  if (hit && hit.size === st.size && hit.mtimeMs === st.mtimeMs) return hit.actual
  const persisted = store?.get(filePath)
  if (persisted && persisted.size === st.size && persisted.mtimeMs === st.mtimeMs) {
    hashCache.set(filePath, persisted)
    return persisted.actual
  }
  // Join an in-flight hash of the same file instead of starting a second concurrent
  // multi-GB read. The joiner still persists to ITS store (the leader may have been
  // created with a different/no store) — but the entry it writes is the LEADER's
  // (leader-stat key + leader digest): keying the leader's digest under the joiner's
  // own, later stat would mint a live-keyed entry whose hash was never computed for
  // that content if the file is replaced mid-hash. The leader's entry stays honestly
  // stale-keyed in that race, exactly like a pre-single-flight hash.
  const inFlight = inFlightHashes.get(filePath)
  if (inFlight) {
    if (onProgress) inFlight.sinks.add(onProgress)
    const actual = await awaitInFlightHash(inFlight, onProgress, signal)
    store?.set(filePath, { size: inFlight.size, mtimeMs: inFlight.mtimeMs, actual })
    return actual
  }
  const sinks = new Set<(bytesHashed: number) => void>()
  if (onProgress) sinks.add(onProgress)
  // #392: this branch is the real cache MISS — a physical multi-GB read that leaves the file
  // page-cache-warm. Hand the path over so a later model-load window over it never samples RAM.
  const instrumentation = beginChecksumInstrumentation(
    label ?? { modelId: null, file: null },
    st.size,
    filePath
  )
  // #420: the abort controller belongs to the PHYSICAL read, not to any one caller —
  // `awaitInFlightHash` fires it only once every waiter has abandoned the read.
  const controller = new AbortController()
  const entry: InFlightHash = {
    promise: undefined as unknown as Promise<string>,
    sinks,
    size: st.size,
    mtimeMs: st.mtimeMs,
    waiters: new Set<object>(),
    abort: () => {
      if (inFlightHashes.get(filePath) === entry) inFlightHashes.delete(filePath)
      controller.abort()
    }
  }
  // The instrumentation, the `computed` counter and both cache writes now live INSIDE the
  // run, because the run outlives its leader: a leader that cancels while a joiner is still
  // waiting must not close the pair for a read that is still going (and a cancelled read
  // must still close it with ok:false, which is what keeps a cancelled hash out of the #108
  // read sample and out of #392's `checksumWarmedPaths`).
  const run = (async (): Promise<string> => {
    try {
      const actual = await sha256File(
        filePath,
        (b) => {
          for (const sink of sinks) sink(b)
        },
        controller.signal
      )
      // Count + cache only a COMPLETED physical hash (a throwing hash increments nothing,
      // matching the pre-#106 behaviour `install_state_done.cacheHit` depends on).
      checksumCacheStats.computed += 1
      const cached: CachedHash = { size: st.size, mtimeMs: st.mtimeMs, actual }
      hashCache.set(filePath, cached)
      store?.set(filePath, cached)
      instrumentation.end(true)
      return actual
    } catch (err) {
      instrumentation.end(false)
      throw err
    } finally {
      // Only ever retire OUR OWN entry (a later hash of the same path may already have
      // registered its own).
      if (inFlightHashes.get(filePath) === entry) inFlightHashes.delete(filePath)
    }
  })()
  entry.promise = run
  inFlightHashes.set(filePath, entry)
  return awaitInFlightHash(entry, onProgress, signal)
}

/**
 * Is there a LIVE cached hash (L1 memory or L2 store) for this file, matching its current
 * size+mtime? RT-3 uses this so the lazy/chat path still serves a cached checksum for free
 * (honest state) and only SKIPS the multi-GB hash for genuinely un-cached weights.
 */
function cachedHashFor(filePath: string, store?: HashStore): boolean {
  return cachedHashOf(filePath, store) !== null
}

/**
 * The LIVE cached digest of this file (L1 memory, then the L2 store, matching its current size+mtime), or null when
 * there is none. Hashes nothing. #913 (S-913-1): the lazy path reads it to honour a cached MISMATCH on any one file of
 * a model, which a full check that stopped at that file left as the only cached entry.
 */
function cachedHashOf(filePath: string, store?: HashStoreReader): string | null {
  let st: ReturnType<typeof statSync>
  try {
    st = statSync(filePath)
  } catch {
    return null
  }
  const hit = hashCache.get(filePath)
  if (hit && hit.size === st.size && hit.mtimeMs === st.mtimeMs) return hit.actual
  const persisted = store?.get(filePath)
  return persisted && persisted.size === st.size && persisted.mtimeMs === st.mtimeMs ? persisted.actual : null
}

/**
 * #933: what the checksum cache already knows about a model's files, synchronously and without hashing anything by
 * construction (a `statSync`, an in-memory lookup and a `store.get` per file, never `sha256File`): a placeholder hash
 * outside developer leniency is `unverified`; a live cached digest that differs from the manifest's is `damaged` (a
 * check found it so); anything else is `ok` (verified, or not checked yet). The same two facts `computeInstallState`'s
 * lazy branch turns into `checksum_failed`, so the Performance rows and the AI Model card agree. A path that escapes
 * the drive root names no file on it: `ok` here (the presence rule already reads it as absent).
 */
export function knownFileVerdict(
  manifest: ModelManifest,
  rootPath: string,
  opts: { developerMode: boolean; hashStore?: HashStoreReader }
): ModelFileVerdict {
  let files: ManifestFile[]
  try {
    files = manifestFiles(rootPath, manifest)
  } catch {
    return 'ok'
  }
  if (files.some((f) => !isRealSha256(f.sha))) return opts.developerMode ? 'ok' : 'unverified'
  for (const f of files) {
    const actual = cachedHashOf(f.path, opts.hashStore)
    if (actual !== null && actual !== f.sha) return 'damaged'
  }
  return 'ok'
}

/**
 * #959: `knownFileVerdict` for a list of manifests, keyed by manifest id: the before and after of a pass that may
 * write the checksum cache. Same guarantees: synchronous, never hashes.
 */
export function knownVerdicts(
  manifests: readonly ModelManifest[],
  rootPath: string,
  opts: { developerMode: boolean; hashStore?: HashStoreReader }
): Map<string, ModelFileVerdict> {
  return new Map(manifests.map((m) => [m.id, knownFileVerdict(m, rootPath, opts)]))
}

/** Verify a weight file against its expected SHA-256 (cached by size+mtime). `label`
 *  identifies a real hash in the #106 instrumentation (marks + app.log). */
export async function verifyChecksum(
  filePath: string,
  expected: string,
  store?: HashStore,
  onProgress?: (bytesHashed: number) => void,
  label?: ChecksumLabel,
  signal?: AbortSignal
): Promise<ChecksumResult> {
  if (!existsSync(filePath)) return { exists: false, matched: null, actual: null }
  const actual = await sha256FileCached(filePath, store, onProgress, label, signal)
  if (!isRealSha256(expected)) return { exists: true, matched: null, actual }
  return { exists: true, matched: actual === expected, actual }
}

/**
 * Absolute path of a manifest's weight file. `local_path` is relative to the drive root.
 * A manifest on a prepared drive lives in a user-writable location, so we reject a
 * `local_path` that escapes the drive root (`..`/absolute) before it could become a
 * `llama-server --model` argument pointing at an arbitrary file.
 */
export function weightPath(rootPath: string, manifest: ModelManifest): string {
  return safeDrivePath(rootPath, manifest.localPath)
}

/**
 * Absolute path of a vision model's mmproj projector file (image-understanding plan §8.2).
 * Same drive-root escape guard as `weightPath` (the projector path also becomes a
 * `llama-server --mmproj` argument). Throws if the manifest carries no `mmproj` block.
 */
export function mmprojPath(rootPath: string, manifest: ModelManifest): string {
  if (!manifest.mmproj) throw new Error(`Model "${manifest.id}" has no mmproj projector`)
  return safeDrivePath(rootPath, manifest.mmproj.localPath)
}

/**
 * Join a manifest-relative path onto the drive root, rejecting one that escapes the root
 * (`..`/absolute) before it could become a `llama-server --model`/`--mmproj` argument
 * pointing at an arbitrary file. Shared by `weightPath` + `mmprojPath`.
 */
function safeDrivePath(rootPath: string, relPath: string): string {
  const full = join(rootPath, relPath)
  const base = resolve(rootPath)
  const resolved = resolve(full)
  // A bare drive root (e.g. `D:\`) already ends in the separator, so `base + sep` would
  // double it (`D:\\`) and reject every legitimate path. Only append a separator when the
  // base does not already end in one.
  const prefix = base.endsWith(sep) ? base : base + sep
  if (resolved !== base && !resolved.startsWith(prefix)) {
    throw new Error(`Manifest path escapes the drive root: ${relPath}`)
  }
  return full
}

/**
 * One verifiable file a manifest carries (the GGUF, a vision model's mmproj projector, or an
 * `extra` file the manifest's `files:` list declares — e.g. shards 2..N of a GGUF shard set).
 */
export interface ManifestFile {
  /** Absolute, escape-guarded path on the drive. */
  path: string
  /** Expected SHA-256 (lower-case hex; may be a placeholder). */
  sha: string
  /** Drive-relative path (forward slashes) for honest reporting (which file failed). */
  localPath: string
  /** Which manifest slot this file fills — labels the #106 checksum instrumentation. */
  kind: 'weight' | 'mmproj' | 'extra'
}

/**
 * The verifiable weight files a manifest carries: always the language GGUF, plus the mmproj
 * projector for a `role: vision` model (image-understanding plan §8.2), plus every ADDITIONAL
 * required file the manifest's `files:` list declares (#310). Install state requires ALL of
 * them present + verified. Each entry has its own expected hash; the checksum cache keys by
 * (path, size, mtime) per file so each is hashed once like the GGUF. Exported so the
 * drive-build verify side (`verifyDriveModels`/`buildChecksumsJson`, DIST-2) iterates exactly
 * the same set the install side does — a drive can never half-pass with only the first file.
 */
export function manifestFiles(rootPath: string, manifest: ModelManifest): ManifestFile[] {
  const files: ManifestFile[] = [
    {
      path: weightPath(rootPath, manifest),
      sha: manifest.sha256,
      localPath: manifest.localPath,
      kind: 'weight'
    }
  ]
  if (manifest.mmproj) {
    files.push({
      path: mmprojPath(rootPath, manifest),
      sha: manifest.mmproj.sha256,
      localPath: manifest.mmproj.localPath,
      kind: 'mmproj'
    })
  }
  // #310: the rest of a multi-file weight, in declaration order, through the same drive-root
  // escape guard as the weight and the projector.
  for (const extra of manifest.files ?? []) {
    files.push({
      path: safeDrivePath(rootPath, extra.localPath),
      sha: extra.sha256,
      localPath: extra.localPath,
      kind: 'extra'
    })
  }
  return files
}

/**
 * #932: does any file this manifest declares (the GGUF, the mmproj projector, the `files:` list: the files
 * `manifestFiles` lists) carry a placeholder hash, so it has no checksum on record? From the manifest alone, no I/O.
 */
export function hasPlaceholderHash(manifest: ModelManifest): boolean {
  const hashes = [
    manifest.sha256,
    ...(manifest.mmproj ? [manifest.mmproj.sha256] : []),
    ...(manifest.files ?? []).map((f) => f.sha256)
  ]
  return hashes.some((sha) => !isRealSha256(sha))
}

export interface InstallStateOptions {
  /** When true, skip checksum verification for placeholder/dev hashes. */
  developerMode: boolean
  /** Optional persistent hash cache (L2) so unchanged weights are hashed once ever. */
  hashStore?: HashStore
  /**
   * Optional per-file hashing progress (running byte count). Fires only when this model's
   * weight is actually hashed (a real, present, non-cached file); drives the first-run bar.
   */
  onProgress?: (bytesHashed: number) => void
  /**
   * RT-3 lazy verification: when true, a present weight with a real expected hash is
   * reported `installed` WITHOUT hashing it. Used on the chat path (`buildModelList`'s
   * lazy mode) to report the inactive models for display without paying minutes of USB
   * I/O to SHA-256 every multi-GB GGUF on a cold cache. The §7.4 verification gate is
   * NOT relaxed: `startModelRuntime` re-verifies the model it actually launches, and the
   * Models screen's explicit "Check all model files" action (#382) + the ship-time gates
   * (verify-models --strict / assertCommercialDrive) still hash fully. A cached hash is
   * still used when present: a cached mismatch on any one file reports `checksum_failed` (#913).
   */
  skipHash?: boolean
  /**
   * #420 cancellation. Checked at the head of the per-file loop AND threaded into the read
   * itself, so a cancel between two multi-GB weights takes effect at once instead of after
   * the current file finishes. Aborting makes this function throw `HashAbortedError`;
   * `buildModelList` turns that into the calm "present but unchecked" answer. Omitted by
   * the §7.4 start gate, `verifyModel` and the ship-time gates, which stay uncancellable.
   */
  signal?: AbortSignal
}

/**
 * #890: the synchronous part of `computeInstallState`, its first two steps in the same order: the runtime/format is
 * one this app supports, and EVERY file the manifest declares (`manifestFiles`: GGUF, mmproj, `files:`) exists. So
 * true means the state is past `unsupported` and `missing`; it verifies no hash. A path that escapes the drive root
 * (`safeDrivePath` throws) names no file on the drive, so it counts as absent rather than throwing to the caller.
 */
export function manifestFilesPresent(rootPath: string, manifest: ModelManifest): boolean {
  if (!isSupportedRuntimeFormat(manifest.runtime, manifest.format)) return false
  let files: ManifestFile[]
  try {
    files = manifestFiles(rootPath, manifest)
  } catch {
    return false
  }
  return files.every((f) => existsSync(f.path))
}

/**
 * Compute the install-level model state (spec §7.4): unsupported | missing |
 * checksum_failed | installed. Runtime states (ready/running) are layered on later.
 */
export async function computeInstallState(
  manifest: ModelManifest,
  rootPath: string,
  opts: InstallStateOptions
): Promise<ModelState> {
  if (!isSupportedRuntimeFormat(manifest.runtime, manifest.format)) {
    return 'unsupported'
  }
  // A model can be several files (GGUF + mmproj; GGUF + the `files:` list's shards, #310);
  // install state requires EVERY one present + verified (image-understanding plan §8.2).
  // A single-file model has exactly one entry, so this loop is byte-identical for it.
  const files = manifestFiles(rootPath, manifest)
  for (const f of files) {
    if (!existsSync(f.path)) return 'missing'
  }
  // #420: a cancel that landed before this model started must stop the pass here, not one
  // multi-GB file later.
  if (opts.signal?.aborted) throw new HashAbortedError()

  // A placeholder hash can never verify, so hashing the (multi-GB) file would be pure
  // wasted I/O — decide from the manifest alone. Outside developer mode an unverifiable
  // file is treated as a checksum failure (spec §7.4 gate); in developer mode it counts
  // as installed. With two files, any placeholder hash short-circuits the same way.
  if (files.some((f) => !isRealSha256(f.sha))) {
    return opts.developerMode ? 'installed' : 'checksum_failed'
  }

  // RT-3: on the lazy (chat) path, report a present weight as installed without hashing —
  // unless the cache can answer for free. A live cached MISMATCH on ANY file decides
  // `checksum_failed` (#913, S-913-1): a full check stops at the first damaged file, so a damaged
  // vision GGUF leaves its projector unhashed, and the lazy pass right after "Check all model
  // files" must not flip it back to installed. A cached MATCH decides nothing until EVERY file
  // has one. The chat start gate re-verifies the model it launches.
  if (opts.skipHash) {
    const cached = files.map((f) => cachedHashOf(f.path, opts.hashStore))
    if (cached.some((actual, i) => actual !== null && actual !== files[i].sha)) return 'checksum_failed'
    if (cached.some((actual) => actual === null)) return 'installed'
  }

  // Verify each file, accumulating the progress byte offset across files so the first-run
  // bar advances monotonically (a cached file contributes 0 bytes and fires no progress).
  let hashedBase = 0
  for (const f of files) {
    // #420 loop head: a cancel between two files of the same model stops it immediately.
    if (opts.signal?.aborted) throw new HashAbortedError(f.path)
    const willHash = isRealSha256(f.sha) && !cachedHashFor(f.path, opts.hashStore)
    const check = await verifyChecksum(
      f.path,
      f.sha,
      opts.hashStore,
      willHash && opts.onProgress ? (b) => opts.onProgress!(hashedBase + b) : undefined,
      { modelId: manifest.id, file: f.kind },
      opts.signal
    )
    if (check.matched === false) return 'checksum_failed'
    if (willHash) {
      try {
        hashedBase += statSync(f.path).size
      } catch {
        /* file vanished mid-verify — the next existsSync pass will report it missing */
      }
    }
  }
  return 'installed'
}

/** #913: what the start check says about a model's files. `damaged` refuses the start; `ok` keeps today's start. */
export type ModelStartVerdict = 'ok' | 'damaged'

/**
 * #913: the start check of one model by its manifest id, as the composition root builds it (`main/index.ts`): the
 * manifest, the policy-aware developer leniency and the workspace hash store. `hash: false` reads the cache only;
 * `hash: true` hashes a file the cache does not know. `signal` aborts a hash in progress.
 */
export type ModelStartCheck = (
  modelId: string,
  /** `manifest`: the one the service was composed with, when the caller holds it (no folder read). */
  opts: { hash: boolean; signal?: AbortSignal; manifest?: ModelManifest }
) => Promise<ModelStartVerdict>

/** #913: one service's start check, bound to its model and its hashing choice (`compose-services.ts`). */
export type BoundModelStartCheck = (signal?: AbortSignal) => Promise<ModelStartVerdict>

/**
 * #913 (C §913.3): the check every non-chat role runs at its cold start, inside its single-flight start and before it
 * spawns, so a file a check found damaged never starts in any role (the chat start gate does its own full hash). Over
 * `computeInstallState` with the same leniency as chat: `hash: false` is the `skipHash` read (a cached mismatch on any
 * file, or a placeholder hash outside developer mode, is `damaged`; nothing is hashed), `hash: true` is the full check
 * (the search and voice models, whose bad output is stored in the index: G-4 (d2), seconds once per workspace).
 *
 * Only a proven case refuses (the #876 rule): a missing or unsupported file is `ok` here, and so is a check that could
 * not finish (a read error), which is logged; the start then fails or runs as it always did. An abort rejects with
 * the hash's own `HashAbortedError`, so a lock or quit during the hash ends the start at once.
 */
export async function checkModelBeforeStart(
  manifest: ModelManifest,
  rootPath: string,
  opts: { developerMode: boolean; hashStore?: HashStore; hash: boolean; signal?: AbortSignal }
): Promise<ModelStartVerdict> {
  let state: ModelState
  try {
    state = await computeInstallState(manifest, rootPath, {
      developerMode: opts.developerMode,
      hashStore: opts.hashStore,
      skipHash: !opts.hash,
      signal: opts.signal
    })
  } catch (err) {
    if (isHashAborted(err) || opts.signal?.aborted) throw err
    log.warn('Model start check could not finish; starting as before', {
      modelId: manifest.id,
      // The code or the name only: a file system error's message names the weight file by its path.
      error: err instanceof Error ? ((err as NodeJS.ErrnoException).code ?? err.name) : 'unknown'
    })
    return 'ok'
  }
  if (state === 'checksum_failed') {
    log.warn('Model start refused: a file of the model failed its check', { modelId: manifest.id })
    return 'damaged'
  }
  return 'ok'
}

/**
 * Will `computeInstallState` actually hash this weight (a real, present, non-cached file
 * with a real expected hash)? Used by `buildModelList`'s pre-pass to compute the
 * verification bar's byte denominator WITHOUT hashing — a cheap `statSync` + cache lookup.
 * Returns the file size to hash, or `0` when the file will be skipped (missing, cached,
 * placeholder hash, unsupported).
 */
function pendingHashBytes(
  manifest: ModelManifest,
  rootPath: string,
  opts: { developerMode: boolean; hashStore?: HashStore }
): number {
  if (!isSupportedRuntimeFormat(manifest.runtime, manifest.format)) return 0
  let files: Array<{ path: string; sha: string }>
  try {
    files = manifestFiles(rootPath, manifest)
  } catch {
    return 0 // an escaping local_path/mmproj path never reaches a hash
  }
  // Any placeholder hash makes `computeInstallState` short-circuit before verifying ANY
  // file — so nothing hashes this pass.
  if (files.some((f) => !isRealSha256(f.sha))) return 0
  let total = 0
  for (const f of files) {
    let st: ReturnType<typeof statSync>
    try {
      st = statSync(f.path)
    } catch {
      return 0 // a missing file → 'missing' before any verify
    }
    // A live cache hit (memory or store, matching size+mtime) means this file won't hash.
    const hit = hashCache.get(f.path)
    if (hit && hit.size === st.size && hit.mtimeMs === st.mtimeMs) continue
    const persisted = opts.hashStore?.get(f.path)
    if (persisted && persisted.size === st.size && persisted.mtimeMs === st.mtimeMs) continue
    total += st.size
  }
  return total
}

/** Recommend a model id for a hardware profile + role (spec §7.3). */
export function recommendModelId(
  manifests: ModelManifest[],
  profile: HardwareProfile,
  role: ModelRole = 'chat'
): string | null {
  const match = manifests.find((m) => m.role === role && m.recommendedProfiles.includes(profile))
  return match?.id ?? null
}

/**
 * Total RAM of this machine in whole GB. Rounded (not floored) so a "16 GB" machine
 * reporting 15.9 GiB usable still counts as 16 — a min-RAM-16 model must not be flagged
 * unusable on the exact hardware it was sized for.
 */
export function machineRamGb(): number {
  return Math.round(totalmem() / 1024 ** 3)
}

/**
 * Measured-speed signal fed into the picker (model-benchmarks.md §6.5, issue #95): the
 * Diagnostics probe's honest pairing (issue #52) — the measured tok/s AND the model that
 * produced it. Absent/null anywhere → the pure RAM-best-fit path, byte-identical.
 *
 * Basis (#291): since 2026-09-04 the figure is the runtime's decode-only `predicted_per_second`
 * (tokens, prefill excluded) whenever the runtime sent `timings`, else the old prefill-inclusive
 * chunk rate. `SLOW_PICK_TOKENS_PER_SECOND` was calibrated on the chunk basis and deliberately
 * NOT retuned — a decode-only figure reads higher, and the gate is an order-of-magnitude crawl
 * test (model-benchmarks.md §6.5 "Basis note").
 */
export interface PickerSpeedSignal {
  /** Measured tok/s from the loaded-model probe; null when the probe did not run. */
  tokensPerSecond: number | null
  /** Id of the model the probe streamed through; null/unresolvable → no signal. */
  measuredModelId?: string | null
}

/** A loaded-model probe STRICTLY below this steps the recommendation down one size tier
 *  (model-benchmarks.md §6.5). Distinct from `VERY_LOW_TOKENS_PER_SECOND` (3), which steps
 *  the legacy PROFILE down — the two thresholds serve different surfaces on purpose. The value
 *  is `shared/performance-rules.ts`' `SLOW_TOKENS_PER_SECOND` (PR #303 audit N3): the
 *  Performance screen's "Slow" speed rating is this very gate, never a re-typed copy. */
export const SLOW_PICK_TOKENS_PER_SECOND = SLOW_TOKENS_PER_SECOND

/** The comfortable-stage ordering (§6.2): capacity first, then rank, then disk size. */
function comfortableOrder(a: ModelManifest, b: ModelManifest): number {
  return (
    b.recommendedRamGb - a.recommendedRamGb ||
    b.recommendationRank - a.recommendationRank ||
    b.sizeOnDiskGb - a.sizeOnDiskGb
  )
}

/** The stage pool (§6.3 ranked-only guard): ranked fits only, unless nothing ranked fits. */
function preferRanked(fits: ModelManifest[]): ModelManifest[] {
  const ranked = fits.filter((m) => m.recommendationRank > 0)
  return ranked.length > 0 ? ranked : fits
}

/**
 * §6.5 step-down: apply the measured-speed signal to a COMFORTABLE-stage pick. The crawl is
 * a valid signal only when the measured model resolves among the role's candidates with a
 * `recommendedRamGb` at or below the pick's (an oversized loaded model is expected to crawl
 * — the #52 lesson — and must never move the pick). The step re-runs the comfortable stage
 * below the pick's whole capacity band over RANKED models only, so it can never land on a
 * rank-0 model; with no lower ranked tier, the original pick stays.
 *
 * `eligible` (the card path, §6.6 rule C step 3; PR #308 audit R1/R2): when given, the measured
 * model counts only if it is in the pick's eligible pool (fits the card AND passes the RAM
 * floor — a crawl on a model the card cannot hold says nothing about a model it can), and the
 * destination must itself be eligible, else the pick stays. Omitted (the RAM path) → the
 * pre-#308 predicate, byte-identical.
 */
function applySpeedSignal(
  candidates: ModelManifest[],
  pick: ModelManifest,
  signal: PickerSpeedSignal | null | undefined,
  eligible?: (m: ModelManifest) => boolean
): ModelManifest {
  if (!signal) return pick
  const tps = signal.tokensPerSecond
  if (tps == null || tps <= 0 || tps >= SLOW_PICK_TOKENS_PER_SECOND) return pick
  const measured = signal.measuredModelId
    ? candidates.find((m) => m.id === signal.measuredModelId)
    : undefined
  if (!measured) return pick
  if (measured.recommendedRamGb > pick.recommendedRamGb) return pick
  if (eligible && !eligible(measured)) return pick
  const lower = candidates
    .filter((m) => m.recommendationRank > 0 && m.recommendedRamGb < pick.recommendedRamGb)
    .filter((m) => !eligible || eligible(m))
    .sort(comfortableOrder)
  return lower[0] ?? pick
}

/**
 * RAM-best-fit recommendation: the LARGEST model whose comfortable RAM
 * (`recommended_ram_gb`) fits this machine; if nothing fits comfortably, the lightest
 * model that at least meets its minimum (`recommended_min_ram_gb`); else null. Replaces
 * the profile-table lookup as the primary recommendation — "which model?" is a RAM
 * question first, and this can never recommend a model the RAM gate disables.
 *
 * QUALITY-AWARE TIEBREAK (model-benchmarks.md §6.2): among models that tie on the
 * capacity fit (same comfortable RAM, or same minimum), prefer the higher
 * `recommendationRank` — the benchmark verdict — BEFORE falling back to disk size. Without
 * ranks (all 0) this is exactly the old biggest-disk behaviour, so legacy callers are
 * unchanged; with ranks the picker stops recommending a benchmark loser (e.g. Granite) over a
 * winner (Ministral) just because it is larger on disk.
 *
 * RANKED-ONLY GUARD (model-benchmarks.md §6.3, issue #48): within each stage, a rank-0
 * model (never benchmarked, or a benchmark loser — §9 grants ranks only after the local
 * eval) is considered ONLY when no ranked model fits that stage at all. Rank is a
 * within-tier tiebreak, not a cross-tier score, so the capacity-first ordering stays —
 * but a bigger-on-disk, never-evaled model can no longer hijack the recommendation from
 * a benchmarked winner by capacity alone. A role whose catalog carries no ranks at all
 * (e.g. embeddings) is unchanged.
 *
 * SPEED-SIGNAL STEP-DOWN (model-benchmarks.md §6.5, issue #95): an optional measured-speed
 * signal steps a comfortable-stage pick down ONE capacity tier when the probe crawled
 * (strictly under `SLOW_PICK_TOKENS_PER_SECOND`) on a right-sized model (predicate in
 * `applySpeedSignal`). Stateless and single-step: the base pick is recomputed from RAM
 * alone on every call, so downgrades never compound. A runnable-stage (fallback) pick
 * never steps — it is already the lightest honest answer. Omitted signal → prior behavior,
 * byte-identical.
 */
export function recommendModelIdByRam(
  manifests: ModelManifest[],
  ramGb: number,
  role: ModelRole = 'chat',
  speedSignal?: PickerSpeedSignal | null
): string | null {
  if (!Number.isFinite(ramGb) || ramGb <= 0) return null
  const candidates = manifests.filter((m) => m.role === role)

  const comfortable = preferRanked(
    candidates.filter((m) => m.recommendedRamGb <= ramGb)
  ).sort(comfortableOrder)
  if (comfortable.length > 0) {
    return applySpeedSignal(candidates, comfortable[0], speedSignal).id
  }

  const runnable = preferRanked(
    candidates.filter((m) => m.recommendedMinRamGb <= ramGb)
  ).sort(
    (a, b) =>
      a.recommendedMinRamGb - b.recommendedMinRamGb ||
      b.recommendationRank - a.recommendationRank ||
      a.sizeOnDiskGb - b.sizeOnDiskGb
  )
  return runnable[0]?.id ?? null
}

// ---- Graphics-memory-aware pick (model-benchmarks.md §6.6; rule C since the PR #308 audit,
// 2026-09-06 — decisions 1, 2, 4, 7, 10, 11). Raw MiB throughout (decision 7): the probe reports
// MiB, the estimate is in MiB, nothing is rounded to a nominal tier; labels round on their own.

/** llama.cpp's `--fit-target` default: the margin the fit keeps free on the card, MiB. */
export const VRAM_FIT_MARGIN_MIB = 1024
/** Working (compute) buffers the runtime reserves beside the weights, as a share of the weights
 *  ON THE CARD (the rig's 27B measured 2.8 GiB on 18.4 GiB of weights at a 2048-token batch,
 *  ~15 %). Applied to the OFFLOADABLE weights since #321 — `estimateGraphicsNeedMib` subtracts a
 *  manifest's measured `host_mapped_weights_mib` first, because buffers scale with what is
 *  actually on the card, not with the embedding tables that stay host-mapped.
 *  KNOWN WEAK (§5 item 22 (e)): the real compute buffers measured 416–569 MiB across models from
 *  3.3 to 19.8 GB — near-flat, because they scale with ubatch and hidden width rather than with
 *  file size — so this share under-reads the smallest models and over-reads the largest. Left as a
 *  share on purpose: a flat term would flip the 8 GB row to the 9B, which #318 leg 2 measured
 *  landing 31/33 there. */
export const VRAM_WORKING_SHARE = 0.15
/**
 * The context-cache term for a manifest that carries no `estimated_context_cache_gib`, GiB
 * (8k tokens on a 27B measured 0.5 under an earlier launch; decision 11 makes the figure
 * per-model — nine manifests carry their own figure, everything else defaults).
 */
export const VRAM_DEFAULT_CONTEXT_CACHE_GIB = 0.5
/**
 * The idle desktop use a card is assumed to carry when the probe reports no free figure, MiB
 * (decision 10: `budget = freeMb ?? totalMb − 1024`; the public `--list-devices` lines in the
 * audit's D3 table show 0.6–1.5 GiB in use on an idle Windows desktop). NOT the fit margin above
 * — that one is the runtime's own reservation and applies on top of the budget.
 */
export const GRAPHICS_IDLE_ALLOWANCE_MIB = 1024

/**
 * The manifest's decimal "size on disk" (GB, 1e9) as UNROUNDED MiB — the unit the probe reports
 * in. Shared with the Performance screen's pre-start estimate (`placementVerdict`, decision 8) so
 * the two surfaces cannot disagree by a rounding step.
 */
export function weightsMib(m: ModelManifest): number {
  return (m.sizeOnDiskGb * 1e9) / 1024 ** 2
}

/**
 * What the runtime needs ON THE CARD to hold every layer of this model, MiB.
 *
 * **Since model-benchmarks.md §6.8 (2026-11-20) a manifest's `projected_graphics_need_mib` decides
 * when it is present:** the figure llama.cpp's own fit prints ("projected to use N MiB of device
 * memory") under the app's launch, plus the same 1 GiB margin. Every manifest the card path can
 * pick carries one (pinned in `committed-catalog.test.ts`). The DERIVED estimate below is the
 * fallback for a manifest without one (a model added before it is measured, or installed by hand),
 * and the rest of this comment is its history:
 *
 *     (weights − hostMapped) × 1.15  +  contextCache  +  1 GiB fit margin
 *
 * — the weights that actually reach the card, the runtime's working buffers beside them (15 %),
 * the context cache at the model's recommended window under the app's launch (the manifest's
 * `estimated_context_cache_gib`, else 0.5 GiB), and the fit's own 1 GiB `--fit-target` margin.
 *
 * **Host-mapped weights are subtracted from the BASE, not only from the working share** (BUILD_STATE
 * §5 item 22 (e), 2026-09-08). #321 took them out of the 15 % share on the reasoning that the share
 * stands for buffers beside the weights on the card; the same reasoning applies with far more force
 * to the weights term itself, and that is where the error actually lived. Measured against the five
 * full-offload starts of #318 — estimate against what the card was really asked for:
 *
 *     E2B   4,746 → 4,423 → 2,271   vs 1,998 measured   (2.4× → 2.2× → 1.14×)
 *     9B    8,014 → 7,830 → 7,285   vs 6,007            (1.33× → 1.30× → 1.21×)
 *     G12  11,159 → 11,041 → 10,254 vs 9,227            (1.21× → 1.20× → 1.11×)
 *     Q4   20,247 → 19,940 → 19,258 vs 17,885           (1.13× → 1.11× → 1.08×)
 *     Q5   23,866 → 23,559 → 22,877 vs 19,692           (1.21× → 1.20× → 1.16×)
 *
 * The E2B is the case that made it visible: 2,152.50 of its 3,147 MiB never leaves the host, and
 * #321's share fix removed only 323 MiB of a 2,748 MiB gap because the other 2,152 was being
 * charged as VRAM by the base term. It mattered little while sub-6 GiB cards never reached the card
 * path; since #321 lowered the gate to 5,120 they do, and the E2B is the model those laptops land on.
 *
 * The estimate stays deliberately conservative — every row above is still above the measurement,
 * and the 1 GiB margin is kept — because a too-small answer costs a silent partial offload while a
 * too-large one costs a smaller recommendation. What is NOT modelled well is the 15 % share itself:
 * the measured compute buffers run 416–569 MiB across models from 3.3 to 19.8 GB (they scale with
 * ubatch and hidden width, not with file size), so the share reads 149 MiB on the E2B and 2,730 on
 * Q5. Replacing it with a flat term was considered and REJECTED (2026-09): it flipped the 8 GB row
 * to the 9B, against #318 leg 2's measured 31/33 partial offload there. §6.8 settled that row
 * differently: on the 9B's measured projection the 8 GB row IS the 9B, which #391 leg 2 measured at
 * 33/33 on that card, and a partial start there now demotes it (`landedPartlyOnCard`).
 *
 * `hostMappedWeightsMib` is measured per model (see the field's doc comment: read off a FULL-OFFLOAD
 * start's `CPU_Mapped model buffer size`), optional, and clamped to the weight total — a manifest
 * without it keeps the whole file as the base, which is the conservative direction. Deriving the
 * split from the GGUF header cannot replace it: the picker judges models the user has NOT downloaded
 * (exactly one of the 29 chat manifests ships on a drive), so the number has to travel in the
 * catalog. That analysis retires the "GGUF header" half of §5 item 22 (e).
 */
export function estimateGraphicsNeedMib(m: ModelManifest): number {
  // §6.8: a manifest that carries the runtime's own projection is judged by it. It is the figure
  // llama.cpp's fit compares with the card's free memory, so only the fit margin is added.
  if (m.projectedGraphicsNeedMib !== undefined) return m.projectedGraphicsNeedMib + VRAM_FIT_MARGIN_MIB
  const w = weightsMib(m)
  const onCard = w - Math.min(m.hostMappedWeightsMib ?? 0, w)
  const cacheGib = m.estimatedContextCacheGib ?? VRAM_DEFAULT_CONTEXT_CACHE_GIB
  return onCard * (1 + VRAM_WORKING_SHARE) + cacheGib * 1024 + VRAM_FIT_MARGIN_MIB
}

/**
 * Added to a MEASURED on-card footprint before a sidecar gate subtracts it (#473 ruling 3), MiB.
 * It covers the gap between the probe's free figure and the fit's own reading, 54–154 MiB on the
 * three cards measured under `-np 1` (model-benchmarks.md §6.6 finding 1).
 */
export const CHAT_MEASURED_MARGIN_MIB = 256

/**
 * The running chat model's share of the card, MiB, for the two sidecar headroom gates — the
 * reranker's and translation's (#473 ruling 3, 2026-10-12). Not the picker's figure: that one
 * judges a model before it starts, this one a model that is running.
 *
 * - **Measured** when this session's load log describes the same model at the same context
 *   window on the card (`latestModelPlacement`): weights + KV + recurrent state + compute buffer
 *   on the card, plus `CHAT_MEASURED_MARGIN_MIB`. A partial offload counts only what reached the
 *   card, which is right: the rest is in host memory.
 * - **Otherwise the estimate**, with its context-cache term scaled UP to the launched window. The
 *   term is the manifest's figure at its recommended window, so a raised context window used to
 *   go uncounted. Never scaled down: a sliding-window cache does not shrink with the window.
 */
export function chatGraphicsShareMib(
  m: ModelManifest,
  launchedContextTokens: number | null,
  measured: ModelPlacement | null
): number {
  if (
    measured != null &&
    measured.modelId === m.id &&
    measured.backend === 'gpu' &&
    (launchedContextTokens == null || measured.contextTokens === launchedContextTokens) &&
    measured.gpuModelMb != null &&
    measured.gpuKvMb != null &&
    measured.gpuComputeMb != null
  ) {
    return (
      measured.gpuModelMb +
      measured.gpuKvMb +
      (measured.gpuRsMb ?? 0) +
      measured.gpuComputeMb +
      CHAT_MEASURED_MARGIN_MIB
    )
  }
  const w = weightsMib(m)
  const onCard = w - Math.min(m.hostMappedWeightsMib ?? 0, w)
  const cacheGib = m.estimatedContextCacheGib ?? VRAM_DEFAULT_CONTEXT_CACHE_GIB
  const scale =
    launchedContextTokens != null && m.recommendedContextTokens > 0
      ? Math.max(1, launchedContextTokens / m.recommendedContextTokens)
      : 1
  return onCard * (1 + VRAM_WORKING_SHARE) + cacheGib * 1024 * scale + VRAM_FIT_MARGIN_MIB
}

/** Would every layer of this model land on a card offering `budgetMib` (see `graphicsBudgetMib`)? */
export function fitsGraphicsMemory(m: ModelManifest, budgetMib: number): boolean {
  return estimateGraphicsNeedMib(m) <= budgetMib
}

/**
 * The graphics-memory BUDGET the fit is judged against (decision 10): the probe's free figure
 * for the budget device — what llama.cpp's own fit targets (`free − margin`) — or, when the probe
 * carries no free figure, the total less the idle-desktop allowance. Null with no device. Both
 * seams (`pickerMemoryFor` for the Models ★, `probeAndPersistGpu` for the benchmark) call this
 * one function so they can never disagree on the figure.
 */
export function graphicsBudgetMib(device: Pick<GpuDevice, 'totalMb' | 'freeMb'> | null | undefined): number | null {
  if (!device) return null
  const free: unknown = device.freeMb
  if (typeof free === 'number' && Number.isFinite(free)) return free
  return device.totalMb - GRAPHICS_IDLE_ALLOWANCE_MIB
}

/** Rule C's fallback order among ELIGIBLE models: rank first, then comfortable tier, then size. */
function eligibleOrder(a: ModelManifest, b: ModelManifest): number {
  return (
    b.recommendationRank - a.recommendationRank ||
    b.recommendedRamGb - a.recommendedRamGb ||
    b.sizeOnDiskGb - a.sizeOnDiskGb
  )
}

/**
 * Graphics-memory-aware recommendation — RULE C (model-benchmarks.md §6.6 as amended by the
 * PR #308 audit, decision 1), and since §6.8 (2026-11-20) the card path. On a computer whose next
 * start uses a discrete card:
 *
 *   1. `base` = the RAM pick of the ORDINARY ranks, computed WITHOUT the speed signal
 *      (`recommendModelIdByRam`, its stage logic untouched — the tier ratifications are the RAM
 *      picker's). It is the no-fit fallback in both modes below.
 *   2. eligible(m) = fits the card (`fitsGraphicsMemory` at `budgetMib`, the manifest's measured
 *      projection where it carries one) AND passes the RAM floor (`recommended_min_ram_gb` ≤ RAM;
 *      the Models screen refuses to start a model over it, and the pick must never point at a
 *      refused model; unknown RAM keeps the floor open, as the pre-rule-C card path did) AND was
 *      not seen landing only partly on this card (`landedPartlyOnCard`, §6.8 point 3).
 *      - **With card ranks** (any manifest of the role carries `recommendation_rank_gpu`, §6.8):
 *        they replace the ordinary ranks here, and `candidate` = the highest-ranked eligible
 *        model outright. §6.6 decision 2 ("the RAM pick stands wherever the card can hold it")
 *        is retired for such a catalog.
 *      - **Without card ranks** (rule C unchanged): `candidate = base` when base is eligible
 *        (decision 2: the 9B, not Gemma 12B, where both fit); otherwise the highest-ranked
 *        eligible model.
 *      Either way ties go by comfortable tier then size, ranked models ONLY (a rank-0 model is
 *      never the automatic pick, #326), and with no ranked model eligible (a small or nearly full
 *      card beside a big catalog) `candidate = base`: the RAM pick partially offloads, which is
 *      still the catalog's best answer.
 *   3. A slow speed reading moves `candidate` once, restricted to the eligible pool on both ends:
 *      with card ranks first along its `step_down_to` chain (`followStepDownChain`, §6.8 point 4);
 *      otherwise, or off the chain, the §6.5 step (`applySpeedSignal` with `eligible`). A crawl
 *      measured on a model the card cannot hold never lowers a fitting pick (R2), and the step
 *      never lands on a model that fails the RAM floor or the card (R1). A no-fit fallback
 *      therefore never steps — nothing eligible exists to step to.
 *
 * Unknown / non-positive budget → the RAM path with the signal, exactly as before. Unified and
 * cpu classes never reach this function (`recommendChatModelId`): unified takes the RAM pick, cpu
 * the processor path (§6.7).
 */
export function recommendModelIdByVram(
  manifests: ModelManifest[],
  budgetMib: number,
  ramGb: number,
  role: ModelRole = 'chat',
  speedSignal?: PickerSpeedSignal | null,
  card?: CardEvidence | null
): string | null {
  if (!Number.isFinite(budgetMib) || budgetMib <= 0) return recommendModelIdByRam(manifests, ramGb, role, speedSignal)
  // §6.8: a catalog that carries card ranks is ranked by them here, and then the highest-ranked
  // model that fits the card is the pick outright (the "base stands" branch below is skipped). A
  // catalog without them is rule C, unchanged.
  const cardRanked = manifests.some((m) => m.role === role && m.recommendationRankGpu !== undefined)
  const view = cardRanked
    ? manifests.map((m) =>
        m.recommendationRankGpu !== undefined ? { ...m, recommendationRank: m.recommendationRankGpu } : m
      )
    : manifests
  const candidates = view.filter((m) => m.role === role)
  const ramKnown = Number.isFinite(ramGb) && ramGb > 0
  const eligible = (m: ModelManifest): boolean =>
    fitsGraphicsMemory(m, budgetMib) &&
    (!ramKnown || m.recommendedMinRamGb <= ramGb) &&
    !landedPartlyOnCard(m, budgetMib, card)

  // The no-fit fallback is the RAM pick of the ordinary ranks: with nothing on the card, RAM decides.
  const baseId = recommendModelIdByRam(manifests, ramGb, role)
  const base = baseId ? candidates.find((m) => m.id === baseId) : undefined
  let candidate: ModelManifest | undefined
  if (!cardRanked && base && eligible(base)) {
    candidate = base
  } else {
    // STRICTLY ranked (owner decision 2026-09-06, issue #326): a rank-0 model is never the
    // automatic pick (model-policy.md), so when no RANKED model fits the card the no-fit
    // fallback below applies — the RAM pick, partially offloaded — rather than a rank-0 fit.
    const pool = candidates.filter((c) => c.recommendationRank > 0 && eligible(c)).sort(eligibleOrder)
    candidate = pool[0] ?? base
  }
  if (!candidate) return null
  // §6.8: with card ranks a slow reading follows the pick's named chain first (a no-fit fallback
  // never steps: nothing eligible exists to step to); what the chain does not cover is §6.5.
  if (cardRanked && eligible(candidate)) {
    const stepped = followStepDownChain(candidates, candidate.id, speedSignal, (m) => m.recommendationRank > 0 && eligible(m))
    if (stepped !== undefined) return stepped
  }
  return applySpeedSignal(candidates, candidate, speedSignal, eligible).id
}

/**
 * The named step-down (model-benchmarks.md §6.7, used by the card path too since §6.8): follow
 * each manifest's `step_down_to` from the no-signal pick `startId`, over models `usable` admits.
 *
 *   - no slow reading, or none on a model → `startId` (nothing moves);
 *   - the measured model lies on the chain and has a usable target → that target;
 *   - the measured model is the END of a chain that was followed → it stays the recommendation;
 *   - the measured model is not on the chain, or is the start with no usable target of its own →
 *     `undefined`: the caller's §6.5 rule decides.
 */
function followStepDownChain(
  candidates: ModelManifest[],
  startId: string,
  signal: PickerSpeedSignal | null | undefined,
  usable: (m: ModelManifest) => boolean
): string | undefined {
  const tps = signal?.tokensPerSecond
  const measuredId = signal?.measuredModelId
  if (tps == null || tps <= 0 || tps >= SLOW_PICK_TOKENS_PER_SECOND || !measuredId) return startId
  const byId = new Map(candidates.map((m) => [m.id, m]))
  const target = (m: ModelManifest): ModelManifest | undefined => {
    const next = m.stepDownTo ? byId.get(m.stepDownTo) : undefined
    return next && usable(next) ? next : undefined
  }
  const seen = new Set<string>()
  let current = byId.get(startId)
  while (current && !seen.has(current.id)) {
    seen.add(current.id)
    const next = target(current)
    if (current.id === measuredId) {
      if (next) return next.id
      return current.id === startId ? undefined : current.id
    }
    current = next
  }
  return undefined
}

/**
 * The chat recommendation for a computer whose next start runs from the PROCESSOR (memory class
 * `cpu`: no usable graphics card, or the GPU switched off) — model-benchmarks.md §6.7.
 *
 * Two differences from the plain RAM pick, both carried by the catalog and not by this code:
 *
 *   1. RANK. A manifest's `recommendation_rank_cpu` replaces its `recommendation_rank` here. The
 *      stage logic is `recommendModelIdByRam`'s, untouched (capacity first, rank inside a band,
 *      ranked models only): a model measured too slow on a processor carries 0 and drops out of
 *      the ranked pool, a model that suits a processor carries its own rank. A catalog without the
 *      field gives exactly the RAM pick.
 *   2. STEP-DOWN. A benchmark under `SLOW_PICK_TOKENS_PER_SECOND` on a model that lies on the
 *      pick's `step_down_to` chain recommends that model's own target. The chain is followed
 *      from the no-signal pick, so the answer is still a function of RAM and the one measurement
 *      (nothing is stored), yet a second slow benchmark on the stepped model steps again: the
 *      9B's chain ends at the fastest ranked model instead of one band below. A target the
 *      machine's RAM floor refuses, or one that is not ranked here, ends the chain. A crawl on a
 *      model that is NOT on the chain falls back to the §6.5 rule (one band below the pick, and an
 *      oversized model is no signal), so a catalog without chains behaves as before. Unlike §6.5
 *      the chain also applies to a runnable-stage pick: its targets are named, not inferred.
 */
export function recommendModelIdForProcessor(
  manifests: ModelManifest[],
  ramGb: number,
  speedSignal?: PickerSpeedSignal | null
): string | null {
  const view = manifests.map((m) =>
    m.recommendationRankCpu !== undefined ? { ...m, recommendationRank: m.recommendationRankCpu } : m
  )
  const baseId = recommendModelIdByRam(view, ramGb, 'chat')
  if (baseId === null) return null
  const chat = view.filter((m) => m.role === 'chat')
  const stepped = followStepDownChain(chat, baseId, speedSignal, (m) => m.recommendationRank > 0 && m.recommendedMinRamGb <= ramGb)
  if (stepped !== undefined) return stepped
  return recommendModelIdByRam(view, ramGb, 'chat', speedSignal)
}

/**
 * What earlier starts on THIS computer's card showed (model-benchmarks.md §6.8): the persisted
 * placement per model id, already limited by the caller to this machine, and the two context
 * settings `launchContextTokens` reads. The picker reads it to drop a model that was seen landing
 * only partly on the card.
 */
export interface CardEvidence {
  placements: Readonly<Record<string, Pick<ModelPlacement, 'backend' | 'gpuLayers' | 'totalLayers' | 'contextTokens' | 'gpuFreeAtStartMb'>>>
  /** `AppSettings.contextTokensOverride`, or null when the manifests' own context applies. */
  contextTokensOverride?: number | null
  /**
   * `AppSettings.contextTokens`, the legacy window a manifest without its own
   * (`recommended_context_tokens: 0`) launches with. Absent → unknown, and such a manifest's
   * next window is unbounded for the evidence rule.
   */
  contextTokens?: number
}

/**
 * The card evidence the settings hold for THIS machine (`here`, a `machineKey`): a placement
 * stamped with another machine's key supplies nothing, an unstamped one stays eligible, like the
 * probe. One function for every seam that feeds the picker, so they cannot disagree.
 */
export function cardEvidenceFor(
  s: { modelPlacements: Record<string, ModelPlacement>; contextTokensOverride: number | null; contextTokens: number },
  here: string | null
): CardEvidence {
  const placements: Record<string, ModelPlacement> = {}
  for (const [id, p] of Object.entries(s.modelPlacements ?? {})) {
    if (here == null || p.machineKey == null || p.machineKey === here) placements[id] = p
  }
  return { placements, contextTokensOverride: s.contextTokensOverride ?? null, contextTokens: s.contextTokens }
}

/** How far below the present budget a start's free memory may lie and still count as "the same card state", MiB. */
export const PARTIAL_EVIDENCE_TOLERANCE_MIB = 256

/**
 * Did an earlier start of this model land only PARTLY on the card, under conditions that still
 * hold (§6.8)? The estimate says what should fit; this is what did. The record counts when
 *   - it is a card start with fewer layers on the card than the model has,
 *   - its context was no larger than the one the next start launches with (a partial offload at
 *     a larger context proves nothing about a smaller one; the next window is
 *     `launchContextTokens`', the one precedence `startModelRuntime` launches with), and
 *   - the card had at least as much free memory then as the budget offers now, within
 *     `PARTIAL_EVIDENCE_TOLERANCE_MIB` (a start beside a game that filled the card must not
 *     demote the model for good). An unknown free figure counts: the layers are the evidence.
 * A later start of the same model that lands fully overwrites the record and lifts the exclusion.
 */
export function landedPartlyOnCard(m: ModelManifest, budgetMib: number, card: CardEvidence | null | undefined): boolean {
  const seen = card?.placements[m.id]
  if (!seen || seen.backend !== 'gpu') return false
  if (seen.gpuLayers == null || seen.totalLayers == null || seen.gpuLayers >= seen.totalLayers) return false
  const launchContext = launchContextTokens(
    { contextTokens: card?.contextTokens ?? Number.POSITIVE_INFINITY, contextTokensOverride: card?.contextTokensOverride },
    m
  )
  if (seen.contextTokens > launchContext) return false
  const free = seen.gpuFreeAtStartMb
  return free == null || free >= budgetMib - PARTIAL_EVIDENCE_TOLERANCE_MIB
}

/** What the chat picker needs to know about the computer's memory (benchmark.md "Your model"). */
export interface PickerMemory {
  memoryClass: MemoryClass
  /** Whole GB, as `machineRamGb()` reports it. */
  ramGb: number
  /**
   * The graphics-memory budget of the next start's card in raw MiB — `graphicsBudgetMib` of the
   * budget device (`nextStartMemory`): the probe's free figure, else total − 1024 — or null when
   * there is no card / the figure is unknown (→ the RAM pick).
   */
  budgetMb: number | null
  /** Earlier starts on this machine's card (§6.8); absent or null → the fit estimate alone decides. */
  card?: CardEvidence | null
}

/**
 * The chat recommendation for this computer: rule C against the card's budget on a discrete
 * card, the processor path (§6.7) on a machine whose next start runs from RAM without a card,
 * and by RAM on unified memory (one pool) and on a discrete class whose budget is unknown.
 */
export function recommendChatModelId(
  manifests: ModelManifest[],
  memory: PickerMemory,
  speedSignal?: PickerSpeedSignal | null
): string | null {
  if (memory.memoryClass === 'discrete' && memory.budgetMb != null && memory.budgetMb > 0) {
    return recommendModelIdByVram(manifests, memory.budgetMb, memory.ramGb, 'chat', speedSignal, memory.card)
  }
  if (memory.memoryClass === 'cpu') return recommendModelIdForProcessor(manifests, memory.ramGb, speedSignal)
  return recommendModelIdByRam(manifests, memory.ramGb, 'chat', speedSignal)
}

/**
 * Every byte a model downloads, as its manifest declares them: the weight, a vision model's
 * projector and each extra file, each from its own `download` block (the validator makes them
 * all-or-nothing). Null when any one is undeclared, and the dialog then shows `size_on_disk_gb`.
 * The weight's size alone understated a two-file model in its own confirmation (#768: 1.9 of
 * the vision model's 3.3 GB once its manifest declared both sizes).
 */
function declaredDownloadBytes(manifest: ModelManifest): number | null {
  const blocks = [
    manifest.download,
    ...(manifest.mmproj ? [manifest.mmproj.download] : []),
    ...(manifest.files ?? []).map((f) => f.download)
  ]
  let total = 0
  for (const block of blocks) {
    if (block?.sizeBytes == null) return null
    total += block.sizeBytes
  }
  return total
}

function toModelInfo(
  manifest: ModelManifest,
  state: ModelState,
  recommended: boolean,
  startableAsMock: boolean,
  insufficientRam: boolean
): ModelInfo {
  // Surface the manifest's optional download block: the renderer's per-download
  // confirmation needs size, URL, license link, and whether an explicit license
  // acknowledgement is required (license_review not approved).
  const download: ModelDownloadInfo | undefined = manifest.download
    ? {
        url: manifest.download.url,
        sizeBytes: declaredDownloadBytes(manifest),
        licenseUrl: manifest.download.licenseUrl,
        licenseApproved: manifest.licenseReview.status === 'approved',
        // #196: a known-dead upstream source. Surfaced so the card explains WHY there is no
        // Download button, instead of offering one that can only end in an HTTP 404.
        ...(manifest.download.withdrawn ? { withdrawn: manifest.download.withdrawn } : {})
      }
    : undefined
  return {
    id: manifest.id,
    displayName: manifest.displayName,
    family: manifest.family,
    role: manifest.role,
    format: manifest.format,
    runtime: manifest.runtime,
    license: manifest.license,
    sizeOnDiskGb: manifest.sizeOnDiskGb,
    recommendedMinRamGb: manifest.recommendedMinRamGb,
    recommendedRamGb: manifest.recommendedRamGb,
    recommendedContextTokens: manifest.recommendedContextTokens,
    localPath: manifest.localPath,
    state,
    recommended,
    startableAsMock,
    insufficientRam,
    ...(download ? { download } : {})
  }
}

export interface BuildModelListOptions {
  manifestsDir: string
  rootPath: string
  developerMode: boolean
  /** Model id currently loaded in a running runtime, if any. */
  runningModelId?: string | null
  /** Optional persistent hash cache (L2) so unchanged weights are hashed once ever. */
  hashStore?: HashStore
  /**
   * This machine's total RAM in whole GB. Models whose `recommended_min_ram_gb` exceeds it are
   * flagged `insufficientRam`, and the recommendation is RAM-best-fit (`recommendChatModelId`).
   */
  machineRamGb: number
  /**
   * Measured-speed signal from the persisted Diagnostics benchmark (model-benchmarks.md
   * §6.5, issue #95), fed into the CHAT recommendation only (the probe streams through a
   * chat model; the embeddings pick never moves on it). Absent/null → pure RAM-best-fit,
   * byte-identical to the pre-#95 behavior.
   */
  speedSignal?: PickerSpeedSignal | null
  /**
   * The computer's memory class for the NEXT start and the budget device's graphics-memory
   * budget in raw MiB (`graphicsBudgetMib`: the probe's free figure, else total − 1024; §6.6
   * rule C, PR #308 audit decisions 9/10). On a discrete card the chat pick is rule C against
   * the budget; unified / cpu keep the RAM pick. Omitted → the RAM pick (legacy callers and
   * tests unchanged). Both come from `pickerMemoryFor` in registerModelIpc.ts, the same
   * decision the benchmark makes.
   */
  memoryClass?: MemoryClass
  graphicsBudgetMb?: number | null
  /** Earlier starts on this machine's card (§6.8, `cardEvidenceFor`); omitted → the estimate alone. */
  cardEvidence?: CardEvidence | null
  /**
   * Optional verification-progress sink. Called once per model that will be hashed (with
   * a 1-based step index + the byte-weighted overall totals), throttled within a file by
   * `sha256File`, plus a terminal `done` event. `overallBytesTotal === 0` ⇒ nothing to
   * hash this pass (all cached) and NO events are emitted. Omitted ⇒ no overhead.
   */
  onProgress?: (p: ModelVerifyProgress) => void
  /**
   * RT-3 lazy verification — since #382 the mode every routine caller uses. When this
   * property is PRESENT, only the model whose id matches is hashed on a cold cache; every
   * other present weight is reported `installed` without hashing (display-only — the start
   * gate re-verifies what it launches). Pass the active model id (or `null` to hash
   * nothing); OMIT the property entirely to hash the full set, which now happens only for
   * the Models screen's explicit "Check all model files" action and the ship-time gates.
   * Distinguishes "lazy, no active model" (`null`) from "full hash" (absent).
   */
  onlyVerifyModelId?: string | null
  /**
   * #420 — the id that tags every `ModelVerifyProgress` of this pass. Minted by the RENDERER
   * and handed down so the Cancel affordance has a handle from the instant the user starts
   * the pass, not from the first progress event: `runId` used to be minted here and only
   * reached the renderer on that first event (and no event fires at all when
   * `overallBytesTotal === 0`), so a cancel clicked in between had nothing to send. Omitted
   * ⇒ a fresh uuid, exactly as before.
   */
  runId?: string
  /**
   * #420 cancellation for the DISPLAY-side pass (the Models screen's "Check all model
   * files"). An abort stops the hashing loops at the next file boundary; the models that had
   * not been reached are reported present-but-UNCHECKED — the same answer RT-3 lazy
   * verification gives — so a cancelled pass is a calm outcome, never an error. The §7.4
   * start gate and the ship-time gates never pass one.
   */
  signal?: AbortSignal
}

export interface ModelListResult {
  models: ModelInfo[]
  manifestErrors: string[]
}

/** #847: the ids of the manifests for a newer HilbertRaum already logged this session (one line per new id). */
const newerAppIdsLogged = new Set<string>()

/**
 * #847: the display-only `ModelInfo` of a manifest for a newer HilbertRaum. `role: 'unknown'` keeps it out of
 * every role branch of the screen (never a fake known role: `'chat'` would make it a chat-model candidate),
 * `state: 'unsupported'`, never recommended, no `download` (no Download button, no size to confirm), and
 * `filesPresent` = every file it declares exists (existence only, no hash; the presence contract of the
 * "On this drive" view, design-guidelines §15).
 */
function newerAppModelInfo(entry: UnsupportedManifest, rootPath: string): ModelInfo {
  let filesPresent = entry.localPaths.length > 0
  try {
    for (const rel of entry.localPaths) {
      if (!statSync(safeDrivePath(rootPath, rel), { throwIfNoEntry: false })?.isFile()) filesPresent = false
    }
  } catch {
    filesPresent = false // an unreadable path reads as absent, never as a broken list
  }
  return {
    id: entry.id,
    displayName: entry.displayName,
    family: entry.family ?? '',
    role: 'unknown',
    format: '',
    runtime: '',
    license: '',
    sizeOnDiskGb: entry.sizeOnDiskGb ?? 0,
    recommendedMinRamGb: 0,
    recommendedRamGb: 0,
    recommendedContextTokens: 0,
    localPath: entry.localPaths[0] ?? '',
    state: 'unsupported',
    recommended: false,
    startableAsMock: false,
    insufficientRam: false,
    needsNewerApp: true,
    ...(entry.role ? { declaredRole: entry.role } : {}),
    filesPresent
  }
}

/** Discover manifests and compute the full ModelInfo[] for the Models screen. */
export async function buildModelList(opts: BuildModelListOptions): Promise<ModelListResult> {
  const { manifests, unsupported, errors } = discoverManifests(opts.manifestsDir)
  const all = manifests.map((m) => m.manifest)
  const ram = opts.machineRamGb
  // RAM-best-fit recommendation (it can never point at a RAM-gated model); the §6.5 speed
  // signal applies to the chat pick only.
  const recommendedChat = recommendChatModelId(
    all,
    { memoryClass: opts.memoryClass ?? 'cpu', ramGb: ram, budgetMb: opts.graphicsBudgetMb ?? null, card: opts.cardEvidence ?? null },
    opts.speedSignal
  )
  // #848 review: an embeddings card has nothing to select (the app composes its own pick), so its ★ marks the model
  // the app composes (`pickManifestForRole`, the flagged default), never another embeddings manifest the RAM ranking
  // would prefer; and only when it fits this machine's RAM, because the ★ is runnable by construction.
  const embedPick = pickManifestForRole(all, 'embeddings')
  const recommendedEmbed =
    embedPick && Number.isFinite(ram) && ram > 0 && embedPick.recommendedMinRamGb <= ram ? embedPick.id : null

  // RT-3 lazy mode: when `onlyVerifyModelId` is present, hash only that model; report every
  // other present weight without hashing. `'onlyVerifyModelId' in opts` distinguishes a
  // provided `null` (lazy, no active model → hash nothing) from an absent property (full).
  const lazyVerify = 'onlyVerifyModelId' in opts
  const skipHashFor = (id: string): boolean => lazyVerify && id !== opts.onlyVerifyModelId

  // Verification-progress pre-pass (no hashing): which models will actually be hashed,
  // and the total bytes — the byte denominator for a determinate first-run bar. Cheap
  // (statSync + cache lookup per weight). Skipped entirely when no sink is wired.
  const willHash = opts.onProgress
    ? manifests.map(({ manifest }) =>
        skipHashFor(manifest.id)
          ? 0
          : pendingHashBytes(manifest, opts.rootPath, {
              developerMode: opts.developerMode,
              hashStore: opts.hashStore
            })
      )
    : []
  const overallBytesTotal = willHash.reduce((a, b) => a + b, 0)
  const hashCount = willHash.filter((b) => b > 0).length
  let completedBytes = 0 // bytes from already-finished models this pass
  let stepIndex = 0 // 1-based step among the models that hash
  // The byte-weighted denominator is only honest when there is work to do; with nothing
  // to hash (everything cached) we emit no events and the renderer shows no bar.
  const emit = opts.onProgress && overallBytesTotal > 0 ? opts.onProgress : undefined
  // Tags every event of THIS pass so the renderer can lock onto one when passes overlap.
  // #420: the renderer's own id when it supplied one (it is also the cancel handle).
  const runId = emit ? (opts.runId ?? randomUUID()) : ''

  const models: ModelInfo[] = []
  // #420: set once the pass has been cancelled. Every model from that point on — including
  // the one that was mid-hash — is reported WITHOUT hashing, which is exactly what RT-3
  // lazy verification reports for a present weight. Nothing is lost and nothing is faked:
  // what finished before the cancel is in the checksum cache, the rest is simply unchecked
  // and the §7.4 start gate still re-verifies the chat model the user launches (the other roles
  // refuse a file a check found damaged, #913).
  let cancelled = false
  for (let i = 0; i < manifests.length; i++) {
    const { manifest } = manifests[i]
    // Loop head: a cancel between two multi-GB weights is noticed here, before the next one is
    // opened. `computeInstallState` takes the signal too, so the two back each other up.
    if (!cancelled && opts.signal?.aborted) cancelled = true
    const thisHashes = !cancelled && willHash[i] > 0
    if (emit && thisHashes) stepIndex++
    const stepAt = stepIndex // capture for this model's throttled callbacks
    let state: ModelState
    try {
      state = await computeInstallState(manifest, opts.rootPath, {
        developerMode: opts.developerMode,
        hashStore: opts.hashStore,
        skipHash: cancelled || skipHashFor(manifest.id),
        signal: opts.signal,
        onProgress:
          emit && thisHashes
            ? (bytesHashed) =>
                emit({
                  runId,
                  modelIndex: stepAt,
                  modelCount: hashCount,
                  modelId: manifest.id,
                  displayName: manifest.displayName,
                  overallBytesHashed: completedBytes + bytesHashed,
                  overallBytesTotal,
                  done: false
                })
            : undefined
      })
    } catch (err) {
      // ONE manifest must never break the whole Models list. validateManifest now rejects an
      // escaping local_path up front, but a manifest that still throws here (e.g. a future
      // safeDrivePath case, or an I/O error) is recorded and SKIPPED rather than rejecting the
      // entire `IPC.listModels` handler — mirroring the pendingHashBytes() pre-pass, which
      // already tolerates the same throw, and discoverManifests' error channel (vuln-scan
      // 2026-06-21 [uncaught-exception-dos]).
      //
      // #420 is the ONE exception: a cancelled hash is not a broken manifest. Re-derive this
      // model's state without hashing (cheap — statSync + cache lookups) and carry on in
      // cancelled mode, so the list stays complete and every state in it stays honest.
      const recovered = isHashAborted(err)
        ? await computeInstallState(manifest, opts.rootPath, {
            developerMode: opts.developerMode,
            hashStore: opts.hashStore,
            skipHash: true
          }).catch(() => null)
        : null
      if (recovered === null) {
        errors.push(`${manifest.id}: ${err instanceof Error ? err.message : String(err)}`)
        if (isHashAborted(err)) cancelled = true
        continue
      }
      cancelled = true
      state = recovered
      // …and fall through to the shared tail, so a cancelled model is described exactly like
      // every other one (recommended ★, RAM gate, mock-startable).
    }
    if (emit && thisHashes && !cancelled) completedBytes += willHash[i]
    if (opts.runningModelId && manifest.id === opts.runningModelId && state === 'installed') {
      state = 'running'
    }
    const recommended =
      manifest.id === recommendedChat || manifest.id === recommendedEmbed
    // Zero-weights first run: a missing CHAT model may start the built-in mock
    // when the caller's (policy-gated) developer leniency is on. Computed here so the
    // renderer renders an affordance the MAIN process actually allows.
    const startableAsMock =
      state === 'missing' && manifest.role === 'chat' && opts.developerMode
    const insufficientRam = manifest.recommendedMinRamGb > ram
    const info = toModelInfo(manifest, state, recommended, startableAsMock, insufficientRam)
    // #932: `computeInstallState` decides a placeholder hash before any file is read, so `checksum_failed` with a
    // placeholder in the manifest means "no checksum on record", never a file that failed its check. Only the card's
    // words and its repair action follow this flag; the state and every start gate stay as they are.
    if (state === 'checksum_failed' && hasPlaceholderHash(manifest)) info.noChecksum = true
    models.push(info)
  }
  // #847: the manifests for a newer HilbertRaum, after every model this build can use. Logged apart from the
  // invalid ones (they are not broken), once per id per session rather than on every Models-screen refresh. Each
  // line names the manifest file and the role as written (local app.log; the invalid-manifest warning names files
  // too): a role TYPO ("embedding", "Chat") lands here, not in that warning, and must stay findable.
  for (const { manifest: entry } of unsupported) models.push(newerAppModelInfo(entry, opts.rootPath))
  for (const { manifest: entry, sourceFile } of unsupported) {
    if (newerAppIdsLogged.has(entry.id)) continue
    newerAppIdsLogged.add(entry.id)
    log.info('Model manifest for a newer HilbertRaum listed', {
      file: sourceFile,
      role: entry.role === null ? null : entry.role.slice(0, 64),
      ...(entry.minAppVersion !== null ? { minAppVersion: entry.minAppVersion.slice(0, 32) } : {})
    })
  }
  // Terminal event so the bar settles to 100% even if the last throttled callback landed
  // a chunk short of the total.
  if (emit) {
    emit({
      runId,
      modelIndex: hashCount,
      modelCount: hashCount,
      modelId: '',
      displayName: '',
      overallBytesHashed: overallBytesTotal,
      overallBytesTotal,
      done: true
    })
  }
  return { models, manifestErrors: errors }
}

export interface SelectResult {
  activeModelId: string | null
  activeEmbeddingModelId: string | null
}

/**
 * Persist the selected active model to settings. Chat models set `activeModelId`;
 * embedding models set `activeEmbeddingModelId`. Throws if the id is unknown.
 * Reranker/transcriber models are availability-driven (they activate when binary +
 * weights exist) — there is no settings slot for them, and a role-else-chat fallback
 * would write a transcriber id into `activeModelId` (the CHAT slot) and break chat.
 * Refuse with friendly copy instead.
 */
export function selectModel(db: Db, manifestsDir: string, modelId: string): SelectResult {
  const { manifests } = discoverManifests(manifestsDir)
  const found = manifests.find((m) => m.manifest.id === modelId)
  // #930: in the interface language, without the id (users never see ids; the select handler logs it).
  if (!found) throw new Error(tMain('main.models.unknown'))

  if (found.manifest.role !== 'chat' && found.manifest.role !== 'embeddings') {
    throw new Error(tMain('main.models.autoSelected'))
  }
  const patch =
    found.manifest.role === 'embeddings'
      ? { activeEmbeddingModelId: modelId }
      : { activeModelId: modelId }
  updateSettings(db, patch)
  const s = getSettings(db)
  return { activeModelId: s.activeModelId, activeEmbeddingModelId: s.activeEmbeddingModelId }
}