Skip to content

AI, fully local on your computer.

45.7 KB
Raw Blame
// Model manifest schema + validator (spec §3.3 / §7.4; see docs/model-policy.md).
//
// A manifest is a small YAML file under `model-manifests/` describing one model.
// Manifests are committed to git; model *weights* are not. The app reads these to
// discover, verify (SHA-256), recommend, and select models with NO code changes —
// so the schema lives in `shared/` and is the single source of truth for the shape.
//
// Parsing uses the pure-JS `yaml` package (boring, reliable, offline). The validator
// is hand-written so every field gets a precise, user-facing error message.

import type { HardwareProfile } from './types'

export type ModelRole = 'chat' | 'embeddings' | 'reranker' | 'transcriber' | 'vision' | 'translation'

/**
 * Speculative-decoding scheme a chat GGUF supports (issue #182). A CLOSED enum, never a
 * free-form argument list: manifests live on the drive and are user-editable, so an
 * `extra_server_args`-style field would let a hand-edited YAML inject ANY llama-server flag
 * — `--host 0.0.0.0` alone would break the loopback-only invariant the security model rests
 * on, because `LlamaServer.buildArgs` appends the extras LAST and a later flag wins. The enum
 * member is a NAME the runtime maps to a fixed, code-owned argument list.
 *
 *   'mtp'  the model ships a trained-in multi-token-prediction draft head inside the same
 *          GGUF (Qwen3.8's `blk.64.nextn.*`), which llama-server loads and then IGNORES
 *          unless `--spec-type draft-mtp` is passed. No second model file, no `--model-draft`.
 */
export type SpeculativeDecoding = 'mtp'

export interface LicenseReview {
  status: 'pending' | 'approved' | 'rejected'
  reviewedBy: string | null
  reviewedAt: string | null
  notes: string
}

/**
 * Optional download metadata. When present, the `fetch-models` script (and
 * the canonical `services/assets.ts`) know where to fetch the weight from and what to
 * verify it against. Validated only when the `download` block is present, so every
 * existing manifest stays valid without it.
 */
export interface DownloadSpec {
  /** Upstream URL for the weight (e.g. a Hugging Face `?download=true` link). */
  url: string
  /**
   * Expected SHA-256 (lower-case hex) of the downloaded file. May be a placeholder
   * until a real drive is built; when it is a real hash it MUST equal the top-level
   * `sha256` (they describe the same file).
   */
  sha256: string
  /** Expected size in bytes (informational; for progress + a sanity check). */
  sizeBytes: number | null
  /** URL of the model license, shown at the license-acceptance prompt. */
  licenseUrl: string | null
  /**
   * WITHDRAWN UPSTREAM SOURCE (issue #196, model-policy.md "Withdrawn upstream sources"):
   * a short dated note saying the `url` above is known-dead — the publisher deleted or
   * replaced the exact file this manifest pins. Absent (the normal case) = the source is
   * live. Present = the app must NOT offer or attempt the fetch: `planModelDownloads`
   * reports `source-withdrawn` instead of `download`, the in-app downloader refuses to
   * start with that reason, and the fetch scripts skip the model with a loud line —
   * instead of everyone rediscovering an HTTP 404 the long way.
   *
   * The rest of the block is deliberately KEPT (url, hash, size, license): a manifest whose
   * weight is already on a drive stays fully usable — the pinned SHA-256 still verifies the
   * local file — and the dead URL remains the provenance record of what that file is. Such
   * a manifest also carries `recommendation_rank: 0`, so the picker never recommends a model
   * a fresh drive can no longer obtain (pinned in `committed-catalog.test.ts`).
   */
  withdrawn?: string
}

/**
 * The multimodal projector sub-block for a `role: vision` model (image-understanding plan
 * §8.1). A vision model is TWO files: the language GGUF (the top-level `local_path`/`sha256`/
 * `download`) plus this CLIP/`mmproj` projector that `llama-server --mmproj` loads. Validated
 * only when present, and REQUIRED when `role: vision`. The builds that predate `vision` reject such a
 * manifest, so it vanishes there; since #847 a role a build does not know is listed as needing a newer
 * HilbertRaum instead (`parseUnsupportedManifest`). Its own `download` block lets the two-job downloader (DIST-1) fetch the
 * projector with the same atomic single-file machinery as the GGUF.
 */
export interface MmprojSpec {
  /** Path of the projector file relative to the DRIVE ROOT (e.g. `models/vision/x-mmproj.gguf`). */
  localPath: string
  /** Expected SHA-256 (lower-case hex). May be a placeholder until a real drive is built. */
  sha256: string
  /** Optional upstream source for the projector (the second `DownloadJob` of a vision model). */
  download?: DownloadSpec
}

/**
 * One ADDITIONAL required file of a model's weight, beyond the top-level `local_path`/`sha256`
 * (#310). The canonical case is a GGUF that ships as a `-00001-of-000NN` shard set: the
 * top-level path is shard 1 (the file `llama-server --model` receives, which finds its siblings
 * by name) and every remaining shard is declared here with its own hash, so install state, the
 * drive verifier, the byte accounting and the download planner account for the WHOLE weight.
 * Deliberately generic — any second file a model needs belongs here rather than in a new slot.
 */
export interface RequiredFileSpec {
  /** Path of the file relative to the DRIVE ROOT (e.g. `models/chat/x-00002-of-00004.gguf`). */
  localPath: string
  /** Expected SHA-256 (lower-case hex). May be a placeholder until a real drive is built. */
  sha256: string
  /** Optional upstream source for this file (one more `DownloadJob` of the same model). */
  download?: DownloadSpec
}

