Skip to content

AI, fully local on your computer.

29.4 KB
Raw Blame
import { existsSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
import { createSelectedEmbedder } from './embeddings/factory'
import { createSelectedReranker } from './reranker'
import { createSelectedTranscriber, transcriberMissingReason } from './transcriber'
import { createSelectedOcrEngine, listOcrLanguages, ocrAssetsDir, type OcrSelectionDeps } from './ocr'
import { OCR_ORIENTATION_LANG } from './ocr/orientation'
import { createSelectedTranslator } from './translation'
import { resolveModelByRole } from './resolve-model'
import {
  discoverManifests,
  findManifestById,
  type BoundModelStartCheck,
  type DiscoveredManifest,
  type ModelStartCheck
} from './models'
import { engineFamilyHasHostBuild } from './runtime-download'
import { clearModelLoadLatch } from './runtime/factory'
import { rearmStartRefusals, type RearmTargets } from './model-start-check'
import { log } from './logging'
import { perfMark } from './perf'
import type { Embedder } from './embeddings'
import type { Reranker } from './reranker'
import type { Transcriber } from './transcriber'
import type { OcrEngine } from './ocr'
import type { Translator, TranslationGpuDeps } from './translation'
import type { AppContext } from './context'
import type { OcrRefreshOutcome, TranscriberMissing } from '../../shared/types'

// M-A3 (audit-2026-06-13): the four availability-driven service selectors (embedder,
// reranker, transcriber, OCR) were ~30 lines of near-identical "resolve the role's model,
// pick the real sidecar-backed service when its binary + weights are present, else
// mock/null, and log the choice" inline in initBackend(). They depend on nothing but the
// drive root + the manifests dir, so they extract cleanly into one builder. The
// runtime/GPU wiring (late-bound crash handler) stays in initBackend — it is genuinely
// entangled and not part of this cohesive unit.

export interface AvailabilityServices {
  embedder: Embedder
  reranker: Reranker | null
  transcriber: Transcriber | null
  /** Why `transcriber` is null (#527) — null when it is selected. See `composeTranscriberSlot`. */
  transcriberMissing: TranscriberMissing | null
  ocrEngine: OcrEngine | null
  /**
   * The TranslateGemma translation sidecar (TG wave, plan §2 D1), selected only when its binary +
   * GGUF are present (null otherwise — translation refuses with a friendly install path at TG-3;
   * no mock, which would invent a translation). Availability-driven via `resolveModelByRole`.
   */
  translator: Translator | null
}

export interface ComposeServicesDeps {
  /** Drive root used to resolve binaries + weight paths. */
  rootPath: string
  /** Resolved model-manifests dir, or null (→ every role falls back to mock/null). */
  manifestsDir: string | null
  /**
   * Developer build (`!app.isPackaged`). Gates the dev-only `HILBERTRAUM_LLAMA_BIN` /
   * `HILBERTRAUM_WHISPER_BIN` binary overrides (M-5): in a packaged build the sidecar
   * binaries are resolved only from the on-drive location, never an env-supplied path.
   * Defaults to `false` (ignore the override) so a forgetful caller fails SAFE.
   */
  isDev?: boolean
  /**
   * GPU signals for the TRANSLATION sidecar's device ladder (issue #42) — the same Settings
   * read-callbacks the chat ladder gets. Only the translator consumes them for now: the embedder,
   * reranker, and vision sidecars keep their own (CPU) device postures per their design records.
   */
  gpu?: TranslationGpuDeps
  /**
   * Manifests already discovered by THIS composition pass (PF-4, full-audit 2026-07-10).
   * `composeServices` fills it in so its role resolutions share ONE synchronous walk + YAML
   * parse; the issue-#40 `onModelInstalled` → `composeTranslator` call site omits it and
   * re-discovers, because it reacts to a download that just CHANGED the drive layout.
   */
  discovered?: DiscoveredManifest[]
  /**
   * Step 4-4 (Wave 4 ruling (a)), Wave 8 ruling (a)/(b)(Q) (step 4-8): which device the reranker
   * sidecar should use — consulted by `rerank()` before starting/joining/reusing the sidecar,
   * and again after every await inside it (never once per cold start any more). Optional on
   * THIS base type only because `composeTranslator` shares it and never touches the reranker;
   * `composeServices`'s own signature below REQUIRES it (`ComposeServicesRerankerDeps`) — Wave 8
   * NF-1, the analysis's finding that an optional wire here is exactly how a posture input
   * silently goes missing. The ONE production caller (`main/index.ts`) builds it with the
   * exported `createRerankerCallbacks` factory (`rag/device-posture.ts`), never inline. Tests
   * that construct a reranker directly (`createLlamaReranker`, bypassing `composeServices`) are
   * unaffected — that option stays optional there too, which is what keeps the acceptance
   * harness inert by default (ruling (f)).
   */
  rerankerDevicePosture?: () => 'gpu' | 'cpu'
  /**
   * Wave 8 ruling (b)(G): the CPU posture's per-call request ceiling. Optional on this base type
   * for the same `composeTranslator`-sharing reason as `rerankerDevicePosture` above;
   * `composeServices`'s own signature requires it. Absent at the `LlamaReranker` level (a direct
   * construction, e.g. the acceptance harness or a manual smoke) admits every request —
   * additive, never a behaviour change there.
   */
  rerankerRequestCeiling?: () => number
  /**
   * #913: the start check every non-chat role runs before it spawns its model (`main/index.ts` builds it from the
   * workspace: the manifest by id, the policy-aware developer leniency, the hash store). Each composer binds it to its
   * role's model and hashing choice (`HASH_BEFORE_FIRST_START`). Optional on this shared base only (the
   * transcriber's own composition reads it off the context); `composeServices` and `composeTranslator` require it,
   * so a composition root that forgets it does not compile (the NF-1 rule below, #913 review S3).
   */
  checkModel?: ModelStartCheck
}

/**
 * #913, G-4 (d2): the roles whose file is hashed before its first start in a workspace (cold: seconds, once; then the
 * cache answers in about 1 ms). Their bad output is stored: damaged search vectors go into the index, a damaged voice
 * model writes wrong transcripts. The other roles only read the cache, so they refuse a file a check already found
 * damaged and never pay a first-use hash (vision 10–33 s, translation 22–73 s on USB 3).
 */
export const HASH_BEFORE_FIRST_START = {
  embeddings: true,
  transcriber: true,
  reranker: false,
  translation: false
} as const

/**
 * #913: `check` bound to one role's model, its hashing choice and the manifest the service is composed from, or
 * undefined (no check) without a check or a model. The manifest comes from this composition's walk (`discovered`),
 * else from one read now, so a cold start (and every transcription) reads no manifest folder (#913 code review): the
 * service runs the file this manifest names until it is composed again, and the check goes by the same manifest.
 */
function startCheckFor(
  check: ModelStartCheck | undefined,
  model: { id: string } | null,
  role: keyof typeof HASH_BEFORE_FIRST_START,
  deps: Pick<ComposeServicesDeps, 'manifestsDir' | 'discovered'>
): BoundModelStartCheck | undefined {
  if (!check || !model) return undefined
  const hash = HASH_BEFORE_FIRST_START[role]
  const manifest =
    deps.discovered?.find((d) => d.manifest.id === model.id)?.manifest ??
    findManifestById(deps.manifestsDir, model.id) ??
    undefined
  return (signal) => check(model.id, { hash, signal, manifest })
}

/**
 * Wave 8 ruling (b)(G)/NF-1: the two reranker callbacks, REQUIRED specifically on
 * `composeServices`'s own parameter type (below) — never on the shared `ComposeServicesDeps`
 * base, which `composeTranslator` also takes and never touches the reranker. An intersection,
 * not a widened base interface, so `composeTranslator`'s existing callers are untouched and a
 * composition test can prove `composeServices` alone refuses a missing wire
 * (`// @ts-expect-error`).
 */
export type ComposeServicesArgs = ComposeServicesDeps &
  EnginePinsDeps &
  Required<Pick<ComposeServicesDeps, 'rerankerDevicePosture' | 'rerankerRequestCeiling' | 'checkModel'>>

/** The translator's composition: the drive layout plus the start check, required (#913 review S3). */
export type ComposeTranslatorDeps = ComposeServicesDeps & Required<Pick<ComposeServicesDeps, 'checkModel'>>

/**
 * #842: where the engine pins live, for the transcriber's composition and `composeServices`. Never on
 * the shared base: `composeTranslator` takes that and never reads it, and an optional field there would
 * be one a composer could drop without a compile error (the NF-1 rule above).
 */
export interface EnginePinsDeps {
  /**
   * The app's own `model-manifests/` (`AppContext.bundledManifestsDir`): its `runtime-sources.yaml`
   * says whether the in-app installer could fetch the voice engine here (#527), the same pins the
   * installer reads. Null: no engine build to fetch.
   */
  bundledManifestsDir: string | null
}

/** The transcriber's composition: the drive layout plus the engine pins (#842) and the start check (#913, required). */
export type ComposeTranscriberDeps = ComposeServicesDeps &
  EnginePinsDeps &
  Required<Pick<ComposeServicesDeps, 'checkModel'>>

/**
 * Build (or re-build) JUST the translation sidecar selection from the current drive layout.
 * Extracted from `composeServices` for issue #40: a completed in-app model download re-runs THIS
 * selector (via `AppContext.onModelInstalled`) so translation activates without an app restart —
 * both call sites stay byte-identical in their deps. Cheap + synchronous by design (the sidecar is
 * lazy; construction spawns nothing).
 */
export function composeTranslator(deps: ComposeTranslatorDeps, reranker?: Reranker | null): Translator | null {
  const model = resolveModelByRole(deps.manifestsDir, deps.rootPath, 'translation', {
    discovered: deps.discovered
  })
  return createSelectedTranslator({
    beforeGpuStart: translationGpuYield(reranker),
    rootPath: deps.rootPath,
    isDev: deps.isDev ?? false,
    model,
    checkModel: startCheckFor(deps.checkModel, model, 'translation', deps),
    gpu: deps.gpu,
    onDeviceFallback: (reason) =>
      log.warn('Translation sidecar fell back to CPU for this session', { reason }),
    // Issue #42 reopen: log every cold start's observed outcome symmetrically with the chat
    // ladder's "started via rung …" line. The layer split is what makes a silent `--fit`
    // PARTIAL offload (a resident chat model took the VRAM → ~CPU-speed decode under a 'gpu'
    // posture) diagnosable from app.log; posture alone would hide it.
    // #671: with whether the load log put a buffer on a graphics device — the split alone reads
    // `49/49 layers` on a PC with no usable card too.
    onStarted: ({ device, gpuLayers, totalLayers, gpuBuffers }) =>
      log.info('Translation sidecar started', {
        device,
        offload: gpuLayers != null && totalLayers != null ? `${gpuLayers}/${totalLayers} layers` : 'not reported',
        gpuBuffers: gpuBuffers ?? 'not reported'
      }),
    onSelect: (kind, reason) => log.info('Translation backend selected', { kind, reason })
  })
}

/**
 * #473: the translator's `beforeGpuStart` hook. A translation cold start that will try the
 * graphics card first takes a reranker RESIDENT ON THE CARD off it, the way a chat model switch
 * already does (`registerModelIpc`), so `--fit` sizes translation against memory the reranker no
 * longer holds. A reranker on the processor, or not resident, is left alone: suspending it would
 * cost its next ask a cold start and free no graphics memory. The reranker's next ask restarts it
 * on the processor while translation occupies the card (its posture reads `gpuOccupied()`), and
 * on the card again once translation idles out.
 */
export function translationGpuYield(reranker: Reranker | null | undefined): (() => Promise<void>) | undefined {
  if (!reranker?.suspend) return undefined
  return async () => {
    if (reranker.isLoaded?.() !== true || reranker.devicePosture?.() !== 'gpu') return
    await reranker.suspend?.().catch((err: unknown) => {
      log.warn('Reranker sidecar suspend before a translation GPU start failed', {
        error: err instanceof Error ? err.message : String(err)
      })
    })
  }
}

/**
 * Should the issue-#40 `onModelInstalled` refresh replace the current translator slot?
 * True for a NULL slot (the role was unavailable at startup — the original #40 case) and for
 * a `startFailed`-latched instance (BE-7, full-audit 2026-07-10): a latched instance is
 * lazy/dead — construction spawns nothing and no live child exists to orphan — and without
 * replacement a corrupt-GGUF delete-and-re-download repair stayed blocked until an app
 * restart. A LIVE (or merely lazy, non-latched) sidecar is never replaced.
 */
export function shouldReplaceTranslator(current: Translator | null | undefined): boolean {
  return current == null || current.isStartFailed?.() === true
}

/**
 * Build (or re-build) the audio-transcriber slot from the current drive layout, plus WHY it is empty (#527) — the
 * transcriber twin of `composeTranslator` (issue #497). ONE construction shared by `composeServices` (startup) and
 * `refreshTranscriberSlot` (the two mid-session install hooks: `AppContext.onModelInstalled` after a speech-model
 * download, `EngineDownloadManager.onInstalled` after a whisper.cpp engine install), so the call sites can never
 * drift. Cheap + synchronous: construction spawns nothing (the whisper CLI runs per `transcribe()` call). No context
 * window (`includeContextTokens: false`) — the CLI takes none.
 *
 * The reason: the transcriber needs the whisper.cpp engine AND the speech model, and the composer hint, the
 * audio-import failure and the AI Model screen each name the piece that is really missing — including "the engine has
 * no build for this system", where no download can help. Computed here, from the same model resolution, at the same
 * three moments the slot itself is, so the reason can never describe a different drive state than the slot;
 * `getAppStatus` (polled by the shell) only reads it back.
 */
export function composeTranscriberSlot(deps: ComposeTranscriberDeps): {
  transcriber: Transcriber | null
  missing: TranscriberMissing | null
} {
  const isDev = deps.isDev ?? false
  const model = resolveModelByRole(deps.manifestsDir, deps.rootPath, 'transcriber', {
    includeContextTokens: false,
    discovered: deps.discovered
  })
  const transcriber = createSelectedTranscriber({
    rootPath: deps.rootPath,
    isDev,
    model,
    checkModel: startCheckFor(deps.checkModel, model, 'transcriber', deps),
    onSelect: (kind, reason) => log.info('Transcriber backend selected', { kind, reason })
  })
  if (transcriber) return { transcriber, missing: null }
  const missing =
    transcriberMissingReason({
      rootPath: deps.rootPath,
      model,
      isDev,
      engineFetchable: engineFamilyHasHostBuild(deps.bundledManifestsDir, 'whisper_cpp')
    }) ??
    // Both pieces are on the drive, yet nothing was selected (the ladder and this check read
    // the same files, so only a race with a removal lands here): the model is the honest guess.
    'model'
  return { transcriber: null, missing }
}

/**
 * Should a mid-session install refresh replace the current transcriber slot (#497)? ONLY a null
 * slot: the CLI transcriber has no start-failure latch (nothing starts until a transcribe), and a
 * live instance may hold an in-flight whisper child that the lock/quit teardowns reach through
 * `ctx.transcriber` — replacing it would orphan that child from `suspend()`/`stop()`.
 */
function shouldReplaceTranscriber(current: Transcriber | null | undefined): boolean {
  return current == null
}

/**
 * Fill a null `ctx.transcriber` from the current drive layout after a mid-session install
 * (#497): the hook body both install paths share. Returns true when the slot flipped from null
 * to a live transcriber. Re-discovers the manifests (no `discovered`) because the install just
 * CHANGED the drive. NEVER throws: the download manager wraps the whole `onModelInstalled` hook
 * in one swallowing try/catch, so a throw here would silently skip the issue-#40 translator
 * refresh that follows it in `main/index.ts` — a fault is logged and reads as "still
 * unavailable" instead.
 */
export interface TranscriberSlot {
  transcriber?: Transcriber | null
  /** Re-derived on every refresh of a null slot (#527), cleared when the slot fills. */
  transcriberMissing?: TranscriberMissing | null
  /** Only the drive root is read (binary + weight paths resolve against it). */
  paths: Pick<AppContext['paths'], 'rootPath'>
  manifestsDir: AppContext['manifestsDir']
  bundledManifestsDir: AppContext['bundledManifestsDir']
  isDev: AppContext['isDev']
  /** #913: the start check the refreshed transcriber gets, as at startup. Required (#913 code review). */
  checkModel: AppContext['checkModel']
}

export function refreshTranscriberSlot(ctx: TranscriberSlot): boolean {
  try {
    if (!shouldReplaceTranscriber(ctx.transcriber)) return false
    const next = composeTranscriberSlot({
      rootPath: ctx.paths.rootPath,
      manifestsDir: ctx.manifestsDir,
      bundledManifestsDir: ctx.bundledManifestsDir,
      isDev: ctx.isDev,
      checkModel: ctx.checkModel
    })
    // #527: the reason moves with every refresh — an engine install that lands without the model
    // turns "engine" into "model", which the composer hint must say on the next status read.
    ctx.transcriberMissing = next.missing
    if (!next.transcriber) return false
    ctx.transcriber = next.transcriber
    return true
  } catch (err) {
    log.warn('Transcriber refresh after an install failed', { error: String(err) })
    return false
  }
}

/**
 * `AppContext.onModelInstalled`, the hook a completed in-app download runs. Never throws: the download manager
 * swallows the whole hook, so a throw would skip what follows it.
 * - #372: a freshly downloaded weight is a new file — re-arm the chat ladder for this model first.
 * - #497: fill an empty transcriber slot, before the translator refresh (a different slot).
 * - #634 / #913 review S1: re-arm the role that refused, if this model is its (`rearmStartRefusals`: the search
 *   model and the reranker by their id, the images and translation roles by role — an empty translator slot is
 *   filled, issue #40). The role comes from the model's manifest; one no manifest names re-arms by id only.
 */
export function afterModelInstalled(ctx: TranscriberSlot & RearmTargets, modelId: string): void {
  clearModelLoadLatch(modelId)
  refreshTranscriberSlot(ctx)
  const role = findManifestById(ctx.manifestsDir, modelId)?.role ?? 'unknown'
  rearmStartRefusals(ctx, [{ id: modelId, role }])
}

export interface ComposeOcrEngineDeps {
  /** Drive root — the language files live at `<root>/ocr/`. */
  rootPath: string
  /** Developer build: the engine starts `'available'` instead of `'probing'` (#232). */
  isDev?: boolean
  /** Test seam (default: the tesseract.js engine). */
  makeEngine?: OcrSelectionDeps['makeEngine']
}

/**
 * Build (or re-build) JUST the OCR engine selection from the drive's `ocr/` folder — the OCR twin
 * of `composeTranscriberSlot` (#410). ONE construction shared by `composeServices` (startup) and
 * `refreshOcrSlot` (after an in-app install), so the two can never drift. Cheap + synchronous:
 * the tesseract worker starts lazily. A packaged build's engine starts `'probing'` and must be
 * proven with `probeOcrEngine` before `ocrAvailable` may say so (#232).
 */
export function composeOcrEngine(deps: ComposeOcrEngineDeps): OcrEngine | null {
  return createSelectedOcrEngine({
    rootPath: deps.rootPath,
    probeRequired: !(deps.isDev ?? false),
    ...(deps.makeEngine ? { makeEngine: deps.makeEngine } : {}),
    onSelect: (kind, reason) => log.info('OCR backend selected', { kind, reason })
  })
}

/**
 * The packaged-mode OCR execution probe (#232): one bounded worker start (the engine's own start
 * timeout), released on success. Shared by startup (fire-and-forget) and `refreshOcrSlot`
 * (awaited, so the install job can report a definite outcome — #410). Never rejects. Content-free
 * log: outcome, duration, engine id.
 */
export async function probeOcrEngine(engine: OcrEngine): Promise<boolean> {
  const t0 = performance.now()
  try {
    const ok = await engine.probe()
    log.info('OCR execution probe', { ok, ms: Math.round(performance.now() - t0), engine: engine.id })
    return ok
  } catch (err) {
    log.warn('OCR execution probe threw', {
      error: err instanceof Error ? err.message.slice(0, 300) : String(err).slice(0, 300)
    })
    return false
  }
}

/** The slice of the app context `refreshOcrSlot` reads and (for a null slot) writes. */
export interface OcrSlot {
  ocrEngine?: OcrEngine | null
  /** Only the drive root is read (the language files resolve against it). */
  paths: Pick<AppContext['paths'], 'rootPath'>
  isDev: AppContext['isDev']
}

function sameLanguageSet(a: readonly string[], b: readonly string[]): boolean {
  if (a.length !== b.length) return false
  const sortedA = [...a].sort()
  const sortedB = [...b].sort()
  return sortedA.every((lang, i) => lang === sortedB[i])
}

/** `dir` exists but cannot be listed (#687): what `listOcrLanguages` reads as an empty folder. */
function unlistable(dir: string): boolean {
  if (!existsSync(dir)) return false
  try {
    readdirSync(dir)
    return false
  } catch {
    return true
  }
}

/**
 * Re-read the drive's `ocr/` folder after an in-app install and bring the OCR slot up to date
 * without a restart (#410). Every consumer reads `ctx.ocrEngine` per call (the ingestion deps,
 * the doc tasks, preview, status, lock, quit), so one assignment flips them together. Rules:
 *   - NULL slot → compose an engine from the folder and probe it: `'activated'` when it proved it
 *     runs, `'startFailed'` when it could not start, `'unchanged'` when the folder still holds no
 *     language files;
 *   - an engine whose language set equals the folder's and that latched `'unavailable'` → probe
 *     THAT instance again (the worker re-reads the files from disk — `cacheMethod: 'none'`);
 *   - an engine whose language set DIFFERS from the folder's (in practice: it grew) →
 *     `'restartRequired'`. Its languages are fixed at construction, and it is never replaced
 *     mid-session: `stop()` latches permanently, tesseract.js leaves pending jobs hanging on
 *     terminate, and an un-stopped old worker would survive the lock teardown. A folder that lists
 *     no language at all is not a difference — it may just be unreadable right now (#687) — and
 *     falls through to the rules below;
 *   - an available engine with the orientation file on the drive → `'activated'`: the engine looks
 *     for that file at each detection, so a just-installed one is in use without a restart (#538);
 *   - otherwise `'unchanged'`.
 * The probe is awaited, bounded by the engine's own start timeout. NEVER throws: a fault is
 * logged and reads as `'startFailed'`.
 */
export async function refreshOcrSlot(
  ctx: OcrSlot,
  deps: Pick<ComposeOcrEngineDeps, 'makeEngine'> = {}
): Promise<OcrRefreshOutcome> {
  try {
    const rootPath = ctx.paths.rootPath
    const current = ctx.ocrEngine ?? null
    if (current == null) {
      const next = composeOcrEngine({ rootPath, isDev: ctx.isDev, ...deps })
      if (!next) return 'unchanged'
      ctx.ocrEngine = next
      return (await probeOcrEngine(next)) ? 'activated' : 'startFailed'
    }
    const dir = ocrAssetsDir(rootPath)
    const onDisk = listOcrLanguages(dir)
    // #687 (owner call): a folder that exists but cannot be LISTED right now (an antivirus lock, EACCES) says
    // nothing about the language set — `listOcrLanguages` reads it as no files — so a live engine is not told to
    // restart. A folder that lists is compared as before, so language files deleted by hand still read as a change
    // (and an `osd` file left alone never reads as "activated" for an engine with no languages on disk).
    if (!(onDisk.length === 0 && unlistable(dir)) && !sameLanguageSet(current.languages, onDisk)) {
      return 'restartRequired'
    }
    const availability = current.availability()
    if (availability === 'unavailable') {
      return (await probeOcrEngine(current)) ? 'activated' : 'startFailed'
    }
    if (
      availability === 'available' &&
      existsSync(join(ocrAssetsDir(rootPath), `${OCR_ORIENTATION_LANG}.traineddata.gz`))
    ) {
      return 'activated'
    }
    return 'unchanged'
  } catch (err) {
    log.warn('OCR refresh after an install failed', {
      error: err instanceof Error ? err.name : 'unknown'
    })
    return 'startFailed'
  }
}

/**
 * Build the availability-driven services from the drive layout: the embedder (real E5 when
 * its binary + weights are present, else mock so the app launches model-free), and the
 * reranker / transcriber / OCR engine (real when provisioned, else `null` — a mock there
 * would invent an ordering / a transcript / OCR text and silently corrupt answers).
 */
export function composeServices({
  rootPath,
  manifestsDir,
  bundledManifestsDir,
  isDev = false,
  gpu,
  rerankerDevicePosture,
  rerankerRequestCeiling,
  checkModel
}: ComposeServicesArgs): AvailabilityServices {
  // PF-4 (full-audit 2026-07-10): ONE manifest walk + YAML parse serves every role resolution
  // of this composition pass — initBackend runs it synchronously before the window exists, and
  // each `resolveModelByRole` call used to re-walk the dir. Scoped to THIS call, NOT a module
  // cache: the per-action callers (model IPC, `onModelInstalled` → `composeTranslator`)
  // deliberately re-discover so a just-downloaded manifest is never served stale. An unreadable
  // dir reads as "no models" for every role — exactly what each resolver's own catch produced
  // before (the same throw, once per role), minus the redundant re-walks.
  let discovered: DiscoveredManifest[] | undefined
  try {
    discovered = manifestsDir ? discoverManifests(manifestsDir).manifests : undefined
  } catch {
    discovered = []
  }
  const embeddingModel = resolveModelByRole(manifestsDir, rootPath, 'embeddings', { discovered })
  const embedder = createSelectedEmbedder({
    rootPath,
    isDev,
    model: embeddingModel,
    // #913 (d2): hashed before its first start in a workspace — damaged vectors would go into the index.
    checkModel: startCheckFor(checkModel, embeddingModel, 'embeddings', { manifestsDir, discovered }),
    onSelect: (kind, reason) => {
      log.info('Embedder backend selected', { kind, reason })
      // Measurement-run validity check: an ingestion timed against the mock embedder is
      // meaningless, and the fallback is otherwise silent (perf.ts content rules).
      perfMark('embedder_selected', { kind })
    }
  })
  // The retrieval reranker — selected only when binary + reranker GGUF exist (null
  // otherwise; retrieval then keeps today's ordering byte-identical). `rerankerDevicePosture`
  // is consulted by `rerank()` on every call (Wave 8 ruling (b)(Q)); `rerankerRequestCeiling`
  // gates the CPU posture's request size (Wave 8 ruling (b)(G)).
  const rerankerModel = resolveModelByRole(manifestsDir, rootPath, 'reranker', { discovered })
  const reranker = createSelectedReranker({
    rootPath,
    isDev,
    model: rerankerModel,
    checkModel: startCheckFor(checkModel, rerankerModel, 'reranker', { manifestsDir, discovered }),
    onSelect: (kind, reason) => log.info('Reranker backend selected', { kind, reason }),
    devicePosture: rerankerDevicePosture,
    requestCeiling: rerankerRequestCeiling,
    // #474: surfaced the same way translation's GPU fallback is disclosed — a log line here, and
    // the Performance screen's reranker row already reads `devicePosture()`, which reports 'cpu'
    // once this latch is armed.
    onDeviceFallback: (reason) => log.warn('Reranker sidecar fell back to CPU for this session', { reason })
  })
  // The audio transcriber — the whisper.cpp CLI; selected only when binary + GGML weights
  // exist (null otherwise; audio imports fail per-file with copy that names the missing piece,
  // #527). Shares `composeTranscriberSlot` with the #497 post-install re-selection (speech-model
  // download or whisper.cpp engine install) so the call sites can never drift.
  const { transcriber, missing: transcriberMissing } = composeTranscriberSlot({
    rootPath,
    manifestsDir,
    bundledManifestsDir,
    isDev,
    discovered,
    checkModel
  })
  // Local OCR — tesseract.js over the drive's vendored `ocr/` language files; selected
  // only when those exist (null otherwise; photo imports fail per-file and detected scans
  // show the notice without the "Make searchable" offer).
  // A packaged build must prove the worker runs before `ocrAvailable` may say so: the engine
  // starts 'probing' and the main wiring runs `probeOcrEngine` once at startup (#232). Shares
  // `composeOcrEngine` with the #410 post-install refresh so the call sites can never drift.
  const ocrEngine = composeOcrEngine({ rootPath, isDev })
  // The TranslateGemma sidecar (TG wave). Selected only when the llama-server binary + the
  // translation GGUF are present (null otherwise — no mock; translation refuses with the friendly
  // install path at TG-3). Its own lazy `LlamaServer`, --ctx-size from the manifest, no --jinja.
  // Shares `composeTranslator` with the issue-#40 post-download re-selection so the two call
  // sites can never drift.
  const translator = composeTranslator({ rootPath, manifestsDir, isDev, gpu, discovered, checkModel }, reranker)

  return { embedder, reranker, transcriber, transcriberMissing, ocrEngine, translator }
}