Skip to content

AI, fully local on your computer.

1.9 MB
Raw Blame

Architecture — HilbertRaum

This doc is both the architecture overview and the home of the §-numbered design records (with their §-anchor legends): code comments and the other docs cite §N / finding-id anchors that resolve here. The records absorb the earlier audit ledgers and remediation waves; the full original working papers live in git history.

Layout of this file (wayfinding only — nothing below is reordered or renumbered):

  1. Overview & system shape — process model & security, swappable interfaces, storage.
  2. Design records — the bulk of the file: one §-numbered record per subsystem or wave (performance waves, models/chat/ingestion, GPU, i18n, document organization, skills, translation, result tables, test-enforcement seams, image understanding, …). § numbers restart inside every record (standing decision — §N collisions across records are deliberate; resolve a citation via the record named alongside it), and several records end with their own "§-anchor legend" for retired-plan citations.
  3. Audit remediation ledgers §24–§52 — one continuous series interleaved among the records (find one with ### §N <audit name>); each holds a round's finding dispositions.
  4. Data flow (RAG) and the Module ↔ spec map — near the end of the file.
  5. "Original MVP spec — retirement record & §-anchor legend" — at the very END: the resolution table for every spec §N citation in code, tests, manifests, and docs.

Overview

HilbertRaum is an Electron desktop app. It maps the spec's Tauri/Rust design onto TypeScript while preserving the same module boundaries (spec §7) and command surface (spec §9.1), so a future move to Tauri/Rust is a localized swap.

┌──────────────────────────────────────────────────────────────┐
│ Renderer (React, sandboxed)                                    │
│  Screens: Onboarding · Home · Chat · Documents · Images ·      │
│           AI Model · Settings (General/Privacy & data/Diag.)   │
│  No Node / no network access — only window.api (typed bridge)  │
└───────────────▲───────────────────────────────┬──────────────┘
                │ contextBridge (preload)        │ IPC events (streams)
┌───────────────┴───────────────────────────────▼──────────────┐
│ Main process (the "backend")                                   │
│  ipc/        → handlers mirroring spec §9.1                     │
│  services/   (~30 top-level modules + subsystem dirs —          │
│              see Module ↔ spec map below)                        │
│    workspace · db (node:sqlite) · models · runtime/ ·          │
│    chat · ingestion/ · embeddings/ · rag · reranker/ ·         │
│    doctasks/ · analysis/ · collections ·                       │
│    transcriber/ · ocr/ · benchmark · policy · audit ·          │
│    downloads · logging · security/                             │
└──────────┬──────────────────┬────────────────────┬───────────┘
           │ spawn (Phase 10)  │ spawn (Phase 36)    │ files
   ┌───────▼────────┐  ┌───────▼────────┐  ┌─────────▼─────────┐
   │ llama.cpp       │  │ whisper.cpp     │  │ Drive / workspace │
   │ llama-server    │  │ whisper-cli     │  │ models/ workspace/│
   │ 127.0.0.1 only  │  │ per-file spawn  │  │ logs/ config/     │
   └────────────────┘  └────────────────┘  └───────────────────┘

Process model & security

  • Renderer: contextIsolation: true, nodeIntegration: false, sandbox: true. Talks only to the preload bridge.
  • Preload: exposes a single typed window.api object (see src/preload/index.ts). Stays CommonJS even though main ships ESM — Electron only allows ESM preload with sandbox: false, which we never do. See packaging.md "Module format & renderer bundle — design record".
  • Main: owns all file I/O, the database, the model runtime, and the llama.cpp sidecars. Bundled as ESM (out/main/index.mjs).
  • CSP: same-origin only; no remote origins. Applied as both an index.html meta tag and a response header — strict in production, HMR-compatible in dev. In production the pages load from the app's own hilbertraum://app/ scheme, whose handler sets the header on every response, and the session hook (session.webRequest.onHeadersReceived) adds a second copy; the packaged build turns Electron's GrantFileProtocolExtraPrivileges fuse off. See security-model.md and "App scheme hilbertraum://app/ — design record (#560)" below. The packaged binary's other fuses (no ELECTRON_RUN_AS_NODE, no --inspect, no NODE_OPTIONS since #564, app.asar integrity) are in "Electron fuses — design record (#562)".

Swappable interfaces (spec §9.2)

  • ModelRuntime — MockRuntime or LlamaRuntime, chosen per start() by availability (Phase 10).
  • Embedder — MockEmbedder or E5Embedder, chosen by availability (Phase 10).
  • Reranker — LlamaReranker or null, chosen by availability (Phase 21). Deliberately no mock: a mock reranker would invent an ordering; null keeps retrieval byte-identical to the vector-only pipeline.
  • DocumentParser — txt/md/pdf/docx/csv adapters (Phase 4); plus AudioParser (wav/mp3/flac/ogg → whisper.cpp transcript, Phase 36) and ImageParser (png/jpg/jpeg → OCR, Phase 38).
  • VectorIndex — cosine over SQLite-stored vectors (Phase 5) → sqlite-vec/HNSW later; hybridized with an FTS5 keyword pass + RRF in rag.retrieve (Phase 21).
  • VisionAnalyzer — the lazy vision sidecar (services/vision/) or absent: with no vision model the Images screen shows a calm unavailable state. A dedicated multimodal llama-server (own LlamaServer, NOT the chat RuntimeManager) — see "Image understanding — design record".
  • Translator — the lazy TranslateGemma sidecar (services/translation/) or null, chosen by availability (TG wave). Deliberately no mock (a mock would invent a translation). See "Translation sidecar — design record" below.

Storage

node:sqlite — built into the Node bundled by Electron ^43.7.7 (Node 24.x; measured 24.21.0 / SQLite 3.53.4 on the Electron 43.7.7 binary, wave DEP-5). It is loaded via createRequire in services/db.ts because the experimental module is absent from module.builtinModules, which otherwise makes bundlers try to resolve a non-existent sqlite package. One SQLite DB per workspace (workspace/hilbertraum.sqlite) holds the original spec §8 tables (settings, conversations, messages, documents, chunks, embeddings, runtime_events) plus additive tables for document organization (collections, document_collections, conversation_documents), whole-document analysis (tree_nodes, tree_edges, summary_cache, extraction_records), Skills (skills, plus the nullable conversations.active_skill_id + messages.skill_id refs), and the FTS5 virtual tables (chunks_fts, messages_fts). The authoritative schema is services/db.ts. In encrypted mode (Phase 9) the whole DB file is encrypted at rest.

Skills (skills table + the nullable conversations.active_skill_id / messages.skill_id refs) are a derived index over plain folders outside the encrypted workspace (app-skills/ read-only + user-skills/ read-write); the registry, import/lifecycle, prompt integration, the Tier-2 tool gate, the bank-statement tools, and the run UI are consolidated in the "Skills — design record (Phases S2–S12)" below (security model in security-model.md, layout in drive-layout.md).

Performance — design record (perf audit 2026-06-18, Wave P1)

Condensed from docs/performance-audit-2026-06-18.md after Wave P1 shipped (doc-lifecycle rule; the full findings report stays as the audit record). Target that shapes every choice: HilbertRaum runs fully offline from a high-latency portable USB drive on commodity/CPU-only laptops, so fsync/seek I/O and main-thread CPU are the scarce resources. The wins below are constant-factor / batching — no behavior change.

Storage write path (services/db.ts, services/ingestion/index.ts).

  • DB-1 — ingestion writes are transactional. processDocument was the lone batch writer not wrapping its inserts (every other — tree-build, extract, node-vectors, bank/invoice — does). With WAL each bare insert.run() is its own fsync'd auto-commit, and each chunk insert also fires the chunks_fts_ai FTS trigger inside that commit: up to ~3000 fsync'd commits per document. The delete-then-insert chunk phase and the embedding-insert phase are each now one BEGIN…COMMIT (ROLLBACK on throw, the tree-build.ts pattern). The async embedder.embed() await stays outside the transaction (only synchronous inserts go inside — the node-vectors.ts precedent).
  • DB-2 — portable-drive PRAGMAs. After journal_mode=WAL + foreign_keys=ON, openDatabase now also sets synchronous=NORMAL (WAL-safe durability, far fewer fsyncs), busy_timeout=5000 (the concurrent import-vs-chat path waits instead of throwing SQLITE_BUSY), mmap_size=268435456 (256 MB — the vector scan reads BLOBs via mapped pages), cache_size=-16000 (~16 MB page cache), temp_store=MEMORY. These are a data-contract / durability change (NORMAL is the WAL-recommended setting; only the last txn is at risk on OS/power loss, never corruption).
  • DB-4/6/7 — additive indexes (created CREATE INDEX IF NOT EXISTS after ensureColumn, so the migrated category_id column exists): idx_embeddings_model on embeddings(embedding_model_id) (every retrieval + stale-check filters it); idx_extract_type_nv on extraction_records(record_type, normalized_value) (the unscoped "list every date/amount" path the doc-leading idx_extract_doc_type can't serve); idx_documents_status on documents(status); idx_bank_transactions_category on bank_transactions(category_id); idx_messages_conv_kind on messages(conversation_id, kind) (full-audit-2026-06-28 PERF-3 — the per-turn getLatestCheckpoint compaction lookup, WHERE conversation_id=? AND kind='compaction' ORDER BY rowid DESC LIMIT 1, served with no SCAN/temp-B-tree because SQLite auto-appends the rowid; not (…, kind, rowid) — naming rowid in an index is rejected, "no such column: rowid"); idx_summary_cache_created on summary_cache(created_at) (PERF-4 — turns the age-ordered eviction delete into an ordered index scan, replacing a full-table temp-B-tree sort); idx_documents_pending_dest on documents(id) WHERE pending_destination_json IS NOT NULL (#571 — the per-ask read of a chat's unfiled attachments; partial, so it stays proportional to those rows). idx_messages_conversation (conversation_id alone) is retained — it still serves listConversationTurns / the summary-marker lookup, whose rowid>? range + ORDER BY rowid the composite can't satisfy (the non-equality kind!='compaction' blocks the trailing rowid seek). run_id indexes deliberately omitted — run_id is only ever INSERTed, never joined/filtered, so an index would be pure write-amplification on USB; add one alongside the first query that joins on it.
  • DB-3/ING-2 — listDocuments de-N+1'd. The per-row chunk COUNT + per-indexed-row stale-embeddings COUNT+JOIN (up to 1+2N queries, polled at 400 ms during import) are now two grouped queries loaded into Maps (GROUP BY document_id), mirroring the memberships join beside them. Benefits from idx_embeddings_model and the covering idx_chunks_document. Chat & Documents audit 2026-07-07 DB-5 adds an embedded-count early-out: on a mid-import poll where no row is indexed the whole embeddings⋈chunks scan is skipped (no indexed row can be stale) — see the Session-6 record in the doc-organization reliability/perf notes (the document_id count-map cache was declined there).
  • Data-layer hardening (full audit 2026-06-28, Phase 5). Atomicity + a trigger guard + two pinned invariants, all additive (no schema-shape change; indexes IF NOT EXISTS, the FTS trigger drop/recreate the only non-index DDL).
    • REL-4/REL-5 — transactional parity with deleteDocument. deleteConversation (chat.ts) now wraps its two deletes (messages, then conversations — no ON DELETE CASCADE) in one BEGIN…COMMIT with ROLLBACK on throw, so a crash / SQLITE_BUSY past the busy_timeout between them can't leave an orphaned empty thread (compaction checkpoint rows live in messages too). deleteImageSession (vision/history.ts) now deletes the ROW first (in a txn) and shreds the stored image only AFTER — the DATA-1 "never destroy the on-disk copy while the row delete can still fail" ordering, closing the undeletable-ghost-session window. Both run from IPC handlers with no outer transaction (no nested BEGIN), exactly like deleteDocument.
    • DATA-1 — messages_fts_au kind guard + backfill. The UPDATE trigger now guards its INSERT with WHERE new.kind IS NOT 'compaction' (the DELETE stays unconditional, so a plain→compaction content edit still purges the stale FTS row), matching the INSERT trigger. On existing DBs whose au trigger re-indexed updates unconditionally, CODE-4's ensureFtsRowidSync installs the guarded canonical trigger set in the same open (the separate ensureMessagesFtsUpdateKindFilter rewrite it superseded was removed in the 2026-10 chat + RAG test campaign) — so a future in-place edit of a checkpoint row can never leak its summary text into conversation search, on old or new drives.
    • DATA-2 (invariant, no code change). tree_edges.child_id is a polymorphic FK (chunks.id OR tree_nodes.id) with no FK to chunks; the no-dangling-edge invariant holds only because every chunk-delete path also tears down the document's tree_nodes (cascading the edges via parent_id). Pinned on the delete path by data-layer-hardening.test.ts (a deleteDocument leaves no tree edge) and on the re-index path by whole-doc-analysis.test.ts 're-index tears the tree down (stale)…'.
    • DATA-3 (idempotency confirmed, no code change). extract.ts re-extract is idempotent per chunk: the main loop skips a chunk whose __scan__ marker matches the current content hash, and commitChunk deletes the chunk's prior rows before inserting, so a forced re-commit replaces rather than doubles the marker. Pinned by a no-double-count test.

Compare retrieval (services/doctasks/handlers/compare.ts; the run path moved there by DX-1, §38 — the pure window math stays in doctasks/compare.ts).

  • RAG-2/ING-1 — decode doc-B once. Section-matched compare (mode b) ran VectorIndex.search per doc-A chunk, re-issuing the doc-B embeddings query and re-decoding every doc-B vector each time (O(N_A × N_B) redundant decodes + N_A re-scans), then re-fetched doc-B's text per window. Doc-B's (id, text, chunk_index, vector) is now loaded once into a resident array; the ranking runs in memory. Mirrors the alignNodes precedent (doctasks/compare.ts).
  • P1 (full-audit-2026-06-30) — dotProduct + running top-K. The in-memory neighbor scan is now the pure, exported compareNearestNeighbors (doctasks/compare.ts) using dotProduct (stored vectors are L2-normalized → cosine == dot, the same RAG-1 fast path VectorIndex.search uses; ~2× fewer FLOPs)
    • a running top-K instead of a full sort().slice() per A-chunk. Byte-identical selection to the old cosine-sort-slice (equivalence-tested in tests/unit/compare-nearest-neighbors.test.ts); ~2.2× faster on a 1000×1000 compare. See the Phase B note in the Wave-P4 performance record.

Chat runtime (services/runtime/).

  • RT-1 — chat prefill batch. The chat sidecar left --batch-size/--ubatch-size at llama-server's 512 default, chunking prompt prefill (skill fence + RAG excerpts + history) — the dominant time-to-first-token cost (3.5–15 s on CPU, Skills §17). LlamaServerOptions.physicalBatchSize (opt-in, emitted by buildArgs) is set by the chat runtime to min(contextTokens, CHAT_MAX_PHYSICAL_BATCH=2048); the embedder/reranker don't set it (they tune their own batch via extraArgs, the reranker precedent at reranker/llama.ts). Capping at the context never over-allocates — the whole prompt can't exceed n_ctx.

Deferred to later waves (tracked in the audit §6): the import & OCR pipelines (ING-3/5, Wave P3), cache_prompt grounding split (RT-2), and the main-thread linear vector scan / ANN index (RAG-1/RAG-6, Wave P4 — the documented D15 deferral).

Performance — design record (perf audit 2026-06-18, Wave P2)

Renderer responsiveness on the CPU-only target. The chat transcript and the Documents screen were re-doing O(list) work and re-parsing Markdown on a 40 ms / 400 ms cadence, competing with token generation and causing visible jank. All changes are memoization / polling and are behavior-preserving (no visible UI change except less jank) save the one streaming decision noted below.

Chat transcript (renderer/chat/Transcript.tsx, renderer/screens/ChatScreen.tsx).

  • FE-1 — streaming no longer re-parses the whole transcript. Each persisted turn is a memoized MessageBlock (React.memo, keyed by message id) and AssistantMarkdown is itself React.memo'd (keyed by its text), so a ~40 ms streamText flush never re-parses a prior, unchanged message's Markdown. DECISION (revised) — the live answer streams as Markdown via Streamdown. The original O(n²)-per-flush worry that kept the live bubble as PLAIN TEXT is gone: Streamdown splits the buffer into blocks and memoizes each, so a flush re-parses only the final block, and parseIncompleteMarkdown closes dangling **bold**/`code`/fences/links mid-stream so partial syntax formats cleanly instead of flashing raw markers. The live bubble is now .msg-content.md (same prose CSS as a persisted turn) with the stream caret a sibling of the block. The visible text stays non-live (audit L7); StreamAnnouncer still announces sentence-by-sentence. lastAssistantId is useMemo'd (was a per-flush [...messages].reverse().find), and the scroll-to-bottom effect is gated on an atBottomRef so a flush only forces layout + scroll while the user is pinned to the bottom (also addresses the FE-5 scroll-thrash note).
    • Measured (scripts/bench-markdown-flush.mjs, jsdom client render, total stream time as the reply grows 10→80 rich KaTeX blocks): naive full re-parse each flush (memo defeated) is O(n²) — 263ms→14,358ms, 6.8× per-block growth, confirming the original worry was real. Block memoization alone (no parseIncompleteMarkdown) is flat O(n) — 10.5ms→67ms, 0.8× per-block — so closed blocks are genuinely not re-parsed, and the module-level components/plugin references in Transcript.tsx are what keeps that memoization intact (an inline components object would put the live bubble back on the O(n²) curve). The shipped config (memoization + parseIncompleteMarkdown) lands in between — 14.4ms→346ms, 3.0× per-block, super-linear: parseIncompleteMarkdown re-scans the whole growing buffer each flush. Net: ~40× faster than naive at 80 blocks and ~4 ms/flush, comfortably interactive for realistic replies (flushes are rAF/40 ms-throttled and replies are rarely that long). Ceiling + upgrade path: the residual is the whole-buffer parseIncompleteMarkdown scan; if very long single replies ever feel sluggish, gate streaming off past N blocks (a long buffer has few dangling tokens to close, so the anti-flicker benefit is only at the trailing edge) — not done now (YAGNI at current sizes).
  • FE-3 — chat children memoized; stable handler identities. Transcript and ConversationList are React.memo'd. ChatScreen re-renders on every keystroke (input state) + every flush; a useEventCallback (latest-ref) wrapper gives the handlers passed to those children (onCopy/onSave/onTryAgain/onAnswerWithoutSkill, onSelect/onNew/onDelete/onCollapse) constant identities without stale captures, and the teaching emptyState is useMemo'd (keyed on mode/docs, never on input). So a keystroke no longer re-renders the transcript (compounding FE-1) or re-runs groupByProject/groupConversations.
  • FE-4 — conversation rows memoized. ConvRow (React.memo) with stable per-row callbacks, so opening one row's ⋯ menu (which flips the parent menuOpenId) no longer re-renders every row.
  • Full-audit 2026-07-10 PF-1/PF-2/PF-3 — streaming + audit-log hot-path closures. StreamAnnouncer's sentence-boundary scan starts at the previous announce point instead of re-scanning the whole buffer per flush (byte-identical output, oracle-pinned); the live context-meter word count advances incrementally per flushed chunk (exact-equivalence-pinned); the audit-log prune is slack-gated + transactional over idx_runtime_events_created (see the Audit log record).
  • Full-audit 2026-07-10 PF-4/PF-7 — startup discovery + renderer churn sweep. PF-4: composeServices discovers manifests ONCE per composition pass and threads the result into its role resolvers (resolveModelByRole takes an optional pre-discovered list) — the per-action IPC callers and the issue-#40 onModelInstalled refresh still re-discover; deliberately NO stateful module cache, which could serve stale results. #848 amendment: the walk takes each folder's entry names in code-unit order on every OS (it was raw readdirSync order, sorted only on NTFS), and a resolver takes the manifest of its role flagged default_for_role: true first (the committed E5 sets it), present or not, so a second manifest of a role never re-points the embedder, reranker, transcriber or translator by file name. PF-7a: the Home runtime poll keeps the previous state object on a value-unchanged tick (React bails out of the re-render) and stops entirely once the model runs, with a window-focus re-check instead (the ChatScreen poll-while-not-running pattern). PF-7b: the doc-task store's 400 ms poll ports the skillruns sameRun no-change gate (SKA-39 precedent) — an identical tick sets nothing and the snapshot identity stays stable. PF-7c (closes the carried-forward PERF-5, see the 2026-06-30 ledger): visionSession batches token deltas through a 40 ms flush buffer (ChatScreen's STREAM_FLUSH_MS, one constant in lib/polling.ts since #745; settle paths flush first so no token is lost, discard paths drop the buffer), and ImagesScreen got the FE-3 useEventCallback sweep over onCopy/onTryAgain/onStop — a settled TurnRow no longer re-renders while a sibling turn streams (render-count-pinned like the DocRow PERF-5 memo tests). translateSession deliberately stays per-token (~4 tok/s — documented there). PF-7d: ScopePopover memoizes its indexed/addableDocs/collection derivations on [docs, docIds, collections], so the (usually closed) composer-footer popover no longer re-filters the full docs list on every keystroke/stream flush.

Documents screen (renderer/screens/DocumentsScreen.tsx).

  • FE-2 — derivations memoized. The render body — re-run on every 400 ms import poll and every unrelated state change (menu/hover/modal) — did 5+ array passes + a Map build each time. The derived collections, sourcesById, visibleDocs (section filter + recent ordering; inSection is now a pure module helper), anyActive/staleDocs, and the four rail counts (now one bucketing pass) are useMemo'd on [docs]/[collections]/[docs, section].
  • FE-7 — poll the import job, not the whole list. CONTRACT/behavioral note: both import watchers (DocumentsScreen watchJob, ChatScreen watchAttachJob) now read only the small getImportJob status on the 400 ms tick; the full listDocuments (+ attachment) refresh runs when the job's completed + failed count changes (a file finished) and once at completion — the ModelsScreen download-poll pattern. For attachments this is exactly when the FK-guarded conversation_documents link row appears, so the "Files in this chat" reveal is unchanged. Amended by audit 2026-07-16 F-31: DocumentsScreen's completion-triggered refreshes (watchJob + watchReindex) are now COALESCED by a leading-edge-plus-trailing throttle (makeRefreshCoalescer, REFRESH_THROTTLE_MS = 1500) — the first completion refreshes immediately, a burst of rapid completions folds into at most one refresh per 1.5 s window, and the terminal job.done refresh stays immediate. So a rapid small-file bulk import no longer re-derives the whole library ~2.5×/s (it amplified the registered PF-5 load-all during exactly the sessions that grow a library). ChatScreen's watchAttachJob is unchanged (small attach batches; its per-transition refresh is already id-scoped via CODE-21 listAttachments).

Deferred within Wave P2 (lower-confidence under the behavior-preserving mandate; tracked in the audit §6 / §4.4): the remainder of FE-3 (memoizing Composer + moving input state into it — needs the footer's ScopePopover/DepthMenu/SkillPicker handlers stabilized first, a larger refactor); the FE-4 DocRow extraction (a ~25-prop memoized row — high stale-closure surface); and FE-5 list windowing of the transcript + document list (needs a measured approach to preserve scroll-to-bottom + a11y; the cheap scroll-thrash half of FE-5 is already done under FE-1).

Renderer robustness — design record (full audit 2026-06-28, Phase 3)

The renderer was the least-audited surface (prior rounds were backend-only). Phase 3 closes a top-level robustness gap plus a cluster of unhandled-rejection / effect-lifecycle / key / i18n / a11y items. All changes are renderer-only (plus the shared i18n catalogs); no IPC surface, no main-process behavior. The labels below are the audit's FE-1…FE-9 (full-audit-2026-06-28 — distinct from the Wave-P2 perf FE-* record above).

Error boundary (FE-1 — the one High). Before Phase 3 there was no error boundary anywhere, so any screen render throw (e.g. Streamdown on malformed model output, a Radix portal edge) unmounted the whole tree → a blank window with no recovery, in an offline app the user must force-quit. The contract now:

  • Component: renderer/components/ErrorBoundary.tsx — a class component with getDerivedStateFromError + componentDidCatch. It takes a fallback(reset) render-prop and an optional onError sink. Logging is LOCAL-ONLY (CLAUDE.md hard rule: no cloud/telemetry/remote crash reporting): there is no renderer→main log IPC (the preload exposes only the READ-only getLogTail/exportLog), so it logs via console.error — never a network call.
  • Per-screen boundary (App.tsx). AppShell wraps the active screen in an <ErrorBoundary> keyed by screen, so navigating to any other destination re-mounts the subtree and clears a captured error. The boundary is INSIDE <main>, so the nav rail (rendered outside it) stays alive — the user is never trapped. The localized fallback (ScreenErrorFallback, role="alert") offers an in-place Try again (reset) and a Go to Home escape — the latter calls reset() and navigate('home'), since when Home is itself the throwing screen navigate('home') is a same-value no-op (the key never changes), so reset() is what actually clears the boundary.
  • Outer last-resort boundary (main.tsx). Wraps <App/> so a throw ABOVE the per-screen boundary (the gate, the i18n provider, AppShell itself) still shows a localized reload prompt (RootErrorFallback) instead of a blank window. It sits OUTSIDE I18nProvider, so it resolves the pre-unlock language itself (resolvePreUnlockLanguage + the standalone t).
  • New i18n keys (en + de, parity typecheck-enforced): errorBoundary.title/body/retry/home and errorBoundary.app.title/body/reload.

The FE-2…FE-9 cluster.

  • FE-2 (unhandled IPC rejections). ModelsScreen cancel now .catches → friendlyIpcError into the error banner; SkillsTab.pick() moved pickSkillPackage INSIDE its try → a rejecting picker shows the skills.import.failed toast, not an unhandled rejection.
  • FE-3 (skill toggle double-submit). A per-skill in-flight Set (toggling) disables the row Switch while an enable/disable is pending and ignores a second submit for the same skill; refresh() reconciles to the server state in finally. Disable-while-pending over optimistic UI (simpler, robust).
  • FE-4 (setState-after-unmount). The HomeScreen let active guard (or a component mountedRef where the async setState lives in a shared callback/interval) is applied uniformly: the DocumentsScreen import poll (guard checked after each await before any setState), PrivacyTab, DiagnosticsTab refreshers, SkillsTab settings load, and the General tab. (React 18 makes a post-unmount setState a silent no-op, so this is defensive correctness; the DocumentsScreen test has teeth by asserting listDocuments is not re-fetched after unmount.) Extended (full audit 2026-06-29, FE-1): ChatScreen was the remaining FE-4-class gap — its attach-import poll (watchAttachJob) and streamed-token flush (flushStream) both resolve after the user can navigate away mid-import / mid-generation. It now carries the same mountedRef (gating the poll/flush setStates) and clears the pending flush timer on unmount. Hard constraint: the main-side stream is not torn down — it is intentionally recovered on remount via getActiveStream (see "Stream recovery across navigation" below); the fix is guard-only. Teeth: ChatUnmount.test.tsx unmounts with an attach-poll tick in flight and asserts listDocuments is not re-fetched when it resolves. The flush-timer guard has no test: React 18 makes a post-unmount setState a silent no-op, so nothing observable can show it (the chat-ui test campaign removed a warning check that could not fail). Reconciled (full audit 2026-06-29 postmerge, F22 — the "applied uniformly" claim was overstated): two hold-outs remained when this record was written. ModelsScreen's download/engine poll callbacks (setJob + a transitional void refresh()) had no guard, and the DiagnosticsTab loadActivity/loadMoreActivity refreshers — though this bullet listed "DiagnosticsTab refreshers" as covered — guarded only refreshStatus/refreshLogs/the mount effect, not the activity-page setStates. Phase 6 gives ModelsScreen its own mountedRef (guarding refresh() after its await + both poll .thens) and routes the two DiagnosticsTab activity setStates through the existing component mountedRef, so the discipline is now actually uniform across every screen. Teeth: ModelsScreenUnmount.test.tsx (see §32). Sibling renderer lifecycle/a11y fixes landed the same phase: F21 (DictationButton mic-stream released when getUserMedia resolves after unmount — same mountedRef idiom) and F20 (WorkspaceGate per-phase focus management — useEffect([phase])).
  • FE-5 (effect re-run on language change). I18nProvider.applyLanguageSetting is now useCallback([]) (identity-stable; it only needs setLang), so App's policy/settings effect, which lists it in deps, no longer re-fires getPolicy()+getSettings() purely because the UI language changed.
  • FE-6 (unstable keys). ScopePopover pending-attachment chips key by name+index (name-aware so a new import re-mounts a changed slot, index-disambiguated so two cross-folder files with the same base name don't collide on a duplicate key); the ChatScreen optimistic user-message id uses a monotonic counter (not Date.now(), which collides within a millisecond).
  • FE-7 (untracked toast timer). ToastProvider tracks its auto-dismiss setTimeout ids in a ref and clears them in a cleanup effect.
  • FE-8 (raw English in localized copy). DiagnosticsTab benchmark failures route through friendlyIpcError (no transport/Error-class prefix in diag.bench.failed); the literal 'UNKNOWN' is replaced with t('diag.app.unknown').
  • FE-9 (SegmentedControl Home/End). Home/End now select the FIRST/LAST enabled segment directly (moveToEdge), instead of relying on the arrow-key modulo wrap to land there incidentally.

Drag-drop intake (full-audit-2026-06-29 follow-up, Phase 2 — FE-A / FE-C). Chat drag-and-drop attach was silently dead in the shipped app: ChatScreen.pathsFromDrop read (file).path, the non-standard File.path Electron removed in v32 (the app pins ^43.7.7; installed 43.7.7). At runtime .path is undefined, so the loop produced [], attachFiles was never called, and a drop did nothing — no import, no pending chip, no error. It went unnoticed because the only intake test (ChatAttach.test.tsx) fabricated dataTransfer.files = [{ name, path }], injecting a property real Electron doesn't provide → green test, broken product (the round's headline test lesson: never fabricate a platform property the renderer could read directly).

  • FE-A — resolve the path in the PRELOAD. The replacement, webUtils.getPathForFile(file), is only callable from the (sandboxed) preload, never the renderer. A new preload bridge method window.api.getDroppedFilePath(file) (preload/index.ts, next to pickDocuments) wraps it; pathsFromDrop now calls the bridge per dropped File. NOT a new IPC channel — webUtils is synchronous and in-process in the preload, so the resolver is a plain bridge function (no ipcRenderer.invoke, nothing added to shared/ipc.ts); the renderer call site is typed via PreloadApi = typeof api. File objects cross contextBridge to the function; contextIsolation/ sandbox stay intact. Main still re-validates every path (existence + supported extension) on import, so a spoofed value simply fails to import (unchanged trust model). The paperclip picker (pickDocuments → main dialog → real paths) was always unaffected. The Images drop zone reads File bytes (FileReader/arrayBuffer), never File.path, so it needed no change (confirmed).
  • FE-C — no silent zero-path drop. onDrop had no else: a Files-bearing drop resolving to zero importable paths (now any browser-origin drag, and — pre-FE-A — every drop) was indistinguishable from "nothing happened." It now surfaces a friendly banner (chat.attach.dropUnsupported, EN+DE) when a drop carried Files but yielded no path, matching the Images screen's drop feedback.
  • #742 — a busy chat refuses the drag instead of swallowing the drop. While an answer is being written or a file is still being added (attachBusy: the states attachFiles turns a file away in, and the paperclip is disabled / withheld), onDragOver used to show the copy cursor, and the drop then vanished. It now still preventDefaults (left alone, Chromium's navigate-on-drop would try to open the file as a page, which the #560 navigation guard blocks just as silently) but sets dropEffect = 'none' and shows no overlay: the OS shows its no-drop cursor and, per the HTML drag model, a release ends the drag with a dragleave, not a drop. onDrop keeps a busy guard as the backstop. Pinned in ChatAttach.test.tsx ("a file drag is refused while the chat is busy").
  • Tests / verification. ChatAttach.test.tsx now drives the real bridge shape — the dropped File carries no .path and a WeakMap stands in for webUtils' File→path resolution — every drop row drops a path-less File (the empty-composer row also asserts the getDroppedFilePath call, FE-A), plus the FE-C empty-drop banner test; ChatUnmount.test.tsx updated to the same shape; preload-attach.test.ts is the preload-surface contract (resolver exposed + forwards to webUtils.getPathForFile). All are teeth-checked (revert the bridge wiring → red, verified). jsdom can't exercise webUtils, so the unit tests prove the wiring; the real-Electron leg (bridge exposes the resolver in the actual renderer; webUtils.getPathForFile is callable in the sandboxed preload on 37.10.3 (API unchanged in Electron 39 — not in the 38/39 breaking-changes; unchanged again in Electron 43 — absent from every 40–43 breaking-change list, and the packaged E43 preload still exposes the getDroppedFilePath seam, wave DEP-4; typechecks against 43.4.0's electron.d.ts) — a renderer-built File resolves to '' without throwing) was confirmed by launching the built preload under the app's exact webPreferences. A true native OS drag (Explorer → chat) isn't faithfully automatable (a synthetic File has no on-disk path), so the disk→path success leg rests on that availability proof + the wiring tests.

Phase D (full audit 2026-06-30) — renderer lifecycle & a11y (F1–F8). A renderer-only sweep extending the FE-4 mountedRef family; no main-process, IPC, schema, or i18n change (the one banner reuses the existing images.err.busy key). Each fix is independently revertible and the four behavioral ones are teeth-checked (neuter → red → restore). Suite 2673 → 2677 / 41 skipped (+4: F1, F4, F6, F8). Per-finding disposition:

  • F1 (Medium — the one real bug) — DictationButton.stopAndTranscribe() fired onText after unmount, crossing conversations. start() was F21-mountedRef-guarded but the stop path awaited the multi-second transcribeDictation IPC and then unconditionally called onText(text) / onError(...) / setState('idle'). Stop-dictation-then-navigate-away leaked the transcript into whatever composer is now mounted (the parent's mountedRef doesn't gate its setInput). Fix: the same if (!mountedRef.current) return guard before onText/onError and before the finally setState — the IPC completes harmlessly, the dead component is never touched. Test: Dictation.test.tsx resolves transcribeDictation AFTER unmount() → onText/onError not called, no act-warning (mirrors the F21 test). Teeth: drop the guard → red.
  • F2 (Low, perf) — Transcript localized the streaming buffer twice per ~40 ms flush. localizeServerCopy(t, streamText) (an O(n) Map-lookup + two regex .exec over the growing buffer) ran once for the visible bubble and again for <StreamAnnouncer>. Now a single const localizedStream = useMemo(() => localizeServerCopy(t, streamText), [t, streamText]) feeds both — byte-identical, half the work on the CPU-bound path.
  • F3 (Low) — proactive skill-suggestion debounce setState was unguarded. ChatScreen's 400 ms refreshSuggestion resolved suggestSkills then setSkillSuggestion with no mounted/convId check, so a late reply setState'd a dead component or stamped a stale-conversation suggestion. Fix: gate the .then/.catch behind mountedRef.current && (activeIdRef.current ?? '') === convId (reusing the existing FE-1 activeIdRef the stream path already keeps); convId is '' for a still-"new" draft, matching activeId ?? '' at call time.
  • F4 (Low-Med) — ImagesScreen "Try again" was silently dropped while another turn streamed. The per-turn action stayed clickable while analyzing, and analyze() early-returned on activeJobId with no feedback. Fix: thread a busy (= analyzing) prop through AnswerThread→TurnRow and disable "Try again" while busy (mirroring the already-disabled composer; Copy stays live — a harmless read); plus defense-in-depth, analyze() now returns 'started' | 'busy' | 'noop' and runAnalyze surfaces images.err.busy if a click still reaches the busy guard. Disabling on analyzing is stronger than the activeJobId guard — it also covers the create round-trip window before activeJobId is set. Test: with a second analysis in flight, the prior done turn's "Try again" is toBeDisabled(). Teeth: drop disabled={busy} → red.
  • F5 (Low) — DEFERRED (accepted). Composer's auto-grow effect reads scrollHeight/offsetHeight after writing style.height → one synchronous reflow per keystroke. It is a single textarea (the audit itself rates it acceptable); an rAF batch would add a cancelable frame handle + an unmount cancelAnimationFrame and risk a one-frame height-lag jump, for a sub-millisecond, imperceptible cost. Left as-is by design.
  • F6 (Low, a11y) — StreamAnnouncer length-based fallback ADDED. The announcer only advanced on sentence terminators, so a table-/list-/run-on answer with no . ! ? …/newline stayed silent until completion. When the unannounced tail grows past ANNOUNCE_SOFT_CAP (160) with no new terminator, it now flushes up to the last word boundary (lastWordBoundary), holding back the trailing partial word — so AT hears progress incrementally. Accepted residual: a pure code block is stripped to ~nothing by stripMarkdown (voicing code punctuation is worse a11y than silence), so that case stays intentionally quiet; the surrounding prose still announces (recorded in known-limitations Accessibility). Test: a 210-char terminator-less buffer announces complete words and excludes the trailing partial. Teeth: neuter the fallback → region stays empty → red.
  • F7 (Low) — DEFERRED (accepted; self-heals). ChatScreen.onTryAgain optimistically slices the last assistant turn before stream(...). If the IPC throws before the backend mutates, stream's catch already calls refreshIfVisible() → setMessages(await listMessages(convId)) in place when the user stayed on the conversation, restoring the answer from the DB; if they switched away, the activeId-change effect re-reads from the DB on return. So the slice is restored without manual re-select in both cases — the audit's "until a manual re-select" framing predates the catch-path refresh. Deferring avoids weakening the immediate optimistic feedback (recorded in known-limitations).
  • F8 (Low, hypothesis → CONFIRMED reachable, FIXED) — a superseded vision analyze could wire a zombie stream. The busy guard rejects a second analyze() only once activeJobId is set, but that isn't set until AFTER the imageAnalyze create round-trip resolves. A slow round-trip + image-switch + re-analyze (the new image resets analyzing, re-enabling the composer) leaves two analyzes both awaiting imageAnalyze; the slower one would reassign the module-global unsubs over the newer job's (leaking the old listeners), and its own late done/error would then teardownStream() the newer job and null its activeJobId. Fix: each analyze() claims a monotonic analyzeGen (bumped by abortActive/clearVisionSession); after the await a superseded call (myGen !== analyzeGen) cancels its now-orphan job main-side and bails without wiring, and the catch path only touches the turn/flag when still current. Per-handler if (jobId !== snapshot.activeJobId) return checks are belt-and-braces (the gen guard already prevents two jobs' listeners from being live at once). Test (visionSession.test.ts, store-level): a slow A-create resolving after a switch-to-B is cancelled (imageCancel('jobA')) and never wires; B is the live job. Teeth: remove the gen bail → A wires, imageCancel('jobA') never fires → red.

Performance — design record (perf audit 2026-06-18, Wave P3)

Pipeline throughput & latency on the two hottest operations — import a document and ask a question — plus runtime-startup knobs. Unlike P2 (pure memoization), several P3 items are structural (concurrency, prompt layout, runtime flags), so each preserves a stated correctness contract. Condensed from docs/performance-audit-2026-06-18.md §4.2/§4.3/§4.5 after Wave P3 shipped.

Import pipeline (services/ingestion/index.ts, ipc/registerDocsIpc.ts).

  • ING-3 — 1-deep parse/embed pipeline. Import was fully serialized: per file, parse → chunk → embed (sidecar round-trips) → write, each fully awaited, so file N+1's parse (CPU) never overlapped file N's embed (I/O wait). processDocument is now split at the already-DB-mediated chunk↔embed boundary into prepareDocument (setup → parse → chunk → persist chunks, leaving the doc in embedding) and finalizeDocument (embed the persisted chunks → mark indexed); processDocument is their back-to-back composition, so the reindex / OCR re-ingest / materialize callers are behavior-identical. The import loop runs prepareDocument(N+1) while finalizeDocument(N) embeds. The embed sidecar is the single contended resource, so embeds are NEVER parallelized — only the next file's parse overlaps the prior embed. Per-file ImportJobStatus counts, ordering, per-file error isolation (each phase self-captures failure on the row), the DB-1 per-phase transactions, and lock-mid-job are all preserved (the look-ahead is drained + de-registered from processing on a lock break so the post-job reconcile still fires). Transients (decrypted working copies) shred at the end of prepare — the embed phase reads chunk text from the DB, not the files — strictly shortening plaintext lifetime. New data contract: prepareDocument / finalizeDocument / PreparedDocument are exported alongside processDocument.

OCR (services/ocr/pipeline.ts, services/ocr/rasterizer.ts, services/ocr/page-cap.ts).

  • ING-5 — 1-deep render/recognize look-ahead. OCR rendered page N (pdfjs, hidden window) then awaited recognize(N) (WASM tesseract) before rendering N+1 — two different engines run strictly serially. A new pure pipelinePages(pageCount, renderPage, onPage, opts) helper renders page N+1 while page N recognizes, keeping recognitions serial and in order. Memory stays bounded (at most one extra rendered PNG resident); page ordering, progress %, and cancellation are unchanged. The helper is Electron-free so it is unit-testable with fake render/recognize functions.
  • REL-4 — per-page PNG byte cap (backend-audit-2026-06-27). The hidden window caps render dimensions at MAX_RENDER_PIXELS (4096/side), but the encoded PNG it returned over IPC was previously unbounded — unlike the vision subsystem, which enforces VISION_MAX_IMAGE_BYTES. With the 1-deep look-ahead holding up to two page PNGs resident, a crafted PDF rasterising near the worst case across many pages could drive main-process memory. services/ocr/page-cap.ts (assertPageWithinByteCap, OCR_MAX_PAGE_PNG_BYTES, electron-free + unit-tested) now rejects an over-cap page the moment the rasterizer receives it — before it is handed to recognition or held behind the look-ahead — and the OCR task downgrades to a friendly failure. The cap is 96 MiB, sized to the WORST CASE of a legitimate page (a 4096×4096 RGBA bitmap is 64 MiB raw and a near-incompressible scan PNG-encodes to about that), not the vision path's 20 MiB, which would reject real dense color scans; env-overridable via HILBERTRAUM_MAX_OCR_PAGE_BYTES. (The vision vs OCR caps differ on purpose: vision images are arbitrary user files, OCR pages are bounded by the render-dimension cap, so their worst cases — and thus their byte ceilings — differ.)
  • SEC-3 — navigation guard on the hidden window. The rasterizer's worker window renders untrusted PDF bytes; it denies window-open and, via installNavigationGuard(win.webContents, () => false) (services/navigation-guard.ts), all navigation on both will-navigate and will-redirect (see security-model.md — a redirect reaches a remote origin without firing will-navigate).

Grounded-answer prompt (services/rag/index.ts).

  • RT-2 — cacheable grounding prompt (updates §17 (a) to implemented). The stable grounding rules + preface rode in the per-turn USER message, so cache_prompt's longest-common-prefix reuse stopped at BASE_SYSTEM_PROMPT and re-prefilled the whole rules block on every documents turn (the prior user turn is replayed as the RAW question, so the grounded prefix never matched). They now live in a new GROUNDED_SYSTEM_PROMPT (BASE_SYSTEM_PROMPT + the rules); the user turn carries only the per-turn question + excerpts (+ the skill fence, which stays in the user turn as untrusted reference text — never system, skills plan §11.2). ~58 approx tokens of rules now sit in the always-reused system prefix instead of re-prefilling per follow-up. Correctness preserved: precedence is unchanged/strengthened (rules in system ≥ the user turn, still outrank the fence); the [Sn] citation contract and the no-context refusal path are untouched; the skill-fence budget is sized against GROUNDED_SYSTEM_PROMPT so the total fixed-token reserve is unchanged. A test asserts the system prefix is byte-stable across two turns (the precondition for reuse).

Model verification on the chat path (services/models.ts, ipc/registerModelIpc.ts).

  • RT-3 — lazy model hashing. listModels fired on both the Models-screen visit and the workspace gate into Chat, SHA-256-hashing every present multi-GB GGUF on a cold cache (minutes of USB I/O) on the awaited IPC. buildModelList gains an additive onlyVerifyModelId: when present, only that model is hashed on a cold cache; other present weights are reported installed without hashing (display-only) — a live cached hash is still served for free, so a known checksum_failed still surfaces. A cached mismatch on any one file of a multi-file model is enough (#913): a full check stops at the first damaged file, and before, the lazy answer trusted the cache only when every file had an entry, so a vision GGUF the check had just found damaged read installed again on the next visit. Threaded via a new optional lazyVerify arg on the listModels IPC: the WorkspaceGate (chat path) passes true with the active model id. The §7.4 gate is intact — startModelRuntime re-verifies the model it actually launches, and verify-models --strict / assertCommercialDrive still hash fully.
  • RT-3 amendment (#382, 2026-09-08) — the Models screen verifies lazily too. RT-3 left the Models screen on the full pass, and models starts null there, so the WHOLE screen (cards, the star pick, downloads, the engine install) waited behind it. On the #330 slow-drive round trip that was 39.44 GB / 36.73 GiB in 1,529,844 ms = 25.5 min at a mean 25.8 MB/s, strictly sequential — and the 27B alone was 16.8 GB / 648 s, 43 % of the wait, on a box whose ★ pick is the 9B. Because DEFAULT_SETTINGS.activeModelId is null, a fresh workspace auto-starts nothing and Chat has no picker, so this screen is the SOLE route to a first model: the cost was unavoidable and paid before any choice. The screen now passes lazyVerify: true like every other caller, and the full pass moved to an explicit "Check all model files" action beside the lead. Consequences, all accepted:
    • Passive checksum_failed discovery for un-started models is gone. Damage is found when a model is started (the gate hashes), by the per-model "Verify checksum" button, or by the new action. This is the trade the option was chosen for.
    • A workspace whose ACTIVE model is not cached still blocks for that one file. Lazy resolves to onlyVerifyModelId: settings.activeModelId; that is one weight, it matches the gate's own behaviour, and it is rare after this change because the start gate warms the cache.
    • The bar needed a second render site. Its only one was inside the !models branch, which lazy verification now skips, so a "Check all model files" pass would have hashed for minutes with nothing on screen. verifyBar() renders in both places.
    • The pass CAN be cancelled — issue #420, 2026-09-08 (it could not when #382 shipped, and the button copy said so). sha256File now takes an optional AbortSignal, threaded through sha256FileCached → computeInstallState → buildModelList, and a Stop checking button sits beside the bar. See "Cancelling a verification pass (#420)" below for the two traps that made it non-trivial. The §7.4 start gate and the ship-time gates pass no signal and are unchanged; the per-model Verify checksum button is deliberately still uncancellable (one file, and it is the repair action).
    • #108 is unaffected. Under lazy verification a first start hashes its own weight (cacheHit === false), suppressNextModelLoadSample() fires, and an honest checksum sample is recorded from the one file that matters — #382 makes #392's guard unnecessary on the first-run path rather than breaking it.

Sidecars (services/runtime/sidecar.ts, services/embeddings/e5.ts).

  • RT-4 — embedder physical batch. In --embedding mode llama-server forces n_batch = n_ubatch and defaults both to 512, so a 32-input embed request co-decodes ~1 full-length sequence per physical batch. The embedder now sets --batch-size/--ubatch-size to max(ctx, 2048), packing multiple in-context inputs per ubatch (each input ≤ ctx still fits one ubatch — required because mean pooling cannot split a sequence). Mirrors the chat 2048 (RT-1) and the reranker's raise (different reason — one big query+doc sequence). Verified on the pinned b9585 binary (PAID smoke drive): with both flags at 2048 the "n_batch (2048) > n_ubatch (512) … setting n_batch = n_ubatch = 512" downgrade warning does not fire and a multi-input /v1/embeddings request returns correctly.
  • RT-5 — readiness-poll backoff. waitForHealthy polled /health at a fixed 250 ms, so a fast-ready sidecar paid up to a full interval of dead time on every start / model switch. It now starts at 50 ms and doubles each miss up to the configured cap (healthIntervalMs, default 250 ms); the overall timeout budget is unchanged, and a tiny test interval caps the initial too.

Vector search (services/embeddings/index.ts).

  • RAG-1 — dot-product fast path (cheap slice only). Stored vectors and the query vector are both L2-normalized (e5.ts l2normalize; the mock embedder too), so cosine == raw dot product. A new dotProduct helper replaces cosineSimilarity in VectorIndex.search, dropping the two per-row norm accumulators (~2× fewer FLOPs/row); ranking is identical to floating-point tolerance (asserted by a test). The off-main-thread / ANN scan stays Wave P4 (the documented D15 deferral) — this is only the constant-factor slice. (full-audit-2026-06-30 P1 later extended this same dotProduct + running-top-K fast path to the compare pairing — see the Phase B note in the Wave-P4 record below.)

Implemented in Wave P4 (below): the per-query BLOB re-read + re-decode (RAG-1/RAG-6 beyond the dot product). Still deferred from P2: Composer/input move, DocRow extraction, FE-5 windowing.

Performance — design record (perf audit 2026-06-18, Wave P4)

The real fix for the synchronous main-thread vector scan (RAG-1/RAG-6) — the documented MVP deferral D15. Condensed from docs/performance-audit-2026-06-18.md §4.2 after Wave P4 shipped. Stays behind the unchanged VectorIndex.search(queryVector, topK) signature, so rag/index.ts retrieve() and every scope filter are untouched. The sibling scans in analysis/node-vectors.ts (the summary-tree node_vectors table) and doctasks/handlers/compare.ts (compare's one-shot doc-B load) are NOT VectorIndex and are out of scope.

RAG-1 / RAG-6 — process-resident decoded-vector cache (services/embeddings/resident-cache.ts). The scan SELECTed all matching embeddings rows including vector_blob (~150 MB at the heavy 100-doc × 1000-chunk bound) and decodeVector + dotProduct'd every row in one uninterruptible main-process loop — re-reading and re-decoding the same BLOBs on every question. Now every stored vector is decoded once into a process-resident Map<chunkId, Float32Array> (one cache per open Db, WeakMap-keyed). A query keeps the exact same scope-filtered WHERE but projects only chunk_id (no blob read), then looks each vector up in the resident map — zero per-row allocation, zero re-decode. Ranking is byte-identical (same dotProduct, same sort); the dimension-mismatch skip and the truncated-blob skip are preserved (a short blob is excluded at build time, so the chunk is simply absent from the map). The vector ↔ BLOB codec moved to embeddings/codec.ts so the cache can decode without an index ↔ resident-cache import cycle (re-exported from the barrel).

Invalidation contract (the highest-risk surface — a stale buffer silently corrupts ranking). Belt-and-suspenders, three mechanisms (the per-write full rebuild was removed in Phase 5 — see the PERF-1 note below; the original mechanism descriptions are folded into the three bullets):

  • Incremental delta (primary in-band path, PERF-1 / full-audit-2026-06-29 Phase 5; named-delta fast path, F12 / post-merge close-out): invalidateResidentVectors(db, delta?) is called at the three embeddings write sites — ingestion/index.ts finalize-insert + reindex chunk-phase delete + deleteDocument. It MARKS the cache pending (it no longer drops it); the next getResidentVectors RECONCILES. PERF-1 removed the per-write full decode; F12 removed the per-write O(N) id-scan for the in-band paths: each write site now passes the exact chunk_ids it added/removed (the pure-add finalize knows them from its insert; the two delete sites capture them via embeddingChunkIdsForDocument before the delete), so the reconcile drops the named removed ids and decodeVector's only the named added ids by point lookup on the chunk_id PRIMARY KEY — no whole-table scan. A pure-add of K decodes K and reads 0 extra rows. A cheap Map.size === COUNT(*) gate then confirms consistency; a delta-less invalidate(db) (a direct/out-of-band writer — tests, the manual bench), a missed/wrong delta, or a truncated-blob omission falls back to the FULL chunk-id scan (SELECT chunk_id, no decode) — the self-healing path. Both paths key on the UNIQUE chunk_id, so they stay correct when a deleted row's rowid is reused by a re-index (new row → NEW chunk_id → old id out, new id in) — also what closes the one signature blind spot: deleting the single max-rowid row then inserting one row reusing that rowid leaves (count, maxRowid) unchanged, so only the explicit flag (not the signature) can see it. The result is byte-identical to a from-scratch rebuild for every insert/delete/reindex/same-rowid sequence (an in-band write never mutates a vector under a surviving chunk_id; re-index mints fresh ids).
  • Staleness signature (self-healing backstop): a cheap whole-table signature (COUNT(*), MAX(rowid)) is recomputed at the top of every search. If the table changed but NO write went through the explicit hook (a direct SQL / out-of-band writer — e.g. test seeding), the dirty flag is clear yet the signature mismatches → fall back to a FULL REBUILD. MAX(rowid) is O(1) (rightmost btree leaf) and COUNT(*) a fast index count — negligible vs the scan they gate. This is the path that makes a missed/buggy incremental update self-heal on the next query; it is also the cold first build. The COUNT(*) is load-bearing and RETAINED (full-audit-2026-06-30 P6 considered dropping it but DEFERRED): an out-of-band DELETE of a non-max-rowid row leaves MAX(rowid) unchanged, so only COUNT(*) detects it (a tested guarantee). A COUNT-free clean path would need a DB-side counter (a trigger = a schema change).
  • Security (lock): purgeResidentVectors(db) drops the map outright on workspace LOCK (registerWorkspaceIpc, beside the embedder's suspend()). Distinct from invalidate (which only marks dirty): the vectors are derived from chunk text and must not linger in main-process RAM after the vault re-encrypts — a requirement the staleness signature does NOT cover (the table is unchanged on lock). No embedder-switch purge is needed: the cache is per-Db and per-chunk (model-agnostic), the SQL model-id filter scopes results, and unlock reopens the Db → a fresh (empty) cache.

PERF-1 (full-audit-2026-06-29, Phase 5) — per-write rebuild → incremental. The original cache DROPPED the whole map on every embeddings write (each insert/delete/reindex invalidate = caches.delete), so the next query paid a full ~150 MB re-read + ~580 ms re-decode at the 100k bound — and it recurred after every import/re-index/delete (a heavy "import N docs, ask between each" session paid N full rebuilds). The incremental delta above removes that: a mutation now only pays the ids-only scan + a decode of the new rows. F12 (full-audit-2026-06-29-postmerge close-out) then removed the ids-only scan too for the in-band paths — the named delta (above) decodes the new rows by point lookup with no whole-table scan, falling back to the scan only for a delta-less/out-of-band write or a tripped size gate. The off-main-thread worker (P4b) and ANN (P4c) remain the longer-term paths and the linear-scan ANN deferral (D15) is unchanged. Proven in tests/integration/resident-cache-incremental.test.ts: equivalence (incremental map == a from-scratch rebuild byte-for-byte across insert/delete/reindex/same-rowid), the decode-count speedup (K not N, with a purge→full-decode teeth contrast), the same-rowid blind spot (signature unchanged → only the hook catches it), the signature backstop self-heal, and the lock-purge drop; F12 adds the named-delta equivalence (delta == cold rebuild), a no-SELECT chunk_id-scan assertion (the delta path issues no whole-table scan), delta-composition (add-then-delete nets out), and the size-gate self-heal (a wrong/incomplete delta falls back to the full scan, teeth-checked). tests/manual/resident-cache-bench.test.ts adds the reconcile-cost leg (FULL id-scan vs DELTA no-scan).

Measurement — confirmed on the PAID drive (D:, b9585; the "real E5-runtime numbers PENDING" item is now closed). Two legs, because the scan is data-independent (N dot-products of 384-dim Float32 + sort — identical timing for random unit vectors and real E5 outputs); only the cold-build I/O and the query-embed round-trip are real-hardware variables.

  • Scan scaling, DB on the real drive (synthetic vectors). Warm cached scan vs the old decode-every-query path: 13.6 ms vs 22.4 ms @ 5k chunks (1.7×), 52.5 ms vs 63.3 ms @ 10k (1.2×), 164.6 ms vs 225 ms @ 30k (1.4×), 605 ms vs 753 ms @ 100k (1.2×). Cold rebuild (the from-scratch full build — now only on the first build or the out-of-band signature-backstop path; an in-band mutation pays the incremental reconcile instead, Phase 5) 33 ms @ 5k … 1.48 s @ 100k. These track the earlier mock/SSD projection (~14/50/167/ 580 ms) within noise — mmap (DB-2) keeps the cold build off USB cheap, so the drive does not move the numbers.
  • Real E5 vectors, end-to-end on the drive (genuine multilingual-e5-small-q8 outputs from the b9585 sidecar, stored through the production codec, queried via searchText): @2k chunks (a realistic ≤~10-doc corpus) warm scan 5.8 ms, cold build 17.7 ms, full query (E5 embed round-trip + cached scan) 17.8 ms — the query-embed dominates the scan 3.1×; @10k chunks warm scan 73 ms, cold build 317 ms, full query 102 ms (embed still dominates 1.4×). Real-E5 warm-scan timing matches the synthetic table at the same N, confirming data-independence.

The win is the removed per-query BLOB re-read + re-decode (RAG-6 — also a real GC/memory-pressure win the wall-clock under-reports); the residual is now SQLite→JS row marshalling + the dot-product scan + sort, not decode. The measurements live in tests/manual/resident-cache-bench.test.ts (scan scaling, RESIDENT_BENCH_DIR points the DB at the drive) and tests/manual/resident-cache-real.test.ts (real-E5 end-to-end, HILBERTRAUM_RESIDENT_REAL points at the drive root).

Why the worker (P4b) and ANN (P4c) stay DEFERRED — evidence-based (now real-drive confirmed). At realistic MVP corpora (≤10k chunks ≈ ≤10–50 documents) the cached scan is single-digit-to-70 ms on the real drive — fine on the main thread. The measured query path is the proof: at 2k chunks the scan is 5.8 ms and the query-embed round-trip dwarfs it 3.1×; at 10k the scan (73 ms) and embed (29 ms) are comparable, and both are dwarfed by the reranker (seconds) when engaged. So nothing in the realistic range makes the synchronous scan the bottleneck. Only the heavy 100k-chunk upper bound (605 ms on the drive) still blocks — the narrowed remaining D15 cliff.

  • P4b (off-main-thread worker). Genuine fix for the event-loop block at scale, but heavy (SharedArrayBuffer for the vectors, a second read-only DB handle or id-set hand-off, abort/cancel, writer-race avoidance) — all of which must stay offline. Trigger: a representative corpus measures the cached main-thread scan over 100 ms routinely. The resident cache is the substrate a worker would scan via SharedArrayBuffer, so P4a is also P4b's groundwork. When the trigger fires, the P4b design must also cover residency, not just blocking: at the 1M-chunk bound the Float32 vectors are ~1.5 GB (1.8 GB resident with Map overhead), and a worker scan alone does not fix that — only a quantized/disk-resident scheme would (full-audit 2026-07-10 PF-8; no action at realistic corpora ≤~10k chunks).
  • P4c (ANN — sqlite-vec / pure-JS HNSW). sqlite-vec is a native loadable SQLite extension, which is against the no-native-build / portable cross-OS packaging posture that put the embedder in a llama.cpp sidecar rather than onnxruntime-node (D15's reasoning). Not adopted; a pure-JS HNSW would be reconsidered only if a linear scan over the resident buffer (even off-thread) still bites.

Phase B (full-audit-2026-06-30, P1 + P2) — the residual row-marshal + the compare quadratic, both behavior-preserving (equivalence-tested, teeth-checked). No schema/IPC/audit-payload change.

  • P2 — resident-map iteration on the unscoped path (embeddings/index.ts). The PERF-1/F12 cache killed the per-query BLOB read, but the scan still ran SELECT chunk_id FROM embeddings WHERE … and materialized one JS row object per in-scope chunk before the dot-product loop. VectorIndex.search now splits into collectResidentHits (fast) and collectScopedHits (the unchanged scoped SQL scan), sharing the determinism sort. When there is no document/collection scope AND the archived exclusion removes nothing, the fast path iterates the resident map directly (no SELECT chunk_id, no transient rows). Two equivalence subtleties are handled exactly: (1) the resident map holds chunks under all model ids (a transient mock→real migration mix), so the cache now also keeps a modelByChunk map (chunkId → embedding_model_id, same key set as byChunk, maintained in build + both reconcile paths) and the fast path replicates WHERE embedding_model_id = ? in memory; (2) archiving keeps embeddings, so archived chunks are resident — the gate canIterateResident() takes the fast path only when there is no scope union AND (includeArchived OR no archived docs exist, a cheap documents-table probe), else the scoped scan runs byte-unchanged. Result is byte-identical to the scoped scan over the same universe (tests/integration/vector-search-resident-iteration.test.ts: unscoped == all-docs-scoped, hit-for-hit; a db.prepare spy confirms the marshal is gone). Measured ~5× / query at 10k–50k chunks (env-gated tests/manual/phaseB-perf-bench.test.ts, RUN_PHASEB_BENCH=1; never runs in CI).
  • P1 — dotProduct + running top-K in the compare pairing (doctasks/compare.ts). Section-matched compare (mode b) scored every doc-B vector with cosineSimilarity + a full per-A-chunk sort().slice(topK) — O(N_A·N_B·dim) + N_A sorts, a multi-second main-thread freeze at ~1000 chunks/ side. The inline nearestB is now the pure, exported compareNearestNeighbors using dotProduct (the same RAG-1 unit-vector fast path VectorIndex uses — stored vectors are L2-normalized, so cosine == dot) + a running top-K (descending score, ties broken by doc-B chunk_index order). The running top-K is byte-identical to a stable dot-sort + slice; on normalized vectors the dot ranking equals the old cosine ranking (tests/unit/compare-nearest-neighbors.test.ts: the running top-K equals a dot-sort-slice, and the full helper equals the old cosine-sort-slice — so dot ranks like cosine here). Measured 2.2× on a synthetic 1000×1000 compare. Mode-(c) alignNodes (node-vector cosine) is out of scope and unchanged.
  • P6 — DEFERRED (the companion). Dropping the per-search (COUNT(*), MAX(rowid)) staleness signature to a MAX(rowid)-only backstop would let an out-of-band DELETE of a non-max-rowid row go undetected (a tested guarantee — resident-cache.test.ts "reflects a direct DELETE"); a safe O(1) row-count that survives out-of-band writes needs a DB-side counter (a trigger = a schema change). So the COUNT(*) is RETAINED. See the audit report's P6 disposition.

Performance — design record (perf audit 2026-06-18, Wave P5)

Three remaining Medium findings on hot/felt paths, all bounded and behavior-preserving. Condensed from docs/performance-audit-2026-06-18.md §4 after Wave P5 shipped (doc-lifecycle rule).

Hot-path prepared statements (services/db.ts, chat.ts, collections.ts, ingestion/index.ts).

  • DB-5 — cache compiled statements per connection. node:sqlite re-parses AND re-plans the SQL text on every db.prepare(), and the hottest per-chat-turn read/write paths re-compiled the same STATIC SQL each call. A new prepareCached(db, sql) (a module-level WeakMap<Db, Map<sql, Stmt>>) compiles each distinct SQL string once per connection and reuses the StatementSync; the WeakMap lets the statements GC with their Db (no leak across encrypted-workspace open/close). Routed through it: chat.ts listMessages / appendMessage (insert + the updated_at bump) / getConversation / listConversations; collections.ts resolveScope (the scope-row select + the attachments select, ~2×/turn); the four listDocuments DB-3 grouped-counter prepares. HARD CONSTRAINT: only CONSTANT-SQL callers use it — any prepare built with a dynamic IN (?, …) arity (or otherwise per-call-varying text) stays on db.prepare(), since caching those would leak unbounded entries and/or bind the wrong arity. Results and ordering are unchanged; a unit test asserts statement-object reuse for identical SQL, distinctness for different SQL, per-Db isolation, and unchanged results across reuse.

Import selection walk (services/ingestion/index.ts).

  • ING-4 — halve the walk's syscalls. expandPaths walked the picked tree with readdirSync(dir) plus a statSync per entry, and the tree is walked twice (the preflight IPC summarizeImportPaths, then again on import via expandPathsWithSource). On USB each statSync is a real seek on the synchronous event loop. walk() now uses readdirSync(dir, { withFileTypes: true }), so directory-vs-file is known from the readdir syscall itself — one syscall/entry instead of two. Symlink subtlety (behavior-preserving): a Dirent does NOT follow symlinks (it reports isSymbolicLink(), never isDirectory()/isFile()), whereas the old statSync DID — a symlink to a dir was walked, a symlink to a supported file added (intentional, audit L3/L5). So only plain dirs/files take the cheap Dirent path; a symlink (or any special entry) falls back to statSync(full), reproducing the exact link-following expansion set. Tests prove a dir-symlink is still walked and a file-symlink still added (skipped where the OS denies symlink creation, e.g. Windows without the privilege). Symlink-cycle guard (backend audit 2026-06-27, REL-9): the link-following fallback above could recurse forever on a self-referential tree (a/loop -> ..), so walk() now tracks the realpathSync of every directory on the current recursion path in a Set and skips a directory whose real path is already an ancestor. This terminates the cycle while keeping every acyclic walk's expansion set byte-identical (a symlink to a distinct directory is not an ancestor → still followed). Teeth: a junction cycle re-adds the same file 64× without the guard, exactly once with it. SKIPPED — the optional cross-call cache (reuse the preflight's expansion on import to avoid the second walk): preflight and import are separate IPC calls and the filesystem can change between them, so a cross-call cache carries a real staleness risk for a modest gain; the per-walk syscall win is the safe, unconditional part.

Document preview pagination (shared/types.ts + ipc.ts, ingestion/index.ts, ipc/registerDocsIpc.ts, preload, DocumentsScreen.tsx).

  • FE-6 — paginate the preview. The preview returned the whole extracted document as one IPC payload and mounted every segment synchronously (a large PDF/transcript crossed the bridge as one giant JSON blob and hitched the modal). DocumentPreview gains OPTIONAL totalSegments + nextOffset; absent ⇒ the payload is the whole document (so internal consumers and old mocks are unaffected). A new service wrapper extractDocumentPreviewPage(offset, limit) (DEFAULT_PREVIEW_PAGE_SIZE = 50) slices the UNCHANGED extractDocumentPreview and sets the cursor; previewDocument now returns the first page and a new previewDocumentPage IPC serves the rest. #681: the renderer supplies offset and limit, so main clamps both: a page holds 1–50 segments (the size the app asks for), and a non-finite value takes the default (offset 0, limit 50), never an empty page. The modal accumulates pages behind a "Show more" control + a "Showing X of N" hint. HARD CONSTRAINT preserved: the internal full-text consumers — registerSkillsIpc, doctasks/manager (compare/translate), registerRagIpc — keep calling extractDocumentPreview and get ALL segments (their tests pass unchanged). TRADE-OFF: there is no partial parse, so each page re-extracts + slices; the common single-glance case is strictly better (same one parse, tiny payload), and only reading a huge doc page-by-page re-parses per "Show more" — bounded to one parse per interaction (what the old code paid up front). requireNotProcessing
    • deterministic parse keep totalSegments/slices stable across page calls.
  • Preview cap stack (backend audit 2026-06-27, REL-5 / MAINT-4). The preview re-parse formerly threaded none of the ingest cap stack (only maxPages, and only in layout mode), so a pathological but already-indexed file (e.g. a 4000-page PDF) could wedge the main process on a "Show more" where import would have killed it. Both extractDocumentPreview and extractDocumentPreviewPage now route the re-parse through the single parseWithLimits(parser, source, ctx, limits) decorator shared with the ingest path (prepareDocument) — the ONE cap-enforcement point (MAINT-4). It injects maxPages + maxInflatedBytes from the resolved IngestionLimits and applies the wall-clock parse timeout (audio exempt — its signal + the transcriber watchdog bound it instead); the byte ceiling stays the ingest path's pre-selection stat (the preview reads the already-import-capped stored copy). The ingest path is byte-for-byte unchanged (the decorator injects the same caps it set inline before). The caps resolve through resolveIngestionLimits() on every call (env-overridable); tests dial them down through the same HILBERTRAUM_* variables.

Deferred with explicit, unmet triggers (recorded, not built): P4b worker/SharedArrayBuffer scan (trigger: cached main-thread scan >100 ms routinely; measured ≤70 ms @10k chunks), P4c ANN/sqlite-vec (rejected — native loadable extension vs the no-native-build posture, D15), and the behavior-sensitive renderer items FE-5 list windowing / FE-3 Composer-input move / FE-4 DocRow extraction.

Performance — design record (perf audit 2026-06-18, Wave P6 — Low backlog)

The opportunistic Low findings, resolved as a closing wave (branch performance-low-backlog). All are behavior-preserving internal optimizations — no change to ranking, query results, parse output, or visible UX. This section folds in the audit's §4 Low items and retires the audit report (docs/performance-audit-2026-06-18.md deleted; the High/Medium records already live in the Wave P1–P5 sections above, the full original stays in git history). The deferred-with-trigger items (P4b/P4c/FE-3/ FE-4/FE-5) are unchanged — see Wave P4/P5 above.

Shipped (✅):

  • DB-8 — project columns on the targeted document getters (ingestion/index.ts). getDocumentSummary and getDocumentOcrPages now SELECT only the one TEXT column each needs instead of the shared getRow SELECT *, so a summary/OCR read no longer also deserializes the potentially large ocr_json. Output identical (same parseSummary/parseOcr). (A third getter, getDocumentOrigin, had no production caller and was removed in the 2026-10 documents test campaign; provenance is read through getDocument/listDocuments' origin.)
  • RAG-5 — per-embedder query-vector LRU (embeddings/index.ts). searchText serves the query embedding from a small LRU (QUERY_VECTOR_CACHE_MAX = 32) in a WeakMap keyed by embedder INSTANCE, so re-asking / "try again" / the re-index honesty re-check skip the embed round-trip that DOMINATES the scan at realistic corpora (Wave P4 measurement). Keyed by the EXACT query string (no lossy normalization ⇒ a hit returns precisely the embedder's vector — byte-identical results); a model swap is a new embedder instance ⇒ a fresh empty cache ("cleared on embedder change"). Tested: one embed per repeated query, cache shared across VectorIndex instances over one embedder, fresh per new embedder.
  • RAG-7 — read persisted token counts; memoize message tokens (rag/index.ts, chat.ts). The retrieval budget loop reads chunks.token_count (which IS approxTokenCount(text) by construction in the chunker, with a recompute fallback for a legacy NULL) instead of re-scanning each candidate's text; carried in a side Map<chunkId> so it never rides the returned RetrievedChunk shape. messageTokens is memoized by message-object identity (WeakMap) — a pure function of m.content, summed repeatedly per turn (fitMessagesToContext then getConversationContextUsage). Both byte-identical.
  • ING-6 — flagged, not rewritten (doctasks/handlers/shared.ts; moved there by DX-1, §38). The materializeDocument write-temp → re-parse → re-embed round-trip is DELIBERATE (it reuses the canonical import path for encryption, FTS, citations, and the crash-safe queue-time provenance stamp); documented in a comment so it is not mistaken for an oversight.
  • ING-7 — coalesce the re-index status read/write (ingestion/index.ts). The chunk-replace transaction read tree_status then extract_status (two SELECTs) and reset each in its own UPDATE; now one SELECT of both + one combined UPDATE (four statements → two). The other audit-cited per-doc reads in doctasks/manager.ts were already single multi-column SELECTs — left as-is.
  • ING-8 — async OCR PDF read (doctasks/handlers/ocr.ts; moved there by DX-1, §38). readStoredPdfBytes now uses await readFile (node:fs/promises) instead of a blocking readFileSync on a PDF up to ~1 GiB, so the bytes stream off the main event loop; the method became async and its single runOcr caller awaits it.
  • ING-9 — coalesceSegments joins once (ingestion/chunker.ts). Each merged page/section group accumulates its parts in a string[] and join('\n\n')s once at group end, replacing the prev.text = prev.text + '\n\n' + … accumulate-by-concat (O(total chars) realloc per group).
  • ING-10 — per-word token fast path (ingestion/chunker.ts). atomize uses a new wordTokenCount: a whitespace-free word with no space-less-script char is exactly one token group (len <= ONE_TOKEN_WORD_CHARS ? 1 : ceil(len / CHARS_PER_TOKEN)), skipping approxTokenCount's replace() + split() passes; mixed-script words fall back to the full counter. Byte-identical.
  • FE-8 — resolve the previewed doc once; titles via the Map (DocumentsScreen.tsx). A useMemo'd previewDoc (from the existing sourcesById Map) replaces six linear docs.find scans across the PreviewModal props, and titleOf routes through sourcesById instead of a per-provenance-line find.
  • FE-10 — narrow the runnable-tools effect deps (ChatScreen.tsx). listRunnableTools derives its result from the skill + the conversation's in-scope documents, NOT the message count, so the effect now keys on [currentSkillId, activeId] only; the old messages.length dep just re-fired the IPC after every turn for an identical answer (the new-conversation transition is already covered by activeId).
  • RAG-8 — noted, not changed (doctasks/compare.ts). alignNodes' O(|A|×|B|) cosine product is over level-1 summary sections (tens) with pre-decoded vectors; a comment records the per-A top-K cap to add only if the tree's branching factor is ever lowered enough for section counts to grow.

Accepted residuals (deferred with reason, not built):

  • DB-8 (listDocuments ocr_json). The document list's OCR badge needs pageCount/languages/ engineId, which live ONLY inside ocr_json, and the list's summary preview needs summary_json — both large TEXT. Dropping the read requires either a schema migration with backfill (a behavior-risk for existing-data badges, beyond a Low fix) or duplicating parseOcr's malformed-page validation in SQL JSON functions (not byte-identical). The disk page is read either way; only the targeted-getter projections are safely shippable now.
  • FE-9 (single chat-bootstrap IPC / shared list cache). Post-DB-3 listDocuments is cheap, so the per-screen mount fetch is a minor cost; a cross-screen shared cache risks showing a stale list (each screen deliberately re-fetches on its own events) and a batched getChatBootstrap IPC is a non-trivial new IPC surface (channel + preload + handler + types + tests) for a marginal saving. Revisit if mount latency is ever felt.
  • RT-6 (n_threads = cores/2). Reasonable default; tuning (physical cores for chat, a smaller budget for the CPU-pinned embedder/reranker) needs measurement on representative hybrid hardware first, and an over-eager bump risks oversubscription when ingesting while chatting (three CPU-pinned sidecars).
  • RT-7 (KV cache lost on GPU→CPU fallback). A full cold prefill after a mid-session GPU crash is bounded to one event; --slot-save-path + restore is real complexity/disk weighed against a rare path. Accepted residual for v1.
  • RT-8 (first-run benchmark token-probe steal). Was mitigated by startup ordering (the benchmark fired before maybeAutoStartActiveModel, so runtime.active() was null and the 64-token probe skipped at first-run). Since PR #303 P7 that order is deliberately the REVERSE — the automatic measurement is scheduled behind the auto-start's settlement (benchmark.md "Scheduling behind the auto-start"), so on a machine with an active model the probe DOES run, on the freshly started runtime. The steal stays bounded: the #185 busy check at the probe skips the leg when a chat is already in flight or a model start is (#393), a probe that becomes contended mid-stream is discarded, the probe is capped at 64 tokens, and SD2 allows one automatic attempt per unlock session. A precise in-flight gate still needs a streaming signal not cheaply available here.
  • RT-9 (§17(b) fixed user-turn fence reserve). The cache_prompt prefix-reuse win is LATENT — no shipped skill trims its fence, so the current live-final-turn term never actually shifts the fence text — while switching to a fixed reserve changes the fence-SIZING formula, a prompt-assembly change that could alter the fence (and thus the output) for a near-budget skill. Disallowed under the behavior-preserving mandate; revisit when a trimming skill ships (§17).
  • FE-3 / FE-5 (renderer tail). DocRow extraction LANDED in the full-audit-2026-06-28 Phase 7 (PERF-5 Part A): a module-level memo(DocRow) fed PER-ROW BOOLEANS (selected/menuOpen) and a parent-narrowed rowTask (+ a stable anyTaskActive boolean), so a 400 ms task-progress tick — or opening one row's ⋯ menu, or toggling another row's selection — re-renders ONLY the targeted row, not the whole list. The latest-ref useEventCallback was extracted to a shared renderer/lib/ module and feeds stable handlers; render-count tests pin the win (teeth: dropping memo, or passing the whole selected Set / menuOpenId string, re-renders every row). PERF-5 Part B (list windowing) — DOCUMENTS LIST now DONE (full-audit-2026-06-29 follow-up Phase 4 / PERF-2; see §36): the documents list is windowed with @tanstack/react-virtual, so its DOM + per-row Radix DropdownMenu.Root count no longer grows linearly with library size. The chat transcript half stays deferred as genuinely behavior-sensitive (variable-height messages + scroll-to-bottom + find-in-page + StreamAnnouncer); it remains the tracked top renderer item. The Composer-input move (needs footer handler stabilization first) also stays deferred.

Models & runtime (Phase 2)

  • Manifests are local YAML under model-manifests/ (committed; weights are not). The schema + validator live in src/shared/manifest.ts so renderer and main share one definition. YAML is parsed with the pure-JS yaml package in the main process only.
  • services/models.ts discovers manifests (recursively), validates them, and computes each model's state (unsupported → missing → checksum_failed → installed, with running overlaid for the active runtime). local_path is resolved relative to the drive root, so weights live at <root>/models/.... SHA-256 is streamed (large GGUFs never fully buffer). Placeholder hashes are treated as installed only in developer mode; otherwise they fail the §7.4 verification gate.
  • Checksum cache (two tiers). Hashing a multi-GB GGUF takes minutes of USB I/O, so verified hashes are cached by (path, size, mtime): an in-memory map (L1, keyed by absolute path) plus the persisted AppSettings.checksumCache (L2, injected as a HashStore), so an unchanged weight file is hashed once ever, not once per session. The L2 store keys by the drive-relative path (forward slashes — CODE-15, full-audit 2026-07-11) so moving the drive between machines (a new drive letter / mount point) re-hashes nothing; pre-CODE-15 absolute-key entries are lazily migrated on read/write. A size/mtime change re-hashes; the AI Model screen's Verify checksum button calls the verifyModel IPC, which drops the cache entry and re-hashes for real. The ship-time gates (verify-models --strict, assertCommercialDrive) always hash fully.
  • Model verification progress (first-run bar). The first cold pass over a fresh drive hashes the multi-GB weights — minutes of I/O behind what used to be an opaque spinner. buildModelList now takes an optional onProgress(p: ModelVerifyProgress) sink: a cheap pre-pass (statSync + cache lookup, no hashing) sums the bytes of only the files that will actually hash (cached / missing / placeholder-hash weights excluded) into overallBytesTotal, then sha256File streams a running byte count (throttled to one callback per 64 MB, plus a final exact-total flush) that the loop re-weights into the overall total and a 1-based modelIndex / modelCount step label. A terminal done event settles the bar to 100%. overallBytesTotal === 0 (everything cached — the common 2nd-run case) ⇒ no events, no bar. The listModels handler forwards the sink to the calling renderer over EVENTS.modelVerifyProgress via event.sender (guarded by isDestroyed()); the renderer subscribes through api.onModelVerifyProgress. Surfaces: the first-run WorkspaceGate finishing step and the first cold AI Model screen visit render the shared Progress bar (byte-weighted %, "Checking model N of M") in place of the spinner; both keep their existing fallbacks (the gate's Skip + never-trap catch, the screen's calm "Checking…" hint). Each pass carries a runId: listModels can run as overlapping passes (a screen remount, the download poll), each with a different modelCount as the cache warms, and the events broadcast to the renderer — so the renderer locks onto the first runId it sees and ignores the others until that pass's done (without this the bar flips between e.g. "1 of 1" and "2 of 2"). Since #420 the id is minted by the renderer when it supplies one (listModels(lazyVerify, verifyRunId)) and is then also the cancel handle; main still mints a randomUUID for every other caller. A cancelled pass still emits its terminal done, so the bar settles rather than lingering. Additive behind the locked listModels contract; omitting the sink is zero-overhead, so tests/legacy callers are unchanged.
  • Cancelling a verification pass (#420, 2026-09-08) — design record. The full "Check all model files" pass is a ~25-minute operation on the #330 slow drive (39.44 GB at a mean 25.8 MB/s) that the user starts deliberately, so it must be stoppable. Before #382 the uncancellable pass was an accidental block; after #382 it was a user-facing defect. Only the display-side passes are cancellable — the §7.4 start gate, the per-model verifyModel and the ship-time gates pass no signal and hash to the end, by construction rather than by convention.
    • The handle. The renderer mints the run id (crypto.randomUUID) BEFORE calling listModels, and models:cancelVerify takes it. The obvious alternative — main's own ModelVerifyProgress.runId — leaves two holes: the id only reaches the renderer on the first progress event (seconds of hashing later), and no event fires at all when overallBytesTotal === 0. Both are precisely the windows a user clicks Cancel in. The change to listModels is one optional trailing argument, so the three screens on that locked contract are untouched. Main keys an AbortController registry (verifyRuns) by that id — the inFlightStreams pattern, with one cancelVerify handler playing chat:stop. Like stopRuntime the handler is not gated on an unlocked workspace: it only stops work already running and touches no database.
    • Trap 1 — a naive abort would HANG, not stop. sha256File attaches only error and end. A bare stream.destroy() emits close and neither of those, so the returned promise would never settle and every awaiting caller — computeInstallState, buildModelList, the IPC handler, the renderer's busy flag — would park forever. The abort therefore destroys the stream with an error (HashAbortedError), an already-aborted signal rejects without opening the file, and a close handler settles anything that still reaches it. Pinned by tests that assert the promise rejects, not merely that hashing stopped. Since #1033 that close handler settles every unaborted hash: the digest is taken at end but handed over only once the stream has closed the file (it closes it after end, on libuv's thread pool), and a close that fails after a complete read still resolves the digest, as before. An unaborted hash that resolves therefore means the file is released, so a caller may rename the file's folder right away; Windows refuses that rename while a file inside is open (EPERM). Measured with a busy thread pool: 1,000 of 1,000 such renames refused before, none after (sha256-file-close.test.ts). An abort once the whole file is read (from the final progress call, which fires inside end, as a cancel between two weights does) stops nothing and does not wait for the close: it resolves the digest at once, as before #1033, so a saturated pool never holds a cancel, and the shared read (sha256FileCached) caches that digest before its last waiter's cancel returns. A caller that comes next finds it cached instead of starting a second full read.
    • Trap 2 — single-flight sharing (the sharp one). inFlightHashes (#106) makes concurrent callers of the same path share ONE physical read; it exists precisely because the unlock auto-start races a Models-screen pass over the same weight. A signal wired naively into the leader would abort every joiner, so a cancelled display pass could kill the start gate's hash. The rule, refcounted: each waiter holds a token; a waiter's own abort settles that waiter at once (its loop stops immediately) but the shared read continues, and the physical read is aborted only when the last token is dropped. A caller with no signal holds a token it never drops, so it can never be collateral damage. Both interleavings are tested (gate joins the screen's hash → screen cancels → gate still resolves; and the reverse).
    • Cancellation reaches the LOOPS, not only the stream. buildModelList and computeInstallState both check the signal, so a cancel between two multi-GB weights takes effect before the next file is opened rather than after the current one finishes. The two back each other up: the first takes the signal to the second, so either check alone stops the pass.
    • A cancelled pass is a calm result, never an error. buildModelList catches the abort and reports the model it was on — and every model after it — without hashing, which is exactly what RT-3 lazy verification reports for a present weight. The returned list stays complete and honest: what finished is verified from the cache, the rest is simply unchecked, the §7.4 gate still re-verifies the chat model the user launches (the other roles refuse a file a check found damaged, #913), and no error banner is shown. Nothing is half-written: checksumCacheStats.computed, the L1/L2 cache entry, the #108 read sample and #392's checksumWarmedPaths mark are all written only by a hash that completed.
    • Navigating away. The pass runs in main and still survives leaving the screen — but the Models screen now remembers it in module state (the rememberedJob pattern), so a revisit re-draws the bar and can still stop it, instead of showing an idle screen while minutes of hashing carry on. The memory is cleared by the pass's own finally, which runs whether or not the screen is still mounted.
    • The gate's Skip is unchanged. WorkspaceGate's lazy pass hashes at most the ACTIVE model since #382 — one file, the very one the start gate would hash moments later — so making Skip abort it would only force the same read to happen twice.
    • Accepted residual. A partially-read file IS partly page-cache-warm yet carries no checksumWarmedPaths mark, so a later model-load window over it can sample a partly-warm read. Bounded (the figure lands between the two honest ones) and rare; recorded in known-limitations.md.
  • Recommendation is RAM-best-fit (post-MVP). recommendModelIdByRam(manifests, ramGb) picks the LARGEST model whose comfortable RAM (recommended_ram_gb) fits this machine; if nothing fits comfortably, the lightest model meeting its minimum; else none. Used by listModels (live machineRamGb() = totalmem rounded to whole GB) and by the benchmark (same rounding, so the two surfaces always agree). The legacy recommended_profiles lookup remains the benchmark's fallback when RAM is unknown. 2026-09-06 amendment (PR #308 audit): on a machine with a usable discrete graphics card (and graphics acceleration not switched off), recommendChatModelId dispatches instead to recommendModelIdByVram (services/models.ts), which judges fit against the budget device's free graphics memory rather than RAM, RAM still a hard floor, otherwise reusing the same rank tiebreak — see docs/model-benchmarks.md §6.6.
  • RAM gate (post-MVP). buildModelList flags insufficientRam on models whose recommended_min_ram_gb exceeds the machine RAM; the AI Model screen disables Select/Start and shows a "Needs ≥N GB RAM" badge, and startModelRuntime refuses to load installed weights that don't fit (friendly §11.4 copy — the zero-weights mock fallback is not gated). Rounding is Math.round, so a "16 GB" machine reporting 15.9 GiB still counts as 16.
  • services/runtime/ defines the ModelRuntime interface and a RuntimeManager that owns the single active runtime and restarts it on model switch. MockRuntime streams a deterministic echo with zero model files; the real LlamaRuntime (localhost-only sidecar) is selected when binary + weights exist. The factory passed to RuntimeManager is the only thing that changes.
  • Start is idempotent for the in-flight/running model; startingModelId is server truth. RuntimeManager.start() serializes via a queue (orphan-safe on a switch), and now short-circuits when the requested model is already running or already starting — a double-click or a revisit to the AI Model screen before a large GGUF finished loading used to stop-and-restart the runtime (two "Start runtime" log lines, two backend selections). It tracks the in-flight startingModelId (set synchronously, cleared when the start settles) and exposes it on RuntimeStatus.startingModelId. The AI Model screen reads runtime status (and polls while a start is in flight) to show a disabled "Starting…" button that survives leaving + re-entering the screen — the per-component busy flag is lost on remount, this is not. The Chat screen's no-model state likewise says "your model is starting" while startingModelId is set. A model switch (start B while A runs) still stops A first; only same-model re-starts are suppressed.
  • IPC (ipc/registerModelIpc.ts): listModels, selectModel, verifyModel, startRuntime, stopRuntime. The active runtime is stopped on will-quit.
  • Auto-start (post-MVP). maybeAutoStartActiveModel starts the persisted activeModelId in the background once the workspace is usable (app launch for plaintext dev; unlock/create for encrypted), so a restarted app matches what Home shows. Same §7.4 install gate as the manual startRuntime; failures are logged, manual start still works. Since PR #303 P7 it returns a Promise<void> that settles when the start completed, was skipped or failed (never rejects): the first-run benchmark scheduler awaits it (benchmark.md "Scheduling behind the auto-start" — the seams run prepareFirstBenchmark → maybeAutoStartActiveModel → scheduleFirstBenchmark → maybeStartLocalApi, and the benchmark's measurement never overlaps the weight hash + load); the seams themselves stay fire-and-forget. Opt-out via AppSettings.autoStartActiveModel (Settings toggle, default ON).

Chat & streaming (Phase 3)

  • services/chat.ts (spec §7.6) owns conversation/message persistence and prompt assembly: createConversation, listConversations, listMessages, appendMessage, deleteLastAssistantMessage, buildSystemPrompt, buildChatMessages, and the streaming orchestrator generateAssistantMessage. IDs are UUID v4, timestamps ISO-8601 UTC. Messages order by created_at ASC, rowid ASC so equal-millisecond timestamps keep turn order. The system prompt is built per request and not persisted — the messages table holds only user/assistant turns, so the prompt can evolve (the grounded path swaps its own prompt into the last user turn). messages.citations_json is written only by grounded answers.
  • Plain-chat system prompt revised (2026-07-01, owner-approved, supersedes the spec §7.6 wording). From D:\ chat testing: the original BASE_SYSTEM_PROMPT (a) had standalone "You do not have internet access. / You must not claim to have accessed external services." lines that small local models parroted as an offline/no-internet/training-cutoff disclaimer on almost every answer, and (b) carried document-grounding lines ("answer only from the context… / include citations…") that leaked into plain chat, so the model refused general-knowledge questions and pushed "upload a document." Fix: the grounding lines are removed from the base (they already live in full in GROUNDING_RULES, appended for the grounded path as GROUNDED_SYSTEM_PROMPT — so RAG is unchanged), and the offline framing is reworked to a single load-bearing guardrail ("never claim to have browsed / accessed data you weren't given") plus a positive instruction to answer general questions directly from the model's own knowledge, without per-turn disclaimers, and to respond in the user's language. GROUNDED_SYSTEM_PROMPT = BASE_SYSTEM_PROMPT + GROUNDING_RULES still governs document questions (the later, more-specific rule wins). The frozen spec §7.6 prompt survives only in git history (the retired spec — see the retirement legend at the end of this doc); this record is the as-built source of truth.
  • Role alternation (fix 2026-06-14). A failed answer persists the user turn but no assistant reply; left unguarded, the next turn sent consecutive user messages, which several chat templates (Mistral, Qwen tool-style) reject with HTTP 500 ("roles must alternate"). buildChatMessages and buildGroundedChatMessages run collapseToAlternating, which forces strict user/assistant alternation after the system prompt by keeping the LATEST of any same-role run (stale orphan turns dropped) — so a conversation with earlier failures stays answerable.
  • History fits the context window (fix 2026-06-16). The chat and grounded-answer message lists replay the WHOLE persisted history, so an accumulating conversation (or a single grounded turn carrying a large retrieved-chunk block) used to assemble a prompt larger than the model's window — an HTTP 400 exceed_context_size_error that never reached generation. fitMessagesToContext (in services/chat.ts, the single owner) now trims the history to fit contextTokens: it always keeps the leading system message(s) and the FINAL turn (the current question / grounded prompt — never dropped, so an unavoidable overflow is left to the runtime to map), and drops older turns oldest-first, keeping a contiguous recent tail so strict role alternation is preserved. User-first normalization (CB-1, chat-docs audit 2026-07-07): a contiguous tail preserves alternation but NOT first-role parity — an even-length trim can leave an assistant-first tail, which strict templates (Mistral-family) raise_exception on (HTTP 500) — so in the trimmed branch only, fitMessagesToContext drops any leading assistant turns to leave the kept tail user-first (this also prevents replaying the synthetic compaction pair's ack without its intro); the no-trim identity path stays byte-identical (real chats + the compaction pair are user-first, so it pops nothing). A CHAT_RESPONSE_RESERVE_TOKENS (1024) headroom leaves room to generate. buildChatMessages/buildGroundedChatMessages require contextTokens (the production callers pass effectiveContextWindow(runtime, getSettings(db)) — the LAUNCHED --ctx-size the runtime reports (§L0), settings only as the fallback) (D-1, chat-docs audit 2026-07-07; required since #739). Per-turn read hygiene (CB-6, 2026-07-07): buildTurnFence sizes the skill fence against just the final turn via a LIMIT 1 getLatestMessage (a byte-identical twin of listMessages(...).at(-1)) instead of paging the whole history, and generateAssistantMessage reads getSettings once per turn, threading the launched window and the chatCompactionEnabled toggle (new optional compactionOn param on buildChatMessages, default = a fresh read so callers stay byte-identical) rather than re-reading settings three times. This complements the doc-task window budgets (doctasks/summary.ts), which already sized their inputs to contextTokens — the gap was only the conversational path. Since 2026-07-04 the doc-task budgets follow the LAUNCHED window too (DocTaskManager.getContextTokens → effectiveContextWindow of the active runtime), so no area budgets against a different context size than the one the sidecar runs with; the user can change that size via settings.contextTokensOverride (AI Model screen "Context size" card, applied at the next model start — rag-design §15.8). German subword safety (2026-07-01): messageTokens scales the 1.3 base word rate by CHAT_TOKENS_PER_WORD_SAFETY (1.5 → ≈1.95 real tokens/word) because a German machine reply tokenizes at ~1.5–2 tokens/word; the 1.3 base under-counted it, so the trim kept too much history and the answer overflowed. Mirrors the RAG ÷1.5 German safety (rag-design §15.1); one estimate feeds both the trim budget AND the usage meter, so German trims/compacts sooner and the meter reads truthfully high (English reads slightly high — accepted, the meter is labelled approximate).
  • Conversation compaction (L2, above the L1 floor). When history approaches the launched context window (RuntimeStatus.contextWindow? / effectiveContextWindow, not settings.contextTokens), ensureCompacted (services/chat/compaction.ts) summarizes the OLDER turns once into a cached kind='compaction' checkpoint row and assembly thereafter replays a synthetic user→assistant summary pair + only the post-checkpoint turns — instead of silently dropping the oldest. fitMessagesToContext still runs after and still guarantees fit; below threshold (or with the chatCompactionEnabled setting off) behaviour is byte-identical to drop-oldest. CB-3 (chat-docs audit 2026-07-07): the trigger is capped at L1's own floor — min(COMPACT_THRESHOLD·window, window − CHAT_RESPONSE_RESERVE_TOKENS) — so a SMALL window (2048/4096) compacts BEFORE L1 silently drops the oldest turns (the crossover is window ≈ 6827: windows ≥ that keep the exact 0.85·window trigger, byte-identical). The pre-pass estimate also folds in the previously-omitted fixed costs — the real compactionSummaryPair intro/ack text, the base system prompt, and the pre-sized skill fence (passed as reservedTokens; generateAssistantMessage builds the fence BEFORE ensureCompacted, free since buildTurnFence has no checkpoint dependency). Every new path fails safe (any summarizer failure ⇒ no checkpoint, turn proceeds). UX: a composer context-usage meter (now with an always-visible % that updates live as the answer streams — ChatScreen liveUsage = resting read + in-flight user turn + streaming-answer estimate, reconciled to the main-process resting read when the turn settles; since 2026-07-04 the in-flight base is the REAL assembled prompt usage reported by the generators over the ephemeral STREAM.usage channel, so a document turn's injected excerpt block — invisible to any renderer estimate — reads true, rag-design §15.8), a one-shot "summarizing…" notice (STREAM.compaction), and an expandable transcript summary marker. Full design record (L0/L1/L2 + trigger + summarizer + UX, with the deferred Phase-3 /tokenize): rag-design.md §15.
  • Honest truncation signal (L0, 2026-07-01). The balanced/deep chat path sends no max_tokens, so a long reply on a small window can hit the context ceiling and stop mid-word (finish_reason: 'length'). Previously the app was blind to it — the SSE parser only read delta.content, so the partial persisted as if complete. Now readChatSSE/parseSseLine surface finish_reason via a new RuntimeChatOptions.onFinish callback; generateAssistantMessage flags finishReason === 'length' and persists it as messages.truncated (additive nullable column; threaded through Message, appendMessage, and the regenerate delete/restore snapshot). The transcript renders a quiet amber note (.msg-truncated, chat.truncated.*) with an actionable tooltip. A user Stop carries no finish reason, so the intentional partial is not flagged. Since 2026-07-04 (rag-design §15.8) the grounded doc-answer paths (generateGroundedAnswer/generateGroundedDataAnswer) stamp the same flag — a budget-filling document turn is where the ceiling actually hits — and in PLAIN CHAT a 'length' that came from a max_tokens CAP (Fast mode's 1024) is no longer flagged: the badge claimed "context limit", and a capped reply at single-digit meter usage wearing it was a false "context is full" signal. Since 2026-09-21 (#498) the badge names no cause at all — it reads just "Reply cut off" — because the grounded paths DO flag their own pinned cap (they pin 1024 per pass and continue, §15.8/#491) and the "raise the context size" remedy is wrong for those. The cause rides per message instead, as Message.truncatedCause ('context' | 'cap', plus 'repeat' since #994 for a whole-document answer the repetition guard stopped; persisted messages.truncated_cause, NULL on a legacy row ⇒ read as 'context'), and the renderer picks the tooltip from it. Decided by the pure truncationCause(finishReason, sentCap, timings) (rag/whole-doc-tree.ts): not 'length' ⇒ no cause; no cap sent ⇒ 'context'; the server generated FEWER tokens than the cap it was given ⇒ 'context' (only the window explains stopping short); otherwise 'cap'. On the continuation engine the window also wins whenever it shrank or eliminated a pass's room (continueUntilComplete reports the cause back with the final finish reason).
  • First-answer warm-up hint (#39, 2026-07-09). The first generation after a model start/switch pays one-time costs (weights into memory + the long system-prompt prefill that cache_prompt: true then reuses — dramatic on CPU-pinned sessions); the sidecar already budgets for it internally (PREFILL_IDLE_MS ≫ STREAM_IDLE_MS) but the user previously got no equivalent signal. Now a new optional ModelRuntime.warmedUp() (implemented by LadderRuntime + MockRuntime, flipped on the first streamed chunk of any real generation — answer token or reasoning delta) rides RuntimeManager.status() as RuntimeStatus.warmedUp; the ChatScreen arms a per-turn WARMUP_HINT_DELAY_MS (3 s) timer and, only if the turn has streamed NOTHING by then AND a fresh status read says warmedUp === false, shows the calm .chat-warmup-hint line under the pending bubble ("the first answer takes a little longer — the model is warming up"), dropped on the first chunk / turn end. Deterministic no-model answers (routing/refusal/listing) never call chatStream and stream instantly, so they neither mark the runtime warm nor show the hint; an absent field fails safe. Design record: design-guidelines §11.11. Tests: ChatWarmupHint.test.tsx + the warm-up tracking (#39) block in runtime-ladder.test.ts. #1003 amendment (follow-ups wave 7, 2026-11-22): a call with RuntimeChatOptions.auxiliary no longer flips warmedUp(). The cross-language translation (rag/cross-language.ts), the one call a German question over English documents makes before its answer, passes it, so the hint still covers the answer's own cold prefill after a model start. The knowledge-pack planner's call and the skill classifier's call are not marked and still flip it, as before. Test: the auxiliary row in the same runtime-ladder.test.ts block.
  • Hidden warm-up generation (#109, 2026-08-08) — "ready means ready". The #39 hint explained the first-prompt stall; #109 removes most of it: /health resolving says nothing about the one-time prefill/graph warm-up, which measured 6–8× the settled TTFT (10–30 s CPU-only, medium-independent — compute, not IO). LadderRuntime.start() now runs one tiny hidden generation after the winning rung turns healthy and BEFORE start() resolves, so the extra seconds live inside the existing "Starting…" state (startingModelId; the Chat screen already shows its friendly chat.noModel.starting panel throughout — no new status value, no new i18n). Placement decisions, each test-pinned in the hidden warm-up generation (#109) block of runtime-ladder.test.ts + the #109 warm-up window block of runtime-manager.test.ts: (1) in LadderRuntime only — never LlamaServer (shared with the embedder/reranker/vision/ translation sidecars, which must never get a chat warm-up), never the rung-4 mock (zero-assets starts stay instant); (2) AFTER the probe-derived backend label, so a GPU crash mid-warm-up routes through the §5.3 onGpuCrash auto-fallback (gated on backend === 'gpu'); (3) the CODE-2 cancel + CODE-3 latch reach the window — stop() kills the inner server, the warm-up stream errors, and the ladder settles as cancelledStartError() (never a rung walk or mock commit) (the latch itself is manager-level and pinned window-independently in runtime-manager.test.ts "quit-path lifecycle"); (4) a non-cancel warm-up failure never fails the start (the server IS healthy — warn via onWarmup, proceed to ready; a crash still reports via onUnexpectedExit); (5) an overall WARMUP_TIMEOUT_MS (90 s ≈ 3× the worst #109 measurement) aborts a pathological warm-up and proceeds — the CB-5 idle watchdog rides along inside it; (6) the request is content-free ("Hi"), thinking off (omitted mode → enable_thinking: false), max_tokens 8, loopback-only, discarded — never persisted, never audited as a chat; (7) it calls inner.chatStream directly so the #39 served flag does NOT flip: the real first prompt still pays the full system-prompt prefill (no shared cache_prompt prefix), and the #39 hint stays armed as the safety net. Observability: the onWarmup hook (done/timeout/failed) logs through main/index.ts.
  • Concurrent weight prefetch (#114, 2026-08-09). llama-server's mmap load faults pages in a non-sequential order that slow media punishes (#107: ~2/3 of a stick's sequential throughput; 2.4× the pure-sequential time under memory pressure). LadderRuntime.start() now launches a plain sequential read of the weight file set (startModelPrefetch, runtime/prefetch.ts) ALONGSIDE the first rung's load — the bytes are discarded; priming the OS page cache at full media speed is the whole effect. Shipped on the #114 on-hardware matrix (16 GB box, all four variants × cold/warm × stick/SSD, evidence in the issue): −49% cold start on a 23.5 MB/s stick (6.65 GB model: 680 s → 346 s), −36% on an 868 MB/s USB SSD (15.0 → 9.6 s), ~neutral in every other cell; concurrent beat prefetch-then-spawn, and --no-mmap was REJECTED (fastest cold on the stick but forfeits the page cache: 292 s warm restarts vs 5 s, worst in every SSD cell). Contract, pinned in the concurrent weight prefetch (#114) block of runtime-ladder.test.ts + runtime-prefetch.test.ts: (1) FIRST rung only — a later rung re-reads a file the failed attempt already pulled through the cache (the #108 sample rule's reasoning); (2) skipped when the install-state pass just hashed the weights — the same one-shot #108 suppression signal, peeked without consuming (isNextModelLoadSuppressed); since #392 the #108 SAMPLE rule is deliberately broader than this skip (any hash of the weight this session drops the load sample; only the start's OWN hash skips the prefetch), because a stale warmth signal costs at most one droppable sample but a wrongly skipped prefetch costs the measured −49 % cold-start win; (3) aborted the moment the load window ends either way, and by the CODE-2 stop/lock cancel (the reader must not keep the drive busy past a stop; abort lands within one 4 MiB chunk); (4) any prefetch outcome is control-flow-inert — 'failed' means the load proceeds unassisted; (5) the file set is weightPaths (manifestFiles()'s full list — the GGUF, a vision model's mmproj, and since #310 any files: entries — from startModelRuntime's manifest), falling back to modelPath. The #108 model_load sample now measures the prefetch-assisted window — still the honest rate the user felt, closer to what the medium can deliver. Observability: the onPrefetch hook logs through main/index.ts + a model_prefetch perf mark pair.
  • Surfaced runtime errors (fix 2026-06-14, hardened 2026-06-16). LlamaRuntime.chatStream throws a typed ChatRequestError carrying the server's {error:{message,type}} body (previously the body was discarded and only "HTTP " survived). isExceedContextError recognizes the exceed_context_size_error (an HTTP 400 — the prompt is larger than contextTokens); the doctask manager and the chat/RAG stream wrapper map it to the friendly, localized main.model.contextExceeded ("too large for this model — try a larger-context model or a smaller document") instead of a raw code. The raw reason still goes to the local log only. The renderer surfaces the invoke REJECTION, not the chat:error event — so withChatStream now throws the mapped friendly message (not a raw rethrow) on overflow, and friendlyIpcError strips any WordError: class-name prefix (not just Error:). Before this, the carefully-built friendly copy was dead for the chat/RAG path and users saw the raw ChatRequestError: … HTTP 400.
  • Regenerate is delete-after-slot (F2, post-merge audit 2026-06-29). "Regenerate" re-answers the last user turn by dropping the previous assistant reply. The destructive delete must NOT commit before the stream slot is claimed: node:sqlite is synchronous, so a pre-slot deleteLastAssistantMessage was durable the instant it ran, and any non-abort failure between it and the first persisted token — acquireSlot rejecting, a sidecar that died mid-session, or (most reachably) an exceed_context_size_error HTTP 400 because regenerate replays the full history near the window — left the turn answer-less and irrecoverable. The IPC layer now only does the read-only hasRegenerableAssistantReply precondition (the unchanged "nothing to regenerate" bail) before the stream; the delete itself runs inside withChatStream's runFn via withRegenerateGuard (ipc/chat-stream.ts) — after the slot is held + the controller registered — and the snapshot it returns is re-inserted byte-faithfully (restoreMessage: same id, timestamp, citations, coverage, skill stamp) if generation fails for a NON-abort reason. A user Stop (abort) keeps the delete (the new partial/empty reply stands). Applied symmetrically to both channels — registerChatIpc (generateAssistantMessage) and every registerRagIpc withChatStream site (grounded / whole-doc / compare / exhaustive-run / listing / refusal). The slot/stream semantics are otherwise identical; the only change is WHEN the regenerate delete runs.
  • Streaming contract (LOCKED). Main → renderer over per-conversation IPC event channels keyed by the conversation id: chat:token:<id> (one token per event), chat:done:<id> (the final assistant Message), chat:error:<id> (an error string) — helpers in src/shared/ipc.ts STREAM. The renderer subscribes via the preload onToken/onDone/onError before sending. sendChatMessage(conversationId, content, options) also resolves with the final assistant Message, so a caller can simply await it; the event channels drive the incremental UI. The streaming id is the conversation id (one active stream per conversation). Phase 20 added one ADDITIVE channel: chat:reasoning:<id> (preload onReasoning) carries Deep-mode thinking deltas; token events still carry only answer text, and reasoning is a live-display affordance that is never persisted. A further additive channel chat:scope:<id> (STREAM.scope) carries a one-shot ScopeNotice — the filenames retrieval was auto-restricted to — before the first token of a document answer when filename auto-scope fires; informational only, never persisted.
  • Per-answer speed line (issue #290, 2026-09-04) — design record §1–§3. §1 What it shows. Under a FINISHED plain-chat answer, one quiet metadata line in the skill-glyph / truncation-note style: 42 tok/s · 1.8 s to first token · 615 tokens (no decimals at or above 10 tok/s, one below; EN + DE via chat.speed.line, formatted by renderer/chat/answerSpeed.ts). §2 Where the numbers come from. Tokens/sec and the token count are llama-server's own timings (predicted_per_second, predicted_n) handed up by readChatSSE → onFinish(reason, timings) (the #291 seam) → generateAssistantMessage's onTimings (fired only for a COMPLETED stream) → withChatStream's sendTimings; time to first token is withChatStream's own clock (stream registration → first sendToken, the same figure as the first_token perf mark — prompt assembly, any compaction pre-pass and prefill included, i.e. the user-felt wait). One ADDITIVE ephemeral channel chat:speed:<id> (STREAM.speed, payload AnswerSpeed keyed to the persisted message id) fires right before done; answerSpeedFrom is the single rule and yields nothing without timings, without a first token, for an empty reply or for non-positive figures — so an aborted answer (no final chunk) and the mock runtime (no timings) show no line, never a wrong one. §3 Scope + persistence. Nothing is persisted, no schema change, not in streamBuffers (R14): the renderer keeps a session map by message id (ChatScreen answerSpeeds → Transcript), so a reload shows nothing on old messages. Plain chat only — the document channels, the hidden warm-up (#109), Fast-mode warm-up, doc tasks, skill runs and compaction never wire sendTimings. The local API deliberately still omits usage (local-api.md §6.5).
  • Answer-depth modes (Phase 20, spec §10.3). ChatOptions.mode (fast|balanced|deep, per message, sticky per conversation in the renderer) threads through generateAssistantMessage → RuntimeChatOptions.mode. The mapping to request parameters lives in ONE place, runtime/llama.ts requestParamsForMode (D4): fast = thinking off + temp 0.7 + 1024-token cap; balanced (and omitted) = thinking off, server defaults; deep = thinking on + temp 0.6. Thinking is toggled per request via chat_template_kwargs.enable_thinking (D5, verified against the pinned llama.cpp b9585); every chat sidecar is spawned with --jinja --reasoning-format deepseek (CHAT_SERVER_ARGS, which also carries -lv 4 for the placement parser and, since 2026-09-07, -np 1 — one server slot; GPU record runtime record, issue #319) so the kwarg acts and reasoning streams as separate delta.reasoning_content frames. stripThinkBlocks (services/chat.ts) scrubs any inline <think> block from persisted replies AND from assistant turns replayed as history (D6 — the collapsed "Thinking…" block is a live-stream affordance only; an all-think aborted reply persists nothing). Document answers (rag/) never pass a mode — grounded answers always run balanced. Grounded answers additionally pin temperature: 0 and max_tokens: 1024 on the request itself, independent of requestParamsForMode (unchanged) and never sent to plain chat or the local API, so a grounded answer's wording no longer varies because of sampling — never "identical": the call's position inside the long-lived llama-server process still moves the output (a dedicated determinism check ruled out prompt-cache and compute-graph reuse as the cause); the whole-document map-reduce engine's own map/reduce calls keep SUMMARY_TEMPERATURE unchanged. Research note that shaped D4/D5: at b9585 --reasoning auto (the server default) turns thinking ON for every capable template — the bundled Qwen3 models were ALREADY thinking on every reply while the app silently dropped those deltas (pure latency cost), so enable_thinking is ALWAYS sent explicitly; balanced/omitted = false. The Qwen3 /think·/no_think soft switches were rejected (they leak into transcripts). D4's fast/deep values come from Qwen3's model-card sampling guidance (re-tune when the release hardware matrix lands); explicit RuntimeChatOptions.maxTokens/temperature always win over mode-derived values. Deep is offered only when the RUNNING model's manifest sets supports_thinking_mode (via RuntimeStatus — the Chat screen already polls it; see model-policy.md).
  • Cancellation. Each in-flight send holds an AbortController in the per-conversation inFlightStreams map in ipc/inflight.ts (shared by the chat AND RAG channels, not registerChatIpc.ts); stopGeneration(conversationId) aborts it. The runtime's chatStream honours options.signal and stops emitting; whatever streamed so far is persisted as the (partial) assistant message and a normal done is emitted (D-3, chat-docs audit 2026-07-07).
  • Chat backend robustness (CB-2…CB-5, CB-7 — chat-docs audit 2026-07-07). A backend sweep of the streaming/cancellation path (ledger + CB-n disposition in §45; the audit/plan were retired there):
    • Deterministic teardown (R1). withChatStream publishes a per-stream streamSettled promise (in ipc/inflight.ts) that resolves — never rejects — in its finally, AFTER runFn (and thus its abort-driven appendMessage) has fully unwound. A lock/quit teardown MUST therefore abort() every in-flight controller FIRST, then await all settles (awaitInFlightStreamsSettled), then close the DB — so a partial reply persists before ctx.db closes (never rejected, so allSettled can't hang teardown). The order is pinned by workspace-ipc.test.ts "lockWorkspace awaits each in-flight stream settle before re-encrypting (R1)" (lock) and shutdown.test.ts "AWAITS each in-flight stream settle before locking (R1)" (quit); tests/integration/lock-stream-persistence.test.ts pins the end states in the chat service itself (an aborted partial persists on an open DB, and the defence-in-depth guard drops a partial-persist against a closed DB without a rejection).
    • CB-2 — regenerate never loses the prior answer on a produced-nothing run. withRegenerateGuard deletes the prior reply INSIDE the stream (F2). A user Stop BEFORE the first token resolves (does not throw) with an unpersisted empty message (content === ''), so besides restoring on a non-abort throw the guard now also restores on that empty resolve — restoreMessage re-inserts the original id/timestamp (no duplicate) and getLatestMessage returns it so chat:done re-shows the answer. Two clicks (Regenerate, Stop) no longer silently erase a reply.
    • CB-4 — a completed-but-empty completion surfaces an error, not a silent blank. The content === '' early return is narrowed: a stop-before-first-token OR an all-<think>/fence-echo reply that stripped to empty (tokens arrived — receivedAnyToken) stays the benign silent-empty; only a COMPLETED, non-aborted stream that produced zero tokens throws EmptyCompletionError.
    • CB-5 — a hung sidecar aborts with a distinct error instead of wedging. readChatSSE races each reader.read() against a two-phase idle watchdog (PREFILL_IDLE_MS 120 s until the first chunk — a near-window regenerate prefill is legitimately slow — then STREAM_IDLE_MS 30 s between chunks; reasoning deltas count as chunks; idle is injectable, the production default keeps live streams byte-identical). A timeout cancels the reader and rejects RuntimeUnresponsiveError; a user Stop (signal abort) still wins first, so a hang is never converted to an abort (the partial persists as today) or vice-versa. Scope: post-response streaming only — a hang in the initial server.fetch is a separate seam, deferred. (Closed by the #594 amendment below.)
      • #594 amendment (2026-10-05) — the header wait, and pings. The facts, on the pinned builds:

        • Headers go out when the slot starts, before prefill. That is the is_begin result in upstream server-context.cpp:3416-3424, at b9849 and b11146 alike. Measured on the b11146 CPU build with the 9B and the app's argv (a 6,394-token prompt): headers after 14 ms, first token after 320.9 s. So a legitimate header wait is tokenisation plus the wait for the one slot. It is long only behind a cancelled request's batch, which takes ≈100 s per 2048 tokens for that 9B.
        • The old wait ended only at undici's limit. Electron 43.7.7's fetch gave up after 304.8 s (UND_ERR_HEADERS_TIMEOUT), and the user saw a raw "fetch failed". Until then the turn held every busy signal, which refused the #516 engine update, and the local API kept its one slot.
        • b11146 writes an SSE comment : after every ~30 s of silence (--sse-ping-interval, default 30, polled each second). The per-read timer re-armed on each ping. (This record said b9849 has none. It has the same ping; the #598 amendment below corrects it.)

        As built. LlamaRuntime.chatStream gives the headers PREFILL_IDLE_MS, 120 s (owner call; #598 then gave them their own 180 s).

        • It uses combineSignals. On arrival a new disarmTimeout() stops only the timer: the request keeps following the caller, so a Stop tears the stream down as before.
        • Expiry → RuntimeUnresponsiveError; a Stop wins a tie.
        • The deadline stays armed over an error response's body, so a stalled error body leaves only the status.
        • In readChatSSE, after the first chunk the stream budget counts only time spent waiting since the last model output, on the monotonic clock. Model output is any bytes that are not a blank line or a comment, including the start of a line split across reads. Pings no longer count; the consumer's time between pulls still doesn't.
        • Before the first chunk, pings still re-arm the prefill budget, on purpose (owner call): a real CPU prefill runs for minutes, and on b11146 the pings are its only sign.

        Accepted (owner, with the 120 s): the header clock includes any queueing for the server's one slot (-np 1).

        • A re-ask right after a Stop waits for the cancelled request's batch to finish. On a slow CPU that batch can take longer than 120 s, which ends the re-ask with this error; a retry then works.
        • Two in-app answers on one model would queue the same way. The UI rules that out: ConversationList disables the other conversations while one streams, and onSend refuses.

        Left open:

        • #598: a hung prefill on b11146 stays unbounded, and b9849 cuts a long one at 120 s. Closed by the #598 amendment below. The b9849 half was wrong: it pings too.
        • #599: a running server's liveness is never re-checked. Closed by the #599 amendment below.
        • #600: a model stop mid-answer shows "fetch failed". Closed by the #600 amendment below.

        Real app (2026-10-05, DesktopDiT, dev build, b11146 Vulkan, the 4B on the GTX 1070 Ti). The sidecar was frozen with NtSuspendProcess just before a chat.

        • On master, the chat ended after 305.9 s with "fetch failed".
        • With the fix, it ended after 120.0 s with main.chat.runtimeUnresponsive.
        • Both times the engine update was refused as busy until the chat ended, then accepted.
        • Once the process was resumed, the next chat answered in 0.2 s.

        Tests. llama-runtime.test.ts "the wait for the response headers (#594)" (a real loopback socket and real fetch), read-chat-sse.test.ts "SSE comment pings in the stream phase (#594)", combine-signals.test.ts disarmTimeout(), and local-api-server.test.ts "502 runtime_unresponsive, slot freed".

      • #598 amendment (2026-10-06) — prefill liveness: a process clock and a compute clock. The facts, verified at both pins (upstream source at 7fe450e1 / 799fcc04 and real captures):

        • Both pins ping. b9849 has the same --sse-ping-interval loop as b11146 (server-context.cpp:4276-4290 at b9849). Measured: 15 pings over a 566.8 s b9849 CPU prefill (the 4B, 2 threads). So before #598 a ping re-armed the 120 s prefill budget on both pins: a long CPU prefill was never cut, and a wedged one was never ended.
        • A ping proves only that the process lives. It comes from the HTTP thread. Repro: one compute thread of a b11146 CPU server suspended (SuspendThread, never the whole process) right after a batch. The pings kept coming every 30 s for 151.7 s with no progress, and /health answered 200 in 62 ms (so did /slots, with stale progress).
        • return_progress: true is parsed by both pins (server-schema.cpp:37). The server sends a prompt_progress event with the headers (processed 0, measured +18–35 ms) and after every n_batch (2048) prompt batch. Each event has a {role, content: null} delta, so it carries no text. The batches can be uneven (qwen3.5's checkpoint splits: 11 / 2048 / 2048 / 239 / 2044 / 4).
        • Batch times. About 100 s per 2048 tokens for the 9B on the i7-8700 (6 threads). 43.6 / 59.6 / 73.7 s for successive batches of the 4B there: later batches of one prompt run slower. 363–414 s for one 2,015-token batch of the 9B on the i7-8550U laptop in power-saver mode, on CPU and on its iGPU alike (leg0-9b-*). That iGPU run is labelled gpu, so a budget keyed on the backend label would be unsafe.

        As built. IdleWatchdog gains progressMs, and before the first chunk readChatSSE runs two clocks on the monotonic waiting time (the #594 accounting):

        • the process clock (prefillMs, 120 s): any byte re-arms it, pings included. A frozen process still ends here, as before;
        • the compute clock (progressMs, 10 min, owner call; first 7, raised once the calibration below was weighed): only a progress event or model output re-arms it. It runs once the server has sent a progress event, so a server that sends none keeps the pre-#598 rule.
        • The read waits for whichever runs out first, and the error names the clock (no prompt progress for 600000ms). After the first chunk nothing changed.
        • LlamaRuntime.chatStream sends return_progress: true on every chat request. The headers get their own HEADER_WAIT_MS, 180 s (owner call), no longer CB-5's 120 s.
        • Vision shares the reader but does not ask for progress events. With none arriving it keeps the process clock alone, under its own 300 s request cap. No capture shows how progress events fall around image encoding, so a compute clock there needs its own capture and calibration first.
        • The local API re-serialises tokens, so its clients never see the progress events.

        Accepted (owner):

        • 10 min sits about 40 % above the slowest batch measured (414 s for 2,015 tokens, about 421 s for a full 2048-token batch, later batches slower). A bigger model on CPU (the 27B/31B class) can still exceed it per batch. It is a one-line constant (PROGRESS_IDLE_MS).
        • A re-ask right after a Stop still waits for the cancelled request's batch, now for up to 180 s.

        Out of scope. The translation sidecar's reader had no watchdog at all. #605 gave it these clocks with its own budgets and restarts a hung sidecar: see the translation sidecar record's "#605 amendment". The "about 90 min" first written here was wrong, because Electron's fetch ends 300 s of silence by itself; it was ≈ 50 / 45 / 10 min per window.

        Real app (2026-10-06, DesktopDiT, dev build over CDP, b11146 CPU rung, the 4B at ctx 4096).

        • A 3.4K-token question answered after 214.7 s, past the old 120 s.
        • Next, the busiest llama-server thread was suspended 6 s into the same kind of prefill. During the stall /health answered 200 in 7 ms.
        • The chat ended with main.chat.runtimeUnresponsive exactly one compute budget after its last progress event (the 0 % one at slot start): 420.2 s with the first 7-minute value, and 600.0 s with the final 10-minute one.
        • After the thread was resumed, the next chat answered in 32.2–32.6 s. It first waited for the stalled batch to finish, inside the 180 s header budget.

        Tests.

        • chat-sse-progress-fixture.test.ts replays two real b11146 captures on their recorded timelines (chat-sse-progress-b11146.txt, chat-sse-progress-stall-b11146.txt).
          • A legitimate 187 s, four-batch CPU prefill answers.
          • The captured wedge ends exactly 10 min after its last progress event, with the pings still coming. This one fails on the pre-#598 code.
          • A b9849 capture of the same request (chat-sse-progress-b9849.txt, truncated after the first token) pins that the older pin sends the same per-batch events, so the compute clock holds on drives without the #516 update.
        • read-chat-sse.test.ts "prefill liveness (#598)" pins the clock rules: per batch, not total; a frozen process ends at 120 s; no progress events means the old rule.
        • llama-runtime.test.ts covers the 180 s header budget and the return_progress request field. Each rule was mutation-checked.
      • #600 amendment (2026-10-06) — the model stopped, switched or crashed mid-answer. The facts:

        • What users saw (real app on master, DesktopDiT, b11146):
          • A stop or a switch mid-answer showed "terminated" and lost the partial answer. Only an abort keeps a partial; this was a killed socket.
          • A request still waiting for its headers showed "fetch failed".
          • A re-ask followed by a stop restored the old answer, but with the raw error.
          • A CPU-mode crash then showed "fetch failed" on every later turn, because the status still says running (#599).
          • The local API answered 502 runtime_unresponsive or an in-band runtime_error.
        • undici's shapes (Electron 43.7.7, a b11146 server killed at each phase, all within 3 ms): a queued request → TypeError: fetch failed (cause ECONNRESET); prefill or mid-stream → TypeError: terminated (ECONNRESET); a new request to the dead port → "fetch failed" (ECONNREFUSED).
        • On POSIX a stop is a SIGTERM. llama-server then holds an open stream silently for 30–57 s, with no clean end (curl exit 18), and the app SIGKILLs it after its 2 s grace. With the client gone first it exits in 0.8 s (WSL, the b11146 Linux build).
        • A switch first hashes the new model's weights (17 s for a cold 9B; minutes from a slow drive). The old model keeps answering meanwhile.

        Owner decisions (2026-10-06).

        • End in-flight work at the kill point, not at the click, and only for a deliberate stop or switch. There is no wait before the kill, and the crash restart is excluded.
        • Keep the partial with its own "Reply stopped" marker, never the "Reply cut off" flag.
        • A re-ask cut by a model stop keeps its previous complete answer.
        • The scope is chat, document answers and the local API. Document tasks keep their honest failure: a cancelled task is silent on the Documents screen. Skill runs move to #606.
        • A crash shows main.chat.connectionLost and drops the partial (the F-02 rule).
        • A question that got no answer is marked; a calm note on the AI Model card replaces any dialog.

        As built.

        • The hook. RuntimeManager.setModelStopHook is called from doStop(kind) after current is cleared and before stopping.stop(), synchronously, for stop and switch; forceRestart passes restart and skips it. A wait there would let a GPU crash queue a forceRestart of the model just stopped. Lock and quit abort first anyway, and the first abort reason wins.
        • endWorkOnModelStop (ipc/model-stop.ts, wired in main/index.ts) ends, in order:
          • the local API's request (endForModelChange). It goes first because a turn ended inside its compaction pre-pass re-enters the gate;
          • a deep-index build;
          • every inFlightStreams controller, with modelStopAbortReason(): an AbortError-named DOMException tagged in a WeakSet (runtime/model-stop.ts; since #612 one WeakMap for all three causes, chat/ended-early.ts).
        • The gate returns at once for an in-app call whose turn is already aborted, so such a call no longer pre-empts the external lane or stamps lastPreemptedAt.
        • persistAssistantMessage stamps endedEarly: 'model' from that reason. It is a new nullable column, messages.ended_early, because an older app reads an unknown truncated_cause as "raise the context size", while it ignores a new column (#994's 'repeat' cause accepts that older-app reading on purpose for a rare answer; see docs/data-contracts.md messages.truncated_cause). The column is carried through DeletedMessage, read tolerantly, and its values user/lock are reserved for #612 (written since the #612 amendment below).
        • withRegenerateGuard now holds the model-stop rules for every turn:
          • a re-ask the stop cut deletes its saved partial and restores the predecessor, in one transaction (a failed restore keeps the partial). It keys on the saved answer's endedEarly, not the signal, so a stop landing after a complete answer was saved keeps it;
          • a re-ask that threw with nothing saved restores its predecessor for any reason. Before, aborts were skipped, so a Stop during document search lost the answer — reachable through "Answer without it" / "Run with ". #779: after that restore an abort resolves with the restored answer (CB-2's shape), so chat:done carries it instead of an empty message; any other failure still rethrows to chat:error;
          • a turn left with no answer marks its question (markUnansweredQuestion, last visible row only).
        • A crash surfaces as RuntimeConnectionLostError, raised by LlamaRuntime.chatStream on a socket-loss TypeError (fetch and body read) when the caller's signal is clear, and by the ladder's "not started" guard. It maps to main.chat.connectionLost, which names the "KI-Modell-Bereich" in German per the design guide. A Stop always wins a tie.
        • The local API reads the code back from the abort reason: model_not_loaded / model_starting as a 503, or the same codes in-band. A queued request gets the same 503, not 429 busy. A stop the app follows with a start itself (an engine update, the demo → real engine restart) passes stop({ startFollows: true }) and reads as a switch.
        • The UI.
          • "Reply stopped" and its hint on the answer; "Not answered — the AI model was stopped." on the question.
          • RuntimeStatus.answering (in-flight streams) drives the AI Model card's note, which polls until it clears.
          • The evidence snapshot's answerStopped makes the pack say the answer was stopped (since #612 answerEndedEarly, which names the cause).
          • Design record: design-guidelines §11.21.

        Not covered.

        • A Stop during the pre-generation slot handoff (REL-3) ends before the guard runs; its question is not marked.
        • Document tasks fail with main.task.genericFailure on a stop (by decision).
        • The stop ends every in-flight chat turn, a deterministic extraction that might not have needed the model included; it ends as a Stop would, and answering counts it the same way.
        • A stopped bank-statement narration still gets its totals block (#612). Kept on purpose: see the #612 amendment below.
        • Skill runs are left to #606. Closed by the #606 amendment below.
        • Answers ended by the Stop button, lock or quit keep no marker (#612). Closed by the #612 amendment below.
        • There is still no resend for an unanswered question (#613). Closed by the #613 amendment below.

        Tests.

        • model-stop-mid-answer.test.ts: the real manager, hook body, chat stream and generateAssistantMessage against a runtime that dies like the sidecar; plus the hook order.
        • runtime-manager.test.ts "the model-stop hook (#600)".
        • chat-stream-regenerate.test.ts "#600".
        • llama-runtime.test.ts "a sidecar that dies under the request (#600)": a real loopback socket and real fetch.
        • chat-stream.test.ts, local-api-server.test.ts, chat.test.ts "ended early", evidence-snapshot.test.ts, evidence-pack-html.test.ts, TruncatedNotice.test.tsx and ModelsScreen.test.tsx.
        • All 16 rules were mutation-checked; the end-to-end test fails with "terminated" on the pre-fix code.

        Real app (2026-10-06, DesktopDiT, dev build over CDP; the same script as the master run).

        • A stop or a switch mid-answer resolves with the partial marked.
        • A re-ask followed by a stop keeps its 976-character predecessor.
        • A GPU crash and a CPU crash show the connectionLost copy, and so does the next turn on the dead CPU sidecar.
        • A stop before the first word marks the question.
        • Local API: a stop → in-band model_not_loaded / 503 model_not_loaded; a switch → model_starting.
      • #612 amendment (2026-10-06) — the Stop button, lock and quit leave the same lasting marker. The facts:

        • What users saw. Four things abort an in-flight answer (inFlightStreams): the Stop button (chat:stop), "Lock now" (runLockTeardown), quit (performShutdown) and the #600 model stop. Only the model stop passed a reason. The other three called a bare controller.abort(), so their partials were saved like complete answers. After a reload, an unlock or a relaunch nothing said they were cut. The Stop toast showed only in the window that pressed Stop.
        • The first abort wins. Lock's own runtime.stop() fires the model-stop hook, but every turn is already aborted by then. That is why a lock-cut partial never got #600's 'model' either.
        • The evidence snapshot copied 'model' only, so a pack built on a Stop or lock partial said "No output truncation was recorded for this answer."
        • Not released yet. #600 is not in v0.1.62, so answerStopped (below) never shipped, and the column already reserved 'user' and 'lock'. No migration was needed.

        Owner decisions (2026-10-06).

        • The cut bank-statement or invoice narration keeps its deterministic totals echo (and the date / text-quality caveats); the "Reply stopped" marker labels it. A "Reply cut off" narration keeps them the same way, and the echo contradicts a figure the partial misquoted. Dropping it would have removed that guard exactly where the answer is incomplete.
        • A re-ask cut by a lock or quit restores the previous complete answer, as a model stop does: the user acted on the workspace, not on the answer. The Stop button keeps its partial.
        • A Stop before the first word marks the question too ("Not answered — you stopped it."), so all three causes follow #600's rule that a question with no answer says why.

        As built.

        • One tag module, chat/ended-early.ts: endedEarlyAbortReason(cause) mints an AbortError-named DOMException registered in a WeakMap, endedEarlyCause(signal) reads it back, and parseEndedEarly is the one tolerant reader of a stored value. It replaces #600's runtime/model-stop.ts.
        • The sites. chat:stop aborts with 'user'. runLockTeardown and performShutdown abort with 'lock'; quit locks the workspace too, so it shares the cause. The model-stop hook keeps 'model'.
        • persistAssistantMessage stamps whatever cause the turn's signal carries, so all four streamed answer paths are covered. A bare abort carries none. Since #742 it stamps none on a truncated reply: runtimes report a finish reason only for a stream that ran to its end (readChatSSE at [DONE] or a clean close; the continuation engine reports none on a Stop), so such a reply was cut by the ceiling before any abort. On today's paths only microtasks separate the stream's end from the persist, so the IPC-dispatched abort cannot land there; the rule makes "one note, never both" hold by construction rather than by that timing. Its twin, a COMPLETE reply ('stop') stamped "Reply stopped" by an abort in that same window, is left as is: one label, not two, and equally unreachable today.
        • withRegenerateGuard. It marks an unanswered question with any cause, and restores the predecessor for 'model' and 'lock' (RESTORES_PREVIOUS_ANSWER). A lock runs that while its teardown awaits the turn's settle (R1), so the database is still open.
        • The evidence snapshot records the cause as answerEndedEarly, replacing #600's answerStopped boolean. The pack, the review footer and the review summary say review.summary.stopped.<cause>.
        • The UI. The transcript shows one "Reply stopped" label with a hint per cause (chat.endedEarly.hint.*) and the "Not answered" note per cause (chat.unanswered.*). Design record: design-guidelines §11.21 "#612 amendment".

        Not covered.

        • A Stop or lock during the pre-generation slot handoff (REL-3) still ends before the guard runs, so its question is not marked. Since #613 it still offers "Send again" (amendment below).
        • The OS session-end lock (emergencyLock, #248) closes the database without aborting, so a partial it cuts is not saved at all, as before.
        • The Markdown transcript export carries neither "Reply cut off" (#498) nor "Reply stopped".
        • A partial still replays into later prompts as if complete (the Stop button's long-standing behaviour).

        Tests. Each fails on the pre-fix behaviour; all ten rules were mutation-checked.

        • chat-ipc.test.ts C1: the Stop handler → the saved partial reads 'user'.
        • workspace-ipc.test.ts "(#612)": a real turn on a real encrypted vault, "Lock now", then a fresh unlock that reads 'lock' back.
        • shutdown.test.ts "(#612)": quit aborts with 'lock'.
        • chat-stream-regenerate.test.ts: the restore rule per cause, the "Not answered" mark per cause (and none for a bare abort).
        • rag.test.ts: a stopped grounded-data narration keeps its echo and is marked.
        • evidence-snapshot.test.ts, evidence-pack-html.test.ts and TruncatedNotice.test.tsx: per cause.

        Real app (2026-10-06, DesktopDiT, dev build over CDP, the 4B on the GTX 1070 Ti, b11146). The run was made on a plaintext-dev root, then again on an encrypted one (E:'s policy.json):

        • Stop mid-answer → the partial reads "Reply stopped" ('user'), and its evidence review says answerEndedEarly: 'user', before and after a relaunch.
        • Stop before the first word (a 6,162-character question) → the question reads "Not answered — you stopped it."
        • "Lock now" mid-answer → locked; after unlock the partial reads 'lock'.
        • A complete 906-character answer, Try again, then "Lock now" mid re-ask → after unlock the same answer (same id, no marker) is the one left.
        • Quit mid-answer → only hilbertraum.sqlite.enc at rest; after relaunch and unlock the 206-character partial reads 'lock'.
        • Every label and tooltip was read off the DOM in English and German; screenshots are in the PR.
      • #606 amendment (2026-10-06) — skill runs and the benchmark when the model is taken away. The facts:

        • Two lanes were missing from the teardown lists. Lock (runLockTeardown), quit (performShutdown) and #600's model-stop hook end every lane on the chat model before it dies. The skill-run controller was reachable only from registerSkillsIpc, and the benchmark's speed leg had no signal at all.
        • What a killed request did to a skill run. The run's own signal was untouched, so undici's TypeError: terminated (not an abort) took each seam's failure path. A redaction fell back to the rule-based floor (D73), dropped what the model had already found, and opened its save dialog. A document edit ended failed / editFailed. A categorize run's model call is a document task (D26), which lock and quit already cancelled.
        • Seen in the real app (master, DesktopDiT, encrypted vault, the 4B on the GTX 1070 Ti, b11146, a 200-line register at window 1 of 7). Stop runtime → "rule-based floor" in the log and the "Save redacted copy" dialog. "Lock now" → the same dialog over the lock screen. After a cancel and an unlock the run read failed, "This could not be saved": its write hit the closed database, and the next unlock reconciled a skill_runs row left at started.

        Owner decisions (on the issue, 2026-10-06).

        • A stop or switch of the model is a third trigger: "Stop runtime", "Use this model" and the Performance screen's "Start … and measure" cancel the runs streaming on the model. The honest outcome for a privacy tool is a cancel ("Stopped. Nothing was saved."), never a floor copy.
        • An abort cannot close a save dialog that is already open. Saving there writes, and the run reads done.
        • A categorize run follows #600's rule for document tasks: a model stop leaves it to fail.

        As built.

        • SkillRunController gains a per-run usesModel flag and three main-side methods: cancelAll() (lock, quit), cancelModelRuns() (the hook) and awaitSettled(ms). They are not on the IPC surface; SKA-25's handle-only rule for the renderer stands.
        • startSkillRun sets usesModel from the same two facts the #186 span reads: a direct tool and a running model. A floor-only redaction started with no model is never cancelled by a later stop, and neither is categorize (doctask) or an extraction.
        • ctx.skillRuns is assigned by registerSkillsIpc, beside skillRunActive, narrowed to the three methods.
        • Lock and quit call cancelAll() next to cancelAllDocTasks(), before the sidecars stop. They await awaitSettled (5 s) beside the doc-task settle, so the cancel is recorded while the database is open. Quit's 30 s overall budget sum is unchanged.
        • endWorkOnModelStop gains a fourth step, cancelModelRuns(), after the answers.
        • The seams are untouched. With the signal aborted first, isAbortError(e, signal) already maps the killed request to the calm cancel, and the pre-dialog signal.aborted check stops the save. The run bar's existing copy reads "Stopped. Nothing was saved."
        • The benchmark is in benchmark.md "Lock and quit cancel the speed leg (#606)": an abort slot, ctx.cancelBenchmark in both teardowns, nothing persisted. A model stop keeps #393's warnSpeedSkipped.

        Not covered.

        • A crash mid-redaction (forceRestart, no hook) still fell back to the floor and opened the save dialog; the "rule-based detection only" note appeared only after it. Fixed by #620: any model failure during the locate pass now fails the run with nothing saved (Skills record §21 "#620 amendment").
        • The OS session-end lock (emergencyLock) aborts nothing (#612 note above).
        • A run parked in an already-open save dialog does not settle; lock and quit go on at the bound.
        • usesModel is fixed when the run starts. A stop in the short tail after the locate pass (the tool's in-memory pass, a DOCX rezip) cancels a run that would not have needed the model again; it reads "Stopped" and can be run again. Accepted as simpler than tracking the pass.
        • A lock that then fails (CODE-1a, e.g. ENOSPC) has already cancelled the runs, as it has the answers and the document tasks.

        Tests. Each fails on the pre-fix code; all twelve rules were mutation-checked.

        • model-occupancy-ipc.test.ts "(#606)": startSkillRun → the real manager + hook → a stop or switch mid-locate ends redaction and edit cancelled, no dialog, no file. Before: done (the floor copy saved) and failed.
        • workspace-ipc.test.ts "(#606)": the real redaction seam on a real encrypted vault, "Lock now" → cancelled, no save, the benchmark cancelled before the runtime stop, and the row read back cancelled after unlock. Plus the settle row beside TA-1 H2's.
        • shutdown.test.ts: the REL-4 ordering and the settle row beside H1's.
        • model-stop-mid-answer.test.ts: the hook order (cancelModelRuns, never cancelAll).
        • skills-run-controller.test.ts "(#606)", plus the benchmark tests listed in benchmark.md.
        • The runtime that dies like the sidecar is one helper now, tests/helpers/killable-runtime.ts.

        Real app (the same root and script as the master run, fixed build): Stop runtime at window 1 of 7 → cancelled within ~2 s, no dialog. "Lock now" → no dialog while locked; after unlock the run reads cancelled. No floor line in the log.

      • #599 amendment (2026-10-06) — the running model's liveness. The facts:

        • What users saw. status().healthy was the start's health check, never re-read (RuntimeManager.last). During the #594 hang (b9849 Vulkan, GTX 1070 Ti) the sidecar answered neither chat nor /health at 0 % CPU, and for 4½ minutes the AI Model screen and Diagnostics said "running, healthy". A CPU-mode crash was worse: the ladder dropped its exit (onUnexpectedExit returned for backend !== 'gpu'), so every surface kept saying "running" and each later turn failed on the dead port until the user pressed Stop runtime, then Use this model (a restart of the same model was a no-op).
        • What a probe can see (b11146 source, server-context.cpp): /health is answered by the HTTP thread, so it catches a frozen or suspended process but not a wedged compute loop. /slots and /metrics go through the task queue and block during a legitimate long batch, so they cannot tell slow from wedged either. Only the CB-5 watchdog sees a wedged loop.
        • The "starting" gap. startingModelId is set only when the load begins, after startModelRuntime's weight check — minutes on a freshly copied drive. A document summary asked in that window failed with "No AI model is running… start one first".

        Owner decisions (2026-10-06).

        • Probe /health on status reads, cached about 10 s; no background timer.
        • A RuntimeUnresponsiveError marks the model unresponsive until the next completed answer or a restart; a passing /health cannot clear it.
        • The AI Model card shows "Not responding" with a one-click Restart. The app offers the restart and never performs it: from outside, a long CPU prefill and a wedge look alike. Diagnostics keeps its healthy/unhealthy wording.
        • An unresponsive GPU is not a GPU fault: nothing persists gpuAutoDisabled for it.
        • A CPU-mode crash restarts the model once per model per session, with a notice; a second crash of that model leaves it stopped, with a notice.
        • "Is starting" counts from the start request: "The AI model is starting. Try again in a moment." Chat's waiting screen gets a matching title; a stale "no model" banner clears when the model is back.

        As built.

        • RuntimeManager (runtime/index.ts):
          • refreshHealth() re-probes the running runtime's /health at most once per HEALTH_PROBE_TTL_MS (10 s). Concurrent reads share one probe, a probe that outlives a stop or switch is discarded, and each probe is bounded by the sidecar's own 3 s timeout. The getRuntimeStatus handler awaits it, so Diagnostics, the AI Model card, Chat and the Copy report all read a fresh verdict.
          • The generation gate sets wedged when a stream ends with RuntimeUnresponsiveError and clears it when one completes unaborted; a new runtime starts clear.
          • status(): healthy is false and unresponsive: true while wedged or after a failed probe. startRequested comes from beginStartRequest(), which startModelRuntime opens at its top and releases in a finally; isStarting() folds it with startingModelId.
          • restartCurrent() = forceRestart(currentOpts, 'switch'): the same model with the options it was started with, its in-flight answers ended as a switch ends them (#600). A start already in flight (a crash restart, a switch) replaces the runtime anyway, so a Restart then joins it. stopCrashed(modelId) drops a crashed runtime without the model-stop hook, and only when it fails its health check: a late or duplicate report must not take down the runtime that replaced it.
          • The "starting" window has an owner (startingClaim): only the last start() / forceRestart() that claimed it clears it. Comparing model ids let a start whose warm-up crashed clear the window of the crash restart queued behind it.
          • The watchdog verdict is matched by name (an Error named RuntimeUnresponsiveError), so the manager imports no concrete runtime (spec §9.2). The probe cache runs on performance.now(): a wall clock stepping back would stop the probes.
        • The CPU crash (factory.ts): the ladder routes a non-GPU unexpected exit to onCpuCrash once its backend label has settled (before that, 'cpu' is only the default: a rung-1 server dying before its GPU probe resolves keeps its pre-#599 path). createCpuCrashAutoRestart restarts once per model id (main.runtime.crashRestarting), then calls stopCrashed (main.runtime.crashStopped). Overlapping reports while a restart or stop is in flight count once (since #656 LlamaServer itself reports one death once — Node may emit 'exit' after 'error' — so the guard only keeps a re-entrant report out), and a crash during a lock does nothing — the restart is neither spent nor announced. It is wired in main/index.ts through the AUD-02 guardedCrashRestart the GPU and speculative handlers now share, and audits runtime_crashed.
        • The restart IPC: runtime:restart (restartRuntime), gated on the unlocked workspace like startRuntime; it aborts a deep-index build first and audits runtime_started ("restarted").
        • "Is starting": assertChatStreamReady (chat and document answers) and both doc-task guards throw main.modelStarting while isStarting(); the friendly task-error filter keeps it. Since #620, startSkillRun refuses a direct tool (redaction, edit) the same way while no runtime is active (Skills record §21 "#620 amendment"). shared/runtime-status.ts isModelStarting(status) is the one reader-side definition: the local API's model gate (model_starting), Chat's waiting screen, the engine update's busy check (an update during a weight check would resume the previous model behind the user's back), its post-update resume, the demo → real engine restart and the benchmark's start-in-flight check.
        • The UI: the running card's "Not responding" badge, hint and Restart button (design-guidelines §11.22) — a Restart re-reads the status at once, so the card shows the reload instead of "Not responding"; Chat's waiting screen title chat.noModel.startingTitle and the clearing of a stale main.noModelRunning / main.modelStarting banner on any status read that finds the model running (a quick restart is often over by the re-read after the refusal). A crash's own message stays: it explains why the question has no answer.

        Not covered.

        • A wedged compute loop with a live HTTP thread reads healthy until an answer runs into the watchdog (up to 10 min per batch, #598); /slots cannot tell slow from wedged.
        • The Performance screen's "loaded now" reads healthy, so it says "not loaded" while the model is unresponsive — honest, but not a separate state.
        • The restart budget is per app session: a lock and unlock does not reset it.
        • Accepted: on a frozen process a status read takes up to 3 s (the probe's bound), once per 10 s. Answering from the cache and probing in the background would leave a screen that does not poll (the AI Model screen while a model runs) showing "Running" until it is reopened.
        • Accepted: one failed probe marks the model "Not responding" — a machine too overloaded to answer /health within 3 s can show it while an answer still progresses. A later passing probe clears it, and the restart stays the user's click (the owner's "never automatic").

        Tests.

        • runtime-manager.test.ts "liveness of the running model (#599)": the watchdog mark and what clears it, the probe, its 10 s cache and a probe outliving a switch, Restart, stopCrashed, the start request; and "GPU mid-session crash auto-fallback through the real manager (REL-1)": the GPU fallback once, then the CPU crash budget through the real forceRestart/stopCrashed.
        • runtime-ladder-exit-wiring.test.ts "a CPU-mode crash restarts the model once per session": the real sidecar exit wiring through the ladder and the restart policy.
        • core-model-ipc.test.ts "liveness of the running model (#599)": the status read probes, a start counts from the request (held inside the weight check), Restart.
        • chat-ipc.test.ts, doctasks.test.ts (the "is starting" refusals, the friendly filter), local-api-server.test.ts (the gate), ModelsScreen.test.tsx, ChatSendFailure.test.tsx.
        • engine-consent-ipc.test.ts (an update during a start's weight check is refused).
        • All 45 rules were mutation-checked.

        Real app (2026-10-06, DesktopDiT, dev build over CDP, b11146, the 4B in CPU mode).

        • A CPU crash mid-answer (taskkill /F): the turn ends with main.chat.connectionLost; the restart notice shows; the model is back on a new process 7.0 s later and the next chat answers. A chat sent within ~0.6 s of the kill still meets the dead process (Windows reports the exit after the socket reset) and gets the same crash copy.
        • A second crash of the same model (idle): it stays stopped, with the second notice; a chat then gets main.noModelRunning.
        • A frozen process (NtSuspendProcess): a read inside the 10 s cache still says healthy; the next read takes 3.0 s (the probe's bound) and returns healthy: false, unresponsive: true; the card shows "Reagiert nicht" + "Neu starten" (German UI). Restart takes 5.2 s, the frozen process is gone, and the next chat answers.
        • A chat during a model start: startRequested: true and main.modelStarting.
      • #613 amendment (2026-10-06) — "Send again" for a question that got no answer. The facts:

        • A dead end. An error, a crash or a stop before the first word leaves the conversation ending in the question. "Try again" renders only on the last assistant turn, in chat mode only (SKA-37). The error banner offered no retry, although main.chat.connectionLost and the CPU-crash notice say "send your message again". The user retyped the question, and the next send dropped the orphan from the prompt (collapseToAlternating), so it was never answered.
        • Only early ends are marked. #600 and #612 mark the question for a Stop, a lock or a model stop. An error (a crash, a server error, an empty completion, an overflow) leaves it unmarked, and its banner is gone after a reload or a conversation switch. The anchor is therefore the transcript's tail, not the mark.
        • Main could already re-answer from history (deleteLastAssistantMessage deletes nothing when the tail is a question), but F2's pre-stream hasRegenerableAssistantReply refuses a user tail. Relaxing it would bring SKA-37 back: a stale "Answer without it" or offer click would re-answer a later question. The resend is therefore its own intent on the wire.

        Decisions (the issue's candidate fix; the design calls taken as recommended defaults).

        • One "Send again" under the last question while no answer follows it, in chat and documents mode. It is always shown, never hover-revealed: it exists only in that state, and it is the way on. The banner gets no button of its own.
        • It answers the stored question in place: nothing is appended and nothing is deleted.
        • Depth and skill are the composer's, the arguments a send from it would carry. An untouched composer lets main resolve the saved default and score the stored question for auto-fire, as the first send did. A routed run's question keeps the run's own skill and document instead.
        • The "Not answered" note names the latest attempt's cause.

        As built.

        • The wire. ChatOptions.resendMessageId on chat:send; a 6th askDocuments argument, resendMessageId, on rag:ask. regenerate wins when both are set; content is unused.
        • Main. Both handlers call one precondition, resendableQuestion (chat-stream.ts). It reads getUnansweredQuestion (the last visible message when it is a user turn; compaction rows skipped). A different id, or none, refuses with main.chat.nothingToResend before any stream or write. The chat branch hands the stored question to resolveTurnSkillFromRegistry. The documents branch makes it text, so retrieval, the filename auto-scope and the skill engines all see it. The guard runs with regenerate: false.
        • The mark. markUnansweredOnEarlyEnd calls clearUnansweredMark before runFn, so only once the slot is held. A refusal before that (no model, busy, a stale skill id, a Stop during the slot handoff) keeps the old cause; an attempt that ends early marks the question again. For a plain send or a regenerate the tail carries no mark, so the call changes nothing there.
        • The renderer. Transcript derives resendableId: the last message when it is a user turn, but not while this conversation streams. MessageBlock renders a .msg-actions-resend row with one .msg-action, "↺ Send again". The trailing question's old note is hidden during that stream too. ChatScreen.onSendAgain calls stream(…, resendMessageId) with turnSkillArgFor and depthFor, guarded by sendInFlightRef (the CH-14 rule); there is no optimistic bubble. The stale Transcript.tsx SKA-37 comment ("covered by the error banner") now points here. Design record: design-guidelines §11.21 "#613 amendment".
        • When ChatScreen offers it (canSendAgain), found by the review of the change:
          • only once the recovery effect's tick has found nothing in flight for this conversation (idleCheckedId). A fresh remount mid-reply lists the question main is still answering a moment before that tick flips recovering, and a click there met streamInFlight and broke into a working reply. A tick that gave up after STREAM_RECOVER_FAILURE_BUDGET failed reads (CH-4) unlocks the composer but found nothing out, so it leaves the gate shut (#742);
          • never under an optimistic bubble (isOptimistic): a failed send whose refresh also failed keeps one, and main has no question with its id;
          • a routed question (the Summarize / Categorize relay, documents mode) keeps its run's skill and document pin (routedTurnRef), which the composer never showed. Without them the re-ask skipped the run's 0-model-call handler (C2) and spread over the whole scope (ux-6).

        Not covered.

        • Only the last question can be sent again. An older unanswered question keeps its note, and the next send still drops it from the prompt.
        • A routed question keeps its run's skill and pin for one visit of the Chat screen. After a remount or a reload it is resent under the composer's skill and the ordinary scope.
        • A send refused before its question was saved (no model, busy) leaves nothing to resend; the draft goes back into the composer (CR-1), as before.

        Tests. Each fails on the pre-fix code. Ten rules were mutation-checked: the auto-fire text, the shared id check, the clear, both streaming gates, the in-flight-check gate, the optimistic guard, the routed skill and pin.

        • chat-ipc.test.ts "(#613)": answered in place, the model gets the question once; the two refusals; auto-fire on the stored question.
        • rag-regenerate-ipc.test.ts "Send again": the documents twin and its refusal.
        • chat-stream-regenerate.test.ts "(#613)": a resend that fails with an error drops the old cause.
        • TruncatedNotice.test.tsx "(#613)": placement, the label in EN and DE, the streaming gate.
        • ChatSendFailure.test.tsx "(#613)": a crash, one click, the question once and the banner gone; no button under an unsaved bubble; the documents channel.
        • ChatStreamRecovery.test.tsx "(#613)": nothing under the question until the in-flight check comes back empty.
        • SkillRunLifecycle.test.tsx "(#613)": a routed question is resent with the run's skill and pin.

        Real app (2026-10-06, DesktopDiT, dev build over CDP, the 4B in CPU mode on b11146, a plaintext-dev root with E:'s e5). Every button was clicked in the DOM; German and English UI.

        • A Stop before the first word (a 4,917-character question): the note and "↺ Noch einmal senden" sit under the question. During the answer the question shows once, with no note and no button; afterwards there is one question and one answer, and its ended_early is cleared. After a reload the transcript is the same.
        • A crash mid-prefill, through the UI (Send, then the chat sidecar killed). The first crash of the session showed #599's "Das KI-Modell startet" screen for ~4 s, then the question with its button; one click answered it. A second crash left the model stopped (#599). The transcript then showed the question, "↺ Send again" and the connectionLost banner together; after "Use this model", one click answered it.
        • A document chat whose model was stopped mid-prefill: "Nicht beantwortet – das KI-Modell wurde beendet." After the restart, one click gave a grounded answer citing the document.
        • With the model stopped, a remounted Chat shows its no-model state, not the transcript. Its question kept its 'user' cause through the stop, the start and the remount, and was answered with one click once the model was back.
    • Friendly-error chain in withChatStream (rethrow-friendly, mapped copy on BOTH the chat:error event and the invoke rejection): RuntimeUnresponsiveError → main.chat.runtimeUnresponsive, RuntimeConnectionLostError → main.chat.connectionLost (#600), EmptyCompletionError → main.chat.emptyCompletion, ChatStreamError → main.chat.streamError, overflow → main.model.contextExceeded, else raw. Composition: CB-2+CB-4 (a regenerate that produces nothing never loses the prior answer, whether it stops or completes empty); CB-3+CB-6 (the fence reorder supplies the compaction pre-pass's reservedTokens).
    • CB-7 (per-token IPC batching) — DEFERRED. The renderer already coalesces re-renders (the ChatScreen flush timer); the only residual cost is a structured-clone of a short string, and batching would add a lifecycle seam to the most safety-sensitive path (streamSettled teardown) for a negligible, unmeasured gain. Revisit only if profiling shows contextBridge volume is a real bottleneck.
  • Stream recovery across navigation. The Chat screen is unmounted when the user switches screens, which destroyed its streaming state + token listeners while the main-process generation kept running — on return the fresh screen looked idle yet a new message was rejected ("a response is already being generated"). withChatStream now mirrors the accumulated answer + reasoning into a shared streamBuffers snapshot (in ipc/inflight.ts, cleared in lockstep with the AbortController); both sendToken and the new sendReasoning it hands runFn write to it, so the chat + RAG paths buffer identically. The read-only getActiveStream(conversationId) IPC returns the live snapshot (or null). On mount/conversation-change the Chat screen, when it does not itself own a stream, polls getActiveStream (STREAM_RECOVER_POLL_MS, only while one is in flight) and drives the same streaming UI (live bubble via streamText/streamThinking, locked composer + Stop) through a derived busyStreaming = streaming || recovering. The token events missed while unmounted are not replayed — the snapshot carries the full accumulated text, so the bubble resumes complete. Completion (snapshot → null) refreshes the transcript from the DB. Re-selecting the streaming conversation on remount (2026-07-01). The poll above only re-attaches when the visible activeId already points at the streaming conversation — but a fresh mount resets activeId to null (it was never persisted), so on return the screen showed an empty new chat while the reply streamed invisibly (and, since the one-stream guard is per-conversation, that empty conversation would even accept another turn). The Chat screen now, on mount with activeId still null, calls the read-only listActiveStreamConversations IPC ([...inFlightStreams.keys()], in-memory + workspace-agnostic like getActiveStream) and, if a generation is in flight, selects that conversation (most-recent = last key) and mirrors its mode — the existing recovery poll then re-attaches. Guarded so it never clobbers a deliberate mid-load click and never yanks the user onto an old conversation when nothing is generating.
  • FE audit 2026-07-07 — Chat renderer correctness (CR-1…CR-9). A renderer-side sweep of ChatScreen.tsx + Transcript.tsx (ledger + per-finding CR-n disposition in §45, where the audit and plan were retired) hardened the send/switch/stop paths without adding an unstable prop to a memoized child on the keystroke/flush hot path. The load-bearing decisions:
    • CR-2 (transcript scroll bleed) — key={activeId ?? 'new'} on the Transcript instance, NOT a reset-on-effect. A fresh instance per conversation resets atBottomRef + DOM scrollTop and the mount scroll effect re-pins to the newest message. Keying on activeId (not messages) is decisive: an intra-conversation refreshIfVisible and a streaming reattach keep activeId stable → the key is stable → React.memo still skips the transcript on the hot path; only a genuine switch (rare) pays the remount. Keying on messages would remount on every flush and defeat the memo.
    • CR-9 (Stop target) — onStop targets streamConvId ?? activeId; latent hardening, byte-equivalent today. Reachability: ConversationList disables every non-active row while streaming (disabled={streaming && !active}, fed streaming={busyStreaming}), and every activeId-mutating path is busyStreaming-guarded, so the Composer's Stop only ever renders in a state where streamConvId === activeId (local OR recovered stream). The one-line change future-proofs Stop if a later change relaxes the disabled-row guard — that guard must not be relaxed without re-checking onStop. ChatSwitchStop.test.tsx (T-2) pins the disabled-row invariant so it reddens first.
    • CR-1 (draft loss) — restore into a still-empty composer, only when the user turn did not persist. stream reports persistence from its post-failure listMessages (no new IPC); onSend restores with a cur === '' guard (newer in-flight typing wins) so a routine pre-persist reject (DOC_TASK_BUSY / no model / slot held) never eats a typed question, while a stopped-partial / errored-after-persist turn does not duplicate. CR-4 confirms a recovered stop in the recovery tick's completed branch (no local stream() finally there — M-U2 parity). The local finally confirms a stop only when the send came back (sendSucceeded): a stopped send resolves, so a failed one is a real failure that beat the Stop to main, and its banner already explains the end (#742). CR-5 branches the send on the conversation's own mode (conversations.find(...)?.mode ?? mode) so a reattach that failed to mirror mode still routes a documents send through askDocuments. CR-6/CR-7 clear the error banner on activeId change (effect ordered before the history load) and add the sibling activeIdRef.current === convId stale-response guard to the three switch-time loads. CR-8 drops depths['new'] in ensureConversation (SKA-18 parity — a 'new'-composer depth pick must not become every later new chat's default). Tests with teeth: ChatStreamRecovery.test.tsx (T-1: recovery bubble + CR-4 stop + CR-5 routing + re-select guards), ChatSendFailure.test.tsx (CR-1), ChatSwitchStop.test.tsx (T-2 + CR-2). CR-10 (transcript windowing) stays the accepted PERF-2 chat half; CB-*/DB-* findings are other sessions of the same wave.
  • FE audit 2026-07-07 — Documents renderer polish (DR-1…DR-9). The Documents half of the same sweep (DocumentsScreen.tsx + screens/documents/{DocRow,SectionRail,format}.tsx; ledger + DR-n disposition in §45, where the audit and plan were retired). Two of the nine tighten invariants rather than merely patch: DR-4 replaces the screen-global previewLoading boolean (which flipped a memo-busting prop on every windowed DocRow twice per preview) with a per-row previewLoadingId === d.id — the clicked row gets true, every other row a stable false, so DocRow.memo now holds on a preview open (DocumentsScreenPolish.test.tsx asserts row B's render-count delta is 0; DocRow's boolean prop is unchanged). DR-2 funnels every refresh() caller (poll tick, toolbar, run, mount) through one monotonic refreshSeq choke point — an older listDocuments snapshot can no longer clobber a newer one and stick once the poll interval clears, reducing spurious full-list swaps (revert-confirmed teeth). The rest: DR-1 the preview "Show more" updater returns cur (not next) on id-mismatch/closed-modal so a late page can't resurrect a closed modal or clobber a doc-task's auto-opened preview (revert-confirmed); DR-3 the toolbar Refresh onClick catches the rejection into the banner (every other call site already did); DR-5 Import is gated on busy !== null (all four buttons) so a concurrent bulk re-index can't fight the single busy scalar — main-side job exclusivity stays the correctness backstop, the label still keys on 'import'; DR-6 archived projects get the active class + aria-current (mirroring active projects) so a selected archived section is visible to the user and screen readers; DR-7 a failed doc-task's persist-canonical error runs through localizeServerCopy so the de-AT UI stops leaking raw English; DR-8 a first-mount role="status" spinner (new docs.loading key, both locales) fills the docs === null gap that used to render blank; DR-9 formatSize gains a GB tier (locale decimal unchanged). All additive/renderer-only; the FE-4 mountedRef setState-after-unmount guards and the PERF-2 windowing path are untouched. CB-*/DB-* are other sessions of the wave.
  • MockRuntime.chatStream emits a deterministic reply token-by-token with a small delay so the renderer's streaming + stop path is exercised with zero model files. The real LlamaRuntime (Phase 10) swaps in behind the same ModelRuntime interface.
  • Markdown rendering (post-MVP). Assistant replies (persisted and streaming) render as GitHub-flavored Markdown + KaTeX math via Streamdown (@streamdown/math), a streaming-aware drop-in for react-markdown — local models emit Markdown, and raw **asterisks** read as broken output. Streamdown builds React elements (no innerHTML). Its rehype chain is pared to rehype-sanitize only (we drop rehype-raw so model HTML renders as literal text — the no-injection posture is unchanged — and drop rehype-harden as redundant under the CSP + the link gate below). The math plugin's rehype-katex step runs after that chain, so KaTeX's own output is not sanitized; its gate is KaTeX's trust option, which nothing sets (DEP-7 record §3, pinned in assistant-markdown.test.tsx). The app ships no Tailwind, so Streamdown's one non-semantic element — **bold** as a styled <span> — is mapped back to <strong>; every other element is already semantic and styled by the existing .md CSS. The components/plugin objects are module-level in AssistantMarkdown.tsx so their references stay stable across the ~40 ms flush — an inline object would defeat Streamdown's block memoization (see FE-1, measured); linkSafety stayed an inline object until #685 (DEP-6 §13). Links are whitelisted to http(s) and get target="_blank" so the main process's window-open handler routes them to the OS browser and denies everything else (superseded in part by #236, PR #287: the handler now routes them through a native confirmation naming the site — main/external-open.ts; the in-app denial is unchanged). User turns stay plain text — they are not Markdown and must not be reinterpreted.
    • KaTeX math — a deliberate win for tax / finance / accounting users. The whole point of an offline local-LLM workspace for a tax professional is to reason over numbers: effective rates, depreciation schedules, apportionment, $$r = \frac{tax}{base}$$-style formulae. Before this, a model that emitted LaTeX math showed raw \frac{…}{…} noise; KaTeX now renders it as typeset math inline in the answer, persisted and live. Fonts bundle as local assets (out/renderer/assets/KaTeX_*.woff2/ttf) so it stays fully offline under font-src 'self' — no CDN, consistent with the no-cloud rule. Delimiters are $$…$$ / \(…\) / \[…\], and a single $…$ span is promoted to inline math only when it looks like math (#501): Pandoc's rule (no space just inside the delimiters, no digit right after the closer, same line) plus a TeX signal (\ ^ _ { } = + < > |) or a one-or-two-letter span like $x$. remark-math's own single-$ mode stays off, so prose like "owes $5 and $10", $HOME/$USER and escaped \$ are never mangled.
    • Display $$ and the live bubble (#701, AssistantMarkdown.tsx). remark-math's flow construct takes $$ only alone on its fence lines. Models write display math otherwise, so before this, TeX on the opening line was dropped as the fence's "meta" (an empty block), TeX glued to the closer kept the block open to the end of the answer (\end{aligned}$$: one KaTeX error box), and a one-line $$ x $$ paragraph rendered inline (the 4B's own shape). A $$ … $$ pair on lines of its own is now rewritten into the fence form at its line's indentation (canonicalizeDisplayDollars), as a line-anchored \[ … \] always was. That rule now keeps the indentation too, so a formula in a list item stays in it. A fence keeps an indentation only under four columns (fenceIndent): four or more, or a tab, is an indented code block outside a list, so such a line keeps its earlier reading (a \[ drops the indentation, a $$ pair is left alone). A pair sharing its line with prose stays inline, as do $x$ and \(x\). A lone $$ at the start of a line (a stopped or cut-off turn) keeps the TeX on its line: typeset if it parses, else KaTeX's error text. A \[, \], \( or \) whose backslash is itself escaped is no delimiter: \\[2pt] is a TeX row break. While streaming, the remend handler (trailing-math, priority 10) completes a dangling \[, \(, $ or $$ through completePartialTex, which KaTeX validates, or hides it for that flush. Before this, a dangling $$ went to remend's own katex handler, which only appends the closer: the error box until the TeX parsed (~200 ms in the real app). Four details keep the bubble free of error boxes:
      • A lone $ at the end counts as half a closer.
      • \\[2pt] is no \[ opener here either. Read as one, it hid the rest of the answer.
      • A completed display tail ends in a newline, so the closers remend's later handlers append cannot glue to its fence.
      • An unmatched [ inside a formula is spelled \lbrack (with the space), the same glyph and spacing. Otherwise remend's links completion read it as an unfinished link, appending ](streamdown:incomplete-link) after a half-open interval like [0, 1), or into a formula still streaming. The handler completes a dangling $$ only when it is the last of the trailing prose segment; one that lies before a code span is left to remend's katex handler, as before. The persisted turn renders statically, without remend, from the model's own TeX. The two passes cost under 1 ms per flush on a 20 KB answer. Known limits:
      • An environment (\begin{aligned}) or a \left streams hidden until it closes.
      • A line that starts with $$x$$ and goes on in prose streams as display until the prose arrives, as \[ x \] does.
  • Runtime requirement (decision). sendChatMessage does not auto-start a runtime: a chat needs a started model (RuntimeManager.start()). With no active runtime the handler throws and the Chat screen shows a "start a model" empty state that links to Models (and polls getRuntimeStatus so it flips to the composer by itself once the background auto-start — see the Models section — finishes loading). Rationale: starting the real llama.cpp sidecar mid-request is heavy and surprising; the startup auto-start is a deliberate, bounded exception that reuses the same gated start path.
  • IPC (ipc/registerChatIpc.ts). Single source of truth: the chat group in shared/ipc.ts — enumerate there, not here, so a new channel can't leave this list stale (D-6, Chat & Documents audit 2026-07-07). The notable families: conversation lifecycle (createConversation, listConversations, listMessages, deleteConversation, searchConversations — Phase 31 full-text); streaming (sendChatMessage, stopGeneration, getActiveStream + listActiveStreamConversations for stream recovery / re-selecting the in-flight conversation after navigation); scope / anchor (updateConversationScope, setConversationScope, setConversationCollection, setConversationDefaultSkill); attachments / context (listAttachments, getConversationContextUsage, getConversationSummary); and export (exportConversation, exportMessageTable). Note suggestSkills appears in this group in shared/ipc.ts but is registered by the skills IPC (registerSkillsIpc), not here. Regenerate reuses sendChatMessage with options.regenerate — it deletes the last assistant message, then re-streams from history. deleteConversation removes a conversation (chat or document Q&A) and its messages; it refuses while a stream is in flight for that conversation (the persisted assistant turn would otherwise resurrect/violate the FK after the delete).
  • Conversation search (Phase 31, wave-3 plan §4). messages_fts (FTS5, content + message_id UNINDEXED) mirrors the chunks_fts design exactly: self-contained (not external-content — VACUUM renumbers implicit rowids), three sync triggers on messages (insert / delete / update-of-content), guarded migration + one-time backfill in openDatabase (ensureMessagesFts). Messages are persisted with think blocks already stripped (Phase 20 D6), so reasoning is never indexed. searchMessages(db, query, limit) (services/chat.ts) sanitizes via the SHARED buildFtsMatchQuery (lifted from rag/hybrid.ts into services/fts.ts), ranks bm25 with a newest-first tie-break (D23) and groups hits per conversation (conversations ordered by their best hit). Snippets use FTS5's snippet() (verified in Electron 37 main AND system Node — research gate R-S1), matched terms wrapped in the SEARCH_MARK_* control characters so the renderer highlights without parsing HTML. IPC chat:search (preload searchConversations) is plain request/response; the search UI lives atop renderer/chat/ConversationList.tsx. The index lives inside the (possibly encrypted) DB file — encrypted at rest for free; while the vault is locked the db getter throws, so search is simply unavailable pre-unlock. Searches are never logged or audited — queries and snippets are content (Phase-19 privacy rule), and a sentinel test asserts runtime_events stays untouched.

Document ingestion (Phase 4)

  • services/ingestion/ (spec §7.7). parsers/ implements the DocumentParser interface (spec §9.2) with pure-JS adapters — TxtParser, MarkdownParser, PdfParser (pdfjs-dist legacy build, no worker), DocxParser (mammoth), CsvParser (papaparse) — each returning ordered text segments with optional pageNumber/sectionLabel. chunker.ts splits segments into overlapping ~500-token windows (overlap 80, cap 1000) without crossing segment boundaries, so each chunk inherits one page/section. index.ts orchestrates the status lifecycle (queued → extracting → chunking → embedding → indexed, failed on error) and persists to the documents + chunks tables. The embedding step embeds all chunks in one batch when an embedder is injected; without one it is a pass-through.
  • File storage decision. Imported files are copied into the workspace (workspace/documents/<id><ext> → stored_path); original_path is also recorded. The drive stays self-contained and re-indexable; delete removes the workspace copy + chunks + row (never the original).
  • Import model (decision). Async with polling: importDocuments queues rows and processes in the background; the documents table is the per-file source of truth; the job aggregate is in-memory via getImportJob. The renderer (Documents screen) polls while a job runs.
  • Parser libs are external (externalizeDepsPlugin in electron.vite.config.ts) so the large pdfjs ESM bundle is require/import-ed from node_modules, not bundled (R3).
  • Read-only preview (post-MVP). extractDocumentPreview re-parses the stored copy on demand and returns the parser's text segments (page/section labels intact) for an in-app modal. It re-parses rather than reading chunks because chunks OVERLAP (~80 tokens) — concatenation would duplicate text at every boundary. (Exception: AUDIO documents read from stored chunks instead — exact by construction and avoids a minutes-long re-transcription; see "Audio transcription" below.) In an encrypted workspace the .enc copy is decrypted to a transient .parse-preview-<uuid> working file and shredded on the way out (covered by the startup .parse* crash sweep); the original bytes are never handed to an external viewer, which is why this is an in-app TEXT preview and not a shell.openPath. The transient name carries a per-call randomUUID() infix (DB-2, Chat & Documents audit 2026-07-07): the same helper is shared by the preview IPC, buildDocumentSegmentReader, and extractSegmentTexts, so a deterministic <id>.parse-preview path let two concurrent same-doc reads decrypt into and shredFile the SAME file — each shredding the other's parse. The uniqueness closes that race; the .parse infix keeps the crash sweep covering a leak. The two export readers (.parse-export-<uuid>, .parse-export-bin-<uuid>) got the same fix.
  • IPC (ipc/registerDocsIpc.ts). Single source of truth: the docs group in shared/ipc.ts — enumerate there, not here, so a new channel can't leave this list stale (D-5, Chat & Documents audit 2026-07-07). The notable families: import (pickDocuments → importDocuments → getImportJob, plus importPreflight, the Phase-36 size-aware audio confirm); listing + lifecycle (listDocuments, deleteDocument, setDocumentLifecycle, addToCollection/removeFromCollection); single + bulk re-index (reindexDocument; startReindexAll/getReindexAllJob/cancelReindexAll); bounded preview (previewDocument, previewDocumentPage); and export (exportDocument, exportSummary, exportDocumentOriginal). See the "Document organization" §5 IPC table; full pipeline detail lives in rag-design.md.
  • Original-file export (issue #90) — design record. docs:exportOriginal saves a document's stored ORIGINAL bytes — any format — to a user-chosen file. Decisions: (1) a NEW channel, not a widening — docs:export stays text-only because the Translate screen shares its save-as-Markdown semantics, and EXPORTABLE_TEXT_EXTENSIONS stays its gate; (2) the reader is the existing D77 readStoredDocumentBytes (stored .enc-aware copy first, original_path fallback, decrypt transient shredded in finally) — no new byte path; (3) the DocRow menu gate became a deliberate split: generated docs (d.origin) keep the text "Export", IMPORTED docs get "Export original file" — before #90 imported documents had NO export action at all (the reported bug); (4) the write is the shared saveBinaryExport (ipc/save-export.ts), hoisted from registerSkillsIpc's module-local DOCX writer and upgraded to the evidence-pack atomic tail (tmp sibling → fsync → rename), which the skills DOCX export now gets too (the skills TEXT exports — the CSVs, invoice JSON/XML, redacted.txt/edited.txt — took the same tail through saveTextExport only with #838); (5) the byte read holds the beginDocumentWork lease (released before the dialog opens) so it cannot interleave with a password-change re-key of the sidecar; (6) consent + boundary per the evidence-pack §24.3 posture — renderer ConfirmDialog warning before the native dialog, same copy in the dialog message; audit document_exported {documentId} ONLY. Bulk/multi-select export was deliberately deferred (single document per invocation). Boundary detail: security-model.md "Document original export boundary (#90)".

Audio transcription (Phase 36, wave-3 plan §9)

A recording (.wav/.mp3/.flac/.ogg — exactly what the pinned binary decodes, R-W2) becomes a normal corpus document: transcribed locally, chunked, embedded, searchable, citable with time ranges ("ask your meetings"). m4a/aac is descoped (no bundled ffmpeg); it fails with friendly convert-to-WAV/MP3 copy.

  • services/transcriber/ — the second sidecar family. A Transcriber interface (transcribe(filePath) → TranscriptSegment[{ startMs, endMs, text }]) behind availability selection: createSelectedTranscriber returns the real backend iff the runtime/whisper.cpp/<os>/whisper-cli binary AND the models/transcriber/ GGML weights exist, else null — the reranker D9 pattern, deliberately no mock (an invented transcript would silently corrupt the corpus). Missing transcriber ⇒ the audio FILE fails friendly ("Audio import needs the transcription model — download it on the AI Model screen") through the documents-table error path; text ingestion is untouched.
  • D34 (resolved by R-W1): per-file CLI, not a server. whisper.cpp v1.8.6 ships prebuilt binaries for Windows only (so a server gives no per-OS lifecycle win), the CLI emits -pp progress + progressive segments while it works, there is no multi-hundred-MB upload over loopback, and cancel/lock-suspend is just killing the child. WhisperCliTranscriber spawns the pinned CLI per file (-oj JSON to a transient .parse-transcript.json in the documents dir — content, shredded after, crash-sweep-covered), parses transcription[].offsets (ms). The exit code is NOT the success signal (R-W2: a decode failure exits 0 with stderr-only complaints) — success = the JSON exists and parses; the error tail keeps stderr only (stdout carries the transcript, which must never ride an error message into logs). suspend() (workspace lock) and stop() (will-quit) kill in-flight children; the failing parse marks that document failed and the decrypted transient is shredded.
  • Cancellation & watchdog (backend audit 2026-06-27, REL-1/REL-6). Audio is EXEMPT from the wall-clock withParseTimeout (a long recording legitimately transcribes for many minutes), so two mechanisms bound a wedged/cancelled child instead: (1) an inactivity watchdog in run() — whisper emits -pp progress continuously, so the watchdog is reset on every stdout/stderr chunk and only fires when the child has been completely silent for idleTimeoutMs (default 15 min, HILBERTRAUM_WHISPER_IDLE_TIMEOUT_MS), distinguishing a spinning/hung child (no output → killed + rejected) from a slow-but- advancing one (keeps resetting); (2) a real AbortSignal now threaded end-to-end (IngestionDeps.signal → ParseContext.signal → AudioParser → transcribe), so the import loop aborts the in-flight transcription the moment the workspace locks mid-job (registerDocsIpc per-job AbortController; belt-and-suspenders with suspend()). The previously-dead abort listener in run() is now armed. REL-6: TranscribeOptions.workDir is now required (no OS-tmpdir default) — the transient transcript is recognised speech (content) and must stay inside the .parse crash sweep; an empty workDir fails closed before any spawn. The watchdog/timeout errors carry only durations, never any transcript. SIGKILL escalation (full-audit 2026-06-29, REL-2): the watchdog, the abort handler, and suspend()/stop() previously sent a bare child.kill() (SIGTERM) and waited on close — with no escalation. A whisper-cli wedged in native decode code that ignores SIGTERM never emits close, so the watchdog "fired" but the slot stayed held, and suspend()/stop() (on lock/quit) awaited an exit that never came — hanging teardown indefinitely with the transient still on disk. All three kill sites now route through killWithEscalation, which mirrors LlamaServer.stop(): SIGTERM, then SIGKILL after killGraceMs (default 2 s) if the child hasn't gone (grace timer unref'd + cleared on a clean exit). And suspend()/stop() bound their cleanup await with suspendTimeoutMs (default 10 s) so a child that ignores even SIGKILL can't hang quit/lock — past the cap the .parse crash-sweep is the shred backstop.
  • AudioParser implements DocumentParser. parse(filePath, ctx) uses the transcriber injected per call via the ADDITIVE ParseContext (carried from IngestionDeps.transcriber — the embedder-injection precedent; text parsers ignore it). Whisper segments are packed into paragraph-sized ExtractedSegments (~180-token target, hard cap AUDIO_SEGMENT_MAX_TOKENS = chunkSizeTokens − 100 = 400, a margin below the 500-token chunk window) labeled sectionLabel: "mm:ss–mm:ss" (h:mm:ss above an hour) — D29: the time range rides the EXISTING Citation.section, zero citation-path changes. The cap is measured in approx-tokens (approxTokenCount, CJK/Thai-aware), NOT whitespace words (RAG-N1, full audit 2026-06-28 Phase 4): a space-less phrase is a few "words" but hundreds of tokens, so a word cap let an audio segment overflow the window and the chunker then windowed+overlapped it. Packing matters twice: distinct labels never coalesce in the chunker (raw whisper segments would mean thousands of tiny chunks), and the ≤AUDIO_SEGMENT_MAX_TOKENS cap makes each audio chunk one packed segment, verbatim, no overlap — so reconstruction has no duplicated/dropped spans — which is why extractDocumentPreview (and through it translate/compare re-extraction) reads audio text from the STORED CHUNKS instead of re-transcribing for minutes. (Exception: the rare oversize-single-segment split re-coalesces and may normalize a piece boundary to one whitespace — never a dup/loss; see rag-design.md §2 "Audio packing" / §3 windowing.)
  • D35: the audio original is KEPT (the locked Phase-4 copy-into-workspace contract + reindexDocument re-parsing the stored file force it), encrypted (.enc) on encrypted workspaces; a re-index of an audio document is a full re-transcription (no transcript cache — known-limitations.md). Large audio (>50 MB picked) gets an explicit import confirmation (importPreflight IPC → summarizeImportPaths).
  • Progress. The CLI's -pp lines (~every 5%) flow transcriber → ParseContext.onProgress → IngestionDeps.onTranscribeProgress into an in-memory map in registerDocsIpc, merged into listDocuments responses as DocumentInfo.transcriptionProgress — the polling UI shows "Transcribing… N%" on import AND re-index with no new channel (R-W4: a 52-min mp3 ≈ 35 min wall on the dev CPU, peak RSS ≈ 1.2 GB with the small model — honest progress is mandatory).
  • Audit: the existing document_imported (filename, document id, status, chunk count — never content) covers audio; the transcript is CONTENT and never reaches runtime_events (sentinel-tested end-to-end).
  • #869 amendment (2026-11-18): every whisper-cli child starts in the documents folder and gets an ASCII command line, or none at all. The pinned whisper-cli (v1.8.6, Windows x64) has a narrow main and, unlike llama-server since b12110 (#729), no UTF-8 activeCodePage manifest (PE read), so Windows fills its argv in the ANSI code page. Measured with the real ggml-small model on code page 1252: a model path (-m) with an umlaut makes it die with a fail-fast exception (0xC0000409) right after "loading model from" (it exits within 0.3 s; no error dialog keeps it alive), one with characters outside the code page arrives as ? ("failed to open", exit 3) — so under a root such as C:\Users\Jürgen\AppData\Roaming\HilbertRaum or a Kit folder Übungen every import and dictation failed; an audio or output path (-f, -of) with characters of the code page (März) worked, one with characters outside it (Олена 日本) failed (-f: "input file not found", exit 2; -of: exit 0 with no transcript written). A RELATIVE path is read exactly (the OS resolves it against the child's wide working directory), so design as built, one pure planner (transcriber/argv.ts): (a) the child starts in opts.workDir — the workspace's documents/ folder — on every platform, and gets every file there (the transcript -of, a stored copy, a decrypted transient, the dictation WAV) by its bare name; (b) on Windows a model (-m, -vm) goes absolute when ASCII, else relative (..\..\models\transcriber\…), and with no ASCII spelling — a non-ASCII folder or file name in the model's path below models/ (an ASCII file name in a non-ASCII folder too), which only a user's own manifest can give — the call is refused before anything starts (WhisperPathError, log class whisper:non-ascii-path, its own row and dictation copy: main.ingest.voiceModelPathUnsupported, main.dictation.voiceModelPathUnsupported); copying gigabytes per call is no option; (c) on Windows the audio goes absolute when ASCII, else relative when ASCII (never across drives), else it is copied into the documents folder as <uuid>.parse-audio<ext> for the run: an encrypted workspace's first import parses the user's ORIGINAL file wherever it is (ingestion/index.ts), and a name or folder with characters outside the code page cannot be named to the child (the copy rule needs no knowledge of the code page, so every original without an ASCII spelling is copied, e.g. a Kit on D:\ and the file in C:\Users\Jörg\Musik\). The copy is the same plaintext class as an encrypted re-index's decrypted .parse transient: written only after the engine-install gate and the binary hash, right before the spawn; shredded in the same finally as the transcript; and under the startup crash sweep by its .parse infix. While it is being written the call has no child, so it is tracked on its own (copying): the call's signal (cancel, lock, quit) and suspend()/stop() (lock, quit, and an engine update, which suspends without aborting the import's signal) abort it; no child starts after that, and suspend()/stop() return only after the partial copy is shredded, under the same 10 s cap as a child. An engine install that begins its swap during the copy holds the spawn at the #516 gate, re-checked after the copy. macOS and Linux take (a) only — their argv is bytes, so they never copy and never refuse. Every path is resolved against the APP's working directory before the spawn (the command too, whisperCommand): the child starts elsewhere, so a relative one (a dev run's relative drive root, HILBERTRAUM_WHISPER_BIN) would otherwise be looked up from the documents folder (the #787 trap). Why the documents folder (the #787 DLL-search caveat, rag-design.md §17 D-Z1). Windows searches a process's working directory for a DLL it finds neither beside the exe nor in the system folders, and the pinned build imports MSVCP140.dll, VCRUNTIME140.dll, VCRUNTIME140_1.dll and VCOMP140.DLL, which the zip does not carry (#530); whisper-cli also calls ggml_backend_load_all, whose scanner (ggml.dll: current_path(), LoadLibraryW) looks for ggml-*.dll backends beside the exe AND in the working directory. The documents folder is the app's own and holds only names the app chooses (<uuid>…, <docId><ext>, .enc, .parse*), so nothing there can carry such a DLL name, and writing there needs the same access as writing the unhashed DLLs beside the exe; it is never the audio's own folder (a Downloads folder, what #787 rejected) nor the engine folder (an engine install replaces it while no child runs, #516). Before this, the child inherited the app's own working directory. A documents folder of 258+ characters cannot be a working directory (Node's spawn fails ENOENT, absorbed by guardChildStdio, #790): the file fails with the generic copy, as it did before (whisper-cli opens its files without a long-path prefix). The real layouts are tests/manual/whisper-smoke.test.ts "#869 layout matrix" (three roots ascii, Jörg äöü, Олена 日本: a stored file, a foreign original, a dictation with VAD; a Kit on another drive; the refusal; MAX_PATH), red on master and green here; a whisper pin bump re-runs it (runtime-sources.yaml, "To bump") and may retire (b)–(c) if upstream adds the manifest. No transcript, citation or stored-data change.

Voice dictation (Phase 37, wave-3 plan §10, decision D30)

Push-to-talk into the chat composer — a thin client of the Phase-36 transcriber. The whole pipeline (locked in D30): renderer getUserMedia audio → MediaRecorder (webm/opus) → decode + resample to 16 kHz mono via an OfflineAudioContext render → level gate (shared/dictation-level.ts, #497 amendment: a clip with no usable signal — peak under −50 dBFS, RMS under −70 dBFS or shorter than 300 ms — is refused HERE with the "check your microphone" copy, and again in main as the backstop, because the pinned whisper hallucinates a word on silence rather than returning nothing; the module records the calibration) → pure-JS WAV encode (renderer/lib/wav.ts, no new deps) → BYTES over the request/response IPC dictation:transcribe (preload transcribeDictation; no new event channels) → main writes a transient <uuid>.parse-dictation.wav into the documents dir (the .parse infix = crash-sweep coverage), runs Transcriber.transcribe(tempPath, { workDir, vad: true }) — #504: whisper-cli runs Silero VAD first (--vad -vm <model> -vp 200; the VAD model is the whisper manifest's second required files[] entry, found by name in transcriber/factory.ts), so a clip without speech decodes to NO segments; imports pass no vad — shreds the WAV in finally, returns the text. The composer (renderer/chat/DictationButton.tsx + Composer.tsx) inserts it at the cursor for review — never auto-sent; the insert prefers execCommand('insertText') so it joins the input's normal undo history. Streaming ASR is explicitly out of scope.

  • Availability-driven (D14 precedent, no settings key): AppStatus.dictationAvailable = "a transcriber is selected"; the live mic renders with it and — the #497 amendment to D30 — a visibly disabled "not installed" mic renders without it (DictationUnavailableButton: aria-disabled, a click reveals the hint that names the missing speech model plus the onNavigate('models:voice') deep link (models until #527, below); the composer prop is tri-state, null = status unread → nothing, so mount never flashes either state). The AI Model screen's hide-the-disabled-Select precedent (§11 of the design guidelines) does not apply: there the one clear action sits on the same card, here it lives on another screen, so the mic is the pointer. The IPC refuses friendly as a backstop. Restart-free activation (#497, 2026-09-21): the slot is re-selected by refreshTranscriberSlot (compose-services.ts, the transcriber twin of the issue-#40 composeTranslator) from BOTH install hooks — AppContext.onModelInstalled after a speech-model download and EngineDownloadManager.onInstalled after a whisper_cpp engine install — a null slot only (a live instance may hold an in-flight child that the lock/quit teardowns reach through ctx.transcriber). Every consumer already read the slot per call (dictation IPC, the per-operation ingestion deps, the pack-article save, lock, quit), so the "captured at wiring time" premise the restart requirement rested on was never true for the transcriber (it is for the embedder: main/index.ts getIngestionDeps; the OCR engine was captured there too until #410 made both OCR reads live — "In-app OCR install — design record"). The chat screen re-reads the flag on mount and on window focus (the Translate-screen pattern).
  • #527 amendment — the hint names the missing piece. The transcriber needs two pieces, the whisper.cpp engine and the speech-model weights, and the hint used to blame the model in every case. Seen on Linux (v0.1.62): the model was installed, the engine was missing and had no build to install (the whisper_cpp pin was Windows-only), and the hint still pointed at the model download. Along with the slot, composeTranscriberSlot (compose-services.ts) now stores AppContext.transcriberMissing (TranscriberMissing: model · engine · model-and-engine · engine-unsupported). It is computed by transcriberMissingReason (transcriber/factory.ts), which checks the binary and the weights separately. The selection ladder can't give the reason: it stops at the first missing rung, binary before weights. engineFamilyHasHostBuild (runtime-download.ts) decides fetchable versus unsupported. The reason is set at startup and by every refreshTranscriberSlot, the same three moments that set the slot. getAppStatus (which the shell polls) only reads it back, as the optional AppStatus.transcriberMissing.
    • The hint. Each cause gets its own text and its own button: "Get the speech model", "Get the voice engine", or "Set up voice dictation". The hint no longer borrows chat.noModel.open. Every button opens the new virtual target models:voice: the AI Model screen on Browse, filtered to the Voice task, where the speech model is listed whether or not it is installed and the voice-engine banner sits above it. Before, the link landed on "On this drive", which by definition does not list a missing model.
    • engine-unsupported. The hint has no button, and the mic is labelled "not available on this operating system". The speech-model card on the AI Model screen says the model alone does not enable dictation or audio import there. Its download stays offered, because a drive builder can compile the engine.
    • Audio imports. The same reason picks the persisted failure (audioUnavailableMessage): three new persist-canonical values, while the model copy stays byte-identical so old rows still map.
    • "Open AI Model" is gone from every button (Home, the chat no-model state, this hint). Next to "AI", "Open" reads as the company name. The buttons now say "Go to AI Model"; the German „KI-Modell öffnen“ has no such reading and is kept.
  • #530 amendment — an engine that is present but cannot run.
    • What it covers. TranscriberMissing covers an engine that is ABSENT. An engine the OS loader refuses is the other case: whisper-cli is on the drive, the transcriber is selected, and every spawn dies first. Linux without libgomp1 and Windows without the Visual C++ runtime are the measured cases.
    • Classification. WhisperCliTranscriber classifies the exit and throws EngineCannotRunError (whisper_cpp), and the session verdict names it.
    • What the user sees. Dictation shows main.dictation.engineCannotRun; audio import stores main.ingest.voiceEngineCannotRun; the speech-model card gets a quiet hint with Check again.
    • Side fixes. The four dictation refusals moved from English literals to catalog keys (their English text is unchanged); the spawn passes windowsHide; a signal death keeps its stderr tail.
    • Record: "Engine load failures — design record".
  • #539 amendment — the models:voice landing becomes the rule for every missing optional model. Three more buttons had the defect #527 fixed: Images' "Go to AI Model" (all three unavailable reasons), Translate's "Go to AI Model", and the Documents row item "Get the translation model…". Each landed on "On this drive" whenever any model was installed. They now open models:images / models:translation.
    • One table. ModelsScreen's FOCUS maps each focus to its task (voice → transcriber, images → vision, translation → translation) and to the engine families whose missing-engine banner keeps the screen at the top instead of scrolling the library into view (voice: llama_cpp + whisper_cpp, unchanged; images / translation: llama_cpp, the runtime of both manifests). NavResolution.modelsFocus is the ModelsFocus union; the focus is session-only App state, read once at mount.
    • One target for Images. no-runtime (the engine binary is missing) puts the engine banner on top of that view; incompatible shows on the vision row as "Unsupported". An engine that is present but cannot run (#530) leaves vision available, so the Images card never sends the user there.
    • Unchanged on purpose. Every chat-model and engine button (Home, the chat's no-model state, the #530 App notice, Performance, the first-run gate) keeps plain models; the default view shows what they are about. resolveNavTarget('models') stays exactly { screen: 'models' }.
    • In the skip predicate since #532 (2026-10-05). The #530 "can't run" banner for the chat engine, now carrying the #532 reinstall, keeps the screen at the top like a missing-engine banner (all three focuses list llama_cpp). The voice engine's #530 notice is a hint on the speech-model card, inside the library, so it does not. The decision waits for the first read of the engine verdicts (useEngineProblemsRead().settled), and a refusal reported after that read cannot move the screen. #516's banner should join the predicate when it lands.
    • The rule is recorded once in design-guidelines §7 ("a button about a missing optional model lands on that model").
  • Permissions: the Phase-31 deny-by-default setPermissionRequestHandler gained its single exception — media requests that are audio-only and from the app's own WebContents (services/permissions.ts; scope matrix unit-tested). See security-model.md.
  • Privacy: the recording exists only as the shredded transient; no audit event (content-adjacent, like search); errors to the renderer are fixed friendly copy with the technical reason in the local log only. The OS mic indicator is the recording signal. Locked workspace: the composer doesn't exist pre-unlock, and since S3 the IPC refuses on a locked vault anyway (main.dictation.locked, before any byte is written).
  • Concurrency & timeout (backend audit 2026-06-27, REL-3). whisper is not internally serialized, so the handler holds a single-flight guard: a second dictation:transcribe while one is in flight is rejected with friendly copy (DICTATION_BUSY_MESSAGE) BEFORE it writes the temp WAV or spawns — rapid mic presses can't double-spawn. A wall-clock ceiling (DEFAULT_DICTATION_TIMEOUT_MS, 10 min; override HILBERTRAUM_DICTATION_TIMEOUT_MS) drives an AbortController whose signal is passed to transcribe — a wedged child is killed and the mic spinner gets the friendly failure instead of hanging forever. The temp WAV is shredded in finally on every path (success, refusal, timeout).
  • Live in-input waveform (2026-06-13): an in-app "recording started" cue. A read-only Web Audio AnalyserNode tap on the SAME getUserMedia stream (never wired to a destination, never touching the recorded bytes) is exposed as DictationCapture.analyser; renderer/chat/Waveform.tsx paints its time-domain data to a <canvas> overlaid on the textarea while recording (Composer adds .composer-recording to dim the draft + accent the border). Decorative (aria-hidden) — the mic aria-pressed/label stays authoritative — and prefers-reduced-motion-aware (static baseline). Degrades to no wave (button pulse + dim only) when Web Audio is absent (analyser: null). Local, no new deps. Live no-signal hint (#497 follow-up, owner request): useNoSignalHint samples the same tap four times a second and, once its peak has stayed under the gate's −50 dBFS floor for 2 s, the composer shows the "no sound is reaching the microphone" note until signal returns or recording ends; a null analyser never shows it (the post-stop gate still refuses). Full record: wave-3 plan §10.
  • #869 (2026-11-18): the dictation WAV and its transcript reach whisper-cli by their bare names from the documents folder, the speech and VAD models (-m, -vm) by an ASCII spelling, so dictation works under a root with any character; a VAD or speech model whose path (a folder or the file name below models/) has no ASCII spelling is refused with main.dictation.voiceModelPathUnsupported. Record: "Audio transcription (Phase 36)", "#869 amendment".

Scanned-PDF / photo OCR (Phase 38, wave-3 plan §11, decisions D31–D33)

Image-only PDFs and photos of pages (.png/.jpg/.jpeg) become searchable corpus documents via local OCR: tesseract.js (pure WASM, pinned 7.0.0) over language files vendored on the drive (ocr/deu.traineddata.gz + eng.traineddata.gz — German + English, the tessdata_best-INTEGERIZED variant per R-O3). Zero network at runtime (R-O2: tesseract.js's CDN langPath default and CWD cache are explicitly disabled; sentinel-tested), zero native deps.

  • Step 0 — scan detection (the Phase-17 trust spirit). A PDF where NO page reaches PDF_TEXT_PAGE_MIN_CHARS (25) of extractable text used to silently index NOTHING. The PdfParser now fails it friendly ("This PDF looks like a scan — it has no readable text yet."); DocumentInfo.scanDetected is DERIVED (failed + that exact notice) and drives the row's "Make searchable (OCR)" offer. Hybrid text+scan PDFs are NOT detected — their text pages index normally, exactly as before.
  • D31 (resolved by R-O1): the split execution design. Rendering a PDF page to pixels needs a canvas; the main process has none and Electron 37's utilityProcess has NO OffscreenCanvas (probed — option (b) was impossible). So a hidden BrowserWindow (ocr.html, its own tiny sandboxed preload exposing exactly the five OCR_RASTER channels, never the app API) does ONLY pdf→PNG rasterization with the SAME pinned pdfjs legacy build the PdfParser uses (originally forced by the modern build's Uint8Array.prototype.toHex, which Electron 37's Chromium lacked; that motive expired with pdfjs 6.2 + Chromium 142 — see the DEP-3 record — and the legacy build is retained for one-build-everywhere consistency) at 300 DPI (capped at 4096 px/side). Recognition always runs MAIN-side in tesseract.js Node mode (services/ocr/tesseract.ts): image Buffers decode inside the WASM core (no canvas), the worker script + core load from the app's own node_modules (packaged: asarUnpack + the app.asar → app.asar.unpacked workerPath rewrite — worker_threads cannot read inside asar). Photos never touch the renderer at all. The rasterizer protocol is pull-based (services/ocr/rasterizer.ts): main requests one page at a time and recognition backpressures rendering, so a long scan never queues unbounded page images.
  • Per-page timeout & recovery (backend audit 2026-06-27, REL-2). A tesseract.js WASM job is not cooperatively cancellable and recognitions are serialized through one worker chain, so one crafted/huge image could wedge OCR for the whole session and Cancel only landed between pages. recognize() now races worker.recognize against a per-page timeout (DEFAULT_OCR_PAGE_TIMEOUT_MS, 2 min, overridable with HILBERTRAUM_OCR_PAGE_TIMEOUT_MS) and the abort signal; on timeout OR mid-page abort the only real recovery is to terminate() the worker (cleared → recreated lazily) and reject — which frees the serialized chain so the next page proceeds with a fresh worker. A plain recognition error still leaves the worker intact (unchanged). The OCR document task surfaces a timed-out page as a friendly task failure (the recognition stays unpersisted; Cancel/redo unchanged). A second, independent ceiling bounds rendering, not recognition: the hidden-window rasterizer's per-page open+render round-trip is capped at a fixed RASTER_STEP_TIMEOUT_MS (60 s, services/ocr/rasterizer.ts), with no env override — a page that renders slowly fails the task at 60 s regardless of HILBERTRAUM_OCR_PAGE_TIMEOUT_MS, which only governs the main-side recognition step.
  • D33: OCR is NEVER automatic for PDFs. Detection marks the row; "Make searchable (OCR)" runs as a Phase-33 document task (kind 'ocr' — queue, progress "pages + 1", cancel; the D26 guards hold, but it needs the OCR engine instead of the chat runtime). The task rasterizes + recognizes page by page, persists the recognition in the additive documents.ocr_json column (CONTENT — DB only, never logs/audit; metadata surfaces as DocumentInfo.ocr), then re-ingests: the PdfParser's ParseContext.ocrPages hook turns the stored recognition into one ExtractedSegment{ pageNumber } per page ⇒ page citations work unchanged. ocr_json survives re-index (like origin_json): re-index and preview reuse the stored pages instead of silently re-OCRing; re-running the task is the explicit redo. Cancel contract (GAP-7, two-part): a cancel landing before the persist point (setDocumentOcr) persists nothing — the document stays a detected scan; a cancel landing after it (during the signal-less, minutes-long re-ingest) is deliberately IGNORED and the task completes 'done', because the recognition is already persisted and the chunks/index are being rebuilt from it. Photos are the D33 asymmetry: the ImageParser OCRs on import directly (one small image, seconds) via the engine injected through ParseContext — the transcriber-injection precedent.
  • Initiation surface, admission guard & finishing-step display (OCR-R P1; ocr-audit 2026-07-18 FE-1/FE-2/BE-1/FE-4/FE-5). A detected scan is by definition a FAILED row, and failed rows have no "⋯" overflow (§11.6) — so the offer is an inline "Make searchable (OCR)" button on the failed row itself (strictly showOcr-gated; ordinary failed rows are unchanged), and the D33 explicit redo is a separate "Read again (OCR)" overflow item on already-OCR'd INDEXED PDFs (d.ocr != null && ocrAvailable). Task admission mirrors the docs-IPC requireNoActiveTask guard in the reverse direction: DocTaskDeps.isDocumentProcessing — late-bound to registerDocsIpc's module-local processing set via ctx.docIngestionActive (the skillRunActive pattern; predicate injection chosen over extracting the set into a shared service) — refuses startDocTask for EVERY kind while a target document is mid-import/re-index (main.task.documentBusyIngesting); without it an OCR re-run admitted mid-re-index would interleave two chunk rebuilds + two embed phases on one document. Finishing-step display contract: progress stays "pages + the final re-ingest step" (stepsTotal = n + 1), but once the last step is reached the row's busy label switches to docs.task.ocrFinishing ("Finishing — making the text searchable…") instead of "Reading the scan… (n/n)" — Documents keeps the +1 by LABEL while Translate subtracts the step for display; the two conventions are deliberate, not drift. Cancel stays ENABLED through the finishing step (a legitimately cancellable pre-persist instant shares that renderer-visible state); after a cancel click the button renders disabled as "Stopping if possible…" (docs.task.stopping) — honest about the two-part cancel contract above (a cancel the IPC rejects offers Cancel again, #680). The ~ms ambiguity (the pre-persist instant already reads "Finishing") is accepted.
  • Availability-driven (D14/D9): createSelectedOcrEngine returns the engine iff <root>/ocr/*.traineddata.gz exist, else null (no mock — invented text would corrupt the corpus). AppStatus.ocrAvailable gates the UI; absent assets ⇒ the scan notice appends a "needs the OCR files" hint and photo imports fail friendly per-file. No settings key (ocrLanguages was considered and dropped — availability-driven).
  • Distribution (D32): the ocr: block on runtime-sources.yaml is a NEW asset class (plain verified files { lang, url, sha256, dest }, no extraction, no marker — the hash IS the install state), fetched by fetch-runtime --family ocr, asserted by assertCommercialDrive (ocrAssetsVerified) + both script gates.

OCR quality amendment — orientation, confidence, photos, scanned pages (#538, #574, #575, #576; 2026-10-05)

Owner rulings (2026-10-05): orientation by Tesseract OSD with a pinned osd file (not trial rotations); a text PDF's scanned pages are short pages that paint an image (not every short page); Read again (OCR) on a photo is a re-index.

Facts it rests on (measured 2026-10-05 on rendered A4 letter pages, 68 distinct words, deu+eng best_int, tesseract.js 7.0.0, DesktopDiT i7-8700):

  • Upright clean page: mean confidence 94, 68/68 words. The same page sideways: 55–62, 0/68 (and 3–4× slower — the garbage reading is the expensive one); upside down: 35, 0/68. A degraded but UPRIGHT photocopy (150 DPI, noise, 1° skew, JPEG q50): 53, 60/68. A Cyrillic page (no rus data): 50–56 in every orientation. So confidence alone cannot tell sideways from poor; within one image the right turn always scores highest (margin ≥ 14 on the photocopy, 3–8 on a 110-DPI ruin).
  • tesseract.js applies EXIF orientation with an exact right-angle turn but finds it only as a BIG-endian byte run in the first 500 bytes (setImage.js): a little-endian (II) phone photo held sideways read 0/68; the core's rotateRadians turns inside the original frame and lost the top and bottom lines of a sideways page (63/68).
  • The "WASM core cannot run the legacy engine" premise (#538 option 2) was wrong: the legacy-capable cores ship and are unpacked; with osd.traineddata.gz (4.3 MB) OSD found the right turn on every clean and moderately degraded page in 0.15–0.7 s and declined ("too few characters") on a 110-DPI ruin and a near-blank page. Its own confidence is unreliable (0.8–15 when right).
  • pdf.js getOperatorList tells a scanned page from a blank one, but building it DECODES every image the page paints, in the calling process and with no size limit (~0.1 s for an A4 JPEG page; unbounded for a crafted one) — not acceptable in the main process at import (PR review M1). pdf.js checks an image's DECLARED size (maxImageSize) before touching its data, and with stopAtErrors a too-large image ends the page's operator list; without it the image is dropped and the rest kept. Comparing the two lists finds image pages with no decode: 1–2 ms per page, the same verdicts on every test PDF.

Design as built:

  • Orientation marker (services/ocr/orientation.ts): every turn is a big-endian EXIF Orientation entry placed FIRST in the bytes (a PNG eXIf chunk after IHDR, a JPEG APP1 after SOI), composing the image's own orientation (read in either byte order, bounds-checked) with the turn. An image with nothing to say passes through untouched. tests/unit/ocr-orientation.test.ts runs tesseract.js's own setImage against the markers, so a tesseract.js bump that changes how orientation is found reds in CI.
  • OSD worker (ocr/tesseract.ts): a second worker, createWorker('osd', 0, { legacyCore, legacyLang }), started lazily on the first unsure page, serialized on the recognizer's chain, same per-page timeout, torn down with it (lock, quit). Optional in every sense: no file → no detection (the file is looked for at each call until the worker starts, so an in-app install is used at once and refreshOcrSlot reports activated); a failed start, a timeout or a death switches detection off for the engine's life and never changes availability(). Worker starts are serialized (the process.on('worker') capture window would otherwise see both threads). listOcrLanguages leaves osd out — before, a dropped-in osd.traineddata.gz became a "language" and failed the LSTM-only start.
  • Reading policy (ocr/upright.ts, readUpright): read at the expected turn; a reading at confidence ≥ 75 is kept (clean scans cost exactly one reading, the bytes untouched); otherwise OSD, and if it names another turn (or declines while the first turn was not upright) read there too and keep the more confident reading — a wrong OSD verdict cannot make a page worse. The scan task tries the previous page's turn first, so a sideways scan pays the detour once (real app, 300 DPI A4: 4 upright pages 6.2 s; 4 sideways 11.6 s; 4 mixed 0/90/270/180 19.3 s, all 68/68). Photos use the same policy with their EXIF honoured in either byte order.
  • Kept with each page (ocr_json pages): confidence and turn (absent = 0) — parseOcr copies both (it rebuilds pages field by field).
  • Metadata (ingestion/ocr-meta.ts ocrMetaOf, the one derivation for the writer, the photo path and the backfill): textPageCount (#576 — pages whose reading produced text) and lowConfidencePageCount (#538 — text pages under OCR_LOW_CONFIDENCE = 65; absent when no page carries a confidence). The open-time backfill re-derives every sidecar that lacks textPageCount (filtered in JS: a corrupt sidecar must never fail the open).
  • Photos (#574): the image parser returns its reading's counts as ParsedDocument.ocrMeta; prepareDocument writes it as the photo's ocr_meta_json on each import/re-index, and it is cleared whenever the photo ends failed (reading it, or embedding it — finalizeDocument). No ocr_json — a photo's text still lives only in its chunks.
  • Scanned pages in a text PDF (#575): with ParseContext.detectScannedPages (import and re-index only), the PDF parser checks which pages under PDF_TEXT_PAGE_MIN_CHARS of a PDF that has real text pages paint an image — findScannedPages: after the text document is released, two documents of its own with maxImageSize: 1 (lenient, then stopAtErrors), one at a time; a page whose strict operator list is shorter than its lenient one paints an image. No image is ever decoded. Bounded by SCANNED_PAGE_CHECK_BUDGET_MS (20 s; unchecked pages count as scanned). Stored as documents.scanned_pages_json ({ pages, pageCount }); DocumentInfo.scannedPages carries the counts. The OCR task admits such a PDF and rasterizes only those pages (RasterizePdfOptions.pages → pagesToWalk). It persists a reading that found no text only on the FIRST read of those pages (the offer then goes); a re-run never replaces an earlier reading with nothing, a run that read no page persists nothing, and a whole scan with no text still fails ocrNoText. The parser merges per page: a short page with stored recognition contributes the recognition (its rendered layer is part of the reading), every other page keeps its text layer; a whole scan keeps its old path.
  • UI (design-guidelines §11.19): the preview counts recognized pages ("on 2 of 3 pages", against the whole document for #575, "found no text" when none); an unsure reading is a quiet row caption and, in the preview, the causes plus Read again (OCR); a text PDF with unread scanned pages gets a caption and Make searchable (OCR) in its ⋯ menu; the photo variants say "this photo". The AI Model OCR row names the orientation file when it is the only one missing (OcrInstallLanguage.role).
  • Verified in the real app on DesktopDiT (Smart App Control off, Norton on), dev build and the packaged HilbertRaum.exe (electron-builder --win dir: shipped fuses, asar integrity, encrypted workspace, OSD core from app.asar.unpacked): the little-endian sideways photo 68/68 (was 0/68); a 0/90/270/180 scan 4×68/68; a text+scan+blank+title+sideways-scan letter: import found pages 2 and 5 only, OCR read only those, both 68/68; a poor photocopy flagged unsure on 2 of 2 pages. The in-app installer fetched only osd (4,320,130 bytes, pin verified) behind Norton and reported activated.

Document tasks (Phases 33–35; OCR Phase 38; tree/extract = whole-document analysis, rag-design §14)

  • services/doctasks/ (barrel: doctasks.ts) — the shared task engine. Split into a doctasks/ directory, with the manager keeping the pump and the handlers owning each kind (DX-1, full-audit-2026-06-29 follow-up Phase 8 — see §38; the earlier audit-M-A4 split first carved the window-math siblings out of the monolith). manager.ts (the DocTaskManager) keeps ONLY the queue/pump + arbiter handshake + the generate model loop, and dispatches each dequeued job via MODEL_TASK_HANDLERS[kind](task, runtime, ctx) — except ocr/categorize (no/optional runtime) and, since TG-3, translation (dispatched directly with the Translator; its sidecar-shaped window retry lives in its handler). Each kind's actual work lives in its own handlers/ module: handlers/index.ts (the MODEL_TASK_HANDLERS registry + the ocr/categorize/translation exports), handlers/shared.ts (the shared doc helpers materializeDocument/buildProvenance/extractSegmentTexts), and one file per kind — tree.ts (deep index + extract), summary.ts, ocr.ts, translation.ts, compare.ts, categorize.ts. The window-math/prompt siblings summary.ts/translation.ts/ compare.ts at the doctasks/ root stay (the PURE math + templates each handler calls). context.ts is the leaf vocabulary module: DocTaskDeps (the injected seams, re-exported from manager.ts for the barrel), InternalTask (the in-flight job), and DocTaskCtx — the narrow orchestration handle (deps + the model-slot arbiter + the generate model-loop fn) the manager hands each handler so a run<Kind> body calls the shared model loop without a this reference. A job state machine on the Phase-4/18 async-with-polling precedent: startDocTask({ kind, documentIds, params }) → { jobId }, getDocTask(jobId) → { state, progress { stepsDone, stepsTotal }, error?, resultRef? }, cancelDocTask(jobId?). States: queued → running → done | failed | cancelled; unknown job ids report a terminal status so pollers always stop. Seven DocTaskKinds (shared/ types.ts) run on the one machine: summary (Phase 33), translation (Phase 34), compare (Phase 35 — exactly TWO distinct source documents; the others take one), ocr (Phase 38), the two whole-document-analysis builds tree (deep index) and extract (structured extract), and categorize (the bank-statement LLM categorizer, D26). Deps are injected (getDb, getRuntime, getTranslator — the TranslateGemma sidecar, TG-3 —, isChatStreaming, getContextTokens, getStoreDir, getIngestionDeps, beginDocumentWork, getOcrEngine, rasterizePdf, audit), so the engine tests without Electron; main/index.ts wires it and exposes it as AppContext.docTasks. getOcrEngine and the ingestion deps' ocrEngine read ctx.ocrEngine LIVE (#410 — an in-app OCR install fills the slot mid-session); only the embedder stays captured.
  • Concurrency (D26, RESOLVED): strict one-at-a-time, with one exception. Tasks serialize among themselves (one FIFO queue, one runner). Every task kind refuses to START while a chat answer streams (startDocTask reads the shared in-flight registry before any per-kind check, so the yielding tree/extract builds and categorize refuse too; only a RUNNING yielding build cedes the slot to a chat that arrives later — the exception below) but owns its own AbortController and is NEVER an entry in the per-conversation map — stopGeneration cannot kill a task and a task cannot block a conversation key (fact §2.8). The inverse guard lives in the chat/RAG handlers: a message sent while a non-yielding task is active throws the shared DOC_TASK_BUSY_MESSAGE, which the chat screen renders with a "Cancel document task" button (cancelDocTask() with no jobId cancels the active task). Exception — the yielding builds: tree and extract are long, resumable background builds that cede the model slot to an incoming chat via the ModelSlotArbiter (services/analysis/model-slot-arbiter.ts): the builder parks after the current node, chat acquires the slot (acquireChatSlot), streams, and the build resumes in-session — so chat is not refused during a deep-index/extract build (rag-design §14.3). Abort-aware handoff (full-audit 2026-06-29, REL-3): the builder parks only between generate calls, and a single node's generate is a multi-second CPU summarization. Before the fix acquireForChat had no signal, so a user "Stop" landing while a chat was parked waiting for the handoff aborted a controller nobody was watching — "Stop" appeared dead for up to one tree-node. The chat turn's AbortController.signal is now threaded withChatStream → acquireChatSlot → acquireForChat: an abort during the park rejects the wait at once (removing the waiter from the queue and giving back its holder slot, and dropping the pause when it was the last waiter — so the builder doesn't park for a chat that's gone). withChatStream treats that rejection like a no-token Stop: it resolves cleanly via done with an empty message rather than surfacing chat:error. The handoff wait drops its own abort listener when it resolves, one microtask before the holding-phase listener exists, so acquireForChat checks signal.aborted once more at that point: an abort in that gap releases the slot and rejects the same way, instead of waiting for withChatStream's finally (#555, PR #556). The R-T1 probe (tests/manual/server-concurrency-probe.test.ts, HILBERTRAUM_CONCURRENCY_PROBE) showed the b9585 of 2026-06-11 serving two requests on PARALLEL slots at the default args of the time, which is why the app-side guard exists. That verdict is historical: since #319 (2026-09-07) CHAT_SERVER_ARGS carries -np 1, so the chat server has one slot and a second request queues for it (translation and vision pass --parallel 1); the app-side guard still decides first, and the server queue is only a backstop.
  • Tasks call the active chat runtime over the locked chatStream contract with EXPLICIT maxTokens/temperature — never the answer-depth modes. No runtime running → a friendly "start a model first" refusal, never an auto-start (the sendChatMessage decision). Failures surface friendly §11.4 copy; the raw reason goes to the local log only. Cancellation never persists a partial result (chat keeps partials; tasks do not). Exception since TG-3: translation runs on the TranslateGemma sidecar (DocTaskDeps.getTranslator, see the design record below) — the chat runtime is irrelevant to it; an absent translator refuses with main.translation.noModel (a deep link to the AI Model screen in the UI). The FIFO + chat↔task exclusion apply unchanged (plan D9: RAM co-residency — a ~9.5 GiB translate next to a resident chat model).
  • Summary algorithm (D25): budget-driven two-level map-reduce over stored CHUNKS (no re-parse; the ~80-token chunk overlap slightly duplicates stitched text — accepted). The per-call input budget is derived in WORDS (the chunker's token-estimate unit) with an explicit words→tokens safety factor: (contextTokens − 512 output reserve − 300 prompt reserve) / 1.3 — the estimate undercounts real tokens, so a budget-sized window provably fits the model's real context. Total ≤ budget → one call; else chunks pack greedily into budget-sized windows (an over-budget chunk is SPLIT, not truncated) → per-window partial summaries → one reduce pass, with each map call's maxTokens sized to usableTokens / windowCount so all partials fit the reduce input at every shipped window (≥ 4096; at the 2,048-token settings minimum the 128-token floor overshoots from 10 windows, and the reduce belt cuts the joined partials' tail and flags the summary truncated, #682 — it was stored as complete until then). Hard ceiling: 12 map calls (≈ a ~50-page document at the default context); beyond it the summary covers the beginning and is flagged truncated (the UI says so honestly).
  • Persistence (D25): additive nullable documents.summary_json ({ text, modelId, createdAt, truncated }, ensureColumn migration). Cleared FIRST by reindexDocument (content may have changed — even a failed re-parse clears it); gone with document delete. Surfaced as DocumentInfo.summary. Summaries are CONTENT: they live only in the (possibly encrypted) DB; the additive audit events document_task_completed/document_task_failed carry { kind, documentId } only (plus the additive ids-only documentIdB for a compare) — sentinel-tested in audit-ipc.test.ts.
  • Translation (Phase 34, D27/D36; rerouted onto the TranslateGemma sidecar at TG-3): map in document order, materialize a NEW document. params.sourceLang/params.targetLang over the curated 10-language set (widened to 51 by issue #31 — see D5/#31b) (TRANSLATION_LANGUAGE_CODES, shared/types.ts — the canonical list the sidecar prompt builder also keys off; validated server-side, source ≠ target; TranslateGemma needs an explicit source — no auto-detect). D36 — the input is the parser's SEGMENTS, re-extracted from the stored copy via extractDocumentPreview, NOT the stored chunks: chunks overlap by ~80 tokens for retrieval, and naive in-order chunk concatenation would duplicate text at every boundary in the translated output (a summary tolerated that; a faithful translation cannot). The segments are ordered, non-overlapping, and exact; the cost is one re-parse — the same cost the in-app preview pays, on the same code path (encrypted copies decrypt to a .parse* transient and are shredded). Overlap-trimming adjacent chunks was rejected as heuristic where the re-parse is exact. Windows budget against the SIDECAR's launched --ctx-size (Translator.contextWindow(), 4096 from the manifest) — not the chat window — split by measured token weight (R-T2: input 1.3 tokens/word, output 2.0; measured on Qwen3-4B, kept as conservative defaults until TG-6 re-measures on the Gemma tokenizer) and hard-clamped to the model card's ~2K input spec (TRANSLATION_MAX_INPUT_TOKENS = 1800, plan D4 — over-chunking is the failure mode, never overflow). No window ceiling and no reduce — a faithful translation may not silently truncate; windows are translator.translate() calls in order, strictly SEQUENTIAL (plan D9 — one --parallel 1 slot; parallel requests are the #25142 Windows-Vulkan hang shape); the trained prompt lives INSIDE the sidecar (services/translation/prompt.ts, greedy temperature 0) — no app-side system/window prompts remain. A window the model refuses/garbles is retried ONCE (the sidecar-shaped retry lives in handlers/translation.ts), then marked visibly in the output with the original text kept below — never silently dropped; only an all-windows failure fails the task. Attribution + provenance stamp the TRANSLATION model's id. Page-completeness accounting (issue #58, 2026-07-17): the failed-window honesty above starts at the MODEL — a source page whose extraction is EMPTY (a scanned page inside a hybrid PDF) used to emit no segment and vanish from the output without a trace. The parser now reports the source's declared pageCount (ParsedDocument/DocumentPreview, additive), extractTranslationSource keeps per-segment page numbers, and planTranslationBlocks (doctasks/translation.ts) plans BLOCKS: segment runs packed into windows exactly as before, interleaved with gap blocks (computeMissingPageRanges — O(segments), ranges not lists, so a crafted M-2 page count can't balloon memory) that materialize as inline missingPageNotice markers at their true reading position (L12 posture: localized at materialization). The finished task carries DocTaskStatus.gaps { missingPageRanges, failedWindows } (set only when incomplete) → the Translate screen's hint warn lines; the failed-window count thereby reaches the UI too (previously in-document only). A per-segment packing invariant (assertNoTextDropped: non-whitespace chars in == out) turns any future planner drop into a loud task failure. With no gaps the block plan degenerates to exactly planTranslationWindows (pinned by unit test). Page accounting applies to formats WITH pages (PDF incl. the stored-OCR path); page-less sources rely on the packing invariant.
  • Compare (Phase 35, D28/D37): two documents in, one materialized report out. The strategy auto-switches on token math (the D25 budget shape: `(max(1024, ctx) − 512 −
    1. / 1.3input words per call). Both full texts fit ⇒ **mode (a)**: one structured-comparison call over both. Else **mode (b), section-matched**: doc A's chunks pack into half-budget windows (over-budget chunks split, pieces keep their chunk id), each window's nearest doc-B chunks come from doc B's STORED vectors under the active embedder's id, loaded and decoded once (RAG-2/ING-1) and ranked in memory by the purecompareNearestNeighbors(P1:dotProducton L2-normalized vectors, a running top-K) — noVectorIndex` search, so the pairing is deterministic and costs nothing but dot products (top-3 neighbors per A-chunk, best-first fill of the other half-budget, presented in doc-B order); per-pair map calls use a deliberately smaller prefixed-bullets format (R-T2-confirmed), then one reduce merges the notes into the four dictated report sections (share / differ / only-in-A / only-in-B; headings dictated verbatim, body in the documents' language; temp 0.3, output cap 512 — both R-T2-validated over two smoke rounds on the real b9585 + Qwen3-4B). Map ceiling 12 → an honest truncation notice INSIDE the report ("covers the beginning of A"); map output caps are sized so all notes fit the reduce input at every shipped window (the D25 fit property; at the 2,048-token settings minimum the 128-token floor overshoots from 10 windows, and the belt cuts the joined notes and adds that truncation notice, #682). D37: mode (a)'s input AND the mode decision use the re-extracted parser segments (chunk overlap would read as phantom "shared" content and inflates a length estimate by ~16% — enough to mis-route the switch); mode (b)'s map deliberately uses the stored chunks (vectors needed; notes tolerate overlap, the D25 precedent). Embedder-visibility guard: before any model call, mode (b) verifies BOTH documents have vectors under the ACTIVE embedder id — a stale/vectorless document fails friendly with the Phase-17-style "re-index first" answer, never a silently empty pairing (mode (a) needs no vectors and skips the guard).
  • Materialize (D27): only after every window succeeded (cancel persists nothing), the Markdown — "> Machine-translated by <model> — may contain errors." (translations) or "> Machine-generated comparison by <model> — may contain errors." (+ the truncation notice when capped) — is written to a <jobId>.parse.md transient (the startup crash sweep covers it) and run through the NORMAL import path (createQueuedDocument with the display title "<original> (<native target name>).md" — since issue #31 the label spans all 51 TRANSLATION_NATIVE_NAMES, e.g. (Українська), not just (Deutsch|English) (#164 D-5) — / "Comparison: <A> vs <B>.md" + processDocument with the real ingestion deps) ⇒ chunked, embedded, searchable, citable, .enc-encrypted automatically; the transient is shredded. Provenance lands in the additive documents.origin_json column — a DocumentOrigin discriminated union ({ type: 'translation', translatedFrom, targetLang } | { type: 'compare', comparedFrom: [a, b] }; Phase-34 rows persisted without type parse as 'translation' — an additive migration), surfaced as DocumentInfo.origin; malformed JSON reads as null; survives re-index — provenance, not sync. A failed import deletes the half-born row: a generated document fully succeeds or persists nothing.
  • Vault lease split: a summary takes NO beginDocumentWork() lease, deliberately — it only reads chunk rows and writes one DB column. A translation's/comparison's MATERIALIZE step writes .enc sidecars, so that step — and only that step — holds the lease (the long window loop must not block a password change for minutes); a concurrent password change makes the materialize fail friendly (VaultBusyError passes through). registerDocsIpc refuses re-index/delete of any document an active task targets (isDocumentBusy — both compare sources), and the freshly created OUTPUT document is appended to the task's documentIds at creation so the guard covers it before the import finishes.
  • IPC + UI: doctasks:start/get/cancel (+ preload mirrors); the read-only analysis channels analysis:coverage (a document's DocumentCoverage — breadth + depth of the current summary, no model call) and analysis:listAll (structured extract aggregation, zero model calls) are handled by the same registerDocTasksIpc.ts (design: rag-design §14.4/§14.5); docs:export saves a text document's stored content via the main-process save dialog (the exportConversation pattern — built for materialized translations, which are always Markdown; audit ids-only). The renderer watcher (renderer/lib/doctasks.ts) lives at module level so a running task's busy/progress state survives screen navigation — ONE store for all kinds (startTask(kind, documentIds, params) — one id, or two for a compare; D26 guarantees at most one task anyway). The Documents screen polls it (useSyncExternalStore), shows the per-row "Summarizing…/Translating…/Comparing… (n/m)" busy state + Cancel on EVERY source row; "Translate" opens a small modal with SOURCE + TARGET selects over the curated 10 (widened to 51 by issue #31 — see D5/#31b) (native-name labels, untranslated by design — the Settings language-picker precedent; the pair is remembered session-local, source ≠ target enforced in UI and server). With no translation model installed (AppStatus.translationAvailable, read from ctx.translator like ocrAvailable) the Translate item disables and a sibling "Get the translation model…" item deep-links to the AI Model screen (plan O2/D3). "Compare (2)" appears on the Phase-17 multi-select at exactly two selections. A done summary opens the preview (collapsible section, "Generated by · ", Regenerate); a done translation reveals the new document in the refreshed list with a quiet "Translated from " provenance line (row + preview); a done comparison opens the new report's preview with its "Comparison of and " line. Both materialized kinds offer Export. Poll write-back (#680): a 400 ms tick reads the entry again after its round-trips (getDocTask, and the #38 chain read) and spreads THAT entry, never the one it read before them, so a Cancel latch (DOC-5) set meanwhile survives and an entry a lock purge (SH-4) dropped or a newer task replaced is left alone. One tick runs at a time (a per-timer in-flight latch, fileTranslateSession's TA-3 / H4 shape), so a slow round-trip cannot land after an overlapping tick gave up (CODE-6) and revive a task nothing polls; a rejected cancel clears the latch. The skill-run store had the same overlap and has the same latch since #688. Cancel targeting (#689): the store holds only the tasks the Documents screen started, while the lane is shared with a Translate-screen file translation, a skill's categorize, and an import's deep-index build. The row's Cancel (cancelActiveDocTask) therefore sends the entry's jobId (#157 DT-2's exact-id cancel, stale-safe), and sends nothing when there is no entry. With no id, main cancelled whatever held the lane, so a row task queued behind another screen's task stopped that task and then ran itself. A deep-index tree that finished hands its cancel on to the extract pass it chained (#38, InternalTask.chainedJobId): the row still holds the tree's id until its next poll adopts the extract. The chat busy banner keeps the no-id cancel (cancelRunningDocTask), deliberately. Chat is refused while any task is active (hasActiveTask()), the copy names the running task, and the store may hold nothing or a task queued behind it. With a second task queued, the next send is refused again; that is truthful.

Translation sidecar — design record (TG wave)

The TranslateGemma translation wave (TG-1…TG-6, 2026-07-05) as built: the translation manifest role + dedicated llama-server sidecar, the doc-task reroute, and the Translate view (text + document drag-and-drop). This is the COMPLETE record — the plan (docs/translategemma-translation-plan.md) was folded here + into model-policy.md (role + license/research) + model-benchmarks.md §11 (measurements + promotion bar) and DELETED at TG-6 per the CLAUDE.md doc-lifecycle rule; the full original is in git history. In-code comments still cite the plan's §N / DN / ON / VN anchors — the §-anchor legend at the end of this record keeps them resolvable (the "Functionality wave 3" precedent).

  • TA-1 — main-process lifecycle seams: quit + lock flush the whole doc-task pipeline (translation audit fix wave, 2026-07-06; findings H1/H2). Both lifecycle paths now cancel the running doc-task and the queue, then await the running task's abort-unwind before the DB closes.

    • H1 (quit). performShutdown (shutdown.ts) aborted the deep-index build + the Translate-view job but never the doc-task, so on quit mid-translation translator.stop() killed the in-flight window, retries failed fast against the stopped latch, and a task with an already-succeeded window proceeded to materializeDocument during teardown — a half-translated plaintext .parse transient racing the DB close. Fix: it now calls ctx.docTasks.cancelAllDocTasks() in the same best-effort block that aborts the build (before the sidecars stop), and awaits awaitActiveTaskSettled() (bounded ~5 s) next to the in-flight-stream settle, so the abort-unwind's materialize/shred finishes while ctx.db is open.
    • H2 (lock). registerWorkspaceIpc called ctx.docTasks.cancelDocTask() (active task only). The DB stays open while the lock handler awaits the sidecar suspends, so when the cancelled task settled manager.pump() dequeued the next queued translation into the lock window — decrypting document text to a .parse transient and cold-starting a fresh ~10 GB sidecar that outlived the lock (the old comment's "still-queued tasks fail friendly at dequeue" was false during the handler). Fix: it now calls cancelAllDocTasks() (running + queued) and awaits awaitActiveTaskSettled() before purge/lock, mirroring the stream-settle treatment.
    • New manager seams. DocTaskManager.cancelAllDocTasks() walks the running id + a queue snapshot and reuses the per-id cancelDocTask (each queued task → terminal cancelled, dequeued synchronously — a queued task never reaches running), holding no permanent latch (pump is driven per startDocTask, so the manager is usable again after unlock). awaitActiveTaskSettled() exposes the tracked run(task) dispatch promise (resolves immediately when idle); the callers bound it with a ~5 s Promise.race timeout so a wedged handler can never hang quit/lock.
    • The quit hold (#936, follow-ups wave 4). holdQueueForQuit() makes pump start nothing; releaseQueueHold() clears it and pumps. The running task goes on, and a task started meanwhile is queued (it runs if the quit is called off); hasActiveTask() and listActiveDocTasks() are unchanged (a held task is still active, so the chat busy guard still sees it). Two callers set it (main/close-guard.ts): the main window's close guard, when it commits to a close that quits, and holdQueueOnQuit, at every un-prevented before-quit (main/index.ts). The guard's Keep open releases it, and so does a successful unlock or (#955 item 4) create (registerWorkspaceIpc.ts; no quit is under way then, so a hold still set would be stale). Why: a quit the guard holds while the window saves (Ctrl+Q on Linux, ⌘Q or Dock Quit on macOS) closes the OCR window first, so the run ended before will-quit flushed the queue and the next task started into the save, only to be cancelled a moment later (measured on Electron 43.8.6). Still no permanent latch: Keep open releases it, and on a quit that goes on cancelAllDocTasks() ends everything anyway.
  • TA-2 — renderer session-store purge moved to the real lock seam (translation audit fix wave, 2026-07-06; finding H3). The purge of the three module-level renderer stores (the live TEXT translation lib/translateSession.ts, the DOCUMENT translation lib/fileTranslateSession.ts, and the vision session lib/visionSession.ts) was dead code: it lived in per-screen useEffects gated on a component-state locked flag read from getAppStatus().workspaceReady. But screens render one-at-a-time and App.lockNow swaps the whole shell to WorkspaceGate (unmounting every screen) the instant lockWorkspace resolves, so the effect could never observe locked === true. The module stores survive the unmount by design (a running job keeps streaming across navigation), so the source text, streamed translation, materialized preview, and image/answer stayed resident in renderer memory for the whole locked period — contradicting each store's "dropped on lock" contract and security-model.md. Fix: a single purgeSessionStores() helper (renderer/lib/lockPurge.ts) that calls all three clear* functions, invoked from App.lockNow right after lockWorkspace() resolves (next to setWorkspace) — the one seam where the lock actually happens. A renderer grep confirmed App.lockNow is the only lock initiator (no auto-lock timer, no main-pushed lock event, no workspace-state polling), so the single call covers every path; the helper is the extension point if another initiator is ever added. The dead locked purge effects — and the confirmed-dead locked EmptyState branches (their gate, workspaceReady === isUnlocked(), is the same signal the shell gates the whole screen on, so it can never be observed while mounted) — were removed from TranslateScreen/ImagesScreen rather than left as a defense-claiming no-op. Also fixes the stuck-busy shape: a mid-stream text session that returned after unlock stuck translating (main's jobs.stop() emits no trError, and adoptActiveJob early-returned on the still-set activeJobId) is now reset by the purge.

  • TA-4 — SSE reader terminal-frame + error-field handling, control-token sanitization (translation audit fix wave, 2026-07-06; findings M2/M3/M4/L1/L4). The raw /completion reader (services/translation/completion.ts) + prompt builder (prompt.ts) were hardened against silent truncation and control-token forgery.

    • M2 (sawFinal). readCompletionSSE treated reader done with no terminal stop:true frame as normal termination, so a server-side close mid-decode resolved the accumulated partial as a truncated "success" (the view emitted trDone with cut text; the doc-task materialized a truncated document). It now tracks sawFinal and, if the stream ends without it and the caller did not abort, throws IncompleteStreamError (a CompletionError subtype — deliberately NOT an AbortError, so both consumers hit their existing retry/fail paths: the view job → runtimeFailed, the doc-task translateWithRetry → retry-then-fail).
    • M3 (error-field). parseCompletionLine handled only data: lines; llama.cpp can emit a mid-stream failure as a bare error: {…} SSE field line (compounding M2's silent-truncation shape). It now recognizes error:-prefixed lines (nested {error:{…}} or a bare payload) and maps them to CompletionError; even an unparseable error field is surfaced, never swallowed. The real pin's error framing is a manual-smoke TODO (needs drive access — not gating).
    • M4 (control-token sanitization). buildTranslationPrompt interpolated source text raw, and llama-server tokenizes /completion prompts WITH special-token parsing — a document containing a literal <start_of_turn>/<end_of_turn> forged a turn boundary (the D2 "translated, never obeyed" guarantee only covered plain-text imperatives). sanitizeSourceText now rewrites the two Gemma turn markers to a visually-identical, non-token spelling using mathematical angle brackets (⟨start_of_turn⟩/⟨end_of_turn⟩ — U+27E8/U+27E9): reversible-safe, human-legible, and confined to those exact markers so ordinary <…> content is untouched. The builder's own scaffold markers are appended AFTER the rewrite, so they survive.
    • L1 (abort throws). An abort between token deliveries used to end the generator cleanly, letting translate() resolve partial output (violating the "resolves with the full text" contract; latent because both consumers re-check the signal). The reader now throws the abort reason instead of returning, matching what an in-read() abort already throws.
    • L4 (garbled-frame counter). The reader's parse-failure branch only ever swallows a genuinely garbled COMPLETE frame (the \n-splitter feeds whole lines, so it is never a partial). It now counts such frames and logs a single content-free log.warn('translation SSE: dropped unparseable frame', { count }) per stream (the count only, never the frame text — privacy rule). New tests/unit/translation-completion.test.ts drives the reader directly (scripted ReadableStream: mid-line splits, CRLF, no-trailing-newline flush, terminal→onFinal, both error shapes, M2/L1/L4).
  • TA-5 — limit-stop detection + view-job empty-window retry (translation audit fix wave, 2026-07-06; findings M6/M7 + test-gap #4). The final frame's stop reason is now LOAD-BEARING for both translation consumers, so an output-limit truncation can no longer masquerade as a clean window.

    • M6 (limit-stop detection). The final frame's stop reason was surfaced only as stoppingWord via onFinal, and NEITHER real consumer passed onFinal — any non-empty reply counted as a clean window, so a greedy-decode repetition loop (the classic temperature-0 MT pathology) or a token-dense window running to the ~2,070-token cap was stitched mid-sentence into the persisted document silently. CompletionFinal gained stoppedEos and a shared isCleanStop(final) helper (both next to it in completion.ts): a window is clean iff its final frame carries a non-empty stopping_word OR the eos flag. Both consumers now thread onFinal and reject a non-clean (limit) window as a FAILED attempt — the doc-task translateWithRetry folds it into the existing retry-then-mark path (empty OR truncated → marked window), so onFinal threading (the smaller diff, keeps the smoke's runtime-layer consumer working) was preferred over resolving {text, final}.
    • M7 (view-job empty/truncated-window retry). The doc-task's retry-then-mark policy lived only in the doc-task handler; the view loop (jobs.ts) accepted whatever each translate() resolved, so one transiently empty (or, post-M6, truncated) window in a multi-window paste completed "done" with a silently missing/cut paragraph. The view loop now retries such a window ONCE and, if it still fails, fails the whole job with the existing runtimeFailed shape — the interactive view surfaces a visible failure rather than inventing a partial-result UI. The genuinely-empty-INPUT fast path is unchanged (rejected badRequest at start).
    • Test-gap #4 (timeout ≠ cancel). A per-request timeout aborts the COMBINED signal with a TimeoutError while the task's own signal stays unaborted, so isAbortError(err, taskSignal) is false and the window is retried-then-failed (never mistaken for a user cancel). This hung on the abort reason's name and was unpinned; doctasks-translation.test.ts now pins it (a TimeoutError single-window run → 2 calls → task fails friendly, not cancelled). Also added: the M6 marked-window case (doc-task) and empty/truncated-window runtimeFailed cases (translate-ipc.test.ts, the view), plus isCleanStop/stopped_eos unit coverage. The manual smoke's header notes stopping_word is now load-bearing (no behavior change expected — a real within-budget window ends on <end_of_turn>).
  • TA-6 — sidecar runtime robustness (translation audit fix wave, 2026-07-06; findings M1/M5/L2/L3). Crash recovery, single-flight teardown, and sender-lifetime binding for the TranslateGemma sidecar (services/translation/runtime.ts, jobs.ts, ipc/registerTranslateIpc.ts).

    • M1 (crash recovery). TranslationRuntime never observed the child dying on its own, so a mid-session crash left this.server pointing at a dead handle: every translate() failed with a connection error, and each failed attempt re-armed the idle clock, so the outage persisted as long as attempts arrived < the 120 s idle window apart. ensureStarted now wires LlamaServer's existing onUnexpectedExit hook (fired only for a healthy child dying outside stop()) to null this.server — identity-compared (if (this.server === server)) so a late crash notice can never clobber a NEWER instance a soft teardown + restart already installed. The next translate() then cold-starts (the doc-task's one retry gets a fresh spawn). The connection-error catch-path fallback (option b) was unnecessary — the sidecar offers the exit callback (option a).
    • M5 (single-flight teardown). teardown() was not single-flighted: a quit stop() arriving while a suspend's kill was in its SIGTERM→2 s→SIGKILL window saw this.server already nulled and resolved immediately (app could exit with the escalation pending → orphan on POSIX), and two overlapping suspends let the second's finally clear tearingDown while the first was still killing (a racing translate() then cold-started during the vault re-encrypt). A shared teardownPromise now holds the in-flight pass (mirroring idleTeardownPromise): an overlapping teardown returns/awaits it instead of starting a second pass, and tearingDown + teardownPromise clear together — via a .finally on the shared promise (which runs on a microtask, so the assignment always wins even when the body completes without awaiting) — only once it settles. While here, a cold start now awaits a live idleTeardownPromise first, so a translate racing a soft idle teardown no longer briefly double-loads ~10 GB (it waits for the dying child, then spawns one).
    • L2 (dead latch removed). TranslateJobService.tearingDown was dead code — stop() has no await (TA-5 left it synchronous), so the flag set and cleared within one synchronous block and no continuation could observe it. The latch (and its defense-claiming comment) were removed; the real defense — stop() aborts every controller's signal before the vault re-encrypts, so a run() scheduled just before then sees signal.aborted — is now what the run() guard checks and the comment states.
    • L3 (cancel-on-destroy; full rebind deferred). trToken/trDone/trError are bound to the starting webContents for the job's life; in the multi-window app a destroyed window dropped those events silently while the job decoded to the 45-min timeout holding the busy lane. translateStart now binds the job's lifetime to the sender: a 'destroyed' listener cancels the job (parity with the lock/quit purge), detached on terminal state so a long-lived window running many translations does not accumulate one listener per call. A full emitter-rebind onto another window via getActive is deliberately deferred (recorded in the TA-wave deferred backlog). Tests: runtime crash-recovery + identity-guard, concurrent stop()+suspend() awaiting the shared teardown, overlapping-suspend tearingDown hold, translate-awaits-idle-teardown (no double spawn); translate-ipc.test.ts destroyed-sender cancel + listener-detach.
  • TA-7 — low sweep, doc drift, wave close-out (translation audit fix wave, 2026-07-06; findings L9/L11/L12, decision L10, doc-drift D1–D5).

    • L9 (window-budget backstop direction). translationUsableTokens clamped contextTokens up to 1024 — the wrong direction: a future manifest with a smaller real context would then budget every window against a larger context than the model has, overflowing all of them. It now uses the REAL context and only falls back to TRANSLATION_FALLBACK_CONTEXT_TOKENS (1024) for a junk/≤0 read (no real context to respect); translationBudgetWords clamps the budget DOWN to what the real context holds rather than inflating past it. Unit case at ctx 512 (doctasks-windows.test.ts).
    • L11 (unbounded tasks map + wrong expired-kind). The manager's tasks map grew for the whole session and the expired-id getDocTask fallback hardcoded kind:'summary'. Terminal tasks are now evicted past DOC_TASK_MAX_TERMINAL_HISTORY (16; running/queued never evicted), and a bounded kindHistory lets an evicted task's late poll echo its REAL kind (never mislabel an evicted translation as a summary). Manager eviction + kind-recovery unit tests (doctasks.test.ts).
    • L12 (persisted English strings). failedWindowNotice + translationAttributionLine are written INTO the generated document, yet were hardcoded English. They now route through tMain (new en+de keys main.translation.failedWindowNotice / .attributionLine, parity compile-enforced) so the materialized document is in the app language at materialization time — the one deliberate persisted-string exception to the canonical-English-in-DB rule. Integration de-materialization assertion (doctasks-translation.test.ts).
    • L10 (ACCEPTED, no code). approxTokenCount under-charges a pathological glued emoji/astral run, so "over-chunk, never overflow" is not an absolute guarantee. Deliberately NOT fixed in this wave (touching the shared chunker for a pathological input is not worth the cross-pipeline blast radius; the failure mode is an honest failed-window notice). Documented in known-limitations.md (translation) + the doctasks/translation.ts header; a real fix belongs in a separate chunker-owned change. (Update 2026-07-17: audit-2026-07-16 F-24 fixed the SIBLING symptom of the same astral gap — surrogate-pair-splitting cuts at window boundaries — with a boundary-only pair-aligned slice in chunker.ts; the under-count itself remains accepted as recorded here.)
    • Doc drift D1–D5. Smoke row / header wording aligned to what the tests assert (identifiers verbatim, numbers/dates localize — packaging.md, translategemma-smoke.test.ts); the doctasks/translation.ts prompt-reserve comment made past-tense; security-model.md log enumeration extended with the content-free error: String(err) failure log; three stale HILBERTRAUM_TRANSLATION_SMOKE → HILBERTRAUM_TRANSLATEGEMMA_SMOKE smoke comments corrected.

Translation audit (TA wave) — outcomes. A four-lens adversarial audit of the shipped TranslateGemma wave (docs/translation-audit-2026-07-06.md, 4 High / 8 Medium / 12 Low + 5 doc-drift) was fixed across TA-1…TA-7, all on master, 2026-07-06 — then the audit report AND the fix plan (docs/translation-audit-fix-plan.md) were folded here and DELETED per the doc-lifecycle rule (git history keeps both). Per phase: TA-1 quit+lock flush the whole doc-task pipeline (H1/H2); TA-2 renderer session-store purge moved to the real App-level lock seam (H3); TA-3 renderer store hardening — per-timer poll latch, post-picker guard, stop/error edges (H4/M8/L5–L8); TA-4 SSE terminal-frame + error:-field handling + Gemma control-token sanitization (M2/M3/M4/L1/L4); TA-5 limit-stop detection + view-job empty-window retry (M6/M7); TA-6 sidecar crash recovery, single-flight teardown, sender-destroy cancel (M1/M5/L2/L3); TA-7 low sweep + doc drift + this close-out (L9/L11/L12, L10-accept, D1–D5). One decision of record: L10 accepted as-is (above).

Follow-up audit (FA wave) — outcomes. A second, full-surface pass over the as-built TranslateGemma feature the same day the TA wave closed (docs/translation-audit-2026-07-06-followup.md, 8 new findings F-1…F-8) was fixed across FA-1…FA-4, all on master, 2026-07-06 — then the working paper was folded here and DELETED per the doc-lifecycle rule (git history keeps it). The F-N / FA-N anchors that code comments cite resolve against the per-finding disposition below. Per phase: FA-1 (F-1, F-4); FA-2 (F-2, F-5); FA-3 (F-6, F-3); FA-4 (F-7, F-8 + this close-out). Suite 3584 / 47 at close (baseline 3580, +4 FA-4 pins). One decision of record: F-7 shipped as option (c), with option (a) rejected-with-reason (below).

Per-finding disposition (F-1…F-8):

  • F-1 (HIGH/MED, correctness) — FIXED (FA-1). View-job retry duplicated already-streamed text into the terminal done. jobs.ts run() now checkpoints job.text after the '\n\n' window separator and restores it via patch() (cancelled-guarded) before each retry attempt, so a transiently-failed attempt's deltas are rolled back and the window lands once. No new IPC (trDone carries the full text).
  • F-2 (MED, latency) — FIXED (FA-2). Both retry loops now classify the failed attempt: a THROW or EMPTY reply is TRANSIENT (retry once); a NON-EMPTY non-clean-stop is a deterministic temperature-0 limit-stop and fails immediately (greedy + cache_prompt reproduces the identical truncation — the second ~30-min decode was pure waste). Abort contract byte-identical.
  • F-3 (MED, UX) — FIXED (FA-3). adoptActiveFileTranslation() mirrors the text path's adoptActiveJob: on Translate-screen mount it reads main's active doc-task over the new getActiveDocTask IPC and, for a running translation task, re-seeds translating + window progress (null-tolerant fileName) and resumes the poll under a fresh generation (pollDocTask extracted + shared with the fresh start). (Superseded in mechanism 2026-08-09, #157 DT-5 / #164 D-7c: the adopt now reads the NEW listActiveDocTasks IPC — running + queued in lane order — and accepts a QUEUED translation too (the #150/DOC-8 acceptance, previously unreachable because a task becomes running in the same tick it becomes runningId); getActiveDocTask stays running-only for the #38 chain-adopt.)
  • F-4 (LOW, leak) — FIXED (FA-1). registerTranslateIpc keeps a jobId → detach map; the destroyed listener is now detached on the cancel terminals (which emit neither done nor error) too. (Addendum, audit 2026-07-16 F-25: FA-1 missed a THIRD terminal — the lock/quit purge jobs.stop() emits neither done nor error AND does not destroy the window, so its listeners leaked one per lock-during-in-flight cycle. TranslateJobService.onStop now notifies the IPC layer, which runs every outstanding detach on a purge.)
  • F-5 (LOW, hardening) — FIXED (FA-2). sanitizeSourceText rewrites the full Gemma special-token family (<bos>/<eos>/<unk>/<pad>/<start_of_image>/<end_of_image> + the two turn markers) to the visually-identical ⟨…⟩ non-token spelling; exact-marker alternation leaves ordinary <…> HTML untouched. TODO(smoke) reconfirms the family against the pinned GGUF tokenizer.
  • F-6 (LOW, correctness edge) — FIXED (FA-3, ahead of F-3). cancelDocTask(jobId?) routes a present id to cancelActiveDocTask(id), which cancels ONLY when the id IS the active task (else no-op); the file store threads its held docTaskJobId through both cancel paths, so a stale/superseding Stop can never kill a foreign task that took the lane. Absent id keeps the active-task fallback for old callers.
  • F-7 (LOW, availability) — FIXED (FA-4), option (c). A latched start failure could permanently disable translation for the session with only "runtime failed" to show. Decision: keep the latch (correct for the permanent case — the reranker precedent) but tag its error with a distinct code (TRANSLATION_START_FAILED_CODE) so both consumers surface actionable "restart the app / free memory" copy (new translate.err.startFailed + main.translation.startFailed, en+de, parity-compile-enforced; content-free — no cause message crosses to the renderer, so security-model logging is untouched). Option (a) "classify OOM-shaped failures as non-latching like bind races" — REJECTED: no reliable transient/OOM signature exists across OSes. Verified against LlamaServer's start surface — the only machine-readable signal is the exit code, and on Windows the OOM / std::bad_alloc exit 0xC0000409 COLLIDES with the PERMANENT #20305 minja template crash, while a Linux OOM-kill SIGKILL is indistinguishable from our own stop(). Un-latching on that signature would also un-latch a genuinely permanent fault → every window re-spawns + re-awaits the full health timeout (the exact cost the latch prevents). Option (b) time-bounding the latch shares that reliance and re-pays the cost on a timer — not chosen. The bind-race exemption is unchanged (a bind race still propagates raw, non-latching).
  • F-8 (NIT, cosmetic) — FIXED (FA-4). The file progress label counted the materialize step (stepsTotal = windows + 1), so a 12-window doc read "(3/13)". A display-only windowProgress() helper in fileTranslateSession.ts subtracts the materialize step and clamps windowsDone, applied on BOTH the fresh-start poll and the FA-3 adopt seed; the doc-task's real progress contract is untouched. (The DocumentsScreen inline-translate label is a separate surface, out of scope, left as-is.)

Deferred backlog (audited in the TA wave, deliberately NOT scheduled — recorded for a later wave).

  • Full emitter rebind on getActive adoption across windows (L3 shipped as cancel-on-destroy only — a destroyed sender cancels its job; a live handoff to another window is not built).

  • Paste-size cap for the Translate view (multi-hour multi-window pastes).

  • GeneratedProvenance lacks the translation language pair (a data-contract addition).

  • Doc-task dedup on a double-clicked Translate (hasPendingKind generalization).

  • extractSegmentTexts abort signal (cancel during a long encrypted-PDF re-parse).

  • Mid-segment split's spurious paragraph break in doc-task output (the view path already avoids it).

  • resolveSidecarSelection dead makeReal param on the translator factory.

  • Drop-zone onDragLeave child-element flicker; duplicate tab stops.

  • File-pane live region (a11y) + partial-output indication after cancel/error.

  • TG-5 — document drag-and-drop in the Translate view (plan §2 D7). A drop zone (renderer/components/FileDropZone.tsx, the one the Images screen renders too since #745 — drag-over state, a WCAG 2.5.7 "choose a document" button, multi-drop rejected) under the input pane. A dropped/picked file does NOT go through the live TEXT job; per D7 it rides the EXISTING translation doc-task: getDroppedFilePath (or pickDocuments) → importDocuments(paths, {destination:{kind:'temporary'}}) → poll getImportJob → startDocTask('translation', docId, {sourceLang,targetLang}) → poll getDocTask → on done load the materialized doc's Markdown (bounded previewDocument) into the SAME output panel + Export (exportDocument) / "Show in Documents" (onNavigate('documents')). NO new parsing/IPC path — provenance, audit and encryption invariants ride the doc-task for free. Orchestrated by a second renderer store lib/fileTranslateSession.ts (the translateSession template — module-level, survives navigation) that owns import + doc-task polling + the result load. One output panel + one busy state (recorded): the screen shows the live text stream OR the file result — ownership is "file if the file session is non-idle, else text" (each path resets the other on start, so at most one is non-idle → remount-safe with no component flag); the screen's single busy = textTranslating || fileBusy disables BOTH triggers, so the file path naturally takes the D9 lane (a real ctx.docTasks task, so the text path's hasActiveDocTask() guard blocks it too). The file path shows numeric window progress (Translating… (3/12)) driven by stepsDone/stepsTotal with the materialize step subtracted for display (FA-4 F-8 — windowProgress()); the text path deliberately shows none. Deliberate deviation from the plan's "poll (lib/doctasks.ts store)": the new store runs its OWN import + doc-task polling rather than the GLOBAL doctasks store's startTask, so the result load never races a foreign acknowledgeDocTask from DocumentsScreen/ChatScreen; the backend still enforces one-task-at-a-time, so the D9 lane holds. Temporary-source lifecycle: the source is imported as a Temporary document (never the Library); the materialized translation is a Generated document (zero membership, findable under Documents). We do NOT bespoke-delete the temporary source — it rides the existing Temporary-lifecycle retention (owner-gated, Phase E.2). Audit stays content-free (the doc-task path already logs ids/kinds only — security-model.md).

  • TG-4 — the Translate view (text path, plan §2 D6). A new 7th primary rail destination (ScreenId 'translate', between Documents and Images — design-guidelines §2 now "7 primary + 1 utility") for live TEXT translation on the SAME ctx.translator sidecar the doc-task uses (no second model). (Rail superseded 2026-09-05: the rail is now three groups plus the brand mark, with Skills folded into Settings as a tab — design-guidelines.md §2 is current, not this count.) A per-job streaming service TranslateJobService (services/translation/jobs.ts, the vision image-job template) behind new IPC — translate:start → {jobId} (validates isTranslationLangCode + source ≠ target + non-empty + a model present; busy-REJECTs a second job; refuses while a doc task holds the lane), translate:cancel, translate:getActive for remount recovery, and STREAM.trToken/trDone/trError(jobId) (additive, the image-channel shape). Single window = fast path; longer text plans with the SHARED planTranslationWindows (Translator.contextWindow() + the D4 clamp — imported, not duplicated) and streams window-by-window (blank-line joins) into ONE output. The renderer store lib/translateSession.ts (visionSession template) keeps a running job alive across navigation; a full reload re-adopts via translate:getActive. D9 busy-gating decision (recorded): the view job takes the SAME one-at-a-time lane as doc tasks — it refuses to start while docTasks.hasActiveTask() (RAM co-residency: 12B translate + a resident chat model + embedder), surfaced honestly as "a document task is running". It does NOT block chat (different sidecar; chat-during-translate relaxation stays TG-6). The doc-task manager is unchanged (D9 "all other kinds unchanged"); the shared --parallel 1 sidecar serializes the rare reverse race at the server. Teardown: TranslateJobService.stop() aborts the in-flight job + purges the map, wired to lock (registerWorkspaceIpc, before translator.suspend()) AND quit (shutdown.ts) — its next window would otherwise lazily respawn the just-suspended sidecar (the TG-3 fix, reused). Audit stays content-free (ids/langs only — security-model.md). END-TO-END VERIFIED live against the real b9849 sidecar (CDP-driven, 2026-07-05): „Guten Morgen. Wie geht es dir?" streamed „Good morning. How are you?" (content-free log); the model-missing EmptyState deep-linked to AI Model. Two review-workflow bugs were fixed first — a persistent-store error banner that reappeared on remount (new store acknowledgeError()), and a multi-window paste that flattened paragraph structure (split on blank lines into segments before the shared planner).

  • TG-3 — the doc-task reroute (BREAKING, plan O2/D3/D4/D5). kind:'translation' consumes ctx.translator via DocTaskDeps.getTranslator — the chat runtime no longer participates (its prompts/temperature were deleted; the manager dispatches translation directly like ocr, outside MODEL_TASK_HANDLERS). Guards: enqueue AND dequeue require a non-null translator (main.translation.noModel, friendly + deep-linked); chat may be entirely absent. Languages widened to the curated 10 (widened to 51 by issue #31 — see D5/#31b) with a required sourceLang (shared/types owns the canonical TRANSLATION_LANGUAGE_CODES; the sidecar's prompt maps key off it — one source of truth). Window planning moved to Translator.contextWindow() + the D4 TRANSLATION_MAX_INPUT_TOKENS = 1800 clamp; the Qwen-measured 1.3/2.0 tokens-per-word constants were carried as conservative defaults here and REPLACED at TG-6 with the Gemma-measured 2.5/3.0 (see the TG-6 bullet above). AppStatus.translationAvailable (from ctx.translator, the ocrAvailable twin) gates the Documents UI. V6 re-verified: resolveModelByRole('translation') carries the manifest's recommendedContextTokens (4096) into the sidecar launch exactly as vision/reranker do.

  • Why a dedicated sidecar (services/translation/). TranslateGemma is served by its OWN lazy llama-server (the FIFTH LlamaServer composition after chat, E5, reranker, vision) — NOT the chat RuntimeManager. Forced: a chat-parsing rework (llama.cpp PR #19419) regressed the --jinja embedded-template path for this model (issue #20305, fix PR #20956 still open — see model-policy.md "The translation role"), so the sidecar launches without --jinja and cannot ride the chat slot (which hard-codes CHAT_SERVER_ARGS = ['--jinja', …]). Desirable anyway: chat stays usable, and ctx/prompt/sampling are model-specific (plan §2 D1/D2).

  • Launch args (runtime.ts, translationServerArgs(device)). --ctx-size 4096 (the model card's 2K input budget + output headroom, plan §2 D4) --parallel 1 (TRANSLATION_SLOT_ARGS — strictly sequential windows; contains the #25142 Windows-Vulkan parallel-translation hang in BOTH device postures) the device posture (issue #42: 'auto' = NO device args → the pin's -ngl auto + --fit on VRAM-aware offload, b9849 and b11146 alike (#660), the chat rung-1 shape; 'cpu' = --device none via TRANSLATION_CPU_DEVICE_ARGS — the only CPU-forcing mechanism, never -ngl) --chat-template gemma (TRANSLATION_TEMPLATE_ARGS — REQUIRED, TG-2 smoke finding: b9849 crashes at STARTUP validating TranslateGemma's embedded template — the #20305 minja crash at init, even without --jinja — so we override it with the built-in legacy gemma template; safe because /completion never applies the chat template). NO --jinja, NOT CHAT_SERVER_ARGS. Since #605 also --batch-size 512 --ubatch-size 512 (TRANSLATION_BATCH_ARGS: a progress frame per batch; see the "#605 amendment" at the end of this record).

  • Prompt in app code (prompt.ts), raw /completion (completion.ts). The trained single-user-turn prompt is formatted in buildTranslationPrompt (our own code → English name map — the template's dictionary is unusable without jinja) and POSTed to the native /completion endpoint with temperature 0 (greedy MT) + stop: ["<end_of_turn>"]; readCompletionSSE parses the bare-object stream (NOT readChatSSE's choices[].delta shape; since #605 with that reader's liveness clocks and return_progress). Source text inside {TEXT} is translated, never obeyed (no "part n of m" scaffolding, D2). VERBATIM template reconciliation (plan §7 V1) is done by the translategemma-smoke harness against the server's /props.

  • Lifecycle — a hybrid. The vision RUNTIME-4 SOFT idle-teardown interlock (120 s default, HILBERTRAUM_TRANSLATION_IDLE_MS; re-armed only when the last in-flight window settles) bounds the ~10 GB co-residency window (plan §2 D9); the reranker stop() (permanent, quit) vs suspend() (soft, workspace lock → lazy restart) split + tearingDown/bind-race-forgiving startFailed latches keep the session-held instance safe across lock/unlock. A cancel ends a window's wait for a cold start without cancelling the start, and the start arms the idle clock itself when it lands (#637, image-understanding record §6 "#637 amendment"). Availability-driven: resolveModelByRole('translation') → resolveSidecarSelection → createSelectedTranslator (null when binary/weights absent; no mock — plan O2). Composed in compose-services.ts, carried on AppContext.translator, stopped on quit (shutdown.ts) + suspended on lock (registerWorkspaceIpc).

  • TG-2 gate — PASSED. The translategemma-smoke harness RAN on the real b9849 Vulkan pin (2026-07-05) and PASSED: clean DE↔EN translation, injection-resistant, no stop-token leak, ~3.7–4.0 tok/s CPU decode, ~9.5 GiB peak RSS. Its load-bearing finding is the --chat-template gemma startup fix above (without it b9849 can't start on this model).

  • TG-6 — calibration + closure (the measurements the design rests on). The manual smoke + llama-tokenize re-measured the REAL Gemma tokenizer + runtime on the pin (full table in model-benchmarks.md §11). The load-bearing finding: the Qwen3-4B-measured planner constants (1.3 input / 2.0 output tokens-per-word, carried as "conservative defaults" through TG-3) were unsafe on the Gemma tokenizer — real input runs to 2.26 tok/word (Czech; en 1.11 … cs 2.26 on realistic prose, 2.8 on token-dense invoice lines) and output to 1.96 tok/source-word (word-sparse German → dense Slavic/Cyrillic; dense short samples ~3.06). At the old constants a full ~1,150-word window would have been ~3,200+ input tokens alone, overflowing BOTH the 2K trained input and the launched 4096 context (silent truncation). Fix (doctasks/translation.ts): a translation-specific TRANSLATION_INPUT_TOKENS_PER_WORD = 2.5 (NOT the shared SUMMARY_TOKENS_PER_WORD, which is the chat model's summary factor for a different tokenizer) + TRANSLATION_OUTPUT_TOKENS_PER_WORD = 3.0, both conservative ceilings over the measured maxima so a window can only OVER-chunk, never overflow (the D4 clamp still binds: at 2.5 tok/word a clamp-word window's input stays under 2K). Windows shrink to **690 words** (windowMaxTokens ≈2,071) — the honest cost of the heavy tokenizer. (Raised to 2.8 / 3.1 by #512 on 2026-09-27 — 642-word windows; see the #512 bullet at the end of this record.) D8 (GPU): TG-6 KEPT the CPU pin for v1 (~3–4 tok/s tolerable for a background doc-task; GPU deferred, not rejected) — superseded by issue #42 (2026-07-09), which pulled GPU forward: see the issue-#40/#42 bullet below. The per-window timeout was recalibrated to 45 min (a ~2,070-token full window at the observed-worst ~1.1 tok/s is ~30 min; it stays — an upper bound is harmless on a fast GPU decode; since #605 a hung sidecar ends much sooner, see the "#605 amendment"). D9 (chat-during-translation relaxation): KEEP serialization — co-residency measured ≈13.2 GiB (translation ≈9.2 + a 4B chat + embedder); a 12B chat pushes the pair past a 16 GB machine, so two large models decoding at once is infeasible. min-RAM (D10): recommended_min_ram_gb reset to 17 (the §4 peak+3-headroom rule applied to the measured 13.24 GiB co-residency floor, which excludes the Electron shell) — superseded by PR #30 (2026-07-07, issue #164 D-1 marker): the shipped manifest carries 13; the 17 had erroneously baked the CO-RESIDENCY floor into the hard minimum, locking translation out of 16 GB machines it runs on (model-benchmarks §11.2 records the correction). Pre-ship gap — CPU safety-net binary: the pinned pure-CPU b9849 build was fetched + SHA-256-confirmed against the runtime-sources pin (fa7d9d93…4352, exact) at TG-6, but the RUN is still pending: on the dev box Windows Defender quarantines the freshly-downloaded, unsigned llama-server.exe on execution (only that exe was removed; every sibling exe survived), and adding an AV exclusion needs admin. The substantive CPU DECODE path is already fully exercised — every TG measurement runs --device none (pure CPU) on the b9849 server, and the CPU-only binary shares identical server/template/tokenizer code (differs only in omitting the Vulkan backend). Run the cpu-safety-net leg on a drive/CI where the CPU build ships AV-allowlisted before release.

  • Issue #31 (2026-07-07) — false failure banner on every successful translation + language-set widening. Two beta findings, one wave.

    • #31a — isCleanStop misread the pinned server's final frame (the "translation works but the failure banner always shows" bug). TA-5 M6 keyed the clean-stop test on stopping_word / stopped_eos — the LEGACY llama-server fields. The server rework that predates the b9585/b9849 pins consolidated the stopped_eos/stopped_word/stopped_limit booleans into ONE stop_type field ('none' | 'eos' | 'limit' | 'word'), and on Gemma a finished turn ends on <end_of_turn> as an EOS-class token — so the real success frame is stop_type: "eos" with an empty stopping_word and NO stopped_eos. isCleanStop therefore returned false for every successful window; the view job classified it a deterministic limit-stop (FA-2 F-2: non-empty + no clean stop ⇒ no retry) and failed the job runtimeFailed AFTER the full translation had already streamed — the issue's always-on "Das Übersetzungsmodell konnte nicht fertigstellen" banner. The doc-task path took the same misread into its retry-then-mark branch (every window retried once — a full duplicate ~30-min CPU decode — then marked "could not be translated" even though the text was fine). Fix (completion.ts): CompletionFinal gained stopType (parsed from the frame's stop_type); isCleanStop is now stop_type ∈ {eos, word} OR the legacy signals (non-empty stopping_word / stopped_eos: true), so older frame shapes and the scripted test translators stay valid, and a REAL limit stop (stop_type: "limit") still fails the window. Regression-pinned in translation-completion.test.ts with the exact b9849 success- and limit-frames; the manual smoke's window log now prints stop=<stop_type> (TA-5's "no behavior change expected" note was wrong precisely because the smoke predated M6 — the smoke asserted output fidelity, never the frame fields M6 later keyed on).
    • #31b — language set widened from the curated 10 to the 51-code WMT24++ production tier (owner decision on the issue). TRANSLATION_LANGUAGE_CODES now carries the 55 WMT24++-evaluated locales (arXiv:2601.09012) collapsed to 51 bare codes (regional/script variants fold into base codes; zh = Simplified). The list REMAINS closed + server-side validated (D5's shape survives; only its extent changed): the template's ~160 languages include ~105 experimental (GATITOS/SMOL) ones Google flags for higher hallucination — those stay out. Per-language round-trip evidence: the original 10 keep their TG-6 smoke record; the widened 41 ship on the model's own WMT24++ evaluation (MetricX-24 3.60 / COMET22 83.5 for the 12B). English prompt names follow the template dictionary where known (fa "Persian", zh "Chinese (Simplified)") — the GGUF tokenizer.chat_template stays the verbatim authority, reconciled at the next manual smoke. Planner safety on the new space-less scripts (ja/zh/th/…): approxTokenCount charges them per-character (over-counts vs the real tokenizer), so windows still only ever OVER-chunk. The smoke's calibration leg deliberately keeps measuring its curated-10 samples (SMOKE_LANGS); the pickers render all 51 native names, defaults stay de/en.
  • Issues #40 + #42 (2026-07-09) — restart-free activation + GPU offload. Two beta findings, one wave.

    • #40 — the translator selection was frozen at startup. composeServices ran once in initBackend, so downloading TranslateGemma mid-session left ctx.translator null until a restart — while the Translate empty state kept pointing the user at the download flow (a circle). Fix: DownloadManager gained onModelInstalled (fired once when a job reaches done, after every file is renamed into place — placeholder-hash completions included, since the selectors are presence-driven); the IPC wiring routes it to AppContext.onModelInstalled (main/index.ts), which re-runs composeTranslator (compose-services.ts — the ONE construction startup and refresh share) and re-assigns ctx.translator only when the slot is null or the current instance reports isStartFailed() (shouldReplaceTranslator; full-audit 2026-07-10 BE-7 — a latched instance is lazy/dead with no child to orphan, so the delete-and-re-download repair now activates without a restart; a live sidecar is never replaced). Every consumer reads ctx.translator live (translate jobs, doc tasks — whose getTranslator was the one startup-const capture, now fixed — core-status IPC, lock/quit teardowns), and the Translate screen already re-reads translationAvailable on mount/focus. Scope: the transcriber/reranker/embedder keep the restart requirement — their handles are captured at IPC-registration/ingestion-wiring time (registerDocsIpc deps, getIngestionDeps), so a ctx re-assignment alone would activate them inconsistently; adopting the same seam there needs its own capture-site pass (known-limitations.md records this). Tests: downloads.test.ts (hook fires once on done, on unverified too, never on failed/cancelled, hook faults can't fail the job) + compose-translator.test.ts (real temp-drive layout: null → live selection as the GGUF lands).
    • #42 — GPU offload for the translation sidecar (TG-6's deferred D8, pulled forward). The sidecar now runs a two-rung device ladder (runtime.ts): per COLD START it re-reads the SAME Settings signals the chat ladder gets (gpuMode + gpuAutoDisabled, injected as TranslationGpuDeps from the shared gpuSignals in main/index.ts) — allowed ⇒ launch with no device args (the pin's -ngl auto + --fit on, b9849 and b11146 alike; on a GPU-less box that IS CPU mode), else --device none. A non-bind-race GPU start failure retries once at forced CPU within the same start and arms a session-scoped gpuFellBack latch (later cold starts pin CPU — no repeated GPU health timeouts); a mid-session crash of a GPU-composed sidecar arms the same latch (the chat §5.3 auto-fallback, session-scoped), so a doc-task's per-window retries can't crash-loop a ~10 GB GPU load. Only the FINAL (CPU) rung failing arms the permanent startFailed latch (F-7 semantics preserved); a bind race stays raw/retryable and touches neither latch. The latch deliberately never writes the persisted gpuAutoDisabled — a 12B translation model can fail on a GPU where the smaller chat model runs fine, and chat's ladder owns that flag; translation only reads it. #25142 stays contained by --parallel 1 in both postures; the 45-min window timeout stays (upper bound, harmless on GPU). The idle-teardown + per-cold-start re-read mean a Settings flip needs no restart. Open owner action: the GPU-decode re-smoke on a real GPU drive (model-benchmarks.md §11.4) — the smoke now defaults to the shipping 'auto' posture (HILBERTRAUM_TRANSLATEGEMMA_SMOKE_DEVICE=cpu re-measures the CPU calibration). Tests: the translation-runtime.test.ts ladder suite (off/auto-disabled pin CPU, per-cold-start re-read, GPU-fail → CPU fallback + latch, final-rung-only startFailed, bind-race neutrality, mid-session GPU crash latch, CPU crash does NOT latch).
    • #42 reopen (2026-07-10) — cold-start observability. Field-verified on an RTX 3090: the ladder works, but under --fit a large RESIDENT chat model silently squeezes the 12B into leftover VRAM — a partial offload at ~CPU speed, with no failure for the fallback hook to see and no log/UI trace (the fit is also pinned per cold start until the idle teardown re-fits). Fix (observability only, no ladder change): LlamaServer gains an onStderrData tap; the translation runtime parses the server's own load_tensors: offloaded X/Y layers to GPU line (a rolling window across chunk boundaries — the only place the real fit outcome is reported), fires onStarted once per successful cold start (compose-services logs "Translation sidecar started" with posture + split, symmetric with the chat "started via rung …" line), and exposes deviceStatus() (last-known survives the teardown, live flags a current child) → getAppStatus().translationDevice → the Translate screen's muted #36-style device line, whose partial-offload form names the ~CPU speed and whose tooltip carries cause + remedy. Field numbers + the contention case: model-benchmarks.md §11.4; user-facing shape: known-limitations.md "Document translation". Tests: translation-runtime.test.ts ("cold-start device observability" — chunk-split parse, once-per-start, the CPU form (since #671 from real captures, which print the split under --device none too), throwing hook harmless; the ladder suite's GPU-fail → CPU row pins that the fallback lands as 'cpu'), core-model-ipc.test.ts (status feed), TranslateScreen.test.tsx (hint forms + absent-before-first-start).
  • Translation-audit wave #156–#165 (2026-08-09) — the read-only pipeline audit's fixes, one branch. Behavioral deltas to this record (details in the issues + the wave PR): (#156) extractTranslationSource forwards the OCR engine, so image-source documents translate/compare instead of failing "sourceUnreadable". (#157) targeted cancel is EXACT-ID (running or queued; stale-safe by construction) and the reload adopt reads the new listActiveDocTasks lane list (queued translations adoptable — see the F-3 supersede note above). (#158) the import/re-index deep-index offer runs after the processing release, so the Q1/Q4 auto-build fires with a runtime up. (#159) LlamaServer gained an opt-in startAbortSignal; the translation teardown aborts an in-flight cold start (child killed inside the health wait, start rejects AbortError, never latches startFailed, never walks the CPU rung mid-teardown) — lock/quit no longer block up to the 180 s health timeout. (Audit 2026-09-02 REL-10, #244: the E5 embedder, the reranker and the vision runtime now carry the same per-start AbortController + startAbortSignal + isStartAbortError latch bypass, abort-first in their teardowns — every lazily-started llama-server wrapper aborts an in-flight cold start on lock/quit; tests/integration/sidecar-teardown-abort.test.ts bounds all four at < 5 s under production defaults — typically one health-poll, ≈ 5 s worst case with the 3 s probe timeout and the 2 s SIGTERM grace — where the three used to take the full 180 s and then latch.) (#635: a caller's own Stop is the other half. It ends only that caller's wait for the start (waitUnlessAborted), never the start, which other callers may share — the embedder and the reranker since 2026-10-07 (rag-design.md §12.4 "#635 amendment"), vision and translation too (#637, image-understanding record §6 "#637 amendment").) (#160) the F-2 retry classification splits the per-request timeout by tokens-flowed (live-decode timeout = deterministic, no retry; wedged = one retry) in BOTH consumers; the view paste is bounded by TRANSLATE_MAX_TEXT_CHARS ('tooLong'); run() defers a microtask so no terminal can emit before start() returns. (#165) the translation planners pack in the budget's own WORD unit (approxBudgetWordCount — the token estimator's defenses in word currency; summary packing byte-identical), ending the 1.5–2.5× window under-fill on compound-heavy prose; the Translate screen adds the "Reading…"/"Saving…" phase labels and the file store skips no-op poll writes. Frontend deltas (#161/#162) live in the screens (always-mounted ErrorBanner, single-control drop zones, visible device remedy, doc-path sameLang guard).

  • #512 (2026-09-27) — planner constants raised to 2.8 in / 3.1 out (owner decision 3). TRANSLATION_INPUT_TOKENS_PER_WORD 2.5 → 2.8, TRANSLATION_OUTPUT_TOKENS_PER_WORD 3.0 → 3.1. The basis is the curated-10 measurement (owner-accepted; the other 41 languages were not measured): the translategemma smoke's short 19–23-word samples reach 2.79 input / 3.06 output tokens per word on both b9849 and b11146, while realistic prose stays at ≤ 2.26 / ≤ 1.96. So this is a deliberate margin for token-dense text (invoices, tables), not a correction for prose, which was already under 2.5 / 3.0. At the launched ctx 4096 the D4 clamp now binds — floor(1800 / 2.8) = 642 words, where the context split would allow 643 — and windowMaxTokens is 1,998 (was 690 words / 2,071). A full window of ~2.8 tok/word text is ≈ 1,798 input tokens plus the scaffold, under TranslateGemma's trained 2K input; at 690 words it was ≈ 2,080, just over. The cost is about 7 % more windows per document. The 45-min per-window timeout is unchanged (a ~2,000-token window at ~1.1 tok/s is still ~30 min).

  • #605 amendment (2026-10-08) — liveness clocks for the translation stream; a hung sidecar is restarted. Before, readCompletionSSE had no idle watchdog: only the 45-min request cap and one retry bounded a window. The issue's "about 90 min" was wrong, because Electron's fetch (undici 7.29.1) ends 300 s of byte silence or header wait by itself (measured under #594 and #607). The real cost per window:

    • a prefill wedge with pings ≈ 50 min: the cap, then the retry queued behind the stuck slot until undici's header limit;
    • a decode wedge 45 min: timed out mid-decode, so not retried (#160);
    • a frozen process ≈ 10 min.

    Nothing restarted the sidecar, so every later window of a document waited ≈ 10 min more. All that time the doc-task lane refused chat, other document tasks, the local API, benchmark and skill runs and the engine update. The 12B also stayed resident, since the idle teardown cannot fire mid-job, and a GPU-posture sidecar kept the card from the reranker (gpuOccupied).

    Facts, verified at both pins (upstream source at 7fe450e1 / 799fcc04, and captures on DesktopDiT):

    • The native /completion stream carries prompt_progress when the request sets return_progress (server_task_result_cmpl_partial::to_json_non_oaicompat). The frame carries no text (content "", tokens [0]). One comes with the headers, then one after every n_batch decode (post_decode).
    • The default n_batch is 2048 (common.h; the physical n_ubatch is 512). So a window of up to ~1,950 prompt tokens prefilled as ONE batch, with nothing between 0 % and 100 % (captured: 1,263 tokens, the 100 % frame at 29.9 s).
    • --batch-size 512 keeps the compute, because the physical batch is 512 either way. Prefill: 29.9 / 28.6 s at the default, 30.8 / 26.3 s at 512 (the 4B, 1,263 tokens, the CPU posture). A 14B took 33.6 / 36.1 s per 512-token batch on the i7-8700's CPU.
    • Every decoded token sends a frame, but its content can be empty: the server holds text back while it may be the start of the stop string (captured: <end_of_turn> as five text-less frames). Hybrid / SWA models take the last few prompt tokens apart for a context checkpoint (1018 → 1022).
    • Pings start only after the headers (set_next). Before them, the handler waits for the first result.

    As built (owner calls 2026-10-08; the first wording of the budget questions was unclear to the owner and was re-asked in plain words):

    • TRANSLATION_BATCH_ARGS (--batch-size 512 --ubatch-size 512) goes into translationServerArgs, so the manual smoke follows. Every window sends return_progress: true.
    • readCompletionSSE races each read with the chat reader's readWithIdleTimeout, on its own budgets (TRANSLATION_IDLE):
      • the process clock, 120 s: any byte re-arms it, pings included;
      • the compute clock, 10 min per progress frame (owner). The slowest per-batch estimate is ~2.4 min on the slowest laptop measured, ~8 min under memory pressure;
      • the decode clock, 120 s (owner): it starts at the first token FRAME (text or not), and only model output re-arms it — any data, the #594 rule — never pings.
    • The /completion headers wait HEADER_WAIT_MS, 180 s (chat's value). The 45-min cap stays as the outer bound for a decode that is alive but too slow (#160, not retried).
    • Either error is chat's RuntimeUnresponsiveError. TranslationRuntime.restartHung then stops the hung child as a soft teardown (idleTeardownPromise): a racing translate waits for the kill, and a lock or quit awaits it. The posture is kept (owner): a hang does not latch the session to the CPU, unlike a GPU-posture crash.
    • Both consumers retry the window once, tokens or not. The error is not a TimeoutError, so the #160 rule does not apply. The existing runtimeFailed copy and the failed-window notice fit unchanged.
    • Requests take the one slot in turn (takeSlot, from the code review). A document translation can start while a Translate job runs (jobs.ts D9), and the two used to queue at the --parallel 1 server. There the second request's wait for its headers covered the first one's whole window, which the header wait would read as a hang and so stop a healthy sidecar under both. Now they queue in the app, and a cancel ends a queued window's wait at once.

    Tests:

    • translation-sse-progress-fixture.test.ts replays four real captures (b11146 legitimate prefill, prefill wedge, decode wedge; b9849 legitimate) at the production budgets.
    • translation-completion.test.ts "liveness clocks" covers a silent process, held-back tokens and a Stop mid-read.
    • translation-runtime.test.ts "#605" covers the restart, the header wait, the one-slot queue, and the argv and body.
    • The #160 neighbours in translate-ipc and doctasks-translation pin the retry.

    Real app (2026-10-08, DesktopDiT): the dev build over CDP, b11146 in the CPU posture, and the qwen3.5-9b as a stand-in in the translation slot (there are no TranslateGemma weights on that machine). "Before" is master's reader and runtime swapped in.

    • Whole process frozen 3 s into a 400-word Translate job.
      • Master failed the job 609 s after the freeze: terminated at 301 s, then the retry's fetch failed at +306 s. The frozen process stayed the sidecar.
      • The fix ended the attempt 120.0 s after the last byte and had a fresh sidecar up 6.3 s later. The retry finished the translation.
    • One compute thread suspended mid-decode, pings still flowing.
      • Master was still waiting 321 s later.
      • The fix ended the attempt 120.0 s after the last token, and the retry finished.
    • One compute thread suspended mid-prefill: the fix ended the attempt 600.0 s after the 0 % frame, although the pings kept coming. The retry finished.
    • A three-window document translation, the sidecar frozen 8 s in: window 1 ended at 120 s. Its retry and windows 2–3 ran on the fresh sidecar, and the task finished with no failed window.
    • A Translate job and a document translation started together (after the code review): the document's first window waited in the app for 919 s behind a 640-word Translate window, slowed by a test run beside it. No hang was declared and no sidecar restarted; both finished on one sidecar, the document with no failed window. Without the queue it would have been declared hung at 180 s.

    Accepted:

    • A hang that recurs on a fresh sidecar for the same window fails that window twice, at ≈ budget + cold start each. A document marks it and moves on.
    • A window sent right after a cancel waits for the cancelled request's current 512-token batch. When that batch takes longer than 180 s (a slow laptop under memory pressure), a healthy sidecar is restarted: one cold load, then the retry. The header wait must stay under Electron's own 300 s limit, or a pre-header hang would end as a plain "fetch failed" and restart nothing.
    • The compute budget rests on a 14B proxy and scaling: no TranslateGemma prefill has been measured on the slowest laptop.
  • #671 amendment (2026-10-13) — a start's own GPU buffers say where translation ran, never the offload line. The device hint and the Performance row read the layer split as the measure of the card. The line is no evidence of a card (the GPU record's §5.2 "#653 amendment"), and it reached the user:

    • No usable graphics device. The #473 gate answers 'auto' when no usable device is on record (budgetMib == null), so the sidecar started with no device args and printed offloaded 49/49 layers to GPU. The Translate screen said "runs on the graphics card (GPU, 49/49 layers)" while VRAM stayed flat.
    • Every forced-processor start. --device none prints the same line beside a visible card, so deviceStatus() carried 49/49 and the "Models on this computer" row read "processor · 49 of 49 layers on the card". That is the common case on any card TranslateGemma does not fit (#473's too-large, beside-chat, chat-starting), on every 8 GB card. The issue did not name it. The #42-era premise "a forced-CPU start prints no offload line", pinned by a test row with a hand-written log, was never measured.

    Facts (DesktopDiT, GTX 1070 Ti, TranslateGemma 12B Q4_K_M, the sidecar's exact argv, captured load-only): with the card hidden (GGML_VK_VISIBLE_DEVICES=7), b11146 and b9849 both print 49/49, every buffer on the processor (CPU_Mapped, CPU_REPACK, CPU KV and compute), VRAM unchanged. --device none beside the card prints the same. The 'auto' posture on the card places 39/49, with model, KV and compute buffers on Vulkan0.

    As built:

    • The runtime reads its load log with the chat runtime's createPlacementParser, not its own regex. The parser keeps the split, and it reassembles lines across chunks, which covers CODE-22. It is fed until the start lands; the reading is taken once.

    • It records TranslationDeviceStatus.gpuBuffers from the parser's gpuBufferEvidence(), which reads #653's holdsGpuBuffers both ways:

      • true means a buffer landed on a device the log's device_info lists as a GPU;
      • false means every buffer the log printed was under a processor-side label (CPU, CPU_Mapped, CPU_REPACK, *_Host);
      • null (absent on the wire) means nothing to judge by: no buffer line, or a buffer under a label that is neither processor-side nor a listed GPU.

      The review asked for that last case to stay open. Chat uses the evidence only positively and has the probe behind it. Translation would use it negatively, so a device_info block that a future pin prints differently would have turned every start on the card into "the processor".

    • One rule, translationRanOnProcessor (shared/runtime-status.ts): a 'cpu' posture, or gpuBuffers === false. The Translate screen, the Performance row and the runtime's occupancy all read it.

    • The Translate screen shows the plain translate.device.cpu copy, with no cause: the screen cannot know why no device was usable.

    • The Performance row says processor for such a start, and a row that says processor shows no split at all, whatever the sidecar printed. The RAM total then counts the whole model.

    • gpuOccupied() and yieldGpu() read the same rule: a resident sidecar that put nothing on a graphics device neither blocks the reranker's card posture nor is stopped for a chat start.

    • Its crash no longer arms the session CPU latch, following chat's #599 rule for a CPU-mode crash.

    • "Translation sidecar started" logs gpuBuffers.

    • The 0-layer rule in yieldGpu is unchanged, although that start still holds its compute buffer on the card (#653's -ngl 0 measurement).

    • The row's device follows the last start, as it followed the posture since #42. Gating only the new evidence on live would make the row disagree with itself (review finding, declined).

    Real app (dev build over CDP, scratch Kit roots, b11146, German UI):

    • Card hidden: master said "Übersetzung läuft auf der Grafikkarte (GPU, 49/49 Schichten)" and "Prozessor · … · 49 von 49 Schichten auf der Karte"; the fix says "… auf dem Prozessor (CPU)" and "Prozessor · wird bei Leerlauf entladen".
    • Card visible (too-large, --device none in the OS argv): the hint was already right on master and stays the same; the row loses master's "49 von 49 Schichten auf der Karte".

    Tests:

    • translation-runtime.test.ts replays the three captures (placement-b11146-translategemma-{gpuless-49of49-cpu,devnone-49of49-cpu,partial-39of49}.txt, which are in the DR3 net of placement-parser.test.ts), with gpuOccupied, yieldGpu and crash rows.
    • placement-parser.test.ts covers the edge rows of gpuBufferEvidence.
    • TranslateScreen.test.tsx and performance-gpu.test.ts cover the hint and the row.

    Residuals:

    • A Sapphire Rapids PC with no usable card whose model lands in ggml's AMX buffer reads as unknown, so the hint keeps master's "graphics card" form there.
    • A device_info block that a future pin prints differently reads as unknown too, which is the safe direction. The re-capture rule at each pin bump still catches it.

§-anchor legend (historical plan citations)

The retired translategemma-translation-plan.md was folded — its decisions into this record + the docs below, its facts/license into model-policy.md, its measurements into model-benchmarks.md §11. In-code comments and the kept docs still cite plan §N, DN, ON, VN, TG-N — the numbers were never renumbered, so this legend keeps them resolvable (the doc-lifecycle "stable anchors" intent, the "Functionality wave 3" precedent) without churning ~40 comments. Read a historical anchor as:

Plan anchor Meaning Now lives in
O1 License: Gemma Terms pending; download behind the ack gate; not bundled model-policy.md "The translation role" license-review record
O2 Require the model (no chat fallback) D3 below + known-limitations.md "Document translation"
O3 12B only; 4B/27B manifest-only follow-ups D-table below + model-benchmarks.md §11 (promotion bar)
O4 Curated 10 languages D5 below + shared/types.ts (TRANSLATION_LANGUAGE_CODES guard)
§1 / §1.1 Verified facts (gemma3 arch, 2K input, GGUF source, --jinja/#20305) model-policy.md "The translation role" (architecture facts + research note)
§2 D1–D10 Design decisions the decision table below (and the bullets above)
§3 Data-contract changes (translation role, widened langs, translate:* IPC) as-built in shared/manifest.ts / shared/types.ts / shared/ipc.ts
§4 (TG-1…TG-6) The six phases the per-wave BUILD_STATE.md log
§5 Risks (#20305, #22908, #25142, Gemma Terms, RAM co-residency, drift) the bullets above + known-limitations.md
§6 Non-goals (image translation, 4B/27B, auto-detect, chat-during-translate) this record + model-benchmarks.md §11
§7 V1–V6 Re-verify-at-implementation items (all resolved) V1 prompt reconciled (smoke /props); V2–V4 URL/filename/sha256 (model-policy.md + manifest); V5 #20305 still open (model-policy.md); V6 recommendedContextTokens (the launch)

Decision table (D1–D10, as resolved):

# Decision As built
D1 New translation role + dedicated lazy sidecar services/translation/runtime.ts — own LlamaServer, --parallel 1, 120 s soft idle teardown, availability-driven via resolveModelByRole('translation')
D2 No --jinja; app-side prompt + raw /completion prompt.ts (trained single-turn format, own code→English-name map) + completion.ts (bare-object SSE); --chat-template gemma avoids the #20305 STARTUP crash
D3 Hard model requirement (O2) enqueue+dequeue require a non-null Translator; friendly main.translation.noModel + deep link; chat may be absent
D4 2K input budget, structurally enforced --ctx-size 4096 + TRANSLATION_MAX_INPUT_TOKENS = 1800 clamp in planTranslationWindows; TG-6 sized the tokens-per-word constants so the clamp binds in REAL tokens
D5 Curated 10 languages, source+target TRANSLATION_LANGUAGE_CODES (shared) + native-name selects; no auto-detect. Superseded in extent by issue #31 (2026-07-07): widened to the 51-code WMT24++ production tier — still a closed, server-validated list (see the issue-#31 bullet above)
D6 Translate view = 7th primary destination TranslateScreen + TranslateJobService (translate:* IPC, trToken/trDone/trError)
D7 Dropped/picked documents ride the doc-task FileDropZone → import {kind:'temporary'} → startDocTask('translation') → materialized Markdown
D8 GPU posture CPU-pinned shipped at TG-2; TG-6 kept it (GPU deferred, not rejected). Superseded by issue #42 (2026-07-09): a two-rung device ladder honours gpuMode/gpuAutoDisabled per cold start — GPU auto-offload by default, forced-CPU fallback + session latch on a GPU fault (see the issue-#40/#42 bullet above); the GPU-drive re-smoke (§11.4) is the open owner action
D9 Concurrency guards stay doc-task FIFO + chat↔task exclusion + view-job docTaskBusy; TG-6 KEEPS them (co-residency ≈13.2 GiB rules out two large models decoding at once)
D10 Manifest discipline rank 0, profiles [], not bundled, license_review: pending; recommended_min_ram_gb set to 17 (§4 rule on the TG-6 co-residency floor 13.24 GiB). Superseded by PR #30 (2026-07-07): shipped value 13 — the 17 baked the co-residency floor into the hard min (model-benchmarks §11.2)

Functionality wave 3 — design record (Phases 31–38, decisions D23–D37 + research gates)

The wave — conversation search · vault password change · document tasks + summary · translation · compare · audio transcription · voice dictation · scanned-PDF/photo OCR — shipped 2026-06-11 (Phases 31–38 ALL DONE). The as-built per-feature mechanisms live in the sections above (Conversation search under "Chat & streaming"; "Audio transcription", "Voice dictation", "Scanned-PDF / photo OCR", "Document tasks") and in security-model.md (password change, descriptor v2, dictation + scoped-permission data-paths), model-policy.md (the whisper.cpp transcriber family + the OCR asset class + their licenses), drive-layout.md (whisper family + ocr/ assets), known-limitations.md, user-guide.md, PRIVACY.md. This record keeps the wave's DECISIONS and the RESEARCH-GATE evidence — the content the retired docs/functionality-wave-3-plan.md carried as a unit, folded here when that plan file was deleted in the 2026-06-29 doc cleanup (the full original plan, drafted 2026-06-10 with review round 1 + plan audit 2026-06-11, is in git history). Decision numbering continues the project-wide sequence (D1–D7 wave 1 · D8–D15 retrieval · D16–D22 catalog · D-UI1–4 UI wave).

§13 Decisions (D23–D37)

# Decision Resolution
D23 Search ranking RESOLVED (round 1): bm25 with newest-first tie-break; revisit with use
D24 Password-change mechanism RESOLVED (round 1): (b) envelope descriptor v2, migrate-on-first-change — a random data key wrapped by the password-derived KEK; first change pays the one-time v1→v2 bulk re-encrypt (journaled swap), every later change is an atomic single-file re-wrap. O(1) recurring change, atomic commit point, unlocks future key features (recovery codes, rotation); v1 vaults untouched until they opt in. Direct re-encrypt and migrate-on-unlock rejected
D25 Summary persistence + long-doc strategy RESOLVED (round 1): documents.summary_json + budgeted map-reduce with hard ceiling + honest truncated flag. Alternatives (summary-as-conversation, unbounded map-reduce) rejected: surface sprawl / CPU latency
D26 Doc-task concurrency vs chat RESOLVED (round 1): strict one-at-a-time — tasks serialize among themselves (one queue), a task refuses to start while a chat answer is streaming, and a chat message sent while a task runs gets friendly copy ("A document task is running — you can cancel it"). Tasks are cancellable so the user is never stuck. R-T1 demoted to informational (see §14); revisit parallelism only with evidence
D27 Translation output form RESOLVED (round 1): materialized corpus document (" (Deutsch)" — since issue #31 the title label spans all 51 native names, #164 D-5) + origin_json provenance — searchable/citable/exportable, encrypted for free. Export-only and a dedicated results panel rejected (results leave the workspace / a whole new surface). Implemented in Phase 34
D36 Translation input: chunks vs re-parse RESOLVED (Phase 34, 2026-06-11): re-extract the parser's SEGMENTS from the stored copy (the extractDocumentPreview path) and window them with the D25 budget math. Stored chunks overlap by ~80 tokens — in-order concatenation duplicates text at every boundary, which a summary tolerated (D25) but a faithful translation cannot; trimming the overlap out of adjacent chunks was rejected as heuristic (chunk text is whitespace-normalized) where the re-parse is exact. Cost = one re-parse, same as the in-app preview. Regression-tested (every source word exactly once in the output)
D28 Compare result form + big-doc strategy RESOLVED (round 1): materialized "Comparison: A vs B" document (same principle as D27, origin_json records both source ids); auto mode-switch full-stuff vs section-matched (vector-paired) by token math. No new result tables. Implemented in Phase 35
D37 Compare mode-(a) input + mode decision: chunks vs re-parse RESOLVED (Phase 35, 2026-06-11): re-extract the parser's SEGMENTS (the D36 path) for mode (a)'s input AND for the mode decision itself. Two reasons beyond D36's: chunk overlap would present duplicated text as phantom "shared" content to a comparison, and the ~80-token overlap inflates a chunk-based length estimate by ~16% — enough to mis-route a fitting pair into the heavier mode (b). Mode (b)'s map step deliberately uses the stored CHUNKS instead (the pairing needs their vectors; per-pair notes tolerate overlap like summary partials, D25 precedent). Regression-tested (every source word exactly once in the mode-(a) prompt)
D29 Timestamp representation RESOLVED (round 1): whisper segments → sectionLabel: "mm:ss–mm:ss" (existing Citation.section surfaces it). No schema change
D30 Dictation capture pipeline RESOLVED (round 1): renderer MediaRecorder → OfflineAudioContext resample → WAV bytes → main temp file (shredded) → transcriber; mic via scoped setPermissionRequestHandler. Streaming ASR explicitly out of scope. Implemented in Phase 37 exactly as locked
D31 OCR execution context RESOLVED (Phase 38, 2026-06-11, by R-O1): the split design — a hidden BrowserWindow does ONLY the pdf→PNG rasterization (it is the sole context with a canvas: R-O1 probed the Electron-37 utilityProcess and found NO OffscreenCanvas/DOM globals at all, killing option (b)); recognition ALWAYS runs MAIN-side in tesseract.js Node mode on image-file Buffers (no canvas needed — probed in BOTH runtimes), where the worker script + WASM core load from local node_modules with zero CDN involvement. Photos never touch the renderer at all. The renderer↔main round-trip carries only page PNGs
D32 OCR asset distribution RESOLVED (Phase 38, 2026-06-11, by R-O2's inventory): ride runtime-sources.yaml with a new additive ocr: asset class (plain verified files { lang, url, sha256, dest }, no extraction, no per-OS variance), fetched by fetch-runtime's Phase-36 --family mechanism. The drive carries ONLY the traineddata (ocr/<lang>.traineddata.gz — tesseract.js reads the .gz layout natively, single hash per file); the worker JS + WASM core ship inside the app as the pinned npm deps. A dedicated fetch-ocr script family was rejected: two small files don't justify a third script family when the family mechanism already exists
D33 OCR trigger RESOLVED (round 1): never automatic for PDFs — detection notice + explicit "Make searchable (OCR)" cancellable task with progress; photos OCR on import (small, fast). Auto-on-import and a settings toggle rejected (silent slow imports / a key + two code paths before the feature exists)
D34 Whisper invocation mode RESOLVED (Phase 36, 2026-06-11, by R-W1): per-file CLI, not a server. The v1.8.6 zip ships BOTH whisper-cli.exe and whisper-server.exe — but only for Windows, so "server ships per-OS" (the lean-server condition) fails; and the CLI wins on merits for batch-only use: progressive -pp progress + segments while it works (the R-W4 signal), no multi-hundred-MB upload over loopback, no port/health lifecycle, cancel/lock-suspend = kill the child. The localhost-only sidecar rule is moot (no socket). Revisit server mode only if Phase-37 dictation latency demands a warm model
D35 Audio originals on the drive RESOLVED (Phase 36, 2026-06-11): keep the copy — the locked Phase-4 copy-into-workspace contract + reindexDocument re-parsing the stored file force it (transcript-only storage would break re-index and the self-contained drive). Shipped with the recommended riders: size-aware import confirmation (>50 MB picked audio, docs:importPreflight), honest "Transcribing… N%" progress on import AND re-index, re-index = full re-transcription recorded in known-limitations.md. A sha256-keyed transcript cache only on evidence. Bonus that fell out of the packing design: preview/translate/compare read the STORED CHUNKS (exact for audio — no overlap by construction), so only re-index pays the re-transcription

§14 Research-gate evidence (run BEFORE the affected phase; all resolved)

Gate Question Finding
R-S1 FTS5 snippet()/highlight() present in both runtimes? GO (probed 2026-06-11): Electron 37.10.3 main process AND system Node 24.13.0, both SQLite 3.50.4: snippet(), highlight(), bm25() all work on a self-contained fts5 table. JS-truncation fallback not needed (Phase 31)
R-T1 llama-server b9585 concurrent-request behavior (slots/queue/reject)? Probed 2026-06-11 (tests/manual/server-concurrency-probe.test.ts, HILBERTRAUM_CONCURRENCY_PROBE, real b9585 + Qwen3-4B): at our default spawn args a second /v1/chat/completions is served on a PARALLEL slot (continuous batching) — request B fired 1.5 s into A's stream got its first token at +212 ms and finished while A was still streaming (A: first token 49 ms, done 4 386 ms, 700 tok; B: first token 1 718 ms, done 1 791 ms). Not queued, not rejected ⇒ the D26 app-side guard is the ONLY serialization, which is exactly why it exists (predictable latency, no context splitting). INFORMATIONAL; D26 stands. Facts banked for a future parallelism revisit. Historical since #319 (2026-09-07): the chat sidecar now spawns with -np 1 (in CHAT_SERVER_ARGS; translation and vision pass --parallel 1), one server slot, so a rerun on the pinned build would show B QUEUED behind A; the app-side guard is no longer the only serialization
R-T2 4B-class quality: long-input translation drift; comparison-format adherence RESOLVED 2026-06-11. Translation half (tests/manual/translation-smoke.test.ts, HILBERTRAUM_TRANSLATION_SMOKE, real b9585 + Qwen3-4B-instruct-q4, shipping prompts @ temp 0.2): (1) no refusals/chatter; an adversarial embedded-instruction window was translated, not obeyed. (2) No language drift on a near-budget (1100-word) EN→DE input (function-word scoring de=42/44, en=0/0). (3) Markdown survival complete (h1/h2/bullets/table pipes/bold/blockquote, DE→EN). (4) The load-bearing finding: word ratios are ~1.0–1.1 (DE→EN) / ~0.94 (EN→DE), but German output costs **2 real tokens per source word** (subword-heavy compounds): the first run's half-input/half-output context split CAPPED a near-budget window at maxTokens (ratio 0.67, output cut mid-sentence — silent truncation, exactly what this gate exists to catch). Fix shipped: usable context now splits by measured weight — input 1.3 tok/word, output 2.0 (TRANSLATION_OUTPUT_TOKENS_PER_WORD); at 4096 ctx → 1150-word windows, maxTokens 2301; re-run 19/19 numbered sections present, no truncation. (5) Number VALUES/names/codes survive; formats localize (14.03.2026 → March 14, 2026) — accepted, documented. Retry policy: one retry then visible marking. Comparison half (tests/manual/compare-smoke.test.ts, HILBERTRAUM_COMPARE_SMOKE, same model @ temp 0.3, two rounds): (1) the 4B holds the dictated four-section report format (all four ## headings verbatim + exactly once in every probe, clean bullets, zero refusals, no truncation: reports 106–221 words vs the 512-token cap ⇒ COMPARE_OUTPUT_TOKENS = 512, a fixed cap not a per-word weight). (2) Fact placement correct; names/numbers/dates exact. Round 1 caught two real issues — only-in-one facts ALSO cross-listed under "differs", and the matched-pair map step silently MISSED an only-in-A fact (the silent-omission class). Round-2 prompt fixes shipped: an exactly-ONE-section instruction (fixed the reduce; mode (a) still cross-lists one-sided clauses under "differs" — accurate but redundant, documented) and a "check every fact in the section of A" recall instruction (fixed the map miss). (3) Mode (b) DOES need the smaller per-pair format — compact - Same:/- Different:/- Only in A/B: bullets held at a 256-token map cap. (4) Reduce over per-pair notes merged duplicate shared facts, placement correct, no inventions. (5) German inputs: report body stays German; the DICTATED headings stay English (cosmetic, in known-limitations)
R-W1 Pinned whisper.cpp release: binaries per OS, server vs CLI, JSON timestamp output, license, archive shapes + hashes Pin: v1.8.6 (2026-06-02), probed against the real ggml-org/whisper.cpp release assets. (1) Prebuilt binaries exist for WINDOWS ONLY — whisper-bin-x64.zip (plain CPU, 3.9 MB, sha256 b07ea0b1…0a822) plus Win32/BLAS/CUDA variants and an Apple xcframework; NO mac/linux CLI assets ⇒ mac/linux = a documented source-build step. (2) The zip nests everything under Release/ (the existing flatten step handles it) and contains BOTH whisper-cli.exe AND whisper-server.exe + ggml DLLs + SDL2.dll (zlib). (3) D34 → CLI. (4) -oj JSON shape verified: transcription[].offsets.{from,to} in ms + text, result.language. (5) License MIT; model weights MIT (OpenAI) — reviews in model-policy.md. (Phase 36)
R-W2 Decodable input formats of the pinned binary (mp3? flac? m4a?) RESOLVED with real files against the real v1.8.6 binary. The binary declares + decodes wav, mp3, flac, ogg (all four verified incl. real German mp3/ogg; ogg an upside vs the plan's wav/mp3/flac guess). m4a: NOT decodable — and the failure mode is the trap this gate existed for: whisper-cli EXITS 0 with "failed to read audio data" on stderr and NO output. ⇒ the transcriber treats "JSON exists and parses" as the only success signal, never the exit code; m4a is descoped with friendly convert-to-WAV/MP3 copy. Format promise = wav/mp3/flac/ogg (Phase 36)
R-W3 Whisper model size for DE+EN on the reference laptop (RTF, RAM) RESOLVED (dev box, 4 threads; TTS German with known ground truth + real LibriVox German speech). base (142 MB): RTF ≈ 0.17–0.21 but meaning-destroying word errors on real speech ("Leichenwagen"→"gleichen Wagen", "Töchter"→"Teuchter", "Särge"→"sehrge", "Magd"→"Markt"). small (466 MB): RTF ≈ 0.43–0.46 (~2.4×), fixes nearly all; clean-speech German near-perfect, numbers/names/dates exact. Shipped default: small (German quality is the product promise); real hashes captured for both (base banked for a possible future low-end manifest: 60ed5bc3…2efe). All profiles recommended (peak RSS ≈ 1.2 GB, batch job). Manifest = whisper-small-multilingual (Phase 36)
R-W4 60-min file: time/memory/progress signal RESOLVED: a real 52-min German mp3 (128 kbps LibriVox) through the small model on the dev CPU (4 threads): 2123 s wall (≈35 min, RTF ≈ 0.68), peak working set 1155 MB, 616 segments, -pp progress lines every ~5% (20 ticks) + segments streamed progressively to stdout ⇒ the import job shows real per-file "Transcribing… N%" (CLI -pp → ParseContext.onProgress → in-memory map → DocumentInfo.transcriptionProgress on the existing polling path — no new channel). Memory is a non-issue; wall time is the honest cost in known-limitations.md + the size-aware import confirm (D35). Job UX = per-file percent (Phase 36)
R-O1 pdfjs render-to-OffscreenCanvas in utilityProcess/worker; tesseract.js on Node Buffers w/o canvas RESOLVED in pinned Electron 37.10.3 AND system Node 24.13.0 (two-runtime discipline), tesseract.js pinned 7.0.0. (1) utilityProcess has NO OffscreenCanvas — nor document, createImageBitmap, ImageData, DOMMatrix, Path2D (all undefined); D31 option (b) impossible in the Electron we pin. (2) A hidden BrowserWindow renders fine: the pinned pdfjs LEGACY build rasterized page 1 of a real image-only PDF at 300 DPI (2550×3301) in ~350 ms with an explicit LOCAL workerSrc. (3) tesseract.js Node mode consumes image-file Buffers WITHOUT canvas in BOTH runtimes (PNG + JPEG decoded inside the WASM core): confidence 95, near-perfect German incl. umlauts/ß. (4) Full split-pipeline e2e proved in the pinned Electron: hidden-renderer render → PNG bytes over IPC → main-side recognize, confidence 94, all six probe words (Auftragsbestätigung, Großmann, Bürostühle, Schloßallee, Özdemir, Grüßen) exact. → D31 (split design). (Phase 38)
R-O2 Full vendored-asset inventory for offline tesseract.js + licenses + sizes RESOLVED (source inspection + live probes with a net.Socket.connect watch installed). Node-mode inventory: workerPath defaults to the LOCAL tesseract.js/src/worker-script/node/index.js; the WASM core is required from the LOCAL tesseract.js-core package (SIMD variant picked at runtime) — both ship INSIDE the app as npm deps, NOT on the drive. The two runtime-fetch traps: langPath defaults to https://cdn.jsdelivr.net/npm/@tesseract.js-data/... (MUST be set to the drive's ocr/ dir) and the traineddata cache writes into CWD by default (MUST set cacheMethod: 'none'). No-network proof: zero remote connect attempts across every probe. Licenses (reviewed per model-policy.md): tesseract.js 7.0.0 Apache-2.0 · tesseract.js-core 7.0.0 Apache-2.0 · traineddata Apache-2.0. Shipped sizes: deu.traineddata.gz 1.27 MB + eng.traineddata.gz 2.82 MB ≈ 4.1 MB. Packaged-app caveat: worker_threads cannot load a script from inside app.asar → asarUnpack tesseract.js + tesseract.js-core, resolve workerPath through .unpacked (release-acceptance item; the green gate never packages). → D32. (Phase 38) ⟶ SUPERSEDED IN ITS PACKAGED-APP CAVEAT (measured 2026-07-19 on a real packaged Windows build, DEP-1 P4): unpacking those two packages is not sufficient — the worker's own hoisted deps (regenerator-runtime, is-url, …) stay inside app.asar and cannot be resolved from app.asar.unpacked; the uncaught exception kills the whole app while ocrAvailable still reports true. Pre-existing and version-independent (fails identically on Electron 37); dev-mode OCR is unaffected (raster → IPC → recognize proven end to end on Electron 39). Fix bundle = the DEP-1 record's §5 follow-up 2; the rest of this row (inventory, fetch traps, licenses, sizes) stands. ⟶ CONTAINED (#232, PR #268): the worker's load failure is now a per-document error (process.on('worker') hook + bounded start + errorHandler), a packaged build proves the worker at startup and reports OCR unavailable until it does; the asarUnpack closure landed in PR #269.
R-O3 fast vs best traineddata on real German scans RESOLVED on generated German office-scan pages (150-DPI clean + ~82-DPI/JPEG-q0.45 degraded). Load-bearing finding: true tessdata_best (float) CRASHES the tesseract.js WASM core (missing function: DotProductSSE) — only INTEGER models run, so the real choice is fast vs best_int (what tesseract.js's own CDN default uses). Clean scan: a dead tie (103/104 words exact for both). Degraded scan: best_int 3 misses vs fast 7 of 104 — fast garbles the reference number 4711-Ä/2026 and Jürgen, best_int keeps both. Cost: ~1.3 s vs ~0.8 s per page, +1.6 MB. Shipped: best_int (@tesseract.js-data/{deu,eng}@1.0.0, 4.0.0_best_int, sha256 pinned in runtime-sources.yaml). The .gz-on-drive layout (langPath + gzip: true) verified end-to-end. (Phase 38)

§-anchor legend (historical plan citations)

The retired functionality-wave-3-plan.md was folded — its per-phase records (§4–§11) into the topic-doc sections listed below, and its §13/§14 into this record. In-code comments and the kept docs still cite wave-3 plan §N (and D23–D37, R-*); those numbers were never renumbered, so this legend keeps them resolvable (the doc-lifecycle "stable anchors" intent) without churning ~30 comments. Read a historical anchor as:

Historical anchor Meaning Now lives in
§4 Conversation search (messages_fts, bm25, chat:search, the deny-by-default permission rider) "Chat & streaming → Conversation search" above + security-model.md (permission handler) + user-guide.md §6
§5 Vault password change (descriptor v2 envelope, journaled v1→v2 migration, race guard) — decision D24 security-model.md "Vault descriptor" + "Password change" + user-guide.md §10 + known-limitations.md
§6 Document-task engine + one-click summary (DocTaskManager, D25/D26) "Document tasks" above + known-limitations.md "Document tasks & summaries" + user-guide.md §7
§7 Translation workflow (D27 + D36) "Document tasks" above (translation) + known-limitations.md "Document translation" + user-guide.md §7
§8 Compare two documents (D28 + D37) "Document tasks" above (compare) + known-limitations.md "Document comparison" + user-guide.md §7
§9 Audio transcription as ingestion (whisper.cpp, D29/D34/D35) "Audio transcription" above + drive-layout.md (whisper family) + model-policy.md (whisper licenses) + known-limitations.md "Audio transcription" + user-guide.md §7 + PRIVACY.md
§10 Voice dictation (D30) "Voice dictation" above + security-model.md (scoped permission + dictation data-path) + known-limitations.md "Voice dictation" + user-guide.md §6 + PRIVACY.md
§11 Scanned-PDF / photo OCR (D31–D33) "Scanned-PDF / photo OCR" above + model-policy.md "The OCR asset class" + drive-layout.md (ocr/ assets) + known-limitations.md "Scanned-PDF / photo OCR"
§12 Session-hardening rider (the deny-by-default setPermissionRequestHandler) + cross-cutting impact inventory security-model.md (permission handler + the Phase-37 scoped allow); the DB/IPC/audit deltas are recorded in the per-feature sections above
§13 Decisions D23–D37 this record's "§13 Decisions" above
§14 Research gates R-S1 / R-T1 / R-T2 / R-W1–4 / R-O1–3 with banked findings this record's "§14 Research-gate evidence" above
§15 Testing posture (zero-network/model/binary/GPU/mic CI; manual harnesses behind HILBERTRAUM_* env vars) the wave's test files (tests/manual/{whisper,ocr,compare,translation}-smoke.test.ts, server-concurrency-probe.test.ts)

Privacy & offline (Phase 8)

Real local inference (Phase 10)

Real on-device inference drops in behind the unchanged ModelRuntime/Embedder interfaces — no caller changes. Both backends are opt-in by availability (graceful-fallback rule): the real one is used only when BOTH the platform llama-server binary AND the model's GGUF weights are present; otherwise the mock is used, so the app launches and the whole test suite passes with zero model files.

  • services/runtime/sidecar.ts — sidecar discovery + lifecycle.
    • resolveLlamaServerPath(rootPath, platform, env) finds runtime/llama.cpp/<os>/llama-server[.exe] (spec §6 drive layout; win/mac/linux sub-dirs). A HILBERTRAUM_LLAMA_BIN env var overrides it for dev. Pure existsSync check — no surprises in the "binary present?" decision.
    • findFreePort() asks the OS for a free loopback port (listen on 127.0.0.1:0, read it, close).
    • LlamaServer owns one child process: spawns llama-server bound to 127.0.0.1 only (--host 127.0.0.1 --port <random> --model <gguf> --ctx-size <n> --threads <n> + optional extra args), polls /health with a timeout before reporting ready (never hangs on a wedged server), exposes a loopback fetch, and stop() kills the child and waits for exit so no orphan survives. A child that crashes or never gets healthy makes start() throw a clear error. The spawn passes windowsHide: true (REL-7, backend-audit-2026-06-27) so this high-frequency spawn (every model start — chat, embedder, reranker, vision all funnel through here) never flashes a console window on Windows, matching the tar / transcriber / runtime-download spawns. Sidecar auth (local-api wave P1): every spawn generates a fresh 32-byte hex API key, delivered via the child-scoped env (LLAMA_API_KEY, verified enforced on b9849 — where the upstream exempted /health and /v1/models — and on the b11146 pin, where only /health is exempt, #512) — never argv (visible in process lists; llama-server echoes resolved params to stderr) and never the parent process.env (whisper-cli/tar/the GPU probe would inherit it). LlamaServer.fetch() is the single HTTP chokepoint and injects Authorization: Bearer <key> for all consumers. Stderr never carries the key out: the drain applies exact-key redaction over a partial-line hold-back (complete lines publish with unchanged timing; a chunk-split key always lives in a partial line, so it is reassembled and scrubbed before ANY sink — the capped tail or the onStderrData observer — sees it), and tail reads (redactedTail → start-failure errors, gpuLastError, the audit trail, the app log, the support-log export) add the generic api…key <value> pass once at read time (value-shaped tokens only, so the routine api_keys: 1 keys loaded count line stays legible). scripts/measure-peak-rss.ps1 deliberately spawns its own keyless server and is unaffected.
  • services/runtime/llama.ts — LlamaRuntime implements ModelRuntime, composing a LlamaServer. chatStream POSTs to the server's OpenAI-compatible /v1/chat/completions with stream: true, sending messages as plain role/content (the server applies the model's chat template — we never hand-roll Qwen's prompt format) and mapping maxTokens/temperature. readChatSSE parses the SSE data: frames (buffering partial lines, ignoring keep-alives, stopping on [DONE]) and yields each delta, honouring options.signal. An IN-BAND mid-stream error frame (data: {"error":{…}} or a bare error: {…} field line, then a close without [DONE]) rejects with a typed ChatStreamError instead of ending cleanly — a failed generation can never persist as a clean answer (audit 2026-07-16 F-02; frame shapes pinned to b9849, re-verify on pin bumps per TS-3(a)). This feeds the locked Phase-3 streaming contract unchanged. The reader also keeps the server's top-level timings block (last one seen on any chunk) and hands it up through onFinish(reason, timings?) at [DONE]/close, never on an abort (#290/#291; RuntimeTimings in runtime/index.ts), so measureTokensPerSecond (Phase 7) reports the runtime's decode tokens/sec (predicted_per_second, prefill excluded, tokens not chunks) the moment a real runtime streams, and only falls back to a chunk count for a runtime without timings.
  • services/runtime/factory.ts — createSelectingRuntimeFactory({ rootPath, … }) returns a RuntimeFactory that picks LlamaRuntime vs MockRuntime per start() (when the concrete model path is known), behind the unchanged RuntimeManager. main/index.ts uses it in place of the bare createMockRuntime. Phase 15: when binary + weights are present the factory returns the GPU start ladder (see below) instead of a bare LlamaRuntime.
  • Generation gate (local-api wave P1). RuntimeManager.doStart wraps the factory-returned runtime (ladder AND mock — the shipped gate is the one CI exercises) in a decorator whose chatStream counts in-flight generations per lane (RuntimeChatOptions.lane: 'in-app' default / 'external'), because generation reaches the model through several lanes no single registry sees (chat/RAG streams, doc tasks, skill runs, the benchmark, compaction, classification) — all via active().chatStream, so the manager is the one chokepoint. RuntimeManager.isExternallyBusy() is THE predicate for external (local-API) admission — any in-flight generation OR no active runtime, fail closed: active() is null through the whole start window, exactly when the #109 warm-up generation streams against the inner rung runtime, invisible to the decorator. (isGenerating() is the narrower any-lane read; on its own it is NOT fail-closed.) Lane rules (D8, in-app wins): an external entry is refused (ExternalGenerationBusyError) in the same synchronous frame as its counter increment whenever the in-app lane is active or another external stream runs (the slot is single, structurally — admission's serialization is advisory); an entering in-app generation fires the registered pre-emption hook on EVERY entry (setExternalPreemption — local-API admission's abortAll cancels its active AND admitted-but-unstarted requests) and awaits the external stream's real teardown before issuing — bounded (~5 s), because the abort already cancels the sidecar socket (the KV slot frees) even if a misbehaving consumer never resumes its generator. Counter discipline: increment as the generator body's first act (a created-but-never-iterated generator holds no count), decrement in finally, epoch-guarded: every model start/stop bumps the gate epoch and zeroes the counts, so a count leaked by an abandoned external generator self-heals on the next runtime transition instead of wedging admission forever. External-lane consumer contract: try { for await … } finally { await gen.return() } on every exit path. The gate deliberately does NOT serialize in-app lanes against each other (the pre-existing skill-run/benchmark concurrency, A6/A7, is unchanged — now merely visible). External admission itself lives in services/local-api/admission.ts: single external slot, queue depth 0–1 with a ~30 s cap (deeper queues are silent multi-minute hangs on CPU boxes), workspaceAdmitsWork-class lock refusal, abortAll for pre-emption + teardown, a promotion handoff that stays with the holder until real stream teardown (an active caller's disconnect never releases in the abort frame), and the invariant ready:false ⇒ signal aborted. Kin note: analysis/model-slot-arbiter.ts coordinates the same physical slot for in-app yielding builders (cooperative pause/resume); admission is refuse/queue/abort for outside callers — deliberately separate.
  • Local API endpoint (local-api wave P3). services/local-api/server.ts + handlers.ts: the opt-in OpenAI-compatible loopback endpoint (node:http, no framework). Binds 127.0.0.1 AND ::1 (O5), never 0.0.0.0 (D2); exists only while the workspace is unlocked AND policy ∧ setting permit (D3/D7 — maybeStartLocalApi at the three post-unlock seams: plaintext startup, unlock, create; runLockTeardown/performShutdown stop it FIRST, before the sidecars, so no outside caller holds the model mid-teardown; applyLocalApiSettings rides settings:update). Requests route through the manager-gated active().chatStream (never a raw sidecar proxy) so external generations inherit abort registration, watchdogs, context budgeting, and the D8 pre-emption contract. The full exposed HTTP contract (pipeline order, field policy, envelopes, error mapping, limits) lives in data-contracts.md; the request pipeline's check ORDER (Host → OPTIONS → Origin → content-type → auth → route) is part of the security contract, pinned in local-api-server.test.ts "check order: %s" (each request fails two or more checks, and the answer names the one that runs first).

GPU acceleration: probe + start ladder (Phase 15; design record below)

The Phase-14 drive ships the Vulkan full build as the default llama-server (it contains every CPU backend and degrades to CPU on GPU-less machines), so GPU offload happens with default spawn args (b9585: -ngl auto + --fit on — we never pass -ngl, locked decision). What Phase 15 adds is the safety machinery:

  • services/runtime/gpu.ts — probeGpuDevices(binPath) spawns the drive's own llama-server --list-devices (offline, no model, sub-second, kill-timeout-bounded (10 s); resolves on the child's close event so late-buffered stdout is never truncated; never throws — an exit 0 is the answer (the devices, or []), and everything else that is not an answer resolves null, "unknown", which is not the same fact as "this machine has no device": the kill-timeout (the driver never answered, #380, 2026-09-08), a program the OS refused (#530), a crash or a failed spawn (#653, 2026-10-13); only a binary the integrity check refuses still reads []) and parseListDevices parses it (pure, fixture-tested). The spawn passes windowsHide: true (REL-7) so the once-per-session probe never flashes a console window on Windows, and the child is unref()'d right after spawn (REL-8): the probe is not tracked by shutdown(), so detaching it from the parent event loop means a wedged/cold driver can never delay app quit — the probe's own 10 s kill-timeout still reaps it. looksIntegrated(name) is the conservative iGPU heuristic for the Phase-16 profile bump (covers Windows + RADV APU names and Meteor-Lake Arc). createCachedGpuProbe() memoizes per binary per session and exposes invalidate() (wired to "Try GPU again") — but a null entry drops itself the moment it settles (identity-guarded), so an unknown answer is never the session's answer and the next caller re-probes; R5's in-flight coalescing is untouched, so a re-probe during the wedge still rides the one child. The ladder kicks the probe off concurrently with the rung-1 server start, and since #380 the three post-unlock seams settle the session's probe refresh BEFORE the auto-start (FirstBenchmarkDecision.probed), so on that path the answer is normally already in hand; when the probe lists no device (unknown, or since #653 an empty answer) the rung is labelled from this start's own load log — gpu when it filed buffers on a device its own device_info block lists as a GPU (PlacementParser.holdsGpuBuffers; never the offload line, which a GPU-less rung 1 prints as offloaded 37/37 layers to GPU too), named from the device_info rows — rather than defaulting to cpu. The probe labels the backend for the UI; it can't prove stable inference — the ladder is the actual guarantee.
  • The start ladder (factory.ts, §5.2): rung 1 = default binary, default args (GPU auto-offload; on a GPU-less machine this is CPU mode) → rung 2 = same binary, --device none (the only way we force CPU) → rung 3 = the pure-CPU safety-net build (runtime/llama.cpp/<os>/cpu/, when shipped) → rung 4 = MockRuntime (the existing graceful-fallback rule; the app can never be stuck). gpuMode: 'off' (Settings) or a persisted gpuAutoDisabled skip rung 1. A rung-1 failure is held and persisted (gpuAutoDisabled + gpuLastError, so later starts pay no repeated GPU health timeout) once a forced-CPU rung starts — the control probe that proves the model loads here. If every rung fails the same way, the model is blamed instead and nothing is persisted (issue #312, §5.2); anything unknown or ambiguous stays a device fault. With no GPU rung at all (acceleration off / auto-disabled) every rung failing still names the model, and a blamed model is latched for the session — its next start spawns no rung and lands on the mock at once (issue #372, §5.2; cleared by "Verify checksum", a re-download, an engine install or a restart — not by "Try GPU again"). The Diagnostics tab's "Try GPU again" clears the flags. RuntimeStatus now carries backend: 'gpu' | 'cpu' | 'mock' + gpuName.
  • Mid-generation crash auto-fallback (§5.3): LlamaServer gained an onUnexpectedExit hook (fires only for a healthy server dying outside stop()). When the active backend was GPU, createGpuCrashAutoFallback persists the flags, forces a one-shot restart at CPU via RuntimeManager.forceRestart — NOT start(), whose same-model idempotency guard would otherwise swallow the restart entirely (§5.3) — and broadcasts the friendly §11.4 notice (runtime:notice event → preload onRuntimeNotice): "Switched to compatibility mode for stability…" — never "GPU failed".
  • The E5 embedder is pinned to CPU (--device none in its extraArgs, §7 — decided): the 384-dim model gains little from a GPU, and the pin keeps ingestion immune to driver flakiness and VRAM contention with the chat model.
  • GPU settings (gpuMode, gpuAutoDisabled, gpuLastError, gpuProbe) live in AppSettings (the possibly-encrypted DB) — fine, because sidecars only ever start while a workspace session is open; every read in main/index.ts is still guarded (locked → safe defaults). That claim was aspirational until the lock latch (AUD-02/AUD-03, security-model.md "The lock latch"): isUnlocked() is just "the DB handle is non-null", and the DB stays open for the whole multi-second lock and quit teardown, so work admitted in that window used to respawn a suspended sidecar, and a model start still hashing a multi-GB weight could spawn llama-server after the lock finished. What enforces it now: admission goes through workspaceAdmitsWork() (isUnlocked() && !isLocking()), the latch is armed as the first act of both the lock handler and performShutdown, and startModelRuntime re-checks it plus a session epoch after the hash. Note the safe-default reads above are precisely what kept a stale start from failing loudly on its own. Residual: RuntimeManager.forceRestart (the GPU-crash auto-fallback) re-checks only the quit latch internally — its workspace check lives at the main/index.ts composition seam, so a future caller added elsewhere would not inherit it.
  • CI never touches a GPU/binary: the probe + ladder are covered through the existing SpawnFn/fetch seams; a real-GPU smoke lives in tests/manual/gpu-smoke.test.ts, skipped unless HILBERTRAUM_GPU_SMOKE points at a provisioned drive.
  • The Phase-16 surface on top of the ladder: Settings' "Use GPU acceleration" toggle binds gpuMode 'auto' | 'off' (default ON). The Settings "Diagnostics (advanced)" tab shows the Acceleration line (live RuntimeStatus.backend/gpuName while running, else the snapshot's currentGpu — this machine's ELIGIBLE probe as performance:get resolves it, never settings.gpuProbe read raw; see benchmark.md "One eligible source" and issue #327), the runtime build line (getRuntimeInstall IPC runtime:install → the .hilbertraum-runtime.json marker), and the compatibility-mode notice with "Try GPU again" — a dedicated IPC (gpu:try-again) that clears gpuAutoDisabled/gpuLastError, invalidates the session probe cache, and re-probes + persists (hidden while the toggle is OFF, where it would do nothing). The benchmark path injects the probe as RunBenchmarkDeps.gpu: { name, useful, totalMb, budgetMb, memoryClass } (gpuUsefulForProfile: ≥ USABLE_VRAM_MB — 5120 MiB since #321 — AND not integrated → the conservative classifyProfile bump; the rule lives in shared/gpu-rules.ts since the PR #303 audit, so the Performance screen rates a device by the same definition — name, totalMb and budgetMb are one device's, the BUDGET device nextStartMemory selects, PR #308 audit decision 9); benchmark.ts itself keeps zero child_process. prepareFirstBenchmark (the cheap half of the first-run benchmark, PR #303 P7) additionally refreshes settings.gpuProbe once per session even when a benchmark already exists, so a drive moved between machines re-labels itself; a completed chat-engine install runs the same refresh (refreshGpuProbeAfterRuntimeInstall, issue #323) when this machine's eligible probe lists no device, so a benchmark run before the binary existed is not frozen on its empty probe.
  • services/embeddings/e5.ts — E5Embedder implements Embedder, the real backend behind the same interface with the manifest id + 384 dims. It composes a LlamaServer started with --embedding --pooling mean (the same prebuilt binary — zero new npm deps, no fragile native build), is lazy-started on first embed() and reused, POSTs to /v1/embeddings, re-orders the response by index, and L2-normalizes each vector (interface contract). An additive stop() kills the sidecar (wired into will-quit). services/embeddings/factory.ts createSelectedEmbedder({ rootPath, model, … }) picks E5Embedder vs MockEmbedder by availability (the embeddings model is read from the manifest, since settings live in the possibly-encrypted DB and are unreadable before unlock).
  • Embedding-model-mismatch guard. Mock vectors (mock-embedder) and real E5 vectors are both 384-dim, so VectorIndex's dimension guard cannot separate them — mixing them silently corrupts ranking. VectorIndex takes an optional { embeddingModelId } that scopes the cosine scan to one model's vectors (WHERE embedding_model_id = ?); rag.retrieve passes the active embedder's id, so a corpus indexed under the mock can't pollute search under real E5 (and vice-versa) until a reindex re-embeds everything. The default (no id) still scans all rows, so existing callers/tests are unchanged.
  • services/reranker/ (Phase 21, rag-design.md §11) — LlamaReranker implements Reranker, the THIRD LlamaServer composition: the same b9585 binary spawned with --rerank --device none (CPU-pinned like the embedder; CHAT_SERVER_ARGS never reach it), lazy-started on the first documents question, POSTs /v1/rerank and maps results[].{index, relevance_score} back by index. createSelectedReranker returns it only when binary + reranker GGUF exist, else null (no mock — pass-through is the contract). A failed start latches for the session (no health-timeout stall per question); a query-time failure logs and keeps the fused order. Stopped on will-quit; suspended (stop + lazy restart allowed) on workspace lock — suspend() also fixed the embedder's post-lock latch. The E5 embedder carries the same failed-start latch, with one deliberate difference: its latch clears on suspend() — the embedder has no graceful degradation (a latched failure blocks all imports), so replacing a bad GGUF + lock/unlock must make imports retryable without an app restart. A transient port-bind race never arms either latch (F4/F7, isBindRaceError — see GPU record §5.5b): only a genuine load fault latches, so a double-unlucky startup port race no longer silently disables imports / reranking for the session.
  • Hybrid keyword retrieval (Phase 21) — chunks_fts (FTS5, text + chunk_id UNINDEXED, trigger-synced from chunks, guarded migration + backfill in db.ts) gives rag.retrieve a BM25 keyword pass fused with the cosine pass by reciprocal rank (k = 60, rag/hybrid.ts). Keyword hits are restricted to chunks with a vector under the active embedder, so hybrid search never widens what vector search could see (the Phase-17 re-index honesty story).
  • Localhost-only is non-negotiable. Every bind/spawn/fetch targets 127.0.0.1. The Phase-8 offline guard exempts loopback precisely for this sidecar; a routable bind would expose local inference to the LAN and violate the spec. The no-network test assertions assume loopback-only.
  • R5 — live inference is manual. Platform sidecar binaries + a GGUF model are not in the repo, so a real-model answer is a manual acceptance step. Everything else (discovery, fallback, localhost binding, process cleanup, health-timeout, SSE parsing, the embedder mechanics, the mismatch filter) is covered by tests with a mocked child process / mocked loopback fetch.

GPU acceleration — design record (Phases 14–16, §1–§8)

Formerly docs/gpu-support-plan.md (folded in here, 2026-06-12 docs housekeeping; the full original implementation plan — research tables, change inventory, phased plan, deviation log — is in git history: git show 4549934:docs/gpu-support-plan.md). IMPLEMENTED 2026-06-10 (Phases 14–16) + a same-day audit round, all findings remediated (BUILD_STATE §3 "GPU audit round"). The runtime design as implemented is the "GPU acceleration: probe + start ladder" subsection above; § numbers below are stable — code comments cite them as "GPU record §N".

§1 Decisions

Decision Choice Why (short)
GPU backend (Win + Linux) Vulkan One ~37 MB build covers NVIDIA + AMD + Intel with standard drivers; CUDA is NVIDIA-only and ~620 MB (see §4)
Build shipped per OS The Vulkan full build is the default at runtime/llama.cpp/<os>/ — it contains the complete CPU backend set (GGML_BACKEND_DL), so on a GPU-less machine it is the CPU build Verified by unpacking the b9585 assets
CPU-only safety net Also ship the pure-CPU build at runtime/llama.cpp/<os>/cpu/ (+16/+15 MB) — rung 3 of the ladder Last-resort escape if ggml-vulkan's mere presence destabilizes a machine (AV/loader edge cases)
User control GPU is always the default; only a detected problem (the ladder) moves a machine to CPU. Settings has a "Use GPU acceleration" toggle (default on); Diagnostics has "Try GPU again" Zero-technical-knowledge rule
-ngl strategy Pass nothing — b9585 defaults to -ngl auto + --fit on (VRAM-aware auto-offload). CPU is forced with --device none, never -ngl 0 Upstream owns VRAM fitting (§3)
GPU detection Both: a --list-devices probe (labels the backend for UI/profile) and the try-then-fallback start ladder (the actual guarantee). A probe that hits its 10 s bound, crashes or cannot be spawned is unknown, not "no device" (#380, 2026-09-08; #653); a probe that lists no device yields to GPU buffers in the start's own load log, never to its offload line (#653, 2026-10-13) The probe can't prove inference works; the ladder can't name the GPU
First-start CPU-vs-GPU auto-benchmark Not built v1 trusts llama.cpp auto-offload even on weak iGPUs; §8's honest copy covers the modest-gain case
macOS No change — arm64 already runs Metal with auto-offload; mac/x64 + win/arm64 are out of scope (Intel Macs documented in known-limitations.md) Upstream ships mac/x64 with Metal off; macOS has no Vulkan
Embedder (E5) Forced CPU (--device none) See §7
New npm deps None — probe + ladder use node:child_process on our own shipped binary No native/fragile deps (project theme)

Size delta per drive: win +53 MB download / +166 MB disk; linux +51 MB / ~172 MB; mac 0. Negligible next to multi-GB weights.

§2 Hard rules (these bound every choice)

  • 100% offline at runtime. GPU builds are fetched at drive-build time (fetch-runtime); the capability check is a local subprocess of a drive-local binary. No network, ever.
  • Plug-and-play. No driver installs, no required settings. GPU is automatic when it works, invisible when it doesn't; a failed GPU attempt can never leave the user stuck — worst case is the CPU experience.
  • ModelRuntime/Embedder interfaces + the graceful-fallback rule stay intact. The app launches and the full suite passes with zero models, zero binaries, zero GPUs (CI default).
  • Localhost-only sidecar binding (--host 127.0.0.1) untouched.
  • Friendly copy (spec §11.4): "compatibility mode", never "GPU failed" / "your hardware is bad". CPU mode is presented as normal, not degraded.

§3 llama.cpp b9585 facts this design relies on

(Verified 2026-06-10 against the then-pinned tag b9585; re-verify on the next pin bump. PIN BUMPED 2026-07-01: the live pin is now b9849 — bumped from b9585 as the Qwen3.5 compatibility gate, runtime-sources.yaml + model-policy.md. The b9585-tagged facts below are the last verified runtime evidence; the b9849 re-verification is the REQUIRED manual smoke in model-benchmarks.md §9. These facts — -ngl auto/--fit on defaults, --device none, --list-devices, the Vulkan-archive-is-a-full-build property — are long-standing upstream behaviour expected to hold on b9849, but that is not yet re-confirmed on this project's drive.)

PIN BUMPED 2026-09-27: the live pin is now b11146 (= upstream stable v0.5.0, issue #512), and the facts below were re-verified on it on an i9-14900K / RTX 3080 Ti with the app's exact argv and b9849 alongside as the control: every flag the app passes still parses (--device none, --pooling mean, --no-mmproj-offload, --spec-type draft-mtp, --reasoning-format deepseek, …); -ngl auto / --fit on are still the defaults (the gpu smoke passed 4/4, and every load-log line placement.ts reads is unchanged, with identical MiB); --list-devices stdout is byte-identical (b11146 adds an llama_server: initializing ... line on stderr, which parseListDevices never reads); the win-cpu asset serves rung 3; mmproj_use_gpu, kv_unified = false under -np 1, cache_ram_mib = 8192 and n_ctx_checkpoints = 32 are unchanged defaults. Removed upstream: --mlock / --no-mmap (now --load-mode, default auto = mmap, plus --lazy-mode) — the app passes none of them. The one behaviour change the app follows is the prompt cache (qwen3.5 / gemma4 now restore; shared/prompt-cache-rules.ts). The Vulkan free-memory reading on NVIDIA/Windows is still constant (#318). MTP was verified on the RTX 3090 rig with the Linux Vulkan asset (the 27B at 66/66 with --spec-type draft-mtp, draft acceptance 0.754 against b9849's 0.760, decode within noise; PR #524, model-benchmarks.md §6.6 "Rig legs"). The macOS asset is hash-checked only.

PIN BUMPED 2026-11-07: the live pin is now b12110 (= upstream stable v0.9.0, cd959bae, issue #729; owner calls: v0.9.0 rather than v0.8.0 = b11960, merged no earlier than 2026-11-11). Why: b11146 keeps a llama-server context checkpoint at position 0 across requests, so a prompt that opens with a user turn after <bos> (Gemma) skipped its first prompt break and was prefilled in other batch shapes when it followed an unrelated request (upstream #30666, first in v0.8.0). Re-verified on the GTX 1070 Ti box (i7-8700, 32 GB, Windows 11) against b11146 with the app's exact argv:

  • #729 itself. gemma4-e2b, the issue's sampling, a request R after an unrelated X: on the card b11146 changes R (token 0 Wenn −0.9346 → −0.8797, the text from character 221, R a third time differs too); b12110 gives the same R every time, with the issue's flags and with the app's argv and cache_prompt: false. On this processor neither build moves the numbers, but b11146's checkpoint log shows the same leftover checkpoint (2 of 32 where b12110 starts again at 1 of 32). A fresh server is deterministic on both.
  • CLI and defaults. Every flag the app passes is in b12110's --help, draft-mtp included. The option lines differ from b11146's only by additions (--connect, --connect-code, --moe-cache-mib, two --spec-draft-*, a router margin), the --port default (8080 → 9931; the app always passes --port) and --cache-ram's help ("0 for decision models" when the flag is not given; the app always gives it). -ngl auto, --fit on, the fit targets, kv_unified under -np 1, n_ctx_checkpoints = 32 and mmproj offload are unchanged. All 155 variables --help names match the #730 filter.
  • --list-devices. Stdout has the same shape (CRLF, (none) with no device); b12110 no longer prints llama_server: initializing ... on stderr.
  • Load log. device_info gains a row for the processor (- CPU : Intel(R) Core(TM) i7-8700 …), which placement.ts already reads as a CPU label and never as a card. GPU starts read the same model, KV and spill figures as on b11146 (full and partial offloads of the 4B, 9B, 14B and TranslateGemma); a start on the processor sums ~100–200 small CPU_Mapped lines that no longer map the repacked share, so its CPU-side weights drop to llama.cpp's own breakdown (the 4B 4,045.83 → 2,375.83 MiB; benchmark.md HW2). The last line of a failed start names server_run_i instead of llama_server, and even the first line is uncoloured; the #515 signature (the first E line) is the same as on b11146, so a b12110 main build and a b11146 cpu/ net still blame a broken model together.
  • Wire. The chat stream keeps the b11146 shape: content chunks, timings on the finish_reason: "stop" chunk, [DONE] (chat-sse-timings-b12110.txt). return_progress still sends an event with the headers and after every prompt batch (chat 2048, translation 512 tokens), and the HTTP thread still pings after every 30 s of silence (chat-sse-progress-b12110.txt, translation-sse-progress-b12110.txt, each with a b11146 run of the same request beside it: the same events). Vision frames are unchanged (vision/vision-sse-b12110.txt). The 400 exceed_context_size_error and 500 image-not-supported bodies are byte-identical. Auth: the same 18 routes answer the same with and without the key; the endpoints new in v0.8.0 (POST /tts, /v1/realtime and its websocket upgrade) answer 401 without it.
  • Embeddings and rerank. E5 vectors are identical (cosine 1.000000 on 80 texts), so a b12110 query against a workspace embedded on b11146 ranks exactly as before (top-5 order 20/20); bge-reranker scores move by at most 0.0042, same order in 10/10 calls.
  • Windows paths. The executables now embed an application manifest selecting the UTF-8 code page and long paths (upstream #31329), and llama.cpp dropped its own wide-argv rebuild (#31417): a model and an mmproj under …\pfad äöü 日本 [1]\ load and answer on both builds. Windows honours the manifest from Windows 10 1903 on; on an older build (10 LTSC 2019 is 1809) a path with characters outside the system's ANSI code page would no longer reach the engine (expected, not measured; known-limitations.md).
  • Archives and host. The only new file in all five archives is llama-connect[.exe], the --connect tunnel program; the installers leave it out (neverInstalled, security-model.md). Linux needs exactly what b11146 needs (objdump -T: GLIBC 2.34, GLIBCXX 3.4.30, OpenSSL 3, libgomp), and both Linux builds start and embed in WSL Ubuntu 24.04; the Windows builds import the same Visual C++ runtime.
  • Smokes and quality. On b12110: gpu-smoke 6/6 (rung 1 at 37/37 on the card, the unknown-probe label from the load log, --device none, rung 3 on the cpu/ net, the #730 leg), thinking-smoke (deep streams separate reasoning deltas, balanced none), gemma-thinking 15/16 (b11146 14/16; the one miss is the same deep answer on both), rerank-smoke, rag-quality, vision-smoke (cold start, prefill reuse, idle teardown), translategemma-smoke 4/4 on the card and on the processor, the concurrency probe, and the categorizer's json_schema enum (0 off-set categories). bringup-smoke covers four challengers this box does not hold (ps-work leg). Grounded-QA gate (§2 harness, Vulkan, gemma4-e2b, qwen3-4b, qwen3.5-4b, qwen3.5-9b): EM, citation-correct, grounded and unanswerable-abstention are identical on all four, mean_f1 moves by at most 0.005, 80–96 of 100 answers are byte-identical. Two abstention flips, both on answerable items and neither a loss: qwen3-4b's wrong fee becomes "not stated directly", qwen3.5-4b's correct answer stops tripping the scorer's phrase list. qwen3-14b (partial offload, its own run): every column identical, 94 of 100 answers byte-identical. Three items' retrieved sources vary between two runs of the SAME build (b11146), so that is the harness's run-to-run variation, not the bump; the E5 vectors are identical and the reranker shifts by ≤ 0.0042 with the same order.
  • Not verified here: the MTP start (the Qwen3.8 27B needs the 24 GB rig), the other five catalog chat models' gate, and the macOS asset (hash-checked only); they gate the next release tag. The #729 analysis saw two early b11960 servers end mid-generation with no crash record on ps-work. Here about 60 b12110 servers ran (repro, probes, gate, smokes, cache, speed, the real app); none ended on its own.

HOST CONFIGURATION (#730, 2026-10-29). Since b11146 (absent in b9849) llama.cpp applies config files before its 150 environment variables and the command line: %PROGRAMDATA%\llama.cpp\config.ini and %APPDATA%\llama.cpp\config.ini on Windows, /etc/llama.cpp/config.ini and `${XDG_CONFIG_HOME:-/.config}/llama.cpp/config.inielsewhere. Nothing turns it off. A key is an option's env name or its long name, so a host could set anything the app does not pass,--rpc and the download options included (--connectfrom v0.8.0, which has no negative form). The path is only tested withexists(), on b11146 and b11960 alike. Every llama.cpp spawn (LlamaServer, the --list-devicesprobe, the load check) therefore takesruntime/engine-env.ts's environment: no inherited LLAMA_*/HF_*/MTMD_*, and the OS's lookup variables (PROGRAMDATA+APPDATA, or XDG_CONFIG_HOME) point below the engine binary file, a path that cannot exist. A folder beside the engine would have been a fixed place on the drive to plant a config (review of #730). Measured on both builds with the app's argv: a host LLAMA_ARG_*or config file moved the KV cache to q8_0 and, on b11146, the chat model from 36/36 to 0/36 GPU layers; filtered, neither applied. Re-verify on every bump withgpu-smoke's #730 leg, which also fails when --helplists a variable the filter lets through. The fixed/etc/llama.cpp/config.ini is a residual (security-model.md`).

VISION RE-VERIFIED 2026-07-01 (RUNTIME-5 + RUNTIME-6). The b9849 vision smoke that §9 owed was run live on the provisioned D:\ drive. Garbage ("multilingual token-salad") image descriptions turned out to be b9849 default drift, not a model↔runtime incompatibility — the sidecar returns coherent output for every valid image when driven directly (CPU/GPU, small/large, PNG/JPEG), and corrupted input yields a clean load error, never salad. Two defaults the vision launch args never accounted for:

  • RUNTIME-6 — the salad fix (--no-mmproj-offload). On b9849 the mmproj/clip projector offloads to the GPU by default even under --device none (llama-server --help: mmproj-offload default = on). On the target hardware (shared-memory Intel Iris Xe iGPU, Vulkan default, co-resident with a 6–8 GB chat model on a 16 GB machine) the projector's GPU compute was starved under contention and miscomputed the image embeddings → the LM decoded noise as token-salad. The salad therefore reproduced ONLY in the full app (contended iGPU), never in an isolated sidecar (free iGPU). VISION_DEVICE_ARGS now also passes --no-mmproj-offload, pinning the projector to CPU and completing the "avoid VRAM contention" intent. Owner-confirmed fixed in-app 2026-07-01.
  • RUNTIME-5 — a separate large-image crash (--parallel 1). b9849 defaults to n_slots = 4 with a unified KV cache (kv_unified = true), splitting the 4096-cell context across four slots. The warm-reused sidecar (cache_prompt) + a 1536-px image's ~1700–3000 vision tokens oversubscribe the shared pool → failed to find a memory slot for batch / failed to restore kv cache → HTTP 500. --parallel 1 (VISION_SLOT_ARGS) gives the strictly one-at-a-time vision request the full context with a clean KV (n_slots = 1, kv_unified = false). A/B-confirmed live: without it a repeat large-image request 500s; with it, both succeed.

(Open follow-ups, not blocking: a 1536² image is 3000 tokens ⇒ ~4 min CPU prefill, which can hit the 300 s per-request timeout — consider lowering the renderer DOWNSCALE_TARGET 1536→1280 and/or raising the vision --ctx-size for generation headroom.)

  • -ngl defaults to auto and --fit defaults to on (upstream PR #15434, Aug 2025): the server does VRAM-aware maximum offload with a ~1 GiB margin and a min-context guard — no GPU args needed; VRAM exhaustion at load is upstream's problem.
  • --device none forces pure-CPU inference in the same binary — our only CPU switch.
  • --list-devices prints the device list and exits: an offline, no-model probe. Format: Vulkan0: NVIDIA GeForce RTX 3080 Ti (12300 MiB, 11511 MiB free).
  • The win/linux Vulkan release archives are standalone full builds carrying every ggml-cpu-* variant (dynamic backend loading): no usable Vulkan → same binary runs on its bundled CPU backends.
  • Driver baseline: Vulkan 1.2 — NVIDIA Kepler/Maxwell+, AMD GCN+ (Adrenalin/RADV), Intel Gen9+. Ships with normal GPU drivers (no SDK/runtime install); older machines fail the probe cleanly and stay on CPU.
  • Pinned asset hashes live in model-manifests/runtime-sources.yaml; the license-review record naming the two Vulkan assets is in docs/model-policy.md.

§4 Alternatives considered (and why not)

Alternative Verdict
CUDA Rejected as default (schema leaves the door open): ~620 MB incl. cudart, NVIDIA-only, proprietary-redistributable license review; Vulkan reaches ~85–95 % of CUDA token-gen speed
HIP/ROCm Rejected: AMD-only, 125–306 MB, narrow supported-GPU list; Vulkan covers AMD with standard drivers
CPU default + opt-in GPU build dir Rejected: forces a binary choice before knowing if GPU works; the Vulkan build's bundled CPU backends make the split unnecessary
Probe decides everything (no ladder) Rejected: --list-devices proves enumeration, not stable inference — a driver can enumerate fine and crash on first compute
In-house GPU detection (registry/wmic/native module) Rejected: native deps or platform scraping; --list-devices is ggml's own truth, zero deps

§5 Detection & fallback design

Implementation detail (probe §5.1, ladder §5.2, mid-generation crashes §5.3) is the "GPU acceleration: probe + start ladder" subsection above. The ladder, as a picture:

start(model), settings.gpuMode = 'auto' (default)
├─ Rung 1a— default binary + the MTP speculative-decoding flags (#182; opted-in manifests only,
│           and only past the probe/VRAM precondition — MTP record §4). Rung 1 IS its fallback.
├─ Rung 1 — default binary, NO -ngl/--device args (auto-offload; GPU-less machine ⇒ already CPU)
│           the cached probe runs CONCURRENTLY with the server start and labels backend gpu|cpu
│           a probe that lists no device yields to this start's GPU buffers (#380, #653)
├─ Rung 2 — same binary + `--device none`   (after rung-1 spawn error / exit / health timeout)
├─ Rung 3 — pure-CPU safety-net build <os>/cpu/llama-server (if present)
└─ Rung 4 — MockRuntime (existing graceful-fallback rule — never stuck)

Model fault vs device fault: the CPU control probe (issue #312). A rung-1 failure is not persisted at once — it is held, and the forced-CPU rungs are its control:

A rung-1 failure is a device verdict unless the forced-CPU rung proves otherwise. A non-GPU rung starting flushes the held failure (gpuAutoDisabled + gpuLastError, exactly as before — the model loads here, so the device was the differentiator). Only when every real rung fails and the last forced-CPU rung's failure is the same class as the GPU rung's is the model blamed: nothing is persisted, deps.onModelLoadFailure names the MODEL to the user, and the walk ends on the rung-4 mock as always. A cancelled walk (CODE-2, §5.6) blames nothing. Unknown, ambiguous, partial or contradictory evidence ⇒ device fault, i.e. today's behaviour — misclassifying a real GPU fault as a model fault would reinstate a multi-minute health timeout on every later start.

The class comes from failureSignature(reason) (sidecar.ts, beside isBindRaceError): the sidecar's own four throw shapes — launch / exit:code N / exit:signal S / timeout / integrity — plus the last non-empty line of the captured — last output: tail (earlier progress lines differ between two loads of the same broken weight). It classifies this machine's own evidence, never llama.cpp's vocabulary: a VRAM allocation failure prints the same error loading model: prefix as an unsupported architecture, so a text allowlist could not separate them — while the control probe does, and for free (a VRAM fault means the CPU rung succeeds, so the GPU is still blamed). It also survives a runtime-pin bump that drops an architecture. An unrecognised shape yields null, which the conservative fallback above reads as a device fault. Bind races (REL-1, §5.5) are still excluded before any of this.

#515 amendment (2026-09-27): the tail line is the first ERROR line, timestamp stripped, and the log is uncoloured. The rule above compared the last tail line, and on real llama-server output that line was never evidence. At -lv 4 every line carries a per-process timestamp (0.00.160.242 E …), so two rungs' last lines never matched and a model fault stayed a device verdict — the #312 bug, live wherever the log is uncoloured (macOS/Linux). On Windows the sidecar's stdout is NUL, which llama.cpp's --log-colors auto reads as a terminal, so the last line was a bare colour reset and ANY two same-code failures matched. Either way the last line is the generic exiting due to model loading error. Now (sidecar.ts failureLine): ANSI codes and the <elapsed> <level> prefix are stripped, and the signature line is the first E-level line — llama.cpp prints the root cause first (gguf_init_from_reader: this GGUF file is version …), then the generic lines, identically on every rung; else the first unprefixed error … line (an argument error, followed by a usage screen); else the last line. Every LlamaServer spawn (chat, embedder, reranker, translation, vision) passes --log-colors off (present on b9849 and b11146), and the stderr tail is stripped of colour codes before it reaches error strings, gpuLastError, the audit trail or the log export. Verified with real captured tails (tests/fixtures/start-failure-b11146-*) and the real ladder on the pinned binaries: a corrupt GGUF fails every rung and names the model, persisting nothing; a healthy model starts on rung 1.

The model verdict is remembered for the session, and reached without a GPU rung (issue #372, 2026-09-07 — the #312 follow-up). Two additions to the branch above, both in factory.ts:

Naming without a control. With gpuMode: 'off', with gpuAutoDisabled already persisted, or when the GPU rung's failure was a bind race (REL-1 drops it before it can be held), there is no held rung-1 failure and so no comparison to make. When every rung still fails, the model is named anyway (onModelLoadFailure, the same main.runtime.modelCannotLoad notice — "could not be loaded on this computer" is accurate whatever the cause) and onGpuFailure never fires on that path: nothing is persisted, gpuAutoDisabled is never written without a control.

The per-model session latch. Every model the ladder blames — on the #312 comparison, or on the no-control path above when the last failure has a failureSignature class (never a bind race, never an unrecognised shape: unknown evidence is enough to tell the user, not enough to skip every later attempt) — is latched for the session (latchModelLoad, a module-level Map<modelId, reason> beside the #182 speculativeSuppressed set; never persisted). A later start of a latched model spawns no rung: LadderRuntime.start() re-fires onModelLoadFailure with the original reason (the user is told once more why the replies are simulated) and commits the rung-4 mock at once — the outcome the first walk reached, minus up to three 180 s health timeouts. No prefetch, no read sample, no warm-up (nothing loaded); a CODE-2 cancel before the latched start still settles as cancelled, never as the mock.

Clearing rule. "Try GPU again" is about the graphics card and does not touch this latch (pinned in performance-gpu.test.ts). What re-arms a model is evidence that the file or the runtime changed: "Verify checksum" on that model (models:verify → clearModelLoadLatch; a re-verified file is a new file — also the way to retry after a transient cause such as RAM pressure), a completed in-app download of that model (ctx.onModelInstalled → the same, as the handler's first statement), a chat-engine install (EngineDownloadManager.onInstalled for llama_cpp → clearModelLoadLatches; a new binary may load what the old one could not — a kiwix-only install clears nothing), and an app restart (module state). A device verdict never latches the model, so a persisted gpuAutoDisabled still re-walks from rung 2 as before. Tests: runtime-ladder.test.ts "#372", core-model-ipc.test.ts (verify), engine-consent-ipc.test.ts (engine install), the ctx.onModelInstalled source-text pin, performance-gpu.test.ts (Try GPU again).

#530 amendment — a program the OS loader refused is neither verdict.

  • The defect. A refused llama-server (Linux without libgomp1, Windows without the Visual C++ runtime, a Smart App Control block) dies before printing a line of its own, so the #312 comparison judged the loader's line. On Linux that line carries the binary's path, which differs between the main build and the cpu/ safety net. So a prepared Kit blamed the GPU (it persisted gpuAutoDisabled), and the next start blamed and latched the model. On Windows the bare exit codes matched, so the model was blamed at once.
  • The fix. LlamaServer now throws EngineCannotRunError for such a refusal. A refused rung is excluded from the comparison: no pendingGpuFailure, no cpuSignature, no speculative latch. A walk refused on every rung fires onEngineCannotRun instead of either verdict.
  • Healing stale state. The heal at unlock clears a gpuAutoDisabled whose gpuLastError classifies as a refusal.
  • Record: "Engine load failures — design record" below.

#653 amendment (2026-10-13) — a start's own GPU buffers label it; a probe that crashed is unknown.

  • The defect. probeGpuDevices resolved [] ("no graphics card") for any non-zero exit the loader classifier did not know (a Vulkan driver crashing during enumeration: Windows 0xC0000005, a Linux SIGSEGV) and for any spawn error that was not a refusal (EMFILE, EAGAIN, ENOMEM, a POSIX ENOENT or EACCES). The session cache kept that answer and probeAndPersistGpu stamped it, and the ladder let an empty answer outrank the start's own load log. A card start was labelled cpu for the whole session:
    • the chat header and Diagnostics said CPU, and the placement record read backend: 'cpu' beside 37/37 layers on the card;
    • the stored probe was overwritten, so the Performance snapshot named no device and judged against RAM (memory class cpu, the ★ from RAM), and the #473 card gates switched off;
    • a mid-session GPU crash took #599's restart on the same GPU rung, then the stop, instead of this record's §5.3 fallback;
    • #669's heal re-probe (reprobeGpu) could re-stamp a card machine as having none.
  • A measurement that changed the rule. On the GTX 1070 Ti box, b11146 and b9849 both print offloaded 37/37 layers to GPU on rung 1 with every Vulkan device hidden (GGML_VK_VISIBLE_DEVICES=7, the stand-in for a GPU-less PC) and under --device none. Every buffer was on the processor (CPU_REPACK), the card load was 0 % and the prefill ran at 54–56 tok/s. So the offload line is no evidence of a card. #380's unknown-probe label read it, which mislabelled a GPU-less PC whose probe gave no answer as gpu: on the real app, master showed "· GPU (Grafikkarte)" with VRAM unchanged.
  • Owner calls (2026-10-13), all as recommended:
    1. A probe that lists no device, whether it answered empty or gave no answer, yields to GPU buffers in this start's load log. The start is then labelled gpu and named like #380 did (the device_info row with the largest compute buffer). The same rule replaces #380's gpuLayers > 0. A log that is silent or shows only CPU buffers never overrides.
      • The evidence is PlacementParser.holdsGpuBuffers(): a model, KV, recurrent-state or compute buffer of more than 0 MiB, filed under a label the log's own device_info block lists as a GPU, or under <label>_<suffix> (a mapped buffer). A CPU-side label never counts.
      • It is a method, not a field of the reading, because the reading is the persisted ModelPlacement shape.
      • The first version counted any buffer isCpuDevice does not claim. The review caught that this is a blacklist: ggml's CPU backend has an AMX buffer type (Sapphire Rapids; the shipped ggml-cpu-sapphirerapids.dll carries the name), which would have labelled a GPU-less Xeon gpu.
    2. The mirror stays. A listed card with offloaded 0/N layers is labelled gpu. Measured with -ngl 0: the start still reserves a 91 MiB Vulkan0 compute buffer and runs the prefill on the card (74 % load, 302 tok/s against 56 with --device none). A driver crash can still hit it, and §5.3, which really removes the card, is the right path for it. The Performance screen already shows the 0/N split.
    3. The root cause. The probe resolves null (unknown) for any non-refusal non-zero exit or signal and any non-refusal spawn error. That answer is not cached and not persisted, so the stored probe stands, and it is logged once ("The device probe gave no answer"). It records no engine verdict: the engine ran, and the server may well start a moment later. Only an exit 0 is an answer: the parsed devices, or [] when it printed none (b11146 writes (none) under the header, b9849 the header alone, both captured). A binary the integrity check refuses still reads []. (Changed by #1012 code review round 6: it reads null, with the engine-files verdict; security-model.md "Re-hash sidecar binaries before spawn".) Rejected: treating an exit 0 with unparsed lines as unknown. A driver that writes to stdout would make every probe on that machine unknown, and the pin-bump case it would catch is already caught by the b11146 capture test and the re-capture rule.
    4. The Translate screen's device hint reads the same offload line. On a GPU-less PC it would claim the card. That is filed as #671, not fixed here. (Fixed by #671: the translation record's "#671 amendment".)
  • What each part changes.
    • The label (1) fixes, for this start, everything that reads RuntimeStatus.backend and the placement: the header, Diagnostics, the stored placement, the #322 speed identity, the #473 chat share and the §5.3 crash gate.
    • The root cause (3) keeps a crash out of the stored gpuProbe, so the tile, the memory class, the ★ pick, the profile and the #473 gates keep this machine's last real answer.
    • #669's reprobeGpu now writes nothing on a crash.
    • A probe that crashes every time costs one crashing child per caller, bounded at 10 s. That means each refresh, check or "Try GPU again", and each model start: two for a model with the MTP rung, since the speculative check's null drops itself before rung 1 asks again. The server would then crash at the same point too.
    • The kill-timeout settles the probe before it kills. Its own SIGKILL, or an error from a kill that failed, is then not logged as a second non-answer. What a late close says about the program still counts: an exit 0 clears a stale refusal verdict, because the program ran, and a loader refusal is still recorded as the verdict. The crash log carries the stderr tail, as the refusal log does.
  • Real app (DesktopDiT, GTX 1070 Ti, b11146, the 4B). A wrapper in a scratch root ran --list-devices as an exit 0xC0000005 and everything else as the real server, inside a kill-on-close Job Object. Launch 1 stored the card; launch 2 crashed the probe.
    • Master: stored probe [], live snapshot without a device, chat header "· CPU", Diagnostics "CPU", placement cpu with 37/37 layers while VRAM rose 2.2 → 5.5 GB. Killing the server restarted it on the same GPU rung; a second kill stopped the model.
    • Fix: the stored card stood, the header read "· GPU (NVIDIA GeForce GTX 1070 Ti)" with the placement gpu. The first kill took §5.3 (compatibility mode, --device none, gpuAutoDisabled); the second took #599's one CPU restart.
  • Residuals:
    • An exit-0 empty answer the server contradicts (an enumeration race, a pin bump that changes the device-line shape) labels the start correctly. But [] stays the session's cached answer and the stored probe until "Try GPU again" or the next session. The ladder's dependency is a bare function, so it cannot invalidate the cache.
    • A probe that lists a card is never demoted (owner call 2). So a start that holds no GPU buffer at all reads gpu: an eGPU unplugged after the session's probe, say.
    • The persisted gpu/cpu MiB split (gpuModelMb, …) still uses the isCpuDevice blacklist, so an AMX buffer would count as card memory in the placement figures and the #473 chat share. This predates #653 and is a follow-up candidate; the label no longer reads it.
    • A drive that has never stored a probe still shows no card on the tile while its probes crash.
    • Like a timeout (#380), a crash at the unlock refresh leaves the ladder's own probe to run beside the weight upload. An answer there becomes the session's and can be persisted with the chat model already on the card. That is the baseline #473 sequenced the unlock probe to avoid. It is rare, and harmless on NVIDIA/Windows, whose free figure does not move (#318). Caching a crash's unknown for the session would close it, against owner call 3's "not cached".
    • The binary verifier reports a transient read failure (an antivirus lock while hashing) as mismatch, so the probe answers []: "no GPU" for the session. The integrity paths keep [] by owner call 3. (Fixed by #1012: a read failure is unreadable, and since its code review round 6 every integrity path answers null.)
  • Tests:
    • runtime-ladder.test.ts:
      • real b11146 captures for the empty and unknown answers yielding to GPU buffers, the GPU-less rung 1, and the 0/37 mirror;
      • handwritten rows for an AMX buffer (cpu) and a Metal mapped buffer (gpu);
    • gpu.test.ts: crashes and EMFILE resolve null; neither the kill's own close nor a failed kill logs anything;
    • engine-load-spawn.test.ts: no verdict for an unclassified exit; after the timeout, a late exit 0 clears a stale verdict and a late refusal records one;
    • placement-parser.test.ts: holdsGpuBuffers' edge rules (0 MiB, KV-only, RS-only, Vulkan1 vs Vulkan10, a host buffer against a numberless row); the DR3 content guard covers the two new captures.

Interaction with #320 (excluding a hybrid laptop's iGPU with --device at launch): decided 2026-09-07 — it does not land; the fit already drops the integrated device by type (runtime record above), so rung construction is unchanged and this interaction is moot. Had it landed, a rung-1 failure could have been caused by the app's own device selection — and would still be classified correctly, because the forced-CPU rung comes up and flushes the failure as the device verdict it is. A text-allowlist design would not have that property.

(Rung 1a, the speculative-decoding rung, is documented in its own record — "MTP speculative decoding — design record (issue #182)" below. It never persists gpuAutoDisabled, and its mid-session crashes take a separate handler from §5.3 for the same reason: the extra flags are the suspect, not the device.)

§5.3 Mid-session crash auto-fallback (corrected — full-audit 2026-06-28, REL-1):

A GPU-backed llama-server can die after it became healthy — a driver crash, VRAM stolen by another process. LlamaServer's onUnexpectedExit hook fires (only for a healthy server dying outside stop(), and once per death: #656 — its 'error' and 'exit' handlers share one per-spawn reportUnexpectedExit, because Node may emit 'exit' after 'error'); LadderRuntime forwards it to onGpuCrash only when the backend it landed on was gpu (its onUnexpectedExit; a non-GPU exit goes to onCpuCrash since #599). Since #653 that label is gpu for a start whose own log put buffers on a card even when the probe listed none; before, a crashed probe sent a card start's GPU crash down #599's same-rung restart (§5.2 "#653 amendment"). createGpuCrashAutoFallback then, in order: persists gpuAutoDisabled + gpuLastError, surfaces the friendly compatibility-mode notice, and restarts the model once at CPU — so the user's next message just works.

The idempotency interaction (the bug this record previously mis-described). The restart can not go through RuntimeManager.start(). After a mid-session crash the manager has not observed the child's exit: the crashed LadderRuntime is still this.current with the same modelId, and this.last still holds the health snapshot cached at start. start()'s same-model idempotency guard (runtime/index.ts, "already running / start in flight → no-op") then early-returns a stale status read — the "restart at CPU" never stops-and-restarts, status() keeps reporting the dead server as running/healthy, and the next chat/RAG/doctask turn routes to it and fails. (The earlier wording here — "restarts the same model once at CPU" — was therefore false; the restart was silently swallowed. The unit tests missed it because the ladder test injected a fake restart and the manager test proved the guard in isolation; nothing wired the real crash path through the real manager.)

The fix (option b — a crash-only forceRestart). RuntimeManager.forceRestart(opts) runs doStop() (clearing current/last, so status() immediately stops reporting the dead server as healthy) then doStart(opts) inside one enqueued op, bypassing only the same-model guard. Normal start() idempotency is untouched — a double-click or an AI-Model-screen revisit still must not restart; only the crash path forces it. startingModelId is set synchronously (exactly as start() does) so a concurrent manual start(sameModel) joins the in-flight restart instead of queueing a second one. The crash wiring in main/index.ts calls runtimeRef.forceRestart, not start. (Alternatives weighed: (a) wiring-level stop()-then-start() — rejected, the two ops enqueue separately so a concurrent user start could interleave between them; (c) have the manager subscribe to the runtime's unexpected-exit and clear current/last itself — more plumbing for no extra guarantee. forceRestart is atomic within the queue and easiest to test.)

#600 amendment (2026-10-06).

  • The answer the crash interrupted now ends with main.chat.connectionLost ("The AI model stopped before the answer was finished…"), not undici's raw "terminated". The runtime raises RuntimeConnectionLostError; see the CB-5 "#600 amendment".
  • forceRestart passes restart to doStop, so the model-stop hook (which ends in-flight answers as clean stops on a deliberate stop or switch) does not run. Those answers have already failed on the dead socket.

#599 amendment (2026-10-06) — the CPU-mode crash.

  • The ladder used to drop a non-GPU unexpected exit, so after a CPU crash every surface said "running" and each turn failed on the dead port. It now goes to onCpuCrash: createCpuCrashAutoRestart restarts the model once per model per session (main.runtime.crashRestarting), and a second crash of that model stops it (RuntimeManager.stopCrashed, main.runtime.crashStopped). No GPU flag is touched.
  • The budget is separate from the GPU fallback: a GPU crash restarts on CPU (this section), and that CPU runtime still gets its one restart. At most two automatic restarts per model per session.
  • A user Restart (the AI Model card, for a model that stopped responding) also uses forceRestart, passing switch: the user acted on the model, so its answers end cleanly first (#600). An unresponsive GPU is not a GPU fault. See the CB-5 "#599 amendment".

Retry bound (no restart loop). gpuAutoDisabled is persisted before the restart, so the ladder rebuilt inside doStart skips rung 1 and lands on CPU (--device none). A later crash is then a CPU crash, which LadderRuntime does not route to onGpuCrash (backend !== 'gpu') — so a GPU session auto-falls-back at most once, never in a loop. (Since #599 that CPU crash gets its own single restart, then the model stays stopped.) Re-entrant crash reports while a restart is in flight are also dropped by createGpuCrashAutoFallback's restarting latch.

(LlamaServer.start() additionally carries its own single-flight latch (REL-2): two overlapping direct start() calls now share one spawn instead of the second orphaning the first — so the crash-restart's stop-then-start can never race a stray direct start into a leaked sidecar.)

§5.5 Port-race retry + bind-vs-device classification (full-audit 2026-06-29, REL-1). findFreePort binds port 0, reads the assigned port, then closes the listener before handing the number to llama-server --port N. In that TOCTOU window another process — or a sibling in-app sidecar (chat + embedder + reranker + vision start near-simultaneously) — can grab the port, so the child exits "address already in use". Two corrections: (a) LlamaServer.start() now retries doStart() once on a bind-class immediate exit (isBindRaceError, matched against the start error message which carries the stderr tail), acquiring a fresh free port — bounded to one retry so a genuine failure still surfaces; this covers the chat runtime AND the embedder/reranker/vision (which compose LlamaServer directly and previously had no retry at all). (b) LadderRuntime no longer persists gpuAutoDisabled when a rung-1 failure message is a bind race rather than a device/driver/model fault — so one unlucky port collision can never disable GPU for the whole session. Only a real device failure auto-disables — and since #312 (§5.2) "real device failure" is decided by the CPU control probe, not by the message text: the bind-race exclusion here runs first and is unchanged.

§5.5b Bind-race aware START-LATCH for the embedder + reranker (full-audit-2026-06-29-postmerge, F4/F7). The bind retry above is bounded to ONE attempt, so during the documented near-simultaneous chat + embedder

  • reranker + vision startup a sidecar can still lose the port twice and have start() throw a bind-class error. The embedder (embeddings/e5.ts) and reranker (reranker/llama.ts) each carry a failed-start latch that fails fast (no health-timeout stall) on every subsequent call — intended for a PERMANENT fault (a corrupt/incompatible GGUF). The latch's .catch previously armed for any rejection, so a transient double-bind-race latched a permanent-looking failure: the embedder then silently disabled ALL imports for the session (it has no graceful degradation) until lock/unlock, and the reranker disabled reranking for the whole session (a silent quality regression — rag/index.ts falls back to fused order) and its latch even survives suspend(). Both .catches now reuse the same isBindRaceError classifier as the retry (the retry and the latch must agree): a bind-class message leaves startFailed null, so the next embed()/rerank() re-attempts a fresh start on a new port. Only a genuine load fault latches — which makes the reranker's deliberate keep-the-latch-across-suspend() policy correct again (a bad GGUF won't load after unlock; a port race must not be remembered). The embedder additionally clears its latch on suspend() (its one deliberate difference — see "Models & runtime"), so a replaced weight file is retryable via lock/unlock.

§5.5c tearingDown guard — suspend() gets the orphan protection stop() has (full-audit-2026-06-29-postmerge, F19). stop() (will-quit) sets this.stopped = true BEFORE teardown(), so a racing lazy ensureStarted refuses to spawn and can't leave an orphan. suspend() (workspace LOCK) sets no such latch, so a suspend() that interleaved with a concurrent embed()/rerank() — a RAG-query or tree-build embedding, which are NOT in inFlightStreams and which abortActiveBuild() only cooperatively cancels — could stop the OLD sidecar while a fresh ensureStarted spawned and retained a new one, surviving the lock with chunk/query-text- derived state in process RAM. Fix (both embeddings/e5.ts and reranker/llama.ts): a tearingDown flag is set at the top of teardown() and cleared in its finally; ensureStarted refuses (throws "is suspending") while it is set — at the top AND re-checked after await this.starting (a teardown may begin during that await and null the server it would return). Cleared in finally, so a normal post-suspend embed()/rerank() still lazily restarts (only stop()'s separate, permanent stopped latch blocks that). Deterministically teeth-tested (e5-embedder.test.ts / reranker.test.ts, F19): a gated-exit child parks teardown's server.stop(), a concurrent embed/rerank fires in that window, and the assertion is that NO sidecar survives the lock (one spawn, killed) — red without the flag (the concurrent start spawns + is retained).

Phase-6 extensions of this latch family (full-audit-2026-06-29 follow-up; see §37 for the ledger). (a) REL-2 ports the SAME tearingDown shape to VisionService (which had no orchestrator-level latch): set at the top of stop(), re-checked in run() at the top AND after the getStatus() await, so a NEW analyze() arriving during teardown can't rebuild the ~4.6 GB vision sidecar past the lock. (b) REL-3 adds the missing BETWEEN-batches re-check to e5.embed() (it captures server once then loops): each batch re-throws the same recognizable cancellation if stopped/tearingDown is set or the captured server went stale (this.server !== server), so a suspend()/stop() mid-ingestion ends as a clean cancel instead of a confusing "llama-server is not started" on the next batch.

Phase-C extension (full-audit-2026-06-30 R7; see §39). VisionRuntime.stop() re-calls cancelIdleTimer() AFTER its awaits so its "no idle timer is live on return" postcondition holds LOCALLY. The race is already closed by armIdleTimer's this.stopped + !this.server early-returns (both set synchronously by stop() before any await — triple-guarded), so this is a defense-in-depth backstop in the same co-guarded family, not a live fix.

§5.6 Shutdown latch + cancellable start (full-audit 2026-07-11 CODE-2/CODE-3; rider CODE-11). Two quit-path gaps in the manager/ladder lifecycle, closed together:

  • CODE-3 — RuntimeManager.shutdown() latch. The chat manager was the one runtime without the TranslationRuntime.stopped-style permanent latch. startModelRuntime hashes a multi-GB weight before touching the manager; a quit beginning in that window found nothing to stop, and the hash could then complete inside the teardown's awaited windows and enqueue a fresh start AFTER the stop — app.exit(0) kills the parent mid-start and orphans the child (Windows especially). Now: performShutdown arms runtime.shutdown() (synchronous, latch-only) as its FIRST act; once armed, start()/forceRestart() reject without invoking the factory, a start already sitting in the queue refuses inside doStart before it can spawn, and startModelRuntime re-checks the latch right after its hash completes (ctx.runtime.isShutdown()). The awaited runtime.stop() stays in the sidecar block (REL-4 ordering intact — pinned in shutdown.test.ts).
  • CODE-2 — cancellable model start. stop() deliberately queues behind an in-flight start() (that ordering is what prevents orphans), but the start itself was uncancellable — a 20 GB GGUF load, or a failing ladder walking up to 3 rungs × 180 s health timeouts, froze quit and "Lock now" for minutes (users hard-kill → orphan, the exact outcome the queue exists to prevent). LlamaServer.stop() during waitForHealthy already worked one layer down (the exit-check throw); the fix makes it reachable: the manager tracks the in-flight startingRuntime and stop() forwards a cancel to it directly, and LadderRuntime.stop() sets a permanent cancelled flag that (a) aborts the ladder walk between rungs, (b) stops the in-flight rung's server, (c) never persists gpuAutoDisabled for a killed attempt (not a device fault), and (d) refuses the rung-4 mock fallback for a cancelled start. Queue semantics are unchanged — the queued stop still runs after the start settles; the start just settles promptly now. Never a bare timeout race (would orphan the loading child). Pinned in runtime-manager.test.ts ("quit-path lifecycle": "stop() mid-start kills the loading child…" covers (a)–(d) over a real LlamaServer) + runtime-ladder.test.ts ("ladder start cancellation": a stop before the walk begins; the warm-up window and the #312 / #372 verdict cancels sit in their own blocks).
  • CODE-11 — crash-exit child reap (rider). A hard uncaughtException skips will-quit's awaited sidecar stops entirely, and on Windows the children survive process.exit(1). Every sidecar spawn funnels through LlamaServer or WhisperCliTranscriber; both now register/deregister their live child PIDs in a module-level registry (runtime/sidecar.ts), and the crash handler's last act is a best-effort synchronous SIGKILL loop over it (throw-safe per PID, after the vault lock). Residual: a crash that bypasses uncaughtException itself (native crash of the main process, external kill) still orphans — accepted; the OS is the only backstop there.

§5.4 Where GPU state lives:

Datum Home
gpuMode: 'auto' | 'off' (user intent; Settings toggle) AppSettings (encrypted DB)
gpuAutoDisabled, gpuLastError (detected problem) AppSettings — written by the ladder once its CPU control probe confirms a device fault (§5.2, #312); cleared by "Try GPU again". A model no rung can load writes neither field, nor does a program the OS loader refused (#530) — and a pair a refusal wrote before #530 is cleared at the next session start (healEngineLoadState)
Models blamed as unloadable this session (#372) factory.ts module state (Map<modelId, reason>, the #182 speculativeSuppressed idiom) — never persisted; a latched model's next start spawns no rung. Cleared per model by "Verify checksum" / a completed download of it, for every model by a chat-engine install or a successful engine "Check again" (#530), and by an app restart — not by "Try GPU again" (§5.2)
gpuProbe (devices + probedAt + machineKey, the stamp of the machine it ran on — PR #303 audit M8.3) AppSettings — persisted by the benchmark path and refreshed once per session post-unlock, so a drive moved between machines re-labels itself; a probe stamped with another machine supplies nothing to the Performance screen, the Models ★ or the benchmark, an unstamped legacy one stays eligible until a local refresh replaces it (eligibleGpuProbe, shared/gpu-rules.ts). Since the PR #308 audit (decision 6) a probe that cannot run (no binary resolves) or that threw persists an empty probe ({ devices: [], probedAt, machineKey }) exactly like an empty successful probe — stamped, and only after the admission + unlock-epoch re-check — so a card from a previous session on the SAME machine never survives a failed refresh and the Models badge, the benchmark and the Performance tile can never disagree on the device (an empty stamped result re-stamps no old device, so #303's "no re-stamping" guarantee holds either way). Refreshed again when the chat engine is installed (issue #323, 2026-09-06): EngineDownloadManager.onInstalled → refreshGpuProbeAfterRuntimeInstall re-runs the same probeAndPersistGpu (cache invalidated first) when a llama_cpp install reaches done and this machine's eligible probe lists no device — the empty probe of a benchmark run before the binary existed; an eligible probe with a device, a whisper-only install, or a failed / cancelled one leaves it alone, and the benchmark is never re-run. Decision 6 amended (#380, 2026-09-08): its one exception is a probe that TIMED OUT — that is not an answer but the absence of one, so it writes nothing and pushes nothing, the stored stamped probe stands until the next start / check / "Try GPU again", and the summary the run uses comes from this machine's record (eligibleDevicesFor), which is what decision 6 actually requires. Persisting the empty stamped probe there was the #330 failure: the driver was busy with the weight upload, and a card machine was recorded as having none. #530: a program the OS loader refused is the same kind of non-answer — the probe resolves null and records the engine verdict instead of persisting "no graphics card". #653: so is a probe that crashed (any other non-zero exit or signal) or could not be spawned — null, no verdict, nothing written; before, it stamped [] over a card machine's record (§5.2 "#653 amendment")
Active backend + GPU name this session RuntimeStatus (in-memory, getRuntimeStatus IPC) — factory.ts's gpuName is the shared displayDevice(devices) pick (PR #303 audit M8.2: the budget device, else the largest non-integrated one, else the first listed — an earlier devices[0] rule named the iGPU on a hybrid box while the model ran on the dGPU), display only; it is not necessarily the budget device the picker or the Performance tile use. When the probe lists no device — UNKNOWN (#380), or since #653 an empty answer — both the backend and the name come from this start's own load log instead: gpu when it filed a buffer on a device its own device_info block lists as a GPU (PlacementParser.holdsGpuBuffers; until #653 this read gpuLayers > 0, which a GPU-less rung 1 prints as 37/37 too), named from the device_info row that took the largest COMPUTE buffer (else the largest row). Never the FIRST row: the parser keeps them in LOG order, which is not the order the fit used — on the ryzen-7-5800h-rtx-3060-laptop-6gb-14gb evidence Vulkan0 is the iGPU, listed first and given no buffers at all, while every buffer went to the RTX at Vulkan1. displayDevice itself cannot be reused there: it takes GpuDevice[], whose totalMb is non-null, and a PlacementDevice's is nullable

Runtime record (PR #308 audit, 2026-09-06; the -np half DECIDED 2026-09-07), not a picker change. The chat server used to run on b9849's default four unified slots (n_slots = 4, kv_unified = true) because the app's argv passed no -np; for a single-user chat app that cost real recurrent/sliding-window cache the picker's estimated_context_cache_gib term had to account for (model-benchmarks.md §6.6). Owner decision 2026-09-07 (issue #319): CHAT_SERVER_ARGS passes -np 1 — one slot, chat only. The app already serialises every lane that reaches this server (the model-slot arbiter; the local API's depth-one admission answering 429 beyond it), so the four slots were never used in parallel, and on the rig one slot turned the 27B Q5's 62/66 layers at 30.4 tok/s into 66/66 at 51.0 by cutting the recurrent state from 1,795.50 to 448.88 MiB (#318 leg 1). It does not change the context window: --ctx-size is the total cache on both settings and each slot sees all of it (n_ctx_slot = 8192 either way), so only the per-sequence recurrent term moved in the seven manifest cache estimates — the KV and Gemma's sliding-window caches are cell-sized and counted once. Accepted cost, corrected 2026-09-09 (#399): a background job evicts the chat conversation's KV prefix, and on 11 of the 14 chat models llama-server's host-RAM prompt cache does not restore it — recurrent state (the whole qwen3.5/qwen3.8 line) and a sliding window (all four gemma4 manifests) both close that path, so the server saves the conversation and silently re-prefills it anyway. Not caused by -np 1 (four slots lose the restore the same way) and not fixable by any slot arrangement, so the fix is not to evict: the model-slot arbiter waits 90 s after a chat turn before resuming a parked deep-index build, capped at 10 minutes of deferral per park (D3(a)), and --cache-ram 0 stopped the unreadable copy being written for those families (D5). Reversed on the b11146 pin (#512, 2026-09-27): qwen3.5 and gemma4 restore there (48 of ~1,700 tokens re-prefilled), so the family gate is gone; every chat start gets --cache-ram min(8192, total RAM MiB / 8), and a manifest opts out with disable_prompt_cache: true (none does; shared/prompt-cache-rules.ts). The D3(a) arbiter wait is unchanged. Record: model-benchmarks.md §6.6 "2026-09-07 amendment (#319)", its "2026-09-09 correction (#399)" and its "#512 amendment"; BUILD_STATE §5 item 22 (f)/(i). Separately, whether --fit also puts layers on a hybrid laptop's iGPU — which the app never excludes with --device — was read from common/fit.cpp as "it spreads layers across every device --list-devices lists". MEASURED FALSE on the pinned b9849 build (#318 leg 5, 2026-09-07; decided on #320 that the never---device rule stands): llama.cpp drops the integrated device by type before the filling pass. On the desktop hybrid (RTX 3080 Ti + UHD 770, discrete listed first) both devices appear in device_info and then using device Vulkan0 alone; on the APU-first laptop (AMD Radeon(TM) Graphics listed FIRST, RTX 3060 Laptop second) every GPU buffer landed on the RTX and the fit's own device list never contained the iGPU — its "device 0" was Vulkan1. So an app-side --device would change nothing, and it would break the ladder's contract that --device none is the only device argument the app ever passes. Evidence: eval/results/hardware/i9-14900k-rtx-3080-ti-12gb-64gb/leg5-baseline.*, …/ryzen-7-5800h-rtx-3060-laptop-6gb-14gb/leg5-device-landing.comment.md; BUILD_STATE §5 item 22 (j). Residual: no Intel-first hybrid exists in the project; the exclusion is by device type, so it is expected to carry over.

"Try GPU again" is the dedicated gpu:try-again IPC: clears the flags and invalidates the session probe cache and re-probes + persists (a plain settings write would keep a once-timed-out probe cached as "no GPU"). Diagnostics hides the button while the Settings toggle is off. R5 (full-audit-2026-06-30, §39): the cache invalidate() drops only SETTLED probes — while a probe is still in flight a re-probe COALESCES onto it rather than spawning a second short-lived child, so mashing the button during a slow/cold driver init can't stack one-per-click children for a binary. All GPU decisions happen post-unlock (settings live in the possibly-encrypted DB) — fine, since sidecars only ever start while a workspace session is open. That invariant is enforced by the lock latch (security-model.md "The lock latch — admission during the teardown"), not by isUnlocked() alone: the DB stays open for the whole lock teardown and the whole quit teardown, so every content surface admits through workspaceAdmitsWork() (isUnlocked() && !isLocking()), the latch is armed first by both the lock handler and performShutdown, and a model start whose multi-GB weight hash spans a lock is refused by that check plus a session-epoch comparison. The one gap left: RuntimeManager.forceRestart re-checks only the quit latch internally, so the GPU-crash fallback's workspace check sits at its main/index.ts composition seam rather than in the manager.

§6 Per-OS build matrix (what ships on the drive)

OS/arch runtime/llama.cpp/... Backends inside
win/x64 win/ ← win-vulkan zip (default) · win/cpu/ ← win-cpu zip (safety net) Vulkan + all CPU variants · CPU only
linux/x64 linux/ ← ubuntu-vulkan tar.gz (default) · linux/cpu/ ← ubuntu tar.gz same
mac/arm64 mac/ ← macos-arm64 tar.gz (unchanged) Metal + CPU
mac/x64, win/arm64 not shipped (out of scope; Intel-Mac note in known-limitations.md) —

Each install dir carries a .hilbertraum-runtime.json marker ({version, backend, os, arch}); fetch-runtime skips are marker-based and re-fetches pre-clean the dir (everything except the archive + cpu/) so an upgrade can never keep a stale binary under a fresh marker.

§7 The embedder (E5) stays on CPU

E5Embedder composes the same LlamaServer, so the Vulkan build would auto-offload it too. It is pinned with --device none: the 384-dim ~242 MB model embeds hundreds of chunks/second on CPU (ingestion is parsing-bound), while GPU would add a second VRAM context competing with the chat model and a second process exposed to driver flakiness during ingestion, where a crash fails a whole document. Revisit only if a larger embedding model lands. This is also the codebase's permanent, tested forced-CPU spawn example.

The reranker no longer shares this permanent pin (step 4-4, rag-design.md §17 PR-B record). Until Phase 4 PR-B, LlamaReranker cited this SAME section for the identical reasoning ("a sub-1B scorer gains little from a GPU and must never contend for VRAM with the chat model") — both sidecars were permanently --device none. PR-B splits them: the reranker's device posture now follows the rerank hardware profile (rag/rerank-profile.ts) — CPU-pinned (--device none, byte-identical to before) on the cpu-hi and default profiles, on the GPU (no --device argument at all — llama-server's own ngl-auto + --fit, the same rung-1 semantics the chat runtime uses) on the gpu profile. --device none stays the only device argument the app EVER passes anywhere (never -ngl); the embedder above is unaffected and remains permanently CPU-pinned. See reranker/llama.ts's own header for the exact launch-argument construction and rag-design.md §17 for the profile rule, run L's selection and run A3's acceptance floors.

The posture is gated on PROVABLE HEADROOM, not the profile bump (step 4-5, Wave 5 ruling (d), rag-design.md §17 PR-B record continued). The scoped Opus review of step 4-4 found that gating the reranker's GPU posture on gpuUsefulForProfile (the profile-bump predicate above — some probed device at or above USABLE_VRAM_MB) answers the wrong question: that predicate is deliberately conservative in ONE direction (never bumps a model recommendation too high) and, by its own doc comment, never decides placement — it says nothing about whether there is room for a SECOND resident model beside the chat model already loaded. rerankerDeviceFor (rag/rerank-profile.ts) now takes the budget device's free-memory figure (graphicsBudgetMib(primaryUsefulDevice(probeDevices))) minus the active chat model's own placement estimate (estimateGraphicsNeedMib, the same estimator §8's picker and the fit budget use), and compares the remainder against the reranker's own estimated need under that same estimator (≈ 2.8 GiB, derived from the shipped bge-reranker-v2-m3 manifest and frozen as RERANKER_HEADROOM_FLOOR_MIB). An unknown or empty probe, no useful device, no budget figure, no active chat model, or an unresolvable manifest all mean 'cpu' — a machine cannot earn the GPU posture by failing to report. gpuUsefulForProfile keeps every other job it has (the profile bump above, the Models ★, the graphics tile); only the reranker's own posture question is re-sourced. Disclosed limit: the project's 12 GiB measurement machine (RTX 3080 Ti) has ample headroom for both models at once, so on it the new gate behaves identically to step 4-4's — the step's acceptance read confirms no regression there, but cannot validate the gate on the small-card path the gate exists for (a 5–6 GiB card where the chat model alone may leave too little room for the reranker too). No such machine was reachable from step 4-5's session (hardware-leg.json, available: false); the insufficient-headroom branch is covered only by rerank-profile.test.ts's fixtures (real device/manifest figures, including the #318 RTX 3060 Laptop's own totalMb), not by a live run — see docs/known-limitations.md for the same gap. A live small-card leg remains open.

The posture gate now also determines the candidate scope on the gpu profile (step 4-6, Wave 6 ruling (a), rag-design.md §17 PR-B record continued). Step 4-5 deliberately left resolveRerankProfile's scope classification alone when it re-sourced the posture, which meant a small-card machine could resolve profile gpu — and therefore the wide GPU_RERANK_SCOPE, up to ALL_SCOPE_MAX_DOCS = 512 documents — while the sidecar it was about to call correctly started --device none. rerankScopeFor now takes the resolved posture and, on the gpu branch only, returns capped when the posture is cpu; cpu-hi and default are unaffected (cpu-hi's posture is always cpu by construction, so a general "posture cpu ⇒ capped" rule would have killed its top48 opt-in — a dedicated regression-guard test pins this). The posture itself is computed by ONE shared helper (main/services/rag/device-posture.ts) that both the sidecar's own rerankerDevicePosture seam and the per-ask resolveAskCandidateScope call, so the two cannot disagree for a given settings AND occupancy snapshot (Wave 8, step 4-8, below, adds occupancy to what "the same snapshot" means). The coupling was proven a no-op on the measurement machine (its recorded posture is gpu, remainder 7,478.6 MiB) before landing, offline, with no new acceptance read. The small-card disclosure above is unchanged by this: the gate still ships on the arithmetic alone, unconfirmed by a live small-card run — what changed is that a small card now also gets the fast, bounded capped scope instead of a 512-document wide scope run through a CPU reranker.

Step 4-7 (Wave 7 ruling (a)) closed a drift window across settings snapshots: a posture-moving settings change suspends the sidecar too, as an early release. The scoped Opus review of step 4-6 found that the shared helper above guarantees the sidecar and the per-ask scope compute the SAME posture from the SAME inputs, but not at the same MOMENT: the sidecar resolved its posture once per cold start and held it for the session, the ask re-resolved on every ask, and only a gpuMode/gpuAutoDisabled flip suspended the resident sidecar — an activeModelId change (which also fed the posture at the time, through chatModelNeedMib) suspended nothing, reopening the wide-scope/CPU-reranker combination through a drift window (measured concretely on the project's own GTX 1070 Ti — finding C2). activeModelId joined the suspend trigger, fired from all three settings-writing channels (settings:update, models:select, runtime:use) through one shared predicate. That event-time suspend is a head start, not the correctness guarantee — see step 4-8 below for what actually makes the posture correct at every moment.

Step 4-8 (Wave 8 rulings (a)-(d)) resolved a THIRD gap, finding C3 (scoped Opus review of step 4-7): activeModelId was never a safe posture input to begin with. It is a proxy for "the chat model that will be loaded", true only once runtime:use's multi-GB weight hash and load finish — and false for the WHOLE window before that. A down-switch on the project's own measured GTX 1070 Ti ({totalMb: 8273, freeMb: 7504}: the 9B running at posture cpu, switching to the 4B) could cold-start the reranker on the GPU beside the still-resident, still-running OLD chat model, for as long as the checksum hash took (minutes on a cold per-workspace cache). Option B′, the fix: the posture's chat-model input is now the RUNTIME's COMMITTED model (RuntimeManager.activeModelId(), main/services/rag/device-posture.ts), never the setting, and never a fallback to it — during the hash window the committed model is still the OLD one, so the posture is correct by construction, not by a suspend's timing. A null committed model, a chat-model start in flight, a chat-model start PENDING (a per-call counter in startModelRuntime covering the window it spends awaiting the reranker's own single-flight suspend before the load, placed between the RAM gate and the shutdown re-check so the existing shutdown/lock/epoch ordering is unchanged), or a GPU-posture translation sidecar occupying the card (loading, resident, or mid-teardown — deviceStatus().live alone misses all three stages) each force cpu. What makes the posture correct at every MOMENT, not only at a suspend-covered event, is the reranker's own use-time re-check (Q): rerank() resolves its posture fresh before starting/joining/reusing the sidecar, and again after every await inside it, so a resident sidecar recorded under a stale posture is restarted before serving a request — under four race rules (never join a teardown it did not start; after its own awaited teardown, refuse if its own signal aborted or another caller also wanted a teardown during that pass; at most one restart per call; a start-abort not caused by the call's own signal is a non-abort error, landing on Wave 5 ruling (e)(i)'s capped fallback instead of ending the ask). A CPU-posture request above a computed ceiling (2 × ragTopKInitial + totalCandidateCapFor(rerankScopeFor(profile, input, 'cpu')) — 48 at the defaults, 72 under the top48 opt-in) is refused before any start, for the same reason G existed conceptually since Wave 6: a wide set must never reach a CPU cross-encoder. The sidecar's teardown is now single-flight (an overlapping suspend()/stop() shares one pass — the translation runtime's own M5 pattern, ported) and recovers from a dead handle after one unexpected mid-session exit (the translation runtime's M1 pattern; a second exit in the same session latches like a genuine load fault). Wave 7's three event-time suspends stay as early release — a head start before the very next rerank() would have resolved the new posture on its own — not what makes the posture correct any more; Q is. Residuals (translation's own cold-start/teardown occupancy cost to the reranker, the gate's manifest-only chat-model estimate, other GPU consumers and a stale probe, and a GPU-posture failure disabling reranking for the session) are disclosed in docs/known-limitations.md, not fixed — follow-up issues cover a GPU→CPU demotion path, an app-wide VRAM arbiter, the E5 embedder's own pre-existing (unrelated) teardown overlap, and the Performance card summary line's omission of a resident reranker.

§8 Expectations, profile bump, UI copy

Hardware CPU baseline With GPU
Discrete NVIDIA (RTX 2060+) 5–15 tok/s 40–100+ tok/s (4B Q4); ~10× prompt processing
Discrete AMD (RX 6600+) 5–15 tok/s 35–90 tok/s
Intel iGPU (Iris Xe / Arc iGPU) 5–15 tok/s ~1–2× tokens (sometimes ≈ CPU), 2–4× prompt — shared DDR bounds it; say so honestly
No Vulkan-1.2 driver 5–15 tok/s unchanged (automatic CPU)
Apple Silicon already GPU (Metal) unchanged

(Order-of-magnitude community numbers; the release-acceptance matrix replaces them with measured values before release notes claim anything.)

Profile bump rule: classifyProfile takes a precomputed gpuUseful: boolean = gpuUsefulForProfile(devices): some device has ≥ USABLE_VRAM_MB AND !looksIntegrated(name). Conservative by design — an iGPU reporting 16 GB of shared RAM must never bump a laptop's profile; a false negative only costs a too-small model recommendation. The regex lives in shared/gpu-rules.ts (fixture-tested, covers Windows + RADV APU names, Meteor-Lake Arc and, since #320, the bare Intel(R) Graphics). The floor is 5,120 MiB since 2026-09-07 (issue #321, owner decision; 6,144 before): every 6 GB laptop card the project has measured reports below 6,144 on Vulkan — GTX 1660 SUPER 5,746, RTX 4050 Laptop 5,921, RTX 3060 Laptop 5,994 — so the most common 6 GB configuration was classed cpu and starred a model it cannot accelerate (the 9B measured 18/33 layers at 5.2 tok/s on such a card). Lowering the floor moves the bump one step up on those laptops, which is the accepted cost; 4 GB cards stay out — and since 2026-09-08 they stay out on a RESTATED reason (owner decision on #321, its arithmetic corrected 2026-09-10 by #413): the original "nothing ranked fits a 4 GB card anyway" went void when the E2B's threshold fell to 2,271 MiB, and the floor was KEPT because the E2B is the ONLY ranked model that fits the budget such a card actually produces (≈ 3,328 MiB — its ~4,096 total less the 768 MiB idle reserve measured on every card in the project; the 4B's 3,838 does not fit it), so admitting it would star the smallest model at every RAM size with no 4 GB measurement anywhere in the project to justify the demotion. Closed 2026-09-11 (owner, #413): kept without one. The project owns no 4 GB card, and keeping the floor is the side that corrects itself (a crawl on the RAM pick steps the ★ down, §6.5), while a lowered floor would pin the E2B with no step back up. Reasoning and evidence: model-benchmarks.md §6.6 N8 ("Why 5,120 — RESTATED", "Decided 2026-09-11").

UI: Settings toggle ("Uses your graphics card to speed up responses when available…"), Diagnostics Acceleration + runtime-build lines, compatibility-mode notice + "Try GPU again", benchmark-card GPU row. Since #36 the Chat header also carries a muted model · GPU (name) / model · CPU one-liner (source: the same RuntimeStatus.backend/gpuName, plus a gpuAutoDisabled enrichment in the getRuntimeStatus handler); when CPU comes from the auto-disable latch it reads CPU (compatibility mode) — the persistent, low-key home of the ephemeral fallback notice (the runtime:notice broadcast also re-reads the status so the hint flips mid-session). Never "GPU failed" / "your hardware is bad".

§8.1 Chat/translation contention on one card — NO runtime change (#42, owner decision 2026-09-08)

Two services can want the same card: the resident chat model and the translation sidecar, which launches with VRAM-aware auto-offload (--fit) and takes whatever the chat model left. Whichever starts second gets the leftovers. Two runtime remedies were on the table; both are refused, and the record is why.

  • "Reclaim the card when translation goes idle" — largely EXISTS already. The sidecar unloads about 2 minutes after the last translation, and that teardown is exactly what forces a fresh --fit on the next cold start. Freeing memory mid-session already takes effect at the next start; there is no held allocation to reclaim beyond it.
  • "Force translation to the processor while chat holds the card" — would PESSIMISE every machine where both fit. Measured on a 24 GB RTX 3090 (model-benchmarks.md §11.4): ~13 GB free gives translation a FULL offload at ~75 tok/s, against ~3–4 tok/s forced to the CPU. A rule that trades 75 for 3.5 to avoid a case that only bites when the card is nearly full is a net loss.

The condition is also OBSERVABLE — the Translate screen's device line has covered all five forms since #164 (D-7b), and the "Models on this computer" card carries the start-order warning when both are resident on the card. Correction (#629, 2026-10-07): that held only from #629 on. Until then the sidecar ran at llama-server's default log level, below the verbosity 4 at which the pinned build prints its offload line, so every GPU start fell to the plain "runs on the graphics card" form and the card could never count translation as resident. The refusal above rests on the measurement, not on this sentence, and stands.

What was actually wrong was the COPY. The two starved fact lines stated the symptom and nothing else — "about processor speed" — so a user who read no further had a fact and no action. Both now name the cause on the fact line itself ("the graphics memory was mostly taken, usually by the chat model"), and the remedy line under them (visible text since #161/FE-4, not tooltip-only) is the ACTION alone, so the two no longer say the same thing twice. usually is deliberate: a resident chat model is the common cause, not the only one — another application can hold the card just as well. Keys: translate.device.gpuPartial / gpuNone (cause) and partialTitle / gpuNoneTitle (remedy), in both locales; pinned by TranslateScreen.test.tsx "#42" so neither can regress to symptom-only. Full behaviour: known-limitations.md, "A large resident chat model can starve GPU translation…".

§9 Sharing the card: chat, translation and the reranker (#473, owner rulings 2026-10-12)

Three processes can put a model on the graphics card: the chat runtime, the translation sidecar and the reranker. Before #473 only the reranker checked for room. Phase 0 (four independent fixes, among them #629) and the four rulings below settle the rest; the rulings and the re-check behind them are posted on #473. §8.1's refusal stands: no rule forces translation to the processor while both fit.

The facts it rests on.

  • llama.cpp's --fit sizes a process by the device's free figure and fixes the split at load; a running process is never re-fitted.
  • That figure tracks usage on Linux, so a second process is squeezed. It does not on NVIDIA/Windows (model-benchmarks.md §6.6 finding 2), nor on Apple Silicon: build 11146's ggml_metal_device_get_memory reports total = recommendedMaxWorkingSetSize and free = total minus what the ASKING process allocated, so a separate process never sees ours. There a second process overcommits instead.
  • A translation squeezed into 7 GB of its 7.8 GB need ran at about processor speed (§11.4).
  • A chat model that starts second stays squeezed until it is restarted (the Performance card says so); translation's squeeze ends at its 2-minute idle teardown.
  • Under -np 1 the gap between the probe's free figure and the fit's own reading is 54–154 MiB on the three cards measured (§6.6 finding 1).

Decisions. (1) No --fit-target: translation gets a headroom gate like the reranker's, and the app still passes nothing to llama.cpp's fit (§1, §3). Partial offloads are given up. (2) Priority chat, then translation, then the reranker. (3) The running chat model's share of the card is the measured one when this session has it. (4) Apple Silicon gets no rule of its own.

As built.

  • The translation gate — resolveTranslationDevicePosture (rag/device-posture.ts), consulted per cold start through TranslationGpuDeps.gpuHeadroom, after gpuMode, gpuAutoDisabled and the session latch. GPU ('auto') only if the budget device's free figure minus the chat share holds estimateGraphicsNeedMib of the translation model; otherwise --device none. 'auto', llama.cpp deciding as before, when there is nothing to judge: no stored probe for this machine, no usable discrete card, a locked workspace. 'cpu' while a chat start is in flight, pending, or still in its weight check (startRequested, #599). The translation manifest carries measured host_mapped_weights_mib (787.69) and estimated_context_cache_gib (0.75), so its estimate reads 8,892 MiB against 7,811 measured. gpuOccupied() reports the posture the start in flight CHOSE, since the gate can change mid-start.
  • Chat first — RuntimeManager's beforeStart hook, awaited by every start (Start, a switch, the auto-start, Restart, the crash restarts) after the old runtime stopped and before the spawn, calls Translator.yieldGpu() on a machine whose card the gates share out (cardIsShared: GPU on, a usable discrete device or Apple's Metal pool on record). A Stop or a lock arriving meanwhile cancels the chat start before it spawns (stopRequests), never after a whole load; the "Starting…" clock starts after the hook. yieldGpu waits for a soft kill already under way, leaves a sidecar that put no layers on the card alone, and stops one resident on the card the way #605 stops a hung one (softTeardown): the window in flight fails with an ordinary stream error that both consumers retry once, and the retry cold-starts after the kill — on the processor, because the gate sees the chat start. A GPU cold start already in flight is let finish (at most 30 s, YIELD_START_WAIT_MS) and then stopped, never aborted: an abort reaches a document task as a cancel. The reranker already yields to both (Wave 8; Phase 0's translationGpuYield).
  • The chat share — chatGraphicsShareMib (models.ts), read by both gates: this session's measured placement for the same model and window (weights + KV + recurrent state + compute on the card) plus CHAT_MEASURED_MARGIN_MIB (256); else the estimate with its cache term scaled UP to the launched window; 0 when the chat model runs on the processor.
  • Apple Silicon — by the Metal fact above, both gates already compute "working-set cap minus the chat share", the number a unified-memory rule would; gpu-sharing-gates.test.ts pins it.

Residuals (also in known-limitations.md). Other applications' card use stays invisible on NVIDIA/Windows and Apple Silicon — no gate can see it. The single-process spill (§6.6 finding 8) is untouched; --fit-target stays a candidate for it once its cause is known. A translation moved off the card by a chat start stays on the processor until its idle teardown, even if the card has room once the chat model has loaded. A translation cold start in flight can delay a chat start by up to 30 s. The reranker's load log is still not parsed, so a GPU reranker is assumed fully on the card. Hardware legs still open: two processes on NVIDIA/Windows, AMD/Windows, a Mac.

GPU failure modes (all handled, none block)

Failure What happens
No Vulkan loader / 1.2 driver / RDP session backend lib doesn't load or 0 devices → the default binary runs on its CPU backends; probe shows CPU
Driver enumerates but crashes at model load rung-1 exit → rung 2 (--device none); gpuAutoDisabled persisted once rung 2 (or 3) starts — the CPU control proving the model loads is what makes it a device fault (#312)
A model no rung can load (unsupported architecture, corrupt GGUF, a quantization the pin rejects) every rung exits the same way → nothing persisted, GPU stays enabled for every other model and for translation; the user gets the main.runtime.modelCannotLoad notice naming the model, and the rung-4 mock's disclosed simulated replies (#312). The same with acceleration off or auto-disabled (no GPU rung to compare against). The model is then latched for the session: its next start pays no health timeout — notice + mock at once — until "Verify checksum", a re-download, an engine install or a restart re-arms it (#372)
Driver hangs (never healthy) 180 s (3 min) health timeout (DEFAULT_HEALTH_TIMEOUT_MS; the chat runtime never overrides it) → rung 2; cost = one slow first start, then never again (flag persisted)
Driver crash mid-generation / VRAM stolen mid-run §5.3 auto-restart at CPU + friendly notice; next message works
VRAM too small at load upstream --fit partial offload — no special casing
Vulkan present but slower than CPU (weak iGPU) no crash; honest §8 copy; Settings toggle exists; no auto-benchmark in v1
Rungs 1–2 both fail (binary-level breakage) rung 3 pure-CPU build
The OS refuses the program (a missing system library like libgomp.so.1, a system too old, the Visual C++ runtime missing, Smart App Control) EngineCannotRunError on every rung it hits → neither verdict: nothing persisted, nothing latched, the probe answers unknown; the session verdict drives the AI Model banner and main.runtime.engineCannotRun; Check again or a restart heals it (#530, "Engine load failures — design record")
Stale flag after a driver upgrade "Try GPU again" (re-probes, clears flags)

Release acceptance: the manual 9-machine hardware matrix lives in BUILD_STATE §5 (item 1b — canonical); the fake-spawn unit tests cover the logic, the matrix covers the drivers. Machine ① (dev box, RTX 3080 Ti) passed end-to-end 2026-06-10 via tests/manual/gpu-smoke.test.ts (HILBERTRAUM_GPU_SMOKE; CI never runs it).

History: Phases 14–16 = commits f1dcf34, 9067b89, 2d4adb7 (2026-06-10); the GPU audit round = commit 4549934 (same day; full finding list in BUILD_STATE §3 "GPU audit round"); the full original plan: git show 4549934:docs/gpu-support-plan.md.

Engine load failures — design record (#530, 2026-10-01)

An engine program is on the drive, passes the pre-spawn hash check, and the operating system's loader still refuses to start it. Before #530 nothing recognised that; the app blamed the GPU, the model, memory or the archive instead. Code cites this record as "Engine load failures".

§1 The facts it rests on (measured 2026-10-01)

  • Linux. The pinned llama.cpp b11146 Linux builds (ubuntu-x64, ubuntu-vulkan-x64) and whisper.cpp b5130 all link GCC's OpenMP runtime libgomp.so.1; none bundles it. In stock Ubuntu 22.04 and 24.04 containers, without libgomp1, every one of them exits 127 with one stderr line: <abs path>: error while loading shared libraries: libgomp.so.1: cannot open shared object file: No such file or directory. Desktop images do ship libgomp1 (Ubuntu Desktop 22.04.5, 24.04.3/.4 and Debian 13.7 live; owner comment on #530).
  • The real floor is set by the binaries, read with objdump/readelf: glibc ≥ 2.34, libstdc++ with GLIBCXX_3.4.30 (GCC 12), OpenSSL 3 for llama-server, libvulkan.so.1 for the GPU path only. That is roughly Ubuntu 22.04+, Debian 12+ and Fedora 36+.
  • ld.so names only the first missing library. Ubuntu 20.04 reports libssl.so.3, never libgomp.so.1. A "too old" system fails differently: version 'GLIBC_2.34' not found, one line per missing version, with exit 1, not 127. So the classifier reads the text; the exit code decides nothing on Linux.
  • libvulkan is not a load failure. The Vulkan backend is loaded with dlopen (GGML_BACKEND_DL). Without libvulkan1 the program starts, --list-devices prints (none), and the CPU path works. That is the existing "No Vulkan loader" row of the failure-modes table above.
  • kiwix-serve is static ("not a dynamic executable") and is immune on Linux.
  • Windows. A missing DLL exits 3221225781 (0xC0000135) and a mismatched DLL exits 3221225785 (0xC0000139). In both cases there is no stderr, the exit comes about 20 ms after the spawn, and no dialog appears, with or without windowsHide (Node 24). A Smart App Control block was seen on the dev box as 0xC0E90002 (2026-09-04).
  • Every Windows engine imports the Visual C++ runtime. The llama.cpp, whisper.cpp and kiwix-tools builds all import msvcp140.dll, vcruntime140.dll and vcruntime140_1.dll, and no drive folder carries them. A PC without the Visual C++ 2015–2022 Redistributable (x64) is the Windows twin of Linux without libgomp. Whether stock Windows images carry it is unmeasured.
  • macOS (not measured): dyld writes Library not loaded: or Symbol not found: and aborts (SIGABRT).
  • Node's view. On Linux stderr arrived before 'exit' in 40 of 40 measured runs, but Node does not guarantee that order. The GPU probe already waited for 'close'; LlamaServer read the tail on 'exit'. A piped stream can also emit an 'error' of its own, beside the child's: §12 (#790).

§2 Decisions (owner, 2026-10-01)

  1. No bundling. libgomp is not bundled. Bundling is reopened only if real users report the problem; the facts for that case (which copy, where it would live, the licence) are kept on the #530 comment. The Visual C++ runtime is reported, documented and not bundled; bundling it is its own decision.
  2. Detect in both places, with one classifier (option C).
    • Every spawn site classifies its own failure, so no consumer misattributes it.
    • A session verdict feeds the UI before anything fails, and gives one place to heal.
    • A central check alone would fix the message but not the damage: the GPU flag, the model latch, and the stored drive path.
  3. OS scope. Linux is measured end to end. The Windows exit codes are mapped, with a real-app check on the dev box. macOS dyld is classified on its documented wording. Knowledge packs (kiwix) are out of scope (known-limitations).
  4. The verdict is never persisted, and is never a GPU or model verdict. It heals on restart and on Check again. There is no automatic re-check on window focus.
  5. State written before #530 heals at unlock. A gpuAutoDisabled whose gpuLastError classifies as a load refusal is cleared, and failed document rows lose the raw loader line. Audit rows that already hold a path are left as they are (append-only, local); new code writes none.
  6. Copy. The UI names the library and the package (libgomp1 / libgomp). The shell command lives in troubleshooting.md only, and the exit code in Diagnostics only (guidelines §7).

§3 The classifier (runtime/engine-load.ts, pure)

classifyLoadFailure({ exitCode, signal, stderr, platform, systemDllExists }) returns a LoadFailure (reason, os, an optional file or version name, never a path, and the exit string for Diagnostics), or null for every failure that is not the loader's. A null keeps the caller's old handling byte for byte.

Evidence Reason
error while loading shared libraries: <lib>: with a system library library-missing (name = the soname)
… libssl.so.3 / libcrypto.so.3 (in every supported base image, so its absence means a pre-2022 system) system-too-old
… a library the engine ships (lib(llama|ggml|mtmd|whisper)…) files-damaged
version 'GLIBC_x' / 'GLIBCXX_x' / 'CXXABI_x' not found system-too-old
symbol lookup error: <engine lib>: … undefined symbol: X files-damaged (a SYSTEM library — a mismatched Mesa driver — is null: the #312 device logic decides)
dyld Library not loaded: @rpath/… (or an engine dylib) files-damaged
dyld Library not loaded: /usr/lib/…, Symbol not found (expected in a system lib), newer than running OS system-too-old
exit 0xC0000135 / 0xC0000139 / 0xC000007B with a VC++ DLL absent from %SystemRoot%\System32 vc-runtime-missing (name = that DLL)
… with all three present files-damaged
exit 0xC0E90002 blocked (code integrity / Smart App Control)
Windows spawn error EPERM / UNKNOWN / EACCES (classifySpawnError — policy, security software, quarantine); only an error of the spawn (syscall spawn…), never a failed kill() the child's 'error' event also reports (#658 review) blocked

classifyLoadFailureMessage applies the same classifier to a stored message (the exited before becoming healthy (code N) shape), for the heal.

§4 The spawn sites

LlamaServer covers chat, the embedder, the reranker, vision and translation.

  • On an early 'exit' it waits up to 100 ms for 'close' (STDERR_DRAIN_MS) before reading the tail.
  • On a load refusal it logs the raw tail once (local log, path included), reports the verdict, and throws EngineCannotRunError with a path-free message.
  • A spawn error, synchronous (EPERM, spawn UNKNOWN — Node throws those) or async, is a refusal on Windows (classifySpawnError → blocked). Otherwise it keeps the failed to launch shape, now path-free (spawn EACCES; Node's message carried the absolute path into document rows).
    • Review fix: the bare launch signature matched on every rung, so a Windows block had moved from "blame the GPU" to "blame the model".
  • A healthy start of a program that REPORTED the verdict clears it (clearEngineProblemFor): an intermittent block that went away, or a library installed since. The store keeps every reporting program, not only the last one (#655, §9). The cpu/ safety net clears it only as the latest reporter: it starts only after the main build failed, usually by a refusal that still stands. A program that never reported does not clear it: a Windows Kit's cpu/ build starting beside a damaged main folder, or the main build beside a verdict only cpu/ reported. The clear heals the consumers (§5, #654).

The GPU probe (gpu.ts) pipes stderr. A refusal resolves null, the #380 unknown: not cached, not persisted. It also reports the verdict. Before #530 it was cached and persisted as "no graphics card". Since #653 a probe that crashed or could not be spawned for another reason resolves null too, but records no verdict: the engine ran (or may run a moment later), so nothing tells the user it cannot (GPU record §5.2 "#653 amendment").

whisper-cli (transcriber/cli.ts) classifies on 'close' and throws the typed error for the whisper_cpp family. The signal branch now keeps the stderr tail, and the spawn passes windowsHide. A spawn error is classified whether Node throws it or emits it (#658, §9).

Consumers:

  • Chat ladder. A refused rung is never held as a GPU verdict and never sets the #312 control signature; the walk continues. If every rung was refused, onEngineCannotRun fires instead of onGpuFailure or blameModel: nothing is persisted, nothing is latched, and the user gets main.runtime.engineCannotRun (button: Go to AI Model), then the rung-4 mock. A Windows Kit's cpu/ build can still start beside a damaged main folder; it then runs on CPU without gpuAutoDisabled.
  • Embedder. Still latches, so a refused engine is not respawned on every import. Ingestion stores the canonical, display-mapped text: main.ingest.engineLibraryMissing (interpolated {library}) or main.ingest.engineCannotRun. A document question maps the error to main.engine.cannotRun. #634 gives the search model's other failures (a timeout, a damaged weight file, a crash) the same treatment by kind: rag-design.md §12.4 "#634 amendment".
  • Reranker and translation. No GPU-fallback latch, no CPU retry; they latch. Translation reports engineCannotRun instead of the "free memory" copy.
  • Vision. Reports engineCannotRun (it used to say "pick another model") and repeats it through its 5 s cooldown.
  • Dictation and audio import. The voice-engine copy (main.dictation.engineCannotRun, main.ingest.voiceEngineCannotRun). The four dictation refusals, previously English-only literals, are now catalog keys.

§5 The session verdict

The store (engine-load.ts, module-level, the modelLoadLatched idiom) holds one EngineProblem per family (llama_cpp, whisper_cpp).

  • Fed by every classified spawn, and by the startup check: startEngineCheck runs the session's cached GPU probe at app start, before any unlock. This costs no extra spawn on a healthy machine, because the post-unlock refresh and the ladder read the same cache. Before #530 a never-benchmarked drive did not probe at startup at all.
  • Read by AppStatus.engineProblems (chat engine first). The payload-free engine:problemsChanged push, sent on a new, different or cleared verdict, makes mounted screens re-read it.
  • Dropped with a cause (#654, §9): started (a reporting program started: a healthy start, the probe answering), rechecked (Check again found it loads), installed (a new copy replaced it) or gone (it left the drive). rearmWhenChatEngineHeals, subscribed once in main/index.ts, heals a chat-engine started drop the way Check again heals its own: it re-arms the consumers and, when a model answers from the demo runtime, re-runs and persists the probe and then restarts it.

Check again (engine:recheck, ipc/engine-recheck.ts) re-starts each family with a verdict.

  • Each engine gets an explicit spawn (checkProgramLoads): llama-server --version and whisper-cli --help. The chat engine's program is the main build, unless only its cpu/ net reported the verdict: then the cpu/ build is checked (#678, §11).
    • Review fix: the chat engine first re-used the probe, but the probe answers [] for a binary it could not even run (a failed integrity check, a spawn error). That read as "loads".
    • unchecked keeps the verdict.
  • Single flight. The chat banner and the voice hint can both be on screen, and a second click joins the running pass.
  • A program the OS now accepts loses its verdict and is re-armed:
    • rearmLlamaConsumers clears the #372 model latches, the embedder's and reranker's startFailed, the vision cooldown and a latched translator slot;
    • the heal below runs;
    • the probe is invalidated, re-run and persisted for this computer;
    • a selected model standing in on the mock is restarted on the real engine (an active deep-index build is aborted first, like every IPC start path).
  • A program that has left the drive just loses its verdict, with no re-arm.

The engine install hook now runs the same rearmLlamaConsumers and clears the family's verdict. Before #530 it re-armed the model latches only, so a repaired engine still failed every import until a lock/unlock. It re-arms itself, verdict or not; its installed drop heals nothing more.

The heal (healEngineLoadState) runs at every session start (plaintext startup, unlock, create), before the auto-start reads the GPU flags. It clears a loader-caused gpuAutoDisabled together with its gpuLastError. That flag has no machine stamp, so it would otherwise have followed the drive to every computer. It also rewrites failed rows still holding the raw line (rewriteEngineFailureRows). Both steps are idempotent and admission-gated. #634 adds a third after them, for rows holding the search model's raw failure (rewriteSearchModelFailureRows, rag-design.md §12.4 "#634 amendment"); a row this classifier claims keeps #530's text.

§6 Surfaces

Design record: design-guidelines.md §11.17.

  • AI Model screen. A warning banner in the missing-engine banner's place (title, reason sentence, demo note, Check again). The voice engine gets a quiet hint under the speech-model card.
  • Home. The model row says the engine can't run, and the hero's primary becomes Go to AI Model. A demo runtime is no longer reported as "running".
    • Gated on the demo runtime: while a REAL runtime answers (a cpu/ build), Home keeps its running row, and the AI Model banner drops its demo note (demoNote). The banner itself stays, because the main binary still fails the other features.
  • Chat. The runtime notice, which the App drops once the chat verdict clears.
  • Diagnostics. One line per engine, with the library and the exit code, also in the Copy report.
  • Performance. The graphics tile says the card could not be checked, instead of "No usable graphics card".
  • Documents, Translate, Images, dictation. Their own short engine copy.

§7 Not built / residual

  • Knowledge packs keep their old wording for a Windows VC++ refusal (out of scope; kiwix is static on Linux and macOS).
  • No reinstall button for a present-but-broken engine — built by #532 (§8 below). #516's update offer can reuse its mechanism.
  • macOS classification is unmeasured on hardware.
  • The Windows VC++ check is presence-only. An outdated Redistributable whose DLLs are present reads as damaged engine files; the troubleshooting entry covers both causes.
  • Audit rows written before #530 keep their raw reason.

Tests: engine-load.test.ts (the classifier on the measured strings, the store), engine-load-spawn.test.ts (LlamaServer, the probe), runtime-ladder.test.ts "#530", engine-health.test.ts, engine-recheck.test.ts, engine-consent-ipc.test.ts, core-model-ipc.test.ts, the consumer files ("#530" blocks) and tests/renderer/EngineProblem.test.tsx.

Real-app verification (2026-10-01; the built app over CDP, scripts kept out of the repo).

Linux. This branch's app ran under the Linux Electron 43.4.0 in a stock ubuntu:24.04 container without libgomp1, on a drive laid out like a prepared Kit: the pinned b11146 Vulkan build plus the cpu/ net, with a dummy chat and embedder model.

  • The startup check reported library-missing libgomp.so.1 (exit code 127) before anything ran.
  • A model start was refused on all three rungs, and the engine notice fired with gpuAutoDisabled false and gpuLastError null. Before the fix this was the "GPU blamed" defect.
  • An import failed with the interpolated libgomp.so.1 row text. Diagnostics read "Can't run — a system library is missing (libgomp.so.1, exit code 127)".
  • Check again first answered "still can't start". After apt-get install libgomp1 in the running container, a second Check again cleared the verdict without a restart, showed the toast, and restarted the model on the real engine.

Windows (dev box). llama-server.exe sat alone in the engine folder, so exit 0xC0000135 followed, with the Visual C++ runtime present, giving files-damaged. The same legs ran in English and German, in light and dark.

The review found two things, both fixed: the stale engine notice after a heal, and the voice-engine banner contradicting the chat banner.

§8 #532 amendment — "Install the AI engine again" (2026-10-05)

The gap. For files-damaged (a library the engine ships is missing or broken) the banner could only point to the troubleshooting guide: quit, delete runtime/llama.cpp/<os> by hand, restart, install. Three things blocked an in-app repair:

  • engineStatus counts a family as installed when its binary exists, so no button appeared;
  • start() skips every family whose marker is current, so the job failed with "already installed";
  • chatEngineInUse counted the demo runtime as a running model, so the job was refused with "stop the model first". The demo runtime never executes the engine folder, and it is exactly what answers while the engine is refused. This was CODE-13's registered polish candidate (§47), and it also refused a FIRST install while a model answered in demo mode.

Owner decisions (2026-10-05).

  1. Offline Kits: with downloads forbidden by the drive policy, the button shows disabled with the policy reason and the reason sentence keeps the troubleshooting pointer. An offline repair path belongs to the signed update bundles (Phase 22, BUILD_STATE §5 item 3).
  2. Main build only. The reinstall re-fetches the default build; the pre-clean keeps cpu/ as it always has. The in-app installer never installs cpu/, even on a first install, and the startup check probes the main binary. Amended by #678 (§11): the reinstall replaces the builds the OS refused, the cpu/ net included; a first install still never fetches cpu/. Amended by #986 ("In-app engine updates" §6): there is no pre-clean any more; the main build's swap carries cpu/ from the replaced copy into the new one.
  3. The voice engine gets the same action, on its quiet hint (§11.17 decision 5).
  4. One click, like the existing "Install AI engine" button. The drive's copy is replaced only after the new archive downloaded and matched its pinned SHA-256; a cancelled or failed download leaves it as it was.

As built.

  • Request: downloadEngine({ families, reinstall: true }). parseEngineDownloadRequest requires an explicit list of REQUIRED families and a real boolean. The IPC handler then admits it only for families that hold a files-damaged verdict this session (repairable), else main.engine.nothingToRepair. EngineDownloadManager.start installs the named families whether or not they are current; a named family with no build here is main.engine.noHostBuild. Everything else is the ordinary flow: the gates, download, SHA-256 verify, pre-clean (keeps cpu/), extract, marker, verifier cache invalidation. Since #986 ("In-app engine updates" §6) the ordinary flow is a staged swap: extract, check and mark in <os>.new/, then swap it in and carry cpu/ over; a failed reinstall leaves the damaged copy as it was.
  • Status and job: EngineStatus.reinstallableFamilies lists the required families that are on the drive and have a build here. EngineDownloadJob.families and .reinstall let the screen attribute a job's progress to the surface that started it (data-contracts.md).
  • Demo runtime: chatEngineInUse is startingModelId != null || (activeModelId() !== null && status().backend !== 'mock'). A start in flight still counts: its ladder spawns the real binary.
  • After the install (onInstalled, which now also receives each family's installed program path):
    • engineInstalled(family, binPath) drops the verdict and remembers the fresh program for the session;
    • the llama consumers are re-armed and the probe refresh runs, as before;
    • then restartChatOnRealEngine (exported from engine-recheck.ts; it now skips while a start is in flight) brings a model the demo runtime stands in for back on the engine. This applies to a first install too.
  • A fresh copy that still fails. A later files-damaged report about THAT program is stored with EngineProblem.afterInstall: true. Other reasons are stored as they are, and so is a report about another program of the family (the cpu/ net) on its own. Since #670 (§10), a cpu/ refusal that follows the fresh copy's keeps the mark; since #678 (§11), a cpu/ copy the reinstall replaced is a fresh copy itself. The banner then says the files are probably not the cause, points Windows users to the Visual C++ Redistributable (the presence-only check in §7), and offers no second reinstall. Diagnostics says "reported damaged right after a fresh install".
  • Renderer: EngineProblemNotice takes an optional reinstall slot. ModelsScreen fills it from engineJobControls, the progress, Cancel, error and gate controls shared with the install banners. The slot is filled only for engineProblemOffersReinstall (damaged files, not afterInstall) and for a family in reinstallableFamilies. Check again is disabled while the reinstall runs, and a toast confirms a finished one. The chat engine's banner suppresses the deep-link scroll (the "Voice dictation" #539 amendment).

Real-app verification (2026-10-05, DesktopDiT, GTX 1070 Ti, dev build, scratch drive root; the E: stick was only read).

  • With the engine missing and the 4B model answering in demo mode, the argument-less install was admitted. The model then restarted on its own at rung 1 (GPU).
  • With llama.dll removed (llama-server.exe exits 0xC0000135, no stderr), the startup check reported files-damaged. The German banner offered "KI-Engine neu installieren" with "Erneut prüfen" beside it. One click showed the progress in the banner, with Check again disabled; the verdict cleared, the toast appeared, the DLL was back and the model restarted on the GPU.
  • With the fresh copy damaged again, the verdict carried afterInstall. The banner showed the Windows Visual C++ sentence and only Check again, and Diagnostics showed the after-install phrase. Restoring the DLL and choosing Check again healed it ("Die KI-Engine läuft wieder.").
  • English, light and dark: with Allow internet access off, the button was disabled and the Settings reason wrapped below both buttons. The first cut kept it beside them: .hint's max-width capped a 100 % flex-basis, so a zero-height break item now forces the line.

Residuals.

  • The screen's runtime poll runs only while it sees a start in flight. A restart that begins after its post-job refresh (a slow probe refresh) leaves the card on its earlier "running" until the next refresh. #530's Check again restart has the same limit.
  • While a REAL runtime answers from the cpu/ net beside a damaged main folder, the reinstall is still refused with "stop the model first": the status cannot tell rung 3 from rung 2.
  • A model started while a reinstall is in flight can still race the pre-clean (CODE-13's registered residual) — closed by #516: every job now downloads and verifies all its archives before touching the installed folder, and holds the family's spawns from then until the last marker (the spawn gate, "In-app engine updates" §3).
  • A verdict about the cpu/ binary is repaired by re-fetching the main build, which does not touch cpu/ (decision 2). Fixed by #678 (§11).

Tests: engine-consent-ipc.test.ts "#532" (the repair through the real handler and manager, the verdict gate, the demo-runtime install and restart, the payload rows), engine-download.test.ts (the chatEngineInUse table), engine-load.test.ts (the afterInstall store rules), EngineProblem.test.tsx "Install the engine again (#532)" (offer, order, progress, toast, the gate rows, no offer, the voice hint and its attribution, the Diagnostics line) and ModelsScreen.test.tsx (the deep-link rows).

§9 #654 / #655 / #658 amendment — the verdict heals on a healthy start (2026-10-13)

The gaps (found by the runtime-ladder and sidecar-services test campaigns, reproduced on the real app):

  • #655. The store kept only the LAST reporting program. On a Kit the probe and rungs 1–2 (main build) report, then rung 3 (cpu/). Once the fix was in, the main build ran on the graphics card, but its healthy start matched nothing, so the banner and the Performance tile's "could not be checked" stayed until Check again. That contradicted §4.
  • #654. A healthy start or an answering probe dropped the verdict but re-armed no consumer. Only Check again and the install hook did. The banner went away while every import kept failing on the embedder's latch ("The AI engine can't run on this computer"). The reranker stayed latched until a restart. That contradicted §5.
  • #658. Node throws EPERM and UNKNOWN from spawn() instead of emitting 'error'. The whisper-cli spawn had no try, so a policy or security-software refusal never became a verdict. Dictation read "could not be transcribed", and an import stored the generic failure.

Owner calls (2026-10-13; the first posted on #654).

  1. Whenever the chat-engine verdict is dropped, the consumers are re-armed, whichever path drops it.
  2. Not on gone: the binary left the drive, nothing was healed, and a consumer re-armed against a missing binary only fails again.
  3. From the review: a healthy start that heals the engine also restarts a model the demo runtime stands in for. Check again and an install already did. Without it, an import that was the first engine start after the repair left the chat in demo mode with no banner to bring it back.
  4. From the review: cpu/ clears the verdict only as the latest reporter. "Any reporter clears" let a healthy cpu/ start on the next ladder walk drop a verdict the main build had just re-reported, hiding a still-damaged main build and its #532 reinstall offer.

As built.

  • The store (engine-load.ts):
    • StoredProblem.reporters holds every program that reported since the verdict was recorded. The shown problem is the latest report, so the #532 afterInstall rule is unchanged (#670 later kept the mark across reporters, §10).
    • clearEngineProblemFor clears when the healthy program is a reporter. The cpu/ net (runtime/llama.cpp/<os>/cpu/) must also be the latest one (lastReporter).
    • reportEngineProblem's program is required; every production reporter passed it already.
    • clearEngineProblem(family, why) tells onEngineProblemDropped listeners why the verdict went: started, rechecked, installed or gone. A listener that throws is caught. It returns whether there was a verdict to drop.
  • The heal.
    • rearmWhenChatEngineHeals(ctx) (engine-recheck.ts, subscribed once in main/index.ts) answers a llama_cpp started drop. It re-arms the consumers. Then, only if a model answers from the demo runtime with no start in flight, it re-runs and persists the probe (reprobeGpu) and runs restartChatOnRealEngine in the background. The refused probes persisted nothing, and the ladder must read this computer's answer (#380).
    • The chat's own healthy start, the usual trigger, therefore neither restarts nor probes beside its weight upload (#473).
    • The other drops heal where they happen, each once and in its own order. Check again (rechecked) re-arms, heals, re-probes and then restarts. It does all that only for a verdict it dropped itself: a healthy start that landed during the check has already healed it. The install hook (installed) re-arms with or without a verdict, then refreshes the probe and restarts. gone heals nothing.
    • The re-arm spawns nothing, so it cannot report into the store while the store notifies.
    • A consumer start in flight is not latched yet; if that start was refused, it re-latches and re-reports, which is true.
    • The #372 model latches are re-armed too (owner call 1). A model with a real GGUF fault walks its ladder once more after the heal and latches again.
  • whisper-cli (transcriber/cli.ts): the spawn is wrapped. A thrown error and the 'error' event share spawnFailure (classify, log, verdict, EngineCannotRunError). A cancelled call, or one on a stopped transcriber (quit), spawns nothing. That is checked before the #516 gate and the hash, and again after them: a stop() that lands while the call waits finds nothing in active to kill. classifySpawnError now reads only errors of the spawn. Before, a failed kill() on a cancel would have recorded a false "Windows refused to start it".
  • Residuals.
    • A chat on the cpu/ net (rung 3) stays there after the heal. The status cannot tell rung 3 from rung 2 (§8), and rung 2 is also compatibility mode after a GPU fault, so only the demo runtime is restarted.
    • The heal's restart is a chat start. On a shared card it takes the card from a translation that started on it (#473 Phase 1, "a chat start takes the card first"), as Check again's restart did.
    • Unchanged from #532: on a Kit, a cpu/ refusal after a reinstall replaces the main build's afterInstall verdict, so the reinstall is offered again (#670). Fixed by #670 (§10).

Real-app verification (2026-10-13, DesktopDiT, GTX 1070 Ti, dev build, scratch drive roots; D: was only read).

  • #654, the main build only: llama.dll was removed, giving a startup files-damaged and a failed import. With the DLL restored, the 4B started on the GPU and the verdict cleared.
    • Master: the next import still failed with the engine copy.
    • The fix: it was indexed.
  • #655, a Kit with cpu/, both DLLs removed. The main build reported from the probe, an import and rungs 1–2, then rung 3 reported from cpu/. With the DLLs restored, the 4B ran on the GPU.
    • Master: the banner with its demo note and the "answers are simulated" notice stayed, and the import failed.
    • The fix: both cleared and the import was indexed. No Check again and no restart in either case.
  • Review F1, the main build only, llama.dll removed. The chat start ended on the demo runtime. With the DLL restored, an import was the first engine start: it was indexed and the verdict cleared.
    • Master: 120 s later the chat was still in demo mode, with no banner.
    • The fix: the 4B was back on the GPU 4.1 s after the import, with one restart logged. The probe (the 1070 Ti, 7,490 MiB free) was persisted 1 ms before that restart. The legs above logged no restart: there the healthy start was the chat's own.
  • #658, a stand-in whisper-cli.exe with a deny-execute ACL. Node 24.13 throws spawn EPERM synchronously. Smart App Control is off on this box, so the ACL stands in for it at the same Node boundary.
    • Master: dictation said "could not be transcribed", the import stored the generic failure, and no verdict was recorded.
    • The fix: dictation said the voice engine can't run, the verdict was whisper_cpp blocked (spawn error EPERM), the import stored the voice-engine copy, and the speech-model card showed the hint.

Tests:

  • engine-load-spawn.test.ts "a healthy start: …": the #655 table, which includes the cpu/ rule and the never-reporter rule.

  • engine-recheck.test.ts "#654" covers:

    • the re-arm plus restart;
    • the probe re-run before that restart;
    • the chat's own start, which neither probes nor restarts;
    • a healthy start during Check again, healed once;
    • a voice-engine heal that touches nothing of the chat engine.

    Its fake context subscribes as main/index.ts does, so the gone row and Check again's exactly-once counts guard the other causes.

  • engine-load.test.ts: a throwing drop listener, and a failed kill that classifySpawnError does not read as a refusal.

  • transcriber.test.ts: the thrown refusal, the clean-run heal, the pre-aborted call, and the stop/cancel and already-cancelled rows at the #516 gate.

§10 #670 amendment — a fresh copy's refusal outlives the cpu/ net's (2026-10-13)

The gap (found by the review of #655, §9 residual). The store took afterInstall from the latest report alone, and the latest report is the one the screens show. On a Kit, after "Install the AI engine again":

  • the ladder's rungs 1–2 refuse the fresh main build, and that report is marked;
  • rung 3 then refuses the cpu/ net, which the reinstall left as it was (§8 decision 2). The cause that refuses a fresh, verified copy while every system DLL is present (an outdated Visual C++ Redistributable, §7) refuses cpu/ too, and its unmarked report replaced the marked one;
  • the banner offered the reinstall again, with the damaged-files sentence instead of the Visual C++ one: the loop #532 closed. Each walk flipped the verdict twice (two engine:problemsChanged pushes).

Decision (the issue's first option). The mark belongs to the verdict. Once the fresh copy was refused as damaged, every later damaged-files report of that verdict carries afterInstall, whichever program it is about. A reinstall cannot help either program: it replaces only the copy that was just shown not to be the cause, and it never touches cpu/.

  • The second option, offering the reinstall only while the main build had reported without the mark, fixes the offer only. The banner would still show the damaged-files sentence, and EngineProblem would need a new field.

As built (engine-load.ts). StoredProblem.freshCopyDamaged:

  • is set by a files-damaged report of the program engineInstalled remembered;
  • is inherited by every later report of the verdict;
  • goes with the verdict, on any drop and on a new install.

EngineProblem, the IPC and the renderer are unchanged.

  • A cpu/ refusal before the fresh copy's, or after a drop, is still stored as it is.
  • A report with another reason is shown as it is. The mark returns with the next damaged-files report.

Real-app verification (2026-10-13, DesktopDiT, dev build). Scratch Kit roots held the pinned b11146 main build and its cpu/ net; D: was not touched.

  • With llama.dll removed from both builds, the startup check reported the main build as files-damaged, and the app reinstalled it: download, SHA-256 check, a pre-clean that kept cpu/.
  • Then the fresh copy's llama.dll was removed as well. It exits 0xC0000135 while the system DLLs are present, so it is files-damaged. An outdated runtime's missing entry point exits 0xC0000139 and gets the same verdict (§3).
  • A chat start was refused on rungs 1 and 2 (the fresh copy) and on rung 3 (cpu/), in that order.
    • Master: the verdict had no afterInstall. The German banner offered "KI-Engine neu installieren" again, with the reinstall sentence.
    • The fix: afterInstall: true. The banner showed the Visual C++ sentence and only "Erneut prüfen".

Residuals.

  • A verdict that only cpu/ reported still offers a reinstall that does not touch cpu/ (§8). Fixed by #678 (§11).
  • The mark lasts for the session, like the verdict. After an app restart, the first refusal offers the reinstall once more (freshlyInstalled, §8).
  • The handler's repairable check reads only the reason, so it would admit a reinstall request for a marked verdict. The screen does not offer one. Fixed by #678 (§11).

Tests: engine-load.test.ts "#670" covers the walk orders, the push count, a refusal for another reason in between, and the drop.

§11 #678 amendment — the reinstall replaces what the OS refused, the cpu/ net included (2026-10-14)

The gap (a recorded residual since #532, §8 decision 2 and §10). On a Kit the ladder reaches the cpu/ net (rung 3) only after the main build's rungs 1–2 failed, and they can fail for a reason that is not the loader's: a damaged weight file dies the same way on both rungs, so #312/#372 blame the model. If the cpu/ net is then refused as files-damaged, the verdict is the cpu/ net's alone, and the main build runs fine. Four things went wrong with such a verdict:

  • the banner offered "Install the AI engine again", which re-fetched the main build only. The install hook re-armed the model latches, its restart walked to rung 3 again, and the same verdict and offer came back: the loop #532 and #670 closed for the main build;
  • with an import done, the embedder runs from the healthy main build and stays up, so the reinstall was refused outright: "can't be replaced while a model is running", although only the demo runtime answered;
  • Check again checked the main build. It loads, so the verdict was dropped with the "runs again" toast, and the restart's walk brought it back;
  • the IPC repairable gate read only the reason, so it admitted a request for an afterInstall verdict (§10).

Decision (the issue's first option; an owner call taken as the issue recommended it). "Install the AI engine again" repairs what the OS refused: the main build when the main build reported the verdict, the cpu/ net when the cpu/ net did, both when both did. This reverses §8 decision 2, which predates #516's cpu/ install path, but only for a cpu/ net the OS refused. The second option, offering no reinstall for a verdict only cpu/ reported, stops the loop but leaves the drive damaged, and needs a new EngineProblem field. The troubleshooting path it would point to (delete the engine folder, install again in the app) would lose the cpu/ net entirely, because a first install never fetches it.

As built.

  • The store (engine-load.ts): engineProblemBuilds(family) answers { main, cpuNet } from the verdict's reporters (§9), by the same cpu/ path test the clear rule uses. freshlyInstalled holds every program this session's installs put on the drive (engineInstalled(family, binPaths) takes a list and adds it, so a later cpu/-only install leaves the main build fresh), and a fresh cpu/ copy refused as damaged is marked afterInstall like a fresh main build (§8, §10).
  • The IPC gate (registerEngineIpc.ts): repairable applies the renderer's own engineProblemOffersReinstall (damaged files, not afterInstall), and the reinstall passes the refused builds to the manager (reinstallBuilds).
  • The manager (runtime-download.ts): a reinstall takes each named family's main build and/or its cpu/ net plan (#516's EnginePlan.cpuNet, an InstallStep with main: false). The cpu/ net is replaced even if its program has gone since it was refused (a failed earlier attempt). A refused cpu/ net this host's pin has no build for (a main folder provisioned as the processor build over an older Kit's cpu/) is skipped; a job left with nothing is main.engine.noHostBuild. Everything else is the ordinary flow: download, SHA-256, spawn gate, pre-clean, extract, marker.
  • The in-use guard, per build. The helpers (embedder, reranker, vision, translation) run the main build only, and only the chat ladder's rung 3 runs the cpu/ net. A job that replaces only the cpu/ net is therefore refused for a real chat runtime alone, which can be on rung 3 (the status cannot tell, §8), never for a helper.
  • onInstalled reports every program a job put on the drive per family, main build first. A #516 update that replaced the cpu/ net marks it fresh too. A job that stops part-way reports what it replaced, a cpu/ net alone included (#516 reported only a replaced main build).
  • Check again (engine-recheck.ts) checks the cpu/ build (resolveCpuFallbackServerPath) when the cpu/ net is the verdict's only reporter, and the main build otherwise. That matches §9's clear rule, under which a main build that reported clears the verdict whatever reported after it.
  • No contract change: the request ({ families, reinstall: true }), the job, EngineProblem and the renderer are as they were. The banner sentence ("Some of its files on this drive are missing or damaged") fits the cpu/ net as well.

Real-app verification (2026-10-14, DesktopDiT, GTX 1070 Ti, dev build, scratch Kit roots; D: and E: were not touched). Each root held the pinned b11146 main build (healthy) and its cpu/ net without llama.dll, plus a 4B weight cut to its first 300 MB (a manifest copy with a placeholder hash lets a dev build start it). A chat start died of the model on rungs 1–2 ("konnte auf diesem Computer nicht geladen werden") and was refused on rung 3: files-damaged, exit 0xC0000135, the cpu/ net alone. The banner offered "KI-Engine neu installieren" on both builds.

  • Check again. Master answered no verdict and logged "the operating system now starts it"; the restart's walk brought the verdict back about a second later. The fix kept the verdict (the cpu/ build was checked and still refused) and restarted nothing.
  • An import, then the reinstall. The e5 embedder ran from the main build. Master refused the reinstall with "Die KI-Engine kann nicht ersetzt werden, während ein Modell läuft". The fix admitted it while the embedder kept running, fetched llama_cpp:win/x64/cpu only (the main marker untouched, the cpu/ marker rewritten, llama.dll back), and the walk after it ran the fresh cpu/ build, which died of the model (code 1). There was no verdict and no banner; the model's own notice stayed.
  • The reinstall, nothing else running. Master re-fetched the main build (its marker rewritten, cpu/ still without llama.dll), and the hook's restart brought the verdict and the offer back: the issue's loop. The fix replaced the cpu/ net, as above.
  • The fresh cpu/ copy damaged again (its llama.dll removed, then a second manifest id on the same weight walked to rung 3; the first id was latched by #372). The verdict carried afterInstall: true, the banner showed the Visual C++ sentence with only "Erneut prüfen", and a reinstall request was refused with main.engine.nothingToRepair.

The review found two things, both fixed: a job that stopped after replacing only the cpu/ net told no one, and a later cpu/-only install made the store forget that the main build was fresh. Kept by design: when both builds reported, Check again checks the main build, whose healthy start clears the verdict anyway (§9).

Residuals.

  • While the verdict stands, the banner's demo note ("Bis dahin antworten Modelle im Demo-Modus") reads as the engine's doing, although the demo runtime answers because the model failed; the model's own notice says so above it.
  • A refused cpu/ net that this host's pin has no build for gets the offer and then main.engine.noHostBuild (not observed; the drive layout needs a hand-provisioned main folder).
  • Unchanged from §8: while a real runtime answers, the reinstall is refused even when it replaces only the cpu/ net, because the status cannot tell rung 3 from the main build's rungs.

Tests: engine-consent-ipc.test.ts "#678" (the cpu/-only repair through the real handler and manager, its fresh copy refused again, both builds, a gone cpu/ program, no cpu/ build pinned, the per-build in-use guard), engine-recheck.test.ts "#678" (Check again on the cpu/ net), engine-load.test.ts "after a reinstall on a Kit of …" (the fresh-copy mark per installed build and across installs), engine-download.test.ts "#678" (a stopped job reports a cpu/ net it replaced).

§12 #790 amendment — a piped stdio stream's own error is absorbed at every spawn site (2026-11-08)

The gap (found in #787's review, PR #789). A piped stdio stream of a child can emit an 'error' of its own, beside the child's 'error'. With no listener it is an uncaught exception, and in the main process the uncaughtException handler locks the vault and exits: a crash. #789 guarded kiwix-serve's stderr only, since only kiwix-serve passes a cwd (rag-design.md §17 D-Z1 "#787 amendment"). LlamaServer (stderr; chat, embedder, reranker, vision, translation), the GPU probe (stdout and stderr), the engine check (stderr) and whisper-cli (stdout and stderr) attached 'data' only.

The facts (measured 2026-11-08 on Windows 11, in Node 24.13 / libuv 1.51 and in Electron 43.8.3's Node 24.22 / libuv 1.52.1, identically). Each case ran under both stdio shapes the app uses (['ignore','ignore','pipe'] and ['ignore','pipe','pipe']).

  • One trigger: a cwd of MAX_PATH or more. The child emits 'error' ENOENT first, then EVERY piped stream emits ENOTCONN (two uncaught exceptions for the two-pipe shape), then 'close' with -4058; the child never had a PID. A listener on each stream contains it, and the spawn still fails through the child's 'error' (real llama-server b9849 from D:, both shapes).
  • The child's own 'error', streams at EOF: a missing binary or cwd (ENOENT), a binary path over MAX_PATH (ENOENT, long paths enabled), a folder named .exe (ENOENT), a program that requires elevation (EACCES, from a medium-integrity process), no PATH in the parent or the child's env (it spawns).
  • A synchronous throw, so no stream exists: a damaged executable (UNKNOWN), a truncated or empty one (EFTYPE), one held open exclusively (EBUSY: an antivirus scan holding the file), a command line over 32,767 characters (ENAMETOOLONG). Every site already handles the throw (#530, #658).
  • Why (libuv win/process.c, v1.52.1): uv_spawn opens the pipes after the cwd step (a cwd of MAX_PATH or more is shortened with GetShortPathNameW, which fails without an 8.3 name) and the PATH lookup, and before the program lookup and CreateProcessW. A failure before the pipes leaves them unopened; for its five async codes (EACCES, EAGAIN, EMFILE, ENFILE, ENOENT) Node still wraps them, and the first read returns ENOTCONN. On POSIX uv_spawn opens the streams even when exec failed (a disabled #if 0, for Node's sake), so they read EOF (source reading, not measured).
  • Nothing measured reaches the four sites: none passes a cwd, and the inherited one cannot be long enough. Windows refuses a process cwd over 258 characters (process.chdir → ENAMETOOLONG, long paths enabled), and a 258-character one spawns normally.

Decisions (owner, 2026-11-08, each as recommended).

  1. One guard, guardChildStdio (runtime/sidecar.ts, beside registerSidecarChild), called by every site right after spawn() returns: LlamaServer, the GPU probe, the engine check, whisper-cli and kiwix-serve (#789's hand-written listener moved onto it). It listens on stdin, stdout and stderr, whichever is piped. The child's own 'error' / 'exit' / 'close' stay the owner of every outcome; the stream's error is absorbed.
  2. The GPU probe's stdout is its answer. A probe whose stdout stream failed resolves null (unknown: never cached, never persisted) even on exit 0, and logs it as no answer ("its output could not be read"). What arrived may be cut short, and the header alone parses as [], which would be persisted as "no graphics card" (GPU record §5.2 "#653 amendment"). The engine check likewise (a review finding, the same rule): its stderr is what a non-zero exit is read from, so an exit the classifier does not recognise after a failed stderr is unchecked (the verdict as it was), not loads, which would clear it. LlamaServer and whisper-cli read their streams for diagnostics (the tail, progress).
  3. A started child's failed pipe is logged, once per stream, with the program, the stream and the errno code, never the message. A failed spawn's (no PID) stays silent: each site already logs the child's own error.
  4. repo-hygiene keeps it true for spawns that do not exist yet: the modules that import node:child_process are listed, and a file whose spawn pipes a stream calls the guard once per such spawn (a stdio value it cannot read fails closed).

Real-app verification (2026-11-08, DesktopDiT, GTX 1070 Ti, dev build on a scratch root whose runtime\ and models\ were junctions to D:'s b9849 and models). The session's device probe found the card; the 4B started on it, answered and stopped; the log, read after a clean quit, held no pipe line, no ENOTCONN and no uncaught exception. The same day, with the real binary: the probe (the card), the engine check (loads) and an e5 LlamaServer start and stop logged no pipe line. whisper-cli was not run on a real binary (none on this machine); its site is the same call.

Residuals.

  • On a child that started, a failed stream is not known to happen: a Windows pipe whose writer closes reads EOF, and the app never writes to a child's stdout or stderr socket on POSIX. If it did, LlamaServer's stderr tail (the bind-race retry, load-failure classification, the placement read from the load log) is read as far as it arrived, and whisper-cli's progress stops, so its inactivity watchdog (REL-1) can end a long transcription. Node closes the failed stream, so on POSIX the child's next write to it can end the child (SIGPIPE), which takes the site's ordinary exit path (for a healthy LlamaServer, the unexpected-exit report). Each is still better than the main-process crash it replaces. The warn line says which program and stream.
  • The repo-hygiene rule is a text check: it cannot see a spawn with no stdio option at all (Node's default pipes all three; every spawn here states its stdio, and a new spawning module trips the inventory), nor whether each call guards the right child (the per-site rows prove that).
  • Not measured: a spawn failure on macOS or Linux with a stream error (source reading only), a security product that refuses a program asynchronously, a drive on a network share.

Tests: sidecar.test.ts "guardChildStdio (#790)" (a failed spawn: every piped stream absorbed, nothing logged, the site told which; a started child: one code-only line; a stream not piped is skipped); one failed-spawn row per site: engine-load-spawn.test.ts (LlamaServer: failed to launch: spawn ENOENT), gpu.test.ts (both streams: null; an exit 0 after a stdout failure: null), engine-health.test.ts (unchecked; an unrecognised exit after a stderr failure: unchecked), transcriber.test.ts (both streams: the spawn error), zim-serve.test.ts (#787's row, now through the guard); repo-hygiene.test.ts "#790" (the two rules). Mutations: 21/21 red.

§13 #1012 amendment — a recorded file missing before the spawn is the same verdict (2026-11-22)

The pre-spawn check re-hashes every file the engine copy's install marker records (security-model.md "Re-hash sidecar binaries before spawn", #1012). A recorded file that is gone gives the verifier's missing (the program or a library) or missing-other (any other file). That is no tamper, and the engines' spawn sites treat both as this record's files-damaged, without starting the program (reportDamagedEngineFiles, runtime/engine-load.ts). The verdict's exit is 'not started' and it carries no name. A recorded file that cannot be read just now is unreadable (review R-2): no verdict, not cached, and the typed EngineFilesUnreadableError, which the ladder counts as no evidence about the GPU, the model or the MTP flags (it holds, persists and latches nothing, and names no model when every rung ended so).

Since code review round 6 a changed file (mismatch) is the same files-damaged verdict at the engines' sites (isDamagedFilesVerdict). With the whole copy hashed, a damaged library (a copy cut short) gives mismatch just as a tamper does. Before round 6 it was a plain error: rungs that all failed so blamed the model, and no reinstall was offered. The start is still refused, and the verifier's log line still records a possible tamper.

  • Why not start anyway. A start that went ahead and ran would drop the verdict at once (§9, a healthy start clears its reporter), and the #532 offer with it. A missing ggml-vulkan.dll runs silently on the processor, and the probe's empty list was persisted as "no graphics card" (#1013).
  • What each site does.
    • LlamaServer throws the typed error, so the ladder walks on to the cpu/ net (§4).
    • The probe resolves null.
    • checkProgramLoads returns refused, so "Check again" keeps the verdict while the file is gone or changed. An in-app install clears the verifier's cache (invalidateBinaryVerification).
    • whisper-cli throws the typed error.
    • The knowledge-pack tools (no verdict family, no repair) refuse missing (a missing library would be looked for in the library folder they start in, review R-1), and log the code and start on missing-other. A changed file keeps their integrity / verify kind.
    • On unreadable: the probe resolves null, checkProgramLoads returns unchecked, and LlamaServer and whisper-cli throw EngineFilesUnreadableError.
  • What unreadable does elsewhere (code review round 3).
    • Every other LlamaServer user (the embedder, the reranker, translation, vision) rethrows it like a bind race: no startFailed latch, no GPU → CPU demotion, no #117 cooldown.

    • In the ladder, round 4 sets one rule: a walk in which any rung ended unreadable latches nothing. That means no blameModel, no persisted GPU failure (at a later rung's success or at the end) and no MTP latch (one its rung 1a set is taken back). It only reports:

      • the model notice (onModelLoadFailure, no latch) when a forced-CPU (control) rung failed in a way that is evidence (not a bind race, not an engine refusal; round 6: not a GPU rung, whose control never ran);
      • else onEngineFilesUnreadable, which shows main.engine.filesUnreadable beside the demo runtime.

      The reason comes from the last failure that is not unreadable. The next start re-walks. Round 6: this branch comes before #530's onEngineCannotRun, so a main copy that was only unreadable beside a refused cpu/ net never reads as "the engine cannot run" (the net's own verdict stands).

    • The consumers that report a start failure to the user stop at once with main.engine.filesUnreadable (round 4):

      • the translate view (TranslateErrorCode filesUnreadable);
      • a document translation task (a friendly task error);
      • an audio import (a persist-canonical row text, display-mapped);
      • dictation;
      • an image question (VisionErrorCode filesUnreadable, round 5; no #117 cooldown).
    • The chat's files-unreadable notice carries the models target (round 5), so its button opens the AI Model screen. There, "Stop runtime" then "Use this model" restart the model: RuntimeManager.start is idempotent for the same model, so choosing it alone keeps the demo runtime.

    • The knowledge-pack tools report a missing file with their own files kind and an unreadable one with filesUnreadable (round 5). ZimService latches only files until the pack set changes. writeLibraryXml stops on a filesUnreadable kiwix-manage, and (round 6) on a files or verify one, instead of skipping each pack, which would publish an empty library for the revision.

    • A folder or another non-regular file at a recorded path is missing, not unreadable (round 5). Round 6: one stat of every recorded file comes before any hash, so a missing program or library ends the check with nothing hashed. A marker that is there but cannot be read is unreadable, with no fallback from a cpu/ net's own marker to the family's.

  • Tests:
    • binary-verify-spawn.test.ts: the two "#1012" describes, one row per site and verdict.
    • binary-verifier.test.ts "(#1012)": includes which missing file counts, the early stop and the containment of every key.
    • runtime-ladder.test.ts "#1012": an unreadable rung is no evidence; the notice; the evidence rule; the control rung.
    • One row each in e5-embedder, reranker, translation-runtime and vision-runtime.
    • Round 6: runtime-ladder-exit-wiring.test.ts "#1012" (a changed library through the real ladder and verifier), the kiwix-manage refusals in zim-service-lifecycle.test.ts, and the changed-file rows in binary-verify-spawn.test.ts and engine-recheck.test.ts.

§14 #1028 amendment — an install marker that is there but damaged is the same verdict (2026-11-23)

Until #1028 the pre-spawn check took a marker that is there but cannot be read as one (cut short by an interrupted copy, garbled) for no marker: the copy was skip-legacy, cached for the session, and the engine started with nothing checked. A cpu/ net's own damaged marker fell back to the family marker one folder up.

  • The rule. Every reader reads the marker one way (readRuntimeMarkerState, assets.ts): absent, unreadable just now, damaged, or a marker (what counts as damaged: security-model.md "Re-hash sidecar binaries before spawn", and data-contracts.md, which also holds the rules every later writer keeps). The walk stops at the first marker file it finds; a damaged one is the verdict marker-damaged, and so is a map that records files of the copy but not the program it was asked about.
  • What each site does. isDamagedFilesVerdict includes it, so LlamaServer, the probe, checkProgramLoads and whisper-cli treat it exactly as §13's missing file: this record's files-damaged with exit: 'not started', the ladder walks on, the probe answers null, "Check again" stays refused, and the #532 offer comes up. The knowledge-pack tools refuse it with their files kind (owner call 2026-11-23), latched until the pack set changes or the app restarts, like a missing program or library: a marker repaired while the app runs is picked up only then (code review CR-7; the latch is kept). A key that leaves the folder is checked before the program's own key, so it stays a tamper (mismatch, CR-2).
  • Not cached, like missing: one stat and one small read per attempt, nothing hashed. A marker read while fetch-runtime rewrites it in place is read whole by the next attempt, whose healthy start drops the verdict (§9); a marker put back by hand is found without a restart. A reinstall clears the cache anyway.
  • The repair. The #532/#678 reinstall reads no marker of the copy it replaces: the damaged copy goes to .old and is deleted marker first, and the new copy carries a fresh marker. engine-consent-ipc.test.ts holds that loop end to end with nothing injected. Both fetch-runtime twins fetch a copy whose marker is damaged again (the .sh twin used to read the version out of a cut text and skip it). Since review round 2 each twin reads the marker with a small JSON reader of its own, the app's rule step by step (a raw control byte, garbage or a trailing comma, single quotes or a capitalised name no longer slip through), and on a doubt fetches again; the sell gate's line adds "if it reports the engine already installed, delete the engine folder first".
  • Unchanged: the dev posture (skip-dev, no read); a hash-less marker (skip-legacy, the #234 posture); the status, relation and "complete" readers, which read a damaged marker as none (relation unknown).
  • Tests: binary-verifier.test.ts "(#1028)" (the walk, the net, the cache, the postures); assets.test.ts (the reading table, and "complete"); binary-verify-spawn.test.ts "#1028" (one engine row, both kiwix seams); engine-consent-ipc.test.ts (the repair); commercial-drive.test.ts (the gate's lines); script-execution.test.ts (both twins re-fetch, and a byte-order mark still skips).

In-app engine updates — design record (#516, 2026-10-05)

A drive set up before a pin bump keeps its engines: after #514 (llama.cpp b9849 → b11146) every older drive ran b9849 under the new app, and nothing said so. This record covers the detection, the update and its "pause, update, resume" flow, and a bug in the plain install found on the way. Code cites it as "In-app engine updates".

§1 The facts it rests on

  • Detection costs nothing new. Every install writes .hilbertraum-runtime.json with { version, backend }, and the app pins its own runtime-sources.yaml (the bundled model-manifests, never the drive's). Nothing compared the two; Diagnostics showed only the marker.
  • Tags order by number, not as text. As strings, b9849 sorts after b11146. llama.cpp tags are a build counter (bNNNNN); whisper.cpp and kiwix-tools use dotted releases (v1.8.6, 3.8.1).
  • The plain install used to update by accident. It selected every required family "not current by its marker". On a drive like the E: test stick (voice engine missing, chat engine b9849), the "Install voice engine" button therefore also re-fetched the chat engine. While anything used the chat engine, the whole job was refused with "the AI engine can't be replaced while a model is running". Against a NEWER engine (a drive updated by a newer app), the same click downgraded it.
  • An outdated engine is busy. Unlike #532's broken engine, it runs. The chat model runs on it, and the E5 embedder starts on the first import or document question and stays up until lock or quit. The CODE-13/F-32 guard therefore refused almost every in-session replacement.
  • The cpu/ safety net has its own marker (<os>/cpu/.hilbertraum-runtime.json), and the in-app installer never wrote it. Updating only the main build would leave a Windows Kit on b11146 with a b9849 fallback.
  • fetch-runtime reads the drive's yaml first, so re-running it on an old drive re-installs the old pin unless prepare-drive refreshed the drive's manifests first (the #514 reference-drive trap).

§2 Decisions (owner, 2026-10-05)

  1. Offer and report. A quiet notice on the AI Model screen, plus the version gap in Diagnostics and the Copy report.
  2. Pause, update, resume. The update is refused while work runs. Otherwise it stops the model and the engine's helpers, replaces the files and starts the model again; the helpers restart on next use.
  3. Chat and voice engines, and the cpu/ net when it is on the drive and older. The knowledge-pack tools are reported only.
  4. Commercial Kits get it too, behind the same gates: the drive policy, Allow internet access, and the click. Offline Kits see it disabled with the policy reason; signed offline updates stay Phase 22 (BUILD_STATE §5 item 3).

§3 As built

  • Relation per install (assets.ts): compareRuntimeVersions orders two tags of one family (null when the shapes differ or are unknown). runtimeInstallRelation(plan) answers:

    • older: an older version;
    • current: the pinned version, in whatever backend the drive owner chose (review fix: a main folder provisioned with fetch-runtime -Backend at the pin is a choice, and "updating" it would swap the backend; a CPU-era main folder is older by version anyway);
    • newer;
    • unknown: no readable marker, or an unorderable tag.

    Only older is ever replaced. engineStatus reads each marker once.

  • Status: EngineStatus.engineVersions lists every family on the drive with a build here: installed and pinned version and backend, the relation, and cpuNet when the drive carries the cpu/ build. EnginePlan.cpuNet is the yaml's cpu build when the default is another backend in another folder.

  • The plain install fetches MISSING engines only (!runtimeBinaryPresent), which is what its comment always said. An engine on the drive changes only through an explicit update or reinstall. The explicit families path (the knowledge-pack consent) keeps "not current".

  • The update request: downloadEngine({ families, update: true }), with required families only, never combined with reinstall. The manager takes each named family's main build when it is older, plus its cpu/ net when present and older. Nothing qualifying is main.engine.nothingToUpdate, so it never downgrades and never replaces an unrecorded engine. The job carries update: true.

  • Two phases, for every job. run() downloads and verifies every archive first (fetchArchive), leaving the installed engine untouched and usable. Only then does it call StartEngineDownloadOptions.beforeReplace and replace each install (replaceInstall). Amended by #986 (§6): between the phases the job checks the free space; each install is then a staged swap (extract, flatten, completeness check and marker in <os>.new/, then two renames), no longer a pre-clean followed by an extraction in place. Amended by #1000 (§7): three phases. Every copy is also unpacked, checked and marked in its <os>.new/ BEFORE beforeReplace, while the models keep running; only the swaps come after the pause.

    • A failure or cancel in phase 1 replaces nothing.
    • Archives not yet extracted when the job stops are deleted.
    • The spawn gate (runtime/spawn-gate.ts, review fix). From beforeReplace to the last marker, the job holds every spawn of the families it replaces. LlamaServer (chat, embedder, reranker, vision, translation), the GPU probe, the load check and whisper-cli all await waitForEngineSpawns before they verify and spawn, bounded at 6 minutes (the extractor's deadline plus a margin). Amended by #1000 (§7): the gate is held from the pause to the last swap only, so the 6 minutes are now a real bound.
      • Before the gate, a helper restarting by itself (the embedder on a search) or a model start that was still hashing its weights when the pause ran could launch a half-extracted binary. On Windows it could also hold a file the pre-clean was about to delete.
      • The gate covers every job, so it closes CODE-13's registered "a start races the pre-clean" residual for first installs and #532 reinstalls too.
    • A failed install leaves nothing installed (#752). Every failure of replaceInstall comes after the old copy started to go, so each clears the install the way the pre-clean does, one entry at a time and before the status flips, cpu/ kept when it is a real directory. Left behind, a binary read as installed with no marker, and the verifier passed it as skip-legacy. A tar that failed also never reached the sweep, so its links stayed. A user's cancel of a running tar is the exception (see below), but not one that lands on a SEC-2 refusal: that clears too. The residual: a refused archive that wrote into cpu/ is not undone, since the net is kept whole; reaching it takes a tampered runtime-sources.yaml, which can name any archive anyway. Amended by #986 (§6): a failed install now leaves the PREVIOUS install exactly as it was, and no .new. The failed copy is only ever in <os>.new/, which is deleted (a first install still leaves nothing that reads as installed); the clear-up, clearFailedInstall and the cpu/ residual are gone.
    • A job that stops part-way still reports what it replaced (review fix). If the main build was swapped and a later step (the cpu/ net, the voice engine) failed or was cancelled, onInstalled fires for the replaced families, so the new binary's consumers are re-armed and the probe refreshed. The job itself still ends failed or cancelled. Since #1000 (§7) a job can stop part-way only in its swaps: a stage that fails or is cancelled comes before every swap, so the job replaces nothing.
    • A cancel after the files are complete finishes the install (review fix). A cancel during the extraction kills tar (F-33), so install() rejects and the job is cancelled; a half-extracted folder surfaces as #530 "files damaged", which the #532 reinstall repairs. A cancel that lands after install() finished arrives too late to stop anything: the old copy is gone and the new one is whole, so the marker is written and the job reports done. Skipping the marker used to leave a working engine with no version record, which no update offers to replace. Superseded by #986 (§6): nothing installed is touched before the swap's first rename, so a cancel is honoured until then, after the extraction too (the copy in .new is deleted), and arrives too late after it (the step finishes, marker included). A cancelled extraction no longer leaves a half-extracted install folder.
  • The pause (registerEngineIpc.ts startEngineUpdate):

    1. Refused up front while work runs (engineUpdateBusy → main.engine.updateBusy):
      • any modelBusyLane (an answer, a document task, a skill run, the benchmark);
      • any generation in either lane (runtime.isGenerating(): a local-API completion holds no in-app stream and no span);
      • a model that is still starting;
      • a document translation (translateJobs.getActiveJob());
      • an image analysis (VisionService.hasActiveJob());
      • an import, re-index or knowledge-pack article save (the new ctx.ingestionActive: the docs IPC's processing set plus ctx.articleSavesActive);
      • for the voice engine, a live transcription.
    2. In beforeReplace, after the last archive verified, the same check runs again: work may have started during the download. A refusal fails the job with that copy, and the old engine stays. Since #1000 (§7) this runs after the last copy is staged, so work that started during the unpack refuses the swap too (owner decision G-9: keep refusing, do not wait).
    3. The pause itself remembers the running model and stops the chat runtime. It suspends the embedder, reranker and translator (the lock teardown's non-latching suspend()), and lets vision's idle sidecar go (VisionService.releaseRuntime(); review fix: the lock's stop() would also purge finished answers). For the voice engine, it suspends the transcriber. It then checks that no child of the family is alive.
    4. Then the swap. Main checks the in-use flags here instead of at start() when a beforeReplace is given.
  • The resume. On success, the install hook re-arms the consumers, refreshes the probe and then starts the remembered model (resumeChatModel; skipped when the workspace locked or another start is running). On failure or cancel, the new EngineDownloadManager.onSettled listener starts it instead, on whatever engine is on the drive.

  • Renderer: a quiet Banner tone="info" in ModelsScreen after the missing-engine banners (design guidelines §11.20). It has one Update for every outdated required family, through the shared engineJobControls, attributed by job.update. It is hidden for a family with a #530 verdict, because that banner leads and a reinstall fetches the pin anyway. It joins the deep-link no-scroll predicate (the #539 note on #516), and a toast confirms a finished update. Diagnostics has an "Engine versions" row (and Copy-report line) naming every engine or cpu/ net that is not the pin.

  • The update asks first (#843, 2026-11-18). Update opens the engine confirmation (the "In-app engine installer" #843 addendum) with what this job will fetch: the main build and, when older, the cpu/ net, each "installed → pinned". The dialog's preview and start() select the archives with one function, planEngineSteps (extracted from start()), so the rule "the notice never offers what the update would refuse" now holds for the dialog's list too, for the selection (as of the moment it opened; Confirm plans again), and P8's in-app updater extends that function, not a copy. The preview does not run the checks outside the selection: the gates, the one-job check, an engine in use (main.engine.runtimeRunning and its voice and tools twins) and the update's busy check (main.engine.updateBusy). Those refusals can arrive after Confirm, as the same friendly errors (research C §1.8 accepted this). The dialog's "the model pauses for a few seconds" note shows only when the update includes the AI engine: a voice-engine-only update pauses the transcriber alone (pauseEngineUsers).

  • Scripts: fetch-runtime.{ps1,sh} print a note when the drive's yaml pins a different version of the family than the repo's, and say to refresh the manifests (prepare-drive) first (packaging.md). Newer is never replaced there either (#873, 2026-11-18): a present engine whose marker is NEWER than the drive's pin, by compareRuntimeVersions's order (re-spelled in both twins, held to one shared table by script-drift.test.ts), is skipped with a line naming both versions, whatever its backend, unless -AllowDowngrade/--allow-downgrade (not -Force: that is prepare-drive's "overwrite config") or -Commercial/--commercial (a sold drive carries its app's pin; the script says it is replacing the newer engine). An unorderable version re-fetches as before. Applies to llama.cpp (main and cpu/), whisper.cpp and the knowledge-pack tools.

  • The pin is the app's own (#842, 2026-11-17). §1's "never the drive's" was the intent, but the handlers passed ctx.manifestsDir, which the launchers point at the drive's model-manifests/; only a direct start read the bundled copy. A new app copied onto a drive whose manifests were not refreshed therefore compared the engine with the drive's old pin and offered nothing. The status, install, repair and update, and the voice engine's "could it be fetched here" check (#527), now read ctx.bundledManifestsDir, set by resolveBundledManifestsDir: no override reaches it; a packaged build takes exactly <resources>/model-manifests (process.resourcesPath), with no walk-up that could reach the drive's copy above the app, and a dev build the checkout's. The model list keeps ctx.manifestsDir. Engine entries a drive owner adds to the drive's yaml (another OS's build, a mirror) reach the scripts only. After an in-app update the drive's yaml is older than the engine on it. The sell gate (assertCommercialDrive) compares markers with it for EQUAL and reports the updated engine as not matching its pin; fetch-runtime run without prepare-drive first used to re-install the drive's older pin too, and since #873 keeps the newer engine instead (above). prepare-drive brings the yaml back in step.

§4 Real-app verification (2026-10-05, DesktopDiT, GTX 1070 Ti, dev build)

The scratch root was E:'s b9849 engine copied off the stick (only read) plus a b9849 cpu/ net installed with fetch-runtime -Backend cpu. The 4B model was running on the GPU on b9849, and the voice engine was missing.

  • Status: engineVersions reported llama.cpp b9849 → b11146, older, cpuNet older. The AI Model screen showed "Add voice dictation" and "An update for the AI engine is available".
  • The plain-install fix: Install voice engine, with the model running, ran a job of whisper_cpp only. It finished in 2 s, the chat engine stayed b9849, and the model kept running. Before #516 this click was refused.
  • Update: both archives (main and cpu/) downloaded while the model answered (0–4 s). The model stopped at ~5 s, both markers read b11146 at ~6 s, and the model was back on rung 1 (GPU) at ~11 s. That is about 6 s of downtime, most of it the model reload.
  • Afterwards: no notice, and Diagnostics "Runtime build: llama.cpp b11146 (vulkan)" with no "Engine versions" row. The finished-update toast had expired before the capture; the renderer test covers it.
  • fetch-runtime dry-run against E: printed the note (pins llama_cpp b9849; this repo pins b11146), in both the PowerShell and the bash script, and E:'s runtime folder was byte-identical before and after.
  • Second run, after the review fixes (a fresh scratch root, again b9849 with a b9849 cpu/ net):
    • An update asked for while a chat answer was streaming was refused (main.engine.updateBusy), and nothing was downloaded.
    • The idle update downloaded both archives in ~4 s while the model kept serving. The model was back on the GPU ~5 s after the pause, and both markers read b11146.
    • On this card the b9849 Vulkan build hung mid-chat. Two chats on b9849 stalled: one tripped the 30 s stream watchdog, and the other never received response headers (see §5). Two chats on b11146, right after the update, answered in 4–6 s. The update fixed a real failure here, not only a version label.

§5 Residuals

  • A quick translation has no public busy signal (the Translate screen's interactive request; only a private in-flight counter). One in flight at the pause is cut off and fails, and the user retries it. Document translations, image analyses, generations and article saves are all waited for.
  • An unknown engine (no marker, or an unorderable tag) is reported in Diagnostics but never offered an update. The in-app installer no longer leaves one behind (since #986 it marks every copy before it swaps it in, and a cancel leaves the old copy). One copied by hand heals through the #532 repair if the OS refuses it, or through the scripts.
  • The knowledge-pack tools are reported, not updated (decision 3). Their consent dialog installs a missing copy only, and their spawn sites are not behind the spawn gate (no in-app update replaces them).
  • The ModelsScreen runtime poll (see "Engine load failures" §8) can show the card's earlier state until the next refresh when the restart begins late.
  • A chat sidecar that hangs before its response headers — fixed by #594 (found in the §4 second run; it existed before #516).
    • The CB-5 watchdog in readChatSSE covered only the body, so the turn waited until the model was stopped (fetch failed, ECONNRESET) or undici gave up after 300 s.
    • While it waited, its busy signals refused this update with main.engine.updateBusy.
    • The header wait is now bounded: 120 s since #594, 180 s since #598 (chat backend robustness, the CB-5 "#594 amendment" and "#598 amendment").

Tests:

  • assets.test.ts: the version-order table, the relation (the pin in another backend is current).
  • spawn-gate.test.ts: hold, wait, release, bound.
  • sidecar.test.ts "waits for an engine install to finish its swap before it spawns (#516 spawn gate)": the LlamaServer spawn site (all five llama sidecars) waits on the gate; gpu.test.ts (same title) the --list-devices probe, and engine-health.test.ts "waits for an install of its family to finish the swap before it launches (#516 spawn gate)" the "Check again" launch, and transcriber.test.ts "waits for an engine install to finish its swap before it spawns (#516 spawn gate)" the whisper-cli spawn.
  • engine-download.test.ts "engine updates (#516)": status with cpuNet, missing-only, update with cpu/, never newer or unknown, the two phases and the held gate at the pause, a part-way failure still reported, onSettled. Also the CODE-13 pair: a cancel during extraction, and one after it. (#1000 rewrote the phase and part-way rows: §7.)
  • engine-consent-ipc.test.ts "#516": pause, swap and resume through the real handler (vision released, never purged), resume after a failed swap, six busy refusals, work starting during the download. (#1000 split the failed-swap row: §7.)
  • EngineUpdate.test.tsx: the notice, both engines, cpu/ only, five no-notice rows, the Diagnostics row and report.
  • ModelsScreen.test.tsx: the deep-link row.

§6 #986 amendment — the staged engine swap (2026-11-21)

An install, update or reinstall deleted the installed engine and then extracted the new one into the same folder, so any failure after the download left no engine: a full drive, an antivirus hold on a new file, a sleep, an unplug or a kill during the extraction (#986; measured: the b9849 folder was replaced in place, nothing kept). This is the app-update plan's W-67 (T8.5c, PA-225), built before the first Kit release freezes the install path, with the four gaps follow-ups wave 6's research found in it. Code cites it as "In-app engine updates" §6.

The facts it rests on (measured on NTFS, Windows 11, Node 24, follow-ups wave 6 research E):

  • A folder rename is refused with EPERM while any file in it or in a sub-folder is open, and with EBUSY while a process has its working folder inside. A running program does not block the rename of its folder, only its deletion (unlink and rm -rf of it: EPERM). So a rename swap is more tolerant than the old delete, and the existing stop and refuse rules (the pause, the in-use refusal, the spawn gate) stay: a process left running would keep the old copy from being deleted.
  • Windows never renames a folder onto an existing one (EPERM); POSIX replaces an empty one only.
  • On exFAT a folder lists in creation order and the marker is written last, so a delete cut short keeps the marker over missing files. exFAT itself was not measured (owed on a real stick).
  • No reader enumerates runtime/<family>/: every resolver, the verifier, engineStatus, the planner, Diagnostics, the GPU probe and the load check use exact paths, so sibling folders are invisible.
  • The zip central directory states each member's unpacked size: for llama.cpp b11183's Windows Vulkan zip its sum, 92,515,613 bytes in 52 files, is exactly what the extraction writes (96,993,280 bytes at exFAT's 128 KiB allocation unit). No pinned archive is Zip64.

Decisions (owner, follow-ups wave 6 gate G-5 (a), 2026-11-21): W-67 now, with its gaps closed; the free-space figure from the archive itself (no manifest field); two new strings; the sell gate and the Kit gate refuse a leftover; a cancel is honoured until the first rename; CE-F10 (run a complete copy in place on a read-only drive) stays the app-update plan's.

The four gaps in W-67, as closed:

  1. The cpu/ net sits inside the main folder (<os>/cpu/), so the main swap moves it to .old. The main step carries .old/cpu into the new copy when that has none, before .old is deleted; a .old whose net could not be carried is kept, and the start carries it.
  2. "A current folder" means a complete one (the marker parses and every required file is there, engineFolderComplete), never mere existence: the install folder can exist empty (prepare-drive, the archive's download, a net's folder).
  3. Un-mark before deleting: every delete of a copy removes its marker first. Review round 2: a copy is judged by ITS OWN marker: the marker parses and every file its binaries map records is there (the plan's list only for a marker without the map). Judged by the current pin's list, an old copy that lacks a file a newer pin adds read as incomplete, and the start deleted it instead of rolling back to it (and finished an update it should have dropped). #1028: "parses" is the one reading every reader shares (readRuntimeMarkerState): a binaries that is no map, or an entry that is no SHA-256, makes the marker damaged, so the copy is incomplete (before, such a map read as none and the plan's list made the copy complete).
  4. No rename onto an existing folder: a stale .old is deleted (marker first) before the swap, and one that cannot go fails the step before the install folder is touched.

As built (runtime-download.ts, assets.ts, fs-retry.ts, archive-size.ts):

  • Room first. After every archive verified and before the update's pause, missingRoom reads each archive's unpacked size (extractedArchiveBytes: a zip's central directory, a tar.gz's ustar headers through gunzip; each file rounded up to the volume's allocation unit, statfs bsize; one unit per folder) and sums the steps per volume (the replaced copies go only after the job). More than is free: noSpace, main.engine.notEnoughSpace with both figures, nothing touched and nothing paused. A size it cannot read (Zip64, an unknown format) skips the check with a log line.

  • Stage (stageEngineInstall(plan, stagingDir), per step): wait for queued deletes; delete a stale <os>.new (marker first); move the verified archive in (#856: tar runs inside the folder with ./<name>); extract; flatten; remove the left-out executables (#729); the SEC-2 link sweep; delete the archive; every required file present; chmod; hash every file into the marker; flush every file to the device; write the marker LAST, inside .new, and flush it (lens F CE-F1: a marker written after the move made a quit there reinstall over the kept copy). Phase 1 is unchanged: the archives still download into the install folder, which a first install creates. Amended by #998 and #1000 (§7): the archive's own member list is checked against the copy, "every file" means every file the copy holds (it meant the required ones), the flush runs off the main thread, and every step is staged before the pause.

  • Order (review round 1): phase 2 installs each family's cpu/ net BEFORE its main build. The net's archive downloads into <os>/cpu/, inside the main folder: with the main build first, its swap moved that archive into .old/cpu/, and a refused carry left the net step without it (ENOENT) and the archive inside cpu/ for good once the start carried .old/cpu back. Net first, the net's swap happens inside the old install folder and the main build's carry takes the NEW net across; no archive is ever inside a folder another step renames. The cost: a net step that fails now stops the job before the main build, which then stays as it was (it used to be replaced and the net failed after it).

  • A retry never deletes what the last attempt kept (review round 1). Before phase 1, the job runs the start's recovery rule (recoverEngineFolder, below) on each of its folders, main build before its net: a swap whose old copy could not be moved back is finished (the new copy moved in), a net a refused carry left in .old is carried in. Before phase 1, because phase 1 makes the install folder again for its archive. In phase 2 a step still refuses to delete a .new or .old that is the only whole copy (the install folder is not) or that holds a cpu/ net the install folder lacks: it ends filesInUse with nothing touched.

  • Cancel: checked after the extraction, before the swap, and once more inside the swap right before its first rename (after a stale .old was deleted, which can take seconds). Until the swap's first rename a cancel deletes .new and replaces nothing (#516's "finish the install" rule had its reason in the old copy being gone, and is retired); after it, the step finishes. Amended by #999 and #1000 (§7): a cancelled extraction ends only once tar has exited, and a cancel before the swaps never pauses anything.

  • Swap (swapEngineFolder): delete a stale .old; <os> → <os>.old; <os>.new → <os>. Each rename goes through renameWithRetry: on Windows, EPERM, EACCES and EBUSY are tried again with waits of 50 ms doubling to 1 s, 12 s in all; elsewhere the first refusal stands. A refused first rename touches nothing; a refused second one moves .old back. Both end the step filesInUse (main.engine.filesInUse, "try again in a minute") with the installed copy as it was. Only when .old cannot be moved back either do both copies stay; the install folder is then gone for the moment. The next job (the screen offers the install) and the next start first finish such a swap with the start's rule, for every folder of the job's families, the main build's nested net folder included (review round 2). Their renames are tried once, without the waits a job's renames get, so "try again in a minute" holds once the holder has let go; while it still holds a folder, the job ends filesInUse again with nothing touched. Deletes of a copy (removeEngineFolder) get Node's own rm retries on Windows, 15 tries of 100 ms more each (12 s), for a scanner still reading a failed copy.

  • The spawn gate's bound is not the worst case (review round 1). One step can take the extractor's 5 minutes plus several 12 s rename budgets (the archive's move, the flatten, the swap's renames, a move back, the carry), the hashing, the flush and waits on queued deletes, and a job has up to two steps per family, so a job can hold the gate past its 6 minutes. That is enough: the install folder changes only in the swap's renames, so a spawn that stops waiting meets a complete copy, old or new, with two gaps: between the swap's two renames the install folder does not exist, for up to one 12 s rename-retry budget (the spawn finds no program, as with no engine), and between the main build's swap and its carry the new copy has no net for a moment (review round 3). What a spawn let through early can do is run the old copy, which the swap moves to .old, where Windows cannot delete it while it runs; the next swap or start deletes it. Superseded by #1000 (§7): the gate is now held from the pause to the last swap only, so what it covers is a few 12 s retry budgets per step, well inside the 6 minutes; the two gaps stay.

  • After the swap: the main step carries cpu/; the verifier's cached verdicts for the replaced programs are dropped; .old is deleted in the background, marker first, once the job has released the spawn gate (a waiting helper starts on the new copy at once). The deletes run one after another (engineFolderDeletesSettled), and the next stage and swap wait for them. #1000 (§7): so are the copies the job staged and did not swap in, whatever ended it.

  • Start recovery (recoverEngineSwaps, in index.ts as soon as the pins are known, before the transcriber slot and the engine check resolve a binary): for every family's host build, the main build before its net, and only the exact names <os>.new and <os>.old (never a pattern: frozen in the first Kit release, it must leave the app-update plan's <os>@<pin>/ alone):

    • install complete → carry .old/cpu when the install has no whole net (main build), delete .new and .old;
    • else .new complete → move the incomplete install to .old, .new in, carry, delete .old;
    • else .old complete → move the incomplete install to .new, .old back, delete .new;
    • else delete both (an incomplete .old's cpu/ carried first).

    An incomplete leftover already at the spare name is deleted first, synchronously and marker first (its cpu/ net carried into the install folder before); it used to make the start give up, so a broken install folder stayed broken on every start (review round 1). When the spare name holds a WHOLE copy, the incomplete install folder holds no engine and is the one deleted (its cpu/ net carried into the copy about to move in first): two whole copies beside an empty install folder used to stay for good, every start and every job (review round 2).

    The cpu/ carry (start and job) moves the net when the install's cpu/ is not a WHOLE net by its own marker, deleting an incomplete one first (an empty cpu/ used to shadow the only net in .old, which then went). Before carrying out of a copy, a net swap left unfinished inside it (<copy>/cpu.new, cpu.old) is finished or rolled back there, so whole nets never go with the copy (review round 2).

    Renames run synchronously, once each: a refusal is logged as a warning and the layout left as it is, never worse (a refused .new → install falls back to a complete .old). Deletes run in the background. It never throws. A refused rename on a drive that cannot be written is where CE-F10 would hook (pointing the family's resolver at the complete copy); not built.

  • Gates: assertCommercialDrive fails a Kit with a leftover <extract_to>.new or .old beside any pinned build (the net's cpu.new / cpu.old included), and the Kit gate scripts' pre-flight (build-commercial-drive.{ps1,sh}) names it too, the knowledge-pack tools' folders included (their own list, held to the yaml by script-drift.test.ts). Its advice "start the app on this drive once" works for the builder's own OS only: the start recovers this host's builds.

Residuals. exFAT and an antivirus holding a new file are not measured here (the owed T8.5c walk on a real stick). The start's renames, and the job's own recovery's, are tried once, without retries (the start never waits on a lock): a refused one waits for the next start or job. With a junction at the install folder (dev kits only; a real Kit has no links there), the swap renames the junction itself to .old and moves a real folder in, and the main build's carry then moves cpu/ out of the junction's TARGET into the new folder: the target loses its net (on another volume the carry fails, EXDEV, and .old stays for the start). Deleting .old then unlinks the link and never enters it, so the old copy stays on the link's target, orphaned: no folder the app reads points at it any more. A dangling symbolic link at a leftover name is what the PowerShell Kit gate's Get-Item -Force check is for; this machine cannot create one (no symlink privilege), so only the junction case is exercised here. Not modelled: two hosts writing one drive at once.

Tests: engine-swap.test.ts (eighteen crash layouts run through the recovery, the incomplete spare, two whole copies beside an empty install, a net swap inside .old, a pin that adds a file and an empty cpu/ included; a job over two whole copies and a retry that plans the main build alone; the exact-names, marker-first, refused-rename and warning rows; in a job: the cpu/ carry and the marker inside .new at the first rename, stale leftovers, a held handle waited out on Windows, the rollback, the stranded case and its retry, a retry that fails after a keep-both, a job after a refused carry, a refused carry with both builds in one job, a first install, a net-only reinstall, a cancel before, during and just before the swap, no room with nothing touched or paused, the OS tar in .new); engine-extract-containment.test.ts (each failing archive as a first install and over an installed engine, which stays identical; a .new that cannot be deleted); engine-download.test.ts (the cancel rows, the part-way rows on .new); engine-consent-ipc.test.ts (the #532 reinstall keeps cpu/: the carry's regression row); install-audit.test.ts (noSpace with its byte counts); fs-retry.test.ts; archive-size.test.ts; assets.test.ts (the swap folders); commercial-drive.test.ts and script-execution.test.ts (the leftover refusals).

§7 #998 / #999 / #1000 amendment — complete copies, a cancel that waits for tar, stage before the pause (2026-11-22)

Three gaps in §6's staged swap that follow-ups wave 6 left open: "complete" meant the one program (#998), a cancelled extraction let the job go while tar could still run (#999), and the update paused the models for the whole unpack (#1000). Researched in follow-ups wave 7 (lane E) at c62a45f2. Code cites it as "In-app engine updates" §7.

The facts it rests on (DesktopDiT, Windows 11, Node 24; the b12110 copy is wave 6's own in-app update result):

  • The program is a shim. At b12110 llama-server.exe is 9.7 KB and imports llama-server-impl.dll, which with six more DLLs (26.5 MB in all, the stub included) is loaded by the OS loader. The CPU variants (14 ggml-cpu-*.dll), ggml-vulkan.dll and ggml-rpc.dll (62.6 MB) are loaded at run time by ggml.dll. The marker recorded the program alone, so no check knew the rest.
  • What a missing file does. A missing loader import ends the program with 0xC0000135, which #530 reports as damaged files and #532 repairs. A missing ggml-vulkan.dll is silent: the model runs on the processor, and the empty device list is remembered as "no graphics card". With every CPU variant missing the program prints no CPU backend found and exits 1, which was blamed on the model. Every missing whisper.cpp DLL is a loader refusal.
  • A file list per pin was rejected. b9849 lacks b12110's libomp.dll, so judging an older copy by the current pin's list would make every b9849 chat engine read "missing", and "Install voice engine" would reinstall it (#516's trap). The copy's own marker is the list (§6 review round 2).
  • tar ends 2–5 ms after the kill on Windows, and a folder a live process works in resists deletion (EBUSY). The mixed copy #999 feared is not reachable; what was left is a latch that meant "asked to stop", a misleading "files in use" on a quick retry, and no test of the F-33 kill path.
  • The stage reads and writes no install folder (only .new and the archive's move out), so the models can keep running through it. The synchronous flush blocked the event loop for one block per folder: 64–105 ms for the b12110 copy on NVMe (re-measured 205–268 ms on a loaded machine), seconds on a stick by estimate. FileHandle.sync() one file at a time keeps the longest gap at 16 ms (the timer granularity).

Decisions (owner, follow-ups wave 7 gate G-9, 2026-11-22): #998 slices b1 and b2 plus the no CPU backend found classifier line; the "incomplete" status in the UI (b3) is a follow-up; the sell gate verifies what a marker records and never requires a full list (no Kit is re-provisioned); #999 option A; #1000 option R with the async flush, and beforeReplace keeps refusing work that started during the unpack rather than waiting for it. The pre-spawn re-hash's gap is documented now (security-model.md), its hardening is a follow-up. (Done in #1012, 2026-11-22: the verifier re-hashes every key of the copy's own marker before the first spawn of a session; "Engine load failures" §13.)

As built (runtime-download.ts, archive-size.ts, assets.ts, commercial-drive.ts, runtime/engine-load.ts, fetch-runtime.{ps1,sh}):

  • The extractor waits for tar (#999). makeTarExtractor({ spawn, graceMs, goneBoundMs }) builds the default extractor (extractWithTar = makeTarExtractor()). A cancel or the deadline kills the child, SIGKILL after 2 s (on Windows both are TerminateProcess), and the extraction rejects only on the child's exit, or 10 s after the SIGKILL with a log line ("tar did not exit after it was killed"), so a tar wedged in kernel I/O still cannot pin the job (F-33). A kill that could not be delivered does not count as the exit. The job's status still reads cancelled at once; activeJob() stays the job until the extractor settles, so the job's own .new delete never races tar, and a retry in that window reads "already downloading". ExtractFn gained an optional log.

  • Three phases (#1000). run():

    1. the job's recovery, then download and verify every archive (unchanged);
    2. the room check (§6), then the leftover guard of EVERY step, before any step stages (so a net the job staged in <os>/cpu.new is never taken for a leftover), then stageStep per step in installOrder, with the models running and the gate open; a cancel is checked between stages and once after the last; the job then waits for queued deletes, outside the gate;
    3. holdEngineSpawns, beforeReplace (the update's busy re-check, the pause, the in-use check), a cancel check, then swapStep per step: the staged copy checked again, the swap (a cancel is honoured until its first rename), the carry, the verdicts dropped.

    A finally releases the gate and queues the deletes of the replaced copies and of every copy the job staged and did not swap in (a failure, a cancel, a refused pause, a stop part-way, an unexpected throw); a copy the swap kept as the only whole one is not on that list. So a download or unpack that fails or is cancelled (or hangs on a failing stick until the extractor's 5-minute deadline) never pauses a model and never holds the gate. Each FAMILY is all or nothing up to its swaps (round 1, below): a failed stage swaps nothing of its family (the cpu/ net with its main build), while the other families still install. The gate now covers the pause, a stale .old's delete, two renames, a move back and the carry, a few 12 s retry budgets per step, so its 6-minute bound is a real one (spawn-gate.ts). The statuses are unchanged ("Unpacking the AI engine…" while the model answers), and the "few seconds" the update notes promise are now true.

  • The stage's flush is asynchronous (#1000). flushToDeviceAsync (assets.ts) opens each file r+, FileHandle.sync(), closes it; flushFolder awaits it file by file before the marker is written, and the marker after. No fsyncSync runs in the stage.

  • The archive's own list (#998 b1). archiveMembers(path) (archive-size.ts) lists every member that is not a folder, files, links and hard links, from the same readers that size the archive (the zip central directory, the tar.gz headers). A listing that names a member in anything but plain ASCII is not used (how tar spells such a name on the disk is not knowable here), nor one that cannot be read (Zip64, an unknown format): the stage then skips the check with a log line ("could not be listed"). The stage reads the list before the extraction and, after the flatten, the left-out executables and the SEC-2 sweep, checks that every listed member is in .new: under the release folder the flatten emptied it lies at the root, a left-out one (llama-connect) is not expected (names compared without case), and an absolute name or a .. step is never expected (tar refuses those). A member that is gone fails the step incomplete with main.engine.extractFailed: the installed engine stays.

  • Every file in the marker (#998 b1). The stage hashes the required files and then every file the copy holds (installedFileKeys: files and links, a link by its own name, never followed; without the marker and the nested net folders cpu, cpu.new, cpu.old, which carry markers of their own; round 1 below says what a failed hash does). A real b12110 Windows copy records 52 keys (the archive's 53rd member is llama-connect, left out), a marker of 4,689 bytes instead of 162; hashing the 94.5 MB took 0.85 s here, now outside the pause. The verifier still looks up the program's key alone.

  • Each copy judged by its own marker (#998 b2). The check right before the swap reads the staged copy's marker: every key it records must be a file in the copy (engineFolderComplete); a marker with no map falls back to the required files; a copy whose marker went fails. The sell gate verifies every key a marker records on top of the required names: inside the install folder, a file, the recorded bytes (runtimeHashed); a key under another build's own folder (the cpu/ net under <os>/) is that build's to report. A marker that records only the program, as every Kit's does today, passes as before. Both fetch-runtime twins record every file of the install the same way (the marker, cpu/, cpu.new and cpu.old left out; script-drift.test.ts holds the twins to one list), and a re-run re-fetches an install whose marker records a file that is gone, in any mode, so the gate's "re-run fetch-runtime" advice works for a missing file.

  • no CPU backend found is damaged files. classifyLoadFailure (engine-load.ts) reads that line in a program's output as files-damaged, so the ladder stops blaming the model and the #532 repair is offered.

  • Kept: the exact <os>.new / <os>.old names, the marker's name and its binaries shape (Record<string, string>), and the start recovery's exact-name rule, which release 1 freezes (the app-update plan's W-67; W-30's install into a folder of its own reuses stageEngineInstall and so inherits the member check, the full marker and the waiting extractor). The status and the planner predicates did not change (engineStatus stays the bare program test, the default selection runtimeBinaryPresent), so "Install voice engine" still never reinstalls a chat engine. Older apps read a longer map: v0.1.65 and earlier ignore the extra keys; v0.1.66's recovery and leftover guard read it as a stricter "complete".

Residuals. A file a scanner takes days after the install is not shown in the status (b3, a follow-up: it needs copy in ten catalogs and an answer to "stop the model first" for a repair while a model runs on the processor). The pre-spawn re-hash covers the program only (security-model.md, a follow-up). The model downloader still flushes its weights synchronously (a follow-up). The job's own recovery, before its download, renames without the gate (it needs leftovers to act; a non-goal). An archive whose list cannot be read installs without the member check. A marker written before this change gains nothing until a reinstall, an update or a fetch-runtime run rewrites it. A plain install or reinstall checks the in-use flags at its start only, so a helper started during the longer unpack window runs the old copy, which the swap then moves to .old (the "let through early" residual of §6). Work started during the unpack refuses the update (main.engine.updateBusy), after a full download and unpack. The unpack can contend for the stick with a model the user starts meanwhile. A USB-stick walk of the outage gain is owed with the exFAT walk (T8.5c).

Round 1 (review, 2026-11-22). /code-review and an adversarial review found five gaps, all closed:

  • A scanner after the member check. A file taken right after its check was simply not walked, and one taken while the copy was hashed dropped the whole map, so the swap's check fell back to the program; both copies were swapped in. Now the hashed keys are the archive's members AND what the folder holds; when the archive could be listed, a member or a required file that cannot be hashed fails the stage incomplete (main.engine.extractFailed), and the no-map fallback stays for a listing that could not be read. What the marker records is checked once more after the flush, right before it is written. The member check also needs a file or a link where the archive lists one (a folder in its place fails).
  • macOS metadata. macOS bsdtar reads AppleDouble members (._name, __MACOSX/) back into extended attributes, so they never land on the disk there, and the member check would have failed every macOS install. isMacMetadataName (archive-size.ts) leaves them and a Finder .DS_Store out of the member list and the marker, and both fetch-runtime twins skip the same names. Whether the pinned macOS tarballs carry ._ members is unverified: none is on the build machine (owed on a Mac).
  • Links. A link to a folder or a dangling link is not recorded (logged), in the app and in both twins; hashing one used to drop the whole map. Only a required file that cannot be hashed still does, and only for an archive that could not be listed.
  • A queued delete. A job's staged copy that is not swapped in (its family failed) is whole and marked, and its delete waited in the queue while the next job's recovery could move it in without the gate or the pause. A job now waits for the queued deletes before its recovery, and such a copy loses its marker at once (unmarkEngineFolder), so a refused delete leaves nothing to roll in either.
  • Per-family atomicity. "Install the AI engine" on a bare drive fetches the chat and the voice engine; a voice engine that could not be unpacked kept the chat engine from installing (before #1000 the chat engine was swapped first). Now a step that fails (its leftover guard, stage or swap) fails its family, the other families still stage, pause (beforeReplace runs only when a family is left to swap) and swap, and the first failure is the job's, reported once at the end as for a job stopped part-way.

Accepted (no code): a FileHandle.sync() that hangs on a failing stick keeps the job busy until a restart (the models keep running; before #1000 the pause stayed instead). A helper spawned during a reinstall's unpack (no pause there) holds the old copy: Windows then refuses the swap's rename (filesInUse), POSIX swaps under it and the helper runs the old copy from .old until it stops. The pre-swap check's copy main.engine.binaryMissing ("the archive layout may have changed") reads wrong for a file a scanner took; rewording it is a follow-up.

Tests: extract-child.test.ts (a cancel waits for the exit; a child that never exits: SIGKILL at the grace, given up on after the bound; the deadline; an undelivered kill; the controls); engine-download.test.ts (a cancelled job stays busy until its tar has exited, through the default extractor; three phases: staged copies at the pause and none after a refused one; the models keep running while the archives unpack; a failed main stage swaps nothing and never pauses; a cancel during the unpack never pauses; part-way through a refused swap, for the main build and for the voice engine after a net-only reinstall; the marker records every file but llama-connect); engine-swap.test.ts (the gate held from the pause to the last swap only; a recorded file gone at the swap; with the OS tar: a listed member gone after the extraction, and every member checked through the flatten with every file recorded); engine-stage-flush.test.ts (FileHandle.sync() for every staged file before the marker, the marker after, no fsyncSync); engine-consent-ipc.test.ts (a failed unpack never stops the model; a failed swap still brings it back); install-audit.test.ts (no staged copy left after an unexpected throw at the gate); archive-size.test.ts (archiveMembers); commercial-drive.test.ts (a recorded file missing, modified or outside its folder); script-fetch-runtime.test.ts (both twins: every file recorded, never cpu/; a recorded file gone re-fetches); script-drift.test.ts (one skip list); engine-load.test.ts (the classifier line). Round 1: engine-stage-checks.test.ts (a listed DLL taken right after its check, while hashed, while flushed; a folder in a file's place; macOS metadata; links that are not files); engine-download.test.ts (each family installs when the other cannot be unpacked); engine-swap.test.ts (a job waits for the queued deletes; an unswapped copy is un-marked at once); archive-size.test.ts (metadata left out); script-fetch-runtime.test.ts (metadata, links on POSIX); script-drift.test.ts (the twins' metadata, link and order rules).

Internationalization — design record (Phases 39–42)

Formerly docs/i18n-plan.md (condensed here at the Phase-42 closeout, 2026-06-13, per the CLAUDE.md doc lifecycle rule; the full original working paper — phased plan, per-phase as-built notes, original research — is in git history: git show 5059ed8:docs/i18n-plan.md). Phases 39–42 made the entire user-visible surface available in English and German, selectable in Settings → General (default: follow the OS), with the pre-unlock gate already in the right language: no new runtime dependency, no network, no behavior change outside copy. The UI languages wave (2026-11-11/12) added Spanish, French, Italian and Russian, and the second UI-languages wave (2026-11-13) Dutch, Polish, Turkish and Ukrainian, so the interface has ten languages: English and German, natively reviewed, and the other eight, machine-drafted and checked by a second model, with no native-speaker review yet (D-L12); still no dependency and no network. § numbers below are preserved from the plan — code comments cite them as "i18n record §N" (the German style rules of §3.5 live in design-guidelines.md "German microcopy", the other languages' in the sections after it).

Decisions (all LOCKED as built)

ID Decision
D-L1 Hand-rolled typed i18n module in shared/i18n/ (flat keys, {name} interpolation, .one/.other plurals); no new dependency. de.ts is typed Record<keyof typeof en, string>, so typecheck enforces catalog parity — removing a key is a compile error. i18next/react-intl were rejected: async resource loading + ICU machinery en/de don't need, and a provider-suspense would have churned hundreds of green synchronous tests. Amended 2026-11-11 (UI languages wave, D-L9): plurals are chosen per language. Each registry entry carries a plural rule and the plural forms its catalog must provide. English and German keep the exact n === 1 rule (.one for exactly 1, else .other), so their output is unchanged; a language with more forms uses the built-in Intl.PluralRules and carries the extra forms as <base>.few / <base>.many. If a catalog lacks the selected form, .other is used. Still no dependency. Every registered catalog is typed against its own required key set, so parity stays typecheck-enforced for every language.
D-L2 AppSettings.uiLanguage: 'system' | 'en' | 'de', default 'system' (theme precedent); a de-prefixed OS locale ⇒ German, else English — including the bare tag 'de' (the R-L1 finding below). Amended 2026-11-11: the setting accepts any registered language (D-L9). 'system' follows the OS locale's primary subtag (lower-cased, split on - or _) when that language is registered, and is English otherwise; a tag that merely begins with a registered code (deu, frr-DE) does not match. A stored value this build does not know (for example a language added by a newer build on a shared drive) resolves like 'system'. Amended 2026-11-12 (UI languages wave, PR-B): with Spanish, French, Italian and Russian registered, an OS locale in any of them resolves to that language (an fr-FR system gets French). The hint under the picker (settings.language.hint) names no languages, so registering one never makes it false (UI-languages owner call D-12 (a)): System follows the operating system's language when HilbertRaum offers it, and English otherwise. Amended 2026-11-13 (second UI-languages wave): the same holds for Dutch, Polish, Turkish and Ukrainian. Only the primary subtag counts, so nl-BE gives Dutch and uk-UA Ukrainian, while ua (Ukraine's country code, not a language code) and the three-letter codes ukr and nld give English.
D-L3 Pre-unlock language: renderer = the hilbertraum.uiLanguage localStorage mirror → navigator.language fallback; main = a cached language from app.getLocale() until settings become readable (post-unlock / plaintext startup), refreshed on uiLanguage patches. Amended 2026-11-11 (UI languages wave, UI-languages owner call D-17 (a)): before unlock the two can differ (the mirror holds the chosen language, app.getLocale() the OS's), so the gate (WorkspaceGate.tsx) no longer shows main's message for a failed unlock or create. It renders the failure from its reason code through its own t(), with the same main.workspace.* key main emits, one table per call; typecheck makes each table cover every reason. Main's message shows only for a reason a table maps to null (main never sends it for that call; the one that does occur is create's free-text refused, the vault's own sentence, which has no catalog key) and for a reason the tables lack. Main's too-short refusal never reaches the gate, which applies the same floor (MIN_PASSWORD_LENGTH, shared/types.ts) before it sends. Amended 2026-11-12 (review of PR #801): the two tables live in shared/workspace-failure-keys.ts (the gate imports it; main doesn't read it), and tests/integration/workspace-ipc.test.ts drives main's real unlock and create handlers into every branch the gate can receive (all but create's too-short refusal, which the gate's own floor keeps from being sent), in every registered language, checking main's message against the gate's key (a null entry must be free text: the same in every language and no catalog value), so a key changed on one side alone turns red. Amended 2026-11-20 (follow-ups wave 4, #807; owner calls G-6 A + A2 and G-8): no call sends free text any more. Create's two vault refusals are typed (WorkspaceExistsError, PlaintextNotAllowedError) and answer their own reasons, workspace_exists (main.workspace.exists) and plaintext_not_allowed (main.workspace.plaintextNotAllowed); the IPC maps them by class (instanceof or err.name), and the `/not permitted
D-L4 Persist canonical English, translate at display: an exact-match display map over the finite static persisted set (renderer/lib/displayMap.ts). Keeps the scanDetected contract and pre-i18n rows valid; persisted copy is retroactively language-switchable.
D-L5 Ephemeral main→user strings localize at emission via tMain() + the cached language; the IPC error transport (friendlyIpcError) is unchanged.
D-L6 LLM prompts stay English and unchanged (Phase-29 benchmark comparability; models follow the question's language). Task-output language = a future feature; documented in known-limitations.md ("Internationalization").
D-L7 German address form = informal „du" (lowercase mid-sentence), a deliberate brand choice (user decision 2026-06-13); glossary pinned in de.ts. Human review of the German copy gates the wave (the user is the reviewer). Amended 2026-11-12 (UI languages wave): the address form is chosen per language (UI-languages owner call D-3): Russian formal «вы» (lower case mid-sentence), French formal «vous», Spanish informal «tú», Italian informal «tu». Each language's glossary, typography and length rules are its design-guidelines.md section ("Russian/French/Spanish/Italian microcopy", after "German microcopy"), and the glossary is pinned as the comment on top of its catalog file, as in de.ts. On a fixed-width surface such as the rail, a word that does not fit is replaced by a shorter synonym, never an abbreviation (UI-languages owner call D-10 (a)). Those four catalogs are machine-drafted and checked by a second model; no native speaker has reviewed them (nativeReviewed: false, D-L12). Amended 2026-11-13 (second UI-languages wave): Dutch informal «je», Polish informal «ty» (the imperative on buttons and in instructions, impersonal past forms in the app's messages, so nothing needs the user's gender), Turkish «siz» (the short polite imperative in sentences, the bare imperative on buttons) and Ukrainian formal «ви», each lower case mid-sentence. Their rules are the "Dutch/Polish/Turkish/Ukrainian microcopy" sections after "Italian microcopy", each glossary pinned on top of its catalog file; these four catalogs are machine-drafted and checked by a second model too, with no native-speaker review (nativeReviewed: false).
D-L8 Default-English + synchronous t() keeps the ~323 pre-existing English copy assertions green; migrated assertions reference the en catalog instead of re-typed literals. English values for shipped strings stay byte-identical to the pre-i18n literals.
D-L9 Language registry (2026-11-11, UI languages wave). shared/i18n/languages.ts holds UI_LANGUAGES, one entry per interface language, English first: code, nativeName, nativeReviewed, evidencePack, plural, pluralCategories. UiLanguage, UiLanguageSetting, isUiLanguage, isUiLanguageSetting, the catalog types and locale resolution are derived from it; nothing else decides which languages exist (CATALOGS and the pack-language table name them and are compile-checked against the registry). pluralCategories is pinned in the registry rather than read from ICU at runtime, so an ICU update cannot change which keys a catalog needs without a code change; a test compares the pin with the running ICU. There is no completeness tier: every registered language is complete and typecheck-enforced (owner call 2026-11-11). A language whose evidencePack is false does not carry the packExport.* keys, which render only inside an evidence pack.
D-L10 Every registered catalog is required (2026-11-11, UI languages wave). UI-languages owner call D-2 (a): every registered language's catalog is complete and typecheck-enforced; there is no partial or pending tier. D-L1's parity mechanism is extended per language: each catalog is checked against UiCatalog<code> by the CATALOGS map (index.ts), and a new language's file is declared UiCatalog<'xx'> (de.ts keeps the equivalent Record<keyof typeof en, string>); the type's key set is every English key plus one <base>.<form> key per plural base for each form in the language's pluralCategories beyond .one/.other (Russian .few and .many; French, Spanish and Italian .many). A language whose evidencePack is false has no packExport.* key at all, the extra plural forms of a packExport.* base included (UI-languages owner call D-14 (a)): they render only inside a pack, which stays English or German (D-L11). The runtime parity test in tests/unit/i18n.test.ts is the belt to the type: per registered catalog it checks the same key set and adds what a type cannot say, no empty value and the English placeholders per key (a form English lacks is compared with its base's .other). Why: a partial catalog shows two languages on one screen, and a pending list needs a release check. The cost is that every pull request that adds or changes UI text writes it in every registered catalog. Typecheck checks presence, not freshness: a changed English value does not flag translations that went stale (true for German since D-L1). Amended 2026-11-12 (UI languages wave, PR-B): the first languages registered under it are Spanish, French, Italian and Russian (es.ts, fr.ts, it.ts, ru.ts; 2,296 keys each for the three with one, many and other, 2,358 for Russian with one, few, many and other, against English's 2,337; no packExport.*). None of the four is exported from index.ts (only en and de are, as before): a named it export would shadow vitest's global it in any test that imported it, so tests read catalogs through catalogOf(code) (tests/helpers/i18n-catalogs.ts). Amended 2026-11-13 (second UI-languages wave; second UI-languages wave owner call G-1 (a): the rule stands with ten languages): Dutch, Polish, Turkish and Ukrainian (nl.ts, pl.ts, tr.ts, uk.ts): 2,234 keys each for Dutch and Turkish, whose forms are English's one and other, and 2,358 each for Polish and Ukrainian with one, few, many and other (English's 2,337 less the 103 packExport.* keys, plus a .few and a .many for each of the 62 plural bases outside packExport.*). Dutch and Turkish use their CLDR rule too (cldrPlural), which picks .one for the count 1 alone, as English's rule does. The four are declared UiCatalog<'xx'> and, like the first four, not exported from index.ts. A pull request that adds or changes UI text now writes it in ten catalogs.
D-L11 Evidence-pack language (2026-11-11, UI languages wave). Packs are written in English or German only (UI-languages owner call D-5 (b), 2026-11-11). packLanguageFor(info) (shared/evidence-review.ts) maps a UI language's registry entry to the pack language: the language itself when its evidencePack flag is set, English otherwise. The export panel (ReviewSummaryView.tsx) sends that language, and main's boundary (resolveEvidencePackOptions) keeps only a pack language (isPackLanguage, else English). The pack languages are EvidencePackLanguage ('en' | 'de'); a type row in evidence-pack-model.test.ts holds it equal to the registered codes whose evidencePack is true, and the pack renderer (render-html.ts) takes only that type, so a language without the packExport.* keys (D-L9) never reaches it. When the pack language differs from the UI language, the export panel says so in one full sentence per pack language (review.export.packLanguage.en / .de, chosen by packLanguageLineKey): no {language} placeholder and no nativeName, because a language name inside a sentence needs grammatical case and lower-casing in Russian, French, Spanish and Italian ("на английском", "en anglais"). With only English and German registered the line never showed; since Spanish, French, Italian and Russian are registered (2026-11-12), and Dutch, Polish, Turkish and Ukrainian (2026-11-13), the export panel of each of their interfaces shows the English-pack line (.en) in that interface's language, and the German line still has no reader (only a German interface writes German packs).
D-L12 Native-review status (2026-11-11, UI languages wave). Each registry entry carries nativeReviewed: true when a native speaker has reviewed the catalog (English; German by the owner, D-L7), false for a machine-drafted one. UI-languages owner call D-4 (c), 2026-11-11: a machine-drafted catalog ships with no notice in the app; the flag records the status for a later native review and for known-limitations.md. Nothing renders from it today.

UI-languages owner calls (2026-11-11/12). This record and code comments cite the UI languages wave's decision gates as "UI-languages owner call D-N"; these are not the D-numbers used elsewhere in this file. D-2 (a): every registered catalog is complete and typecheck-enforced · D-3: the address form per language (D-L7) · D-4 (c): a machine-drafted catalog ships with no in-app note · D-5 (b): evidence packs stay English or German · D-6 (a): the language picker is a native <select>, System first and then the registered languages in registry order (English, Deutsch; then Español, Français, Italiano, Русский; since 2026-11-13 the order of G-3 below; since #808, 2026-11-15, it saves after a pause, open-issues wave owner call G-6 below) · D-7 (a): System follows the OS into any registered language · D-8 (a): English and German keep the exact n === 1 plural rule · D-10 (a): a shorter synonym, never an abbreviation, where a fixed-width surface is too narrow · D-11 (a): "(1 core)" on a single-core machine · D-12 (a): the System hint names no languages (D-L2) · D-13 (a): the picker's System label is translated · D-14 (a): no packExport.* keys in a catalog whose language writes no packs · D-16 (a): localizing a bundled skill's title and description does not bump its version · D-17 (a): the lock screen renders unlock/create errors in its own language. 2026-11-12: a plural form may add {count} where the language's one isn't exactly 1, and must when its plural form shows the number; English and German plain number keys that read wrong at exactly 1 ("1 sections scanned", "I read 1 transactions"; the NON_GRAMMATICAL groups in tests/unit/i18n.test.ts that say so) are a follow-up. Amended 2026-11-14: that follow-up is done; the eighteen such keys now state their count label-first in English and German too, and only chat.speed.line ("1 tokens") is left as it was (open-issues wave owner call G-5, §5).

Second UI-languages wave owner calls (2026-11-13). This record and code comments cite the second wave's decision gates as "second UI-languages wave owner call G-n". G-1 (a): every registered catalog stays complete and typecheck-enforced with ten languages (D-L10) · G-2 (a): one pull request, one commit per language · G-3 (a): the picker order English, Deutsch, then the other names written in Latin letters in alphabetical order (Español, Français, Italiano, Nederlands, Polski, Türkçe), then the Cyrillic ones (Русский, Українська) · G-4 (a): D-4 (c), D-5 (b), D-7 (a), D-10 (a), D-16 (a) and the Latin unit symbols carry over unchanged · G-5: the three text filters (Documents names, AI Model search, review evidence) fold case with one shared helper, then renderer/lib/textFold.ts, since #818 shared/text-fold.ts (§5) · G-6: the lock screen's edition line "HilbertRaum Lite" is marked lang="en", so CSS capitals never give it a Turkish «İ» · G-7: user project names that CSS shows in capitals take the interface language's casing (a known limitation) · G-10: so does a document's own section heading in the preview (recorded with G-7) · G-12: conversation search and keyword retrieval keep their plain lower-casing (fts.ts; a known limitation and a follow-up; changed 2026-11-14 by #818, open-issues wave owner call G-8) · G-8, G-9, G-11: the real-app check's remaining layout and wording findings accepted as recorded, or collected for follow-up ("Second UI-languages wave QA" below).

Open-issues wave owner calls (2026-11-13 to 2026-11-15). This record and code comments cite the decision gates of the open-issues wave (the i18n follow-ups the two language waves filed, and two older issues) as "open-issues wave owner call G-n", or "open-issues wave G-n" where a line is short; they are not the second UI-languages wave's G-numbers above. G-1, G-2: the wave's scope and the order of its pull requests, with #804, #805, #806, #807 and #812 in one; G-1 also took #632's option A: on What Changed?'s fall-through turn the fence carries paragraph 1 only, the stamp kept; at the code review (owner round WB2-1) the owner limited it to the bundled skill, so a user compare skill keeps its whole fence (§44 SK-3b); #831 (follow-ups wave 4 owner call G-9, 2026-11-20) extended the cap to the four bundled whole-document skills, the needle downgrade included, bundled only again (§44 SK-3b) · G-3 (a): in the Spanish, French, Italian, Dutch, Polish, Turkish, Russian and Ukrainian catalogs a figure or a placeholder and a unit symbol (GB, MB, KB, B, MB/s, tok/s, ms, s) are joined by U+00A0, the Dutch, Polish and Ukrainian rules against a no-break space allow it in exactly that one position more, and a size built in code takes the same space (unitJoin, §5) · G-4 (a): label-value joins and percent signs come from the catalog patterns common.labelValue and common.percent (German then shows "15 %" in the context meter and the transcribing badge, with a no-break space since the real-app check, below), the licence link sits on a line of its own, raw numbers take the language's figures (the invoice tax rate excepted since the code review, below), the copied reports keep their plain code-built joins and the units their Latin symbols, and the brand link's tooltip and the Spain pattern of Spanish figures stay as they are (§5) · G-5 (a): the English and German sentences that read wrong at exactly 1 put the count after a label, chat.speed.line excepted (§5) · G-6 (a): the language select in Settings → General saves about half a second after its last change (LANGUAGE_SAVE_DELAY_MS, 500 ms), at once when it loses focus and when the tab unmounts, with the last choice kept; every save that goes through applies the language, mounted or not, so a save flushed by leaving the tab still switches the app, <html lang> and the mirror (§3.2); one "Saved" toast, in the new language, and none once the tab is gone; a hidden, disabled first option with the System text and the value '' is rendered only for a stored value this build does not register, so choosing the real System is a change and saves 'system', and nothing is written before a choice (SettingsScreen.tsx); by owner call (2026-11-15) the hint under the select (settings.language.hint) keeps its "Changes apply right away." sentence in all ten catalogs, since half a second reads as right away and the sentence's point is that no restart is needed · G-7 (a): a support report copied in any language but English and German carries an English copy in the same paste (§5) · G-8 (a): the keyword-search query is composed (NFC) and lowered without a locale, a capital «İ» to a plain "i" (lowerCaseNfc, shared/text-fold.ts), and a word holding «ı» is also searched with each «ı» written as "i"; the index, its triggers and the stored text stay as they were (rag-design.md §11 "Keyword index"); the filters' foldCase composes first; every project list orders its names with an Intl.Collator of the interface language instead of the system's locale or SQL's code-point order: the conversation list's sections, the Documents rail (active and archived), the "Choose a project" dialog, the chat scope picker and a row's project chips (built-ins first). One renderer helper, renderer/lib/collation.ts (nameCompare, inNameOrder); main's listCollections order is unchanged (§5, #818, #828) · G-9 (a): three CSS rules for the 880×600 minimum window (#803), each written once its cause was confirmed in the running app: the Documents filter's icon padding wins over .text-input (.text-input.docs-filter-input), the chat column has no min-content floor (.chat-main { min-width: 0 }), and the rail scrolls with no visible scrollbar (.sidebar { overflow-y: auto; min-height: 0; scrollbar-width: none }); the dialog title's line height, the button font and the document rows stay out, and the composer footer did too until the owner rounds below (design-guidelines.md §3, §12.1, §16) · G-10 (a): the English and German copy fixes of #805, each changed sentence read by the owner before it was translated; its item S3, "(12 cores)" breaking inside, was left to #803's ten-language check and landed with it (below) · G-11 (a): the small-talk check keeps every letter and digit of any script and knows short greeting, thanks and closing lists for Spanish, French, Italian, Dutch, Polish, Turkish, Russian and Ukrainian (skills/vocabulary.ts); the router recognises the document chat's two example chips in every catalog (§3.3 Rule 3); its English compare words are bounded by letters, digits and "_" instead of the ASCII word boundary, so «différend» (a dispute) no longer reads as "diff", and the French compare words are listed (analysis/router.ts COMPARE_RE); the Italian and Dutch "alle" and the Polish "list" partial labels and the knowledge-pack language detector stay as they are (known limitations) · G-12 (a): one generic lead, "This file couldn’t be added.", above an unrecognised error on a failed document row and in the chat's attach banner (§3.3 Rule 1; amended at the code review, below). Made while the catalog changes were built (2026-11-14): the Spanish review decision labels put the decision in parentheses («Revisado (respaldado)»), because the Spanish style guide has no spaced dash and a colon inside the label doubled the colon of the review summary's label-value join · the internet switch is labelled "Allow internet access for downloads and updates", without "model", since it also gates the engine, the knowledge-pack tools and the OCR files, and the two sentences that quote it follow · the auto-skill setting's hint (skills.autoFire.hint) says the app can give the answer again without the skill, as the auto-skill tooltip does · the licence link, now on its own line, starts with a capital ("Read the license") · the Privacy tab's "internet access is enabled" line names the OCR files too. Made at the real-app check (2026-11-14): German's common.percent writes U+00A0 before the sign, as Spanish and French do, because a plain space let "19" wrap above "%" in the context meter at 880×600 (§5). Made at the code review (2026-11-14), amending G-4 and G-12: the invoice answer's tax rate prints as the plain figure again, with a dot like the amounts beside it, since a skill answer's figures print with a dot in every language (§5) · the chat's attach banner leads with chat.attach.failed, which names the file, and docs.failed.lead, now "This file couldn’t be processed.", serves the failed document row alone (§3.3 Rule 1) · every German percent after a figure takes U+00A0, not only common.percent, and a German typography rule refuses {x}% and {x} % (§5). Made at the owner rounds while #818 and #809 were built (2026-11-14), amending G-8 and G-11: the search residuals are accepted as built: a typed «isi», «Isı» or «ISI» does not find «ısı», a typed «kır» finds «kir» but a typed «kir» does not find «kır» (the filters match both ways), and text stored with a separate Cyrillic mark is found by neither spelling (known limitations) · English "a" and "lot" and German "passt" are no single small-talk fillers any more, since «A lot?» is Polish for "and the flight?", «A Nice ?» French for "in Nice?" and «Passt alles?» asks whether everything is right; "thanks a lot" and its acknowledgements, and "passt", "passt danke", "passt super", "danke passt", "vielen dank passt", "ok passt" and "super passt", are whole-message forms, the bare question «Passt so?» is none, and «Alles gut?» and "all good?" stay small talk · the French compare family is listed: «différence(s)», «différent(e)(s)», «diffère(nt)» and «différencier» with its forms route to compare, while «différend», «différé(e)(s)», «différer», «différemment» and «différentiel(le)(s)» do not (COMPARE_RE). Made at the code review of #818 and #809 (2026-11-14), amending G-8 and G-11: a search word holding «ı» gets only the spellings stored text can have, at most two (the first «ı» as "i" when the word starts with «ı», as a capital first letter is stored, and every «ı» as "i", as capitals are), not every mix, and with no limit on the number of «ı» · a search word keeps the marks inside it, so a mark with no one-character form, such as a Russian stress mark, no longer cuts it, and the index drops that mark from the stored text too (rag-design.md §11 "Keyword index") · eight more English and German whole-message forms: "thanks a lot bye", "thank you a lot bye", "ok thank you a lot", "alles klar passt", "klar passt", "passt vielen dank", "passt danke schön" and "passt danke dir". Made with them, inside G-11: the small-talk check folds «ı» to "i" on both sides (foldCase), so Turkish typed in capitals is recognised; the router composes the question (NFC) once before every check; the two chips still count with a closing ".", "!", "?" or "…"; and the quote-frame reader passes over an opening quote that nothing closes. Made while #808 was built (2026-11-15), inside G-6: a refused save shows the stored language again with the settings.saveFailed toast, and an older save's reply never takes a newer pending choice off the select. Made at the code review of #808 (2026-11-15), inside G-6: a choice equal, when its save would run, to the language the store holds, or will hold once the saves still unanswered land, saves nothing and toasts nothing (a pick and back within the pause, or a pick again of a language whose save is still unanswered); and a refusal's toast is in the language shown when the refusal arrives. Made at the owner rounds while #803 was built (2026-11-15; code comments cite them as "open-issues wave owner round W5-1" to "W5-6"), widening G-9 and G-10: W5-1, the rail's items never shrink (.sidebar > * { flex-shrink: 0 }), since the global button { min-height: 24px } let the brand, the lock button and the indicator squeeze to 24 px before the rail scrolled, and the "Skill: … ▾" trigger stays on one line (.skill-picker-trigger, SkillPicker.tsx), since with the chat column's floor gone "Skill: No skill" wrapped to three · W5-2, a width cap with an ellipsis on that trigger, measured in the running app and replaced by W5-3, since no cap from 35 to 50 % met every measured condition at 880×600 and the 45 % cap left text outside its box in 41 of 60 cases · W5-3, the composer footer wraps (flex-wrap: wrap; row-gap: 4px), so a control that doesn't fit moves to the next row, and a skill name longer than a whole row ends in "…" (.skill-picker-label; the button's name keeps the full title) · W5-4, "(12 cores)" stays together on the Performance tile and in Settings → Diagnostics (keepTogether, renderer/i18nNodes.tsx, puts the core count in a .nowrap span; the Copy reports are unchanged), and the Turkish rail label «Yapay zekâ modeli» keeps its two lines · W5-5, the French and Russian document-mode placeholders (chat.placeholder.documents) are shorter, since at 880×600 with the conversation list open, once the chat column could shrink, they wrapped onto a hidden second line of the empty composer and Chromium gives a textarea placeholder no ellipsis, and the trigger wraps as one group with its ⓘ and ✕ (.skill-picker-group), the suggestion hint outside it · W5-6, the rail never scrolls sideways (.sidebar { overflow-x: hidden }), so a label too wide for the column is clipped at its edge. Made with them: inside G-9, the trigger may give way inside its group, so a name longer than a whole row still ends in "…" with ⓘ and ✕ inside the footer at their size; and the Russian value is «Вопрос по документам…», since the translation check found that «о документах» in the value the round named reads as a topic, where the glossary and the mode label say «по … документам».

§3.1 The i18n module

apps/desktop/src/shared/i18n/ (importable from both processes): en.ts is the source-of-truth catalog (~600 keys at the Phase-39 record; ~1,700 by 2026-08 — #151 AR-2; MessageKey = keyof typeof en), de.ts the typed German catalog with the §3.5 glossary pinned on top, and es.ts, fr.ts, it.ts and ru.ts (2026-11-12) and nl.ts, pl.ts, tr.ts and uk.ts (2026-11-13) the Spanish, French, Italian, Russian, Dutch, Polish, Turkish and Ukrainian catalogs, each with its glossary pinned on top the same way (D-L7). languages.ts is the registry (D-L9) with the plural rules, the catalog types (CatalogFor, UiCatalog<code>) and two pure cores that take the registry data as arguments, pluralKeyFor and resolveUiLanguageIn. index.ts holds the explicit CATALOGS map (leaving a registered language out is a compile error) and exports t(lang, key, params?) (synchronous lookup + {name} interpolation; unknown key/missing param falls back to English — never a crash), tCount(lang, keyBase, n, params?) (the form the language's plural rule selects for n; English and German: .one for exactly 1, else .other; a missing form falls back to .other, and the English fallback uses the English form for the same count), and resolveUiLanguage(setting, osLocale). A new language's catalog is declared UiCatalog<'xx'>: a missing key, a misspelt key or a plural form the language does not have fails npm run typecheck. All catalogs are static imports, bundled into the main, renderer and preview builds (220–340 KB of source per language, the Cyrillic ones largest; each of the second wave's four added about 243 KB to the main and to the renderer bundle; the tools build tree-shakes them).

§3.2 The setting and its resolution

  • Renderer: renderer/i18n.tsx — I18nProvider/useT() re-resolve when settings load and when the Settings language select's save returns (since #808 its own delayed save, not the shared settings patch; open-issues wave owner call G-6), set document.documentElement.lang, and mirror the resolved language to localStorage('hilbertraum.uiLanguage') (written only when a real setting resolves, never from the pre-unlock guess). The gate reads the mirror, falling back to navigator.language — a first run on a German OS shows a German gate with zero stored state; a user who chose the non-OS language gets it back at the next gate render. The mirror is a UI preference, not user data (the ChatScreen localStorage precedent).

  • Main: services/i18n.ts holds the cached resolved language — initialized from app.getLocale() after whenReady, updated when settings become readable and inside updateSettings(). Every main-side emission calls tMain(key, params). No new IPC.

  • The setting's write gate (updateSettings) and the mirror read accept exactly the registered languages, through the registry guards isUiLanguageSetting / isUiLanguage (D-L9). The settings read path stays tolerant on purpose: a stored value this build does not know (a newer build's language on a shared drive) is kept as it is and resolves like 'system' in main and in the renderer, so going back to the newer build still finds the choice.

  • R-L1 locale finding (measured on de-AT Windows 11, Electron 37): app.getLocale() returns the bare language tag 'de' (Chromium UI language — not always a full de-DE tag; app.getSystemLocale() gives 'de-AT'), and the renderer's navigator.language matches. ⇒ resolveUiLanguage accepts bare 'de' as well as de-*/de_* prefixes. The vitest environments are locale-independent (jsdom pins navigator.language to en-US; unit tests pass explicit locales) — never write a test that reads the real OS locale. Re-measured 2026-11-12 (Electron 43.8.6, the same de-AT machine, six languages registered): Chromium's --lang=<tag> switch sets both. With ru, fr, es or it, app.getLocale() and navigator.language return that bare tag, and the UI and main's emissions follow; es-419 stays es-419 and resolves to Spanish, pt-BR stays pt-BR and resolves to English, de-AT comes back as de, en-US as en-US; with no switch both are de. app.getSystemLocale() is de-AT in every case (it reads the OS, not the switch). Renderer and main Intl.PluralRules categories equal the registry's pluralCategories pins for all six languages (ICU 78.2). The dev app passes the switch to Electron only as npm run dev -- -- -- --lang=<tag> (electron-vite's CLI overwrites ELECTRON_CLI_ARGS); the production build takes it as npm run start --workspace apps/desktop -- --skipBuild -- --lang=<tag>. Re-measured 2026-11-13 (the same machine and Electron, ten languages registered, setting System; app.getSystemLocale() is de-AT in every leg):

    --lang navigator.language app.getLocale() UI language
    nl-NL, nl-BE nl nl Dutch
    pl-PL pl pl Polish
    tr-TR tr tr Turkish
    uk-UA uk uk Ukrainian
    en-US en-US en-US English
    de-AT de de German
    none de de German

    <html lang>, the rail and a main-process message followed the UI language in every leg. Chromium ships no nl-BE locale (its locale files have nl), so that leg reports plain nl and cannot show the region subtag at work; the resolver's unit rows (nl-BE, pl-PL, tr-TR, uk-UA) do. Renderer and main plural categories and number formats for the four languages equal those measured in Node (ICU 77.1; Electron has 78.2): no difference. --lang does not stand in for a Turkish operating system in one respect: under --lang=tr-TR the renderer's Intl default locale is tr, yet 'Invoice'.toLocaleLowerCase() still returns "invoice", so the Turkish-locale fault the shared fold removes (§5) is shown only by the jsdom rows, which fake a Turkish default locale.

§3.3 The two-rule boundary for main-process strings

  • Rule 1 — persist canonical, translate at display (D-L4). Anything written to the DB or settings keeps being written as the exact English catalog value via an explicit t('en', …) at the persist site: the parser-failure constants (seven at this record; ten by 2026-08 — the audio + OCR waves added three, and the evidence-review default title main.evidenceReviews.defaultTitle joined the same persist-canonical set — #151 AR-3) (incl. PDF_SCAN_DETECTED_MESSAGE, whose exact-match derives scanDetected — the OCR offer), source-missing/interrupted ingestion messages, NO_DOCUMENT_CONTEXT_ANSWER + REINDEX_NEEDED_ANSWER (persisted into messages.content), DOC_TASK_BUSY_MESSAGE (recognized renderer-side via includes), the buildWarnings strings (persisted in settings.lastBenchmark: four exact-match + the interpolated warnVeryLowTokens (#52) and warnSlowRead (#110)), and the default conversation title 'New chat' (exact-matched by maybeSetTitleFromFirstMessage). The renderer translates at display via the exact-match reverse lookup localizeServerCopy() over DISPLAY_MAP_KEYS — the en.ts persist-canonical section is a data contract: editing a value breaks the match for already-persisted rows. Interpolated persisted constants are reverse-matched by template regex instead (INTERPOLATED_MAP_KEYS). Unknown strings (e.g. raw parser-library errors) render as-is by design. Amended 2026-11-14 (open-issues wave, #807; open-issues wave owner call G-12; the two leads as the code review settled them the same day): a failed document row (DocRow.tsx) shows such a string under a translated lead, docs.failed.lead ("This file couldn’t be processed.", true for a failed import, re-index or text recognition alike), and the chat's attach banner (ChatScreen.tsx) under its own lead, chat.attach.failed ("Couldn't add {name} to this chat."), which names the file; each keeps the string itself as the detail line, so the row and the banner say in the interface language what happened. classifyServerCopy() returns the display text and whether the map recognised the string (the exact map, the five interpolated families or the doc-task-busy substring), and only a string it does not recognise gets a lead; localizeServerCopy() keeps its signature and returns the text alone. Stored data is unchanged, so rows stored before the change get the lead too. Amended 2026-11-20 (follow-ups wave 4, #807; owner call G-7 E-a): four more surfaces show a failed call's or a library's own words as the detail under a translated lead. The file translation's banner reads a failed source document's stored error exactly as DocRow does (classifyServerCopy: a recognised message alone, any other under docs.failed.lead; the session keeps that error apart from doc-task and IPC messages, documentError). The review's save line always leads with review.autosave.error and shows the failed write's message after it (SQLite's "database is locked" says nothing about the edit), and a review that fails to open leads with review.openFailed. The evidence-pack export error leads with review.export.failed ("The evidence pack export did not finish."), true for every failure, including the named outcome whose file was saved but not recorded, which review.export.error ("No file was written") is not; a refused flush keeps review.export.error alone. These three take no classifyServerCopy verdict: their messages are main's tMain text or a library's, which the persist-canonical map never holds, so the lead is always shown. Everywhere else an unknown string still renders as-is: a failed IPC call's own message (friendlyIpcError(e), which strips only the transport prefix) wherever a screen reports a failed action, on its own, with no lead. That is the Documents screen (21 sites), Chat (16), the AI Model screen (9), the knowledge-pack panel (5), Performance (3), the OCR and knowledge-pack tool installs (3 each), the preview and article modals, the sources disclosure, dictation, and the file translation's own calls (fileTranslateSession.ts failWith(friendlyIpcError(e)): an import, start, poll or result read that fails, as opposed to a failed source document). A lead there needs copy per action, left open (counts at 88da1bc5). The Documents banner for a failed summary, translation or OCR task gets app text only: the task manager passes its own messages on and replaces anything else with its generic failure. A hygiene test pins DISPLAY_MAP_KEYS + INTERPOLATED_MAP_KEYS ↔ the persist-canonical section key-for-key.
  • Rule 2 — emit localized (D-L5). Anything ephemeral (IPC guard throws, task-status errors, download/policy refusals, preflight problems, runtime:notice, dialog titles + picker filter names) localizes in the main process at emission via tMain(). Transient messages interpolate values and cannot be exact-matched — that is why display-mapping was rejected for this class.
  • Rule 3 — code that recognises localized emissions iterates every registered language (2026-11-11, UI languages wave). A Rule-2 emission is in whatever language main had cached when it was thrown, and that can differ from the language in force when the text is inspected (the setting can change in between, and main and the renderer resolve separately). So code that identifies an emission by its text compares against the catalog value in every language of the registry (UI_LANGUAGES, D-L9), never a hard-coded pair and never only the current language; otherwise a newly registered language fails silently (a Russian guard message would be replaced by the generic failure). Better still, don't recognise emissions by text: a typed error (err.name, a reason code) or a canonical-English wire constant (Rule 1, e.g. DOC_TASK_BUSY_MESSAGE) needs no loop. Sites at this record, both exact matches against the catalog value × the registry: isFriendlyTaskError (doctasks/manager.ts, the doc-task friendly pass-through over FRIENDLY_TASK_ERROR_KEYS; proof i18n-boundary.test.ts, a registry loop through the real DocTaskManager), and the chat screen's #599 stale-refusal check (STALE_MODEL_REFUSALS in ChatScreen.tsx: a "No AI model is running" / "…is starting" banner goes once a status read finds the model running, whatever registered language main threw it in; proof ChatSendFailure.test.tsx, a registry loop that renders the screen in another registered language). A 2026-11-11 search of src/ found no other site; every other text comparison runs on Rule-1 English, an un-catalogued engine or library literal, or a code. A third site, added 2026-11-12, recognises catalog text the renderer sends rather than a main emission: when a bank statement Summarize cashflow or Categorize run finishes, the chat screen sends chat.skill.summarize.question / chat.skill.categorize.breakdownQuestion in the UI language, and the bank handler (routedQuestions in skills/analysis/bank-statement.ts) matches both exactly in every registered language, because its English and German word stems miss the others, which would get a model answer instead of the checked template (proof skills-analysis-bank.test.ts, one row per registered language). The match is against the catalog text as it is now, so changing the wording of either question in any language changes what the handler recognises: a turn saved with the old wording, regenerated or sent again in a language whose text no English or German stem catches, gets a model answer instead of the template: for the summary question every language but English and German; for the breakdown question French, Russian and Ukrainian, because the Spanish, Italian, Dutch, Polish and Turkish ones contain the stem categor or kategor (2026-11-13). A structured intent (the finished run's tool sent with the request) would need no text match; the exact match is the chosen fix (owner call 2026-11-12). Two more keys, added 2026-11-14 (#809, open-issues wave owner call G-11), are read the same way: the document chat's example chips, which ChatScreen.tsx puts in the composer in the UI language, while the task router's word lists (analysis/router.ts) are English and German, the French compare words aside. The router reads chat.example.summarize and chat.example.indemnity from every registered catalog when the module loads, never copied, and compares them composed, lowered (lowerCaseNfc) and trimmed, as it does the question, both without a closing ".", "!", "?" or "…" (chipText). The summarize chip, by its whole text, is a summary ask (isSummaryAsk). The every-mention chip is recognised by its frame: the text up to and including its opening quote and from its closing quote on, with any text that isn't blank inside the quotes, so a user who puts their own word in the quotes keeps the route. The quote pairs it knows are '…', „…“, „…”, «…» and “…”; a quote right after a letter (the apostrophe in "tenant's") opens none, and a value that quotes nothing would be matched by its whole text. The chip gets the labelled answer (step 4b, fallback: 'partial') the English and German chips get by their own words. Proof extract-router.test.ts, one row per registered language (the summarize chip as written and in capitals; the every-mention chip with its own word and with another; in the eight other languages, that chip without its quotes, or followed by another question, is a plain question). Since #834 (follow-ups wave 4) the skill classifier reads the same frame: isNeedleShaped (skills/vocabulary.ts) counts the every-mention chip as no single-fact lookup in any catalog, whatever stands in its quotes, so with a whole-document skill and one document too long to read whole the chip keeps the whole read in every language (before, the German chip, whose «finde» is a lookup word, went to the passage search, and the other nine kept the whole read). The chip helpers moved from analysis/router.ts to analysis/example-chips.ts (chipText, isSummarizeChip, isMentionChip), which the router and the classifier both import; the router's answers are unchanged. Proof skills-vocabulary.test.ts and rag-whole-doc-skill.test.ts, one row per registered language each. Changing either chip's wording in any language, or the text around the indemnity chip's quotes, changes what the router and the skill classifier recognise, and the old wording is then read like any other question in that language. Not a Rule-3 site: the small-talk check (isSmallTalk, skills/vocabulary.ts), whose greetings, thanks and closings for the eight languages beyond English and German are language data written in main for the check, not catalog values, so no catalog edit changes them. They follow three rules, checked across all ten languages for a filler that is a content word elsewhere: no yes-word (a bare «sí» or «так» can answer the assistant's own offer), no "is it fine?" phrase («¿está bien?», «va bene?», «все добре?»; a one-word «Bien?», «Bene?», «Goed?», «Dobrze?», «Хорошо?» or «Добре?» still reads as small talk, as the German «Gut?» does), and an adjective or numeral that inflects with its noun only inside a whole-message form ("muchas gracias", "большое спасибо"). The short small-talk reply in a documents chat (#963, rag-design.md §19) uses a stricter check in the same file, isSmallTalkReply: a chit-chat question to the assistant, or, with no question mark anywhere, a thanks or greeting formula or small-talk words with at least one thanks, greeting, goodbye or praise word in them. The lists are split for it (social words and forms, acceptance and filler words and forms, question forms); isSmallTalk reads their union, so a one-word question about the last answer («Alles?», "Sure?") or a bare "ok" reads the documents while the whole-document opt-outs keep reading it as small talk.
  • The product name "HilbertRaum" is never translated; language names in the picker stay in their own language (each registry entry's nativeName: English, Deutsch, Español, Français, Italiano, Nederlands, Polski, Türkçe, Русский, Українська), so someone on a UI they can't read can still find their way back, while the picker's System label is translated (settings.language.system, UI-languages owner call D-13 (a), 2026-11-11; the picker is a native <select> built from the registry since then); technical values (model ids, paths, hardware-profile codes) stay as-is. Audit-log message strings stay English in the DB and export (the Phase-19 privacy rule; only the Activity panel's type labels translate).

§3.4 LLM prompts stay English (D-L6)

BASE_SYSTEM_PROMPT, the grounded template, and the task prompts are pinned — see the D-L6 row and known-limitations.md.

§3.5 German style

See design-guidelines.md → "German microcopy (D-L7)": the glossary, the informal-du rules, and §11.4 tone adaptation. The glossary is also pinned as the comment block on top of de.ts. Russian, French, Spanish and Italian, and since 2026-11-13 Dutch, Polish, Turkish and Ukrainian, follow the same pattern (D-L7): their "microcopy" sections come after the German one, and each glossary is pinned on top of its catalog file.

§5 Renderer conventions (the Phase-40 sweep rules, kept for future strings)

  • Label maps keep their structure; label values are MessageKeys resolved at render (t(STATUS_BADGE[s].labelKey)).
  • Every aria-label, title, placeholder, and confirm-dialog string is catalog copy — accessibility copy is user-visible copy.
  • Hand-rolled plurals use tCount; the date sites + number formatting take the resolved locale from useT().lang (useGrouping: false keeps English output byte-identical to the old toFixed).
  • Inline JSX islands (<code>, <strong>) use before/after key pairs (diag.logs.hintBefore/After; the fatal screen's app.fatal.hintBefore/After, around logs/app.log, went with #1024).
  • A label and its value, a figure and its unit, and a figure and its percent sign are joined the language's way, never by code (open-issues wave, #804, 2026-11-14; open-issues wave owner calls G-3, G-4). A ": " or " — " typed between a label and its value, or a plain space between a figure and its unit, is English typography in every language: French puts U+00A0 before a colon, Turkish writes the percent sign first, and a plain space lets a line break between "23" and "GB". This settles the code-built joins both UI-languages waves' QA recorded for follow-up (below). The pieces, as built:
    • common.labelValue joins a label and its value on screen and in an accessible name: {label}: {value} in nine catalogs, {label} + U+00A0 + : {value} in French. Its sites: the Performance screen's model rows and its "Recommended at the time of the check" line, the review summary's decision counts and its Copy SHA-256 button name, an evidence link's Remove link button name, the Documents error banners that name a document, and the type label of a Diagnostics activity line.
    • common.percent writes a percent per catalog: {pct}% in English, Italian, Dutch, Polish, Russian and Ukrainian, {pct} + U+00A0 + % in German, Spanish and French, %{pct} in Turkish. Its sites: the chat's context meter (ContextMeter.tsx) and an audio file's transcribing badge (badgeFor, screens/documents/format.tsx), so German shows "15 %" there with a no-break space: a plain one let "19" wrap above "%" in the context meter at 880×600 (owner call at the real-app check, 2026-11-14). German writes the same U+00A0 before every percent sign after a figure, in the longer sentences too (the context meter's tooltip, the model-start panel, the download, check and install progress lines, the invoice answer's tax line; code review, 2026-11-14), and its TYPOGRAPHY_RULES refuse a {placeholder} followed by % or % (tests/unit/i18n.test.ts, with accept and refuse samples).
    • tNodes(t, key, nodes) (renderer/i18nNodes.tsx) renders a pattern whose placeholders carry markup, which t cannot, since it returns a string: the bold role name of a Performance row, the glyph before a review decision, the bold type label of an activity line. It asks t for the pattern with each placeholder left unfilled (so t's fallback to English still applies), splits it at the placeholders and puts each node in its place; a placeholder with no node stays literal, as t leaves a missing param.
    • unitJoin(lang) (shared/format.ts) is the space between a figure and its unit symbol for a size or a speed built in code: a plain space in English and German, so their output is unchanged, and U+00A0 in the other eight. It reads a table typed over the registry, so typecheck asks a newly registered language for its space. The disk-size formatters (fmtDiskGb, fmtDiskSize, fmtPackSize), main's not-enough-space refusal for a model download (downloads.ts), the model card's sizes (ModelsScreen.tsx) and the Diagnostics rows (memory, read and write speed, free space) use it.
    • The catalogs follow the same rule: in Spanish, French, Italian, Dutch, Polish, Turkish, Russian and Ukrainian a figure or a {placeholder} and a unit symbol (French's list: GB, MB, KB, B, MB/s, tok/s, ms, s) are joined by U+00A0, and each of those languages' TYPOGRAPHY_RULES refuses a plain space there (joinsFigureAndUnit in tests/unit/i18n.test.ts); the Dutch, Polish and Ukrainian rules against a no-break space allow it in exactly that one position more. English and German write a plain space.
    • The three copied reports (Settings → Diagnostics: App & runtime and Hardware benchmark; the Performance screen's report) keep a plain ": " and plain spaces in the joins their builders make in code, so a pasted report stays searchable; their lines that come from the catalog follow it, U+00A0 included. effectiveReadValue (DiagnosticsTab.tsx), shared by the card and the report, takes the join as an argument: the card passes unitJoin(lang), the report a plain space.
    • Raw numbers in copy take the language's figures: a model card's memory figures (toLocaleString(lang), ModelsScreen.tsx). A skill answer's figures do not: they print with a dot in every language, as the app read them, and the invoice answer's tax rate prints the same way (String(taxRatePercent), skills/analysis/invoice.ts), so one line never mixes "5,5" with "5.50 EUR" (code review, 2026-11-14, which took back the rate's localization). The licence link in the model-download and knowledge-pack-tools dialogs sits on a line of its own, so no language needs a separator before it.
    • The guard: tests/unit/label-value-joins.test.ts scans src/renderer/**/*.tsx through the TypeScript AST for the join shapes the renderer has used (a JSX colon after an expression or an element, a ${a}: ${b} or … — ${b} template, a ': ' or ' — ' string) and fails on any join that is not on its ALLOWED list, and on an entry that no longer matches a join. ALLOWED holds, each with its reason, the three report builders, the brand link's tooltip and accessible name in App.tsx (the product name, then the screen it opens), one accessible name in ReviewScreen.tsx (an action, then the item it acts on) and the screenshot harness preview/preview.tsx. Its limits: a join built from variables, or one in a .ts file, is not seen.
    • Left as they are: the dash typed in code between an activity line's time and its entry (DiagnosticsTab.tsx), and Spanish figures, which Intl writes in the Spain pattern for every Spanish-speaking user, since it is given the language code alone. The Spanish review decision labels put the decision in parentheses («Revisado (respaldado)»), so the summary's join adds the only colon (owner call of 2026-11-14 in the open-issues legend above).
  • Shared components RECEIVE a bound t prop/argument (components/translator.ts, englishTranslator default) — they stay pure and provider-less tests keep working (⑤).
  • A support report carries an English copy (open-issues wave, #812, 2026-11-14; open-issues wave owner call G-7). The report builders (buildAppRuntimeReport and buildBenchmarkReport in DiagnosticsTab.tsx, buildReport in PerformanceScreen.tsx) take one LanguageBinding ({ t, tCount, lang }, components/translator.ts; useT()'s value is one) instead of separate arguments, so a report is built in one language throughout. withEnglishCopy(binding, build) returns build(binding) in an English or German interface; in any other it returns that report, a divider line naming English by its registry name (--- English ---), then build(englishBinding). The three Copy buttons copy through it. The English half has plain spaces throughout, as the English catalog does, and equals the report an English interface copies from the same data (DiagnosticsCopySave.test.tsx, PerformanceScreen.test.tsx, through the real buttons in every registered language). The languages a report is read in as it is, ['en', 'de'], are the languages the maintainers read, not derived from the registry, so a newly registered language gets the English half too; the list is a reviewed exception to the hard-coded-language ban in tests/unit/i18n-unused-keys.test.ts.
  • MIC_BLOCKED_MESSAGE stays canonical English in lib/dictation.ts and is exact-matched at display in DictationButton — the renderer-internal analogue of the display map.
  • Tests assert via t('en', key) / the en catalog, never re-typed literals; German render smokes live in tests/renderer/GermanSmoke.test.tsx. tests/renderer/LanguageSmoke.test.tsx (UI languages wave, 2026-11-12) renders the app shell and Settings → General in every registered language other than English (the rail labels, the picker's selection), so a language is proved wired end to end the day it is registered; per-screen depth stays in GermanSmoke, because every screen localizes through the same useT().
  • The catalog guards iterate the registry (UI languages wave, 2026-11-11), so a language is covered the day it is registered. tests/unit/i18n.test.ts: every registered catalog's key set, empty values and placeholders (D-L10), that t renders each language's own catalog file (a CATALOGS entry pointing at another catalog typechecks when the two share a catalog type), the per-language typography rules (TYPOGRAPHY_RULES, keyed by language, so typecheck asks for a list for each new one) and the house dashes. tests/unit/rail-labels.test.ts: every language's rail labels (no invisible breaks; no word longer than the width proxy). tests/integration/repo-hygiene.test.ts: each registered language's catalog file keeps all forms of every plural base on consecutive lines in CLDR order (until 2026-11-12 only chat.scope.projectCount). tests/unit/i18n-unused-keys.test.ts: the unused-key scan skips every catalog file and each one it skips is a registered language's (an unregistered xx.ts fails instead of silently disabling the guard); it also bans hard-coded interface languages in src/ (a union or an array literal naming two or more registered codes, such as the old 'en' | 'de', a comparison or case against a registered code, or a catalog lookup — t/tCount under whatever name the file imports it from shared/i18n — handed a registered language other than English as a literal, such as t('de', key); t('en', …) stays allowed for persisted text; all found through the TypeScript AST, through parentheses, as, satisfies and !; the codes come from the registry, so a newly registered language's literals are caught the way German's are, 2026-11-12) outside shared/i18n/ and a reviewed list of sites (content languages, the pack languages, the Translate default pair, the translation-language list, the legacy translation-provenance check, German inflection endings that happen to spell two codes, and, since Turkish is registered, the two zim/tables.ts comparisons with the HTML table-row tag <tr>). Its limits: a code held in a constant, .includes / Set / startsWith / regex tests, an { en, de } key table and a lookup re-bound to another name are not seen. tests/integration/i18n-boundary.test.ts: no guard key the doc-task pass-through accepts has a {param} (the filter is an exact match, §3.3 Rule 3). Shared convention (tests/helpers/i18n-catalogs.ts): a catalog is shared/i18n/<code>.ts exporting const <code>.
  • A number in copy (CODE-8, for every language; UI languages wave, 2026-11-12). A key whose text shows a number is either a .one/.other pair rendered through tCount, or a plain key on the reviewed NON_GRAMMATICAL list in tests/unit/i18n.test.ts, grouped by the reason it stays right in every registered language: nothing agrees with the figure (a count in parentheses, an ordinal, a unit symbol, an identifier, a money amount, a constant), the translations other than English and German must be written so nothing does (label first, no participle after a bare count), or the key renders only inside an English or German evidence pack (D-L11). English and German keep their wording; where it reads wrong at exactly 1 ("1 sections scanned") that is a follow-up (owner call 2026-11-12, legend above). Amended 2026-11-14 (open-issues wave, #806; open-issues wave owner call G-5): the eighteen English and German keys whose count can be exactly 1 now state it label-first too ("Sections scanned: 1", "I read the whole invoice. Line items: 1.", "Based on sections: 1 of 1"), the "(s)" forms among them; two of them are evidence-pack lines ("Required items decided: {decided} of {required}" and the input-coverage line). LABEL_FIRST_AT_ONE, beside NON_GRAMMATICAL, lists them, and a row refuses in their English and German values a count followed by a word (except "of"/"von" between two counts) and a plural crutch such as "line(s)", "Dokument(e)" or "Zeile(n)". English and German keep a noun after the figure only where the figure is never 1 (each group's reason says where). chat.speed.line is left as it is, so English reads "1 tokens" after a one-token answer. The net finds such keys two ways: in the source, a TypeScript-AST scan of every call or { key, params } table that fills a placeholder with a number or with text formatted from one (two variable hops back); in the catalog, placeholder names that always carry a number ({count}, {total}, {pct}, …). A new key it finds fails with a message saying what to do. Its limit: a number passed through a plain property or parameter under a placeholder name that isn't on the number-name list is not seen. The same scan fails any plural form src/ names itself (n === 1 ? t('x.one') : t('x.other'), a key built on a written-out base in a template literal or by + included), so tCount picks every form by the language's own rule. A pair whose text shows a locale-grouped figure gets the raw number as the count and the grouped string as the param the text shows (count in the two models.* context-size pairs, context in perf.model.line and perf.model.measuredOther); every other pair passes only the count, which tCount supplies as {count}. A tMain-emitted pair would need a tCountMain, which doesn't exist yet: no main.* key is a pair (the pack renderer, main-side, calls tCount with the pack language for the packExport.* pairs).
  • Never pair a key whose figure is shown with fraction digits unless tCount first learns the displayed digits (new Intl.PluralRules(code, { minimumFractionDigits })): CLDR selects by the digits the reader sees, so Russian and Italian "1,0" is other although select(1) is one (so are Dutch, Polish and Ukrainian "1,0"; Turkish "1,0" stays one). Put such a figure before a unit symbol, or write the key label first.
  • A plural form may add {count} in a language whose one is not exactly 1, and must when its plural form shows the number (owner calls 2026-11-12). Russian and Ukrainian .one also serve 21, 31, 101, …, and French .one serves 0 and 1.5, so a form English writes without a number ("Knowledge pack added") shows {count} there, or 21 packs would read as one; tCount always supplies it. The parity rule decides by probing the language's rule, so Spanish, Italian, Dutch, Polish and Turkish (one = 1 alone) get neither the licence nor the duty. No other placeholder may be added or dropped.
  • A text filter folds case with foldCase (shared/text-fold.ts, moved from renderer/lib/textFold.ts by #818; second UI-languages wave owner call G-5, 2026-11-13), on both sides: the query and the text. Its sites are the Documents name filter, the AI Model search and the review evidence filter. Never call toLocaleLowerCase() without a locale: it lowers in the runtime's default locale, not the UI language, and a Turkish default locale lowers "Invoice" to "ınvoice" (shown in Node and jsdom; --lang=tr-TR did not reproduce it in the app, §3.2, and a Turkish operating system was not tested), so a typed "inv" would find nothing. foldCase is lowerCaseNfc and then «ı» as a plain «i». lowerCaseNfc composes the text first (NFC; open-issues wave owner call G-8), so a letter stored as a base letter and a separate mark, as macOS stores file names, matches the same letter typed as one character, and the other way round; it then lowers with toLowerCase(), which reads no locale, and turns the «i» + U+0307 that «İ» lowers to into a plain «i». So I, ı, İ and i match each other in every interface language and on every system. Nothing else changes (no accent stripping), and NFC leaves already-composed text as it is, so English and German text as keyboards type it folds exactly as toLowerCase() folds it. The main process lowers the same way: the keyword-search query (fts.ts buildFtsMatchQuery) and the router's chip match call lowerCaseNfc, and the small-talk check calls foldCase on the question and on its lists, so Turkish typed in capitals meets them. The search keeps «ı» apart from «i», because the index does, and adds the spellings the index stores a word holding «ı» under instead (rag-design.md §11 "Keyword index"; second UI-languages wave owner call G-12, changed by open-issues wave owner call G-8).

Phase-42 QA (as built)

Full de.ts review pass against the glossary/du-form/tone rules (9 value fixes, commit a4d91de); German eyeball walk over every screen incl. the encrypted first-run gate at both window extremes (880×600 and maximized) with a programmatic overflow scan — found and fixed three text-expansion layout issues (chat-header wrap, empty-state chip wrap, .kv dd overflow-wrap) and one untranslated persisted string ('New chat', now D-L4 treated); English regression leg via the Settings picker proved the display map language-switches both ways. All seven acceptance criteria verified (BUILD_STATE §3, Phase-42 entry). Tests: tests/unit/i18n.test.ts (module + catalog hygiene incl. placeholder parity and plural pairs), tests/unit/display-map.test.ts, tests/unit/main-i18n.test.ts, tests/integration/i18n-boundary.test.ts, tests/renderer/I18n.test.tsx + GermanSmoke.test.tsx.

UI-languages wave QA (as built, 2026-11-12)

Real-app walk of the dev build in Spanish, French, Italian and Russian, plus an English and German regression pass: the create-password, starter and unlock gates on an encrypted scratch root, every rail destination, every Settings tab and the key dialogs (model download, knowledge-pack tools, audio import, review export), at 880×600 and maximized, light and dark. Each language was switched through the saved setting and a reload, then checked by <html lang> and one main-process message before any capture. A programmatic overflow scan per view (text wider than its box, clipped or newly wrapping controls, every rail label measured while its destination is active at 600 weight) found no rail-label overflow and no page-wide horizontal scroll in any language. The widest active label is German "Einstellungen", 78.7 px of 79: button text renders in Chromium's default font (Arial on Windows), not --font-sans, so width budgets are measured in the running app, not estimated from Segoe UI. A second model then judged, per language, every light-theme screenshot at both sizes, a dark sample (the gates, Home, Settings) and the native dialogs (address form, quotation marks, glossary, named-button references, plurals for the figure shown, untranslated text) and found no meaning error in any of the four.

Fixed after the walk, copy only (UI-languages owner call D-10: a shorter synonym on a fixed-width surface, never an abbreviation): the lock button (es «Bloquear», fr « Verrouiller ») and the downloads-allowed indicator (es «Red permitida», fr « Réseau activé », it «Rete attiva») fit one line in the rail foot; the answer-detail trigger (es «Detalle», fr « Détail ») no longer takes a third line at 880×600; the Spanish demo-mode chat header fits. From the screenshot review: the Russian first-run «Выбрать модель» button no longer breaks after a hyphen, the Russian Home encryption line and the Italian "allowed by policy" label fit one line, the French conversation search shows its whole placeholder, and two wordings that read ambiguously were reworded (Spanish «Configuración inicial», Italian «Attivata per impostazione predefinita»). The document-row file kind ("Text", "Audio", "Image") was hard-coded English in friendlyMimeLabel and now comes from the catalog (docs.meta.type.*; German shows „Bild“ for an image type that has no format name).

Accepted as they are (owner calls 2026-11-12): the Russian downloads-allowed indicator on two lines (no natural shorter phrase; the local-API state already takes two lines in English); the Spanish and French skill trigger on two lines in document mode at maximized; the Russian summary badge «Краткое содержание» (the glossary term), which at 880×600 pushes the row's Preview button out of the row as German «Zusammenfassung» already does; designed ellipses. Recorded for follow-up, not changed in this wave: code-built joins that ignore a language's typography (a plain ": " before a value where French puts a no-break space, and in the review summary a second colon after a Spanish label that already contains one, «Revisado: respaldado: 0»; {pct}% in the context meter, a spaced em dash in the model-download and knowledge-pack-tools licence line, a plain space between figure and unit from shared/format.ts, though no figure–unit pair broke across lines at either size); the closed language select switching, saving and toasting on every arrow key, with the toast in the language being left; and layout that is wrong in English too: the rail foot below the window at 880×600, the document-mode chat pane running past the window edge at 880×600 with the conversation list open, document rows squeezing the name to nothing at 880×600, and the Documents filter icon covering the placeholder. Changed 2026-11-15 by #808 (open-issues wave owner call G-6): the language select saves about half a second after its last change, or at once when it loses focus or the tab is left, so stepping through it with the arrow keys switches and saves once, with one "Saved" toast in the new language (SettingsScreen.tsx). Changed 2026-11-15 by #803 (open-issues wave owner call G-9): the rail scrolls on its own, so its foot is in reach at 880×600 without the window scrolling; the document-mode chat stays inside the window with the conversation list open; the Documents filter's text starts after its icon; and the Spanish and French skill trigger stays on one line maximized too, the composer footer taking a second row in French document mode instead (design-guidelines.md §3, §12.1, §16). The document rows still squeeze the name at 880×600; they were outside that change.

Other legs: renderer and main plural categories equal the registry pins (the R-L1 note in §3.2); with the lock-screen language different from the OS, a wrong password shows the gate and its error in one language (UI-languages owner call D-17 (a)); the import picker's title and filter names follow the interface language (its buttons follow Windows); a review exported from a Russian interface is an English pack, and the export panel says so in Russian; startup with six catalogs is within noise of the two-language baseline (window ready-to-show median 1,943.7 ms against 2,037.2 ms, five runs each, same machine); the production bundle (npm run start) resolves Russian from --lang=ru in both processes; English and German innerText against the pre-wave baseline changed only by the four new picker names and the System hint. The packaged build was not re-made (it needs the network): the builder config keeps every Electron locale file, and the last packaged build ships es, fr, it and ru.

Second UI-languages wave QA (as built, 2026-11-13)

Dutch, Polish, Turkish and Ukrainian were drafted from English by an AI model in six chunks per language (24 drafting runs), each bound to its accepted style guide (the "microcopy" sections of design-guidelines.md §7), and each chunk was checked by a second model (24 runs): glossary, placeholders, plural forms (Ukrainian one read with 21 and 101), endings next to a placeholder, register, quoted button names, and a back-translation into English of the keys most exposed to a meaning error plus a fixed sample. It found three S1 findings (two Dutch labels that misnamed where a document had moved, and a Ukrainian count idiom applied to a list of page numbers) and seventeen S2 findings (glossary, register, wording, quoted labels), all fixed before the catalogs were committed; most S3 findings were applied too. The 72 localized skill titles and descriptions were all back-translated, with no S1 or S2. Each guide's punctuation, script and placeholder rules became TYPOGRAPHY_RULES (Dutch 12, Polish 18, Turkish 17, Ukrainian 18 rules), among them the Turkish ban on a suffix glued to a placeholder and the Ukrainian ban on ы, э, ъ and ё, and so did the address-form rules a script can check: Dutch bans «u», «uw», «uzelf», «jullie» and «gij», Polish «Pan», «Pani», «Państwo» and a capital «Ty» or «Twój» mid-sentence, Turkish «sen» and a capital «Siz» mid-sentence; Ukrainian has none. The rest of the form of address (the Polish check for a gendered verb among it), the glossary and the spelling stay a review check.

The registry-driven guards covered the four from the day each was registered (catalog parity and placeholders, typography, plural layout, ICU pins, the display map, the write gate, LanguageSmoke, the picker, skills parity, rail labels). New rows cover the rest, each shown to fail on a planted fault: the resolver sends nl-BE, pl-PL, tr-TR and uk-UA to their language and ua, ukr and nld to English, and the Turkish suffix and the Ukrainian letter and apostrophe rules are tried on accepted and rejected samples. Planted faults also showed the existing rows hold for this wave's risks: the plural duty and licence (a Ukrainian .one without {count} fails, a Dutch, Polish or Turkish .one with it fails) and the two zim/tables.ts exceptions to the hard-coded-language ban (one removed fails). The Documents name filter used to lower names with toLocaleLowerCase() and the runtime's default locale, which under a Turkish locale turns "Invoice" into "ınvoice", so "inv" found nothing whatever the UI language (shown in Node and jsdom; --lang=tr-TR does not reproduce it, §3.2); the AI Model search and the evidence filter read no locale but kept ı and İ apart from i. All three now fold with foldCase (§5; second UI-languages wave owner call G-5), with rows on both sides of each filter. The lock screen's "HilbertRaum Lite", which CSS shows in capitals, is marked lang="en" (second UI-languages wave owner call G-6). No English or German catalog value changed.

Real-app walk of the dev build in the four languages plus an English and German regression pass, as in the first wave: every rail destination, every Settings tab, the gates and the chat in its states, at 880×600 and maximized, light and dark, each language switched through the saved setting and a reload and checked by <html lang> and one main-process message before any capture. Electron's ICU (78.2, the version read in main) gives the four languages the same plural categories and number formats as Node's: compared with the Node facts in the renderer and in main, they showed no difference («8192» but «98 304» in Polish, «8 192» in Ukrainian, «%75» in Turkish). Every rail label was measured with its destination active, at weight 600 in Arial: all fit the 79 px box, the widest being Dutch «Afbeeldingen» at 76.0 px, and the Turkish «Yapay zekâ modeli» takes two lines by design. Startup with ten catalogs is no slower than the six-language baseline (window ready-to-show median 2,063.8 ms against 2,242.7 ms, gate visible 2,136.5 ms against 2,328.8 ms, five runs each, same machine). In a Turkish interface Turkish words take Turkish capitals («DİĞER», «KİTAPLIK»), the lock screen shows «HILBERTRAUM LITE», and the Documents filter gives the same results for "inv", «ısı» and «istanbul» in all four combinations of --lang tr-TR or en-US with a Turkish or English UI, as does the AI Model search for its queries (the evidence filter shows only above 24 sources and was not reached). The other legs of the first wave passed for the four: the --lang legs (§3.2), the locked gate in one language with a lock-screen language other than the OS's, the import picker's title and filters, the English-pack line in the export panel, no spell-check dictionary request under --lang=uk-UA, the production bundle resolving Ukrainian from --lang=uk, and English and German innerText changed only by the four new picker names (timestamps, measured figures, paths and the network indicator's start state aside). The packaged build was not re-made (it needs the network); the builder config still keeps every Electron locale file, nl, pl, tr and uk among them.

Fixed after the walk and a second model's screenshot review, ten values, copy only (UI-languages owner call D-10 where a surface is fixed-width):

  • Polish models.verifyAllHint: «na powolnym dysku» («wolnym» can mean "free"), tautology gone.
  • Polish perf.rating.slowDrive: «Powolny dysk», was «Wolny dysk», for the same reason.
  • Polish main.benchmark.warnSlowDrive: «raczej powolny», was «raczej wolny», likewise.
  • Ukrainian indicator.short.online: «З мережею», one line in the rail foot instead of two.
  • Ukrainian chat.runtime.demo: «{model} · демонстрація», no longer cut off in the chat header.
  • Ukrainian chat.scope.answeringFrom: «Джерела: {source}», so the skill trigger beside it fits.
  • Ukrainian gate.starter.chooseModel: «Вибрати модель», as on Home, no break after «ШІ-».
  • Dutch models.verifyAllHint: «Met deze knop controleer je …», no pronoun for a thing.
  • Dutch perf.footer: «volledige» dropped, so the line fits.
  • Turkish diag.system.imagesSize: «Görsel geçmişi boyutu», one line.

Accepted as they are (second UI-languages wave owner calls G-8, G-9): at 880×600 the document rows squeeze the name (Ukrainian to 32 px, English to 85 px), the pattern the first wave already left for follow-up; skill descriptions cut with an ellipsis at maximized in Dutch, Polish and Turkish; Diagnostics labels that wrap; a Polish «(OCR)”.» alone on a line. Recorded, not changed: CSS capitals in a Turkish interface apply Turkish rules to the user's own text (a project called "Invoices" would read «INVOİCES»; a document heading "Overview" reads «OVERVİEW»; owner calls G-7, G-10); conversation search and keyword retrieval lower without the fold, so «ısı» misses "ISI", and a query with «İ» is split at it (buildFtsMatchQuery, fts.ts): «İstanbul» becomes "i" OR "stanbul", which matches neither «İstanbul» nor «İSTANBUL» and can return unrelated text with a lone "I" (owner call G-12); and the first wave's code-built joins, now with one real break, a Ukrainian «23» and «GB» split across two lines on a model card by the plain space the code puts before the unit (shared/format.ts, ModelsScreen.tsx), while Turkish shows «15%» in the context meter whose tooltip, from the catalog, reads «%15». Eight findings that are wrong in English too (layout at 880×600, a few English wordings) were collected for follow-up (owner call G-11). Changed 2026-11-14 by #818 (open-issues wave owner call G-8): the search query is now composed and lowered with lowerCaseNfc, so «İstanbul» is one word, and a word holding «ı» is also searched with each «ı» as "i", so «ısı» finds "ISI" (§5, the foldCase bullet). Changed 2026-11-15 by #803 (open-issues wave owner call G-9): of those layout findings, the Documents filter icon no longer covers the placeholder, the document-mode chat is no longer cut at the window's right edge, and no measured composer-footer control takes two lines (the footer moves a control that doesn't fit to the next row; only a suggestion hint naming a skill longer than a whole row would wrap inside it); the first-run starter step's two-line buttons, the knowledge-pack tools dialog's clipped title and the document rows' squeeze above are not changed. #803's ten-language check found two more, also not changed: the document rows end short of the toolbar's right edge when maximized, and the conversation list and the message area show classic scrollbars with arrow buttons, heavier than the rest of the interface. Native review is open for all eight machine-drafted catalogs (#813), with two words this check left for it: Turkish «Uygulanamaz» ("not applicable", which may read "cannot be applied or enforced") and Polish «Wolno» ("slow", which can also read "allowed").

Encrypted workspace (Phase 9 + audit rounds)

  • services/security/crypto.ts — KDF (Argon2id default, scrypt legacy; descriptor-supplied params are bounds-checked) + AES-256-GCM primitives and the framed blob format.
  • services/workspace-vault.ts — the vault lifecycle (WorkspaceController): create/unlock/ lock, STREAMING whole-file encrypt/decrypt (constant memory; >2 GiB safe), chunked shredFile, crash-recovery sweep (shredStalePlaintext incl. .tmp/.parse* transients), the encrypted document cache (DocumentCipher for workspace/documents/*.enc), and the create-over-existing vault guard. Full design in security-model.md.

Drive tooling & distribution (Phases 11–13)

Canonical, unit-tested TS modules that the self-contained scripts/*.{ps1,sh} mirror natively:

  • services/drive.ts — drive layout (DRIVE_LAYOUT_DIRS), drive.json/policy.json generators, verifyDriveModels, buildChecksumsJson.
  • services/assets.ts — the DIY asset loader logic: planModelDownloads, runtime-build selection, verifyDownloadedFile, injected-fetch download seam.
  • services/preflight.ts — the friendly, non-blocking first-run drive check (runPreflight IPC).
  • services/commercial-drive.ts — assertCommercialDrive, the "is this drive sellable?" gate (commercial policy, weights VERIFIED, license reviews APPROVED, no user data, the app artifact + launcher per declared platform), which build-commercial-drive calls through the built out/tools/assert-commercial-drive.mjs. The build ORDER lives in the two builder scripts alone (script-orchestration.test.ts runs it); the TS step plan that once mirrored it had no caller and was removed (#770).
  • Drive detection without the launcher: workspace.ts locateDriveRoot (an empty HILBERTRAUM_DRIVE_ROOT counts as unset) has findPreparedDriveRoot walk up from the app's real location (PORTABLE_EXECUTABLE_DIR, then APPIMAGE while APPDIR holds the executable, then the exe path) to the config/drive.json marker (audit M16; #858).

In-app model downloader (Phase 18)

The app's first sanctioned network feature — explicit, verified, impossible to trigger silently; its absence changes nothing (the app stays 100 % usable offline). Triple gate, all enforced in MAIN and re-checked per call:

  1. policy.network.allowModelDownloads — the authoritative ceiling (wave-1 decision D3: DEFAULT_POLICY allows it so the spec §3.6 user toggle is the sole gate when no policy file restricts — "policy only restricts" preserved; since 2026-07-01 prepare-drive also writes true in BOTH postures, so a prepared/sold drive lets the buyer add models on demand — still gated by the setting + a per-download confirmation, and update-checks + telemetry stay denied so the drive never phones home).
  2. settings.allowNetwork — the spec §3.6 checkbox, default on for a fresh DIY/dev install (DEFAULT_SETTINGS.allowNetwork: true); gate 1's policy ceiling still wins — a policy.json hand-edited to deny keeps downloads off regardless of the toggle. A locked workspace reads as off.
  3. A per-download confirmation: model name, size, license + license_url, upstream URL, and an explicit license acknowledgement when license_review.status != approved (the in-app --accept-license). The renderer dialog is UX; enforcement is main-side. When gate 1 or 2 fails the AI Model screen says why (policy vs Settings toggle), reusing the PolicyStatus distinction.

A fourth refusal, not a gate (issue #196, 2026-08-20): a manifest whose download.withdrawn records that the publisher deleted the pinned file is refused BEFORE any request, with copy naming the model and the reason — the planner reports source-withdrawn ahead of the license gate, the AI Model card shows the note instead of a Download button, and the fetch-models twins skip such a model with a loud line. Nothing about an already-installed weight changes: it verifies and runs as before. Schema + rules: model-policy.md "Withdrawn upstream sources"; the case that produced it: model-benchmarks.md §9.5.

And a refusal for a download that cannot fit (#768, 2026-11-03). start() refuses when the bytes still to fetch exceed the free space of the drive the weights land on. It runs after the withdrawn / license / already-present refusals and before the job exists, so a refusal creates no job, audits no model_download_started and requests nothing. Still to fetch = Σ over the files to fetch of max(0, size_bytes − its kept .part), since the run resumes a .part. There is no check when any file's size is undeclared or the free space cannot be read, and no headroom on top (owner call: the same gentle posture as preflight's low-space note). The free space is statfs at the files' nearest existing folder, ultimately the drive root (services/disk-space.ts freeBytes, shared with the drive status). main.download.notEnoughSpace names both figures, decimal with one decimal, in the unit the size needs (GB as the confirmation dialog shows it; MB for a projector or the rest of a resume), and says what to do. The two never read alike: free space rounds down to the tenth, and the size rounds up when it would otherwise print the same tenth. Before it, a drive with 13.5 GB free took a 14.4 GB download and stopped on ENOSPC near the end.

Mechanics: services/downloads.ts DownloadManager — a job state machine over the REUSED assets.ts seams (planModelDownloads + optional hashStore; downloadToFile, extended additively with signal/headers/append/onResponse; verifyDownloadedFile). Bytes land in <weightPath>.part, renamed into place ONLY after the hash verifies; a mismatch deletes the partial and fails the job; a placeholder expected hash completes unverified (checksum honesty). Cancel keeps the .part; the next start resumes via a Range header (append iff the server answered 206). A cancel is honoured in EVERY live state — including verifying, where the SHA-256 over a multi-GB weight on USB takes minutes: the abort stops the hash itself (#752), nothing is renamed into place, and a two-file (vision) job stops before its next file (full-audit 2026-07-10 BE-4; previously a cancel there was silently dropped). The card's Cancel stays enabled there, as the engine card's does: it was disabled until #752, so BE-4 was out of the user's reach. A click that arrives after the check finished gets the terminal job back and refreshes the cards itself, since that snapshot stops the poll that would have. A cancel stands against every later failure, by the OCR manager's rule (failJob). activeJob() stays held until the run has settled, as in the engine and OCR managers (#752), so a start in the moment after a cancel is refused rather than put a second writer on the .part; stopping the hash is what keeps that moment short, since a latch alone would have refused every restart for the rest of the hash. A complete .part that settles in place (F-13) is fsynced before its rename, like a fresh download (F-34, #752): the hash reads the page cache, so it says nothing about the device. One download at a time; jobs are in-memory, polled over downloads:start/get/cancel (the Phase-4 import precedent — no new event channels; since #314 downloads:list/downloads:dismiss let a reloaded renderer re-attach). On a VERIFIED success the checksum cache is primed with the hash just computed (models.ts primeChecksum, keyed by the file's size+mtime) so the Models screen's install-state refresh reports installed WITHOUT re-hashing the multi-GB weight — this removed the invisible post-download "Checking…" gap where the card briefly looked un-downloaded (2026-07-01); a placeholder-hash completion still invalidates (it is never trusted). Lock policy (full-audit 2026-07-10 BE-2): downloads keep running through a workspace lock — the weights live outside the vault, and the persistent checksum cache (the job's only DB touchpoint) is lock-aware: createSettingsHashStore takes a () => Db getter (never a raw handle pinned at IPC registration) and degrades to an in-memory fallback while the vault is closed, and runOne treats any cache fault as non-fatal — the cache is an optimization, so a download that verified while locked still reports done and fires onModelInstalled. Switching internet access off stops the job (#782). The gates are read at the start only, and the switch's own copy says "When off, the app makes no internet calls"; the job kept running past it, while the chat-header indicator read Local · Offline. Owner calls (all as recommended, on #782): stop the job; stop only the network part; no confirmation on the switch, a notice instead; a policy file edited mid-session is out (nothing watches it, so a check between files would be half a fix; known-limitations.md). As built: settings:update sees a REAL flip (read before the write, the local-API discipline) and reports it to ctx.downloadsNetworkSwitched (assigned by registerDownloadIpc) and ctx.installsNetworkSwitched (registerEngineIpc: the engine and OCR installers), each isolated so one fault neither skips the other nor fails the save. Each manager's networkSwitched(on, onStopped), over one shared NetworkSwitch (downloads.ts): off cancels a job queued or downloading at once (the model's .part kept, as for a cancel); a job in a local phase (the model's or OCR's check, the engine's archive check or extraction) runs on and stops at its next network request, so a model whose bytes are all on the drive still installs, and Resume — refused while the network is off — is never needed just to check a file already there. On before that request withdraws the stop. A start whose planning straddled a switch-off (the planner can hash a present file for minutes) is refused when its plan is done, unless the switch is back on by then (the engine makes its job before its first await, so it needs no such check). onStopped runs once, for a job that really stopped: ctx.runtimeNotice (index.ts's notifier) shows main.download.stoppedNetworkOff with the AI Model button. The model card reads DownloadJob.stoppedBy: 'networkOff' and says it was the switch, not a cancel; the engine, OCR and knowledge-pack-tools cards show no "cancelled" copy and return to their offer, whose button names the network as the reason. Found on the way and fixed: the engine set downloading after an await mkdir, so a stop landing while it was still queued was overwritten and the aborted fetch read as a failure. A lock still leaves the jobs running (BE-2). Audit events (model_download_started/verified/failed) flow through the injected DownloadManagerDeps.audit hook; a placeholder-hash completion records NO "verified". A failure's audit reason is failureReason's content-free label, shared with the OCR installer, never the error's message: an errno names the drive path, and the audit log's data class is ids and counts (security-model.md). The job's own copy follows the same split (#752): a drive failure says so with no raw reason (main.download.writeFailed), a misaligned resume says the partial was discarded (main.download.resumeDiscarded), and a resume is promised only with bytes on the drive: a request that failed before its first byte reads as main.download.httpFailed. A job reaching done additionally fires DownloadManagerDeps.onModelInstalled → wired to AppContext.onModelInstalled, which re-runs the startup-frozen availability selectors — the translation sidecar today (issue #40; the "Translation sidecar" record has the details). Since #634 it also re-arms the embedder's failed-start latch when the installed model is the embedder's own, so a re-downloaded damaged e5 file works without a lock/unlock (rag-design.md §12.4). No update checks, no catalog (only manifests already on the drive), no background anything; a sanctioned download session is by definition not offlineMode. Gate semantics + licensing: model-policy.md §"The in-app downloader"; user-facing posture: PRIVACY.md.

settings.allowNetwork now defaults ON (2026-06-13). The spec §3.6 checkbox was flipped false → true in DEFAULT_SETTINGS so a fresh install can download models out of the box (onboarding feedback). Gate 1 (the policy ceiling) is unchanged and still authoritative: a policy.json with allow_model_downloads: false — or the packaged-build STRICT_POLICY fallback for a provisioned config dir — keeps the app offline regardless of the toggle. (Since issue #93, 2026-08-03, an UNPROVISIONED config dir — neither policy.json nor drive.json, the standalone portable install's app-data fallback — gets STANDALONE_POLICY instead: downloads + the local API policy-permitted (the latter per owner decision O3, local-api wave — both still behind their own default-off settings/consent), everything else strict; see security-model.md "Fail-closed on a packaged build".) A prepared/commercial drive now writes allow_model_downloads: true (2026-07-01), so the setting + the per-download confirmation are the effective gate there; update-checks + telemetry stay hardcoded/denied so the drive never phones home. A locked workspace still reads the setting as off.

In-app engine installer (2026-06-13)

The model downloader fetches model WEIGHTS only; the llama-server engine binary is a separate asset (runtime-sources.yaml, normally provisioned at drive-build time by fetch-runtime). With weights present but no engine, a started model lands on the demo runtime (runtime/factory.ts — "no llama-server binary on the drive"), which is what a user hits when downloading a model into a dev/incomplete drive. services/runtime-download.ts EngineDownloadManager closes that gap: it resolves the host build (selectHostBuild), then download → verify → clean → extract → flatten → write the .hilbertraum-runtime.json marker — mirroring the canonical fetch-runtime scripts, but in-app. Since #986 ("In-app engine updates" §6) there is no clean: download → verify → room check → extract, flatten, check and mark in <os>.new/ → swap it in by rename; the next start finishes an interrupted swap. The network (fetchImpl) and the archive extraction (extractImpl, default tar -xf, which covers the .zip/.tar.gz host assets via bsdtar/GNU tar) are injected seams, so the unit suite stays zero-network; only the #856 rows run the OS's own tar (packaging.md, the in-app engine section). Same gates as the model downloader (policy ∧ allowNetwork), re-checked in main; placeholder hashes complete unverified (checksum honesty); the install is idempotent via the marker (runtimeInstallCurrent). Surfaced as engine:status/download/getJob/cancel IPC + a Models-screen "Install the AI engine" banner (shown only when the engine is missing but a host build exists; progress/cancel like a model download). CI exercises only the injected seams — the real fetch + tar extraction of the pinned build is a manual smoke (like the GPU/PAID harnesses).

Addendum — #339 P8-1, optional, multi-file families (2026-09-06). runtime-sources.yaml gained a third build family, kiwix_tools, that differs from llama_cpp/whisper_cpp in two ways the installer and the sell gate both had to learn: it is optional, and it ships more than one required file. An optional family is never part of the default selection (downloadEngine() still takes no arguments) and never counted toward installed/ missingFamilies — only an explicit families: [...] request installs it, and its presence/ absence surfaces separately (EngineStatus.missingOptionalFamilies). A multi-file family's required set is the code-side floor (the primary binary plus any alsoRequired names a SidecarFamilySpec declares) unioned with the yaml's own executables and runtime_files lists — the floor is what a user-writable drive yaml can never lower, the yaml is what code cannot know in advance (an ICU DLL name carries its major version). After extraction the installer runs a completeness check over that declared set before treating the install as successful, and hashes every file into the .hilbertraum-runtime.json marker all-or-nothing (a partial hash map is never written — a hashing failure leaves the family on the hashless skip-legacy verifier path rather than reporting some files "hashed" and others not). The sell gate mirrors the same declared-file set for its own presence/hash checks (optionalRuntimesConsistent). Why the yaml's optional flag is declarative rather than load-bearing: runtime-sources.yaml ships on a user-writable drive, so if the on-disk flag controlled the default selection, deleting one line from it would let the argument-less "Install the AI engine" button silently fetch a separately-consented, copyleft binary — the code-side SidecarFamilySpec.optional is the one that actually decides, and a test asserts the two agree for every shipped family. Since #729 a spec can also name executables the archive carries but an install never keeps (neverInstalled; the llama family's llama-connect, the --connect tunnel): the installers delete them after the flatten, a yaml executables entry cannot make one required (compared without case), both fetch-runtime twins carry the same list (script-drift.test.ts) and sweep an install they find current, and the sell gate refuses a Kit that holds one anywhere under an install dir (findNeverInstalledFiles). Record: docs/model-policy.md "Sidecar binaries — kiwix-tools" (the license side), docs/data-contracts.md (the type-level shape), docs/rag-design.md §17 D-Z17 (the family contract from the knowledge-packs side, including the R-1 closure statement).

Addendum — #843, every engine install asks first (2026-11-18). PRIVACY.md item 3 promises a dialog with the size, licence and address of "that specific download"; the engine's install banner, the #516 update notice and the #532 "Install … again" called downloadEngine on the click. Each now opens EngineConfirmDialog (renderer/components), the model dialog's ConfirmDialog + <dl class="kv"> shape: per archive its version (for an update "installed → pinned"), backend, size, full URL in <code> and licence with its link and host (#236), the total when there is more than one archive, a "checked against its checksum, nothing about you is sent" hint, and for an update the pause note. Its title is the clicked surface's own title, its Confirm the action's own label; Confirm is disabled while the download gate is closed (computeDownloadGate). Decisions: (1) the facts come from main — engine:plan answers from previewEngineDownload, which runs planEngineSteps, the step selection EngineDownloadManager.start() itself runs (extracted from start() unchanged), with the same bundled pins and, for a reinstall, the same refused builds. A renderer-side reconstruction would have had to re-derive the cpu/ net and the verdict store's builds and could drift; the equality table in engine-plan.test.ts holds the preview's URLs to the URLs the started job downloads. The preview runs the selection only, not start()'s other refusals (the gates, the one-job check, an engine in use, an update's busy check), so those can still arrive after Confirm as the same friendly error. The dialog shows the plan at the moment it opened: Confirm sends the same request and start() plans again, and main's gates decide again. If the drive changed in between (a background helper start reported a refused cpu/ net while a reinstall dialog was open), the job does what the new plan says, and its audit record names what it really fetched; closing that gap would need a consent token, which decision (2) rules out. (2) No consent token in main: Confirm sends the unchanged request (the argument-less install stays argument-less), main checks the gates on every start as before, so the in-app updater's "one consent covers the engines inside an update" stays possible. (3) The licence is code-side and pre-reviewed (SidecarFamilySpec.license, bundledLicenses per OS, licenseRepo; docs/model-policy.md "What the in-app engine dialog states"), so there is no acknowledgement checkbox (the OCR pattern, not the kiwix one). (4) The sizes are the pins' size_bytes (labels only, never checked — the archive is checked by its SHA-256). The kiwix consent dialog is unchanged; its job is audited like every engine job (below).

Diagnostics & transcript export (audit round)

  • getRuntimeStatus (read-only runtime health), getLogTail (tail of the local app.log), and exportConversation (spec §7.6 transcript export via the OS save dialog) round out spec §7.11/§7.6.
  • Copy / save (support hand-off). Each Diagnostics card — App & runtime, Hardware benchmark, Logs — has a Copy button that writes a plain-text rendering of exactly the rows shown to the clipboard (confirmed by a transient toast), so a user can paste the lot into a support message. The copy goes through window.api.copyToClipboard, which writes from the main process (clipboard:write IPC → Electron's clipboard.writeText) — not navigator.clipboard (unreliable in the file:// renderer: needs a secure context + focus) and not a preload-side clipboard call (the renderer is sandbox: true, so the sandboxed preload has no clipboard module — only ipcRenderer/contextBridge/webFrame/nativeImage/webUtils). The same bridge backs the chat message-copy action. The on-screen rows and the copied text are built from the same helpers (runtimeStatusLine / buildAppRuntimeReport / buildBenchmarkReport in DiagnosticsTab.tsx) so they can't drift. The Logs card additionally has Save to file… → exportLog IPC → saveTextExport, which writes the whole current log (readLogFull(), not just the getLogTail tail) as plaintext to a user-chosen location. This is a deliberate user action: the on-disk app.log stays encrypted at rest (see "Encrypt the diagnostics log at rest"); the export is the user choosing to take a copy outside the vault to share — never uploaded, no telemetry.
  • A never-benchmarked workspace is benchmarked automatically in the background after it becomes usable (spec §2.1 first-run benchmark). Since PR #303 P7 the seams run it in two halves around the model auto-start — prepareFirstBenchmark (restore / seed / probe refresh, synchronous) → maybeAutoStartActiveModel → scheduleFirstBenchmark (the measurement, behind the start's settlement; bounded wait, one continuation, one attempt per unlock session) → maybeStartLocalApi — see benchmark.md "Scheduling behind the auto-start".

Audit log (Phase 19)

services/audit.ts finally writes the spec §8 runtime_events table (created in Phase 1, unwritten until now): recordEvent(db, type, message, metadata?) (NEVER throws), a typed AuditEventType union (shared/types.ts), listAuditEvents (newest-first, beforeId cursor), and retention to AUDIT_MAX_ROWS = 5000 (wave-1 decision D7 — fixed for wave 1; configurability is Office-edition admin surface). The prune is slack-gated (full-audit 2026-07-10 PF-3): an insert prunes back to the ceiling only once the table exceeds AUDIT_MAX_ROWS + AUDIT_PRUNE_SLACK (250), insert+prune in one transaction, ordered by the additive idx_runtime_events_created — readers never see the slack (listAuditEvents clamps to the ceiling). For the user, not telemetry: it lives in the workspace DB (encrypted at rest on encrypted workspaces) and is never uploaded. The app-wide recorder (createAuditRecorder → AppContext.audit, optional so partial test contexts stay valid) is built over the workspace DB getter — while the vault is locked it buffers events in memory (bounded) and flushes them after the next unlock.

Wiring is deliberately shallow — call sites live in the IPC layer, not inside services (keeps services pure/testable): registerCoreIpc (settings_changed, privacy-relevant keys only), registerModelIpc (model_selected/verified, runtime_started/stopped), registerChatIpc (conversation_deleted/exported), registerDocsIpc (document_imported/reindexed/deleted), registerWorkspaceIpc (workspace_created/unlocked/locked/unlock_failed), registerDownloadIpc → an injected DownloadManagerDeps.audit hook (model_download_started/verified/failed — the Phase-18 follow-up), registerEngineIpc (#843: engine_install_started/finished/failed from the engine:download handler and the manager's onSettled; ocr_install_started/finished/failed through the StartOcrInstallOptions.audit sink it passes to every OCR job), plus main/index.ts for runtime_crashed/runtime_fallback (the GPU crash-fallback/ladder callbacks), policy_warning (startup loadPolicy), and offline_guard_violation (a new assertOfflinePosture.onViolation hook).

Surface: the Activity panel on the Settings Diagnostics tab (getAuditEvents(limit, beforeId?) IPC audit:list, client-side type filter, "Show earlier activity" paging) and an export-to-file action (exportAuditLog IPC audit:export, the exportConversation save-dialog precedent, JSON output). Data class + privacy rule: security-model.md §"Audit log data class".

Document organization — design record (Phases A–F, §1–§8)

Formerly docs/document-organization-plan.md (condensed here at the Phase-F v1 closeout, 2026-06-14, per the CLAUDE.md doc-lifecycle rule; the full original working paper — three audit rounds, the §0/§0.1/§0.2 decision ladder, per-phase as-built notes, the open-questions register — is in git history: git show 477f803:docs/document-organization-plan.md). A collection-membership layer over the existing ingestion/retrieval pipeline: one stored file, one chunk set, one vector set per document — organization is metadata. Five user-facing containers — Library, Projects, Temporary, Generated (a role/view, not a place), Archive — plus query-time Smart views. (A rule-based filing-suggestion engine shipped in Phase F and was removed 2026-06-15 — see §4.) Everything stays local + offline. The retrieval / scope half of this design lives in rag-design.md §13 (resolveScope, the RetrievalScope union, collection-filtered search); this record is the data model, IPC, and audit layer. § numbers below are stable; future code comments should cite them as "doc-org record §N" (existing comments still say "plan §x"; those resolve via git history above).

§1 Decisions (the locked ladder — D1/D2/D3 + the audit fixes)

Decision Choice Why (short)
Organization primitive Collection membership (document_collections), never duplicated files/vectors One doc = one chunk/vector set shared across every collection it belongs to (the cheap-change principle)
Projects vs a new table Projects ARE collections (type='project'); Library/Temporary are seeded built-ins (builtin=1) One membership model carries Library, projects, and (later) smart-view ids uniformly
D1 — chat scope A composed UNION the user picks from Library + project(s) + specific docs, persisted in conversations.scope_v2_json Users think in "my sources", not one bucket; survives restart
D2 — duplicate import Always a new document (no sha-dedup, no prompt). Share one doc across folders via Add to collection Import stays dumb + predictable; de-duplicated sharing is the explicit membership action
D3 + N1 — generated docs Get NO document_collections membership at all ⇒ structurally absent from every collection scope; reachable only by explicit doc-id or download + re-import Generated outputs are work products, not auto-trusted knowledge; no exclusion predicate needed
C1 — archive A doc leaves retrieval only via its own lifecycle='archived'; archiving a project just removes it as a selectable source Archiving "Tax 2025" must never make a Library doc vanish from Library answers
C2 — delete-project "with documents" Deletes ONLY docs with no other membership of any kind (built-ins counted) A Library+project doc is Library knowledge — un-filed from the project, never deleted
C3 — temporary chat files Their own scope category — a conversation_documents link, never scope_json scope_json chips would masquerade temp files as a removable manual selection + disable filename auto-scope
M1 — queued-import intent documents.pending_destination_json written at queue time, applied on every indexing success (fileFromPendingDestination runs in the import loop AND inside reindexDocument) A crash mid-import is reconciled to failed; the user's Re-index then re-files to the intended Project/Temporary, not Library (the re-index path files too — DM-1)
Phase F — filing suggestions Rule-based only (no model, no network), never silent / never auto-file; dismissals in AppSettings (no new column) Local-AI classification is a later owner-gated step; a suggestion is inert until Apply
Migration shape Additive only — new tables + nullable columns (the ensureColumn DDL allows no DEFAULT/NOT NULL); NULL-as-sentinel coalesced in code Matches the established scope_json/parseScope precedent

§2 Hard rules (these bound every choice)

  • Additive, nullable columns only — ensureColumn validates DDL with /^[A-Za-z0-9_ ]+$/ (no quotes/punctuation), so every new column is nullable with NULL coalesced in code (e.g. docLifecycle(row): NULL ⇒ 'permanent'). New tables carry full SQL in the SCHEMA constant.
  • Malformed persisted JSON never throws — every parse (parseDocumentScope, parsePendingDestination, parseOrigin) is tolerant → safe default.
  • Privacy/audit data class holds — collection events record id + type + count only, NEVER the collection/project NAME (a project name like "Divorce" is content-ish; the filename allowance does not extend to it). Search/scope query text is still never logged. Enforced by the sentinel-grep test tests/integration/audit-ipc.test.ts.
  • Offline/local — every organization op is a pure local SQLite write; filing suggestions are a pure local rule engine. No network, no model, no telemetry; the feature works with zero models.
  • Encryption at rest — the new tables live in the same workspace DB, so they are encrypted with it.

§3 Data model (additive — db.ts SCHEMA + ensureColumn)

Three new tables; ON DELETE CASCADE on both FKs of document_collections and conversation_documents is load-bearing (C4): openDatabase runs PRAGMA foreign_keys = ON and deleteDocument deletes the documents row directly, so without CASCADE a pre-feature app deleting a doc in a post-feature DB would hit an FK violation. CASCADE makes any build delete a doc cleanly and removes manual membership-cleanup ordering. (The later skills bank_*/invoice_* content tables needed the same treatment — backend audit 2026-06-27 DATA-1 — but since CREATE TABLE IF NOT EXISTS can't add CASCADE to an existing drive, deleteDocument ALSO does an explicit ordered delete of those rows in one transaction; see "Skills — design record" §10.)

collections(id, name, type, description, builtin, color, created_at, updated_at,
            archived_at, retention_policy_json)        -- type ∈ library|project|temporary|archive|smart
document_collections(document_id, collection_id, role, added_at)  -- PK(doc,coll) ⇒ idempotent add
conversation_documents(conversation_id, document_id, added_at)    -- C3 temp-attachment link
  • type='archive'/'smart' are reserved enum strings, not stored as rows in v1 (archive is a lifecycle; smart views are query-time). role='generated' is reserved-unused (N1 — generated docs get no membership). The composite PKs make add idempotent (ON CONFLICT DO NOTHING).
  • Additive documents columns (all nullable): lifecycle (NULL ⇒ permanent), source_relative_path / source_folder_label (folder-import display metadata; no screen shows them since the filing-suggestion removal. A pick that ends in a separator, such as a drive root D:\, matches its files on that separator, and a drive root is labelled D:, #684), pending_destination_json (M1), expires_at (reserved for Phase-E.2 retention, NULL in v1). last_used_at is deferred (L2 — it would add a hot-path write per cited doc).
  • Additive conversations columns: collection_id (the legacy single-project creation anchor) + scope_v2_json (the D1 composite DocumentScope).
  • Migration (idempotent, inside openDatabase): create tables → ensureColumns → seed one Library + one Temporary built-in (canonical English name stored; UI localizes by type) → backfill Library membership for every status='indexed' doc that has no membership and origin_json IS NULL (the M1 status gate + the D3 generated-skip). Re-open is a no-op (membership-guarded). Generated rows get no membership (step is a no-op by construction).

§4 Services (collections.ts)

  • collections.ts (plain functions, no class) — CRUD (createCollection/rename/setCollectionArchived/ deleteCollection), membership (addToCollection/removeFromCollection, idempotent), setDocumentsLifecycle, the C2 predicate projectOnlyDocumentIds (counts ALL memberships so a Library member is spared), and the indexing-success filing entry points fileFromPendingDestination → fileDocumentByDestination (Library default when no intent recorded, so options-less imports stay byte-for-byte). fileFromPendingDestination is the single indexing-success entry point (M1/DM-1): it runs both in the in-session import loop AND inside reindexDocument, so whoever drives a doc to indexed files it by its intent — a crash-interrupted import that the user re-indexes lands in its Project/Temporary, not Library. It is idempotent (Library is unfiled-guarded, pending cleared on first success) and skips generated docs (origin_json set ⇒ no membership, D3/N1), so re-indexing a translation never sweeps it into Library. linkConversationDocument is FK-guarded (N3): verifies the conversation still exists + try/catch the race; if gone, keep the doc in Temporary, drop only the link. The collection case of fileDocumentByDestination is now FK-guarded the same way (DB-1, Chat & Documents audit 2026-07-07): foreign_keys is ON and the membership FK is enforced, so a raw addToCollection against a deleted/unknown collection id threw FOREIGN KEY constraint failed (its ON CONFLICT DO NOTHING catches only the PK). Thrown inside the import loop's try it miscounted the doc failed, skipped its document_imported audit event, and — the permanent harm — left pending_destination_json set so every FUTURE re-index rethrew forever. The fix existence-checks the collection + try/catch the race and degrades to the Library default on a miss (ids-only log.warn), making fileDocumentByDestination TOTAL. The pending-clear UPDATE moved into a finally in fileFromPendingDestination as belt-and-suspenders (the generated-doc origin_json early-return still fires first and never clears — those rows carry no destination). resolveScope is documented in rag-design §13.
  • #571 amendment — an unfiled conversation intent is one of the chat's attachments. A failed conversation-destined import writes no link (N4) but keeps pending_destination_json; M1 meant it only as a filing intent. unfiledConversationDocuments(db, conversationId) now reads it as an attachment too: resolveScope unions those ids (an attach-born chat whose only file failed used to resolve to the whole corpus — rag-design §13.2), and listAttachments adds the FAILED ones (an importing one stays the renderer's pending chip). Parsed with parsePendingDestination, never SQL json_extract (it throws on a malformed row); the partial index idx_documents_pending_dest (post-migration block, the column is migrated in late) keeps the per-ask read to the unfiled rows — checked with EXPLAIN QUERY PLAN on the statement production prepares in collections.test.ts. No new column, no migration: every existing failed attachment is covered as it stands. The rejoin after OCR is pinned: "Make searchable (OCR)" re-indexes the same row, reindexDocument files it by the intent into Temporary + the chat's link and clears it (docs-ipc.test.ts, #570 — the chat pointer's copy rests on it). Residual, pre-existing: deleting a chat's only attachment from Documents still widens it (the link cascades); a flag on attach-born chats would close that.
  • listDocuments stuck-row reconcile — task gate (DB-3, Chat & Documents audit 2026-07-07). The registerDocsIpc list poll reconciles rows left non-terminal by a killed/lock-interrupted run to failed (so the UI offers Re-index instead of a perpetual "in progress"). It fires only when nothing this module tracks is running (!importActive && processing.size === 0) — but doc-task ingestions (translation-materialize, OCR re-ingest) drive documents rows OUTSIDE that processing set, so a poll during their long chunk/embed window would flip a live row to failed. The sweep is now also gated on !ctx.docTasks?.hasActiveTask() (matching the sibling tree/extract sweeps). The now watermark is kept deliberately — NOT swapped for PROCESS_START_ISO: a mid-session lock→unlock strands an import whose updated_at is AFTER process start, and only a now watermark ever reconciles it (a PROCESS_START_ISO watermark would wedge it forever — the exact regression the audit's first-pass suggestion would have introduced). The task gate closes the live-flip hole; the now watermark keeps mid-session recovery working. The skill-run sweep still uses PROCESS_START_ISO (its table bumps no timestamp, so now would be wrong there — the two watermarks are not interchangeable).
  • Documents backend performance — Session 6 (DB-4, DB-5, DB-6, DB-7; Chat & Documents audit 2026-07-07). Four perf/reliability fixes on the same import/list/export hot paths, all additive guards on top of the Session-1 (DB-1/2/3) correctness work.
    • DB-4 — the folder-import queue phase is batched. importDocuments called createQueuedDocument once per file: N single-statement auto-commit transactions + N wasted SELECT * re-reads, all synchronous on the IPC thread over a high-latency USB DB — a multi-second main-process freeze for a few-thousand-file folder before the job even started (the per-row auto-commit pattern DB-1 eliminated for chunk writes). New createQueuedDocuments(db, files) gathers the statSync sizes OUTSIDE the write transaction, then commits all N inserts in ONE BEGIN…COMMIT (ROLLBACK + rethrow on a mid-batch failure → the caller's lease-release catch cleans up, nothing half-queued). The shared bare INSERT is factored into insertQueuedRow (returns the id, no re-read); createQueuedDocument stays byte-identical (still re-reads the full DocumentInfo for its single-doc callers — materialize + ~60 tests). Batch mirrors single-doc insert-regardless behaviour: an unstatable path still queues a row (null size), so the id list aligns 1:1 with the input files and ING-3 in-order push is preserved. DEFERRED — the walk stays synchronous: importDocuments returns {jobId, documentIds} synchronously and the renderer + ~tests depend on the ids being present at return, so expandPathsWithSource (the recursive readdirSync walk) was NOT moved off the hot handler — that would change the return contract. Left for a later pass. (Deviation from the plan's literal test wording: the direct unit passes 4 files — 3 real + 1 nonexistent — and asserts 4 ids in order with sizes-where-statable, rather than "3 ids"; faithfully matching createQueuedDocument's insert-regardless keeps single/batch consistent and the import path unchanged.)
    • DB-5 — listDocuments embedded-count early-out (the count-map cache was DECLINED). The embeddings⋈chunks GROUP BY exists only to flag an indexed doc whose vectors predate an embedder switch (staleEmbeddings); the per-row check fires ONLY on an indexed row, so when no row is indexed — the common case on a mid-import poll (rows are queued/extracting/embedding) — the whole full-corpus join scan is pure waste. It is now skipped when !force && rows.some(r => r.status === 'indexed') is false. The covering CREATE INDEX IF NOT EXISTS idx_chunks_document ON chunks(document_id) was already present (db.ts) — not re-added. The document_id count-map cache was DECLINED (plan decision #4, durable — do not re-litigate): it needs a wider invalidation surface than the F12/PERF-1 resident-vector cache (it must also catch chunk writes that carry no embedding, plus any out-of-band writer), and a stale map surfaces as a user-visible wrong chunk badge / false stale-embeddings flag — poor risk/benefit for a poll-path optimization. The DB-3/ING-2 two-query shape and the resident-vector delta are untouched (no new invalidation coupling — the whole reason the cache is declined). The M7 stale-embedding path (an indexed row present) still builds embeddedCounts unchanged.
    • DB-6 — the jobs map is bounded (IMPORT_JOB_CAP = 16, evict DONE-only). Every import in a long session was retained forever and the importActive list-poll iterated all of them. After each jobs.set the oldest done jobs are evicted down to the cap, mirroring PICKER_TOKEN_CAP — but an in-flight job is never evicted (the loop mutates its status, the renderer polls it; it can also be the oldest entry on a slow import while newer ones finish). A late poll on an evicted (done) id still gets the synthetic done:true from getImportJob, so pollers stop gracefully.
    • DB-7 — export readers decrypt asynchronously (completes the PERF-1 invariant). readStoredDocumentText / readStoredDocumentBytes are now async and use decryptFileAsync + await readFile instead of the sync cipher.decryptFile + readFileSync, so exporting a large encrypted DOCX/original no longer blocks the main process for the whole decrypt+read (every other decrypt on these flows was already async under PERF-1 — this is a fix, not a break). The finally shred still runs after the await; the §22-M1 content boundary is unchanged. The two callers (exportDocument handler, buildOriginalDocumentReader) were already async and now await. The .parse-export-<uuid> / .parse-export-bin-<uuid> transient uniqueness landed in Session 1 (DB-2).
  • Filing-suggestion engine (filing-suggestions.ts, Phase F) — REMOVED 2026-06-15. The auto "suggested project" feature (the rule engine, the read-only docs:filingSuggestions IPC, the per-row suggestion chip, and the dismissedFilingSuggestions setting) was removed as an intentional product decision: it added a near-equal row affordance for a low-value guess. Filing is now fully manual via the row ⋯ / selection toolbar (addToCollection / createCollection). The full original lives in git history (git show HEAD~1:apps/desktop/ src/main/services/filing-suggestions.ts); source_folder_label import metadata is retained.

§5 IPC / preload surface (additive, backward-compatible)

Channel Signature Handler
collections:list/create/rename/setArchived/delete CRUD; delete takes 'membershipOnly' | 'withDocuments' (C2) registerCollectionsIpc.ts
docs:addToCollection / removeFromCollection (documentIds[], collectionId) — Move = add + remove (no channel) registerDocsIpc.ts
docs:setLifecycle (documentIds[], 'permanent'|'temporary'|'archived') ⇒ DocumentInfo[] registerDocsIpc.ts
docs:import (extend) (paths[], options?: ImportOptions) — destination persisted at queue time (M1) registerDocsIpc.ts
docs:list (extend) filter?: { collectionId?, lifecycle?, smart?: SmartListView } — smart shares the pure matchesSmartView with the renderer rail registerDocsIpc.ts
chat:setScope / setCollection / listAttachments composite scope persist · creation anchor · the conversation_documents attachments registerChatIpc.ts
skills:list/get () ⇒ SkillInfo[] · (installId) ⇒ SkillInfo | null (first read reconciles disk→DB) registerSkillsIpc.ts
skills:pick/preview/import OS picker ⇒ path · (source) ⇒ SkillPreview (no write) · (source) ⇒ SkillInfo (validate→place→DS7) registerSkillsIpc.ts
skills:export/delete save dialog ⇒ .skill.zip (package tree only) · default-clear + rm folder — message stamps survive (GAP-1/SKA-38; app skills refuse) registerSkillsIpc.ts
skills:enable/disable/acknowledgeWarning (installId) ⇒ SkillInfo; enable enforces one-active-per-id (DS12) registerSkillsIpc.ts
docs:exportOriginal (#90) (documentId) ⇒ path | null — stored ORIGINAL bytes (any format) via save dialog + atomic saveBinaryExport; encryption-boundary warning; audit ids-only registerDocsIpc.ts

Renderer-untrusted inputs are sanitized at the boundary (sanitizeDestination ⇒ Library fallback; safeIdArray). Every channel mirrors 1:1 in preload/index.ts. Smart views (§7.6) are query-time predicates via the shared matchesSmartView (shared/types.ts) — Generated/Unfiled/Recently added/ Needs re-index/Large/Failed/Audio/OCR — one predicate shared by the rail and docs:list, so the two cannot disagree; they are not stored collections and not pickable retrieval scopes in v1. Since design-guidelines.md §11.16 (2026-09) the rail surfaces only Recently added, Unfiled and Needs attention (composed in the renderer as Failed ∪ Needs re-index); Large/Audio/OCR remain valid docs:list filters with no rail entry.

§6 Generated provenance (Phase D, structured)

A materialized translation/comparison writes a structured GeneratedProvenance ({kind, sourceDocumentIds, sourceCollectionIds?, modelId?, createdAt}) into the reused origin_json (no new column); parseOrigin reads it first, then falls back to the legacy Translation/CompareOrigin shapes unchanged. provenanceView(origin) normalizes both to {kind, sourceDocumentIds} so the UI has one path. The generated row gets zero membership (N1/D3) and is surfaced only by the Generated smart view (origin != null). origin_json is stamped at createQueuedDocument time — BEFORE the row can be indexed (DM-2) — so the Library backfill's origin_json IS NULL guard holds even if the process is killed mid-materialize; the post-success setDocumentOrigin then only re-asserts it and clears original_path. A half-born work-product is therefore never swept into Library. Snapshot semantics are unchanged; the Phase-E generatedStaleness(doc, sources) is a pure, tolerant derivation (no new column, no hot-path write) flagging a row when a source's updatedAt post-dates the output's createdAt (source-changed) or a source is missing/archived (source-removed).

§7 Audit events (id/type/count only)

New AuditEventTypes: collection_created/renamed/archived/deleted and documents_added_to_collection/removed_from_collection/document_lifecycle_changed — metadata is collection id + type + affected count ONLY, never the name. The deliberate asymmetry (filenames are logged, project names are not) is recorded so a future reviewer doesn't "fix" it by logging names. Filing suggestions add NO audit event: Apply reuses documents_added_to_collection, so the suggestion reason (folder / filename pattern / project name) is never logged. The sentinel-grep test seeds a project-name + a folder-label (suggestion-reason) sentinel and proves neither appears.

§8 Accepted v1 trade-offs & deferred work

  • Library == all documents on day one — the distinction earns its keep only as the user adds Temporary/Archived/Project-only docs (intended gradual behaviour).
  • Re-importing the same file yields a second row + vector set (D2) — deliberate de-dup-free import.
  • Pre-feature app on a post-feature DB ignores collections for display but relies on CASCADE for safe deletion (C4) — one-line note in known-limitations.md.
  • Deferred (owner-gated): Phase E.2 explicit retention + Temporary review dashboard (the reserved expires_at column, a review-before-delete UI, default Never, never touching Library/generated/ project-filed docs, shredding sidecars under encryption); last_used_at/"Recently used" (L2); local-AI filing suggestions (Phase F "later"); auto-creating projects from top-level import folders (§11.2 / open question Q8).

History: Phases A–F = commits 5c70021, 7bcd4a1, 39531e8, e0bff6b, 499c3ab, 477f803 (2026-06-14); the full original plan: git show 477f803:docs/document-organization-plan.md.

Skills — design record (Phases S2–S13, §1–§21)

A Skill is a self-contained, local task package (instructions + optional examples/schemas) the user selects to shape one turn. Two tiers shipped: Tier 1 — instruction-only (the body is injected as fenced reference text) and Tier 2 — app-tools (the bundled bank-statement skill runs typed, app-orchestrated tools through a validate→run→validate gate). Tier 3 (sandboxed scripts) is explicitly out of v1. This record consolidates the two working-paper plans (docs/skills-plan.md §1–§19 + docs/skills-s11-plan.md, both deleted at S12 — full text in git history); the security model lives in security-model.md ("Skill-import defences", "App-skill provisioning…", "Skill tool ceiling (Tier-2)"), the drive layout in drive-layout.md, and the accepted residuals in known-limitations.md.

§1 Decisions (the ones that bind as built)

  • DS1/DS2 — files on disk are the source of truth; the skills table is a derived index/state cache. SKILL.md (YAML frontmatter + Markdown body) is canonical; manifest.json is an optional, non-authoritative cache (SKILL.md wins). The shared parser is shared/skill-manifest.ts.
  • DS3/DS19/DS20 — skills are non-secret task knowledge, stored unencrypted as plain folders outside workspace/: app-skills/ (read-only) + user-skills/ (read-write). A folder dropped into user-skills/ installs disabled (DS19); secret material belongs in an encrypted document, never a skill (DS20). (The original encrypted-blob model — DS11 — was revoked.)
  • DS4 — selection is deterministic/manual (picker + Settings + a one-tap suggestion); tools are app-orchestrated — the model never parses tool_calls; it only explains a validated result.
  • DS5 — the skill body is injected as a fenced data block with fixed precedence below the base preamble + grounding rules + a guard line; one skill per turn.
  • DS6/DS8 — permissions are app-computed (restrict-only, clamp-down); in v1 permissions.* is a display string (nothing executes), real enforcement is the Tier-2 ceiling. A skill can never register or self-grant a tool.
  • DS7/DS12/DS15 — a deliberate view-import installs enabled-with-warning; duplicate ids coexist with one active per id by trust-then-version-then-recency precedence; a downgrade is refused outside developer mode (a footgun guard — version is unsigned).
  • DS16/DS18 — a skill applies to one turn (messages.skill_id) with a sticky per-conversation default (conversations.active_skill_id); the per-message glyph marks the answer it shaped. Auto-fire is deferred to S13, gated on an evaluation harness.
  • DS17 — app skills are committed to the repo (app-skills/, text only) and copied by prepare-drive — never network-fetched. Nine bundled app skills now ship (count corrected 2026-08-09, #136/DOC-2 — the prior DOC-106 fix updated drive-layout + README but missed this bullet). Four are Tier-2 tool references — bank-statement (the first, kind: tool, app-orchestrated tools through the §7 gate), invoice (the second Tier-2, proving the gate generalizes to a second content class), document-redaction (read-transform-export), and document-edit (kind: tool, tool apply_document_edits — split out so redaction's privacy posture stays untangled; its own record below). The rest are Tier-1 instruction skills (kind: instruction, allowedTools empty / reservesTools false — they only inject fenced guidance): meeting-protocol (titled Meeting Minutes, the Tier-1 reference) plus the Professional Documents wave — contract-brief, deadline-obligation-finder, what-changed, and share-safe-review (advisory; it points at the redaction tool but declares none and creates nothing). The Professional Documents skills are honest by construction: no legal/compliance certainty, no "fully anonymized" claim, and "ask exactly two documents" / "this is not a complete compliance calendar" guards where coverage is partial. meeting-protocol and invoice are both bilingual-trigger references: their triggers.keywords carry German and English terms, with umlaut/ending singular-plural pairs listed separately (beschluss/beschlüsse, rechnung/rechnungen) because §6 matching is case-insensitive substring (question.includes), so an ending/umlaut breaks the substring and each form must appear in its own right (and short ambiguous tokens — vat/ust/net/gross — are deliberately avoided).

§2 Hard rules (these bound every choice)

Additive-only schema (new tables full SQL, new columns nullable; DS10). No change to CSP, the deny-by-default permission handler, the offline guard, the encryption posture, or packaging (§14 — the loader is pure main-side file I/O + DB; no new renderer capability, no new network path). No new native dependency, fully offline (CLAUDE.md §0). Audit + logs carry ids/counts only; content (skill bodies, the draft question, extracted figures) is never logged/audited (the content-class rule, proven by the consolidated sentinel guard, §12).

§3 Storage & registry (S3)

Skill packages live as plain folders OUTSIDE the encrypted workspace (<root>/app-skills/ read-only + <root>/user-skills/ read-write). Disk is the source of truth; the skills table is a pure derived index + state cache (services/skills/registry.ts), reconciled from those folders the same way services/models.ts discovers manifests and doc-org collections.ts reconciles a DB index. Reconcile inserts new folders (app → enabled; a user drop-in → DISABLED, DS19), updates changed ones while preserving user state (enabled / warning_ack), and marks unavailable (never deletes) a row whose folder vanished — so a transiently-unmounted drive keeps the user's choices and the conversation/message references. A DB rebuild re-derives every row from disk (no orphan). The PK install_id is the deterministic natural key "<source>:<id>" (stable across rebuilds, so the FK-less conversations/messages refs keep resolving); there is deliberately no FK into skills (refs are cleared by an app-level sweep on delete, §4). services/skills/loader.ts has one mode — read the folder — for both sources (no decrypt/transient/shred).

#846 amendment — why a row is off (skills.disabled_reason). A nullable column (one ensureColumn, no SCHEMA_VERSION bump) records the reason with every "off": 'user' (the Settings toggle), 'min_app_version' (the §6.5 gate: the reconcile insert of an app skill, the import gate), 'duplicate' (DS12: the enable IPC's sibling disable, the import's coexist and sibling disables, the reconcile safety net) or 'unconfirmed' (a DS19 drop-in); enabling clears it, and the reconcile's update branch never touches it. The reconcile ACTS on 'min_app_version' alone: an app skill the gate kept off is switched back on once this build's version is known and satisfies the skill (ReconcileResult.reenabled, one content-free log line with the count, no audit event, like every reconcile insert); the DS12 safety net then runs as before, so the built-in wins over an enabled user copy of the same id (today's arrival rule). Every other value, including one only a newer build knows, means "leave it alone", and the reason is read only while enabled = 0. User imports are never switched on by themselves. A row an older build wrote has no reason: "app, off, no reason, installed_at = updated_at" can only be the gate's insert (the insert stamps both from one clock; every later write moves updated_at; the one writer sharing the reconcile's clock, the DS12 safety net, never disables an app row, and every other disable takes a fresh clock), so it is treated as 'min_app_version' and, while the app is still too old, recorded as such. A gate-disabled row an older build touched again (updated by a later drive refresh, or marked unavailable and back) has a moved updated_at, is not inferred and stays off: fail-safe, the user can switch it on. Builds up to v0.1.65 read the table with SELECT * and write it with explicit column lists (verified at v0.1.50, v0.1.60 and v0.1.65), so they ignore the column. A DB rebuild re-derives the gate's reason from disk; a 'user' reason on an app skill does not survive a rebuild, exactly as the enabled choice itself never did.

§4 Import / export / delete lifecycle (S4)

services/skills/installer.ts owns the lifecycle behind IPC. Import validates a .skill.zip or folder with a net-new dependency-free member-by-member safe extractor (built-in node:zlib + a central-directory parser; full defence matrix in security-model.md), stages the whole tree, then places it as plain files at user-skills/<id>/ (folder name == manifest id). Two DoS-hardening bounds sit in the staging loop (audit S-1/S-2, Phase 8): inflateEntry rejects a member whose central-directory compressedSize exceeds the per-file cap before slicing/inflating — bounding the synchronous inflate input, not only its maxOutputLength output (a legitimate text member never compresses past the cap); and after the common-prefix strip the loop re-asserts safeRelPath on the stripped path and rejects two members that collapse to the same relPath (SKILL_IMPORT_ERRORS.duplicatePath) so a later duplicate can't last-writer-wins shadow a preview-validated SKILL.md. It then reconciles the row to enabled-with-warning (DS7) — unless an enabled app skill of the same id is already effective, in which case the import coexists disabled (trust-first precedence, DS12). A lower version is refused unless developer mode (DS15). Delete clears the sticky default ONLY (full-audit 2026-07-11 GAP-1 — the SKA-38 contract): in one transaction it nulls conversations.active_skill_id pointing at the install id and deletes the row (no FK to cascade), then removes the folder; messages.skill_id is deliberately KEPT — the per-message stamp is provenance, the JOIN title resolves to NULL and the renderer shows "(removed skill)", so the glyph

  • the "answer without it" undo survive deletion. App skills refuse. Enable enforces one-active-per-id. The registry handle reconciles disk→DB once per app process: the startup pass when the DB is already open (plaintext dev), else the first read after the first unlock (a reconciledThisSession guard, not an unlock hook; it is never reset, so a later lock and unlock does not re-scan). The importer/deleter call reconcile() explicitly after mutating disk. A skill folder copied onto the drive while the app is running therefore appears only after a restart (or the next import/delete). Audit events (skill_imported/deleted/enabled/disabled) carry ids/counts only.

§5 Selection & prompt integration (S6+S7)

A single shared resolveTurnSkill (services/skills/turn.ts) feeds both chat channels — registerChatIpc (sendChatMessage) and registerRagIpc (askDocuments gained a skill arg, §22-A1) — so a documents conversation gets the skill too; it reads the per-turn override or the sticky default and skips a disabled/deleted/unavailable skill gracefully (resolves to none, never an error). services/skills/prompt.ts builds the fenced skill block — a delimited DATA block (BEGIN/END framing + the guard line SKILL_GUARD_LINE as the last app-authored line), never a system rule (§22-H2). Placement: in plain chat the fence is bracketed inside the system message after BASE_SYSTEM_PROMPT (buildSystemPrompt(skillFence?)); in grounded answers it rides the user turn with the excerpts (buildGroundedPrompt(question, chunks, skillFence?)), where the grounding/citation rules keep precedence. The fence is pre-sized in prompt.ts against the base preamble + final turn (+ grounded excerpts) so it can never starve them — fitMessagesToContext only drops older history (§22-A6); over budget it reduces by whole paragraphs, and if even the minimum won't fit it is omitted entirely rather than truncated mid-instruction. The assistant row is stamped with the install id only when the fence was actually placed (§22-A5); a no-context answer stamps NULL, and listMessages LEFT JOINs skills so a deleted skill resolves messages.skill_id back to NULL. The renderer surfaces a quiet composer "Skill: …" picker + a per-message skill glyph on the answer it shaped (icon + word, never colour-only).

§6 Suggestion heuristic (S8)

services/skills/selector.ts scores each enabled skill's cached triggers against the turn — keyword hits in the draft question (the strong signal) + the in-scope documents' MIME types / filename globs (supporting) — fully deterministic, no model, no network, with a fixed threshold (a lone document signal never fires). services/skills/suggest.ts resolves the conversation's scope main-side from the conversationId (§22-C4), gathers the signals, and returns at most one offer over suggestSkills(conversationId, question?). The question is content: scored but never logged. The offer is surfaced in the composer picker — pinned atop the menu when it is open, and (U-3) mirrored as a quiet, named hint on the CLOSED trigger (chat.skill.suggestedHint, a .skill-suggest-hint footer affordance) so a user who never opens "Skill: none ▾" still sees the nudge. ChatScreen recomputes the offer proactively as the draft changes (debounced ~400 ms via the same defensive suggestSkills call, only when no skill is picked) on top of the open-time refresh. Both surfaces keep the same invariants: no canvas chip, no settings key, inert until tapped, never auto-applied (§22-D3). The closed hint shows only while no skill is selected and the offer was not declined — an explicit "None" pick sets a renderer-side per-draft suggestionDismissed flag (reset on send / conversation change) so it never re-nags; one tap selects the skill. Auto-fire (S13) is the opt-in extension of this same scorer that does apply a skill without a tap, behind a separate higher threshold + an opt-in + a per-turn undo — see §18.

Scale-up revisit trigger (STR-1 review §5.3, 2026-07-20): deterministic keyword suggestion is right-sized at the current 9-skill catalog; the routing literature's degradation zone for keyword approaches starts around 10–20 candidates. If the catalog (counting user-imported skills with trigger vocabularies) approaches that, the documented next step is embedding-based suggestion over the skill descriptions/trigger vocabularies — the app already ships a local embedder for RAG, so it stays offline. A revisit condition, deliberately not built now.

First-selection skill info card (#46, 2026-07-10)

Beta feedback: selecting a skill changed behavior in ways users only discovered afterwards (#44 the run button, #45 the .txt output) — the picker row's one-line description was the entire in-app explanation. Now the first pick of a skill (ever, by declared id) surfaces a compact SkillInfoCard above the composer: three one-sentence lines — what it does, what it needs to apply (when that's missing the skill silently routes to a plain answer), and its key honesty limit — plus the pick-lifetime footer ("applies to your questions in this chat until you change or clear it; Keep for this conversation saves it") and a Learn more link. The lines come from shared/skill-info.ts, a pure-data catalog keyed by manifest id holding skills.info.<id>.what/ needs/limits i18n KEYS (EN+DE; the skill-tools.ts descriptor-table precedent) — app skills only; a user/unknown skill falls back to its own localized description, so the app never invents honesty claims about content it didn't author. Once-per-skill memory is AppSettings.skillInfoSeen: string[] (declared ids — content-free; the settings service's generic string[] element-wise sanitizer covers it), marked seen on first showing; afterwards a quiet ⓘ next to the picker chip (SkillPicker's onInfo prop) re-opens the card on demand, and it hides whenever it no longer matches the ACTIVE pick. An unresolved seen-state (settings read pending/failed) shows nothing — a missed first card, never a re-nag. Learn more deep-links the Skills screen's existing detail modal through a one-shot renderer-side mailbox (renderer/lib/skillDetailRequest.ts — requestSkillDetail(installId) + consumeSkillDetailRequest() in SkillsTab's list-load effect); nothing crosses the IPC. Tests: SkillInfoCard.test.tsx (catalog lines, description fallback), SkillInfoFirstPick.test.tsx (ChatScreen: first-pick shows + persists, seen skill needs the ⓘ, active-pick gating, Learn-more navigation), SkillsTab.test.tsx (deep-link opens the modal / unknown id opens nothing), db-settings.test.ts (skillInfoSeen round-trip + junk sanitization).

§7 Tier-2 tool gate (S10)

services/skills/tool-registry.ts is the static, app-owned map of SkillTools. A skill never registers a tool: it only declares names via allowedTools, and the effective set is declared ∩ registry ∩ wired (resolveWiredTools — A2 removed the vestigial third userGrant leg, audit §6.4-low; see the A2 note below). Runs are app-orchestrated (DS4): the app calls runSkillTool(tool, {skillId, input, ctx, confirmed}) directly. The gate's fixed order: (1) refuse if the AbortSignal is already aborted; (2) validate input against inputSchema (a hand-rolled JSON-Schema subset — no validator dep) and refuse without calling the tool on a bad shape; (3) refuse a write/export tool lacking confirmed:true; (4) run inside a narrow SkillToolContext whose documentIds the gate hands over frozen (un-widenable scope), with no Db/SQL/FS/net handle; (5) validate output against outputSchema — a wrong shape fails the run; (6) bracket with ids/counts-only audit (skill_run_started/done/failed = {skillId, toolName, documentCount}). S10 shipped the gate with one harmless reference tool (count_selected_documents). The full ceiling rationale is in security-model.md "Skill tool ceiling (Tier-2)". (Audit X-2, Phase 10: count_selected_documents is kept deliberately as the gate's test-only canary — registered, but no bundled skill declares it and it is intentionally not wired to a run.ts dispatch seam (tool-runs.ts buildToolRunner returns null for it), so it is registry-only and exposes no live capability. It is the minimal reference the gate tests exercise end-to-end. Both halves are pinned: skills-tool-registry.test.ts asserts it is registered; skills-tool-run-ipc.test.ts asserts buildToolRunner returns null for it — so removing it OR wiring it up both fail a test.)

(Audit SEC-1, backend-audit 2026-06-27 Phase 6 — the trust gate at the runnable-tools surface. The kind:'tool' flip (§8) made a declared allowedTools effective for any non-instruction skill, and the run surface gated on enabled/compatibility/confirm but not on source — so the deliberate posture "Tier-2 tools run for source === 'app' skills only" is now enforced explicitly. A single named predicate skillCanRunTools(skill) (tool-runs.ts, source === 'app') is the gate; it short- circuits runnableToolNames to [] for a non-app skill (so listRunnableTools + the run bar offer nothing) and is re-checked at startSkillRun (defense-in-depth: a forged IPC call with a user skill's id is refused with the generic, content-free run.unavailable string — no title/path leaks, audit posture intact). A user kind:'tool' skill still keeps its declared allowedTools (the parser is untouched) for a future per-tool grant UI — it just runs none of them until that UI exists. Full rationale in security-model.md "Skill tool ceiling (Tier-2)" → SEC-1. API-3: the audit/run-state documentCount is the v1 constant 1 because every wired tool is single-document; an in-code TODO at registerSkillsIpc.ts marks that it must become a real count if a multi-document tool ever lands, else the audit would understate scope.)

(A2, audit §6.2/§6.4-low — the self-describing tool registry. A 9th tool used to cost ~9 hardcoded edits (the wired-list, the runner switch, the renderer label/done maps, the save-dialog constants, two locale catalogs) and the drift shipped user-visible bugs: one CSV save dialog served every export, and one app-wide run controller fired "a skill is already working" across unrelated conversations. A2 makes ONE SkillToolDescriptor per wired tool in shared/skill-tools.ts the single source — {name, labelKey, seamKind, confirm, resultShape, doneKey?/reconcileKeys?/redactionKeys?, dialog?} — and derives the rest: WIRED_TOOL_NAMES (the wired-list), the buildToolRunner guard (dispatch parity — a tool with no descriptor yields null before the switch), the renderer's label/done copy (SkillRunBar), and each export's save-dialog metadata (descriptor.dialog). The table is pure data importable from BOTH processes (like shared/i18n), so the renderer builds its maps from the same source the main dispatch uses; a parity test pins descriptor ↔ registry (every wired name registered; the only registered tool without a descriptor is the X-2 canary; confirm matches the permission-derived toolRequiresConfirmation; every export carries a dialog). The bank-shaped run-outcome field transactionCount became the domain-neutral count (additive; transactionCount kept as a deprecated mirror on SkillRunState for one release; the renderer reads count ?? transactionCount). The trust model is unchanged: a descriptor is app-authored metadata, not a capability — a skill still cannot register or self-grant a tool, and skillCanRunTools (SEC-1) is the trust decision. Full rationale in security-model.md "Skill tool ceiling".)

§8 Bank-statement tools + the run seam (S11)

S11 wires the first Tier-2 feature. The bank specifics live in services/skills/tools/bank-statement.ts (deterministic, offline parsers — kept out of the generic registry, §13); five tools are registered: extract_transactions (read-only; reads a statement's page-addressable chunks through the only content reach a tool has, SkillToolContext.readDocumentChunks — scope-bounded, still no raw handle), validate_statement_balances (printed vs computed running balance → a per-row reconciled flag, honest ok/mismatch/unknown), categorize_transactions (deterministic rules → category_id, seeding the built-in categories/rules), summarize_cashflow (read-only inflow/outflow/net totals — figures are content, not surfaced in v1), and export_transactions_csv (confirm-gated export-file). The app-orchestrated run seam services/skills/run.ts is what a user action triggers (DS4): it records a skill_runs lifecycle row (ids/refs only), builds the narrow context, runs the tool through the gate, and persists atomically (ROLLBACK ⇒ no partial rows). The four downstream tools operate on the already-extracted rows — the seam loads the latest statement for the in-scope document and passes them as structured input, so the tools stay pure and the §7 ceiling is unchanged (no new accessor). (Phase-4 perf, audit P-1: the read-only downstream seams take an optional preloaded rows arg — the analysis handler loads the rows once and supplies it, so the seam skips its own load — and return their validated structured output for in-process reuse by that handler; both are no-ops for the run-bar/IPC path, which passes no rows and maps counts only. See §19.) The CSV export is the first FS-write from a skill tool: the pure tool only produces the CSV string; the seam writes it main-side to a user-chosen path via a save dialog, gated on the export-file confirm — the path + content never touch any log/audit (only "saved N rows" is surfaced), and free-text fields are neutralized against spreadsheet formula-injection (S12 fix). The bank SKILL.md is kind:'tool', which makes its declared allowedTools effective (the SL-1 parser path keeps the list only for kind:'tool') and uses the reconcile/validate body. Geometry-aware PDF reading for columnar statements (Phase 31, D50–D58) + the opening/closing-balance completeness gate are recorded in §21 (the pdf-layout.ts layout mode + extractStatementBalances/assessCompleteness extend these same bank tools; in-code comments here citing architecture.md "Skills — design record" §8 for the bank domain still resolve, the geometry specifics live in §21). The packaged schemas/transaction.schema.json (the machine-readable row contract that ships inside every bank-statement export) is test-pinned to the live TRANSACTION_ROW_SCHEMA in tools/bank-statement.ts by tests/unit/skills-transaction-schema-parity.test.ts — a structural compare (property set, per-property type/pattern/minimum/minLength, required) that kills the "hand-maintained mirror" drift risk (skills-audit-2026-07-07 SK-6); the two are field-for-field identical today, category included (an optional persisted label a categorize run attaches, never emitted by the extractor).

The invoice skill is the SECOND Tier-2 reference (app-skills/invoice/, id:'invoice'), proving the gate generalizes to a second content-class domain with strong EN+DE coverage. It covers the same five-tool shape as bank-statement: five tools in services/skills/tools/invoice.ts — the three core extract_invoice (read-only; the same readDocumentChunks reach over the frozen scope), validate_invoice_totals (read-only; deterministic checks within a half-cent epsilon — line items → net, net + tax → gross, tax vs. rate — each ok/mismatch/unknown, an honest reconciled verdict + a resultKind discriminator like validate_statement_balances), and export_invoice_csv (confirm-gated export-file, the line-items CSV). Format-transformation exports (invoice-format-2026-07-01): the domain adds export_invoice_json / export_invoice_xml — pure serializers (buildInvoiceJson/buildInvoiceXml, XML entity-escaped, 2-dp, stable shape) over the ALREADY-extracted invoice, behind the generic confirm-gated runInvoiceFileExport seam; and an INLINE path (detectFormat() in analysis/invoice.ts) that renders "… als JSON/CSV/xml" in a fenced code block. Design decision (grounded workflow): format transformation is pure serialization of a structured object — it takes no model (a serializer cannot invent a figure the parser did not, so §22-D1 holds by construction). LLM-assisted extraction is deliberately NOT adopted: the shipped small Q4 model hallucinates figures and grammar-constrained decoding guarantees valid structure but not valid values — so a guarded LLM extractor (propose → deterministic re-verify vs a verbatim quote + reconciliation → drop-on-failure) stays deferred behind a D52 gold-set recall measurement, mirroring the Phase-33 "a category is not a figure" boundary. See BUILD_STATE.md INVOICE-FORMAT-1. Parsing is DETERMINISTIC + OFFLINE and CONSERVATIVE (invoice layouts vary — a known limitation that improves later): header fields and totals are read from labeled lines only, line items split a description from a trailing quantity + trailing unit-price/line-total money tokens, and anything that cannot be confidently parsed is dropped (header fields are individually optional, never guessed). The deterministic money/date primitives (parseAmount/parseDate/detectCurrency) and the CSV formula-injection neutralization (csvField) are now shared by both domains in services/skills/tools/money.ts — one parser per locale rule, one audited export boundary. The Unicode word-boundary matcher wordIncludes lives here too (audit C-1, Phase 2): both the deterministic categorizeRow and the LLM prefilterCategory now call it, so a coincidental substring (coffee⊃fee, atmosphere⊃atm, mühlohn⊃lohn) can no longer mis-file a row to Fees/Cash/Income — and the two categorization paths agree on every description rule. It now has a two-sided STRICT mode (the short, ambiguous English tokens) and a one-sided COMPOUND mode (full-audit-2026-06-29 BL-3) the rule table opts the unambiguous German keywords (gebühr/gehalt/überweisung/bargeld) into, so a de-AT closed compound (kontoführungsgebühr) categorizes while the C-1 guards hold (see the 2026-06-29 Phase 1 note below). The run seam is the sibling services/skills/invoice-run.ts: same skill_runs lifecycle, same no-partial-persist (BEGIN…COMMIT/ROLLBACK), same B2/B4 guards, latest-invoice-for-document downstream target, structured input (no new SkillToolContext accessor — the §14 ceiling is unchanged). The dispatch (tool-runs.ts) wires the five names; the controller / IPC / renderer stay domain-free (the renderer adds only the five tool labels

  • the invoice resultKind copy). Content-class isolation holds: the new invoices / invoice_line_items tables + skill_runs never appear in any log/audit/export (audit stays {skillId, toolName, documentCount}).

A1 — one domain-parameterized run seam (audit §6.1 + §6.4 plumbing bullet; 2026-07-03). invoice-run.ts was originally a ~500-line layer-for-layer copy of run.ts — the class that shipped the "45 vs 22 transactions" divergence (two drifted segment readers + a missed replaceExisting) and R3's one-path-only staleness fix. A1 folded that copy into ONE generic engine in run.ts (runDomainExtractionInner, prepareDomainRun — which owns the SINGLE R3 staleness re-extraction path — domainPersistFailure, runDomainFileExport) driven by a per-domain DomainRunConfig ({extractToolName, latestId, isStale, reExtract, deleteForDocument, insertExtraction, countOf, load, toToolInput, buildDownstreamReader, messages}). run.ts holds BANK_RUN_CONFIG + the thin public adapters (runBankExtraction, the four downstream seams) that own the per-document lock and reshape the generic result to the domain-named statementId/transactionCount fields; invoice-run.ts shrank to INVOICE_RUN_CONFIG + its adapters + insertInvoiceExtraction + the ONE authoritative loadInvoice (now exported, so analysis/invoice.ts imports it instead of a byte-identical copy). Strictly behavior-preserving (green-to-green, unchanged test count) — every difference the copies had is a config value/function. One incidental difference is PRESERVED, not fixed: the downstream-run ctx reader is built lazily (bank: buildReadDocumentChunks, no I/O) vs eagerly (invoice: resolveDocumentReader, a discarded full-segment read) — inert because structured-input tools never read chunks; unifying it would change per-run I/O, so it is buildDownstreamReader config and left for a follow-up. The duplicated analysis-handler plumbing (singleInScopeDocument ×3, shouldFallThroughOnEmpty, computeCoverage, fmt, the citation query + [Sn] projection) is lifted into services/skills/analysis/common.ts; the per-domain citation SELECTION strategy (bank page-narrow+head; invoice head+tail) stays in each handler and calls the shared loadCitationChunks/chunksToCitations.

The document-redaction skill is the THIRD Tier-2 reference (app-skills/document-redaction/, id:'document-redaction'), and the read-transform-export shape the bank/invoice domains don't exercise: a single redact_document tool that reads the whole selected document (the same readDocumentChunks reach over the frozen scope), masks the personal data it can detect, and produces the redacted text + per-category counts — which the seam writes to a user-chosen file (the same confirm-gated export-file boundary as the CSVs). It has no content-class data table and no BEGIN…COMMIT: the deliverable is a file, not rows, so services/skills/run.ts's runDocumentRedaction records only the skill_runs lifecycle row (started → terminal; result_ref stays NULL) and surfaces only totalRedactions (a count) + a content-free resultKind ('redacted' when something was masked, else 'clean', handled in the renderer like validate's discriminator). Detection (services/skills/tools/redaction.ts) is deterministic, offline, regex-only — e-mail, URL, IBAN, date (validated via the shared parseDate), phone — applied in a fixed order so masks never overlap (email → url → iban → date → phone; e.g. dates are masked before phones so a dotted date can't be eaten by a 0-leading phone shape), each match replaced by a fixed category token so redaction is idempotent. It is the privacy-aligned skill and the strongest content boundary of the three: the detected values never reach any log/audit/skill_runs row, and the redacted text lands only in the user-chosen file. Honesty posture (recorded in known-limitations.md): regex redaction is best-effort, not a guarantee — there is no ML and no name detection, so it deliberately misses anything without a recognisable pattern and prefers a false negative over corrupting text; the SKILL.md body + the "done" copy tell the user to review the copy before sharing, and the app never implies "fully anonymized" or compliance. The dispatch (tool-runs.ts) wires the one name (null without the MAIN-side saveTextFile); the controller / IPC / renderer stay domain-free (the renderer adds only the tool label + the redaction resultKind copy).

§9 The run trigger + UI (S11b/S11c)

A run is started from a user action, never the model. A generic controller services/skills/run-controller.ts owns each active run's lifecycle (state/progress/cancel) and knows nothing about banks; the bank seam is handed in as an opaque runner by the dispatch services/skills/tool-runs.ts (the one place allowed to map a tool name to run.ts — §13). Concurrency is keyed per-document (A2, audit §6.2): the controller holds a Map<documentId, ActiveRun> so unrelated documents/conversations run in parallel; only a second run on the same document is refused. (The old single app-wide slot fired "a skill is already working" across unrelated chats. The doc-lock below — §9-PC-1 — is the real serializer of true same-document write conflicts, so per-document concurrency here is safe.) Since #606 lock and quit cancel every running run, and a stop or switch of the chat model cancels the runs streaming on it (CB-5 "#606 amendment"). Four generic skills:* IPC channels (listRunnableTools / startSkillRun / getSkillRun / cancelSkillRun) wrap it: all requireUnlocked, the document scope resolved main-side (§22-C4), the run returning ids/counts only (SkillRunState = state/progress/counts, never the rows). The renderer's calm SkillRunBar (a lib/skillruns.ts polling store — no new event channel) shows the offer, the busy row ("Running: <tool> on <N> documents… Cancel"), and the result; write/export tools are gated by a ConfirmDialog before the run starts. Only an IN-FLIGHT run (running / state-unknown) suppresses the offer (#44): a terminal, un-dismissed result row renders ABOVE a restored offer, so the deterministic routing answers (which name the run button unconditionally — see the routing-handler record below) can never point at a button a stale result is hiding. For the two document-transform tools (the descriptors carrying a docxDialog) the confirm body also states the output format up front (#45) — derived renderer-side from the selected target's extension, the same signal main's buildOriginalDocumentReader branches on: .docx keeps its Word format, anything else saves as a plain-text .txt copy (chat.skill.confirm.outputDocx/outputText; unknown target name → the full outputMatrix line, never a guess). The renderer derives each tool's label + done copy from the shared SkillToolDescriptor table (A2 — no parallel renderer copy maps), rendering the reconcile/redaction result shapes from a content-free resultKind discriminator ('reconciled' | 'unreconciled' | 'unchecked'; 'clean' | 'redacted') — the controller/IPC stay bank-free (the discriminator is an opaque string; the meaning lives only in the descriptor's copy keys). The run's count rides SkillRunState.count (A2's domain-neutral rename; transactionCount mirrored one release).

Run-UI target document for a multi-doc scope (audit U-1). The v1 tools are single-document, but a conversation's scope can hold several indexed documents. Rather than silently acting on docIds[0] with an opaque "1 document" label, the run UI surfaces — and lets the user choose — the target: listRunnableTools returns RunnableToolSet = { tools, documentIds }, where documentIds is the in-scope indexed ids in main's resolution order ([0] = the default target). The renderer maps those ids → NAMES from its own already-loaded document list (docs/attachments in ChatScreen), so a document title/filename never crosses the IPC (the §6 content-adjacent posture): SkillRunState and the skills:* channels stay ids/counts only. With exactly one in-scope doc the SkillRunBar shows its name (a disabled chooser); with more than one it shows a small Radix dropdown (the DepthMenu pattern) and passes the chosen documentId to startSkillRun. That id is UNTRUSTED: startSkillRun re-resolves the in-scope set and refuses an id not in it (main.skills.run.documentOutOfScope) — never trusting a renderer-supplied id past the scope filter; documentCount stays the honest 1 (a single-doc tool), not "all N". The busy/result row names the running target from a renderer-remembered name (resolved at launch from the same list), falling back to the legacy count label when unknown (e.g. after a remount). The redaction routing answer is likewise count-honest: with scope > 1 it uses skills.redactionRouting.answerMulti ("pick which document on the button"), still content-free. Post-extract categorize is an explicit offer (audit U-2, Phase 6): a read-only extract no longer silently starts the LLM categorizer; after a successful rows>0 extract the result row offers a one-tap "Categorize transactions" follow-up that targets the SAME document via a renderer-remembered id (runTargetId, the sibling of runTargetName) — see §22. The model pass is user-initiated; the run state stays content-free (no documentId in SkillRunState).

Cross-lane write safety — per-document serialization (audit PC-1, Phase 9). Three INDEPENDENT execution lanes can touch the same bank/invoice tables (§22 / the audit §2.3): Lane A the chat analysis auto-run, Lane B this SkillRunController button run, Lane C the DocTaskManager categorize. The main process is single-threaded, so the hazard is not an OS data race but cooperative interleaving across await points — one lane parked at an await (e.g. re-reading the stored document) while another runs its DELETE+INSERT on the SAME statement (the cardinal case: a chat re-extract replaceExisting DELETE racing a button/categorize run → "statement vanished mid-read", orphaned rows, a nondeterministic final state). A lightweight in-process per-document async mutex (services/skills/doc-lock.ts withDocumentLock(documentId, fn) — a Map<documentId, Promise> chain, re-entrant within one async call chain via AsyncLocalStorage) now serializes every write-capable section by documentId: the write seams (runBankExtraction incl. its replaceExisting DELETE+INSERT, runBalanceValidation, runCategorization, runInvoiceExtraction, runInvoiceTotalsValidation) self-lock, and the two MULTI-step lanes wrap their WHOLE sequence in one outer withDocumentLock (the analysis handlers' extract→validate→categorize, and runCategorize's extract→categorize-persist), so a re-extract from another lane cannot slip BETWEEN a lane's own steps (the inner self-locks are re-entrant no-ops under the outer hold). R9 (skills-audit-2026-07-03 SKA-28) closed the last two unlocked downstream seams: runCashflowSummary and runDomainFileExport (all CSV/JSON/XML exports) now hold ONE re-entrant lock across prepare (incl. the R3 staleness re-extract) + row load + serialization — previously the self-locked re-extract RELEASED before the load, and a competing replaceExisting extract could interleave in that microtask gap (empty CSV, "saved 0 rows"). The export's hold is released BEFORE the save dialog (the serialized text is materialized first — a minutes-open dialog must not block the categorize doctask / chat analysis on that document); redact_document still needs no lock (no bank/invoice table). R9 (SKA-24) also made acquisition abort-aware: withDocumentLock(id, fn, signal?) — a waiter still PARKED behind another lane (a run queued behind a long categorize) rejects with AbortError on cancel instead of a dead "running" spinner; the published chain tail still settles (the aborted waiter releases its own link), so later callers never wedge. The seams thread deps.signal, the analysis handlers thread the turn signal, the categorize doctask threads its task signal. Posture: NO new DB/FS/net capability (an in-memory map in the one main process; the workspace DB is single-writer anyway), no schema change, no IPC change, the audit payload still {skillId, toolName, documentCount}; the key is a document id (never content) and nothing new is logged. The DELETE+INSERT re-extract is already one BEGIN…COMMIT — the mutex serializes lanes, that txn keeps a single re-extract atomic (no new transaction was added). Granularity: per document — unrelated documents still run fully concurrently. No deadlock: the doc lock is finer than DocTaskManager.acquireChatSlot() / the ModelSlotArbiter and is always released in a finally; the analysis lane acquires the chat slot FIRST and only then the doc lock, and Lanes B/C never acquire the chat slot — so no party ever holds the doc lock while waiting on the chat slot (no cycle).

Renderer run lifecycle — the per-run store (skills-audit-2026-07-03 U6, SKA-6/17/18/25/29/37/38/39/40/41). A2 made runs per-document concurrent MAIN-side, but the renderer kept a SINGLE module-level active run and ChatScreen rendered that one app-wide run's bar in EVERY conversation — a second run silently abandoned the first, a conversation switch could categorize the WRONG document, and a routed answer could be dismissed from the wrong chat. U6 gives the renderer the same per-document model A2 gave the controller. renderer/lib/skillruns.ts is now a multi-run store keyed by runHandle: each entry carries {run, conversationId, documentId}, every live handle is polled on its own timer, and the useSyncExternalStore snapshot is rebuilt (a new array) ONLY on a real change — a shallow-compare (state/count/resultKind/progress) gates the notify, so a 400 ms no-op poll no longer re-renders ChatScreen (SKA-39). ChatScreen derives the active conversation's run via pickConversationRun and renders the busy/result bar ONLY when conversationId === activeId; a quiet "working in another chat" chip covers runs elsewhere (SKA-6). Poll resilience: N consecutive failures flip the entry to a labelled "state unknown" row rather than silently dropping a live run (SKA-40). One poll runs per entry at a time (#688, the #680 latch): a tick that finds the previous getSkillRun still resolving skips, so overlapping fast failures cannot give up under a slow call whose late answer would revive a row nothing polls. Reload re-attach: a listSkillRuns IPC (ids/counts only — SkillRunState[], which now additively carries the content-free conversationId? + documentId?) lets a freshly-mounted renderer re-adopt every run main still holds (running AND terminal-unacknowledged), so a finished run's outcome is shown/acknowledgeable after a reload; a busy refusal returns the running handle as a fallback re-attach path; the controller TTL-sweeps never-acknowledged terminal runs so its Map stays bounded (SKA-17). The routed-run relay invariants survive the rewrite: the answer lands only in the launching conversation (C1 — the bar is conversation-gated, so a foreign run is simply not this effect's run), routed under the RUN's skill (C2), pinned to the run's document resolved from the store entry BEFORE acknowledge (ux-6). Confirm-refusal: the post-extract Categorize offer is hidden when its remembered document left the current scope, and MAIN hard-refuses a confirm-gated run whose requested document is out of scope even at a single-doc scope (SKA-29 — never trusting main's single-doc fallback for a write/export; read-only tools keep it). The transcript's undo/Try again render only on the conversation's LAST message when it is the assistant turn (SKA-37), and the glyph + undo key off the persisted messages.skill_id with a "(removed skill)" label so a deleted skill keeps its provenance (SKA-38). The run bar's aria-live region is a single always-mounted status container (SKA-41); the 'new'-composer pick is cleared after being carried onto the created conversation (SKA-18); and the cancel IPC requires a non-empty handle, with requireUnlocked on get/list/cancel/clear (SKA-25). Full residuals in known-limitations.md.

§10 Data model (additive db.ts)

skills (the registry index, keyed by install_id) + nullable conversations.active_skill_id / messages.skill_id refs (S3). skill_runs (the run-history lifecycle — ids/refs only: document_ids_json is ids, result_ref is a bank_statements.id, error is a friendly/technical reason; S11a). The content-class bank tables bank_statements + bank_transactions (S11a) and bank_categories / bank_category_rules / bank_corrections + bank_transactions.category_id/ reconciled/confidence (S11c) hold real figures: encrypted DB only, never logged/audited, never exported (§9.5) — distinct from the non-secret skill packages. The invoice domain adds the parallel content-class tables invoices (header + totals + a totals_reconciled flag) + invoice_line_items (the line-item rows), with the same isolation; skill_runs.result_ref points at a bank_statements.id or an invoices.id, never inline content.

Deletion safety (backend audit 2026-06-27, DATA-1). The bank/invoice tables reference documents (and their parents) — but the original S11a/S11c DDL omitted ON DELETE CASCADE, while deleteDocument deleted only chunks/embeddings/the row. With foreign_keys = ON that left the final DELETE FROM documents to throw SQLITE_CONSTRAINT_FOREIGNKEY after the file was shredded — a corrupt, undeletable document. Fixed two ways: (1) deleteDocument now purges every derivative in FK order inside one transaction — ingestion/index.ts purgeDocumentDerivatives (embeddings → chunks → tree_nodes) → skills/run.ts purgeSkillDataForDocument (bank_corrections → bank_transactions → bank_statements, invoice_line_items → invoices), the single authoritative teardown list (MAINT-1) reusing the re-extract delete — and shreds the workspace copy only after the commit; and (2) the schema now declares ON DELETE CASCADE down both chains, so a fresh DB stays safe even on a bare DELETE FROM documents (defense-in-depth for the next table). CREATE TABLE IF NOT EXISTS can't add the cascade to an existing drive, so there the explicit ordered delete is what's load-bearing — no table-rebuild migration (the ordered delete already closes the bug). Pinned by tests/integration/document-delete-derivatives.test.ts (real bank+invoice extractions deleted cleanly on a simulated pre-fix drive; teeth = the un-cascaded FK throws without the ordered delete; plus the fresh-schema cascade).

Financial-extraction correctness (backend audit 2026-06-27, Phase 2 — BL-1/BL-2/BL-3). Parsing/ aggregation-logic only; no schema or audit-payload change (figures stay content-class — never logged/ audited/exported).

  • BL-1 — value-date column (the LINE PARSER, tools/bank-statement.ts parseLine + tools/invoice.ts parseLineItem). A DACH statement row often prints BOTH a booking date (Buchungstag) and a value date (Wertstellung/Valuta) as its first two columns. The shared MONEY_RE reads a dd.mm.20yy date's .20yy tail as a 2-decimal amount (07.06.2026 → 07.06.20 → 706.20), so a value date left in the scanned remainder either became the row's first "money" match (empty description → the row silently dropped) or fed a wrong figure as the amount. Fix: a shared tools/money.ts splitLeadingDates(line) strips the whole leading run of date tokens before the money scan (not just the first token); parseLine records the first as the booking date and a second as the optional valueDate (schema/CSV already carry it), parseLineItem strips and discards (line items have no date field). Capped at two leading dates (booking + value), stops at the first non-date token (a description is never consumed), handles either column order. The money scanner's last-token readers (lastMoneyOnLine / balance / invoice-total) take the trailing figure — but a TRAILING date token corrupts that (Endsaldo 1.234,56 EUR per 30.06.2026 read 30.06.20 → 3006.20), so the original "they were never affected" claim was WRONG: corrected by full-audit-2026-06-28 BL-N2 (those readers now scrub date tokens via money.ts stripDateTokens before the money scan — see the full-audit-2026-06-28 record below). This is the line-parser fallback (plain-text statements, CSV, and the invoice path — which has no geometry pass); the geometry layout's own out-of-column value-date handling is §21 (the booking-date column model), a separate seam. Pinned by the 4-column Buchung Valuta Betrag Saldo fixtures (skills-bank-statement-tool.test.ts); teeth = reverting to the single-token strip drops/mis-values the rows.
  • BL-2 — single-currency precondition on the completeness gate (assessCompleteness) and reconcileBalances. Both summed amounts across currencies: the gate tied opening + Σamounts == closing and the reconcile chained prevBalance + amount regardless of currency, so a mixed-currency statement could be mislabelled complete/contradicted or carry a spurious per-row mismatch. Now both mirror summarizeCashflow's currencies.size === 1 guard: assessCompleteness returns 'unverified' for a mixed-currency statement (never claims a verdict from a meaningless cross-currency sum) and reconcileBalances reports every row unknown (never reconciled). buildBankAnswer's honesty branches are unchanged — the mixed-currency answer was already gated on summary.currency (the noCurrency branch), so the SKILL.md ⇔ TS parity contract (skills-skillmd-parity.test.ts) holds without a wording change; the fix hardens the public predicates a future caller might trust. Pinned by mixed-currency assessCompleteness/reconcileBalances unit tests; teeth = removing either guard flips the verdict back.
  • BL-3 — currency-blind categoryTotals (analysis/bank-statement.ts). The per-category accumulator keyed by category alone, summing signed amounts across currencies into one figure. Now keyed by (category, currency) — each CategoryTotal carries its own currency and buildBankAnswer renders it with c.currency. The breakdown is only ever rendered on the single-currency branch (so the live output is byte-identical, confirmed by the unchanged category tests); the fix removes the latent currency-blindness for any future reuse.

Financial correctness (full-audit-2026-06-28, Phase 1 — BL-N1…N6 / TEST-N2/N6). A follow-up multi-persona audit found the §22-D1 honesty posture undermined by locale/grouping parse bugs in the SAME line-parser layer (silent row loss + confidently-wrong figures) plus under-masking in redaction. Two of the findings (BL-N1, BL-N2) directly contradicted the just-closed §24 claims. Parsing/aggregation only — no schema, IPC, or audit-payload change (figures stay content-class). All driven by adversarial WHOLE-STRING tests through the real entry points (closing the TEST-N2 gap: the prior tests fed pre-isolated tokens and missed the live MONEY_RE/parseDate bugs). Two owner decisions were taken before implementing:

  • BL-N1 — per-document date-order inference (money.ts inferDateOrder → parseDate(token, order), threaded through splitLeadingDates / extractTransactionRows / extractStatementBalances / extractInvoice / parseLineItem). parseDate was day-first only, so a US mm/dd/yyyy statement either dropped the whole row (12/31/2026 → null → parseLine returns null) or attached a confidently-wrong month (03/05/2026 → 3 May). DECISION 1 as built (owner): per-document locale inference. inferDateOrder scans the document's nn[./]nn[./]yyyy tokens and switches the WHOLE document to month-first ONLY when one is unambiguously US-ordered (its second field is 13–31) AND none is unambiguously EU-ordered; otherwise the de-AT day-first DEFAULT holds (a fully-ambiguous or self-contradictory document is never guessed). This stops the silent row-drop and the wrong month without a result-attached caveat (the output schema is frozen for Phase 1). NB: the audit's BL-N1 prose stated the trigger with the fields swapped ("first field > 12 → mm/dd"), which is logically inverted — a first field > 12 can only be a day, forcing day-first; the mechanically-correct rule (a second field > 12 forces month-first) is what shipped. Redaction deliberately does NOT infer (it stays day-first — see BL-N6).
  • BL-N2 — trailing-date balance/total lines (money.ts stripDateTokens, used by lastMoneyOnLine and invoice lastMoney). The last-token balance/total readers read a TRAILING date as the figure: Endsaldo 1.234,56 EUR per 30.06.2026 → last MONEY_RE match 30.06.20 → 3006.20 — a wrong opening/closing that flips assessCompleteness between complete/contradicted (it can suppress an honest total or bless a partial one). This disproves the BL-1 "last-token readers were never affected" claim (corrected above). Fix: scrub every date-shaped token before the money scan, so a date at EITHER end is removed — the de-AT date-FIRST Kontostand per <date> <figure> shape still reads its figure.
  • BL-N3 — amount column by POSITION (bank-statement.ts parseLine). The amount was matches[0] (the FIRST money token), so a money-shaped reference in the description stole the amount and its sign (Betrag 100,00 EUR -100,00 900,00 → 100, not −100). Fix: with a running balance present (≥2 figures) the amount is the second-to-last figure and the balance is the last; with one figure it is the amount. Byte-identical on the normal 2-figure row. (The geometry column model, §21, remains the stronger separator; this is the plain-text fallback — a money-shaped token in a description is a documented residual, known-limitations.)
  • DECISION 2 as built (owner): full grouping support (MONEY_RE, TEST-N2). MONEY_RE required a 2-dp decimal tail, so a bare de-AT thousands figure 1.000 matched 1.00 → €1 (a 1000× understatement), space-grouped 1 234 567,89 read 567.89, and Swiss apostrophe 1'234.56 read 234.56. MONEY_RE now has three ordered alternatives — space-grouped, the original ./,/apostrophe decimal form, and a bare [.,']-grouped thousands form — with a trailing (?!\d) so 1.000 falls through to the thousands form → 1000, a leading (?<!\d) anchor so a match can never start mid-digit-run, and a (?<![A-Za-z0-9]) boundary on the space-grouped form so its leading 1–3-digit group only fires at a clean word boundary. Together the two boundaries stop the space-grouped form from fusing the 3-digit tail of a preceding token across a space — whether that tail follows a digit (the geometry continuation-line …778899 300,00 → "899 300,00" → 899300, caught in the pre-merge full-suite run) or a letter (Ref123 456,78 → "123 456,78" → 123456.78, surfaced by the adversarial review). parseAmount was already correct (it strips spaces/apostrophes and applies the 3-trailing-digit thousands rule), so only the capture changed. Quantifiers stay bounded/non-backtracking — the ReDoS guarantee holds (the 200k-char regression tests pass).
  • BL-N5 — integer-cents reconcile (reconcileBalances). The per-row running-balance check compared Math.abs(printed − expected) < MONEY_EPS in floats while assessCompleteness (audit C-3) uses integer cents; a per-row mismatch forces contradicted. Reconcile now uses the IDENTICAL Math.round(x*100) integer path — a consistency/defensive fix (no realistic 2-dp input distinguishes the two; the teeth are structural, so it is pinned by the reconcile it.each in skills-bank-statement-tool.test.ts).
  • BL-N4 — redaction under-masking (redaction.ts). PHONE_RE matched only +/0-prefixed numbers, and IBAN detection was case-sensitive (de89… survived). Added a PUNCTUATED US/national 3-3-4 phone alternative (optional leading 1; [.\-] only — so a bare 10-digit run, a prose space-triple, and a slashed date are left alone) and a second case-insensitive COMPACT IBAN candidate (maskIbans uppercases before per-country length validation) that catches a lowercase compact IBAN without the space-grouped form eating a trailing lowercase prose word. Detection stays conservative (prefer a miss over over-masking).
  • BL-N6 — redaction date-masking asymmetry (DOCUMENTED, lowest priority). maskDates masks every parseDate-valid token and does not infer locale (unlike extraction — by design), so an EU 31/12/2026 masks while a US 12/31/2026 leaks — a locale-asymmetric OUTPUT. Kept best-effort and documented in known-limitations; a date-category toggle is a deferred higher-recall wave. There is no path where masked text is un-masked or a detected value reaches a log/audit (privacy posture unchanged).

Financial correctness (full-audit-2026-06-29, Phase 1 — BL-1/BL-2/BL-3). A fresh 7-persona audit found three more correctness bugs in the SAME shared line-parser / categorizer layer, all verified by direct trace and fixed test-first through the real entry points (parsing/categorization only — no schema, IPC, or audit-payload change). One is HIGH (wrong figures); two are MEDIUM (silent suppression / mis-bucketing on the de-AT target locale).

  • BL-1 — leading-minus sign theft (money.ts MONEY_RE), HIGH. The trailing \s*\)?-? reached ACROSS the column gap and consumed the LEADING minus of the next money token, so 2.500,00 -500,00 parsed as amount −2500 / balance +500 (BOTH signs flipped). Because every figure flipped UNIFORMLY the running chain still tied out, so reconcileBalances reported ok on confidently-wrong figures — the safety net could not catch it. It triggers on ANY negative running balance / leading-minus amount (overdrafts, US/international statements, and the §21 PDF-geometry path, which emits a negative balance verbatim). The team's own fixtures never used a negative balance, which is why it slipped past the BL-N* round. Fix: the trailing sign/paren region is now SPACE-DISAMBIGUATED — (?:-|\s*\)|\s+-(?!\s*[-+(]?\d))? — a glued trailing minus (45,90-, the de-AT debit sign) is always consumed, a paren close is consumed, and a spaced trailing minus is consumed only when NOT immediately followed by a figure. The disambiguator is the SPACE: a glued - belongs to the figure on its LEFT, a -<digit> after a space is the next figure's leading sign. This deliberately differs from the audit's first-pass (?:-(?!\s*[-+(]?\d))? suggestion: once that form's \s* has run it also refuses the glued case and would have regressed the common de-AT row 45,90- 1.908,20 (glued debit + running balance) to +45,90. The trailing scans stay UNAMBIGUOUS (each whitespace run is followed by a disjoint atom) and the lookahead is zero-width, so MONEY_RE remains ReDoS-linear (the 200k-char regression test stays green). Residual: a SPACED trailing minus immediately before a balance figure (45,90 - 1.908,20) reads positive — genuinely indistinguishable from subtraction (known-limitations).
  • BL-2 — figure-region currency (bank-statement.ts parseLine), MEDIUM. Per-row detectCurrency(line) scanned the WHOLE line including the free-text description, so a EUR row whose memo read Netflix USD subscription was tagged USD → the row-currency set grew → summarizeCashflow returned no single total, reconcileBalances marked every row unknown, and assessCompleteness dropped to unverified. One description string silently killed totalling for the whole statement. Fix: detect the per-row currency only in the figure region (rest.slice(matches[0].index) — the text from the first money token on), falling back to the statement currency. A currency WORD in the description is ignored; a GENUINE foreign-currency row (code/symbol printed NEXT TO the amount, inside the figure region) is still detected, so mixed-currency honesty is preserved — preferred over statementCurrency ?? detectCurrency, which would silently sum a truly-mixed line in one currency.
  • BL-3 — German closed-compound categorization (money.ts wordIncludes), MEDIUM (de-AT target locale). The C-1 two-sided word boundary (which stopped fee⊂coffee) ALSO stopped the de-AT keywords from ever matching, because German fuses keywords into closed compounds where the keyword sits at a word edge on only ONE side (kontoführungs+gebühr, gehalts+zahlung) — so account/bank fees fell through to the generic Spending bucket and überweisung/gehalt compounds missed. Fix: wordIncludes(haystack, needle, compound) gains a COMPOUND mode (a boundary on EITHER side suffices — one-sided, not raw substring, so a keyword buried with letters on both sides is still rejected); the rule table opts the unambiguous DE keywords (gebühr/gehalt/überweisung/bargeld) in via a per-rule compound: true. Short English tokens (fee/atm/…) and the ambiguous lohn (⊂ muehlohn/Belohnung; income is covered by the positive-sign fallback) stay STRICT, so no C-1 false positive returns. Both categorizeRow and prefilterCategory thread the flag, so the two deterministic paths still agree (the C-1 invariant). The flag is matching-only — run.ts seeds just match_kind/pattern into bank_category_rules (transparency), so nothing is persisted and no schema change is needed.

Financial correctness (full-audit-2026-06-29-postmerge, Phase 1 — F1/F3/F6/F8 + T5). A post-merge fresh pass found the prior round's bank hardening (BL-1/2/3) had not propagated to the sibling invoice path, plus a HIGH amount-column hazard on both. Parsing-only (no schema/IPC/audit-payload change); all fixed test-first through the real extractTransactionRows/parseLineItem/ validateInvoiceTotals entry points (characterization-first, then flipped to the correct values).

  • **F1 — uncaptured amount column read the running BALANCE as the amount (bank-statement.ts parseLine
    • invoice.ts parseLineItem), HIGH.** A whole-euro amount (50) or single-decimal (12,5) is rejected by the 2-dp MONEY_RE, so Sparen 50 1.234,56 collapses to ONE money token — the balance — and the position heuristic took it as the movement amount (off by the whole balance magnitude; reconcileBalances cannot catch it because the row records no balanceAfter). Fix — STATEMENT-CONTEXT-AWARE drop (diverged from the audit's literal "drop whenever a left digit-run remains"). parseLine now FLAGS ambiguousAmount (one money token + a description ending in a bare number); extractTransactionRows drops the flagged row only when the statement has a balance column (rows.some(r => r.balanceAfter !== undefined)). The unconditional drop the audit suggested regressed the flagship HVB "Umsätze" no-balance format (pdf-bank-layout.test.ts), where a numeric-ending payee (REWE … 1234 -19,15) is a single-token row whose lone figure genuinely IS the amount — so it must be kept. The invoice mirror drops on the OPPOSITE side: it reads the line total as the LAST figure, so it drops a row with an uncaptured numeric column to the RIGHT of the last money token (Hosting 12,50 500 → the real total 500 lost), while a bare number to the LEFT is a quantity (kept). Residual: a lone Sparen 50 1.234,56 with no balance-column row to establish context keeps the old read; and a balance-column row that legitimately has a missing balance + numeric payee is dropped (recall loss, never a wrong figure) — both documented in known-limitations.
  • F3 — invoice per-line currency from the WHOLE line + missing single-currency guard (invoice.ts), MEDIUM. The BL-2 figure-region fix was never applied to the invoice path: detectCurrency(line) scanned the description, so USD adapter cable 12,50 on a EUR invoice tagged the line USD (ISO codes scan before symbols). Fix: detect on the figure region (rest.slice(matches[0].index)) with documentCurrency fallback — mirror of bank-statement.ts. Separately, validateInvoiceTotals gained the bank gate's single-currency guard: a line-item currency set of size > 1 returns lineItemsSumToNet: 'unknown' rather than summing lineTotal across currencies into a meaningless cross-currency figure.
  • F6 — space-column FUSION on the geometry-less invoice path (invoice.ts isFusedSpaceGroup), MEDIUM. MONEY_RE's space-grouped alternative reads <1-3 digits> <3 digits> as one figure, so Widget 10 100 fuses to 10 100 → 10100 (~100× too large). The bank path is mitigated by the geometry column model (D58); the invoice path has no backstop (F10). Fix: a matched token with an interior space and NO 2-dp decimal tail is the fusion-prone form (a real line total prints cents) → drop the row. A decimal-anchored space group (1 234 567,89) is kept; a space group WITH a decimal (15 799,00) stays the accepted DECISION-2 trade-off.
  • F8 — greedy quantity split (invoice.ts QTY_TRAIL_RE), LOW (metadata). A trailing number was split off the description as quantity even with no unit word, so iPhone 15 → "iPhone" qty 15. Fix: the unit token is now a CAPTURING group; the split fires only when a unit token is present OR a unit-price column (amounts.length >= 2) corroborates it. The columnar Widget A 2 12,50 25,00 still reads quantity 2. lineTotal was never affected.
  • T5 — the 2-dp integer-cent invariant (money.ts parseAmount). parseAmount now rounds every figure to the nearest cent (Math.round(|value|*100)), so Math.round(x*100) is its EXACT cent value — the load-bearing premise of assessCompleteness/reconcileBalances (which tie out in integer cents) and CSV toFixed(2). Decision: a >2-dp printed figure (only reachable via the both-separator 1.234,567 form) is read to the nearest cent (1234.57), not dropped — a sub-cent normalisation, never a confidently-wrong magnitude. (Single-separator 3-digit-group thousands forms 1.000/12.345 are integers, unaffected — DECISION 2.) Parens-negative through the real scanner (T4) and negative line totals / credit notes (Gutschrift/Rabatt, T9) are now pinned by whole-string tests.

Financial correctness (full-audit-2026-06-29 follow-up, Phase 1 — FIN-1/2/3/4). A follow-up audit found the prior rounds had hardened the per-ROW money parser but left four "confidently-wrong figure / wrong currency / wrong date" paths in the STATEMENT/DOCUMENT-level orchestration ABOVE it. Parsing-only (no schema, IPC, or audit-payload change; figures stay content-class). All fixed characterization-first then test-first through the real extractTransactionsTool/extractInvoiceTool/extractTransactionRows/parseLineItem/ reconstructLine entry points, each teeth-checked. BANK_EXTRACTOR_VERSION 2 → 3 (FIN-1/3/4) and INVOICE_EXTRACTOR_VERSION 1 → 2 (FIN-1/2/4) — the A9/F5 reuse gate (isBankStatementStale/ isInvoiceStale) re-extracts older rows on next analysis (the rollback boundary).

  • FIN-1 — document/statement currency by MAJORITY VOTE (money.ts detectDocumentCurrency, wired into both tool .runs), HIGH. The tool-level fallback was detectCurrency(joined) = "first allowlisted code ANYWHERE in the joined text wins". On a bare-amount de-AT statement a stray USD/CHF in a payee MEMO won → every bare-amount row fell back to USD → summarizeCashflow reported a VERIFIED total in the wrong currency, and because the mislabel was UNIFORM the mixed-currency guard (fires on >1 distinct currency) never tripped. The BL-2/F3 fix had narrowed only the per-ROW figure-region detection; the document-level call still scanned everything. Fix: detectDocumentCurrency votes per line — a MONEY-bearing line votes only on its figure region (text from the first amount onward, so a left-of-amount memo code is excluded; dates are scrubbed first so a leading dd.mm.yyyy isn't read as the first "amount"), a MONEY-less line (a Währung EUR header/label) votes on its whole text; the most-voted code wins, ties broken by first appearance. A genuinely-foreign statement (code adjacent to amounts) is still detected; a truly-mixed statement still reaches the mixed/unverified path because the per-row detection tags each row's own figure-region currency (this only supplies the bare-row fallback).
  • FIN-2 — invoice F1 right-side uncaptured-column drop OVER-fired (invoice.ts UNCAPTURED_AMOUNT_AFTER), MEDIUM. The F1 drop used /(?:^|\s)[-+(]?\d/ — fired on ANY trailing digit after the last money match, so it deleted valid items with a trailing annotation (Service 12,50 (Pos. 3), Beratung 1.234,56 19% MwSt, Line 50,00 EUR 2 Stk). Fix: the region after the last money match must be ENTIRELY a single money-shaped-but-rejected bare token (/^\s*[-+(]?\d[\d.,']*\)?\s*$/ — a whole/grouped integer or single-decimal column, no %/x/unit word/other text), so a true uncaptured total (Hosting 12,50 500) still drops while an annotated item is kept.
  • FIN-3 — geometry classifier read a bare-thousands amount as a DATE (pdf-layout.ts DATE_TOKEN_RE), MEDIUM (latent; HIGH harm when it fires). The old ^(\d{1,2})\.(\d{1,2})\.?(\d{2,4})?$ let 2.500 BACKTRACK into a date (day 2 / month 5 / "year" 00); out of the booking-date column that "date" was DROPPED, so row 07.02. EINKAUF 2.500 1.000,00 reconstructed as …EINKAUF 1.000,00 and the line parser read the BALANCE as the movement amount (the cardinal wrong-money harm, via a path the F1 guard doesn't cover). Fix: require a year to be preceded by its own dot (^(\d{1,2})\.(\d{1,2})(?:\.(\d{2,4})?)?$) so 2.500 (one dot) is un-date-able → it survives as text and the line parser's MONEY_RE reads it. DIVERGENCE from the audit's "widen MONEY_TOKEN_RE to the shared grammar": MONEY_TOKEN_RE was kept a 2-dp-only SUBSET (NOT widened). Widening would make a pdf.js-SPLIT amount (2.000 + ,00, the M3 boundary) classify 2.000 as money and emit a row with amount 2000 — silently dropping the cents on a 2.000,50-style split, a confidently-wrong figure where the row is today safely DROPPED. The DATE_TOKEN_RE tightening alone fixes the wrong-figure harm because the reconstructed line is re-parsed by the shared MONEY_RE (which reads bare-thousands/apostrophe); the trade-off is that a SOLE bare-thousands/ apostrophe figure stays a gate-safe recall DROP (pre-existing — the old MONEY_TOKEN_RE already rejected it). The stale pdf-layout.ts:43 comment ("mirrors the accepted set of the shared MONEY_RE") was corrected to state the intentional subset.
  • FIN-4 — a memo date flipped the WHOLE document's date order (money.ts inferDateOrder), MEDIUM. The scan was over the ENTIRE joined text, so one 03/15/2026 (second field 15 → US) in a payee memo flipped a de-AT statement to month-first → every dotted dd.mm.yyyy booking date with day ≤ 12 silently day/month- swapped (all still valid → none dropped → fully silent; the completeness gate checks balances, not dates). Fix: the vote is scoped by line KIND — a MONEY-bearing line (a transaction row) votes only on its LEADING run of date-column tokens (capped at two, mirroring splitLeadingDates; a memo date deeper in the row can't vote), while a MONEY-less line (an invoice Invoice date 06/15/2026 header, a statement period) votes on any date it carries. DIVERGENCE from the audit's "restrict to the leading date column": the pure leading-column rule BROKE invoice US-date detection (an invoice's header dates follow a LABEL, they don't lead the line) — hence the split-by-line-kind, which fixes the statement-memo contamination while keeping both the single-leading-US-date statement and the labeled US invoice working.

Financial correctness (full-audit-2026-06-30, Phase A — C1/C5). A fresh audit found one false-NEGATIVE in the SAME reconcile/summary layer (parsing-only; no schema, IPC, or audit-payload change; BANK_EXTRACTOR_VERSION unchanged — reconcile re-runs on read). Fixed characterization-first through the real entry points, teeth-checked.

  • C1 — reconcileBalances dropped a balance-less gap row from the chain → false mismatch, MEDIUM-HIGH. prevBalance advanced only on a printed balance, so a mid-statement row with a real amount but no printed balanceAfter (same-day grouping — the bank prints the balance only on the day's last line — or an OCR-dropped balance cell) was OMITTED: the next balance-bearing row computed prevBalance + thisAmount without the gap amount → mismatch → assessCompleteness → contradicted → a correct, verifiable total was withheld from the user (the inverse of the confidently-wrong harm). Fix: a sinceLastPrinted cents accumulator — a balance-less row stays unknown (it prints no balance of its own to check) but its amount is folded into the next printed balance's expected value (toCents(prevBalance) + sinceLastPrinted + toCents(amount)), reset on each printed balance and discarded at the baseline. Since amount is a required number on every TransactionInput/the schema, the chain is never "genuinely broken" by a missing amount, so there is no revert-to-unknown-on-missing-amount branch (the audit's conditional is vacuous); a real read error still surfaces as a mismatch. Supersedes the earlier "reconcileBalances over-reporting (honesty)" note's drop-the-gap behavior. The normal 2-figure de-AT row and the HVB no-balance listing stay byte-identical.
  • C5 — zero-amount classified inconsistently between summarizeCashflow and categorizeRow, LOW. summarizeCashflow counted amount >= 0 as inflow while categorizeRow files a zero Uncategorized (neither Income nor Spending). Fix: summarizeCashflow now uses > 0 inflow / < 0 outflow (a 0.00 row is neither), matching the breakdown. Output is unchanged (the figure is zero) — a convention-consistency fix. T4 (the §4 testing gap) landed alongside: a new tests/unit/money.test.ts table-tests the money/date/CSV primitives in isolation (apostrophe+decimal parseAmount, csvField formula-lead × quote × CRLF, wordIncludes(compound) repeated-needle, inferDateOrder/detectDocumentCurrency boundaries).

§11 IPC / audit surface

skills:list/get/pick/preview/import/export/delete/enable/disable/acknowledgeWarning + suggestSkills + the four skills:* tool-run channels (§9), all requireUnlocked for DB-backed work (the two in-memory controller channels getSkillRun/cancelSkillRun carry no content). Audit events (the exact AuditEventType members): skill_imported/skill_deleted/skill_enabled/skill_disabled

  • skill_run_started/skill_run_done/skill_run_failed, all ids/counts only. (Selecting a skill is a sticky-default DB write and is deliberately not audited — there is no skill_selected event; the abandoned DS13 design that named one was never built.)

§12 Trade-offs, residuals & the closing S12 audit

S12 ran the repo's multi-persona audit over the whole surface against the untrusted-skill-as-input threat principle (§14). No CRITICAL/HIGH. One LOW was fixed (CSV spreadsheet formula-injection at the export boundary), and the scattered S10/S11 sentinel tests were consolidated into a single skills-privacy-guard.test.ts that drives one secret through every sink (import error, loader, all five tool runs, the CSV export, the polled SkillRunState snapshot) plus a console spy. Accepted LOW residuals (documented in known-limitations.md): prompt text-injection is contained by the structural ceiling, not by escaping the fence delimiter; a user skill's triggers.filenamePatterns are matched against a title only on a user action by a linear, non-backtracking two-pointer matcher (selector.globMatches), and the entry length/count are capped at parse time (vuln-scan 2026-06-21 replaced the original glob→RegExp compile entirely — see §13 S2). Deferred: S13 auto-fire (gated on an evaluation harness); native model tool-calling (stays a future option behind the same gate); the app-skill integrity residual (by location, not signature — same as the engine binary, §22-M2). History: the wave shipped S2–S12 (2026-06-17); the original plans: git show <S12^>:docs/skills-plan.md and git show <S12^>:docs/skills-s11-plan.md.

§13 Post-S12 audit follow-ups (2026-06-17)

A second multi-persona audit after the wave closed found no CRITICAL/HIGH; the fixes below landed behind the unchanged §14 ceiling (no new capability, still offline, audit still ids/counts-only):

  • B1/B2 — cancel vs. outcome (run controller). The seam is now the single authority on a run's terminal status: a non-ok outcome carries an explicit cancelled flag (a dismissed CSV save dialog is a cancel, not a failure), and a successful outcome is reported done even if Cancel landed late (the work persisted — never reported "cancelled, nothing changed"). runCsvExport re-checks the abort before the FS-write, so nothing is written under a cancel. SkillRunController.finish reads outcome.cancelled (falling back to signal.aborted only when a runner threw).
  • I1/I2 — localized failure copy. The run seams return a content-free reason code (errorCode: unavailable | needsExtraction | persistFailed | exportWriteFailed) and the import preview returns parallel errorCodes; the renderer maps both to EN/DE copy, so a German user never sees an English failure/import string. The seam/controller stay i18n-free (codes are content-free tokens, like resultKind). EN/DE parity is compile-enforced (de: Record<keyof typeof en, string>).
  • S1 — content-free preview notes. The clamp/manifest.json-conflict notes no longer echo the raw (attacker-supplied) frontmatter value — only the fixed field name — closing the one §22-M1 gap where attacker text could ride the SkillPreview IPC payload into the UI (notes share the path with the already-clean structural errors).
  • S2 — ReDoS guard on filenamePatterns. Two layers: the parser caps each trigger entry's length (≤200) and count (≤64), and the glob is matched against a title by a linear, non-backtracking two-pointer matcher (selector.globMatches) so a *?*?…-style pattern can never hang the synchronous main-side scoring. (S12 originally compiled the glob to a bounded RegExp with a >10-* wildcard cap; vuln-scan 2026-06-21 replaced that with the linear matcher because the cap counted only * — a *?*?… pattern with ≤10 stars still compiled to a degree-10 backtracking RegExp — see known-limitations.md.)
  • B3 — summarize_cashflow self-consistency. net is derived from the rounded totalIn/totalOut so the three reported figures always satisfy net === totalIn − totalOut.
  • B4 — no stranded started run. runBankExtraction and prepareStatementRun now wrap everything after the skill_runs 'started' insert in a guard, so an unexpected throw (e.g. a transiently locked DB while building the chunk reader) still drives a terminal failed status instead of leaving the run row at started forever. The downstream runCashflowSummary is the one seam with no surrounding transaction (it persists no figures), so its terminal finishRun('done') is itself wrapped in a guard that falls back to persistFailure — closing the last path that could strand the row at started.
  • CSV leading-whitespace formula injection. CSV_FORMULA_LEAD now also neutralizes a formula trigger that hides behind leading whitespace (" =cmd") — some importers trim before evaluating — in addition to the leading-control-char and bare-= + - @ cases.
  • Reconcile one-active-per-id (DS12 safety net). reconcileSkills collapses the rare case where two AVAILABLE rows of one declared id end up both enabled (a DB rebuild, or an app skill shipped after a same-id user skill was enabled): it keeps the highest-precedence one (trust app > user → version → recency) and disables the rest. The enable IPC + import already enforced this on their paths; reconcile was the gap.
  • PC-1 — cross-lane write safety (skills-tools-audit-2026-06-26, Phase 9). The three lanes that touch the bank/invoice tables (Lane A chat analysis, Lane B SkillRunController, Lane C DocTaskManager categorize) had no cross-lane lock, so a chat re-extract replaceExisting DELETE could race a button run / a categorize on the SAME statement (cooperative interleaving across await points, not an OS data race — the main process is single-threaded). A per-document async mutex (services/skills/doc-lock.ts withDocumentLock, a re-entrant Map<documentId, Promise> chain) now serializes every write-capable section by documentId: the write seams self-lock and the two multi-step lanes wrap their whole sequence (re-entrant inner locks). In-memory, per-document (unrelated docs stay concurrent), no new capability/schema/IPC, finer than acquireChatSlot and finally-released (no deadlock). R9 (skills-audit-2026-07-03 SKA-24/SKA-28) extended it: acquisition is abort-aware (a parked waiter rejects on cancel; the published tail still settles) and the summarize/export seams gained the outer prepare+load hold (released before the save dialog). Full record in §9.

§14 Content-reach + compatibility audit fixes (2026-06-17b)

A follow-up audit (bugs + docs-vs-code) found one HIGH and the MEDIUMs below; all fixed behind the unchanged §7 ceiling (no new capability, still offline, audit still ids/counts-only).

  • H1 — the content-reading tools read VERBATIM segments, not retrieval chunks (the fix that makes Tier-2 actually work). extract_transactions / extract_invoice / redact_document reach document text through SkillToolContext.readDocumentChunks. That had been backed by the stored chunks table — but those are retrieval windows: the chunker collapses every newline to a space (atomize→space-join) and overlaps consecutive windows by ~80 tokens. So the line-oriented bank/invoice extractors saw one giant "line" (≈0 rows) and the redaction copy came out de-formatted with duplicated overlap regions — on ACTUALLY-ingested documents. (The unit/integration tests masked it by seeding a single chunk whose text carried real \n.) The fix: the IPC injects a readDocumentSegments capability (the same extractDocumentPreview the doc-tasks use — ordered, non-overlapping, newline-preserving parser segments, re-extracted from the stored copy), and the run seams build the tool's reader from it (run.ts resolveDocumentReader). The §7 ceiling is unchanged: the seam, not the tool, holds the FS/cipher capability (a closure), the reach stays frozen to the single in-scope id, and a failed re-extraction surfaces through the tool's own content-free "could not be read" path. The legacy chunk-table reader remains as the fallback for callers that don't inject the capability (the seam-level tests that seed chunks directly); the IPC always injects the verbatim one, and the tool-run IPC tests now seed a REAL stored .txt so they exercise the production path end-to-end.
    • (2026-07-01 follow-up — button/chat extraction parity.) readDocumentSegments is now built by ONE shared factory (ipc/documentSegments.ts buildDocumentSegmentReader) that BOTH the chat-analysis IPC (registerRagIpc) and the run-bar IPC (registerSkillsIpc) call. Previously each IPC had its OWN copy of the closure and they drifted: the run-bar copy dropped the {layout} argument (D58 geometry reconstruction), so the "Extract transactions" BUTTON re-read a columnar statement in plain reading order (fewer, scrambled rows) while the chat answer used layout mode — the SAME document reported a DIFFERENT transaction count by entry point. The single factory makes that divergence structurally impossible (a buildDocumentSegmentReader unit test pins the {layout, maxPages} threading). The extract_transactions / extract_invoice run-bar buttons also now pass replaceExisting: true (matching the analysis + categorize reuse paths — analysis/bank-statement.ts, analysis/invoice.ts, doctasks/handlers/categorize.ts), so an explicit re-extract REPLACES rather than accumulating duplicate bank_statements/invoices that latestBankStatementId/latestInvoiceId (newest wins) could otherwise serve divergently to the chat. A summarize_cashflow run now also routes an analysis-shaped question into the transcript (mirroring the categorize routing, via ChatScreen's ROUTED_RUN_QUESTION map) so the button surfaces the real in/out/net totals — the figures still stay main-side (the run state remains ids/counts-only).
  • M1 — the §6.5 minAppVersion gate is now ENFORCED (was parsed-but-ignored). A pure shared skillNeedsNewerApp(minAppVersion, appVersion) (shared/skill-manifest.ts) drives it. An app skill that needs a newer app reconciles in DISABLED (not auto-enabled); an import installs it disabled; the enable IPC refuses it (main.skills.incompatible); SkillInfo gains incompatible + minAppVersion, and the Skills tab shows a "Needs newer app" badge with the toggle disabled. The app version is threaded from app.getVersion() through the registry + installer deps + IPC. (Originally a residual remained: a skill edited on disk to need a newer app while already enabled stayed effective, because reconcile preserves the enabled flag and the use-sites gated only on enabled. §15 closed it — the gate is now airtight: the use-sites gate on compatibility, not just enabled.) #846 built the other half: an app skill the gate kept off now comes back on by itself once the app is updated (skills.disabled_reason, §3). #896 amendment (owner decision G-7 (b′), 2026-11-18): the gate now makes the model gate's comparison (appOlderThanMinimum, shared/app-version.ts), so a pre-release app is older than its own release (0.1.66-beta.1 no longer meets 0.1.66, and #846 re-enables at 0.1.66, not at its beta). It keeps its lenient read of both versions and its fail-open answer for one it cannot read; build metadata stays ignored. The frozen manifestNeedsNewerApp is unchanged and keeps its own copy of the comparison (scripts/measure-manifest-read.mjs loads shared/manifest.ts through Node's type stripping, which takes no extensionless import); an agreement matrix in skill-manifest.test.ts holds the two gates equal.
  • M2 — the Tier-2 "active tools" note is domain-free. skills.tool.note.active no longer enumerates bank tools (it had shown bank copy for the invoice + redaction skills too); it now reads "run approved local tools on a document you choose…", true for every kind:'tool' skill.
  • M3 — the terminal-run acknowledge handshake is wired. A new skills:clearToolRun IPC + preload method lets the renderer's acknowledgeSkillRun() release the controller's terminal run main-side (SkillRunController.clear was previously dead code; the comment promising the handshake is now true).

§15 LOW / residual follow-ups (2026-06-17c)

The four remaining LOW/residual items after the §14 audit, all fixed behind the unchanged §7 ceiling (no new capability, still offline, audit still ids/counts-only; EN/DE parity still compile-enforced):

  • Docs — user-facing Skills coverage. user-guide.md gained a §8 "Skills" section (the composer picker, the per-message glyph, the one-tap suggestion, tool skills + the run bar + confirm/cancel, and Settings → Skills: import/enable/delete, drop-ins install disabled, the "Needs newer app" badge), and troubleshooting.md gained four entries (drop-in installs disabled DS19; the structural import-rejection reasons; the "Needs newer app" badge §14/M1; and "the skill tool found nothing in my document" — read-step-first / OCR / conservative parsing). Docs-only.
  • reconcileBalances over-reporting (honesty). The lone baseline row (the first row, or the first row after a balance-less run with no PRIOR printed balance to anchor against) is unknown, not ok — it has nothing to compare against, so it is not a genuine check. reconciled is true only when no row mismatched and at least one row was actually compared against a predecessor (okCount > 0). A single-transaction statement therefore reports reconciled: false / resultKind: 'unchecked' (it verified nothing) instead of a false "reconciled". validate_statement_balances' downstream resultKind was already keyed off unknown, so it flowed through unchanged; the baseline row now persists reconciled = NULL (unchecked) rather than 1. The invoice path (validateInvoiceTotals) has no baseline concept — each of its three checks is a genuine figure-to-figure comparison — so it needed no change. Updated by full-audit-2026-06-30 C1 (above): a row whose immediate predecessor printed no balance is no longer auto-unknown — its gap amount is carried in sinceLastPrinted and it reconciles ok against the last printed balance. ONLY the true baseline (no prior printed balance at all) stays unknown.
  • Cancel-during-run audit consistency. When the abort signal has fired, the gate (tool-registry.ts) now suppresses the skill_run_failed audit event (a cancelled run audits as started-then-no-terminal-event), so the audit agrees with the skill_runs row the seam records as cancelled — the audit surface has no skill_run_cancelled event (it stays ids/counts-only, §11). A genuine non-cancel !ok still audits skill_run_failed unchanged.
  • minAppVersion gate made airtight (the §14/M1 residual). The use-sites now gate on compatibility, not just enabled, reusing the shared skillNeedsNewerApp helper (shared/skill-manifest.ts). The app version (already threaded via app.getVersion() in §14) is carried into resolveTurnSkill (turn.ts, via TurnSkillDeps.appVersion + the registry handle's new appVersion field), suggestSkillsForTurn (suggest.ts), and runnableToolNames / runnableToolsForSkill (tool-runs.ts, threaded from the IPC's appVersion at both the listRunnableTools and startSkillRun sites). So a skill edited on disk to need a newer app while already enabled is skipped at turn-resolution, never suggested, and refused at run start — even with a stale enabled flag. The threading is tolerant by default (absent / '' ⇒ compatible), so the seam-level/test callers are unaffected.

§16 Per-locale skill display localization (2026-06-17d)

Skill content (title/description/body) was English-only — the UI chrome is fully i18n'd, but the manifest carried a single title/description, so a German UI showed English skill names in the composer picker, the per-message glyph, and the Settings → Skills cards/detail. Fixed for the display metadata (the chosen scope; the guidance body stays single-language — the model is multilingual and still answers in German, D-L6):

  • Additive manifest block. SKILL.md may carry a localized: map (locale → {title?, description?}), parsed in shared/skill-manifest.ts (lenient like triggers/language: a malformed/blank/over-long/ multi-line entry is noted and skipped, never an error; locale keys are lower-cased and bounded; at most MAX_LOCALIZED_LOCALES = 16). It rides the existing additive-schema posture (§2) and the manifest_json cache round-trips it. SkillManifest.localized + SkillInfo.localized are both optional.
  • Projection. installer.ts recordToInfo copies manifest.localized into SkillInfo so the renderer (which alone knows the resolved UI language via useT().lang) picks the entry; the main side stays locale-agnostic.
  • Renderer pick (display only). A tiny pure helper renderer/lib/skillI18n.ts (localizedSkillTitle/localizedSkillDescription + a skillTitleResolver for the glyph) is used by the composer SkillPicker (trigger label, suggestion offer, each row), the Settings → Skills cards + detail modal, and the per-message glyph in Transcript (an installId→localized-title resolver threaded from ChatScreen, built from the full skills list so a now-disabled stamped skill still localizes, with a stamped-title fallback). Every pick falls back to the canonical text.
  • Bundled skills. The four app skills shipping at the time (bank-statement, invoice, document-redaction, meeting-protocol) gained a localized.de title + description; the four Professional Documents skills added 2026-06-21 (contract-brief, deadline-obligation-finder, what-changed, share-safe-review) carry it too, so all eight bundled skills are now German-localized. (The triggers were already bilingual, which is why German questions already fired the suggestion — only the visible text was English.) 2026-11-12 (UI languages wave): there are nine bundled skills now (document-edit carries localized.de too), and each also carries localized.es, .fr, .it and .ru, one block per interface language; their versions are unchanged (UI-languages owner call D-16 (a)).

Display-only by design: nothing here threads locale into resolveTurnSkill/the prompt, so the gate + ceiling are unchanged and the injected body is byte-identical regardless of UI language.

Agent Skills (agentskills.io) interop mapping (STR-1 review §5.5, 2026-07-20)

SKILL.md became an open cross-vendor standard (agentskills.io, opened 2025-12) after our format was built; the shapes converged independently (YAML frontmatter + markdown body + bundled resources). The mapping, recorded so the door stays open without churn: our id/title ↔ the spec's name; our first-class strict-semver version + minAppVersion compatibility gate have no spec equivalent (a metadata convention at best — we are stricter); our localized: per-locale display overrides fill an i18n gap the open spec does not address (Anthropic's MCPB bundle format solved it the same way, BCP-47-keyed). Consequence: an agentskills.io-conformant pack's body + display-metadata import is near-trivial (map name, default a version); its executable scripts and allowed-tools are and must remain unsupported — imported skills are instruction-only here (skillCanRunTools = app-source only, permissions clamp restrict-only, §14 ceiling), and the standard's permissive execution model is the ecosystem's demonstrated exploit surface (working skill-frontmatter exploit chains, ReversecLabs 2026-05). Full format convergence is deliberately not pursued.

§17 Active-skill turn-latency: measured root cause + the prefix-cache fix (2026-06-17e)

A regression report — "chat with a skill active feels noticeably slower than with no skill" — was measured before being theorized (a temporary, content-free perf harness over the real bundled SKILL.md files + synthetic bodies up to the 64 KB cap; deleted after measuring, §22-M1: ids/counts/ durations only). The numbers localized the cost and refuted the "main-side prompt assembly is slow" guess:

  • Main side is negligible for the shipped skills. The full per-turn resolveTurnSkill path — disk read + YAML parse + validate (loadSkillPackage) plus fence assembly + the paragraph-growth sizing loop (buildSkillFence) — measured < 1 ms/turn for a ~1.5 KB bundled skill (load ≈ 0.65 ms, fence ≈ 0.06 ms) on an OS-cached SSD. Not perceptible.
  • The injected body is the driver, and it's a prefill cost. The bundled skills inject a measured 288–381-token body (≈ 447 tokens including the BEGIN/END framing + guard line); the system prompt grows from 94 to ~541 tokens. That delta is paid in prefill, whose wall-clock is hardware-bound: derived from the measured token count, ~290–450 tokens is sub-100 ms on GPU (3 k tok/s) but ~3.5–15 s on a laptop CPU (~30–80 tok/s) — which fully explains a "noticeably slower" feel and why the effect differs CPU vs GPU.
  • Whether that prefill is one-time or per-turn is governed by KV-cache prefix reuse — and the app was leaving it to the server default. Plain chat brackets the fence in the stable system prefix (§5), so it should be prefilled once and then reused; grounded rides the fence in the per-turn user turn with the varying excerpts (§5/§22-H2), so its +447 tokens are genuinely re-prefilled every turn by design. The chat request sent no cache_prompt, relying on llama-server's default (which has flipped across releases) — so plain chat's "prefill once" was not guaranteed, and any prefix shift (toggling the skill, a large user skill whose fence trims to a question-dependent budget, or history dropping under context pressure) forces a full re-prefill.

Decisions / fixes as built (both behind the unchanged §7 ceiling — no new capability, fully offline, audit still ids/counts-only; no i18n surface touched):

  • PERF-1 — cache_prompt: true is now explicit (runtime/llama.ts chatStream). The KV slot reuses the longest common token prefix instead of re-prefilling the whole prompt, set explicitly rather than inherited from a release-dependent default. With the stable plain-chat system prefix this makes the fence a one-time prefill (toggle-on cost), not per-turn. Loopback-only compute hint, no telemetry. Asserted in llama-runtime.test.ts.
  • PERF-2 — the per-turn load is cached (skills/loader.ts loadSkillPackage). resolveTurnSkill hit disk + re-ran the YAML parse/validate every turn; the result only changes when SKILL.md changes, so it is now cached keyed by the file's (mtime, size). Measured ~33 µs cache hit vs ~650 µs uncached (20×) on SSD — and the win is far larger on the portable drive HilbertRaum targets, where a per-turn read dominates, and for a large user skill that re-parses + re-sizes (the sizing loop is O(paragraphs²): measured **19 ms** at the 64 KB cap). DS1/DS2 honoured — an on-disk edit (mtime/size change) re-parses on the next turn — and the reconcile/installer paths call parseSkillManifestFromDir directly, bypassing the cache, so disk→DB reconciliation always reads fresh. Content-class clean (in-memory parsed result only). Covered by skills-loader-cache.test.ts.

(a) — IMPLEMENTED in Wave P3 (RT-2, 2026-06-18). The grounded answer's stable grounding rules + preface now ride in a cacheable system prompt (GROUNDED_SYSTEM_PROMPT = BASE_SYSTEM_PROMPT + the rules) instead of the per-turn user message, so cache_prompt's prefix reuse no longer stops at BASE_SYSTEM_PROMPT and re-prefills them every documents turn (the prior user turn is replayed as the RAW question, so the grounded prefix never matched). The per-turn user message keeps only the question

  • excerpts. The skill fence still rides in the user turn deliberately — it is untrusted reference text and must never read as a top-level rule (§22-H2), so this is the grounding-RULES move, not a fence move; the excerpts themselves are inherently per-turn and still re-prefill. ~58 approx tokens of rules now sit in the always-reused prefix; precedence is unchanged/strengthened (rules in system ≥ user, still outrank the fence) and the [Sn] + no-context contracts are untouched. See "Performance — design record … Wave P3" (RT-2).

Recommended, not implemented (deliberately out of scope, recorded so the trade-off is visible): (b) for a large user skill near the budget, the plain-chat fence trim depends on the current question's length (buildTurnFence subtracts the live final-turn tokens), so the system prefix can shift turn-to-turn and defeat PERF-1 — sizing the fence against a fixed user-turn reserve would keep it byte-stable, but it is a no-op for every shipped skill (none trim) and was left for a follow-up to avoid changing the §22-A6 budget contract (RT-9, still open).

§18 Auto-fire triggers (S13 — gated on an evaluation harness, 2026-06-17)

S13 closes the one remaining skills feature: auto-fire — the app applying the right skill to a turn the user left without one, saving the tap. It is the opt-in extension of the §6 suggestion scorer, and it shipped in three gated sub-phases. The full original working paper (docs/skills-s13-plan.md, deleted at S13 close — text in git history) holds the baseline tables; this is the design as built.

The gate (S13a — harness + corpus + baseline). Auto-fire ships only after an offline, deterministic harness proves a precision bar on a labelled corpus — a false fire (shaping an answer the user didn't ask for) is the costly event; a miss just falls back to the tap-offer. A synthetic, no-user-data corpus of 161 labelled turns (tests/fixtures/skill-triggers/corpus.json) is scored through the production suggestSkillsForTurn / resolveAutoFireSkill on a real temporary database with the committed app skills reconciled (tests/eval/skill-triggers.ts + .test.ts), reporting precision/recall + a confusion matrix. Still no model and no network. The question is content: scored, never logged (a privacy guard extends the S12 sentinel posture).

The ratified contract (owner, 2026-06-17 — D1–D6). D1 ≥ 95% precision. D2 threshold-3 — fire only when a keyword hit is corroborated by ≥ 1 doc signal (a separate AUTOFIRE_SCORE_THRESHOLD = 3, distinct from SUGGEST_SCORE_THRESHOLD = 2, plus — since #130 (2026-08-09) — an explicit doc-signal-required gate in selectAutoFire: the threshold alone never enforced the doc half — a lone keyword = 2 and a lone doc signal ≤ 2, but TWO capped keyword hits = 4 fired with zero docs in scope — so the gate now structurally means "the user asked and a relevant doc is present"). D3 silent apply + the existing glyph + a one-click undo (never a confirm-before-firing dialog). D4 opt-in, app-skills only in v1. D5 fire only when the turn has no skill set (never override a sticky default or a per-turn pick/clear). D6 additive triggers.autoFire?: boolean (only true opts a skill in). On the original §3.3.1 baseline threshold-3 cleared 100% / 88.2% recall; the harness asserts the owner-set form fired-wrong == 0 AND precision ≥ 0.95 so it survives corpus growth.

Suggestion-selector bar (S13a — gated since 2026-10-05). The same offline harness scores the suggestion path (suggestSkillsForTurn) over the whole corpus, one test per row. The owner ratified the suggestion bar (2026-10-05), and it is a hard CI gate: precision ≥ 0.95 overall; zero wrong and zero missed on the confusion rows (the cross-skill pairs); and every row gives its expected offer except the rows listed in KNOWN_SUGGESTION_DEVIATIONS in tests/eval/skill-triggers.test.ts, whose entry must be removed when the row is fixed (a stale entry fails). Five rows are listed today: adv-meeting-schedule-01 (a scheduling question that merely names a meeting still offers meeting-protocol, the precision ceiling of a one-keyword offer); tp-redaction-de-pd-version-01 and tp-redaction-de-pd-loeschen-01 (German removal requests that only the bare "personenbezogene Daten" offered on until #608; #602 found no safe keyword for them, see below); and tp-redaction-en-sensitive-blackout-01 and tp-sharesafe-de-sensible-01 (a removal request and a check before sharing that only the bare "sensitive data" / "sensible Daten" offered Redaction on, which the labellers accepted, until #604: the accepted cost of that decision, see below). The GDPR row tp-redaction-en-02 left the list in #583, when "remove all personal data" joined the vocabulary. Measured on the 161 rows: suggestion precision 99.1%, recall 96.4% (108 correct, 1 wrong, 4 missed), confusion set 0 wrong / 0 missed. The printout (formatReport, at the start of the S13b gate) shows the two production paths: suggestion (all rows) and auto-fire, the latter twice, once over the gate set and once with the accepted deviations counted as wrong (identical while none is accepted). Question text is scored but never logged. The numbers the deleted skills-s13-plan.md §3.3 used to hold now live here — this record is their durable home.

Auto-fire deviations: none since #604 (owner decisions 2026-10-05 and 2026-10-06). The D1 gate counts the rows in KNOWN_AUTOFIRE_DEVIATIONS separately: they must fire exactly the listed skill, over the other rows fired-wrong == 0 and precision ≥ 0.95, and ACCEPTED_AUTOFIRE_WRONG_FIRES caps the wrong fires over all rows; a row whose document is only in the Library (not explicitly selected) must never auto-fire (the U4 narrowing and the #130 doc-signal gate). From 2026-10-05 the owner accepted two such rows: German share-safe questions with "sensible Daten" (tp-sharesafe-de-01, -02) fired document-redaction's read-only scan, because the keyword belonged to both skills and only redaction auto-fires. #604 ended them (below): the map is empty and the cap is 0. Measured auto-fire precision is 100% (34 correct, 0 wrong, 78 missed, recall 30.4%) over all rows. Auto-fire recall is low by design: rows labelled with the five skills that never auto-fire count as misses.

#604: "sensible Daten" / "sensitive data" stop offering (owner decision 2026-10-06). The #608 mechanism, for the other topic phrases: sensitive data and sensible daten were offer keywords of Redaction (for its "is there sensitive data in it?" scan) and sensible daten also of Share-Safe, so one hit plus any PDF auto-fired Redaction on legal, privacy-policy and contract questions. A pre-registered blind evaluation measured it: 90 messages (46 German, 44 English), each naming sensitive data, labelled independently by two models (agreement 100% / 90%). Today 46 of the 90 got Redaction applied, and both labellers called 18 of those harmful, every one a legal question or a question about what a notice, contract or policy says. The phrases are now route-only in both skills, and Redaction offers six removal phrases instead (remove sensitive data, remove the sensitive data, remove all sensitive data, mask sensitive data, sensible daten entfernen, sensiblen daten entfernen): right suggestions 36 → 60 of 90, harmful auto-fires 18 → 0. On "is there sensitive data in it?" the labellers wanted Share-Safe or no suggestion, not Redaction, and split on an automatic scan there (harmful to one on 7 of 17, to the other on 2, never to both), so the scan stays one pick away. The cost: removal requests phrased only with the topic ("Please black out all sensitive data") lose the offer (13 → 5 of 15), and so do checks before sharing, where Redaction was an accepted offer (8 → 0 of 15). Keeping Share-Safe's sensible daten (scored 58, and ahead on a strict reading, 48 to 43) was the alternative; the owner chose the pre-registered pick. With Redaction active, "Mask the sensitive data" now gets the run button (the bare phrases were offer-only in Redaction, so routing on them is new), and so does a retention question naming "Löschfristen … für sensible Daten" (the #608 lösch rule plus the new route term). The removal phrases are bare verb-plus-topic substrings like #608's "… entfernen" ones: a duty question in that word order ("Muss ich laut Vertrag sensible Daten entfernen, …?") would still suggest and, over a PDF, auto-fire Redaction; none of the 90 messages used one. Eight corpus rows pin it, two of them the accepted cost in KNOWN_SUGGESTION_DEVIATIONS.

#608: the bare "personenbezogene Daten" (owner decision 2026-10-06). The article-less German phrase was an offer keyword of both skills, so it suggested Redaction (the tie-break) and, over a PDF, auto-fired it on GDPR, privacy-notice and contract questions. It now only routes, in both skills, as English "personal data" always did. A blind evaluation decided it: 120 German messages in six situations, written by one model without the keywords and labelled independently by two others (94% agreement), went through the production paths. Right suggestions rose from 59 to 92, and auto-fires both labellers called harmful fell from 24 to 0. The cost: removal requests that name only the data lose the offer (3 of 20). Redaction offers seven German removal phrases instead: "personenbezogenen Daten entfernen", and "entferne …" or "lösche …" before the data, with "alle", "die" or no article (vocabulary.ts). The infinitive "… Daten löschen" is left out on purpose: "löschen" is also the GDPR erasure term, and deletion-duty questions ("Wann muss ich personenbezogene Daten löschen?") would fire Redaction (owner ruling, the same day; the corpus pins both forms). With Redaction active, a word-initial "lösch…" now counts as a removal request in the handler (REDACT_ACTION_RE, beside "entfern…"), so "Lösche die … Daten" gets the run button, and a question about a document's "Löschung …" is no longer answered with a count scan: it gets the normal answer, or the button when a route term (such as the bare phrase) also matches. Asking whether the data is "gelöscht" stays a count scan. The phrase list does not cover every request: "Bitte personenbezogene Daten löschen." and "Entfernen Sie …" get no offer (#602), and first-person statements ("Ich lösche die personenbezogenen Daten nach sechs Monaten – …") still match "lösche die …".

#602: German removal requests stay a limit of keyword suggestion (owner decision 2026-10-06). A second blind evaluation, pre-registered the same way, tested three word lists for Redaction: request forms of the removal verbs (anonymisier, pseudonymisier(e), schwärz, unkenntlich, maskiere(n)), plus Sie-imperative phrases ("Entfernen Sie … personenbezogene Daten"), plus participles and adjectives (anonymisierte, pseudonymisiert, …). The set held 90 fresh German messages: 30 removal requests, 20 requests to remove something that is not personal data, 20 legal questions and 20 questions about a selected document; labeller agreement 94% / 92%. Today Redaction is offered on 6 of the 30 requests. No list passed the gates (no new wrong suggestion, no new harmful auto-fire, at least 3 more requests). The first two lists gained 3 requests, all through unkenntlich, which also suggested and auto-fired Redaction on a legal question about anonymising court decisions; the Sie-phrases caught none. The third gained one more request (through pseudonymisiert) and three new wrong suggestions: a legal question and two questions about a selected document ("Wurden die Daten in der Studie pseudonymisiert oder anonymisiert?"), one of which it auto-fired. Real requests rarely name "personenbezogene Daten" at all ("Namen, Personalnummern und Gehälter müssen raus", "Beteiligte neutralisieren"), so a co-occurrence rule (the data plus any removal word, measured report-only) reached only 12 of 30, with 3 new wrong suggestions and 2 harmful auto-fires. Nothing changed in the vocabulary; three corpus rows pin the rejected words (adv-unkenntlich-legal-01, adv-pseudonymisiert-legal-01, adv-pseudonymisiert-doc-01). Better recall for such requests is the §6 scale-up path (embedding-based suggestion), not more keywords.

#603: German "can I send this?" questions stay a limit of keyword suggestion too (owner decision 2026-10-06). The same protocol tested three word lists for Share-Safe Review: seven nominalised infinitives ("zum Teilen", "zum Weiterleiten", "zum Versenden", …, the family that caught the most on the #608 set), plus 30 permission phrases ("darf ich das …", "kann ich das …", "das so …" with ten sending verbs), plus five safety words (bedenkenlos, unbedenklich, verschickbar, versendbar, weiterleitbar). The set held 90 fresh German messages: 30 questions whether a selected document can be passed on as it is, 20 sending tasks already decided, 20 legal questions about passing on information and 20 questions about a document where sending is the topic; labeller agreement 94%. Both labellers want Share-Safe on 21 of the 30 sharing questions; today it is offered on 1 (through "Metadaten"). No list reached the gate of 3 more right answers: the first two added none, the safety words 2 (with no wrong suggestion). People ask "Geht das so raus?", "Ist der Entwurf reif für die Gegenanwältin?", "Spricht was dagegen?", and when a sending verb appears, the recipient sits inside it ("kann ich das so an den mandanten schicken oder fällt dir noch was auf?"), so no contiguous phrase matches. A co-occurrence rule (a sending word plus a permission word, measured report-only) added 1 right answer net and made 7 wrong suggestions: three legal questions, two sending tasks, a question about what a contract allows, and a sharing question with no document selected. Nothing changed; the route to better recall is the same §6 path.

#582: English and German compare requests route alike (owner decision 2026-10-07). With What-changed active at any document count other than two (one document, three, a whole Library), applies() is false, so intends() (the skill's routing vocabulary) decides between the "select exactly two documents" answer and the ordinary engines (SKA-8, §39). German "Fasse die Unterschiede zusammen" matched unterschiede and got that answer. English "summarize the differences" matched nothing. The task router already reads both as a compare (COMPARE_RE), so the English turn became a top-k answer under the compare fence. The shipped 0.1.59 build with a 4B model showed the cost: over one draft it invented a "Document B", and over three drafts it compared passages mixed across all of them. The owner chose to route both languages:

  • differences is now an offer and route term like unterschiede.
  • Route-only, English: compare, comparison, changes, changed, old version, new version, and the noun the change / a change. A bare change is mostly the verb ("How do I change my password?"), which German ändere/ändern does not route either.
  • Route-only, German: geändert, geänderte(n), verändert, veränderte(n) and veränderung(en). German puts the participle last, so was hat sich geändert missed "Was hat sich am Vertrag geändert?".
  • Route-only, both languages: the rest of what COMPARE_RE reads as a compare: difference, versus, vs, diff, unterschied, and vergleich with vergleiche / vergleichen.

The German forms are listed word by word, because a stem would also catch "unverändert" (unchanged), "unterschiedlich" (various) and "Vergleichs…" compounds (a legal settlement), none of which English routes. compare, difference and unterschied replaced the phrases they cover (compare these, compare the two, difference between, unterschied zwischen), and the offer phrase differences between went with differences. The cost: while What-changed is active at the wrong count, more questions with a compare or change word get "select two", in a Library chat too. German änderung already reached that far. Accepting the differences offer, or a classifier offer (#133 counts the routing answer as engaging), over one document also leads to "select two". The offer changes only for differences. What-changed never auto-fires, and its install id loses every equal-score tie, so it cannot take another skill's offer. skills-analysis-whole-doc.test.ts pins 23 request pairs side by side, and each English request must get the same answer as its German counterpart. rag-skill-analysis.test.ts runs "summarize the differences" through the real W2 pre-pass. Corpus row tp-whatchanged-en-03 is the English twin of tp-whatchanged-de-02. Left open: "amendments" / "modifications" route in neither language (a recall gap, not a language gap).

The mechanics (S13b). triggers.autoFire?: boolean is additive + lenient in shared/skill-manifest.ts (only boolean true opts in; absent/false leaves manifest_json byte-unchanged). services/skills/autofire.ts resolveAutoFireSkill(db, deps, conversationId, question): candidates = enabled + available + app-only (D4) + triggers.autoFire === true (D6) + compatible (§6.5/M1), scored via the existing scorer over the factored-out scope-signals.ts inScopeDocSignals (shared with suggest.ts, no duplication), gated at AUTOFIRE_SCORE_THRESHOLD. It reads the skillsAutoFireEnabled opt-in first and is a true no-op when off; it logs nothing (the question is content). It is plugged into the single resolution path resolveTurnSkill (services/skills/turn.ts) only in the would-return-null branch AND only when no per-turn pick was made (requestedInstallId === undefined) — both chat channels (registerChatIpc / registerRagIpc) pass the turn text, so a documents conversation auto-fires too.

The surprise-mitigation UX (S13c). Two surfaces, both EN/DE:

  • The opt-in toggle (D4). A Switch in Settings → Skills (SkillsTab.tsx) reads/writes skillsAutoFireEnabled through the shared updateSettings patch path, off by default, hidden until the setting loads (never implies an unconfirmed state). This is the only control that makes S13b reachable — until it ships, auto-fire cannot be enabled by a user.
  • The per-turn undo (D3). An auto-fired turn stamps an additive, nullable messages.auto_fired column — set only when the auto-fire path placed the skill AND the fence was actually placed (the §22-A5 stamp-only-when-fenced precedent), so it lines up 1:1 with the glyph and a deleted skill drops glyph + undo together. Carried via an additive TurnSkill.autoFired + Message.autoFired (a boolean — never content; the simpler "undo on every skill turn" alternative was rejected as it would surface the undo on explicit picks too, contradicting D3). The Transcript glyph on an auto-fired turn reads "Answered with <skill>" + a one-click "answer without it" on the last assistant turn; tapping it re-runs the same user question with the skill explicitly cleared (skillInstallId: null) — the explicit per-turn clear both stamps no skill and suppresses a re-auto-fire. It reuses the regenerate path in both modes; askDocuments gained a symmetric regenerate argument (drop the last assistant turn, re-use the existing last user turn — never a duplicate user row).

Safe-merge property. With skillsAutoFireEnabled default-false, a fresh install behaves identically to pre-S13 regardless of which skills opt in — auto-fire only activates once a user turns it on (S13c). The §14 ceilings + the S12 sentinel guard are unchanged: a wrong fire is at worst a worse answer + a one-click undo, never an unauthorized action; the undo is a re-run, not a new capability; no auto-fire path adds an audit event or logs the question.

First opted-in product skill (D6). document-redaction declares triggers.autoFire: true (the first bundled skill to do so; U4 later opted in bank-statement, invoice and meeting-protocol). Once a user enables auto-fire, an "anonymize/redact"-style turn over a selected pdf/plain/markdown document auto-applies it: keyword (2) + the in-scope-doc MIME signal (1) = 3, clearing AUTOFIRE_SCORE_THRESHOLD. On the corpus it fires on no row it should not (the two accepted German share-safe rows ended with #604, "Auto-fire deviations" above). A "selected" document is one in the conversation's persisted scope, so inScopeDocSignals surfaces its MIME main-side (§22-C4) — the same phrase with no document in scope scores 2 and does not fire (regression-tested in skills-autofire.test.ts).

§19 Full-document analysis for tool skills (2026-06-19, D44–D49)

The bug this closes. A kind:tool skill ships deterministic whole-document tools (the §7/§8 gate), but when a user just asked about a document in chat the turn took the ordinary top-k RAG path (generateGroundedAnswer) with the SKILL.md body as a fenced reference — answering from ~5 retrieved passages, not the whole document. For accounting (the bank-statement test case) a partial read means wrong totals; the coverage badge correctly said "based on the most relevant passages," but the analysis was still partial. (Folded from docs/full-doc-skills-plan.md, deleted at this phase; full text in git history. Coverage half cross-linked from rag-design.md §14.7.)

Decisions (locked with the user 2026-06-19, continuing the global series after D38–D43):

  • D44 — the fix is a general kind:tool mechanism, not a bank-only patch: the bug is a class (any tool skill's correctness guarantees are bypassed on the chat path). Bank-statement is the first adopter + the test case; invoice the second.
  • D45 — when a doc can't be analysed exhaustively (any in-scope doc not fully chunked), refuse the partial answer with a fixed, localized message pointing at the existing Documents → Re-index affordance — no model call, no partial answer (honesty posture §22-D1). A silent partial accounting answer is worse than a clear "not yet."
  • D46 — a plain chat question auto-runs the skill's READ-ONLY tools (export stays confirm-gated). Read-only, deterministic, no side effects — a question should give exhaustive results without an extra click. This narrows the "tools run only when the user starts them" contract to read-only tools.
  • D47 — the answer is synthesised from the structured tool output (the compact extracted table), never by prompt-stuffing every chunk: the structured result fits context trivially; top-k RAG exists because raw documents overflow it.
  • D48 — coverage stops being hardcoded relevance: a real CoverageInfo is persisted per message and the renderer shows the truth. Requirement "if we analysed the full document, show that" is inexpressible until the meter is data-driven.
  • D49 — adoption is per-skill: bank-statement + invoice both register an analysis handler; document-redaction does not register an exhaustive handler (it is an action skill — it redacts a document — not an analysis-question skill, so a plain question is never force-routed through a whole-document tool run).
    • D49a (amended 2026-06-22). document-redaction now registers a routing handler instead of nothing. The original "keep the relevance path" choice produced two real defects on an "anonymize this" turn: the model wrote a lecture/refusal (reciting the SKILL.md caveats — "you never run it yourself", everything it won't catch — and inventing a manual procedure) instead of pointing at the one-click run affordance, and it even speculated about the document's content from top-k passages; and the coverage badge read "based on the most relevant passages, NOT the whole document" — misleading, since the tool reads the whole document. The handler gains a mode: 'exhaustive' | 'routing' discriminator (default exhaustive). A routing handler reads no content, runs no tool, emits no audit event: on a redaction-shaped request (applies() matches the action verbs + ≥1 in-scope doc) it returns a short, deterministic, localized answer naming the same run button the SkillRunBar shows (chat.skill.tool.redactDocument), with no citations and no coverage (the meter renders only for answers with citations — Transcript.tsx — so the misleading badge is gone). (#44 closed the other half of this promise: the handler names the button unconditionally and cannot see the run bar's state, so the bar itself now guarantees the button exists — a terminal, un-dismissed result row no longer suppresses the offer; only an in-flight run does.) The chat path skips the D45 fully-chunked refusal for a routing handler (nothing is read). The SKILL.md body was rewritten so its first paragraph (the one the prompt builder guarantees to keep) is the action-routing instruction, with the honesty caveats demoted — fixing the fallback path when the model does answer (an off-topic turn). SkillAnalysisResult.coverage is now optional. The write tool stays user-initiated + confirm-gated — routing points at it, never runs it.

The seam (main/services/skills/analysis/). A small registry keyed by skill install_id → SkillAnalysisHandler (applies({question,scope,db}): boolean + run(ctx): Promise<SkillAnalysisResult>), following tool-registry.ts: no import-time side effects, app-owned, populated by an explicit registerBuiltinSkillAnalysisHandlers() called once at app init (main/index.ts, before any register*Ipc). SkillAnalysisResult = { answer; citations; coverage }. A handler's only content reach is the same run seam the doc-action path uses (run.ts / invoice-run.ts over the faithful extractDocumentPreview segment reader) — the §7/§14 ceiling is unchanged: it adds no new DB/FS/net handle, and the export tier is excluded by construction (the CSV-export run fns are never imported).

Per-message coverage contract (D48). messages.coverage_json TEXT (nullable, additive ensureColumn; old rows = NULL); Message.coverage?: CoverageInfo; appendMessage serializes it tolerantly (a stringify fault degrades to NULL, never blocks the append) and rowToMessage parses it (NULL/malformed → undefined). The relevance path persists no coverage (stays NULL); the renderer falls back to { mode:'relevance' } so every pre-migration message and every non-re-routed turn renders byte-identically (R5). The skill-analysis path stamps a real { mode:'extract', chunksCovered, chunksTotal, fullyChunked }, where fullyChunked gates the "whole document" meter wording. (Later additive fields: D72 stamps relevance with real counts on the relevance path; #643 adds labelledExcerpts to a capped answer whose prompt showed every section under its [Sn] label — rag-design §14.4 "#643 amendment". Old rows stay as written.)

Chat routing + the refuse gate (in registerRagIpc.askDocuments). After the turn skill resolves + scope/filename auto-scope, and BEFORE the routeQuestion/generateGroundedAnswer decision, the turn looks up getSkillAnalysisHandler(skill.installId) (the registry is the opt-in — a registered handler implies kind:tool; no separate kind check). When handler.applies(...): allInScopeDocsFullyChunked(db, scope) reads documents.fully_chunked at turn time (R4, not a cached flag) — not fully chunked ⇒ refuse (skills.analysis.refusePartial, NULL coverage, no model call, skill stamped); fully chunked ⇒ handler.run(ctx) with a production context (the skills audit adapter, the extractDocumentPreview reader, tMain, the chat slot's abort signal). Both outcomes acquire the chat slot via withChatStream exactly as the coverage-extract branch (R3, the single-locked-slot contract). When no handler is registered or applies() is false the whole block is skipped and the relevance + coverage-extract paths run byte-unchanged (R5).

Per-skill adoption. Each handler's applies() is conservative: a single in-scope document (R2 — multi-doc keeps relevance) and an analysis-shaped keyword set (EN+DE, substring-ambiguous tokens avoided per §1's DS17 caution). run() auto-runs the read-only tools through the run seam for their skill_runs lifecycle + ids/counts audit, then computes the answer's figures from the persisted rows via the pure tool functions. Single row load + seam-output reuse (Phase-4 perf, audit P-1/P-2): the handler loads the statement rows once — loadStatementRowsWithCategories is now the sole bank_transactions read on the non-category path — and hands them to the downstream seams as a new optional preloaded arg (prepareStatementRun/prepareInvoiceRun skip their own load when it is supplied). The read-only seams (summarize_cashflow, validate_statement_balances, validate_invoice_totals) now return their validated structured output (CashflowSummary / ReconcileResult / InvoiceTotalsResult) for in-process reuse, so the handler reuses it instead of recomputing the same pure function over a re-queried row set (a pure recompute is the fallback if a seam failed). These outputs are figures (content) and stay in-handler — they are never mapped into ToolRunOutcome/IPC (the run-bar dispatch in tool-runs.ts still maps counts only). The skill_runs lifecycle + ids/counts audit are unchanged (the summarize_cashflow run + its skill_run_* trio still fire — approach A, not the "drop the summary run" alternative B). Net: a non-category bank question issues one bank_transactions read (was three: two seam loads + the handler load); an invoice question one invoice_line_items read (was two). The answer is deterministic, localized Markdown honouring the SKILL.md honesty posture (quote printed figures; surface flagged rows before the headline; never invent), with real [Sn] source-chunk citations (M2-safe, never the synthesised total). On this exhaustive path the honesty posture is code-enforced, not body-driven: buildBankAnswer/buildInvoiceAnswer (analysis/bank-statement.ts, analysis/invoice.ts) reimplement those rules directly in TS, so editing the SKILL.md body changes only the off-topic relevance fallback (where the body rides the fence) — the body and the TS must therefore be kept in step. Audit A-1 (Phase 10) pins that step with a parity test (skills-skillmd-parity.test.ts): for both skills it asserts the SKILL.md body still states each honesty bullet (unreconciled-before-total, reconcile-or-say-so, never-invent) and that the answer builder still produces the matching honest branch for a constructed unreconciled / contradicted / mixed-currency / missing-figure case — so a drift in either the body or the TS now fails a test.

  • bank-statement (analysis/bank-statement.ts): extract_transactions → summarize_cashflow + validate_statement_balances (+ categorize_transactions only when the question is category-shaped). Leads with the count, surfaces unreconciled rows before the totals, reports mixed currency as "no single total." Citations narrow to the transactions' source_page. The category-shaped breakdown runs the deterministic rule pass here (0 model calls); since the "Categorize" button uses the richer LLM taxonomy, the chat answer labels a rule-based breakdown as such and points at the button (audit C-2 — see §22 "Consistent breakdown framing"), so the two entry points are not silently divergent.
  • invoice (analysis/invoice.ts): extract_invoice → validate_invoice_totals. Surfaces any failed reconciliation check (line-items→net, net+tax→gross, tax-vs-rate) before the headline gross; prints only the figures the invoice states (a field that couldn't be parsed is left out). The invoice schema records no per-figure source page, so citations are the document's leading source chunks (still real chunks, M2-safe). i18n: skills.invoiceAnalysis.* (EN+DE parity), reusing the shared coverage.extract.* meter + skills.analysis.refusePartial refuse copy.
  • Invoice reuse / replace / staleness — parity with the bank path (F5, post-merge audit Phase 3). The invoice analysis handler now uses the same reuse-or-re-extract decision as analysis/bank-statement.ts (it previously re-extracted + INSERTed a fresh invoices row on every analysis question — unbounded content-table bloat for a deterministic re-extraction). invoices gained an extractor_version column (additive nullable migration in db.ts, mirroring bank_statements.extractor_version); every extraction stamps it with INVOICE_EXTRACTOR_VERSION (tools/invoice.ts). The handler resolves latestInvoiceId(db, docId) and REUSES it when present and not stale; it re-extracts only when none exists OR isInvoiceStale (stored version NULL/legacy or < current). A re-extract passes replaceExisting: true, so runInvoiceExtraction calls the shared deleteInvoicesForDocument (the SAME ordered FK delete purgeSkillDataForDocument uses — invoice line items, then invoices) inside the persist BEGIN/COMMIT before the INSERT (atomic swap; a failure rolls back to the old). The old totals_reconciled flag goes with the replaced row (the validate seam recomputes it). latestInvoiceId is the single shared "latest invoice" helper (invoice-run.ts, created_at DESC, id DESC tie-break) across both call sites — the downstream run seam and this read-back. Bump INVOICE_EXTRACTOR_VERSION whenever the invoice parser changes output for the same input (it is at 1 — baseline = the parser as built through the post-merge Phase 1 F1/F3/F6/F8 hardening; legacy NULL rows are stale and re-extract on next reuse). Tests: skills-analysis-invoice.test.ts (N questions persist exactly one invoice + one line-item set; a fresh invoice is reused with no duplicate; a version-NULL invoice is detected stale → re-extracted + replaced in place at the current version).

Scope resolution (audit X-1, Phase 10). Each handler's applies()/run() resolve the in-scope documents through the one shared documentsInScope(db, scope, { requireChunks }) helper (services/skills/scope-documents.ts) — the single definition of "indexed documents in a resolved scope," replacing five hand-copied queries. The analysis handlers pass requireChunks: true (they read the stored chunks, so an indexed-but-unchunked document is not answerable here); the run path (resolveInScopeDocumentIds) and the suggest/auto-fire path (inScopeDocSignals) pass false (the run re-extracts faithfully from the stored copy; the suggestion is keyword/MIME signal only). The helper logs nothing and stays main-side — a title is content-adjacent and never crosses IPC from it — and its deterministic ORDER BY created_at, id keeps resolveInScopeDocumentIds[0] the stable default run target (U-1/U-2). (The RAG router reads this same helper since R4; its own scope-filtered counts — extractionsExistInScope, readyTreeCountInScope, allInScopeDocsFullyChunked — are pinned through rag:ask by rag-routing-scope.test.ts, #714.)

Tests. skills-analysis-bank.test.ts + skills-analysis-invoice.test.ts (handler-level: applies() pre-flight, exhaustive math from rows, flagged check surfaced before the headline, figures quoted not invented, export never auto-run, coverage fullyChunked true/false, real source citations); skills-skillmd-parity.test.ts (audit A-1: the SKILL.md honesty bullets ⇔ the buildBankAnswer/buildInvoiceAnswer honest branches, both directions); rag-skill-analysis.test.ts + rag-skill-analysis-invoice.test.ts (IPC-level over the real askDocuments: exhaustive path with coverage.mode==='extract' + no model call, refuse path, relevance path byte-unchanged, single-locked-slot contract).

§20 Skill-aware whole-document analysis for instruction skills (2026-06-22, Wave 2)

The gap this closes. §19 gave kind:tool skills a whole-document path, but the Tier-1 instruction skills (meeting minutes, contract brief, share-safe review, deadlines) still answered from top-k relevance — because the SKILL.md fence is applied on exactly one engine, the relevance generateGroundedAnswer path. Every whole-document engine (the §19 handlers, coverage-extract, tree-summary) ignores the fence. So an instruction skill could be whole-document OR formatted-to-its-spec, never both — worst case meeting minutes built from ~5 retrieved passages miss decisions/action items, and "summarize meeting" could hijack to a generic tree-summary that ignores the 8-section format. (Folded from docs/skill-whole-doc-engine-plan.md, deleted at this phase; full text in git history. Continues the §19 audit recorded in BUILD_STATE 2026-06-22.)

The engine (grounded-whole-doc). A third SkillAnalysisHandler mode (after §19's exhaustive and Wave 1's routing). Unlike exhaustive (deterministic, model-free, hardcoded TS) these stream a model answer, so they do NOT use run() (it is now optional and omitted). Instead registerRagIpc detects the mode and calls generateGroundedAnswer({ wholeDocument: { documentId } }): the grounded context is the single in-scope document read in order (retrieveWholeDocument, not top-k), capped to a whole-document token budget (wholeDocumentBudgetTokens = the real launched window − answer reserve − system prompt − question − the skill-fence allowance), with the SKILL.md fence riding in the grounded USER turn exactly as the relevance path. The persisted coverage is the honest capped mode — truncated:false ⇒ "covers the whole document"; truncated:true ⇒ "covers the beginning" (the meter wording already existed for the summary task). The §19 fully-chunked refusal (D45) still gates the turn (a not-fully-chunked doc is refused, no model call). The relevance path is byte-unchanged: coverage stays undefined ⇒ persisted NULL ⇒ the relevance badge.

Per-skill adoption (single-document; analysis/whole-doc-skills.ts). meeting-protocol, contract-brief, share-safe-review, deadline-obligation-finder each register a handler whose applies() matches an analysis-shaped keyword set (EN+DE) over a single in-scope document. Because these skills are explicitly selected, the keyword sets include the bare domain nouns (e.g. contract/vertrag) — includes can't span "summarize this contract", so the noun is the robust trigger; an off-topic question or a multi-doc scope still keeps the relevance path. what-changed is the 2-document sibling — see the compare record below (Follow-up B).

Large documents — deep-index map-reduce (Follow-up A, Wave 3, 2026-06-22). An over-budget document no longer truncates to its beginning when a ready deep-index tree exists: generateGroundedAnswer detects retrieveWholeDocument's truncated flag and hands off to answerWholeDocFromTree (rag/whole-doc-tree.ts), which runs the SAME map-reduce the tree summary uses (manager.summarizeFromTree) over the precomputed node summaries — the deepest layer (level 1 = full leaf coverage) read via nodeSummariesAtLevel — with the SKILL.md fence applied at every step (a skill-fenced MAP per packIntoWindows window when the summaries span >1 window, then a skill-fenced streamed REDUCE; when they fit one window the single fenced reduce IS the step). With no skill (the #642 tree summary) there is no fence, and each map and fold step takes notes for the user's request, its only target (#952, follow-ups wave 5; rag-design.md §14.10). It stamps the honest tree coverage (treeStatus:'ready', chunksCovered = reachableLeafChunkIds, treeLevels, truncated:false) and cites the leaf chunks (documentLeafProvenance, M2-safe — node summaries are never [Sn]). It returns null when there is no usable tree (no ready status / no node summaries), so the turn falls back to the byte-unchanged Wave 2 capped/"covers the beginning" path; once a model call has run it always returns a Message (the answer, or an empty one on Stop), so a cancel never triggers a second capped pass. A document that fits the budget never enters this branch (truncated:false) — the small-doc path is byte-identical to Wave 2. The §14 ceiling is unchanged: pure DB tree/coverage reads + the chat runtime, no new DB/FS/net handle; the fence (with its guard line) keeps bracketing the untrusted body in every step's USER turn, the app-authored system prompt outside it. Still open for the tree path: a tree-backed compare (applying this map-reduce per oversized document inside the 2-doc compare below) for the DISSIMILAR-document fallback — a similar version pair now goes through the diff-driven path (compare-diff record below), which reads both docs whole without capping.

Whole-doc analysis truncation fix (2026-07-04/05, 4-phase wave — full record: rag-design.md §14.10). The tree rescue above only fires for a document with a ready deep-index tree, which auto-builds at 50 pages — so every document in the "gap band" (1.5–50 pages) still truncated to its beginning, and a long deliverable still overran n_ctx. Four phases closed both cuts, all in the shared core streamWholeDocMapReduce (so the tree rescue and the new chunk path share one engine): (1) the map-reduce body was extracted from answerWholeDocFromTree into that core, and a new answerWholeDocFromChunks runs the same map-reduce over the document's de-overlapped raw chunks (no tree needed) — honest capped/untruncated "covers the whole document"; (2) the reduce output cap is adaptive + notes-first (computeReduceBudget — aims for a 3072-token deliverable, yields toward the 1024 floor so whole-doc coverage survives a 4 k window, prompt + output ≤ n_ctx always); (3) the ephemeral 'analysis' progress notice fires for the silent map-call window (windows.length > 1); (4) continue-generation re-prompts to FINISH a finishReason==='length' deliverable (same fence + notes + question + a resume anchor, seam de-duplicated) across ≤ 2 bounded passes, stamping an honest Message.truncated (OUTPUT-cut, parity with the single-turn grounded path) — kept distinct from coverage.truncated (INPUT coverage) — only when the cap is exhausted. The §14 ceiling + the fence/guard bracketing are unchanged throughout. Repetition guard (#994, follow-ups wave 7, record: rag-design.md §14.10, §14.10.2). The core watches what the model streams (rag/repetition-guard.ts, pure, complete lines only): the same line six times in a row, compared with its numbers, stops the pass by leaving the token loop (the stream's finally cancels the request). Rows that differ only in numbers never trip it; the Meeting Minutes recursion is not stopped (no heading rule passed its evaluation). The answer is cut back to before its repeated tail and ends there, stamped truncatedCause: 'repeat' (B1; a trip in a continuation ends it the same way). A map or fold note that loops is stopped and keeps one copy. The single-turn grounded path passes no guard to the shared engine, and a turn that never trips sends every request as before.

2-document whole-doc compare (Follow-up B, Wave 3, 2026-06-22). what-changed registers a grounded-whole-doc-compare handler (analysis/whole-doc-skills.ts) whose applies() matches a compare-shaped keyword set (EN+DE) over exactly two in-scope documents. registerRagIpc detects the mode (after the same D45 fully-chunked refusal, which now gates both docs) and calls generateGroundedAnswer({ wholeDocumentCompare:{ documentIds } }): retrieveCompareWholeDocuments reads BOTH documents in order (not top-k), splitting the whole-document budget across them size-aware (splitCompareBudget: each gets up to half; a smaller doc donates its unused half to the larger, so two versions that jointly fit are both read whole — the common case — while two large versions each get ~half). The two documents ride the grounded turn as labelled blocks (buildCompareWholeDocPrompt — "Document 1 — …" / "Document 2 — …", so a same-titled version pair stays distinguishable) with the SKILL.md fence; [Sn] labels run continuously across both so a citation unambiguously names its version (M2). Coverage is honest capped — truncated:true when either doc overflowed its share. A 1- or 3-doc compare-vocabulary ask gets the deterministic "select exactly two" answer (rag-skill-analysis.test.ts). The §14 ceiling + the fence/guard bracketing are unchanged.

Tests. rag-whole-doc-tree.test.ts (the tree map-reduce: single-level → one fenced reduce + tree coverage + leaf citations + skill stamp; multi-level + small context → map-per-section then reduce with the fence at EVERY step; no-ready-tree → null + no model call). rag-whole-doc-compare.test.ts (IPC: the compare path streams a model answer with BOTH whole docs in one labelled turn + capped coverage + cross-document citations; the refuse path when a doc isn't fully chunked; a 1- or 3-doc compare-vocabulary ask gets the deterministic "select exactly two" answer (rag-skill-analysis.test.ts)). skills-analysis-whole-doc.test.ts also pins the what-changed handler shape + applies() (compare-shaped over exactly two docs) + splitCompareBudget + retrieveCompareWholeDocuments. skills-analysis-whole-doc.test.ts (handler-level: mode==='grounded-whole-doc' + no run(), applies() matrix EN+DE / off-topic / multi-doc / no-doc — registry wiring now in skills-analysis-registry.test.ts — and retrieveWholeDocument order + truncation + always-keep-first-chunk); rag-whole-doc-skill.test.ts (IPC-level over the real askDocuments: the model IS called with coverage.mode==='capped' + the fence + the whole transcript in the user turn, the refuse path with no model call, and an off-topic question keeping the relevance path with no capped coverage).

Compare-diff record — deterministic word-level diff is the compare backbone (2026-07-02). Problem it fixes. Every compare mode above hands the model two walls of text and asks it to eyeball the differences. That reliably MISSES a subtle change — a single deleted word deep in repetitive text — and lets the model dismiss low-salience/placeholder content ("Lorem ipsum") as "identical, nothing to compare". In the chat path it was compounded by truncation: at the default 4096-token window splitCompareBudget gives each doc ~half, so a ~2-page version pair had page 2 (where the change was) dropped as the capped tail — the model never saw it. Fix. A new pure module services/diff computes a Myers word-level diff (wordDiff, O((N+M)·D) with a DEFAULT_MAX_EDITS cutoff + a DEFAULT_MAX_WORDS guard, so it is near-linear for a real version pair and cheaply BAILS to null when the two diverge). isPreciseDiffUseful (the single routing policy) drives compare by the diff ONLY when the pair is similar (some shared content, changed fraction ≤ 0.5); a rewrite / too-large / too-different pair returns null and falls through to the existing modes. Both compare paths gained a diff-driven mode (d):

  • Chat (grounded-whole-doc-compare): retrieveCompareDiff reads BOTH docs whole (every chunk — no cap), diffs them, and feeds the model the exact changes + a redline via buildCompareDiffPrompt (never two whole-doc walls). Coverage is honest whole-document (the diff examined every chunk, so a page-2 change can't be truncated away); [Sn] citations are attributed to the chunks where the changes are. Identical docs are stated as such; the whole-doc-compare read is the fallback for a rewrite.
  • Doctask (runCompare, materialized "Comparison: A vs B.md"): runCompareByDiff short-circuits an identical pair to a model-free report, else materializes a deterministic redline (renderRedline, struck/added words with context) ABOVE a model interpretation of just the changes (compareDiffPrompt) — so the exact wording is always shown even if the interpretation editorializes. Modes (a)/(b)/(c) run only for a rewrite/too-large pair (which is why every prior compare test — all use maximally-dissimilar fixtures — is byte-unchanged). The redline direction follows document order (there is no reliable old/new signal); the doctask uses the user's explicit A/B selection order. SKILL.md was updated to treat a supplied diff as complete/exact and never dismiss a change as placeholder.
  • Tests. tests/unit/diff.test.ts (the algorithm: the one-word-deletion regression, insert/replace/ identical, the edit-cutoff → null, near-identical large texts, redline/model rendering); doctasks-compare.test.ts mode (d) block (one-word redline, identical short-circuit no model call, rewrite → fallback, the SK-2 PARTIAL note past DIFF_RENDER_MAX); rag-whole-doc-compare.test.ts (chat diff path: exact changes reach the model, identical, rewrite → whole-doc fallback).

§21 Geometry-aware PDF bank-statement extraction (Phase 31, 2026-06-23, D50–D58)

Folded from docs/pdf-geometry-extraction-plan.md (deleted at the Stage-1 closeout per the CLAUDE.md doc-lifecycle rule; the full working paper — every option, the Stage-2 design, the corroborating research — is in git history via git log --follow on that path). In-code comments cite the plan's anchors (§3.1 row/column reconstruction, §3.2 the non-breaking parseDate guarantee, §3.5 the completeness gate, D50–D58); read them against this record (the legend below maps them). Branch pdf-geometry-extraction.

The gap this closes. A real user analysed a German HypoVereinsbank statement with app:bank-statement and got zero transactions. Root cause was the PDF parser, not the regex tools: parsers/pdf.ts calls page.getTextContent() — whose items carry transform (x/y) + width — but keeps only str/hasEOL and concatenates in pdf.js reading order. A columnar statement (date · description · amount, year in the page header) therefore arrives as scrambled interleaved lines, so almost no row survives parseLine (which needs a full date token and the amount on one line), and bare DD.MM. per-row dates with the year only in the header are rejected by parseDate. The geometry needed to rebuild the columns was already fetched and thrown away.

Decisions (the ones that bind as built).

  • D50 — Hybrid, Node-native, no Python sidecar. Deterministic geometry-first extraction; a constrained local-LLM only as a future verified fallback. We already ship pdfjs-dist and the coordinates are in the object we iterate — the gap is discarded data, not a missing ecosystem, so a second runtime (pdfplumber/camelot) would buy column clustering we write in ~100 lines of TS at the cost of bundle size / code-signing / a second binary to verify. No new runtime dependency.
  • D51 — A layout MODE of the existing parser, reached through the existing re-parse seam — not a new standalone reader. A standalone reader taking "the original PDF path" cannot work in an encrypted workspace (no plaintext path; the bytes exist only as a transient extractDocumentPreview decrypts and shreds). Threading a layout flag through ParseContext → PdfParser.parse() reuses the decrypt/OCR/shred/page-cap machinery and keeps the R5 relevance path unchanged.
  • D52 — Stage 1 first; ship + measure; the LLM is gated. Stage 2 (the constrained-LLM fallback) lands ONLY if Stage-1 deterministic recall on the local-only gold set proves below ~90%. Measure before building the expensive path. Not yet closed — see "Conditional future" below.
  • D53/D55 — (Stage 2, not built). Any future LLM row must carry a verbatim grounding_quote verified against the source then balance-reconciled (drop-on-failure, never guess); it needs grammar-constrained decoding plumbed through the llama-server HTTP sidecar. (Update: that plumbing has since shipped as RuntimeChatOptions.responseSchema — the D55 contract the bank categorizer, enricher, both locate passes, and the ingest extract pass (STR-1 §5.1) now ride; Stage 2 itself stays gated on D52's recall evidence.) Recorded for when D52 triggers it.
  • D54/D56 — Honesty + the completeness gate (the cardinal safety property). Never present an invented total, nor a partial/mis-read total dressed up as the statement total. A confident WRONG total (17 of 20 rows presented AS the whole) is worse than today's empty result. The only true proof a total is whole is the printed opening + Σamounts == closing; capturing those statement-level balances was explicit Stage-1 scope (we did not store them before).
    • D56-R (refinement, 2026-06-25) — three outcomes, not a boolean. The original boolean gate refused a total whenever either balance was absent, which conflated two very different cases and wrongly refused a perfectly honest sum on a balance-less "Umsätze" listing (the reported bug). assessCompleteness now returns complete (printed opening+closing tie out → present the VERIFIED total), contradicted (a printed balance the rows refute — a per-row mismatch, or opening+Σ ≠ closing → keep the honest refusal: a suspect read must never surface a number), or unverified (NO opening/closing to tie against AND nothing contradicting → present the figures under an explicit caveat: "a sum of the N rows I read, not a verified statement total"). The cardinal property is preserved exactly — it forbids a number the user could mistake for THE statement total from coming out of an incomplete read; a clearly-labelled "sum of the rows shown" is not such a number. A bounded transaction listing now trails every non-empty answer so the user can SEE the rows that were read.
  • D57 — The gold set is LOCAL-ONLY / gitignored. Real bank statements are user financial data (CLAUDE.md "never commit user data"); only aggregate metrics are committed, and every test fixture is synthetic (makeColumnarPdfPages), never a real statement or excerpt.
  • D58 — Layout mode is bank-statement ONLY. The invoice skill is label/line-scan based, so column-reconstructed text could shift its line composition — adopt layout there (if ever) only behind its own measurement. Redaction/preview/translate/compare/ingest never set layout. Amended by §42 P3 (invoice-hardening-2026-07-04): the invoice analysis handler now DOES re-extract once via readDocumentSegments(id, { layout: true }) on a glyph-soup verdict (text_quality:'suspect') — D58's own escape clause ("adopt layout there only behind its own measurement") was satisfied by the invoice-de-geometry-columns fixture. The scope of "bank-only" is now precisely: the run-bar / IPC extract path and every non-analysis skill never set layout; the one invoice geometry read is the analysis path's suspect retry.

Design as built (deterministic, offline, ZERO model calls).

  • ingestion/parsers/pdf-layout.ts — pure geometry reconstruction. clusterRows groups positioned words into visual rows by baseline y (tolerance band for jitter/superscripts), top-to- bottom, each row left-to-right. resolvePageAnchor resolves the page year and, from a fully-printed date, its month (first fully-printed DD.MM.YYYY, else a header-band 4-digit token with no month, else null → bare rows dropped unless the caller supplies a document-level fallback year/month). reconstructLine emits one clean <DD.MM.YYYY> <desc> <amount> [<balance>] per transaction row — the year resolved during reconstruction (§3.2: the token reaching the SHARED parseDate is already a full date, so parseDate — used by invoice + redaction — is untouched by construction). A row with no resolvable date / no amount / no description is dropped, never invented.

  • The booking-date COLUMN MODEL (detectDatumColumn/inDatumColumn, §3.1.3) — the precision fix (2026-06-23). The gold-set measurement found Stage 1 OVER-extracting the Raiffeisen "Mein ELBA" statement (26 real rows → 43): its Valuta/value-date column prints on a SECOND baseline that aligns with a row's second description line, and that continuation hides a foreign-currency reference amount (39,00 USD); reconstructLine saw a date (the Valuta) + a money token (the FX) and emitted a spurious transaction. detectDatumColumn clusters every date-token x into bands and picks the densest, leftmost band (the booking column prints one date per row, so it is densest; density- first guards against a stray header/period date further left defining a phantom column). A row qualifies as a transaction ONLY when its lead date sits in that band; an out-of-column date (Valuta, or a mid-line label date) is dropped — and the non-transaction RAW fallback (rowText) also drops out-of-column dates so a Valuta line can't be re-extracted by the date-leading parseLine.

  • The BALANCE-LABEL GUARD (isBalanceLabelLine, bank-statement.ts) — the other half of the fix. Raiffeisen prints opening/closing as Kontostand per <date> with the date IN the Datum column, so geometry alone can't reject it. 'kontostand per' belongs to BALANCE_LABELS, so extractTransactionRows SKIPS any such line — a summary is never counted as a transaction (it is read by extractStatementBalances instead). It is deliberately kept OUT of OPENING_LABELS / CLOSING_LABELS: the SAME label prints BOTH balances, so it cannot be split by label alone — it is disambiguated by DATE in extractStatementBalances (see the gate bullet, audit C-4). "Aktueller Kontostand" stays excluded (it restates the closing at the top and would corrupt the opening). This stops the double-count that broke the tie.

  • The completeness gate (D56 + the D56-R refinement). New extractStatementBalances (printed opening/closing, EN+DE labels incl. balance brought/carried forward, opening/closing balance, Anfangs-/Endsaldo, Kontostand per) feeds assessCompleteness, the three-outcome classifier (complete / contradicted / unverified).

    • Cent-exact tie (audit C-3, 2026-06-26). assessCompleteness sums and compares the opening + Σamounts == closing tie in integer cents (Math.round(amount*100)), not a float reduce. Every figure is exactly 2-dp, so the cent sum is exact and the tie is an exact integer test — float drift over thousands of rows can no longer push the difference past MONEY_EPS and flip a genuinely-tying statement to a false contradicted. Read-time only; nothing persisted changes.
    • Single-currency precondition (backend audit 2026-06-27, BL-2). The tie sums every amount into one figure against a single opening/closing pair, so assessCompleteness first returns 'unverified' when the rows span more than one currency (a cross-currency Σ is meaningless), and reconcileBalances reports a mixed-currency statement all-unknown — both mirroring summarizeCashflow's currencies.size === 1 guard. buildBankAnswer's mixed-currency branch (already gated on summary.currency → no single total) is unchanged, so the change only hardens the public predicates; the §10 record carries the full note. Also BL-1's value-date column fix lives in the line parser (parseLine, §10), distinct from the geometry booking-date column model below.
    • Kontostand per date disambiguation (audit C-4, 2026-06-26). Because the same label prints both balances, extractStatementBalances resolves it by DATE: with two distinct-dated Kontostand per lines the earliest is the opening and the latest is the closing; a single such line (no pair to bracket the period) is the closing only (opening undefined → the gate downgrades to an honest unverified labelled sum, never a false contradicted from reading opening == closing). Explicit Anfangs-/Endsaldo labels still win where both appear. This changes the persisted opening_balance/closing_balance on affected statements → BANK_EXTRACTOR_VERSION bumped 1 → 2 (stale v1/NULL statements re-extract via the A9 path on the next reuse).
    • Persistence & rendering. Balances persist additively on bank_statements (opening_balance/closing_balance, REAL, nullable, content-class — never logged/audited/exported). buildBankAnswer renders each outcome: complete → VERIFIED total + the proven-whole caveat; unverified → the SAME single-currency totals + categories under unverifiedCaveat (a labelled sum of the rows read — the no-balance "Umsätze" case, the reported bug); contradicted → skills.bankAnalysis.incompleteNoTotal (the honest refusal). Mixed-currency reports no-single-total (safe) regardless of outcome. A bounded transaction listing (transactionsHeading/transactionItem/transactionsMore, first 10 + "ask to export CSV") trails every non-empty answer. All strings are EN+DE.
  • Wiring (D51/D58). readDocumentSegments(id, {layout}) → extractDocumentPreview (now accepting layout + the maxPages cap, a DoS guard since per-page clustering is uncapped otherwise) → ParseContext.layout → PdfParser layout mode (scan-detection re-keyed on RAW text so an empty reconstruction is never mistaken for an image-only scan). The bank analysis handler sets layout:true; every other caller is byte-unchanged. getDocument is called with verbosity:0 (VerbosityLevel.ERRORS) so pdf.js's font-program WARNINGS — e.g. the Warning: TT: undefined function: 21 flood from a malformed embedded TrueType hint program — no longer spam the log; real errors still surface (a verbosity flag, offline-safe).

  • HVB "Umsätze" multi-baseline recovery (2026-06-25, the D56-R follow-up — pdf-layout.ts). A real HVB online "Umsätze" export exposed three Stage-1 parsing failures the gold set's German statements did not: the payee/purpose prints on CONTINUATION baselines below the booking row, the per-row currency code EUR polluted the description, and a debit's sign sat in a separate cell so a Lastschrift read POSITIVE. Three deterministic, offline fixes (zero model calls):

    • (A1) Multi-baseline row association. reconstructPage is now stateful: a booking row OPENS a transaction; a following dateless, money-LESS text row is a CONTINUATION whose payee/purpose text is appended to that transaction's description (bounded by MAX_CONTINUATION_ROWS=4); the transaction flushes on the next booking row, an intervening non-continuation row, or page end. This is the deferred "multi-baseline association" the over-extraction boundary called for — payees survive instead of being orphaned onto dropped dateless rows.
    • (A2) Currency-token class. A standalone ISO code / symbol is its own token class (kept out of the description); reconstructLine re-emits ONE currency code AFTER the amount, where the line parser still detects it. This also resolves the boundary-1 over-extraction: a phantom <date> EUR <balance> running-balance row now has an EMPTY description → dropped, while a genuine row whose payee wrapped is rescued by A1. The §21 objection to a bare "drop a currency-only description" guard (it silently dropped 8 genuine wrapped rows) no longer applies — A1 is what makes A2 safe: the genuine row's payee continuation makes its description non-empty; the phantom's does not.
    • (A3) Sign-column fold. A standalone +/- or Soll/Haben S/H marker is folded into the amount's sign (S/- → debit/negative, H/+ → credit/positive) ONLY when it is the AMOUNT column's own sign cell: at/right of the amount (within SIGN_ZONE_SLACK) AND nearer the amount than any later money column — so a marker printed beside the running BALANCE never flips the amount (review fix S3). Conservative by design: a dash FAR from the amount (a description dash) is NEVER read as a sign (so it can't flip a total) and a non-folded sign token is kept as description text rather than silently dropped (S2). Caveat (D57): the EXACT HVB sign encoding (separate cell vs a glued trailing minus pdf.js splits) must be confirmed on the real statement via the local gold-set harness; A3 handles the sign-column case without guessing at a mid-line dash. Until confirmed, an unusual sign layout still degrades to the honest gate (contradicted when balances are printed; an unverified labelled sum when they are not).

Gold-set result (local-only corpus, D57; 2026-06-24, measured under the original boolean gate). Three text-layer statements — a sanitized HVB transactions-only excerpt, a full Raiffeisen "Mein ELBA" statement, and an HVB "Umsätze" page — plus one image-only scan (below): micro recall 116.5% (99/85) —

100% because the HVB "Umsätze" page is OVER-extracted (next paragraph); macro recall 100%; figure-exact-match 100% (1/1 with printed balances); hallucinated / partial-total / model-calls all 0. Under the original gate, gate pass was 33% (1/3) because the two balance-less statements refused a total. Under the D56-R refinement (2026-06-25) those two now present an unverified labelled sum instead of refusing — so the harness reports the same one VERIFIED total (Raiffeisen) plus two unverified labelled sums, and the cardinal invariant is re-stated accordingly: no number is ever presented as the verified statement total from an incomplete or mis-counted set. The corpus must be re-measured locally (HILBERTRAUM_PDF_GOLDSET=1) to refresh these figures under the refined harness.

Local re-measurement (2026-06-25, post-Phase-32, refined harness). The full real HVB online "Umsätze" listing (Jan–Mar 2025, 45 transaction rows, NO printed opening/closing — the exact file behind the Phase-32 bug) was re-measured on its own: transaction recall 100% (45/45), over-extracted 0/1 (the old <date> <CUR> <balance> phantom rows are GONE — the A2 currency-token class + A1 multi-baseline recovery hold on the real encoding, not just the synthetic fixtures), the D56-R unverified labelled sum path (no printed balances), and hallucinated / partial-total / model-calls all 0. This confirms A1/A2/A3 on the real layout and that the boundary-1 over-extraction is resolved in the wild. (Only this one statement is present on the current machine; the broader 3-text + 1-scan aggregate above still awaits a re-measure where that corpus lives.)

Known Stage-1 boundaries (2026-06-24, boundary 1 substantially RESOLVED 2026-06-25) — all SAFE (no wrong total is ever shown), residual fixes scoped:

  • Per-row running-balance OVER-extraction — RESOLVED for the <date> <CUR> <balance> shape (A1+A2), 2026-06-25. Some statements (the HVB "Umsätze" export) print a separate running-balance row BETWEEN transactions shaped <date> <CUR> <balance> with the date in the booking-date column. Geometry rebuilt it, and because its only non-date/non-money token was the bare currency code, parseLine read that as the description and emitted a phantom transaction (14 real rows → 28). The currency-token class (A2) now keeps the bare EUR out of the description, so the phantom row's description is EMPTY → dropped, while a genuine row whose payee wrapped onto a continuation baseline is RESCUED by multi-baseline association (A1) (its description is non-empty). The earlier objection — that a naive "drop a currency-only description" guard silently dropped 8 genuine wrapped rows — is exactly what A1 fixes, so A2 is now safe. Pinned end-to-end through real pdf.js (pdf-bank-layout.test.ts case (i): phantom rows dropped, the genuine rows tie out → the gate now PRESENTS the verified total; case (j): payees recovered from continuation baselines). The 2026-06-24 geometry probe still holds — the balance and amount are right-aligned in ONE numeric column, so an x-band "money-column model" could NOT have separated them; the token-class + association fix did. Residual (safe, gate-guarded): a genuine NO-payee row whose booking line is a bare <date> <CUR> <amount> with no continuation below is indistinguishable from a phantom and is also dropped — a recall loss, never a wrong total (the gate downgrades). A statement that carries the running balance INLINE on the booking row (<date> <desc> <amount> <balance>) was never this boundary and is unaffected.
  • Image-only / "blacked-out" statements. A user who blacks out or scans a statement can flatten it to a full-page IMAGE with no text layer. Stage 1 reads the text layer, so PdfParser raises the scan-detected error and nothing is extracted → the safe empty/downgrade (0 rows, no total, 0 model calls — a blacked statement never yields a confident wrong total). Recovering it is the OCR path's job (§ "Scanned-PDF / photo OCR"), out of Stage-1 scope (plan §7). The gold-set harness detects the scan throw, excludes such statements from the recall/gate aggregates, and safety-asserts the empty outcome instead.
  • Split-amount items (identified by the pre-merge audit, 2026-06-24; pinned by tests). When a PDF producer renders one amount as TWO adjacent text items (e.g. 2.000 + ,00, a kerning/positioning gap pdf.js surfaces as separate TextItems), neither fragment classifies as money (2.000 is text, ,00 is text; note 1.234 even back-classifies as a date), so the row carries no amount and is dropped — the real transaction silently vanishes (a recall loss). It is safe in the original sense when the statement prints opening/closing (the missing row breaks the opening + Σ == closing tie → contradicted → refusal, the pinned test path); on a balance-LESS statement, D56-R presents an unverified labelled sum that is silently UNDER-counted by the dropped row — honest per its caveat ("a sum of the rows I read"), but no longer a refusal (same D56-R tradeoff as boundary 1). The scoped fix is an x-adjacency money re-merge (merge neighbouring tokens whose concatenation parses as money and whose x-gap is sub-column), deferred with the money-column model. Pinned by pdf-layout.test.ts (the split drops the row; the same amount as one token reconstructs) + an end-to-end pdf-bank-layout.test.ts case (real pdf.js → safe downgrade). Two related tuning-constant boundaries are pinned alongside it: clusterRows anchors a row on its FIRST baseline (so >DEFAULT_ROW_TOLERANCE=3 pt of cumulative jitter splits a row and loses its amount), and a Datum/Valuta pair closer than DEFAULT_COLUMN_GAP=12 pt MERGES into one band (a Valuta date can then qualify a spurious row — same gate-safe over-extraction class as boundary 1).

Conditional future — Stage 2 is NOT built, but is EXPECTED to be needed eventually. It is not a planned next step (it lands only on evidence, per D52), but the expectation is that it probably will be warranted once the corpus broadens: today's gold set is still narrow (three text statements + one image-only scan, D57), and real statement layouts vary wildly (no-printed-balance statements that the completeness gate can only downgrade, ruled/borderless tables, multi-column or rotated layouts, OCR'd scans). Deterministic geometry will almost certainly miss some of them, and those are exactly the residual hard subset Stage 2 exists to cover. So treat Stage 2 as a probable future need, gated — not abandoned: it lands only if D52's breadth evidence (more banks/layouts — Sparkasse/ING/DKB + invoices) shows Stage-1 deterministic recall below ~90% on a layout the completeness gate can't honestly downgrade. The discipline is still measure-then-build (don't pay for the LLM path until a real layout proves Stage 1 insufficient); its D55 prerequisite (grammar-constrained decoding plumbed through llama-server) has since shipped (responseSchema, used by the categorizer/locate/extract surfaces), so the remaining Stage-2 work is the grounding-quote + reconciliation machinery itself. Until then Stage 1 is the shipped extractor for the verified layouts; Stage 2 remains deferred + unapproved, but the recommendation is to expect it and re-run the gold-set harness on a broader corpus to trigger it.

Tests. tests/unit/pdf-layout.test.ts (clustering, toFullDate year resolution proving parseDate is untouched, detectDatumColumn density/leftmost/tie, out-of-column-date rejection, value-date drop, balance-line preservation, fallback-year, the REL-10 single-pass header fold over a 500k-fragment page, a no-date page emitted raw). tests/integration/pdf-bank-layout.test.ts (SYNTHETIC columnar PDFs via makeColumnarPdfPages: text-mode loses every row while layout-mode recovers them + the correct total + honest coverage + citations + 0 model calls; a non-tying balance MUST downgrade; the Raiffeisen Valuta/second-baseline + Kontostand per regression pins the column model; and the Phase-31 breadth set — English Balance brought/carried forward gate-pass, an English value- date second baseline rejected, an English running-balance-only downgrade, a multi-line wrapped description). Adversarial geometry through real pdf.js (audit M3 CI-realism, 2026-06-24): because every fixture above encodes ideal geometry (one TextItem per cell, identical per-row baselines, wide column gaps) a regression that only bites on a real, messy TextItem distribution could pass npm test; a dedicated pdf-bank-layout.test.ts describe block now drives the messiness through the REAL pdf.js path — sub-tolerance baseline jitter (still one row), over-tolerance jitter (amount splits off → row dropped → gate downgrades), a tight (<12 pt) Datum/Valuta gap (columns merge → over-extraction → safe downgrade), the shared-column running-balance shape of former boundary 1 (case (i): the phantom rows are now DROPPED by A2 and the genuine rows tie out → the gate presents the verified total), and the HVB "Umsätze" multi-baseline recovery (case (j): payees merged from continuation baselines, EUR stripped, a Lastschrift signed negative → the honest unverified labelled sum). pdf-layout.test.ts adds the HVB multi-baseline recovery block (currency strip, sign-column fold, the conservative far-dash no-fold, association + phantom-drop). The local-only gold set remains the real-distribution gate; these pin the documented boundaries + the recovery in CI. tests/real-data/pdf-goldset.realdata.test.ts is the LOCAL-ONLY, gitignored, gated (HILBERTRAUM_PDF_GOLDSET=1) gold-set harness — aggregate metrics only, 0 model calls, skipped in npm test.

§-anchor legend (historical plan citations)

The wave's plan files were folded into this record (S2–S12 into §1–§12; S13 into §18) and security-model.md, but in-code comments and the kept docs still cite the original plans' section numbers (skills plan §N, skills-s13-plan.md §N / §2.1 / D1–D6, §22-*). Those numbers were never renumbered; this legend keeps them resolvable (the doc-lifecycle "stable anchors" intent) without churning ~150 comments. Read a historical §N as:

Historical anchor Meaning Now lives in
§9.2 Import safe-extractor defences §4 + security-model "Skill-import defences"
§9.3 Collision / version / downgrade policy §4
§9.4 Delete = app-level ref-clear sweep §4
§9.5 Content-class data excluded from every export §10 + security-model (Tier-2 ceiling)
§10 / §10.1–§10.4 Selection, prompt placement, suggestion heuristic §5 + §6
§11 / §11.2 Fenced-skill prompt integration §5
§12 / §12.1 / §12.2 Tier-2 tool gate (schema, validate→run→validate, confirm) §7 + security-model "Skill tool ceiling (Tier-2)"
§13 (plan) Bank specifics kept out of the generic infra §8 (note: §13 in THIS record is the post-S12 follow-ups above)
§14 The untrusted-skill-as-input threat model + structural ceilings §2 + §7 + §12; security-model "Skill tool ceiling"
§15 / §16 Renderer surfaces / IPC surface §9 + §11
§18.x Phase/sub-phase breakdown (historical) this record's phase tags (S2–S12)
skills-s13-plan.md §2.1 / D1–D6 Ratified auto-fire contract (precision bar, threshold-3, opt-in, app-only, no-override, schema) §18
skills-s13-plan.md §3 / §4 / §5 Eval harness + corpus (S13a) / auto-fire mechanics (S13b) / surprise-mitigation UX (S13c) §18
§22-A1/A5/A6 One skill-resolution path; stamp only when placed; fence pre-sized §5
§22-A2 Net-new member-by-member safe zip extractor — a .skill.zip never routes through extractWithTar; zip-bomb enforced on actual inflated bytes §4 + security-model "Skill-import defences"
§22-C2 Selector reads triggers from the cache, never unpacks a blob §6
§22-C3/C4 No FK into skills (app-level sweep); scope resolved main-side §4 + §9
§22-D1/D3 Honesty posture (drop, don't invent); suggestion is an inert offer §6 + §8
§22-E2 Nested-archive defence is magic-byte sniffing, not extension allowlisting (a zip renamed .csv is caught) §4 + security-model "Skill-import defences"
§22-E4 assertCommercialDrive gate mirrored in both provisioning scripts services/commercial-drive.ts + scripts/build-commercial-drive.{ps1,sh} (parity pinned by skills-bank-statement.test.ts)
§22-H2 Fence placement — the RAG skill fence rides in the user turn with the excerpts, never system (plain chat: app-bracketed) §5 + rag-design.md §8 "Grounded prompt"
§22-M1 Content-class rule — ids/counts only; no content in log/audit/IPC §2 (the consolidated sentinel guard)
§22-M2 App-skill integrity by location, not signature (accepted residual) §12 + security-model
§22-M4 v1 permissions are a display summary; nothing executes §1 (DS6)
pdf-geometry-extraction-plan.md §3.1 / §3.1.3 Row/column reconstruction; the booking-date column model §21 (pdf-layout.ts)
pdf-geometry-extraction-plan.md §3.2 The non-breaking parseDate guarantee (year resolved in reconstruction) §21
pdf-geometry-extraction-plan.md §3.5 / D56 The opening/closing-balance completeness gate (no partial totals) §21
pdf-geometry-extraction-plan.md D50–D58 Stage-1 architecture decisions (geometry-first; Stage 2 conditional) §21
skills-tools-audit-2026-06-26 D-1…T-1 / C-* / P-* / U-* / S-* / PC-1 / X-* / A-1 / R-1 / R-2 Skills & Tools audit findings (7 personas, 11 phases, no CRITICAL/HIGH) §23 close-out ledger → the per-finding § noted there

§22 Bank-statement LLM categorizer (Phase 33, 2026-06-25, D55/D26)

The deterministic Stage-1 extractor finally recovers real payees/descriptions (§21 multi-baseline recovery), so there is usable text to categorize. Categorization is the FIRST place a local LLM assigns meaning to bank data in this app — defensible under the honesty posture for one structural reason: a category is not a figure. A mislabel only shifts the per-category breakdown; it never moves the verified statement total or the D56 completeness gate (which read the signed amounts, never the labels). So — unlike a future Stage-2 figure extraction (D53/D55 grounding_quote) — no figure verification is needed. The constraints that DO hold:

  • Offline only. A local llama.cpp sidecar, never a hosted API (CLAUDE.md §0).
  • Fixed set, grammar-constrained. The reply is constrained to a json_schema whose category field is an enum of a fixed EN taxonomy (CATEGORIZER_CATEGORIES: Groceries/Dining/Transport/Utilities/ Rent/Insurance/Subscriptions/Health/Shopping/Income/Transfer/Fees/Cash/Tax/Uncategorized) — the model cannot emit an off-list label (the D55 plumbing: RuntimeChatOptions.responseSchema → llama-server response_format:{type:'json_schema',strict:true}). DE glosses ride in the prompt only.
  • Drop-to-Uncategorized. Any invalid / out-of-range / unparseable output drops to Uncategorized (a whole batch drops on a parse failure). Never an invented category. The mock runtime (which ignores responseSchema) exercises exactly this path in CI. Batch robustness (audit L-1/L-2, Phase 2): the per-batch output-token budget batchMaxTokens is now length-aware (a per-row description-length allowance) so a verbose batch is far less likely to truncate; an unparseable reply is retried once before the batch drops (a transient truncation gets a second chance); and the streamed reply is bounded by a generous char cap (batchMaxTokens * 8) so a looping local runtime that ignores maxTokens can't grow text unbounded — past the cap the batch is dropped (not retried). Drop-to-Uncategorized remains the honest final fallback.
  • Model-OPTIONAL. With no model loaded the module degrades to the deterministic rule pass (categorizeRow). Confident description-rule matches (Fees/Income/Transfer/Cash) are a PRE-FILTER that skips the model; the rest go to the model in batches of CATEGORIZER_BATCH_SIZE (=20). Both the PRE-FILTER (prefilterCategory) and the deterministic categorizeRow match on the same shared Unicode WORD-boundary tester (wordIncludes, moved into tools/money.ts at audit C-1, Phase 2 — review fix P10 originally hardened only the pre-filter), so a coincidental substring (fee⊂coffee, atm⊂atmosphere, lohn⊂mühlohn) never makes a confident wrong match on EITHER path, and the two paths agree on every description rule. (Trade-off: a German COMPOUND that merely contains a keyword — Kontoführungsgebühr — no longer rule-matches deterministically; it goes to the model, exactly as the pre-filter already did.)
  • Model-assisted label. The breakdown is labelled model-assisted from the authoritative persisted flag bank_statements.categorized_by_model (=1 whenever the LLM was consulted), written by the categorizer doctask (review fix A8). The earlier "any persisted category OUTSIDE the deterministic rule set" heuristic is kept ONLY as a back-compat fallback for statements categorized before the flag existed — on its own it false-negatives when the model emits only in-rule-set labels (Income/Transfer/Fees/Cash). categorizer.ts + doctasks/manager.ts + analysis/bank-statement.ts.
  • Localized display, canonical-English identity. The PERSISTED category (bank_categories.name) and the enum stay canonical English (so the schema, persistence, and the model-assisted signal are locale-stable); the breakdown DISPLAY label is localized (EN + DE, skills.bankCategory.* → categoryLabel). An unknown name (a future user category) falls back to its raw identifier.

Decisions as built:

  • D26 — the categorizer is a DocTaskManager kind ('categorize'), NOT a model call on the skill-run seam. The ModelSlotArbiter only mediates chat ↔ a yielding build; the chat↔task one-job-at-a-time exclusion (D26) lives in the DocTaskManager (chat checks hasActiveTask(), tasks check isChatStreaming()); the skill-run SkillRunController is a SEPARATE lane that does not observe the D26 model-slot exclusion. A model call on runCategorization could let two chatStream calls hit the one llama-server at once. The doctask lane gives D26 exclusion + progress + cancel + getRuntime() for free. 'categorize' is the one model-OPTIONAL kind (it skips startDocTask's runtime gate; a null runtime ⇒ deterministic). DB-write safety across these lanes (audit PC-1, Phase 9): the lanes were mutually unaware of each other's WRITES — now every write-capable section is serialized PER DOCUMENT by withDocumentLock (services/skills/doc-lock.ts), so a chat re-extract DELETE can no longer race a button run / a categorize on the same statement (see §9). That doc lock is independent of and finer than the D26 model-slot exclusion — it guards table writes, not the llama-server.
  • Button wiring — wrap the doctask in the skill-run shell. The existing "Kategorisieren" button keeps its SkillRunController UX: the categorize_transactions runner ENQUEUES a 'categorize' doctask and MIRRORS its progress/cancel into the run bar (tool-runs.ts runCategorizeViaDocTask). The real job — and the model call — runs in the doctask lane, so D26 holds; the shell is a thin status mirror.
  • Auto-extract (the (D) ordering fix). runCategorize AUTO-EXTRACTS the statement first when none exists (the "categorize before extract" needsExtraction failure is gone). Persistence of category_id is atomic (BEGIN/COMMIT, no partial annotations survive); the categories are seeded by the SHARED ensureBuiltinCategories (now the union of the rule set + the LLM taxonomy).
  • Explicit categorize offer after extraction (Q2; audit U-2, Phase 6; DECISION = explicit offer). A read-only extract_transactions BUTTON click does NOT start the LLM categorizer on its own. The earlier Phase-33 behaviour silently enqueued a background 'categorize' doctask here — invisible in the run bar (it lived in the doctask lane), a no-surprises violation for a calm, privacy-posture app (a deterministic, advertised read-only action triggering an un-asked model pass). Now, after a successful rows>0 extract, the run-bar result row offers a one-tap "Categorize transactions" follow-up; the model invocation is user-initiated. The offer targets the SAME document the extract ran on: its id is remembered renderer-side (ChatScreen runTargetId, mirroring the Phase-5 runTargetName) and rides back through the existing onRunTool('categorize_transactions', false, documentId) → runCategorizeViaDocTask path (D26 lane unchanged). The offer copy is content-free (chat.skill.run.categorizeOffer, EN+DE); the run state / IPC stay ids/counts-only (no documentId in SkillRunState). The audit payload is unchanged ({skillId, toolName, documentCount}) — and because the categorize is no longer auto-fired, an extract click no longer emits a categorize run's audit trio unless the user taps the follow-up. The chat analysis path is unaffected (it never went through that runner), and the deterministic 0-model chat breakdown still works with NO prior categorize.
  • Read-back stays 0-model-calls (Q3 routed feedback). analysis/bank-statement.ts REUSES the latest statement when it is FRESH (re-extraction is deterministic, so reuse avoids a duplicate AND preserves the doctask's persisted categories); a single LEFT-JOINed read (loadStatementRowsWithCategories) returns each row paired with its PERSISTED category (else categorizeRow), so the breakdown alignment is structural. The model call happens ONLY in the doctask. After a categorize run completes the renderer ROUTES the standard breakdown question into the transcript, so the model-assisted breakdown appears as a normal chat answer (ChatScreen → the analysis handler, still 0 model calls).
  • Consistent breakdown framing (audit C-2, Phase 2; DECISION = option A). Two engines categorize the same statement by entry point: the chat breakdown runs the deterministic rule pass when nothing is categorized yet (0 model calls — keeping THIS path 0-model is the load-bearing invariant), while the "Categorize" button + the post-extract categorize offer (Q2/U-2) use the LLM doctask's richer taxonomy. Rather than pull a model call onto the chat path (option B — bigger blast radius, crosses into the doctask lane), the chat answer now labels the rule-based breakdown honestly: when modelAssisted === false it appends skills.bankAnalysis.categoryRuleBased ("a quick rule-based grouping … run the Categorize button for a richer, model-assisted breakdown"), the mirror of the model-assisted note. So the two entry points are no longer SILENTLY divergent, and the 0-model-call chat contract is preserved.
  • Stale-statement re-extraction (A9; Phase 31–33 follow-up). Reuse is gated on FRESHNESS: bank_statements.extractor_version is stamped with BANK_EXTRACTOR_VERSION (in tools/bank-statement.ts) on every extraction; a statement whose stored version is NULL (legacy) or < current is STALE (isBankStatementStale). Both reuse paths — the analysis read-back AND the categorize doctask — re-extract a stale statement with replaceExisting, which DELETES the document's prior statements (+ their transactions/corrections, FK order) in the SAME persist transaction before inserting the fresh one. So a since-fixed parser bug never keeps serving mis-signed / lost-payee rows (the silent-stale risk is sharpest for no-balance "Umsätze" statements, which present an unverified sum the D56 gate can't catch), and re-extraction never accumulates duplicates. The old per-row categories go with the replaced statement (the rows changed because the parser changed them — recompute is the honest move, done by the breakdown's deterministic pass / the next categorize run); model categorization re-runs on the next Kategorisieren click / the post-extract categorize offer. The single shared latestBankStatementId helper (run.ts) keeps the load-bearing created_at DESC, id DESC tie-break identical across all three call sites. Bump BANK_EXTRACTOR_VERSION whenever the line parser OR pdf-layout.ts reconstruction changes output for the same input. It is now at 2 (1 → 2 at audit C-4, 2026-06-26: the Kontostand per date disambiguation changes the persisted opening_balance/closing_balance on Raiffeisen statements — so v1 statements re-extract via this path).

Tests: skills-categorizer.test.ts (taxonomy/enum, prefilter, model path, off-list/out-of-range drop, unparseable-batch drop, batching, no-runtime fallback; Phase 2: categorizeRow agrees with the prefilter on coincidental substrings, L-1 truncation-retry-then-succeed + retry-once-then-drop, L-2 char-cap drop; Phase 11 (audit T-1): an empty input makes NO model call and returns an empty result (modelAssisted:false), and the EXACT batch boundary — exactly CATEGORIZER_BATCH_SIZE(20) model-bound rows is ONE call, 21 is two, a 1-row batch is one); skills-bank-statement-tool.test.ts (Phase 2: categorizeRow word-boundary matching — coffee≠Fees, compound Kontoführungsgebühr→Spending; Phase 3: the cent-exact many-row drift case stays complete (C-3), the Kontostand per dated pair maps opening/closing and a lone line is closing-only → unverified (C-4), BANK_EXTRACTOR_VERSION === 2); skills-run.test.ts (Phase 3: a v1 statement is detected stale at v2, a freshly-stamped one is not); doctasks-categorize.test.ts (model path persists, deterministic fallback persists, auto-extract-then-categorize, A9 stale-statement re-extract + replace); skills-tool-run-ipc.test.ts (Phase 6: an extract with rows enqueues NO categorize doctask and leaves the rows uncategorized — no hidden model run, U-2); SkillRunBar.test.tsx (Phase 6: the result-row "Categorize transactions" offer renders only after a successful rows>0 extract and fires the categorize path with the remembered id; absent for a 0-row / non-extract / non-done run); skills-analysis-bank.test.ts (persisted model categories surface + the model-assisted label; Phase 2: the rule-based note when modelAssisted is false, absent when model-assisted; no duplicate statement on re-ask; A9 stale statement re-extracted+replaced, fresh statement reused).

§23 Skills & Tools audit (2026-06-26) — remediation close-out

A seven-persona audit (architecture, security/privacy, performance, LLM/prompt, UX, docs, testing) swept the whole Skills & Tools surface — selection → the Tier-2 gate → the run seam → the bank / invoice / redaction tools → the LLM categorizer → the .skill.zip installer. No CRITICAL / HIGH. All 11 remediation phases are landed on branch skills-tools-audit-2026-06-26. The standalone report (docs/skills-tools-audit-2026-06-26.md) was deleted under the CLAUDE.md doc-lifecycle rule once fully implemented — its design records were folded into the §§ below as each phase shipped, and the full original report stays recoverable in git history (the parent of the Phase-11 close-out commit, bd2acdb), mirroring the 2026-06-13 audit closeout. This ledger is the durable index — read a code comment's audit <ID> citation through it:

Finding(s) Phase Disposition (one line) Record
D-1, D-2 1 docs truth-up: eight bundled skills; the linear globMatches matcher (no dead globToRegExp cap) §12/§13; DS17
C-1, C-2, L-1, L-2 2 shared word-boundary wordIncludes; rule-based breakdown labels itself; retry-once + char-cap on a batch §8/§22
C-3, C-4 3 cent-exact completeness sum; Kontostand per date disambiguation (BANK_EXTRACTOR_VERSION → 2) §21
P-1, P-2 4 load the rows ONCE; the seams return their validated output for in-process reuse §8/§19
U-1 5 multi-doc target ids ride the IPC, render-side maps ids→names; the chosen id is validated main-side §9/§19
U-2 6 a read-only extract no longer auto-runs the model; an explicit one-tap "Categorize" follow-up instead §9/§22 (D26)
U-3 7 a quiet inline "Suggested: …" hint on the closed picker for a high-confidence offer §6
S-1, S-2 8 bound the inflate INPUT; re-validate + reject a duplicate stripped path §4; security-model
PC-1 9 per-document withDocumentLock serializes the three write lanes (no cross-lane race) §9/§13/§22
X-1, X-2, A-1 10 one documentsInScope helper; count_selected_documents kept as a test-only canary; a SKILL.md⇔TS parity test §7/§19
T-1, R-1, R-2 11 test backfill + the two residuals (below) this section

Phase 11 (T-1 / R-1 / R-2) — as built:

  • T-1 — backfilled only the genuinely-missing edges (no padding). Two categorizer edges were ADDED to skills-categorizer.test.ts: an empty input makes NO model call and returns an empty result (modelAssisted:false), and the exact batch boundary — exactly CATEGORIZER_BATCH_SIZE(20) model-bound rows is ONE model call, 21 is two, a 1-row batch is one. Teeth-verified (a transient batch-step off-by-one made the boundary test fail; reverted). The other clustered T-1 gaps were verified already covered by the earlier phases' own tests and were NOT re-added: cross-lane concurrency PC-1 (skills-concurrency.test.ts + skills-doc-lock.test.ts, Phase 9), multi-doc docIds[0]/chooser + the no-title SkillRunState privacy sentinel + the U-2 no-auto-categorize behaviour (skills-tool-run-ipc.test.ts, Phases 5/6), the whole-batch-drop / retry-once / char-cap / 21 rows ⇒ 2 calls categorizer cases (skills-categorizer.test.ts, Phase 2), and the C-3/C-4 completeness numerics (skills-bank-statement-tool.test.ts, Phase 3).
  • R-1 — auto-fire corpus is intentionally narrow (no rows invented). document-redaction is STILL the ONLY app skill opting into triggers.autoFire, and the eval gate already covers it: the harness's APP_SKILL_IDS and the 33-turn tests/fixtures/skill-triggers/corpus.json (four document-redaction turns among them) drive the S13b gate (fired-wrong == 0 AND precision ≥ 0.95). Per the plan's explicit fallback, since NO new skill opts in, no corpus rows were added — the corpus is deliberately scoped to the auto-fire surface and the eval gate is unchanged. (See §18 for the auto-fire contract.)
  • R-2 — run-surface eyeball deferred (re-affirmed, surfaced for opt-in). The live SkillRunBar Playwright walk (a walk-skills-runbar.mjs, to be modelled on apps/desktop/scripts/walk-skills-composer.mjs) needs a GUI session a test harness cannot drive; every visual state stays unit-covered by SkillRunBar.test.tsx (offer / running / result / confirm-modal, EN+DE). The honest deferral (the documented default since Phase 5) is re-affirmed — no fake captures; the owner may run the capture on a GUI machine. Recipe essentials (full version: git show f549ce8:docs/design-review/skills-s12/README.md — the docs/design-review/ capture staging folder was deleted 2026-07-12 per the delete-captures-after-review convention; the walk scripts mkdirSync it back on demand): (1) seed ONE indexed statement whose lines match the deterministic parser (<ISO-date> <description> <amount with 2 minor digits> + a currency marker on the page) — listRunnableTools returns [] without an indexed in-scope document; (2) drive extract → the busy row → each tool's result row, then the export tool to reach the ConfirmDialog; (3) stub dialog.showSaveDialog so the walk never blocks on an OS dialog; capture every state in both themes × EN/DE; Playwright stays an ad-hoc dev tool (--no-save, never a committed dependency).

Posture held across all 11 phases (load-bearing): offline / no telemetry; the content class (skill bodies, the draft question, extracted figures, redacted text, document text and titles/filenames) is never logged / audited / echoed — only ids/counts cross the IPC/audit boundary; the audit payload stays {skillId, toolName, documentCount}; schema changes are additive; the Tier-2 gate gained no new DB/FS/net capability; i18n parity is compile-enforced (LLM prompts stay English).

Backend-audit 2026-06-27 follow-ups on this surface (Phase 6 — SEC-1 / API-3). A later backend audit re-examined the same skills surface and landed two dispositions, recorded in §7 (full rationale in security-model.md "Skill tool ceiling (Tier-2)" → SEC-1): SEC-1 — the run/runnable surface now gates on source via skillCanRunTools(skill) (source === 'app'), so Tier-2 tools run for built-in app skills only; a user-imported kind:'tool' skill may declare allowedTools (kept for a future per-tool grant UI) but runs none until that UI exists — enforced at runnableToolNames (the choke point) and re-checked at startSkillRun (forged-IPC defense, content- free refusal). API-3 — documentCount stays the v1 constant 1 (single-document tools) with an in-code TODO to make it a real count if a multi-document tool lands. The §22 posture above is unchanged (no new capability; audit payload still {skillId, toolName, documentCount}).

§24 Backend audit (2026-06-27) — remediation close-out

A multi-persona read-only backend audit (report audits/backend-audit-2026-06-27.md, HEAD c26d361) swept the Electron main process + shared/preload of apps/desktop — crypto/vault, the data layer, the full IPC surface, ingestion/parsers, RAG/analysis, doctasks/skills, runtime/downloads, OCR/transcriber/vision, embeddings/reranker — focusing on what the five prior rounds did not cover. 2 High · 9 Medium · 14 Low · 8 Info; no Critical, no remote-exploitable issue (offline by construction). All 8 remediation phases are landed on branch backend-audit-2026-06-27-fixes. Both the working-paper plan (docs/backend-audit-2026-06-27-remediation-plan.md) and the audit report (audits/backend-audit-2026-06-27.md) were deleted under the CLAUDE.md doc-lifecycle rule once every finding was dispositioned — each phase's decisions were folded into the topic-doc §§ as it landed, and the report's lasting content (the per-finding dispositions, the verified-clean inventory, and the accepted residuals) lives in this section. Both files stay recoverable in git history. This ledger is the durable index — resolve a code comment's audit <ID> citation through it:

Finding(s) Phase Disposition (one line) Record
DATA-1 (High), DOC-1, MAINT-1, TEST-1 1 atomic-txn deleteDocument: ordered purgeDocumentDerivatives → purgeSkillDataForDocument (bank/invoice rows) before the row delete, stored copy shredded after commit; fresh schemas also declare full-chain ON DELETE CASCADE; teeth-verified extract-then-delete test arch §10; known-lim §39–46; rag-design deleteDocument row
BL-1 (High), TEST-2 2 shared money.ts splitLeadingDates strips the whole leading date run (booking + value date) before the money scan in parseLine/parseLineItem — value-date column no longer dropped/mis-valued arch §10 (line parser) / §21 (layout)
BL-2 (Med), TEST-6 2 assessCompleteness/reconcileBalances return unverified unless single-currency (mirrors summarizeCashflow) arch §10
BL-3 (Low) 2 categoryTotals keyed by (category, currency) arch §10
REL-1 (Med), TEST-4 3 AbortSignal threaded ParseContext→AudioParser→transcribe + whisper idle watchdog; per-job abort arch "Audio transcription"
REL-2 (Med) 3 per-page OCR Promise.race timeout + terminate-and-recreate worker on timeout/abort arch "Scanned-PDF / photo OCR"
REL-3 (Med) 3 dictation single-flight guard + wall-clock abort arch "Voice dictation"
REL-6 (Low) 3 TranscribeOptions.workDir now required — no OS-tmpdir fallback outside the crash sweep arch "Audio transcription"
REL-5 (Med), MAINT-4 4 one parseWithLimits(parser, source, ctx, limits) decorator across every parse entry point; preview gains maxPages/maxInflatedBytes/wall-clock timeout (ingest byte-for-byte unchanged) rag-design §2 (cap stack); arch "Document ingestion"
REL-9 (Low) 4 expandPaths symlink-cycle guard via recursion-path realpathSync Set arch "Document ingestion"
REL-10 (Low) 4 resolvePageAnchor (then resolvePageYear) single-pass y-range fold (no Math.max(...spread)) arch §21
BL-5 (Info) 4 ragged-CSV overflow cells kept under colN: (no silent truncation) rag-design §2
RAG-1 (Med), TEST-3 5 coverageWhole gated on fullyChunked && scannedChunks >= totalChunks — a multi-doc partial scope falls to "sections scanned" rag-design §14.5
EMB-1 (Med), MAINT-2, TEST-5 5 reranker drops naive truncateWords for the shared CJK/Thai-aware truncateToApproxTokens, per-field caps clamped to the context budget (no silent 500 on space-less input) rag-design §12.4
DATA-2 (Low), EMB-2, TEST-7 5 truncated-blob guard moved into decodeVector (Float32Array | null) so all call sites skip a corrupt row uniformly rag-design §12.4
EMB-4 (Info), MAINT-5 5 module-load LE-endianness assert in codec.ts rag-design §12.4
SEC-1 (Med), DOC-5, TEST-8 6 DECISION: gate Tier-2 tools to APP skills — skillCanRunTools(skill) = source === 'app' at runnableToolNames + re-check at startSkillRun; a user kind:tool skill keeps declared allowedTools (future per-tool grant UI) but runs none arch §7/§23; security-model "Skill tool ceiling (Tier-2)"
API-3 (Info) 6 documentCount left the v1 constant 1 + in-code TODO (no behaviour change) arch §7/§23
SEC-2 (Low) 7 installPermissionCheckHandler mirrors the request handler via one shared grantsMicrophone predicate security-model
SEC-3 (Low) 7 installNavigationGuard attaches one deny-predicate to both will-navigate + will-redirect (main shell-only; OCR window deny-all) security-model
SEC-6 (Low) 7 validateAnalyzeRequest rejects a claimed png/jpeg with a null pixel count (decodeFailed) instead of byte-cap-only security-model; arch (vision)
REL-4 (Med) 7 OCR page PNG byte cap (assertPageWithinByteCap, OCR_MAX_PAGE_PNG_BYTES = 96 MiB) arch "Scanned-PDF / photo OCR"
REL-7 (Low) 7 windowsHide: true on the sidecar + GPU-probe spawns arch (runtime)
REL-8 (Low) 7 child.unref() on the GPU probe so a wedged probe can't delay app quit arch (runtime)
API-1 (Low) 8 requireUnlocked() preamble (new main.chat.locked i18n key) on every DB-touching chat handler registerChatIpc — parity w/ docs/collections/doctasks
DATA-3 (Info), MAINT-3 8 DECISION: row-count eviction — evictSummaryCache deletes oldest rows past SUMMARY_CACHE_MAX_ROWS (50 000), called once per buildTree, content-free counter known-lim "Document tasks & summaries"
DOC-2 (Info) 8 rag-design "Cap" rewritten to over-cap rejection (main.ingest.tooManyChunks), not silent truncation rag-design §14.1
DOC-3 (Low) 8 E5 no-prefix retrieval ceiling surfaced (floor stays 0; reranker load-bearing) known-lim "Retrieval quality"
DOC-4 (Info) 8 summary_cache eviction documented known-lim "Document tasks & summaries"
BL-4 (Low) 8 redaction date-locale asymmetry (US-order / 2-digit-year slip; names/addresses unmasked) recorded as by-design under-detection known-lim "Security & privacy" (redaction bullet)
DATA-4 (Info) 8 ORDER BY chunk_index on documentApproxTokenTotal (sum is order-independent → zero behaviour change) — (read-shape parity)

Accepted residuals & non-code dispositions (on record, deliberately not changed):

  • SEC-4 (Low, Phase 7) — pre-spawn binary verification is session-cached per path (the verify→spawn TOCTOU widens to per-session): a deliberate consistency trade-off, documented in security-model.md.
  • SEC-5 (Low, Phase 7) — imageAnalyze takes raw drag-drop bytes (not picker-token-bound): documented boundary, security-model.md.
  • API-2 (Info, Phase 8) — importPreflight accepts raw renderer paths for the recursive count/size walk: a pre-existing documented residual, no code change.
  • SEC-7 (Info) — the verified-clean inventory: no action, recorded below so it is not re-investigated.
  • TEST-9 (Low) — a double-EOCD / duplicate-name zip adversarial fixture for the installer was not added; the documented installer behaviour stands and the gap is an accepted residual.

Verified-clean inventory (attested 2026-06-27 — recorded so it is not re-investigated next round). The audit read each of these and found them correct and well-tested; they are deliberately not findings:

  • Crypto / vault — Argon2id default + scrypt legacy; descriptor-bound KDF params with sane bounds; the GCM verifier is checked before any DB decrypt; streaming file crypto with atomic temp+rename; key zeroing on lock and on wrong password; journaled v1→v2 rekey that recovers old-or-new per file.
  • Zip importer — enumerate-before-inflate; path/symlink/extension/size re-validation; content-free error codes; no zip-slip.
  • Manifest parsing — no eval/Function/require of package content; no prototype-pollution sink (own-enumerable __proto__, a fresh sanitized object).
  • Subprocess spawns — array argv, no shell, hash-verified before spawn, drive-root escape guards.
  • Offline guard — IPv4-anchored loopback check, fails safe.
  • Audit / log — ids/counts/filenames only, sentinel-grep enforced, log encrypted at rest.
  • Confused-deputy — picker capability tokens; drag-drop symlink-rejected + realpath-canonicalised.
  • Data layer — FKs enforced (foreign_keys = ON); migrations idempotent + identifier-validated against injection; FTS5 mirrors trigger-synced + VACUUM-safe; deleteConversation deletes in FK order; extraction_records/tree_nodes/document_collections/conversation_documents/image_turns all CASCADE correctly; the prepared-statement cache is keyed by constant SQL only. (The one exception — the bank/invoice tables lacking CASCADE — was DATA-1, fixed in Phase 1.)
  • IPC / API surface — the preload bridge is a closed allow-list; every handler validates id/array shapes; exports always go to a dialog.showSaveDialog user-chosen path; image/doc/skill-run jobs use async-with-polling; unknown job ids resolve to a terminal failed rather than throwing.
  • CLAUDE.md hard rules — re-attested ✅: no cloud / hosted-AI APIs (only the two user-gated downloaders + loopback sidecar use fetch; CSP connect-src 'self'); no telemetry / analytics / remote crash reporting; no weights/user-data/logs committed; fully usable offline; user data local + encrypted by default; no hardcoded dev paths; Windows first-class; clean swappable service boundaries.

Posture held across all 8 phases (load-bearing): offline / no telemetry / no new network egress; the content class (document text + titles/filenames, chat, extracted figures, redacted text) is never logged/audited — the new lock message and the eviction counter carry counts only; schema changes were additive (or fresh-schema CASCADE); the Electron + vision/OCR caps are defense-in-depth with no new DB/FS/net capability. Final suite 2335 passed / 39 skipped.

§25 Full audit (2026-06-28) — remediation close-out

A multi-persona read-only full audit (report audits/full-audit-2026-06-28.md), run after the backend audit 2026-06-27 close-out (§24) merged to master, swept apps/desktop (~47k LOC app, ~52k LOC tests), docs/, scripts/, and model-manifests/ across seven personas — security, backend / architecture, data layer, RAG / ingestion, business logic, frontend, testing, documentation — focusing where the backend-only prior round did not look: the renderer, financial-extraction locale correctness, CI, and CJK / Thai ingestion. No Critical, no remote-exploitable issue (offline by construction; only loopback sidecars + the two user-gated downloaders touch the network, prod CSP connect-src 'self'). The §1 severity index enumerates 54 findings — by area REL×5, BL×6, FE×9, TEST×9, PERF×6, RAG×6, DATA×3, SEC×3, DOC×7 (5 High; the report's "48" headline miscounts its own table). All 9 phases (0–8) are landed on branch full-audit-2026-06-28-fixes. The working-paper report was deleted under the CLAUDE.md doc-lifecycle rule once every finding was dispositioned; it had already been committed to the repo (since f1fce73), so the full original stays recoverable in git history (the parent of the Phase-8 close-out commit), mirroring the §24 / 2026-06-27 precedent. Each phase's decisions were folded into the topic-doc §§ as it landed, and the report's lasting content (the per-finding dispositions, the verified-clean inventory, and the accepted residuals) lives in this section. This ledger is the durable index — resolve a code comment's full-audit-2026-06-28 <ID> citation through it.

Finding(s) Phase Disposition (one line) Record
TEST-N1 (High) 0 fixed — .github/workflows/ci.yml: npm ci → typecheck → build → test on ubuntu+windows / Node 22.x, stable ci-success aggregate gate (the first machine backstop) packaging.md "Continuous integration (CI)"; BUILD_STATE Phase 0
TEST-N9 (Low) 0 fixed — whisper-smoke mkdtempSync moved into beforeAll + afterAll cleanup (no import-time temp leak in a skipped file) this ledger; BUILD_STATE Phase 0
BL-N1 (High), TEST-N2 (High) 1 fixed — per-document date-locale inference (de-AT day-first default; flips to mm/dd only on an unambiguously US-ordered date) stops the silent row-drop / wrong-month; adversarial whole-string tests now drive the real extractTransactionRows/parseLineItem path (closing the pre-isolated-token gap); grouped figures (1.000, 1 234 567,89, 1'234.56) fully supported known-lim "LINE PARSER" bullet; arch §10 (DECISIONS as built)
BL-N2 (Med) 1 fixed — stripDateTokens scrubs date tokens at either end before the last-money balance/total scan, so Endsaldo … per 30.06.2026 no longer reads the date as the balance known-lim "LINE PARSER" BL-N2 sub-bullet; §10 / §24 immunity claim corrected
BL-N3 (Med) 1 fixed — amount column chosen by position (second-to-last figure when a balance is present), not the first money-shaped token known-lim "LINE PARSER" bullet
BL-N4 (Med), TEST-N6 (Med) 1 fixed — redaction masks punctuated US/national phones + case-insensitive IBANs; characterization tests pin the residual under-detection (US-order / 2-digit-year / names-addresses) known-lim redaction "Phone and IBAN coverage" sub-bullet
BL-N5 (Low) 1 fixed (code-only, no residual) — reconcileBalances compares in integer cents, matching assessCompleteness this ledger
BL-N6 (Low) 1 docs-only / accepted — redaction masks every date and deliberately does NOT infer locale (US 12/31 leaks while EU 31/12 masks); by-design best-effort, no leak path to any log known-lim redaction date-masking sub-bullet
REL-1 (High) 2 fixed — crash-only RuntimeManager.forceRestart(opts) does doStop() (clears current/last so status() stops reporting the dead server healthy) then doStart(), bypassing only the same-model idempotency guard; bounded to one fallback by persisted gpuAutoDisabled arch §5.3 (corrected)
REL-2 (Low) 2 fixed — LlamaServer.start() instance-level starting single-flight latch (a 2nd concurrent direct caller joins the one start + waits for health) arch §5.3 record (runtime)
FE-1 (High) 3 fixed — ErrorBoundary (per-screen inside <main> keyed by screen + outer last-resort), localized fallback, local-only log (no network), nav rail stays alive arch "Renderer robustness — design record (Phase 3)"
FE-2, FE-3, FE-4 (Med) 3 fixed — unhandled IPC rejections → friendlyIpcError/toast; per-skill in-flight Switch guard; let active/mountedRef unmount guards on every poll arch renderer record
FE-5, FE-6, FE-7, FE-8, FE-9 (Low) 3 fixed — identity-stable applyLanguageSetting; stable React keys (name+index / monotonic id); tracked toast timers; friendlyIpcError + localized UNKNOWN; explicit Home/End edge select arch renderer record
RAG-N1 (Med) 4 fixed — audio packing caps on approxTokenCount (CJK/Thai-aware) keyed off the chunk window; an over-budget single segment is char-split (space-less-safe), preserving the one-segment-per-chunk / no-overlap invariant rag-design §2 (audio packing)
RAG-N2 (Low) 4 fixed — chunker char-slices space-less runs at gcd(size, overlap) so consecutive CJK/Thai chunks gain the ~80-token overlap (was zero) rag-design §3 (windowing)
REL-4 (Med) 5 fixed — deleteConversation wrapped in one txn (ROLLBACK on throw), mirroring deleteDocument arch §10 (data-layer hardening, Phase 5)
REL-5 (Low) 5 fixed — deleteImageSession deletes the row first (in a txn), shreds the file after (DATA-1 ordering) arch §10 (Phase 5)
PERF-3 (Med) 5 fixed — idx_messages_conv_kind serves the per-turn getLatestCheckpoint compaction lookup with no SCAN (EXPLAIN-pinned) arch data-layer index inventory
PERF-4 (Low) 5 fixed — idx_summary_cache_created turns the age-ordered eviction into an ordered index scan arch data-layer index inventory
DATA-1 (Low) 5 fixed — messages_fts_au UPDATE trigger gains the kind IS NOT 'compaction' guard + ensureMessagesFtsUpdateKindFilter backfill arch §10 (Phase 5)
DATA-2 (Low) 5 invariant-only (no code change) — tree_edges.child_id polymorphic-FK no-dangling-edge invariant pinned by an integrity test arch §10 (Phase 5)
DATA-3 (Low) 5 verify-only (no code change) — extract.ts __scan__ per-chunk idempotency confirmed + pinned by a no-double-count test arch §10 (Phase 5)
RAG-N3 (Med), DOC-N6 (Low), TEST-N4 (Med) 6 fixed — reranker MAX_DOC_APPROX_TOKENS raised 320 → whole chunk window (500 = CHUNK_DEFAULTS.chunkSizeTokens) so it scores every chunk in full (n_ctx-safe via the existing clamp); graded-overlap ranking-order test replaces exact-match-only; the E5 prefix-less + reranker-prefix ceilings documented with the prefix-migration TODO rag-design §11 "Known retrieval-quality ceilings" + §12.3
RAG-N4 (Low) 7 fixed — MarkdownParser in-fence flag (a # inside a fenced block is code, not a heading) rag-design §2
RAG-N5 (Low) 7 fixed — CSV/TSV delimiter pinned by extension (\t / ,), not papaparse auto-detect rag-design §2
RAG-N6 (Low) 7 already-correct (no code change) — corpusNeedsReindex routes through the shared buildScopeFilter (archived parity); pinned by a new includeArchived regression test rag-design §13.6
SEC-N1 (Low) 7 fixed — safeRelPath rejects a NUL member name (fixed invalidPath) before any write; previewSkillPackage wraps its body in a catch mapping residual throws to a fixed reason (sentinel-grep teeth) security-model "Skill-import defences"
SEC-N2 (Low) 7 fixed — benchmark IPC (runBenchmark/tryGpuAgain) gains explicit requireUnlocked() parity (localized main.benchmark.locked) security-model "Phase-7 security polish"
SEC-N3 (Info) 7 accepted Info residual — sidecar serverMessage 500-char tail is structural-only (our loopback llama.cpp, never user content); pinned by an INVARIANT (SEC-N3) comment at the cap security-model "Phase-7 security polish"
TEST-N5 (Med) 7 fixed (tests-only) — assert observables not mechanisms (key-buffer-zero vs Buffer.fill spy; ≤ 1 read counts; toContain event arrays) this ledger
TEST-N7 (Low) 7 fixed (tests-only) — fixed LE byte-layout assertion for decodeVector ([00 00 80 3f] → [1.0]), independent of encode this ledger
TEST-N8 (Low) 7 fixed (tests-only) — structural lock test over every registered DB-touching chat/benchmark handler + a retrieve()-level rejecting-embedder test (failure propagates; since folded into rag.test.ts TEST-3) this ledger
PERF-1 (Med) 7 fixed — picker image read → fs/promises (open → stat → read loop → close in finally), preserving the same-handle TOCTOU invariant + byte cap this ledger (ING-8 convention)
PERF-2 (Med) 7 fixed — dictation WAV write → await writeFile (finally still shreds) this ledger (ING-8 convention)
PERF-6 (Low) 7 fixed — AnswerThread memoized TurnRow; the in-flight turn renders plain text, markdown parsed once on completion this ledger
PERF-5 (Med) 7 partially fixed (Part A) — DocRow = memo(...) with stable callbacks so a poll tick / menu open / sibling-select re-renders only the affected row; Part B (list windowing) re-deferred (owner decision — no virt lib; variable-height rows + scroll/find/a11y behavior-sensitive) arch renderer-tail note
DOC-N1 (Med) 8 docs-only — security-model.md now names all six HILBERTRAUM_SKILL_MAX_* caps + the HILBERTRAUM_MAX_IMAGE_BYTES / _PIXELS image caps security-model.md §6.4 caps bullet + D4
DOC-N2 (Low) 8 fixed (comment) — §21 → §22 for the bank-statement LLM categorizer in doctasks/manager.ts and skills/categorizer.ts (2nd instance found by the anchor sweep) code comments → arch §22
DOC-N3 (Low) 8 docs-only — README Qwen3.5-4B size ~2.6 → ~2.9 GB; RAM tiers clarified as recommended best-fit vs the table's lower Min RAM floor README.md
DOC-N4 (Low) 8 docs-only + parity test — scoped the "mirrored from assets.ts" claim to the download/verify/plan logic; the default-set ids live only in the two prepare-drive shells (new prepare-drive-default-set.test.ts pins their parity) packaging.md; drive-layout.md
DOC-N5 (Low) 8 docs-only — single-test commands (npx vitest run <file>, -t "<name>") + test:watch added CONTRIBUTING.md; README.md
DOC-N7 (Low) 8 docs-only — packaging.md harness matrix gains an "optional inputs" table for the six HILBERTRAUM_* artifact-pointer vars packaging.md
REL-3 (Low) — not remediated (accepted) — rasterizer reply waiter stays channel-only (no request-id correlation); a Low-confidence HYPOTHESIS whose impact is bounded by the per-step withTimeout; deferred as a correctness margin this ledger (accepted residuals)
TEST-N3 (Med) 0 / 8 partially remediated (accepted) — the "manual smokes never run in CI" half is accepted-by-design (separate human gate, documented); the canned-fixture policy + the gpu --list-devices fixture exist, but the SSE + whisper-JSON parser fixtures remain OUTSTANDING (follow-up) packaging.md harness matrix / fixture policy

Accepted residuals & non-code dispositions (on record, deliberately not changed):

  • REL-3 (Low, HYPOTHESIS) — not remediated: the OCR rasterizer's hidden-window reply waiter matches on channel only (no request/page-id correlation). Impact is a correctness margin (any hang is bounded by the per-step withTimeout), confidence is Low, and it was never scoped to a phase; deferred as a future nicety, not a live defect.
  • TEST-N3 (Med) — partially remediated: the manual HILBERTRAUM_* smoke matrix is a deliberate separate human pre-release gate (it can't run in offline CI); the canned-real-output fixture-parser policy and the b9585 --list-devices fixture exist, but the promised SSE and whisper-JSON parser fixtures are still outstanding — an open follow-up so those parse layers gain CI coverage.
  • PERF-5 Part B (list windowing) — documents-list DONE (full-audit-2026-06-29 follow-up Phase 4 / PERF-2 — @tanstack/react-virtual; see §36); the chat transcript half stays deferred (variable-height messages + scroll-to-bottom + find-in-page + StreamAnnouncer — genuinely behavior-sensitive), still the tracked top renderer item. Part A (row memoization) shipped earlier.
  • E5 query:/passage: prefix migration (RAG-N3 / DOC-N6) — tracked TODO, not done: it re-embeds the whole corpus (its own phase) and would re-enable a meaningful ragMinSimilarity floor; the reranker full-chunk fix was the smaller-blast-radius lever taken now.
  • DATA-2 / DATA-3 — invariant-only / verify-only (no code change): both are pinned by tests, not altered behavior.
  • SEC-N3 — accepted Info residual: the sidecar serverMessage tail is structural-only by upstream (loopback llama.cpp) convention, pinned by an invariant comment at the 500-char cap.
  • BL-N5 — a clean code-only fix with no residual limitation (not a trade-off), so deliberately absent from known-limitations.md.
  • Residual caveats inside fixed findings (documented in known-limitations.md): BL-N1 — a doc whose dates are all fully ambiguous reads day-first (silent; the tool output schema is frozen); BL-N3 — an unusual layout (two amount columns / a description figure in the amount slot) can still mis-pick; BL-N4 — bare un-punctuated phone runs + space-grouped IBANs still slip (best-effort).

Verified-clean inventory (attested 2026-06-28 — recorded so it is not re-investigated next round). The audit read each of these and found them correct and well-tested; they are deliberately not findings:

  • Crypto / vault — lifecycle, key-zeroing on lock / wrong password, journaled v1→v2 rekey: re-attested (the §24 crypto inventory still holds end-to-end).
  • The full IPC requireUnlocked() surface — every DB-touching handler fail-closes when locked (the ctx.db getter throws); TEST-N8 added a structural lock test over the chat + benchmark handlers and SEC-N2 closed the one benchmark parity gap. (Correction, post-merge §30/F16: the original TEST-N8 enumerated only chat+benchmark — not "every" module. The audit/core-settings/model/rag groups touched ctx.db with no explicit requireUnlocked() preamble, so they fail-closed but surfaced the raw English vault string. §30 added the localized preamble to those four groups and generalized the structural test across the core/model/audit/rag/benchmark/collections modules — see tests/integration/ipc-lock-coverage.test.ts; images (vision test campaign), docs/doctasks (documents test campaign) and chat (chat + RAG test campaign, retiring chat-ipc's own TEST-N8 test) have since joined its MODULES loop.)
  • Electron hardening — deny-by-default navigation / permission guards on both events, the closed preload allow-list, CSP connect-src 'self', OCR window deny-all.
  • spawn / process security — array argv, no shell, hash-verified before spawn, drive-root escape guards, windowsHide / child.unref() on the probe.
  • Offline / SSRF posture — IPv4-anchored loopback guard (fails safe), per-redirect-hop re-validation (https-only + private-range deny), streamed-size cap; only the two user-gated downloaders + loopback sidecars use fetch. (Post-merge §30: the private-range deny also now covers the IPv4-mapped IPv6 form — F15 — and the streamed-size cap is now always bounded on both downloaders — F17.)
  • RRF fusion determinism — the pure rrfFuse units stay strong, and the pass-through guarantee (no keyword / no reranker ⇒ byte-identical to vector-only) was re-verified in Phase 6.
  • Vector codec hardening — decodeVector truncated-blob guard + module-load LE assert; TEST-N7 added a fixed-byte-layout test pinning the on-disk LE contract.
  • FTS injection-safety — FTS5 triggers synced + VACUUM-safe, identifier-validated migrations; DATA-1 added the UPDATE-trigger kind guard.
  • The SEC-1 Tier-2 app-skill gate — Tier-2 tools run for built-in app skills only (skillCanRunTools, re-checked at startSkillRun): re-attested.
  • Chat-stream lifecycle — error / abort / destroyed-renderer / key-reuse paths, IPC subscriptions torn down in finally.

Posture held across all 9 phases (load-bearing): offline / no telemetry / no new network egress; behavior-preserving (every behavioral fix teeth-checked neuter→fail→restore, then restored byte-identical); the content class (document text + titles/filenames, chat, extracted figures, redacted text) is never logged / audited / exported; schema changes are additive (two IF NOT EXISTS indexes + one FTS-trigger guard); the only Phase-8 code touches are the DOC-N2 comment fix (×2) + the DOC-N4 parity test. Final suite 2417 passed / 39 skipped (typecheck + build green across the cumulative branch; no phase regressed another, verified by one full-suite run at close-out).

§26 Full audit (2026-06-29) — remediation close-out

A fresh 7-persona read-only full audit (report audits/full-audit-2026-06-29.md), run after the 2026-06-28 round (§25) was fully remediated and merged (PR #12), swept the real source tree across security, RAG/ingestion, backend reliability, renderer, testing, documentation, and financial/business logic, with the top findings re-verified firsthand (regex traces, a full-suite run, doc/code diffs). No Critical, no remote-exploitable issue (offline by construction). The report enumerated 2 High, ~9 Medium, ~13 Low; the two release-blockers were a confirmed financial-correctness bug (BL-1) and an intermittently-red suite (TEST-1). All six phases (0–6) landed on branch full-audit-2026-06-29-fixes. The working-paper report was retired under the CLAUDE.md doc-lifecycle rule once every finding was dispositioned; it was committed first so the full original stays recoverable in git history (the parent of the Phase-6 close-out commit), mirroring the §24 / §25 precedent. Each phase's decisions were folded into the topic-doc §§ as it landed; the report's lasting content (per-finding dispositions + accepted residuals) lives in this section. This ledger is the durable index — resolve a code comment's full-audit-2026-06-29 <ID> citation through it.

Finding(s) Phase Disposition (one line) Record
TEST-1 (High) 0 fixed (test-only) — dictation-ipc.test.ts REL-3 poll swapped from an iteration cap (i < 100 setImmediate ticks, flaked under full-suite CPU load) to a wall-clock deadline (Date.now() - start < 5000), matching the rest of the integration suite; 3× consecutive green this ledger; BUILD_STATE Phase 0
BL-1 (High, release-blocking) 1 fixed — MONEY_RE's trailing \s*\)?-? stole the NEXT column's leading minus (2.500,00 -500,00 → amount −2500 / balance +500, both flipped, so reconcileBalances blessed the wrong figures); replaced with a space-disambiguated trailing region (?:-|\s*\)|\s+-(?!\s*[-+(]?\d))? — a glued - is a de-AT debit (consumed), a spaced -<digit> is the next figure's sign (left alone). DIVERGED from the audit's literal (?:-(?!\s*[-+(]?\d))? — that form regressed the common de-AT row 45,90- 1.908,20 (glued debit + balance) to +45,90; verified by trace (rationale: BUILD_STATE Phase 1) arch §8 "Financial correctness (full-audit-2026-06-29, Phase 1)"; known-limitations LINE PARSER (spaced-trailing-minus residual)
BL-2 (Med) 1 fixed — per-row detectCurrency now scans only the figure region (rest.slice(matches[0].index)) with statement-currency fallback, so a USD/$ in a payee memo no longer collapses a EUR statement to the mixed-currency refusal; a genuine figure-adjacent foreign code is still honoured arch §8 (figure-region currency); known-limitations
BL-3 (Med, de-AT target) 1 fixed — wordIncludes gained a one-sided compound mode; the unambiguous DE keywords (gebühr/gehalt/überweisung/bargeld) opt in via compound: true so Kontoführungsgebühr→Fees, while English tokens + ambiguous lohn stay strict (no C-1 regression); categorizeRow + prefilterCategory thread the flag (C-1 invariant held) arch §8 (wordIncludes paragraph); known-limitations
REL-1 (Med) 2 fixed — LlamaServer.start retries doStart once on a bind-class immediate exit (isBindRaceError) on a fresh port (covers chat AND embedder/reranker/vision, which had no retry); the ladder no longer persists gpuAutoDisabled on a bind race vs a device fault, so a port collision can't disable GPU for the session arch GPU record §5.5
REL-2 (Med) 2 fixed — killWithEscalation mirrors LlamaServer.stop() (SIGTERM → SIGKILL after killGraceMs, grace timer unref'd/cleared), wired into the whisper watchdog/abort/stop() kill sites; suspend()/stop() bound the cleanup await (suspendTimeoutMs, crash-sweep is the shred backstop) so a SIGTERM-ignoring child can't hang quit/lock known-limitations "Audio transcription" (SIGKILL/teardown residual); this ledger
REL-3 (Med) 2 fixed — acquireForChat(signal?) threads the turn's abort signal (new waitForHandoff); a Stop during a deep-index slot park rejects at once (removes the waiter, returns its chatHolders slot, drops the pause if last), resolved cleanly via done not chat:error; all 7 chat/rag call sites forward controller.signal. Gap closed later: an abort one microtask after the handoff (#555, PR #556) arch doc-task / model-slot-arbiter record; this ledger
DOC-2 (Low) 2 fixed (docs) — GPU table "60 s health timeout" → "180 s (3 min)" (DEFAULT_HEALTH_TIMEOUT_MS; chat runtime never overrides it) arch GPU record §8 table
TEST-2 (Med) 3 fixed (test-only) — binary-verify-spawn.test.ts drives the real verifyBinaryBeforeSpawn at all three spawn seams (LlamaServer.start, GPU --list-devices probe, whisper-cli) with packaged enforcement ON + a hash-mismatched marker → each refuses to spawn; matching-marker positive control; teeth-checked per seam arch "Test-enforcement seams — design record (Phase 3)" TEST-2
TEST-3 (Med) 3 fixed (test-only) — rag.test.ts proves a fresh failing embedder over a non-empty corpus makes generateGroundedAnswer reject (doesn't masquerade as NO_DOCUMENT_CONTEXT) arch test-enforcement record TEST-3
TEST-4 (Low) 3 fixed (test-only) — skills-installer.test.ts covers encryptedZip (GP-flag + ZIP64-sentinel), the SEC-N1 NUL invalidPath no-echo, and pathTooLong through the real previewSkillPackage/importSkill; the "no tar" test relabelled documentation-only arch test-enforcement record TEST-4; this ledger
TEST-5 (Low) 3 fixed (test-only) — the vision success-path no-leak test was converted to route through the real VisionRuntime (recording fetch + SSE body), so the no-prompt/no-image-bytes-in-logs guarantee exercises the real SSE/HTTP path arch test-enforcement record TEST-5; this ledger
FE-1 (Low) 4 fixed — ChatScreen gained the FE-4-class mountedRef (gating the attach-poll + stream-flush setStates) + a flush-timer clearTimeout on unmount; the main-side stream is not torn down (recovered via getActiveStream) — guard-only arch renderer record (FE-4 bullet, "Extended (full audit 2026-06-29, FE-1)")
RAG-1 (Low) 4 fixed — both fusion input lists carry a chunkId tiebreak (vector sort score desc, chunkId asc; FTS ORDER BY bm25(...), chunks_fts.chunk_id) so equal-score ties are total/reproducible across SQLite versions; resident-cache equivalence oracle aligned rag-design §11 per-list tie-break note
RAG-2 (Low) 4 fixed — truncateSnippet counts AND slices by code point ([...trimmed]) so a boundary-straddling astral char no longer leaves a lone surrogate in a citation snippet (display-only) source comments (snippet-truncate.test.ts); this ledger
REL-4 (Low) 4 fixed — combineSignals owns an AbortController + explicit setTimeout and returns { signal, clear }; the three embed/rerank/vision call sites clear() in finally so an early completion no longer leaves a 120 s/300 s timer + any-listener alive (behaviour preserved: caller-abort + timeout still abort, TimeoutError, unref'd). #607: the embed site lost this on 2026-06-30, when the context-overflow retry (dbfee90f) moved the clear() to the response headers; restored, see rag-design.md §12.4 "#607 amendment". source comments (combine-signals.test.ts); this ledger
PERF-1 (Med, the scalability item) 5 fixed — the resident decoded-vector cache is now incremental: invalidate marks dirty (no longer drops the map); the next read reconciles via an ids-only scan (drop gone ids) + a point decode of only genuinely-new chunk ids — a pure-add of K into N decodes K, not N. The (count, maxRowid) signature is retained as the self-healing backstop (out-of-band write → full rebuild); purge still drops the map on lock arch "Performance — design record … Wave P4" (Incremental-delta + PERF-1 Phase-5 note)
DOC-1 (Med) 6 fixed (docs) — collections.ts header no longer claims the shipped C2 delete-with-documents is "left out of v1"; repointed from the wrong rag-design §13.7 to architecture.md §1 C2 (the projectOnlyDocumentIds predicate is in the same file) code comment → arch "Document organization — design record" §1 C2
DOC-3 (Low) 6 fixed (docs) — bge-reranker-v2-m3.yaml size_on_disk_gb 1.08 (GiB mislabel) → 1.16 (decimal GB, matching size_bytes 1159776896 / 1e9 and the other twelve manifests); model-policy.md "1.08 GB" → "1.16 GB" model-manifest + model-policy.md reranker row
DOC-4 (Low) 6 fixed (docs) — dropped the dangling /§11.1 from benchmark.test.ts's "GPU record §8/§11.1" comment (the GPU record is §1–§8; §8 resolves) code comment → arch GPU record §8
SEC-1 doc half (Low) 6 docs-only — added an accepted-residual note: vault unlock has no attempt counter / rate-limit and only an 8-char floor, so against the lost/stolen-drive threat a weak-but-≥8 password is offline-guessable at interactive-minimum Argon2id cost; at-rest Argon2id+AES-GCM is the primary mitigation; recorded as a defensible offline trade-off security-model.md "Accepted residual — offline password guessing"
TEST-6 (Info) 3 docs-only / by-design — the S13b skill-trigger precision bar IS a live CI gate (fired-wrong == 0 ∧ precision ≥ 0.95, skill-triggers.test.ts); the remaining no-automated-floor gap is narrower: RAG answer-quality + real-model output (env-gated out of CI by design), caught only by the manual smoke matrix. (Wording corrected Phase 7 / D1 — the original "owner-gated on D1" claim went stale once the S13b bar landed.) arch test-enforcement record TEST-6
SEC-1 code half (Low) — accepted residual / open follow-up — unlock-path rate-limit/attempt-counter + create-time strength meter/floor; deliberately not built in the docs-only close-out (a UI rate-limit doesn't bind the offline attacker that is the real threat; the at-rest KDF is the mitigation) security-model.md residual note
SEC-2 (Low) — accepted residual / open follow-up — previewSkillPackage stages path-/size-validated, finally-cleaned content to the shared OS tmpdir(); not an escape (skill packages aren't secret). Follow-up: stage under userSkillsDir for trust-zone consistency this ledger
SEC-3 (Info) #681 fixed 2026-10-14 (#681, owner call) — every dialog opener is now requireUnlocked()-gated: pickDocuments was the last, and ipc-lock-coverage.test.ts's registerDocsIpc entry no longer exempts docs:pick, so its loop proves the gate (a real-app call while locked opened "Dokumente importieren" before, and is refused now). Was: accepted residual / open follow-up — the dialog-opener IPCs (pickDocuments/imageChooseImage) mint a capability token pre-unlock, but every consuming handler is requireUnlocked()-gated so the token is inert until unlock; a consistency gap, not an exploit. (Corrected 2026-09-03, #240 / PR #275: pickSkillPackage minted NO token at the time — it returned a raw path that previewSkillPackage/importSkill accepted unverified; since PR #275 it is unlock-gated and mints a token like the other two, via src/main/ipc/picker-tokens.ts. Corrected 2026-10-14: imageChooseImage is unlock-gated too since #119, so pickDocuments is the one dialog opener left ungated — tracked in #681; ipc-lock-coverage.test.ts lists it as the registerDocsIpc entry's exempt channel until then.) this ledger
REL-5 (Low) — non-reachable while the single-DatabaseSync architecture holds; promote to a real fix only if a second DB connection (e.g. a worker-thread reader) is introduced — verified (follow-up Phase 6) architecturally non-reachable: exactly one live synchronous DatabaseSync connection per session (db.ts; others are transient open→seed→checkpoint→close), and all 15–20 BEGIN…COMMIT bodies are synchronous (the slow await embed/generate sits outside the txn). BEGIN IMMEDIATE would be a no-op without a second writer, so the withTransaction(db, fn) refactor stays deferred. Precondition made explicit so a future worker-pool/second-connection change can't silently make it reachable this ledger; §37 (follow-up Phase 6 REL note)
§5 INFO / by-design (CSV single-data-row, DOCX paragraph-split, embedChunks single-batch, corpusNeedsReindex double-scan, rerank-before-dedup cost) — accepted (no change) — low-severity edge/robustness notes; each acceptable as-is, recorded so the next audit skips them this ledger (accepted residuals)
PERF-5 Part B (list windowing), E5 query:/passage: prefix migration — carried forward from §25 (still open) — list virtualization re-deferred (no virt lib; variable-height rows + scroll/find/a11y behavior-sensitive); the prefix migration re-embeds the whole corpus (its own phase) and would re-enable a ragMinSimilarity floor §25 accepted residuals (unchanged)

Accepted residuals & non-code dispositions (on record, deliberately not changed this round):

  • SEC-1 code half / SEC-2 / SEC-3 (SEC-3 closed 2026-10-14 by #681, see its row above) — three security consistency improvements, none an exploit: the offline-guessing residual's only binding mitigation is the at-rest KDF (a UI rate-limit doesn't stop the drive-in-hand attacker), preview-temp staging is path-/size-validated and finally-cleaned, and the dialog-opener tokens are inert until the consuming handler's requireUnlocked() gate (documents and images only at the time — the skills picker gained its token and unlock gate in PR #275, #240). Open follow-ups, not Phase-6 work (Phase 6 was docs-only by charter).
  • REL-5 — BEGIN IMMEDIATE + withTransaction is deferred, now with the precondition stated explicitly: it is non-reachable while the single-DatabaseSync architecture holds (one live synchronous connection per session; every BEGIN…COMMIT body synchronous, the slow await outside the txn). It becomes a real fix to build only if a second DB connection is introduced (e.g. a worker-thread reader / a connection pool) — that change, not this audit, is what would make BEGIN IMMEDIATE load-bearing. Recorded so a future worker-pool change can't silently re-open the gap (verified follow-up Phase 6; see §37).
  • §5 by-design edge notes — CSV single-data-row, DOCX paragraph-split, embedChunks single-batch (bounded by the 1000-chunk cap), corpusNeedsReindex double-scan (only on the already-failed empty-retrieval path), and rerank-before-dedup cost (correct by design): all acknowledged, none scoped to a fix.
  • PERF-5 Part B (list windowing) and E5 prefix migration — carried forward unchanged from the §25 accepted residuals (still the owner-dispositioned long-pole items).
  • §-anchor sweep note (not a finding to fix here): the sweep confirmed DOC-1 (→ §1 C2) and DOC-4 (→ §8) resolve and that every audit-introduced code/test comment cites by finding-ID. It also surfaced two pre-existing dangling §11.1 citations in gpu.test.ts and runtime-ladder.test.ts (the same §11.1 DOC-4 flagged, but at locations the report did not name). Per the Phase-6 scope guard (fix only citations this audit introduced) they were left as-is and reported — a candidate for a future doc-comment pass.

Posture held across all six phases (load-bearing): offline / no telemetry / no new network egress; behavior-preserving (every behavioral fix in Phases 1/2/4/5 teeth-checked neuter→fail→restore; Phases 0/3 were test-only with no src/ behavior change; Phase 6 was docs/comments-only + the report retirement); the content class (document text + titles/filenames, chat, extracted figures, redacted text) is never logged / audited / exported; no schema/IPC/audit-payload change in any phase. Final suite 2463 passed / 39 skipped (2502 collected) (typecheck + build green; the Phase-6 docs/comments change touched no test and the suite is unchanged from Phase 5).

§27 Full audit (2026-06-29, post-merge) — remediation ledger (Phase 1 — money-parser correctness)

A fresh post-merge full audit (report audits/full-audit-2026-06-29-postmerge.md), run after §26 was merged, found the prior round's bank hardening had not propagated to the sibling invoice path. The pattern: the fix exists next door but wasn't applied here. It enumerated 1 High, ~9 Medium, ~13 Low; Phase 1 — the release-blocker money-parser class — is remediated on branch audit-postmerge-phase1-money (suite 2483 passed / 39 skipped, typecheck + build green). Parsing-only; no schema/IPC/audit-payload change. The design record is §8 "Financial correctness (full-audit-2026-06-29-postmerge, Phase 1)"; resolve a full-audit-2026-06-29-postmerge <ID> code comment through this ledger. Later phases (F2/F4/F5/F7/ F9 reliability, F11–F19 RAG/security/concurrency, F20–F24 renderer, D1–D8 docs, T1–T9 test seams) are not started — carried in the report.

Finding(s) Phase Disposition (one line) Record
F1 (High, release-blocking) 1 fixed — an uncaptured amount column read the running BALANCE as the movement amount (Sparen 50 1.234,56 → 1234.56). Bank: parseLine FLAGS ambiguousAmount (one money token + bare-number-trailing description); extractTransactionRows drops it only when the statement has a balance column. DIVERGED from the audit's literal "drop whenever a left digit-run remains" — the unconditional drop regressed the HVB "Umsätze" no-balance numeric-payee format (REWE … 1234 -19,15), so the drop is statement-context-aware. Invoice mirror drops on the RIGHT (line total = LAST figure): Hosting 12,50 500 → drop arch §8 (F1); known-limitations LINE PARSER (F1 + residuals)
F3 (Med) 1 fixed — invoice per-line detectCurrency now scans only the figure region (rest.slice(matches[0].index)) with documentCurrency fallback (the BL-2 fix, never applied to invoices); validateInvoiceTotals gained the bank gate's single-currency guard (lineItemsSumToNet: 'unknown' for a >1 line-item currency set) arch §8 (F3); known-limitations (figure-region currency bullet)
F6 (Med) 1 fixed — on the geometry-less invoice path a space-grouped token WITHOUT a 2-dp decimal tail (Widget 10 100 → 10100) is a likely column fusion → the row is DROPPED (isFusedSpaceGroup); a decimal-anchored 1 234 567,89 is kept; 15 799,00 stays the accepted DECISION-2 trade-off arch §8 (F6); known-limitations (grouping bullet)
F8 (Low) 1 fixed — the invoice quantity split now requires a unit token (a captured QTY_TRAIL_RE group) OR a corroborating unit-price column; iPhone 15 1.799,00 keeps "iPhone 15", Widget A 2 12,50 25,00 still reads qty 2. Metadata-only (lineTotal unaffected) arch §8 (F8); known-limitations (qty bullet)
T5 (test/invariant) 1 pinned — parseAmount rounds every figure to the nearest cent (Math.round(|value|*100)) so the integer-cent invariant holds by construction; a >2-dp 1.234,567 reads 1234.57 (normalised, not dropped). T4 (parens-negative) + T9 (negative line totals / Gutschrift/Rabatt) now pinned through the real scanner arch §8 (T5); known-limitations (2-dp bullet)
F10 (Low) 1 acknowledged (no code change) — the invoice path runs without geometry layout reconstruction (D58 is bank-only), so it is the most parse-fragile money path; Phase 1 prioritised its robustness (F1 right-side drop, F6 fusion drop) since it has no backstop, and the asymmetry is recorded arch §8 (F1/F6); known-limitations (invoice geometry note)
F2, F4, F7, F9 2 fixed (Phase 2) — chat-regenerate data-loss (F2) + embedder/reranker bind-race start-latch (F4/F7) + compaction-failure log (F9); see the §28 ledger arch §28; arch "Chat & streaming"; GPU record §5.5b
F5 3 fixed (Phase 3) — invoice extraction re-inserted a fresh invoice + line items on every analysis question (no reuse/replace/staleness, where the bank path has all three); now mirrors the bank reuse-or-re-extract gate (extractor_version + isInvoiceStale + replaceExisting atomic swap); see the §29 ledger arch §29; arch §8 (invoice reuse/replace/staleness parity)
F14, F15, F16, F17 4 fixed (Phase 4) — security consistency: F15 mapped-IPv6 SSRF deny-list bypass, F14 diagnostics-log buffer readable after lock, F16 IPC lock-guard parity + generalized structural test (subsumes T3), F17 download size caps always bounded; see the §30 ledger arch §30; security-model §D3 + "encrypted log" record; §25 inventory correction
T1, T2, T6, T7, T8, T9, T3 5 closed (Phase 5, test-only) — test-enforcement seams: T1 SIGKILL escalation unit test, T2 resident-cache lock-purge IPC wiring, T6/T7 two TEST-1-family flakes de-flaked (fake timers / vi.waitFor), T8 crash-fallback real-reap assertion, T9 truncated-ciphertext nit; T3 verified subsumed by F16; T4/T5 done in Phase 1. git diff src/ empty; see the §31 ledger arch §31; "Test-enforcement seams" record (Phase-5 subsection)
F20, F21, F22, F23, F24 6 fixed (Phase 6, renderer-only) — frontend a11y + lifecycle: F20 first-run gate phase-focus management (the finishing step had no focus target — the real gap; welcome→password & →starter already focused via autoFocus), F21 mic-stream leak when getUserMedia resolves after unmount, F22 ModelsScreen poll + DiagnosticsTab activity refreshers join the FE-4 mountedRef discipline (the claim now holds), F23 StreamAnnouncer aria-atomic drop, F24 Composer fallback caret-timer cleared on unmount; see the §32 ledger arch §32; "Renderer robustness" FE-4 reconciliation
D1–D8 + F11/F13 doc-notes 7 fixed / recorded (Phase 7, docs + comments-only) — the D1–D8 documentation contradictions reconciled to one source of truth + the F11/F13 as-built distinctions carried into the topic docs + a clean §-anchor sweep; see the §33 ledger arch §33; rag-design §14.4 (F11) + §12.1 R3 (F13)
F12, F18, F19 8 fixed (Phase 8, the close-out) — F12 named-delta resident-cache reconcile (no O(N) id-scan), F18 vision terminal-write cancelled-guard, F19 tearingDown race guard on embedder+reranker suspend(); the audit report was RETIRED here. The F11 renderer half + F13 code are carried forward. See the §34 close-out ledger arch §34 (master close-out); Performance/Wave-P4 (F12); GPU §5.5c (F19); Image-understanding §5 (F18)

Posture held (Phase 1, load-bearing): offline / no telemetry / no new network egress; the content class (extracted figures, document text) is never logged/audited/exported; no schema/IPC/audit-payload change. Every fix is characterization-first then test-first (pin current behaviour → assert the correct post-fix value → red on current code → green after the fix) through the real extractTransactionRows/ parseLineItem/validateInvoiceTotals entry points (TEST-N2 discipline: whole strings, never pre-isolated tokens). The normal 2-figure de-AT row is byte-identical; the HVB no-balance geometry case (pdf-bank-layout.test.ts) stays green (the F1 divergence exists to protect it).

§28 Full audit (2026-06-29, post-merge) — remediation ledger (Phase 2 — chat-regenerate data-loss + sidecar bind-race reliability)

Phase 2 of the post-merge audit closes the reliability cluster — all four "apply the fix that already exists next door" findings: the regenerate path commits a destructive delete before the REL-3-protected slot is claimed (F2), and the embedder/reranker start-latches never received the REL-1 bind-race classifier (F4/F7), plus the silent compaction-failure swallow (F9). Branch audit-postmerge-phase2-runtime-reliability (suite 2492 passed / 39 skipped, typecheck + build green). No schema/IPC-channel/audit-payload change. Design records: "Chat & streaming" (regenerate is delete-after-slot) + GPU record §5.5b (bind-race aware start-latch); resolve a full-audit-2026-06-29-postmerge <ID> code comment through this ledger.

Finding(s) Phase Disposition (one line) Record
F2 (Med, data-loss) 2 fixed — regenerate dropped the prior assistant reply (committed; node:sqlite is synchronous) BEFORE the stream slot was claimed, so a non-abort failure (a context-exceeded 400, a dead sidecar, a rejected slot) left the turn answer-less. The IPC layer now does only the read-only hasRegenerableAssistantReply precondition before the stream; the delete runs INSIDE withChatStream's runFn via withRegenerateGuard (slot held + controller registered) and the snapshot is re-inserted byte-faithfully (restoreMessage) on a non-abort failure. A user Stop keeps the delete. Applied to both channels (registerChatIpc + every registerRagIpc withChatStream site); slot/stream semantics otherwise identical arch "Chat & streaming" (regenerate is delete-after-slot)
F4 (Med) 2 fixed — the embedder start-latch (e5.ts) armed for ANY rejection, so a transient double-bind-race (REL-1 retries only once) latched a permanent-looking failure and silently disabled all imports for the session until lock/unlock. The .catch now skips arming when isBindRaceError(message) — leaving startFailed null so the next embed() re-attempts on a fresh port. The latch still arms (and still clears on suspend()) for a genuine load fault arch GPU record §5.5b; known-limitations (embedder latch)
F7 (Low) 2 fixed — same bind-race exclusion for the reranker (reranker/llama.ts). Its latch is more persistent (it deliberately SURVIVES suspend()), so latching a race disabled reranking for the whole session (a silent quality regression — retrieval falls back to fused order). Forgiving the race makes the keep-on-suspend() policy correct again: only a genuine load fault persists arch GPU record §5.5b; known-limitations (reranker latch)
F9 (Low) 2 fixed — chat/compaction.ts's catch {} around summarizeRegion was fully empty, so a repeatable summarizer BUG (not a user Stop) compacted never, silently, forever (offline/no-telemetry). The fallback to L1 is unchanged; the NON-abort case now log.warns (conversationId + the error message — no chat content), an AbortError still does not arch "Chat & streaming" (compaction)

Posture held (Phase 2): offline / no telemetry / no new network egress; the content class (chat text, document text, extracted figures) is never logged/audited/exported (F9's diagnostic carries only the conversation id + the underlying error message); no schema/IPC-channel/audit-payload change. The bind-race classifier is reused, not re-invented — the retry (§5.5) and the latch (§5.5b) share isBindRaceError, so they can't drift. Every fix is test-first (red on current code → green after): F2 drives the real chat + RAG IPC handlers (chat-ipc.test.ts, rag-regenerate-ipc.test.ts) with a runtime that 400s on a regenerate and asserts the prior reply survives + a service-level delete→restore round-trip (chat.test.ts); F4/F7 inject a double-bind-race at the real spawn/health seam (e5-embedder.test.ts, reranker.test.ts) and assert the latch stays null + a later call retries (F7 also pins survives-suspend vs a genuine fault persisting); F9 spies log.warn on a non-abort summarizer throw and asserts the abort path stays silent (chat-compaction.test.ts). Open (later phases): F11–F19 RAG/security/concurrency (Phase 4/8), F20–F24 renderer a11y/lifecycle (Phase 6), D1–D8 docs (Phase 7), T1–T9 test seams (Phase 5).

§29 Full audit (2026-06-29, post-merge) — remediation ledger (Phase 3 — invoice data lifecycle parity)

Phase 3 closes the single data-integrity finding F5 — again the "apply the fix that already exists next door" pattern: the bank path reuses a fresh extraction and gates re-extraction on a version + staleness check; the invoice path had none of it and re-inserted a brand-new invoices row (+ line items) on every analysis-shaped question. The fix is parity, not a new design — the invoice path now mirrors analysis/bank-statement.ts exactly. Branch audit-postmerge-phase3-invoice-lifecycle (suite 2495 passed / 39 skipped, typecheck + build green). The design record is §8 "Invoice reuse / replace / staleness — parity with the bank path"; resolve a full-audit-2026-06-29-postmerge F5 code comment through this ledger.

Finding(s) Phase Disposition (one line) Record
F5 (Med, data-integrity) 3 fixed — the invoice analysis handler re-extracted + INSERTed a fresh invoices row on every question (silent content-table bloat; a deterministic re-extraction producing identical rows, N questions → N invoices + N×line-items). Now mirrors the bank reuse gate: invoices gained an additive nullable extractor_version column (db.ts, copy of the bank_statements migration); runInvoiceExtraction stamps INVOICE_EXTRACTOR_VERSION (tools/invoice.ts) and accepts replaceExisting; the handler REUSES latestInvoiceId when present and not isInvoiceStale, else re-extracts with replaceExisting: true — which DELETEs the prior invoice + line items (FK order, the shared deleteInvoicesForDocument) inside the persist BEGIN/COMMIT before the INSERT (atomic swap). purgeSkillDataForDocument's ordered delete is unchanged (same helper) arch §8 (invoice reuse/replace/staleness parity); arch §27 (F5 row)

Posture held (Phase 3): offline / no telemetry / no new network egress; the content class (extracted invoice figures) is never logged/audited/exported (extractor_version is a provenance int, content-class adjacent — never surfaced). The schema change is a single additive nullable column added through the existing idempotent ensureColumn mechanism: an old on-disk workspace opens cleanly (pre-existing rows are NULL → stale → re-extracted on next reuse), and the bank table is untouched. node:sqlite is synchronous, so the replaceExisting delete-then-insert stays inside one BEGIN/COMMIT with no await between. Every fix is test-first (red on current code → green after): skills-analysis-invoice.test.ts reproduces the bloat (N questions persisted N invoices) and now asserts exactly one invoice + one line-item set survive, a fresh invoice is reused (same id, no duplicate), and a version-NULL invoice is detected stale → re-extracted + replaced in place at the current version (the tampered figure is gone). Open (later phases): F11–F19 RAG/security/concurrency (Phase 4/8), F20–F24 renderer a11y/lifecycle (Phase 6), D1–D8 docs (Phase 7), T1–T9 test seams (Phase 5).

§30 Full audit (2026-06-29, post-merge) — remediation ledger (Phase 4 — security consistency hardening)

Phase 4 closes the four security-consistency findings F15/F14/F16/F17. None is a remote exploit (the app is offline by construction); each is a gap where a documented control didn't fully hold — a deny-list that missed one host spelling, a buffer that outlived its lock, lock-guards that fail-closed but spoke the raw string, and a size cap that could collapse to the backstop. Branch audit-postmerge-phase4-security-consistency (suite 2515 passed / 39 skipped, typecheck + build green). Every fix is test-first (red on current code → green). Resolve full-audit-2026-06-29-postmerge F14/F15/F16/F17 code comments through this ledger.

Finding(s) Phase Disposition (one line) Record
F15 (Low→Med, SSRF) 4 fixed — IPv4-mapped IPv6 bypassed the download deny-list: new URL() canonicalizes [::ffff:127.0.0.1] → host ::ffff:7f00:1 / [::ffff:169.254.169.254] → ::ffff:a9fe:a9fe, which the dotted-decimal-only regex never matched, so mapped loopback / RFC-1918 / the cloud-metadata IP slipped the guard (reachable via a hostile manifest download.url or a redirect Location:). isPrivateOrLoopbackHost now denies any host containing ::ffff:. The detection-only offlineGuard.isLoopbackHost is left as-is (gates no enforcement). Tests: assets.test.ts (unit on each spelling + redirect-hop + a public-host positive control) security-model §D3 (F15)
F14 (Low, data-handling) 4 fixed — detachVaultKey() dropped+zeroed the vault key and reverted to buffering but left the in-memory buffer holding the just-ended session's metadata (file names/paths/model ids/settings keys — never document/chat text); the buffering read path + the intentionally-ungated getLogTail/exportLog let a still-mounted Diagnostics screen read/export it after lock. Option (a): zero the buffer after the final encrypted flush (next unlock repopulates from app.log.enc — nothing lost); guarded on mode==='encrypted' so the pre-FIRST-unlock diagnostics window is preserved. Test: logging.test.ts security-model "Design record — encrypted log" (F14)
F16 (Low, defense-in-depth + doc) 4 fixed — the §25 inventory overstated "TEST-N8 enumerates every DB-touching handler" (it covered only chat+benchmark); rag/audit/core-settings/model touched ctx.db with no explicit requireUnlocked() (fail-closed via the getter, but raw English string). Added the localized preamble (main.audit.locked/main.settings.locked/main.models.locked; rag reuses main.chat.locked) to those four groups and generalized the structural lock test across the core/model/audit/rag/benchmark/collections modules (tests/integration/ipc-lock-coverage.test.ts), asserting refusal + that the read-only channels (getLogTail/getRuntimeStatus) still resolve when locked. Subsumes Phase-5 item T3 (rag:ask lock-rejection). §25 wording corrected this ledger; §25 inventory correction
F17 (Low, disk-fill) 4 fixed — downloadToFile's cap fell to the 64 GiB backstop when nothing bounded the body; the engine downloader passed no maxBytes and the model downloader passed one only when size_bytes was present. Both now always pass a bounded cap: engine = ENGINE_DOWNLOAD_MAX_BYTES (2 GiB), model = modelWeightMaxBytes(role, sizeBytes) (the declared size plus drift headroom, since BUG dl-size-cap-2026-07-03; else a per-role default: chat/vision 40 GiB, transcriber 8 GiB, embeddings/reranker 4 GiB). Backstop lowered 64→48 GiB (now unreachable from production). The cap policy is extracted to the unit-testable effectiveDownloadCap. Tests: assets.test.ts (pure helpers), downloads.test.ts + engine-download.test.ts (a wrapper around the real downloadToFile reads the applied cap; downloads.test.ts pins the 40 GiB chat and 4 GiB embeddings ceilings) security-model §D3 (F17)

Posture held (Phase 4): offline / no telemetry / no new network egress / no new IPC channel. The only schema-adjacent change is an additive role: ModelRole field on the internal ModelDownloadTask (set from the manifest; the DIY fetch-* scripts don't use the TS type). Three new localized i18n keys (main.audit.locked/main.settings.locked/main.models.locked) added to en + de. The new size-cap constants live in assets.ts (the canonical reference module). Every fix is test-first with genuine teeth — the generalized lock test reddens if any module's requireUnlocked() is removed; the SSRF and size-cap tests red on the pre-fix code. Open (later phases): F11–F13/F18/F19 RAG/perf/concurrency (Phase 8), F20–F24 renderer a11y/lifecycle (Phase 6), D1–D8 docs (Phase 7), T1/T2/T6/T7/T8 test seams (Phase 5; T3 now subsumed by F16's generalized lock test); the §26-carried SEC-1 (code half) / SEC-2 / SEC-3 remain deferred to their own phase.

§31 Full audit (2026-06-29, post-merge) — remediation ledger (Phase 5 — test-enforcement seams)

Phase 5 is TEST-ONLY — it closes the seams where a security/reliability control is correct today but no test proves it stays wired (a silent unwiring would redden nothing). Branch audit-postmerge-phase5-test-seams (suite 2518 passed / 39 skipped, typecheck + build green). git diff src/ is empty — the only source edits were the temporary teeth-check neuters, each restored byte-identical. Every new/strengthened test is teeth-checked: neuter the guarded control → the test reds → restore. The disposition for each is in the "Test-enforcement seams" record below (extended with a Phase-5 subsection); resolve a full-audit-2026-06-29-postmerge T<n> code comment through that record. T4/T5 landed in Phase 1; T3 was subsumed by F16 (Phase 4).

Finding(s) Phase Disposition (one line) Record
T1 (Med) 5 closed — the LlamaServer unit suite couldn't exercise SIGTERM-ignore→SIGKILL escalation (its FakeChild.kill() exits on ANY signal, so stop() always settled on the "exited" branch). New sidecar.test.ts test with a stubborn child (records each signal, dies only on SIGKILL) asserts signals == [undefined,'SIGKILL']. Teeth: revert the line-576 gate this.exited → child.killed → SIGKILL dropped → reds "Test-enforcement seams" (T1)
T2 (Med) 5 closed — the resident-cache lock-PURGE (RAG-6 SECURITY requirement) was proven only at the unit tier, never that the lock IPC calls it. workspace-ipc.test.ts now seeds a real resident map, locks, and asserts purgeResidentVectors fired against the LIVE db (spy delegates to the real impl, shared caches). Teeth: drop the purge call from the lock handler → spy 0× → reds "Test-enforcement seams" (T2)
T6 (Low) 5 closed (de-flake) — the GPU-probe timeout test awaited a real 20 ms setTimeout (a TEST-1-family wall-clock flake). Converted to fake timers (vi.advanceTimersByTimeAsync, the combine-signals idiom) with an injected trivial verify; the kill-on-timeout assertion is preserved. Teeth: neuter the timeout child.kill('SIGKILL') → child.killed stays false → reds "Test-enforcement seams" (T6)
T7 (Low) 5 closed (de-flake) — the privacy-guard snapshot poll was an iteration-capped for(i<50){sleep(5)} (TEST-1 sibling). Converted to vi.waitFor (the picker-seams idiom) — re-polls until the run settles, no fixed cap. The no-secret-in-snapshot assertions are preserved. (The optional vision-runtime.test.ts real-timer copies were left as-is — converting them needs the fakeClock seam, out of scope for a quick nit) "Test-enforcement seams" (T7)
T8 (Low) 5 closed — the crash-fallback test counted a monkey-patched stop() wrapper (made[0].stops===1), which still holds if stop() stops reaching the child kill (orphan). runtime-manager.test.ts now also pins the REAL reap on observable child state: a final mgr.stop() + children[1].child.killed===true (the LIVE restarted child is genuinely killed). DIVERGED from the audit's literal "crashed child killed===true" — the crashed child already exited, so stop() correctly early-returns before any kill (its killed stays false; asserting true would red on correct code). Teeth: early-return stop() before the kill → the live child's killed stays false → reds "Test-enforcement seams" (T8)
T3 (Med) 4 verified subsumed — ipc-lock-coverage.test.ts (F16) drives registerRagIpc against a locked ctx with NO exemptions, so rag:ask is enumerated and asserted to reject with the localized lock copy. No separate Phase-5 test added §30 (F16); "Test-enforcement seams" (T3)
T9 (Low, nit) 1/5 partially closed — invoice negative line totals / Gutschrift/Rabatt were pinned in Phase 1; the AES-GCM truncated (length-reduced) ciphertext case is added at the crypto.ts unit tier (crypto.test.ts, one assertion — distinct from the existing bit-flip cases). The BANK_EXTRACTOR_VERSION tautological-tripwire and the mock-embedder score-band nits are left as accepted "Test-enforcement seams" (T9); arch §8 (Phase 1 T9)

Posture held (Phase 5): no src/ behavior change — nothing shipped changed, so no behavior-doc change. Test-only. The de-flake conversions (T6/T7) removed two real-wall-clock waits (verified stable across repeated runs); the wiring proofs (T1/T2/T8) each redden on a one-line neuter of the control they guard. Open (later phases): F11–F13/F18/F19 RAG/perf/concurrency (Phase 8), F20–F24 renderer a11y/lifecycle (Phase 6), D1–D8 docs (Phase 7); the §26-carried SEC-1 (code half) / SEC-2 / SEC-3 remain deferred.

§32 Full audit (2026-06-29, post-merge) — remediation ledger (Phase 6 — renderer accessibility + lifecycle consistency)

Phase 6 closes the renderer cluster F20–F24 — frontend accessibility + effect-lifecycle consistency. Renderer-only (plus one test file / case per finding); no IPC surface, no main-process behavior, no new user-facing copy (so no i18n catalog change). Branch audit-postmerge-phase6-frontend-a11y (suite 2523 passed / 39 skipped, typecheck + build green). The FE-4 reconciliation is folded into the "Renderer robustness" record (FE-4 bullet, below); resolve a full-audit-2026-06-29-postmerge F2<n> code comment through this ledger. Test-first where observable in jsdom (F20/F21/F22 each red on current code → green).

Finding(s) Phase Disposition (one line) Record
F20 (Med, a11y) 6 fixed — the first-run gate swaps the entire card per phase; focus is now steered to each step's primary control via useEffect(…, [phase]) (WorkspaceGate.tsx — password input on password, Skip on finishing, primary action on starter; the welcome CTA keeps its mount-time autoFocus). PasswordField gained an inputRef prop (mirroring Composer's pattern). DIVERGED from the audit's framing — the audit called welcome → password the critical gap, but that field already carried autoFocus (the new test is green there pre-fix); the real deterministic gap was the finishing step (no focus target at all → focus reset to <body>), which the new test reds on pre-fix. The effect also makes every transition re-entry-safe (autoFocus fires only on first mount). WCAG 2.4.3 / 3.2.2 arch §32; WorkspaceGateFocus.test.tsx
F21 (Low, privacy/lifecycle) 6 fixed — DictationButton.start() assigned captureRef only AFTER await getUserMedia, so unmounting while the OS mic prompt was open ran the cleanup first (nothing to release), then stored a LIVE MediaStream on the dead component and never .stop()d it (OS recording indicator stayed lit). A mountedRef (mirroring ChatScreen/DocumentsScreen) now cancels the just-acquired capture and skips onRecording when unmounted. Teeth: Dictation.test.tsx resolves an injected capture AFTER unmount → asserts cancel() fired + recording was never entered arch §32; "Renderer robustness" FE-4
F22 (Low, lifecycle) 6 fixed — ModelsScreen was the lone FE-4 hold-out: its download/engine poll callbacks ran setJob + (on a live→terminal transition) void refresh() with no mounted guard, and the DiagnosticsTab loadActivity/loadMoreActivity refreshers (listed as guarded but weren't) ran setEvents/setMoreAvailable ungated. Both now carry the mountedRef guard, so the architecture's "FE-4 applied uniformly" claim now genuinely holds. Teeth: ModelsScreenUnmount.test.tsx parks a getDownloadJob tick, unmounts, resolves it → asserts no extra listModels (no refresh on a dead component) arch §32; "Renderer robustness" FE-4 (narrowed)
F23 (Low, a11y) 6 fixed — the StreamAnnouncer live region carefully feeds only newly-completed sentences into a role="log" aria-live="polite" region, but aria-atomic="true" told the AT to re-read the ENTIRE region on every change (re-announcing prior sentences; double-speak on fast boundaries). Dropped aria-atomic (role="log" defaults to atomic=false); the sentence-slicing is untouched. StreamAnnouncer.test.tsx pins not aria-atomic="true" arch §32; StreamAnnouncer.test.tsx
F24 (Low, lifecycle nit) 6 fixed — Composer.insertDictation's non-execCommand fallback (jsdom / future removal) deferred caret restoration via an untracked setTimeout(…, 0). Now tracked in a ref and cleared on unmount (consistency with FE-7/FE-1 timer cleanup). Benign in real Electron (execCommand succeeds there), so this is consistency-only; the Dictation insert-at-caret test still passes arch §32

Posture held (Phase 6): offline / no telemetry / no new network egress; renderer-only; no IPC channel, main-process, schema, or i18n-catalog change; the content class is untouched (no logging/audit/export surface added). No happy-path regression — the mic capture (F21), the streaming announcer slicing (F23), the poll-driven refresh (F22), and the dictation caret-restore (F24) all still work (their existing suites stay green). Every lifecycle guard reuses the existing mountedRef idiom (ChatScreen/DocumentsScreen/ DiagnosticsTab), not a new discipline. Open (later phases): F11–F13/F18/F19 RAG/perf/concurrency (Phase 8), D1–D8 docs (Phase 7); the §26-carried SEC-1 (code half) / SEC-2 / SEC-3 / REL-5 / PERF-5 Part B / E5-prefix remain deferred.

§33 Full audit (2026-06-29, post-merge) — remediation ledger (Phase 7 — documentation reconciliation)

Phase 7 is docs- and code-comment-only — no behavior change (git diff shows only .md/.yaml files and code COMMENTS; no src/ logic edit). It reconciles the §3 documentation findings D1–D8 to a single source of truth, carries the F11/F13 as-built realities into the topic docs, and re-runs the §-anchor sweep. Branch audit-postmerge-phase7-docs. The audit report stays (Phase 8 retires it).

Finding(s) Phase Disposition (one line) Record
D1 (Med) 7 fixed (docs) — the TEST-6 record claimed the S13b skill-trigger precision bar was "owner-gated on D1 / not yet landed"; it is in fact a live CI gate (skill-triggers.test.ts asserts fired-wrong == 0 AND precision ≥ 0.95, re-verified live). Corrected the §27 ledger row + the "Test-enforcement seams" TEST-6 record + the BUILD_STATE TEST-6 bullet: the bar IS asserted; the remaining no-CI-floor gap is narrower — real-model RAG answer quality + the env-gated quality benchmarks arch TEST-6 record + §27 row; BUILD_STATE
D2 (Med) 7 fixed (docs) — known-limitations.md claimed the in-app downloader "drives only tasks[0] (the GGUF)"; the code fetches both GGUF + mmproj as one job (DIST-1, assets.ts planModelDownloads; downloads.test.ts asserts totalBytes == gguf + mmproj + the finish-just-the-projector case). Rewrote the limitation to the as-built reality; user-guide §8 / troubleshooting carry no contradicting claim known-limitations.md (image-understanding)
D3 (Med) 7 fixed (docs) — reconciled the reranker "never bundled by default" contradiction to ONE story: the reranker IS in the DIY prepare-drive --with-assets default fetch set (README/packaging/drive-layout — correct, unchanged), but is flagged bundled_on_preconfigured_drive: false (advisory/unused by the validator) as the intent for a sold/commercial preconfigured drive. Fixed the phrasing in model-policy.md, rag-design.md §12.3, and the reranker manifest comment. The vision "never bundled by default" was left — it is genuinely NOT in --with-assets (opt-in, true) model-policy.md; rag-design §12.3; reranker manifest
D4/D5/D6 (Low) 7 fixed (comments) — four stray test-comment fragments cleaned: gpu-smoke.test.ts "60 s health timeout" → 180 s (DEFAULT_HEALTH_TIMEOUT_MS); dropped the dangling /§11.1 from gpu.test.ts (→ §5.1) and runtime-ladder.test.ts (→ §5.2) and the dangling /§9 from assets.test.ts (→ §6). The GPU design record is §1–§8; §9/§11.1 never existed (benchmark.test.ts was already fixed by DOC-4) code comments → GPU record §5.1/§5.2/§6 + sidecar DEFAULT_HEALTH_TIMEOUT_MS
D7 (Low) 7 fixed (docs) — reconciled the whisper RTF figures to two annotated regimes matching the R-W3/R-W4 source measurements: a long sustained file ≈ RTF 0.67 (real-time÷1.5 / two-thirds; R-W4 52-min → 35 min, user-guide 30-min → 20-min) and a short clip ≈ RTF 0.46–0.5 (R-W3 benchmark clips + dictation). Annotated the short-vs-long distinction in known-limitations.md (audio + dictation) and the whisper manifest comment so the figures no longer read as contradictory known-limitations.md; whisper manifest
D8 (Low) 7 fixed (docs) — clarified README disk-space: the ~3 GB figure is the hand-built minimal footprint (4B + embeddings only); the one-command --with-assets quick-start default set (8B + embeddings + reranker + Whisper + both runtimes) is ~7 GB, so a user sizing a drive from the 3 GB line does not under-provision README.md
F11 (doc-note) 7 recorded (docs) — rag-design §14.4: a mode:'tree' answer's [Sn] citations are whole-document LEAF PROVENANCE (documentLeafProvenance, up to ~1000 leaves), NOT the 1:1 inline-grounded excerpts of the generateGroundedAnswer contract (the tree prompt carries no [Sn] markers). A deliberate coverage choice; differentiating the renderer presentation is the Phase-8 follow-up — recorded as a known distinction rag-design §14.4
F13 (doc-note) 7 recorded (docs) — rag-design §12.1 R3: added a one-line PRECONDITION that re-enabling a positive ragMinSimilarity floor (a goal of the deferred E5 query:/passage: prefix migration) MUST first move the floor before the topKInitial cut — rag/index.ts applies it after the cut today, so a positive floor would silently lose recall. Coupled to that migration phase rag-design §12.1 R3

§-anchor sweep (re-run, Phase 7). Swept every § citation in docs/**, README.md, BUILD_STATE.md, and the apps/desktop/{src,tests} comment tree. The §27–§32 post-merge ledgers (Phases 1–6) exist, are consecutively numbered, and the named-record citations they added (GPU record §5.5b, §22-D1 honesty posture, security-model D3, the "Chat & streaming" / "encrypted log" / "Renderer robustness" / "Test- enforcement seams" records) all resolve. Residuals fixed: the four D4/D5/D6 fragments above, plus one pre-existing dangler the independent sweep surfaced — image-understanding plan §16 (cited in vision-runtime.test.ts / vision-smoke.test.ts) was missing from the image-understanding §-anchor legend; added a legend row mapping plan §16 → §6 (V4/V5 runtime hardening) + model-benchmarks §8. Result: clean — every § citation now resolves.

Posture held (Phase 7): offline / no telemetry; no src/ LOGIC change (docs + code-comments only); typecheck + npm test + npm run build re-run green to confirm the comment edits broke no source-grepping test. Open (Phase 8, the close-out): F12/F18/F19 + the F11 renderer half, then retire this audit report.

§34 Full audit (2026-06-29, post-merge) — remediation CLOSE-OUT

The post-merge full audit (report audits/full-audit-2026-06-29-postmerge.md) is COMPLETE — all eight phases landed. Its pattern was "the fix exists next door but wasn't applied here": the prior round (§26) hardened the bank parser and the chat runtime, and this pass found the invoice parser, the embedder/reranker sidecars, and the regenerate path had not received the sibling hardening. No Critical, no remote exploit (offline by construction); 1 High (F1), ~9 Medium, ~13 Low, 9 test-seam items (T1–T9), 8 doc items (D1–D8). Each phase folded its decisions into the topic docs as it landed (the per-phase ledgers §27–§33, plus the named records); this section is the durable master index — resolve a full-audit-2026-06-29-postmerge <ID> code comment through it. The working-paper report was retired under the CLAUDE.md doc-lifecycle rule once every finding was dispositioned (it was committed first, so the original stays recoverable in git history — the parent of the Phase-8 close-out commit), mirroring the §24/§25/§26 precedent. Phases ran on stacked, unmerged branches (audit-postmerge-phase1-money … phase8-closeout); owner merges when ready.

Per-phase one-liners: P1 money-parser correctness (F1/F3/F6/F8 + the invoice single-currency guard + the T5 2-dp invariant; §27, §8). P2 runtime reliability (F2 regenerate data-loss / F4+F7 bind-race start-latch / F9 compaction log; §28). P3 invoice lifecycle parity (F5 reuse/replace/ staleness; §29). P4 security consistency (F15 mapped-IPv6 SSRF / F14 log-buffer-on-lock / F16 IPC lock-guard parity — subsumes T3 / F17 download caps; §30). P5 test-enforcement seams (T1/T2/T6/T7/T8 + T9; §31, test-only). P6 renderer a11y + lifecycle (F20–F24; §32, renderer-only). P7 docs reconciliation (D1–D8 + F11/F13 doc-notes; §33, docs/comments-only). P8 (this close-out) the low-hangers F12/F18/F19 + report retirement.

Finding(s) Phase Disposition (one line) Record
F1 (High) 1 fixed — uncaptured amount column read the running BALANCE as the amount; bank flags ambiguousAmount + drops only when a balance column exists (statement-context-aware — DIVERGED from the literal unconditional drop, which regressed the HVB no-balance format); invoice mirror drops the right-side uncaptured column §27; §8 (F1); known-limitations
F3 (Med) 1 fixed — invoice per-line detectCurrency scans only the figure region + validateInvoiceTotals single-currency guard (the BL-2 fix applied to invoices) §27; §8 (F3)
F6 (Med) 1 fixed — geometry-less invoice space-grouped token w/o a 2-dp tail dropped (isFusedSpaceGroup) §27; §8 (F6)
F8 (Low) 1 fixed — invoice qty split requires a unit token or a corroborating unit-price column §27; §8 (F8)
F10 (Low) 1 acknowledged (no code) — invoice path runs without geometry (D58 = bank-only); its robustness was prioritised since it has no backstop §27; §8
F2 (Med) 2 fixed — regenerate delete deferred INSIDE withChatStream (withRegenerateGuard) + byte-faithful restore on non-abort failure; both chat + RAG channels §28; "Chat & streaming"
F4 (Med) 2 fixed — embedder start-latch skips arming on isBindRaceError (a transient double-bind-race no longer silently disables imports) §28; GPU §5.5b
F7 (Low) 2 fixed — same bind-race exclusion for the reranker (makes the keep-latch-across-suspend() policy correct) §28; GPU §5.5b
F9 (Low) 2 fixed — compaction.ts catch {} now log.warns the non-abort case (no chat content); abort stays silent §28; "Chat & streaming"
F5 (Med) 3 fixed — invoice reuse/replace/staleness parity with bank (extractor_version + isInvoiceStale + replaceExisting atomic swap) §29; §8
F15 (Low→Med, SSRF) 4 fixed — isPrivateOrLoopbackHost denies any ::ffff: host (the mapped-IPv6 form new URL() canonicalizes to) §30; security-model §D3
F14 (Low) 4 fixed — detachVaultKey() zeroes the log buffer after the final encrypted flush (option a; next unlock repopulates) §30; security-model "encrypted log"
F16 (Low) 4 fixed — localized requireUnlocked() on rag/audit/settings/model + generalized ipc-lock-coverage.test.ts (subsumes T3); §25 wording corrected §30; §25 inventory
F17 (Low) 4 fixed — both downloaders always pass a bounded cap (engine 2 GiB; model exact-size or per-role default); backstop 64→48 GiB §30; security-model §D3
T1 (Med) 5 closed (test) — LlamaServer unit SIGKILL-escalation test (stubborn child); teeth-checked §31; "Test-enforcement seams"
T2 (Med) 5 closed (test) — resident-cache lock-purge wiring asserted at the IPC layer against the live db §31; "Test-enforcement seams"
T3 (Med) 4 subsumed by F16 — ipc-lock-coverage.test.ts enumerates rag:ask against a locked ctx §30 (F16); §31
T4 (Med) 1 addressed — parens-negative pinned through the real extractTransactionRows §27; §8
T5 (Med) 1 fixed + pinned — parseAmount rounds to the nearest cent (the 2-dp integer-cent invariant) §27; §8
T6 (Low) 5 closed (de-flake) — GPU-probe timeout → fake timers; teeth-checked §31
T7 (Low) 5 closed (de-flake) — privacy-guard poll → vi.waitFor §31
T8 (Low) 5 closed (test) — crash-fallback pins a REAL child reap (DIVERGED: the crashed child already exited) §31
T9 (Low nit) 1/5 partially closed — invoice negative totals/Gutschrift (P1) + AES-GCM truncated-ciphertext (P5); the tautological-tripwire + mock score-band nits accepted §31; §8
F20 (Med, a11y) 6 fixed — first-run gate steers focus per phase (the finishing step had none — DIVERGED from the welcome→password framing) §32
F21 (Low) 6 fixed — DictationButton cancels a mic capture acquired after unmount (mountedRef) §32
F22 (Low) 6 fixed — ModelsScreen polls + DiagnosticsTab refreshers join the FE-4 mountedRef discipline §32; "Renderer robustness"
F23 (Low, a11y) 6 fixed — StreamAnnouncer drops aria-atomic (additive role="log" reads only the new sentence) §32
F24 (Low) 6 fixed — Composer fallback caret timer tracked + cleared on unmount §32
D1–D8 (Med/Low, docs) 7 fixed (docs) — D1 TEST-6 record corrected (S13b IS a live CI gate) · D2 downloader fetches GGUF+mmproj · D3 reranker bundling reconciled · D4/D5/D6 four stray comment fragments · D7 whisper RTF two regimes · D8 README disk sizing §33
F11 (Low) 7 / — doc-note recorded (P7); renderer half NOT taken (P8) — the mode:'tree' answer's [Sn] are whole-document leaf provenance, not inline-grounded excerpts (rag-design §14.4); differentiating the renderer presentation stays the carried-forward follow-up (the documented distinction stands) §33; rag-design §14.4
F12 (Low, perf) 8 fixed — the resident-cache reconcile's O(N) SELECT chunk_id scan is gone for the in-band paths: the three write sites pass named added/removed chunk_ids → delta fast path (decode only the new rows, no scan), with a Map.size === COUNT(*) gate falling back to the full scan (delta-less / out-of-band / wrong delta) — byte-identical to a cold rebuild (PERF-1 contract). Bench leg added this ledger; Performance/Wave-P4 record
F13 (Low, latent) 7 / — doc-note recorded (P7); code carried forward — re-enabling a positive ragMinSimilarity floor must first move it BEFORE the topKInitial cut; coupled to the deferred E5 query:/passage: prefix migration (inert at the pinned default 0) §33; rag-design §12.1 R3
F18 (Low, concurrency) 8 fixed — VisionService terminal done write routes through the cancelled-guarded set() (returns whether applied) so a concurrent cancel isn't overwritten / re-emitted. Latent (no await before it today); dual-neuter teeth-check recorded this ledger; Image-understanding §5
F19 (Low, concurrency) 8 fixed — tearingDown flag (the suspend() analogue of stop()'s stopped) bars a racing ensureStarted from spawning a sidecar that would survive the lock; both embedder + reranker; deterministic interleave teeth-test this ledger; GPU §5.5c

Carried-forward open items (deliberately NOT taken; on record for the next pass):

  • F11 renderer half — present mode:'tree' answers as whole-document provenance (or cap the persisted leaf list) rather than identically to inline-cited answers. The doc-note (rag-design §14.4) is the current truth; the renderer change was scoped out of Phase 8 (non-trivial vs the Low severity).
  • F13 code (floor-before-cut) — a precondition of the deferred E5 query:/passage: prefix migration (its own phase): re-enabling a positive ragMinSimilarity floor must over-fetch then floor, or push the floor into the scan. Inert today (floor pinned at 0).
  • §26-carried (re-verified, still valid): SEC-1 code half (unlock rate-limit/attempt-counter + create-time strength meter — the at-rest KDF is the binding mitigation against the offline attacker, so a UI rate-limit doesn't bind the real threat); SEC-2 (preview-temp staging under userSkillsDir); SEC-3 (dialog-opener capability tokens inert until the consuming requireUnlocked() gate; closed 2026-10-14 by #681, every picker now gated); REL-5 (BEGIN IMMEDIATE + a single withTransaction guard — the no-await-in-txn invariant re-verified true at every BEGIN site, so a defense-in-depth margin, its own characterized phase); PERF-5 Part B list windowing — documents-list half now CLOSED (follow-up Phase 4 / PERF-2; see §36); the chat transcript half remains (Diagnostics activity is a lower-volume secondary target) + the E5-prefix migration.

Posture held across all eight phases (load-bearing): offline / no telemetry / no new network egress; no schema change beyond the single additive nullable invoices.extractor_version (P3) + the internal ModelDownloadTask.role field (P4); content class (document/chat text, extracted figures, redacted text) never logged/audited/exported. Behavior-preserving: every behavioral fix (P1/P2/P3/P4/P6/P8) is teeth-checked (neuter the guard → red → restore byte-identical); P5 was test-only (git diff src/ empty); P7 was docs/comments-only. The F12 byte-equivalence + signature backstop + lock-purge, the vision cancel semantics (F18), and the stop()/suspend() teardown semantics (F19) are all preserved. Final suite 2532 passed / 39 skipped (2571 collected); typecheck + npm run build green.

§35 Full audit (2026-06-29, follow-up) — Phase 3 (main-thread import I/O + parser memory caps; PERF-1 / PERF-4)

The follow-up audit (audits/full-audit-2026-06-29-followup.md) found the gaps had moved outward from the fortified core into main-thread I/O. Phase 3 removes the synchronous import freeze (PERF-1) and turns an oversize-text OOM crash into the existing friendly reject (PERF-4). Both are behavior-class fixes with no schema / IPC / audit-payload change; the encrypted-at-rest guarantee and the exact on-disk vault frame are preserved byte-for-byte. Suite 2559 passed / 39 skipped (was 2551/39 → +8: PERF-4 ×4 + PERF-1 async-crypto ×4); typecheck + npm run build green.

  • PERF-1 (High) — async document-cache crypto on the import path. The document-import / re-index / preview / OCR-read path encrypted/decrypted the stored copy through a fully synchronous readSync / writeSync + cipher.update chunk loop on the Electron main thread — multi-second on a large scanned PDF over USB, paid twice in an encrypted workspace (encrypt-on-store + decrypt-to-parse), freezing the UI/IPC and starving the embedder sidecar. FIX: added async siblings encryptFileAsync / decryptFileAsync in workspace-vault.ts — the SAME streaming AES-256-GCM loop on fs.promises FileHandles, awaiting each 8 MiB chunk read/write so the event loop runs between chunks (GCM update on a chunk is sub-ms — per-chunk yielding suffices, no worker thread). They write/read the byte-identical frame (MAGIC | iv | tag-placeholder | ciphertext, the GCM tag positionally patched into its reserved slot at tagPos after final()), cross-verified so a file written by either flavour decrypts with the other (and the in-memory blob path). The DocumentCipher gained encryptFileAsync/decryptFileAsync; the three already-async import callers (ingestion processDocument ×3, extractDocumentPreview, doctasks readStoredPdfBytes) now await them, and the plaintext copy went copyFileSync → await fs.promises.copyFile.
    • DIVERGENCE from the audit's "convert the vault loop" wording (deliberate, mechanically-correct). Rather than make the shared encryptFile/decryptFile async in place — which cascades into the DB-.enc lock/unlock/create/rekey lifecycle, the synchronous crash-only lock (the uncaughtException handler must re-encrypt the working DB before process.exit; an async lock can't finish first → committed in-session data would be lost), and the synchronous vision streaming emitter (createImageSession is reached through a non-awaitable emit.done) — i.e. the highest-stakes, most-tested code, with the real vault-corruption blast radius the audit itself flagged in its CRITICAL RISK note — we added async siblings used only by the actual per-import harm. The session-boundary DB lifecycle (unlock decrypts the whole DB once per session; lock once on lock/quit — NOT "every import") and the bounded, sync-reached paths (image-history via the vision emitter; text export) stay on the synchronous functions. Net effect: the PERF-1 "freeze on every import" is gone; the once-per-session unlock/lock decrypt freeze is an available follow-up (adopt the async siblings there once the crash-lock keeps a synchronous path — encryptFile is retained for exactly that).
      • SUPERSEDE (audit 2026-07-16 F-12, 2026-07-17): the "image-history via the vision emitter stays on the synchronous functions" carve-out above is retired. That path stored/opened/deleted the full image (~60 MiB of sync fs+crypto+shred for a 20 MiB image on an encrypted vault) on the main thread AT the answer-complete moment — the finding's seconds-scale USB freeze. The vision history (vision/history.ts) now uses encryptFileAsync/decryptFileAsync + fs.promises + a new shredFileAsync twin, and the analyze handler awaits ensureSession before firing done (so sessionId still rides the done event — the renderer's follow-up contract). Only the crash-lock / export / DB-lifecycle callers remain on the sync encryptFile/shredFile. Dev-box measurement (local SSD, 16 MiB encrypted store, monitorEventLoopDelay): main-thread stall mean 22.4 ms → 3.4 ms, max ~95 ms → ~24 ms per store; a real USB-stick + encrypted-workspace run was not reproducible on the dev box (the target medium's stall scales with (2–3×size)/throughput, so the win is proportionally larger there).
  • PERF-4 (Medium) — string-safe byte cap for the read-whole-file-to-string formats. The text / Markdown / CSV parsers materialize the file as one UTF-16 JS string (CSV then derives the papaparse row array + the rebuilt lines.join ≈ 3 full copies at once), so a file approaching the generous 1 GiB maxBytes exceeds V8's ~512 MB string/heap ceiling and OOM-crashes the main process instead of producing the friendly fileTooLarge reject. FIX: a new textMaxBytes ceiling (default 64 MiB, env HILBERTRAUM_TEXT_MAX_BYTES)
    • a readsWholeFileToString flag on the txt/markdown/csv parsers; effectiveMaxBytes(title, limits) narrows the existing pre-parse byte checks in processDocument to that ceiling for those formats only — so an oversize text/CSV file hits the unchanged friendly reject, while the streaming / page-bounded formats (PDF/DOCX/audio/image) keep the full maxBytes. Streaming parse remains the better long-term fix; the cap is the safe win (recorded in known-limitations).
Finding Sev Disposition (one line) Record / files
PERF-1 High fixed — async encryptFileAsync/decryptFileAsync (FileHandle, per-chunk yield, byte-identical frame) on the document-import path; copyFileSync → async copyFile. DIVERGED: added async siblings instead of converting the shared sync functions (DB lifecycle + crash-lock + vision emitter stay sync). Teeth: a non-yielding neuter reddens the event-loop-yield test while the frame-identity tests stay green this §35; workspace-vault.ts, ingestion/index.ts, doctasks/manager.ts; known-limitations
PERF-4 Med fixed — textMaxBytes (64 MiB) + readsWholeFileToString flag + effectiveMaxBytes narrows the pre-parse byte cap for txt/markdown/csv → friendly fileTooLarge reject, not an OOM crash. Format-scoped (PDF keeps full maxBytes). Teeth: neuter the narrowing → the over-cap .txt/.csv tests redden this §35; ingestion/limits.ts, parsers/{index,txt,markdown,csv}.ts, ingestion/index.ts; known-limitations

Posture (load-bearing): offline / no telemetry / no new network egress; encrypted-at-rest + the exact on-disk vault frame preserved (cross-read tests pin sync↔async equivalence + GCM auth on tamper); content class never logged. Behavior-preserving: both fixes are teeth-checked (neuter → red → restore byte-identical). Branch audit-followup-phase3-import-io (unmerged; do NOT auto-merge/push).

§36 Full audit (2026-06-29, follow-up) — Phase 4 (documents-list scale; PERF-3 / PERF-2; PERF-6 deferred)

Phase 4 removes the two ways the documents screen got slower with library size: a hot-path DB parse (PERF-3) and unbounded list DOM (PERF-2 = the long-deferred PERF-5 Part B). One additive nullable column; no IPC / audit-payload change; an old on-disk workspace opens cleanly. Suite 2568 passed / 39 skipped (was 2559/39 → +9: PERF-3 ×7 + PERF-2 ×2); typecheck + npm run build green (the new renderer dep bundles offline — no runtime fetch).

Note (location, as of DX-3 — follow-up Phase 8, §38): the behavior claims below are current, but DocumentsScreen.tsx was subsequently split into screens/documents/* (DocRow, SectionRail, PreviewModal, format.tsx, types.ts) — a behavior-preserving relocation; the windowing described here is intact (the DocRow React.memo lives in screens/documents/DocRow.tsx now; the __docRowRenderCounts seam was retired in 2026-10 — the PERF-5 tests count renders test-side, tests/helpers/render-counter.ts).

  • PERF-3 (Medium) — listDocuments no longer parses the full ocr_json blob per OCR'd row. DB-8 (§ Performance Wave P5) projected columns on the single-doc getters, but the list path still did SELECT * and fully JSON.parsed every row's ocr_json — reconstructing pages[] with every page's text — only to read pageCount/languages/engineId/createdAt for the OCR badge. At a library of large scans that is a megabytes-scale parse + a 10⁵-object array allocation on the main thread, on every documents-screen mount / import-completion / collection change. FIX: a cheap, additive, nullable documents.ocr_meta_json sidecar holding ONLY the badge metadata (a serialized DocumentOcrInfo — counts/ids/languages, never page text). Written alongside ocr_json at OCR-write time (setDocumentOcr, lock-step: one statement writes both), and backfilled once at openDatabase for rows imported before the column existed (reads each blob ONCE, extracts meta, writes the sidecar; FK/lifecycle- safe; updated_at untouched; subsequent opens select zero rows). listDocuments now SELECTs an explicit narrow column set that omits ocr_json and reads the badge via ocrInfoForRow from the sidecar (with a one-shot parseOcr(ocr_json) fallback the list path never reaches — its projection omits the blob AND the backfill runs first). The meta extractor (ingestion/ocr-meta.ts — ocrMetaFromJson / parseOcrMeta) is a leaf module (type-only import) so db.ts uses it for the backfill without a db → ingestion cycle, and the page-count semantics (count only well-formed pages) match parseOcr exactly. Measured (50 docs × 2000 pages × 500 chars, ~50 MB OCR text): the per-call ocr_json read+parse the projection removes costs **147 ms in isolation**; the projected listDocuments runs in ~55 ms — and the megabytes-scale string + ~10⁵-object allocation per call is eliminated.
  • PERF-2 (High at scale; = PERF-5 Part B, documents-list half) — the documents list is windowed. Every document mapped to a live, memoized-but-never-unmounted DocRow, each mounting a Radix DropdownMenu.Root — so the DOM and the count of menu-root state machines grew linearly with the library (hundreds of mounted roots at scale, on CPU-only hardware). FIX: @tanstack/react-virtual (a pure-JS, no-native, build-time dep — Vite bundles it; no runtime network call). The documents screen scrolls as a whole inside the app's .content container, so the list virtualizes against that existing scroll element with a scrollMargin for the header/hints above it — additive, the full-screen scroll behavior is unchanged (no inner-pane restructure that would alter scroll position / scroll-to). Variable row height (a failed-import error banner, a stale-embeddings notice, a wrapping chip cluster — .doc-row is min-height: 56px, not fixed) is handled by per-row measureElement over a 57px estimate + overscan, so a taller row self-corrects. The DocRow React.memo is untouched (its render counts have been read test-side since 2026-10, tests/helpers/render-counter.ts); a shared renderRow keeps the windowed and fallback paths' props wiring in one place.
    • GATING (truthful, not a test sniff). Windowing engages only once a real, laid-out viewport is resolved (scrollEl != null && clientHeight > 0). With no .content ancestor or a 0px viewport — a unit test rendering the screen standalone under jsdom, or first paint before layout — there is nothing to virtualize, so it falls back to rendering every row, byte-identical to the pre-PERF-2 list. A 0px viewport genuinely can't be windowed; the guard is honest, and it keeps the existing DocumentsScreen test corpus on the un-windowed path while a dedicated test drives the real windowed path (mocking the viewport's clientHeight and the rows' offsetHeight, which react-virtual measures, not getBoundingClientRect; before virtual-core 3.19 it read the viewport's offsetHeight too).
    • KNOWN TRADEOFF (recorded in known-limitations.md): the browser's find-in-page (Ctrl+F) can't match a row that isn't currently mounted. Acceptable for a name-scannable library list (the in-app section/smart- view filters search the full set); deliberately not applied to the chat transcript.
  • PERF-6 (Low) — DEFERRED with cause. Moving OCR pages from the one ocr_json blob to a per-page child table is the clean root-cause fix for PERF-3, but it is a larger schema migration (backfill existing blobs into child rows, FK/CASCADE lifecycle, the re-index-reuse + doctasks write paths). PERF-3's metadata sidecar already removed the hot-path parse (the actual harm), so the child table is left as its own future phase rather than forced into this one.
Finding Sev Disposition (one line) Record / files
PERF-3 Med fixed — additive nullable ocr_meta_json sidecar (counts/ids only, never text) written at OCR-write + backfilled once at open; listDocuments projects a narrow set that omits ocr_json and reads the badge from the sidecar. Measured ~147 ms blob-parse removed per call. Teeth: revert the projection to SELECT * → the SQL-omission test reddens this §36; db.ts, ingestion/index.ts, ingestion/ocr-meta.ts; tests/integration/ocr-meta-list.test.ts
PERF-2 High@scale fixed (documents list) — @tanstack/react-virtual windows the list against the .content scroll element (scrollMargin + per-row measureElement); gated on a resolved non-zero viewport (else render all). Teeth: force windowed = false → the bounded-count test reddens. Chat transcript half stays deferred this §36; DocumentsScreen.tsx, package.json; tests/renderer/DocumentsScreen.test.tsx
PERF-6 Low deferred (cause) — per-page OCR child table is a larger schema migration; PERF-3 already removed the hot-path parse it would have addressed this §36 (own future phase)

Posture (load-bearing): offline / no telemetry / no new RUNTIME network egress (the virt lib is a build-time dep, bundled, verified no .node binary); the schema change is additive + nullable and opens old workspaces cleanly (backfill on first open); content class (OCR page text) is never materialized on the list path nor placed in the sidecar/logs/export. Branch audit-followup-phase4-docs-scale (unmerged; do NOT auto-merge/push).

§37 Full audit (2026-06-29, follow-up) — Phase 6 (reliability hardening; REL-1 / REL-2 / REL-3 / REL-4)

Phase 6 closes four latent concurrency/teardown gaps in the sidecar lifecycle. None is a live bug today — each mirrors a race class already fixed elsewhere (the F19 tearingDown family; the lock-path stream-abort ordering) — so this is defense-in-depth, proven by teeth-checks (neuter the guard → the deterministic interleave test resurrects the race and reddens → restore byte-identical). No IPC / schema / audit-payload change; behavior-preserving (the robust paths the audit confirmed CLEAN — single-flight start, bind-race retry, SIGTERM→SIGKILL escalation, the VisionRuntime idle interlock, the e5/reranker F19 latch, combineSignals cleanup, partial-on-abort persistence — all stay green). Content class is never logged (a cancellation diagnostic carries ids + the error message only). Suite 2586 passed / 39 skipped (was 2579/39 → +7: vision-teardown ×2, OCR REL-1 ×1, e5 REL-3 ×1, shutdown REL-4 ×3); typecheck + npm run build green. Branch audit-followup-phase6-reliability (unmerged; do NOT auto-merge/push).

  • REL-2 (Low, strongest) — VisionService.stop() defeated by a run() that rebuilds the runtime during teardown. run() does this.runtime ??= createRuntime(status) after await getStatus(). VisionService (unlike the embedder/reranker, F19) had no orchestrator-level latch, and the per-VisionRuntime stopped flag doesn't help (a rebuilt runtime starts without it). FIX: a tearingDown latch on the service (not the runtime), set at the TOP of stop() and cleared in its finally; run() re-checks it at the top AND immediately after the getStatus() await — a losing run() ends cancelled, spawns nothing. DIVERGENCE / sharpened repro (recorded): the audit's "parked in getStatus()" variant is ALREADY neutralized today by the existing if (signal.aborted) check between the await and createRuntime (stop() aborts every vision controller synchronously before yielding). The genuinely-uncovered window the latch closes is a NEW analyze() that lands DURING an in-progress teardown — its controller is fresh (stop()'s abort loop ran before the job existed), so signal.aborted misses it and, without the latch, it would createRuntime a fresh ~4.6 GB vision sidecar co-resident with the vault re-encrypt. The top-of-run() latch is solely load-bearing there (single-neuter teeth-check: createCalls goes 1→2). The post-getStatus() re-check is the defense-in-depth twin (co-guarded by signal.aborted, like F18 — a dual-neuter), kept to mirror e5/reranker's post-await this.starting re-check and harden against a refactor weakening abort-propagation.
  • REL-1 (Low) — OCR worker init latch nulled from under a concurrent ensureWorker(). stop() (lock/quit) calls terminateWorker() out of band — NOT through this.chain — so it can race an ensureWorker() init started inside a chained recognize(). The old terminateWorker nulled this.starting unconditionally and never awaited a pending init, so the worker that init later produced outlived the teardown (a leaked WASM worker holding decoded page bytes). FIX (the e5/reranker teardown mirror): capture this.starting, await it if in flight (so the worker it spawns is the one we then terminate), and clear the latch only if it is still that same promise (a fresh init started during the await is left to run). DIVERGENCE (recorded): the audit's literal "only null when it equals the promise being torn down (capture + compare)" is, without the await, a no-op for the reachable harm — nothing can replace this.starting between a synchronous capture and null, and the pending init is still orphaned. Awaiting the init is the mechanically-correct fix; the equals-compare-before-null is kept on top of it (guards a second out-of-band terminate that replaces the latch during the await). The audit's "spawns a SECOND worker" variant requires an out-of-band terminate that ISN'T stop() (none exists today — recognize() is stopped-gated and the timeout/abort terminate runs inside the chain), so the concrete reachable harm is the init-outlives-stop() leak, which the await closes (teeth: drop the await → the late-born worker is never terminated).
  • REL-3 (Low) — e5.embed() didn't re-check teardown between batches. embed() captures server once, then loops batches; a suspend()/stop() mid-loop nulls the sidecar, so the NEXT server.fetch threw the runtime's "llama-server is not started" — a confusing per-document error rather than a clean cancel (functionally safe — no orphan). FIX: at the top of each batch iteration, throw the SAME recognizable cancellation ensureStarted raises ("Embedder is stopped …" / "… is suspending …"). DIVERGENCE (recorded): the audit said re-check this.stopped/this.tearingDown; the load-bearing condition is this.server !== server (a captured-server staleness check). tearingDown clears in teardown's finally, so a suspend() that COMPLETED between two batches has it back to false — only the staleness signal (teardown nulled/replaced this.server) catches that interleaving, which is the common one. stopped is checked first for the quit path (teeth: drop the re-check → the next batch fetches the dead captured server and reddens with "not started").
  • REL-4 (Low) — quit shutdown() didn't abort in-flight streams before runtime.stop(). The workspace-LOCK path aborts in-flight chat/RAG streams first (so each partial reply unwinds as an ABORT and generateAssistantMessage persists it while ctx.db is open), but the quit path killed the sidecar directly — a non-abort stream error that lost the partial. DECISION: option (a) — abort inFlightStreams before the sidecar stops, mirroring the lock ordering (more consistent than documenting the divergence; the partial persists during the awaited runtime.stop() window, the same settle guarantee the lock path already relies on — neither path awaits the stream itself). The quit teardown was extracted from main/index.ts into main/shutdown.ts (performShutdown(ctx, deps)) so its ORDERING is unit-testable with a fake ctx (the real main/index.ts registers app handlers at import time). Teeth: drop the abort loop → the stream is never aborted and the ordering test reddens.
Finding Sev Disposition (one line) Record / files
REL-2 Low fixed — service-level tearingDown latch (the F19 analogue VisionService lacked); run() re-checks at top + after getStatus(); a new analyze during teardown can't rebuild the ~4.6 GB sidecar. Teeth: neuter both checks → createCalls 1→2 this §37; GPU §5.5c (F19 family); vision/index.ts; tests/integration/vision-teardown.test.ts
REL-1 Low fixed — terminateWorker awaits the in-flight init (e5/reranker mirror) so its worker can't outlive teardown, and clears the latch only if unchanged. Teeth: drop the await → late-born worker never terminated this §37; ocr/tesseract.ts; tests/unit/ocr.test.ts
REL-3 Low fixed — per-batch teardown re-check throws the recognizable cancellation (this.server !== server staleness + stopped/tearingDown) instead of a confusing "not started". Teeth: drop it → next batch fetches the dead server this §37; GPU §5.5b/c; embeddings/e5.ts; tests/integration/e5-embedder.test.ts
REL-4 Low fixed (option a) — performShutdown (extracted to main/shutdown.ts) aborts in-flight streams BEFORE runtime.stop(), mirroring the lock path so a partial reply persists at quit. Teeth: drop the abort loop → ordering test reddens this §37; the LOCK-path record (registerWorkspaceIpc.lockWorkspace); main/shutdown.ts, main/index.ts; tests/unit/shutdown.test.ts

REL-5 (carried, open): unchanged — still keep-deferred (architecturally non-reachable while the single synchronous DatabaseSync connection holds; §26 note). Not in Phase 6's scope (the §26 wording strengthening is Phase 8).

§38 Full audit (2026-06-29, follow-up) — Phase 8 (maintainability + security hardening) & ROUND CLOSE-OUT

The 2026-06-29 follow-up full audit (report audits/full-audit-2026-06-29-followup.md) is COMPLETE — all eight phases landed. The round's pattern was "the gaps moved outward": away from the heavily-fortified core primitives (crypto, money parser, sidecar lifecycle, RAG core — all independently re-confirmed clean) and into document/statement-level orchestration, the Electron-version platform boundary, and main-thread I/O / DOM scaling. No Critical, no remote exploit (offline by construction); 3 High (FIN-1 wrong-currency / FE-A dead drag-drop / PERF-1 import freeze) + PERF-2-at-scale, ~10 Medium, the rest Low/Info. Each phase folded its decisions into the topic docs as it landed (the per-phase records §35 [Phase 3], §36 [Phase 4], §37 [Phase 6], the Phase-7 subsection of the Test-enforcement record, §8 [Phase 1], rag-design §14.4 [Phase 5], the "Drag-drop intake" Renderer-robustness record [Phase 2]); this section is the durable master index — resolve a full-audit-2026-06-29-followup <ID> code comment through it. Per the CLAUDE.md doc-lifecycle rule the working-paper report was retired once every finding was dispositioned (committed folded-in first, so the original stays recoverable in git history — the parent of the Phase-8 close-out commit), mirroring the §24/§25/§26/§34 precedent. Phases ran on stacked, unmerged branches (audit-followup-phase1-financial … phase8-closeout); owner merges when ready.

Per-phase one-liners: P1 financial correctness (FIN-1..4; release-blocking class; §8). P2 Electron-37 drag-drop regression (FE-A webUtils.getPathForFile preload bridge + FE-C empty-drop feedback; Renderer-robustness record). P3 main-thread import I/O + parser caps (PERF-1 async vault crypto / PERF-4 text-CSV byte cap; §35). P4 documents-list scale (PERF-3 ocr_meta_json sidecar / PERF-2 list windowing / PERF-6 deferred; §36). P5 RAG provenance honesty + Sources a11y (FE-B / F11 renderer half + FE-D; rag-design §14.4, design-guidelines §11.8). P6 reliability hardening (REL-1..4 latent teardown races; §37). P7 test-suite robustness (TEST-1/TEST-3/DX-2/DX-4/DX-5/DX-6; Phase-7 subsection, test-only). P8 (this close-out) maintainability (DX-1/DX-3) + security hardening (SEC-4) + FE-E + REL-5 wording + report retirement.

Finding(s) Phase Disposition (one line) Record
FIN-1 (High) 1 fixed — document/statement currency by figure-adjacent majority vote (detectDocumentCurrency), so a USD/CHF in a memo no longer stamps a EUR statement's verified total §8; money.ts; known-limitations
FIN-2 (Med) 1 fixed — invoice right-side "uncaptured column" drop requires the whole trailing region to be ONE money-shaped-but-rejected token (no over-fire on (Pos. 3) / 19% MwSt / 2 Stk) §8; invoice.ts
FIN-3 (Med) 1 fixed — DATE_TOKEN_RE tightened so 2.500 is un-date-able; MONEY_TOKEN_RE deliberately NOT widened (DIVERGED — widening would regress the M3 split-amount safety) §8; pdf-layout.ts
FIN-4 (Med) 1 fixed — inferDateOrder vote scoped by line KIND (money line → leading date column only; money-less header → any) so a memo's foreign-format date can't flip the doc §8; money.ts
FE-A (High) 2 fixed — preload window.api.getDroppedFilePath wraps webUtils.getPathForFile (Electron-37 removed File.path); pathsFromDrop calls it; real-Electron 37.10.3 leg verified Renderer-robustness "Drag-drop intake"; preload/index.ts, ChatScreen.tsx
FE-C (Med) 2 fixed — onDrop shows chat.attach.dropUnsupported when a Files-bearing drop yields zero importable paths Renderer-robustness "Drag-drop intake"
FE-B (Med-High) 5 fixed (closes the carried F11 renderer half) — SourcesDisclosure takes coverage.mode; any whole-document mode renders as provenance ("Drawn from the document — N sections", no [Sn], capped at 24 + reveal); relevance/NULL-coverage byte-identical rag-design §14.4 (AS BUILT)
FE-D (Low, a11y) 5 fixed — aria-controls/role="region"/aria-labelledby on the Sources, Thinking, and SummaryMarker disclosures design-guidelines §11.8
FE-E (Low) 8 fixed — a THROWN first-run model-listing/verify failure routes to the Models screen (not silently to Chat's generic "no model" empty state); an empty list still routes to the starter step; never traps the user this §38; WorkspaceGate.tsx; WorkspaceGate.test.tsx
PERF-1 (High) 3 fixed — async encryptFileAsync/decryptFileAsync (per-chunk yield, byte-identical frame) on the import path; copyFileSync→async (DIVERGED — async siblings, the sync crash-lock/DB-lifecycle/vision-emitter stay sync) §35; workspace-vault.ts
PERF-2 (High@scale) 4 fixed (documents list) — @tanstack/react-virtual windows the list (viewport-gated; else render all). Chat-transcript half carried forward (behavior-sensitive) §36; known-limitations (find-in-page)
PERF-3 (Med) 4 fixed — additive nullable ocr_meta_json sidecar (counts/ids only) written at OCR-write + backfilled once; listDocuments omits ocr_json (~147 ms/call removed) §36
PERF-4 (Med) 3 fixed — textMaxBytes (64 MiB) + readsWholeFileToString flag → friendly fileTooLarge reject instead of a V8 string-limit OOM for txt/markdown/csv §35; known-limitations
PERF-5 (Low) — accepted / carried → CLOSED by full-audit 2026-07-10 PF-7c — ImagesScreen AnswerThread memo defeated by unstable onCopy/onTryAgain/onStop props; closed by the useEventCallback sweep + the visionSession 40 ms token batch (perf design record) this ledger (carried); perf record PF-4/PF-7
PERF-6 (Low) 4 deferred with cause — per-page OCR child table is a larger schema migration; PERF-3's sidecar already removed the hot-path parse (the actual harm) §36
SEC-4 (Low/Info) 8 fixed — (this SEC-4 is the 2026-06-29 follow-up's; distinct from backend-audit-2026-06-27's SEC-4 = session-cached binary verification, §24 / security-model.md) runtime-sources.ts rejects ../absolute/drive-letter extract_to at PARSE time (new isUnsafeDrivePath, applied to the sibling OCR dest too for consistency); defense-in-depth ahead of the load-bearing resolveWithinRoot this §38; shared/runtime-sources.ts; runtime-sources.test.ts
SEC-1c (Low) — accepted residual / open — unlock-path rate-limit/attempt-counter + create-time strength floor; the at-rest Argon2id KDF is the binding mitigation against the offline (drive-in-hand) attacker, so a UI rate-limit doesn't bind the real threat §26
SEC-2 (Low) — accepted residual / open — stage previewSkillPackage content under userSkillsDir (trust-zone consistency); today path-/size-validated + finally-cleaned in the shared tmpdir, not an escape §26
SEC-3 (Info) — closed 2026-10-14 (#681); was accepted residual / open — dialog-opener IPCs mint a capability token pre-unlock but every consuming handler is requireUnlocked()-gated → inert; a consistency gap, not an exploit (documents/images only at the time; the skills picker minted none until PR #275, #240 — see the §26 row. Closed 2026-10-14: every picker is gated since #681 — see the follow-up-audit ledger's SEC-3 row) §26
REL-1 (Low) 6 fixed — OCR terminateWorker awaits the in-flight init so it can't outlive teardown §37
REL-2 (Low) 6 fixed — VisionService tearingDown latch (the F19 analogue) bars a NEW analyze() from rebuilding the ~4.6 GB sidecar mid-teardown §37; GPU §5.5c
REL-3 (Low) 6 fixed — e5.embed() per-batch teardown re-check (captured-server staleness) throws the recognizable cancel, not "not started" §37; GPU §5.5b/c
REL-4 (Low) 6 fixed (option a) — performShutdown (extracted to main/shutdown.ts) aborts in-flight streams BEFORE runtime.stop(), mirroring the lock path §37
REL-5 (Low) — non-reachable / deferred — verified architecturally non-reachable while the single-DatabaseSync architecture holds; promote to a real fix only if a second DB connection (e.g. a worker-thread reader) is introduced (precondition made explicit) §26 (strengthened, P8); §37
TEST-1 (Med) 7 closed (de-flake) — the flaky real-timer vision idle block deleted; its two uncovered cases ported to the deterministic injected-clock twin Phase-7 subsection
TEST-3 (Med) 7 closed (test) — rag-pipeline-floor.test.ts: model-free synthetic floor through the REAL chunk→embed→FTS→RRF→top-k→citation pipeline; teeth-checked ×2 Phase-7 subsection
DX-1 (Med) 8 fixed (refactor) — DocTaskManager god-class split: each run<Kind> extracted to a doctasks/handlers/* module keyed by MODEL_TASK_HANDLERS; the manager keeps only queue/pump/arbiter + the generate/generateWithRetry retry loop, handed to handlers via a narrow DocTaskCtx. STRICTLY behavior-preserving (1758→~580 lines; full doctasks suite identical green) this §38; doctasks/manager.ts, doctasks/context.ts, doctasks/handlers/{index,shared,tree,summary,ocr,translation,compare,categorize}.ts
DX-2 (Low) 7 fixed — prod render-counter import.meta.env.DEV-guarded (no-ops in a production build; memo test green under DEV) Phase-7 subsection; DocumentsScreen.tsx
DX-3 (Low) 8 fixed (refactor) — DocumentsScreen split: DocRow/SectionRail/PreviewModal to sibling screens/documents/* files + pure formatters to documents/format.tsx + shared types/keys to documents/types.ts. STRICTLY behavior-preserving (2190→1164 lines; Phase-4 virtualization + Phase-7 DEV render-counter intact; all Documents suites green) this §38; screens/documents/{format.tsx,types.ts,DocRow.tsx,SectionRail.tsx,PreviewModal.tsx}
DX-4 (Low-Med) 7 closed (test) — ipc-lock-coverage meta-assertion globs every register*Ipc export; a new uncovered module reds it Phase-7 subsection
DX-5 (Low) 7 closed (test) — runtime-ladder-exit-wiring.test.ts: a real LlamaServer child's 'exit' drives the §5.3 crash auto-fallback end-to-end; teeth-checked Phase-7 subsection
DX-6 (Low) 7 closed (de-flake) — three settle-window sleeps → deterministic waits (await the F19-guarded refusal; poll the scripted in-flight count) Phase-7 subsection

Carried-forward open items (deliberately NOT taken; on record for the next pass):

  • SEC-1c / SEC-2 / SEC-3 (SEC-3 closed 2026-10-14 by #681) — three security consistency improvements, none an exploit (re-affirmed accepted residuals with their §26 rationale; the at-rest KDF binds the offline attacker, the skill-preview staging is validated+cleaned, the dialog-opener tokens are inert until the consuming requireUnlocked()).
  • REL-5 — non-reachable while the single-DatabaseSync architecture holds; becomes a real fix to build only if a second DB connection (worker-thread reader / connection pool) is introduced. Precondition now explicit in §26 so a future worker-pool change can't silently re-open the gap.
  • PERF-5 (ImagesScreen AnswerThread memo) — CLOSED (full-audit 2026-07-10 PF-7c): the Images screen was next touched exactly as planned — onCopy/onTryAgain/onStop wrapped in useEventCallback, plus the visionSession per-token notify batched through a 40 ms flush (see the Performance design record, PF-4/PF-7 entry).
  • PERF-2 chat-transcript half — list windowing for the chat transcript stays deferred (variable height + scroll-to-bottom + find-in-page + StreamAnnouncer are genuinely behavior-sensitive); the documents-list half is CLOSED (P4). Still the tracked top renderer item.
  • §26/§34-carried (still open, unchanged): the E5 query:/passage: prefix migration (its own phase; re-embeds the whole corpus) and the coupled F13 floor-before-cut precondition (re-enabling a positive ragMinSimilarity floor must over-fetch then floor) — both inert at the pinned default 0.

Posture held across all eight phases (load-bearing): offline / no telemetry / no new network egress; the only schema change was the single additive nullable documents.ocr_meta_json (P4, backfilled on open); no IPC / audit-payload change in any phase; the content class (document/chat text, titles/filenames, extracted figures, redacted text) is never logged / audited / exported. Behavior-preserving: every behavioral fix (P1/P2/P3/P4/P5/P6) is teeth-checked (neuter the guard → red → restore byte-identical); P7 was test-only (git diff src/ a single DEV-guard line); P8's two refactors (DX-1/DX-3) are STRICTLY relocation — the full doctasks suite (154 tests) and the Documents renderer suites (95 tests) are identical green before and after, and the whole suite is unchanged at 2593 passed / 39 skipped (+4 vs Phase 7's 2589, all from SEC-4). The SEC-4 validator, the