/** A fully-validated manifest. Field names are camelCased from the YAML snake_case. */
export interface ModelManifest {
  id: string
  displayName: string
  family: string
  role: ModelRole
  format: string
  runtime: string
  license: string
  sizeOnDiskGb: number
  recommendedMinRamGb: number
  recommendedRamGb: number
  recommendedContextTokens: number
  /**
   * Whether the model has a native thinking/reasoning mode the runtime can toggle per
   * request (gates the Deep answer mode in the UI). Optional in YAML
   * (`supports_thinking_mode`), defaulting to false — Deep is never offered for a
   * model that did not declare it.
   */
  supportsThinkingMode: boolean
  /**
   * Whether a preconfigured Kit ships this model preloaded (`bundled_on_preconfigured_drive`,
   * #766). The Kit builder fetches only these, and the sell gate requires each one present and
   * VERIFIED; every other manifest on a Kit is its in-app download catalog. Optional in YAML,
   * defaulting to false. The app does not read it at runtime.
   */
  bundledOnPreconfiguredDrive: boolean
  /**
   * Opt-in speculative decoding for this chat model (`speculative_decoding`, issue #182).
   * Absent = off, which is what every manifest that does not name it gets. Declaring it
   * asserts that the WEIGHT carries the draft head; the runtime still gates the actual flag
   * on the hardware it finds (GPU present + VRAM headroom) and degrades silently — see the
   * architecture.md "MTP speculative decoding" design record. Chat role only: the chat start
   * ladder is the sole consumer.
   */
  speculativeDecoding?: SpeculativeDecoding
  /**
   * `disable_prompt_cache` (#512): the pinned llama-server cannot restore this model's evicted
   * prompt, so its host-RAM prompt cache is pure waste. Absent (= false) keeps the cache on, which
   * is what every manifest without the field gets. The runtime maps true to the code-owned
   * `--cache-ram 0` — the manifest states a fact and never supplies arguments. Chat role only;
   * `tests/manual/prompt-cache-smoke.test.ts` tells whoever adds a manifest whether it is needed.
   */
  disablePromptCache?: boolean
  /** Path of the weight file relative to the DRIVE ROOT (e.g. `models/chat/x.gguf`). */
  localPath: string
  /** Expected SHA-256 (lower-case hex). May be a placeholder until a real drive is built. */
  sha256: string
  /** Hardware profiles this model is recommended for (read only by `recommendModelId`, the benchmark's fallback). */
  recommendedProfiles: HardwareProfile[]
  /**
   * Recommendation tiebreak: higher = preferred among models that fit the
   * machine's RAM. Encodes the model-benchmark verdict so the RAM-best-fit picker is
   * quality-aware instead of biggest-disk-wins (model-benchmarks.md §6.2). Optional in YAML
   * (`recommendation_rank`), default 0.
   */
  recommendationRank: number
  /**
   * The rank the picker uses INSTEAD of `recommendationRank` when the next start runs from the
   * processor (memory class `cpu`: no usable graphics card, or the GPU switched off) —
   * model-benchmarks.md §6.7. Optional in YAML (`recommendation_rank_cpu`, a non-negative
   * number); absent → the ordinary rank applies there too. 0 keeps a model selectable but never
   * the automatic pick on a processor: the value for a model measured too slow without a card.
   */
  recommendationRankCpu?: number
  /**
   * The model the processor path (model-benchmarks.md §6.7) and, since §6.8, the card path step
   * to when a benchmark measured THIS model under the slow line: the id of another chat manifest.
   * Optional in YAML (`step_down_to`); absent → this model is the end of its chain. Each path
   * follows a link only to a target it may pick (ranked there; on the card also eligible). The
   * chains are pinned against the committed catalog (`committed-catalog.test.ts`): every target
   * exists, is ranked on the processor, needs no more RAM than its source, and no chain loops.
   */
  stepDownTo?: string
  /**
   * The rank the picker uses INSTEAD of `recommendationRank` on a discrete graphics card (memory
   * class `discrete`, rule C) — model-benchmarks.md §6.8. Optional in YAML
   * (`recommendation_rank_gpu`, a non-negative number); absent → the ordinary rank applies there
   * too. 0 keeps a model selectable but never the automatic pick on a card.
   */
  recommendationRankGpu?: number
  /**
   * What the runtime itself projects this model to take on the card under the app's launch, MiB:
   * the figure of llama.cpp's fit line, "projected to use N MiB of device memory", read off a
   * start with the manifest's own context, one slot, batch 2048 and the manifest's speculative
   * decoding. Optional in YAML (`projected_graphics_need_mib`, number ≥ 0). When present it
   * REPLACES the derived estimate in `estimateGraphicsNeedMib` (the fit margin is still added),
   * because it is the same number the runtime compares with the card's free memory
   * (model-benchmarks.md §6.8). Absent → the estimate, as before.
   */
  projectedGraphicsNeedMib?: number
  /**
   * The context cache (KV + recurrent state) the runtime allocates for this model at its
   * `recommended_context_tokens` under the app's launch (ubatch 2048 and, since issue #319,
   * ONE server slot), in GiB — the per-model cache term of the graphics-memory fit estimate
   * (`estimateGraphicsNeedMib` in services/models.ts; model-benchmarks.md §6.6, PR #308 audit
   * decision 11). Optional in YAML (`estimated_context_cache_gib`, number ≥ 0); absent → the
   * picker books its 0.5 GiB default. Config-derived; the GGUF-header estimate (BUILD_STATE §5
   * item 22 (e)) retires it.
   */
  estimatedContextCacheGib?: number
  /**
   * The share of this model's weights that stays HOST-mapped even on a full offload — the
   * embedding / output tables llama.cpp leaves in `CPU_Mapped model buffer size` — in MiB.
   * Optional in YAML (`host_mapped_weights_mib`, number ≥ 0); absent → `estimateGraphicsNeedMib`
   * behaves exactly as before, applying its working share to the whole weight file.
   *
   * Why it exists (issue #321, owner decision 2026-09-07). The estimate's 15 % working share is
   * meant to cover the runtime's buffers BESIDE the weights on the card, but it was applied to
   * the whole file — including the part that never reaches the card. On the E2B that made the
   * estimate 2.4× too high (4,746 MiB predicted against 1,997 projected and ≈ 1,998 used),
   * because 2,152.50 of its 3,147 MiB file stays host-mapped. The app has no GGUF-header parser,
   * so the figure is MEASURED: read off the `CPU_Mapped model buffer size` line of a
   * FULL-OFFLOAD start under `eval/results/hardware/`. A partial offload inflates it (the 9B logs
   * 545.62 at 33/33 but 824.31 at 31/33), so only full-offload starts count. Deriving it from the
   * GGUF header instead stays open — BUILD_STATE §5 item 22 (e).
   */
  hostMappedWeightsMib?: number
  licenseReview: LicenseReview
  /** Optional download metadata. Absent on manifests with no upstream source. */
  download?: DownloadSpec
  /**
   * Informational input modalities (`input_modalities`, e.g. `[text, image]` for a vision
   * model). Default `[]` when omitted; never load-bearing — capability comes from `role` +
   * `mmproj`, not this list. Parsed so it round-trips rather than being silently dropped.
   */
  inputModalities?: string[]
  /**
   * The multimodal projector (`mmproj`) sub-block. Present (and required) only for
   * `role: vision` models (image-understanding plan §8.1). See {@link MmprojSpec}.
   */
  mmproj?: MmprojSpec
  /**
   * The ADDITIONAL required files of this model's weight beyond `local_path` (#310).
   * Absent on every single-file model — and when it is absent nothing anywhere changes.
   * See {@link RequiredFileSpec}. The YAML block is emitted AFTER
   * `local_path`/`sha256`/`download`/`mmproj`: the flat first-match scrapers in
   * `verify-models.{sh,ps1}` and `fetch-models.{sh,ps1}` read the top-level keys by file
   * order, so a nested `local_path:`/`sha256:` pair placed earlier would poison them.
   */
  files?: RequiredFileSpec[]
  /**
   * `default_for_role` (#848): THIS is the model `resolveModelByRole` takes for its role, present or not, ahead of
   * the walk order (each folder's entry names in code-unit order), so a later manifest of the same role — a
   * release's or a user's — never re-points it by file name. Absent (= false) on every manifest but the committed embedder's. Generic over roles; inert on chat
   * (the active chat model is the user's pick), where it is accepted, never rejected (D848-3).
   */
  defaultForRole?: true
}

export interface ValidationResult {
  ok: boolean
  manifest?: ModelManifest
  errors: string[]
}

/**
 * #847: a manifest for a NEWER HilbertRaum, read for display only. Two ways in, both decided by
 * `discoverManifests` before any validation: a `role` this build does not know
 * ({@link declaresUnknownRole}), or a `min_app_version` newer than this app ({@link manifestNeedsNewerApp},
 * the (a+) lever every later release has over this one). Only the display subset below is read — a
 * release cannot know which of its own rules a future role or field follows, so applying them would make
 * the file vanish — and nothing in it is ever hashed, downloaded, started or selected: discovery keeps these
 * out of `manifests`, so every `ModelManifest` consumer stays unable to pick one by construction.
 */
export interface UnsupportedManifest {
  id: string
  displayName: string
  /** The declared role as written (trimmed); null when it names none (possible only via `min_app_version`). */
  role: string | null
  family: string | null
  sizeOnDiskGb: number | null
  /** `min_app_version` as written, when it is a string. */
  minAppVersion: string | null
  /**
   * Every drive-relative file path the manifest declares in the slots this build knows (`local_path`,
   * `mmproj.local_path`, `files[].local_path`), each through the same escape check as a real manifest's:
   * their existence is checked (the "On this drive" listing), so a hostile path must not reach the disk.
   */
  localPaths: string[]
}

export interface UnsupportedParseResult {
  ok: boolean
  entry?: UnsupportedManifest
  errors: string[]
}

const ROLES: ModelRole[] = ['chat', 'embeddings', 'reranker', 'transcriber', 'vision', 'translation']
const PROFILES: HardwareProfile[] = ['TINY', 'LITE', 'BALANCED', 'PRO', 'UNKNOWN']
const REVIEW_STATUSES = ['pending', 'approved', 'rejected'] as const
const SPECULATIVE_SCHEMES: SpeculativeDecoding[] = ['mtp']

/** 64 lower-case hex chars. Used to tell a real hash from a placeholder. */
const SHA256_RE = /^[a-f0-9]{64}$/

/**
 * llama.cpp's multi-file GGUF convention: `<stem>-<index>-of-<total>.gguf` (#310). Groups:
 * 1 = the 5-digit index, 2 = the 5-digit total, 3 = the extension as written. A path matching
 * this names only PART of a weight, so the manifest must declare the rest in `files:`.
 */
const SHARD_RE = /-(\d{5})-of-(\d{5})(\.gguf)$/i

export function isRealSha256(value: string): boolean {
  return SHA256_RE.test(value)
}

/**
 * True only for an `https://` URL (case-insensitive scheme). Download URLs must be TLS:
 * cleartext `http://` leaks which model is fetched and is downgrade-friendly (L-2). Shared
 * by the manifest validator and the asset planners so the rule has one definition.
 */
export function isHttpsUrl(value: string): boolean {
  return /^https:\/\//i.test(value.trim())
}

function isObject(v: unknown): v is Record<string, unknown> {
  return typeof v === 'object' && v !== null && !Array.isArray(v)
}

/**
 * Validate a `download:`-shaped sub-block (url/sha256/size_bytes/license_url), collecting
 * errors. Shared by the top-level `download` block and the `mmproj.download` block so the
 * rules (https-only URL, L-2; a real download hash must equal the real FILE hash) have one
 * definition. `fileSha` is the hash of the file this block fetches (the top-level `sha256`
 * for `download`, the `mmproj.sha256` for `mmproj.download`); `label` prefixes every message.
 */
function validateDownloadSubBlock(
  dl: unknown,
  fileSha: string,
  errors: string[],
  // `files[N].download` joins the two original labels (#310); every message is derived from
  // the label so a new slot needs no new message text.
  label: 'download' | 'mmproj.download' | `files[${number}].download`
): DownloadSpec | undefined {
  if (!isObject(dl)) {
    errors.push(`"${label}" must be a mapping (url/sha256/size_bytes/license_url)`)
    return undefined
  }
  const url = dl['url']
  if (typeof url !== 'string' || url.trim() === '') {
    errors.push(`"${label}.url" is required and must be a non-empty string`)
  } else if (!isHttpsUrl(url)) {
    // L-2: cleartext http:// leaks which model is fetched and is downgrade-friendly.
    errors.push(`"${label}.url" must be an https:// URL`)
  }
  const dlShaRaw = dl['sha256']
  if (typeof dlShaRaw !== 'string' || dlShaRaw.trim() === '') {
    errors.push(`"${label}.sha256" is required and must be a string (hash or placeholder)`)
  }
  const dlSha = typeof dlShaRaw === 'string' ? dlShaRaw.trim().toLowerCase() : ''
  // A real download hash must equal the real expected hash of the same file.
  if (isRealSha256(dlSha) && isRealSha256(fileSha) && dlSha !== fileSha) {
    const owner =
      label === 'download'
        ? 'the top-level "sha256"'
        : `the "${label.slice(0, -'.download'.length)}.sha256"`
    errors.push(`"${label}.sha256" must equal ${owner} when both are real hashes`)
  }
  const sizeRaw = dl['size_bytes']
  let sizeBytes: number | null = null
  if (sizeRaw !== undefined && sizeRaw !== null) {
    if (typeof sizeRaw !== 'number' || !Number.isFinite(sizeRaw) || sizeRaw < 0) {
      errors.push(`"${label}.size_bytes" must be a non-negative number when present`)
    } else {
      sizeBytes = sizeRaw
    }
  }
  const licenseUrlRaw = dl['license_url']
  if (licenseUrlRaw !== undefined && licenseUrlRaw !== null) {
    if (typeof licenseUrlRaw !== 'string') {
      errors.push(`"${label}.license_url" must be a string when present`)
    } else if (!isHttpsUrl(licenseUrlRaw)) {
      // #236: the licence link renders as an anchor in the download dialog, so it takes the
      // same https-only rule as `url` — a manifest cannot plant an http: or javascript:
      // destination behind the fixed "read the license" label.
      errors.push(`"${label}.license_url" must be an https:// URL when present`)
    }
  }
  // Optional withdrawal note (#196). A non-empty STRING, never a bare `true`: the note is
  // shown to the user and read by a maintainer months later, so "withdrawn" without a date
  // and a reason is worse than no field at all.
  const withdrawnRaw = dl['withdrawn']
  let withdrawn: string | undefined
  if (withdrawnRaw !== undefined && withdrawnRaw !== null) {
    if (typeof withdrawnRaw !== 'string' || withdrawnRaw.trim() === '') {
      errors.push(`"${label}.withdrawn" must be a non-empty string (a dated reason) when present`)
    } else {
      withdrawn = withdrawnRaw.trim()
    }
  }
  return {
    url: typeof url === 'string' ? url.trim() : '',
    sha256: dlSha,
    sizeBytes,
    licenseUrl: typeof licenseUrlRaw === 'string' ? licenseUrlRaw.trim() : null,
    ...(withdrawn ? { withdrawn } : {})
  }
}

/**
 * Validate a parsed YAML object into a ModelManifest, collecting all errors.
 * Pure (no I/O) so it is trivial to unit-test.
 */
/**
 * Reject a manifest path that is not a contained, drive-RELATIVE path: an absolute path
 * (leading `/`, a `C:`-style drive letter, or a UNC root) or one with a `..` segment that
 * could escape the drive root. The runtime escape guard (`safeDrivePath`/`weightPath`)
 * already THROWS on such a path before it could ever reach a `--model` argument, but that
 * throw is unhandled on the model-LIST path, so a single hostile manifest (the threat
 * model's #1 attacker — `model-manifests/` is user-writable) could break the whole Models
 * screen. Rejecting it here at the source means `discoverManifests` records it in `errors`
 * and SKIPS it, so the rest of the list still renders (vuln-scan 2026-06-21 [path-traversal]).
 */
function isUnsafeManifestPath(p: string): boolean {
  const norm = p.replace(/\\/g, '/')
  if (norm.startsWith('/')) return true // POSIX-absolute or a UNC `\\server\share` root
  if (/^[A-Za-z]:/.test(norm)) return true // Windows drive-letter absolute (`C:/…`)
  return norm.split('/').some((seg) => seg === '..')
}

/**
 * #848: THE model for a role, among the manifests it is given (`discoverManifests().manifests`, walk order): the first
 * one flagged `default_for_role`, else the first of the role; whether its files are on the drive is the caller's
 * business. One rule for every place that names "the role's model" — `resolveModelByRole` (what the app composes),
 * the Performance screen's rows, the Models-screen ★ on an embeddings card, and (#890) the images model
 * (`visionCandidates` passes only the vision manifests whose files are all on the drive, so a flagged model that is
 * not there is passed over; the Performance row names that pick and `getVisionStatus` tries it first) — so they
 * cannot disagree. When no usable manifest of the role is flagged
 * (none ever was, or the flagged one is invalid or for a newer HilbertRaum), the walk-order fallback applies; hence the
 * frozen constraint that a release never makes the flagged manifest unusable for an older build without flagging a
 * replacement (model-policy.md `default_for_role`).
 */
export function pickManifestForRole(manifests: readonly ModelManifest[], role: ModelRole): ModelManifest | undefined {
  return manifests.find((m) => m.role === role && m.defaultForRole === true) ?? manifests.find((m) => m.role === role)
}

/**
 * #847: does this parsed manifest name a role this build does not know? Only a NON-EMPTY string outside the
 * known roles counts; a missing, blank or non-string role stays an error in `validateManifest`, exactly as
 * before (a typo of the field is not a newer manifest).
 */
export function declaresUnknownRole(raw: unknown): boolean {
  if (!isObject(raw)) return false
  const role = raw['role']
  return typeof role === 'string' && role.trim() !== '' && !ROLES.includes(role.trim() as ModelRole)
}

/** A `min_app_version`: EXACTLY `MAJOR.MINOR.PATCH`, semver numbers (no leading zero), nothing before or after. */
const MIN_APP_VERSION_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/
/** The app's own version: `MAJOR.MINOR.PATCH`, an optional `-pre.release` (group 4) and an optional `+build`. */
const APP_VERSION_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/

/**
 * #847 (a+): is this manifest for a newer HilbertRaum by its optional `min_app_version`? Read BEFORE
 * validation, so a later release can mark ANY manifest (a new field rule, a new enum value, a model its
 * pinned engine cannot load) as not for this build, and this build lists it instead of rejecting it.
 * Absent (or null): false, the manifest is validated as usual. Fail-safe, unlike the skills courtesy gate,
 * because this build cannot vouch for a manifest that names a version it cannot read: a `min_app_version`
 * that is not exactly `MAJOR.MINOR.PATCH` (a pre-release minimum, a fourth part, a leading zero, a `v`, a
 * number), or an app version it does not know (`''` before startup set it, a tool that passed none), counts
 * as newer. Parts compare as numbers; a pre-release app is OLDER than its own release (`0.1.66-beta.1` does
 * not meet `0.1.66`, semver); build metadata is ignored. FROZEN: every later release's manifests meet this.
 */
export function manifestNeedsNewerApp(raw: unknown, appVersion: string): boolean {
  if (!isObject(raw)) return false
  const min = raw['min_app_version']
  if (min === undefined || min === null) return false
  const need = typeof min === 'string' ? MIN_APP_VERSION_RE.exec(min) : null
  const have = typeof appVersion === 'string' ? APP_VERSION_RE.exec(appVersion) : null
  if (!need || !have) return true
  for (let i = 1; i <= 3; i++) {
    const h = Number(have[i])
    const n = Number(need[i])
    if (h !== n) return h < n
  }
  return have[4] !== undefined // the same release: a pre-release of it does not meet it
}

/**
 * #847: read the display subset of a manifest for a newer HilbertRaum (see {@link UnsupportedManifest}).
 * Requires `id` and `display_name` (non-empty strings, trimmed, as `validateManifest` reads them) and refuses
 * any declared file path that is not drive-relative; every other field is ignored, whatever its value.
 */
export function parseUnsupportedManifest(raw: unknown): UnsupportedParseResult {
  if (!isObject(raw)) {
    return { ok: false, errors: ['manifest must be a YAML mapping (key: value pairs)'] }
  }
  const errors: string[] = []
  const text = (snake: string): string | null => {
    const v = raw[snake]
    return typeof v === 'string' && v.trim() !== '' ? v.trim() : null
  }
  const id = text('id')
  if (id === null) errors.push('"id" is required and must be a non-empty string')
  const displayName = text('display_name')
  if (displayName === null) errors.push('"display_name" is required and must be a non-empty string')
  const localPaths: string[] = []
  const path = (value: unknown, label: string): void => {
    if (typeof value !== 'string' || value.trim() === '') return
    const p = value.trim()
    if (isUnsafeManifestPath(p)) {
      errors.push(`"${label}" must be a drive-relative path (no leading "/", drive letter, or ".." segment)`)
    } else {
      localPaths.push(p)
    }
  }
  path(raw['local_path'], 'local_path')
  const mp = raw['mmproj']
  if (isObject(mp)) path(mp['local_path'], 'mmproj.local_path')
  const files = raw['files']
  if (Array.isArray(files)) {
    files.forEach((f: unknown, i: number) => {
      if (isObject(f)) path(f['local_path'], `files[${i}].local_path`)
    })
  }
  if (errors.length > 0 || id === null || displayName === null) return { ok: false, errors }
  const size = raw['size_on_disk_gb']
  const min = raw['min_app_version']
  return {
    ok: true,
    errors: [],
    entry: {
      id,
      displayName,
      role: text('role'),
      family: text('family'),
      sizeOnDiskGb: typeof size === 'number' && Number.isFinite(size) && size >= 0 ? size : null,
      minAppVersion: typeof min === 'string' ? min.trim() : null,
      localPaths
    }
  }
}

export function validateManifest(raw: unknown): ValidationResult {
  const errors: string[] = []
  if (!isObject(raw)) {
    return { ok: false, errors: ['manifest must be a YAML mapping (key: value pairs)'] }
  }

  const str = (key: string, snake: string): string => {
    const v = raw[snake]
    if (typeof v !== 'string' || v.trim() === '') {
      errors.push(`"${snake}" is required and must be a non-empty string`)
      return ''
    }
    return v.trim()
  }

  const num = (snake: string): number => {
    const v = raw[snake]
    if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
      errors.push(`"${snake}" is required and must be a non-negative number`)
      return 0
    }
    return v
  }

  const id = str('id', 'id')
  const displayName = str('displayName', 'display_name')
  const family = str('family', 'family')
  const roleRaw = str('role', 'role')
  if (roleRaw && !ROLES.includes(roleRaw as ModelRole)) {
    errors.push(`"role" must be one of: ${ROLES.join(', ')}`)
  }
  const format = str('format', 'format')
  const runtime = str('runtime', 'runtime')
  const license = str('license', 'license')
  const sizeOnDiskGb = num('size_on_disk_gb')
  const recommendedMinRamGb = num('recommended_min_ram_gb')
  const recommendedRamGb = num('recommended_ram_gb')
  const recommendedContextTokens = num('recommended_context_tokens')
  const localPath = str('localPath', 'local_path')
  if (localPath && isUnsafeManifestPath(localPath)) {
    errors.push('"local_path" must be a drive-relative path (no leading "/", drive letter, or ".." segment)')
  }
  const sha256 = str('sha256', 'sha256').toLowerCase()

  // Optional capability flag: must be a boolean when present.
  let supportsThinkingMode = false
  const stm = raw['supports_thinking_mode']
  if (stm !== undefined) {
    if (typeof stm !== 'boolean') {
      errors.push('"supports_thinking_mode" must be a boolean when present')
    } else {
      supportsThinkingMode = stm
    }
  }

  // Optional Kit flag (#766): must be a boolean when present.
  let bundledOnPreconfiguredDrive = false
  const bundled = raw['bundled_on_preconfigured_drive']
  if (bundled !== undefined) {
    if (typeof bundled !== 'boolean') {
      errors.push('"bundled_on_preconfigured_drive" must be a boolean when present')
    } else {
      bundledOnPreconfiguredDrive = bundled
    }
  }

  // Optional role default (#848): a boolean when present. Accepted on every role: on chat nothing reads it, and a
  // field this release reads is ignored where it is inert, never rejected (D848-3), so a later manifest that uses it
  // differently does not vanish from this build.
  let defaultForRole = false
  const dfr = raw['default_for_role']
  if (dfr !== undefined) {
    if (typeof dfr !== 'boolean') {
      errors.push('"default_for_role" must be a boolean when present')
    } else {
      defaultForRole = dfr
    }
  }

  // Optional speculative-decoding opt-in (#182). Closed enum (see SpeculativeDecoding) and
  // chat-only — the chat start ladder is the sole consumer, so a value on an embeddings or
  // vision manifest would be silently inert; rejected rather than ignored.
  let speculativeDecoding: SpeculativeDecoding | undefined
  const sd = raw['speculative_decoding']
  if (sd !== undefined) {
    if (typeof sd !== 'string' || !SPECULATIVE_SCHEMES.includes(sd as SpeculativeDecoding)) {
      errors.push(`"speculative_decoding" must be one of: ${SPECULATIVE_SCHEMES.join(', ')}`)
    } else if (roleRaw !== 'chat') {
      errors.push('"speculative_decoding" is only supported for role: chat')
    } else {
      speculativeDecoding = sd as SpeculativeDecoding
    }
  }

  // Optional prompt-cache opt-out (#512). Boolean, chat-only for the same reason as
  // speculative_decoding: only the chat argv builder reads it, so on any other role it would be
  // silently inert — rejected rather than ignored.
  let disablePromptCache = false
  const dpc = raw['disable_prompt_cache']
  if (dpc !== undefined) {
    if (typeof dpc !== 'boolean') {
      errors.push('"disable_prompt_cache" must be a boolean when present')
    } else if (roleRaw !== 'chat') {
      errors.push('"disable_prompt_cache" is only supported for role: chat')
    } else {
      disablePromptCache = dpc
    }
  }

  // Optional: which hardware profiles this model targets.
  let recommendedProfiles: HardwareProfile[] = []
  const rp = raw['recommended_profiles']
  if (rp !== undefined) {
    if (!Array.isArray(rp) || !rp.every((p) => typeof p === 'string' && PROFILES.includes(p as HardwareProfile))) {
      errors.push(`"recommended_profiles" must be a list of: ${PROFILES.join(', ')}`)
    } else {
      recommendedProfiles = rp as HardwareProfile[]
    }
  }

  // Optional recommendation tiebreak: higher = preferred among models that fit.
  let recommendationRank = 0
  const rr = raw['recommendation_rank']
  if (rr !== undefined) {
    if (typeof rr !== 'number' || !Number.isFinite(rr)) {
      errors.push('"recommendation_rank" must be a number when present')
    } else {
      recommendationRank = rr
    }
  }

  // Optional processor-path fields (model-benchmarks.md §6.7). Both move a recommendation, so a
  // wrong type fails the manifest instead of silently falling back to the ordinary rank.
  let recommendationRankCpu: number | undefined
  const rrc = raw['recommendation_rank_cpu']
  if (rrc !== undefined) {
    if (typeof rrc !== 'number' || !Number.isFinite(rrc) || rrc < 0) {
      errors.push('"recommendation_rank_cpu" must be a non-negative number when present')
    } else {
      recommendationRankCpu = rrc
    }
  }
  let stepDownTo: string | undefined
  const csd = raw['step_down_to']
  if (csd !== undefined) {
    if (typeof csd !== 'string' || csd.trim() === '') {
      errors.push('"step_down_to" must be a non-empty model id when present')
    } else {
      stepDownTo = csd.trim()
    }
  }

  // Optional card-path fields (model-benchmarks.md §6.8), validated like the processor ones.
  let recommendationRankGpu: number | undefined
  const rrg = raw['recommendation_rank_gpu']
  if (rrg !== undefined) {
    if (typeof rrg !== 'number' || !Number.isFinite(rrg) || rrg < 0) {
      errors.push('"recommendation_rank_gpu" must be a non-negative number when present')
    } else {
      recommendationRankGpu = rrg
    }
  }
  let projectedGraphicsNeedMib: number | undefined
  const pgn = raw['projected_graphics_need_mib']
  if (pgn !== undefined) {
    if (typeof pgn !== 'number' || !Number.isFinite(pgn) || pgn < 0) {
      errors.push('"projected_graphics_need_mib" must be a non-negative number when present')
    } else {
      projectedGraphicsNeedMib = pgn
    }
  }

  // Optional per-model context-cache estimate for the graphics-memory fit (decision 11): a
  // non-negative number of GiB when present. Wrong type or a negative value is an error, not a
  // silent default — the field moves a recommendation, so a typo must fail the manifest.
  let estimatedContextCacheGib: number | undefined
  const ecc = raw['estimated_context_cache_gib']
  if (ecc !== undefined) {
    if (typeof ecc !== 'number' || !Number.isFinite(ecc) || ecc < 0) {
      errors.push('"estimated_context_cache_gib" must be a non-negative number when present')
    } else {
      estimatedContextCacheGib = ecc
    }
  }

  // Optional measured host-mapped weight share for the same estimate (#321): validated exactly
  // like the cache term above — a typo must fail the manifest, not silently widen the estimate.
  let hostMappedWeightsMib: number | undefined
  const hmw = raw['host_mapped_weights_mib']
  if (hmw !== undefined) {
    if (typeof hmw !== 'number' || !Number.isFinite(hmw) || hmw < 0) {
      errors.push('"host_mapped_weights_mib" must be a non-negative number when present')
    } else {
      hostMappedWeightsMib = hmw
    }
  }

  // Required license-review gate (spec §7.4 / model-policy.md).
  const lr = raw['license_review']
  let licenseReview: LicenseReview = {
    status: 'pending',
    reviewedBy: null,
    reviewedAt: null,
    notes: ''
  }
  if (!isObject(lr)) {
    errors.push('"license_review" block is required (status/reviewed_by/reviewed_at/notes)')
  } else {
    const status = lr['status']
    if (typeof status !== 'string' || !REVIEW_STATUSES.includes(status as (typeof REVIEW_STATUSES)[number])) {
      errors.push(`"license_review.status" must be one of: ${REVIEW_STATUSES.join(', ')}`)
    }
    licenseReview = {
      status: (REVIEW_STATUSES as readonly string[]).includes(String(status))
        ? (status as LicenseReview['status'])
        : 'pending',
      reviewedBy: typeof lr['reviewed_by'] === 'string' ? (lr['reviewed_by'] as string) : null,
      reviewedAt: typeof lr['reviewed_at'] === 'string' ? (lr['reviewed_at'] as string) : null,
      notes: typeof lr['notes'] === 'string' ? (lr['notes'] as string) : ''
    }
  }

  // Optional download block. Validated only when present, so existing
  // manifests with no `download:` stay valid.
  let download: DownloadSpec | undefined
  if (raw['download'] !== undefined) {
    download = validateDownloadSubBlock(raw['download'], sha256, errors, 'download')
  }

  // Optional informational input modalities (e.g. [text, image] for a vision model).
  let inputModalities: string[] | undefined
  const im = raw['input_modalities']
  if (im !== undefined) {
    if (!Array.isArray(im) || !im.every((x) => typeof x === 'string')) {
      errors.push('"input_modalities" must be a list of strings when present')
    } else {
      inputModalities = im as string[]
    }
  }

  // Optional multimodal projector block (image-understanding plan §8.1). Validated only when
  // present, and REQUIRED when `role: vision`. A build that does not know the role never gets here: discovery
  // lists such a manifest as needing a newer HilbertRaum (#847, `parseUnsupportedManifest`).
  let mmproj: MmprojSpec | undefined
  const mp = raw['mmproj']
  if (mp !== undefined) {
    if (!isObject(mp)) {
      errors.push('"mmproj" must be a mapping (local_path/sha256/download)')
    } else {
      const mpLocalRaw = mp['local_path']
      let mpLocal = ''
      if (typeof mpLocalRaw !== 'string' || mpLocalRaw.trim() === '') {
        errors.push('"mmproj.local_path" is required and must be a non-empty string')
      } else {
        mpLocal = mpLocalRaw.trim()
        if (isUnsafeManifestPath(mpLocal)) {
          errors.push('"mmproj.local_path" must be a drive-relative path (no leading "/", drive letter, or ".." segment)')
        }
      }
      const mpShaRaw = mp['sha256']
      if (typeof mpShaRaw !== 'string' || mpShaRaw.trim() === '') {
        errors.push('"mmproj.sha256" is required and must be a string (hash or placeholder)')
      }
      const mpSha = typeof mpShaRaw === 'string' ? mpShaRaw.trim().toLowerCase() : ''
      let mpDownload: DownloadSpec | undefined
      if (mp['download'] !== undefined) {
        mpDownload = validateDownloadSubBlock(mp['download'], mpSha, errors, 'mmproj.download')
      }
      mmproj = { localPath: mpLocal, sha256: mpSha, ...(mpDownload ? { download: mpDownload } : {}) }
    }
  }
  if (roleRaw === 'vision' && mmproj === undefined) {
    errors.push('"mmproj" projector block is required when role is "vision"')
  }
  // #752: all-or-nothing, the rule `files:` follows below. The planner fetches only the blocks
  // that exist, so half of them is a clean multi-GB download of a model that stays `missing`.
  const hasTopDownload = raw['download'] !== undefined
  if (isObject(mp)) {
    const hasProjectorDownload = mp['download'] !== undefined
    if (hasTopDownload && !hasProjectorDownload) {
      errors.push(
        '"mmproj.download" is required when the model declares a top-level "download" (a partial download plan would install a model that cannot start)'
      )
    }
    if (hasProjectorDownload && !hasTopDownload) {
      errors.push(
        '"download" is required when "mmproj" declares one (a partial download plan would install a model that cannot start)'
      )
    }
  }

  // Optional ADDITIONAL required files (#310): the rest of a multi-file weight, each with its
  // own path + hash (+ optional source). Validated only when present, so a single-file
  // manifest validates byte-identically without it.
  let files: RequiredFileSpec[] | undefined
  const rawFiles = raw['files']
  if (rawFiles !== undefined) {
    if (!Array.isArray(rawFiles)) {
      errors.push('"files" must be a list of mappings (local_path/sha256/download)')
    } else if (rawFiles.length === 0) {
      // "Partial declaration" needs a crisp definition: an empty list is a typo, not a claim.
      errors.push('"files" must not be an empty list — omit it instead')
    } else {
      // Every path this manifest already claims. A duplicate would hash the same file twice
      // and double-count its bytes in the load-progress denominator.
      const seen = new Set<string>()
      if (localPath) seen.add(localPath)
      if (mmproj?.localPath) seen.add(mmproj.localPath)
      const parsed: RequiredFileSpec[] = []
      rawFiles.forEach((entry: unknown, i: number) => {
        if (!isObject(entry)) {
          errors.push(`"files[${i}]" must be a mapping (local_path/sha256/download)`)
          return
        }
        const rawLocal = entry['local_path']
        let local = ''
        if (typeof rawLocal !== 'string' || rawLocal.trim() === '') {
          errors.push(`"files[${i}].local_path" is required and must be a non-empty string`)
        } else {
          local = rawLocal.trim()
          if (isUnsafeManifestPath(local)) {
            errors.push(
              `"files[${i}].local_path" must be a drive-relative path (no leading "/", drive letter, or ".." segment)`
            )
          } else if (seen.has(local)) {
            errors.push(
              `"files[${i}].local_path" must not repeat a path the manifest already declares: ${local}`
            )
          } else {
            seen.add(local)
          }
        }
        const rawSha = entry['sha256']
        if (typeof rawSha !== 'string' || rawSha.trim() === '') {
          errors.push(`"files[${i}].sha256" is required and must be a string (hash or placeholder)`)
        }
        const sha = typeof rawSha === 'string' ? rawSha.trim().toLowerCase() : ''
        const hasFileDownload = entry['download'] !== undefined
        let fileDownload: DownloadSpec | undefined
        if (hasFileDownload) {
          fileDownload = validateDownloadSubBlock(entry['download'], sha, errors, `files[${i}].download`)
        }
        // Download all-or-nothing: the planner fetches exactly the files that carry a source,
        // so a half-declared plan would install a model that cannot start.
        if (hasTopDownload && !hasFileDownload) {
          errors.push(
            `"files[${i}].download" is required when the model declares a top-level "download" (a partial download plan would install a model that cannot start)`
          )
        }
        if (!hasTopDownload && hasFileDownload) {
          errors.push(
            `"download" is required when "files[${i}]" declares one (a partial download plan would install a model that cannot start)`
          )
        }
        parsed.push({
          localPath: local,
          sha256: sha,
          ...(fileDownload ? { download: fileDownload } : {})
        })
      })
      files = parsed
    }
  }

  // Shard-convention completeness (#310). A `-00001-of-000NN.gguf` path names ONE piece of a
  // weight; without the rest declared the app would hash a third of a model and call it
  // installed. Non-shard entries in `files:` are untouched — the field stays generic.
  const shard = SHARD_RE.exec(localPath)
  if (shard) {
    const total = Number(shard[2])
    const stem = localPath.slice(0, shard.index)
    if (total < 1) {
      errors.push('"local_path" must name a shard set of at least one shard, not "-of-00000"')
    } else if (Number(shard[1]) !== 1) {
      errors.push(
        `"local_path" must name the first shard (00001) of a multi-file weight, not shard ${shard[1]} of ${shard[2]}`
      )
    } else if (total > 1) {
      const siblings: string[] = []
      for (let n = 2; n <= total; n++) {
        siblings.push(`${stem}-${String(n).padStart(5, '0')}-of-${shard[2]}${shard[3]}`)
      }
      if (rawFiles === undefined) {
        errors.push(
          '"local_path" names shard 1 of a multi-file weight but no "files" list declares the remaining shards'
        )
      } else if (files) {
        const declared = files.map((f) => f.localPath)
        for (const want of siblings) {
          if (!declared.includes(want)) {
            errors.push(`"files" is missing a required shard of this weight: ${want}`)
          }
        }
        files.forEach((f, i) => {
          if (SHARD_RE.test(f.localPath) && !siblings.includes(f.localPath)) {
            errors.push(`"files[${i}].local_path" does not name a shard of this weight: ${f.localPath}`)
          }
        })
      }
    }
  }

  if (errors.length > 0) {
    return { ok: false, errors }
  }

  return {
    ok: true,
    errors: [],
    manifest: {
      id,
      displayName,
      family,
      role: roleRaw as ModelRole,
      format,
      runtime,
      license,
      sizeOnDiskGb,
      recommendedMinRamGb,
      recommendedRamGb,
      recommendedContextTokens,
      supportsThinkingMode,
      bundledOnPreconfiguredDrive,
      ...(speculativeDecoding ? { speculativeDecoding } : {}),
      ...(disablePromptCache ? { disablePromptCache: true } : {}),
      localPath,
      sha256,
      recommendedProfiles,
      recommendationRank,
      ...(recommendationRankCpu !== undefined ? { recommendationRankCpu } : {}),
      ...(stepDownTo !== undefined ? { stepDownTo } : {}),
      ...(recommendationRankGpu !== undefined ? { recommendationRankGpu } : {}),
      ...(projectedGraphicsNeedMib !== undefined ? { projectedGraphicsNeedMib } : {}),
      ...(estimatedContextCacheGib !== undefined ? { estimatedContextCacheGib } : {}),
      ...(hostMappedWeightsMib !== undefined ? { hostMappedWeightsMib } : {}),
      licenseReview,
      ...(download ? { download } : {}),
      ...(inputModalities ? { inputModalities } : {}),
      ...(mmproj ? { mmproj } : {}),
      ...(files ? { files } : {}),
      ...(defaultForRole ? { defaultForRole: true as const } : {})
    }
  }
}