Skip to content

AI, fully local on your computer.

136 KB
Raw Blame

Packaging — portable build, sidecars & model weights

This documents how the app is packaged into a portable build, where the runtime binaries and model weights live on the drive, and that those artifacts are not in the git repository. The pieces: the runtime-side drive layout; the electron-builder portable build + the prepare-drive/verify-models scripts; the scripted asset loader (fetch-models / fetch-runtime) that downloads + verifies the weights and sidecar; and the plug-and-play launcher, code signing/notarization, and the build-commercial-drive master pipeline that produces a finished, sellable drive (see the last section).

Hard rules (recap)

  • Never commit model weights, sidecar binaries, user data, embeddings, logs, or generated files (CLAUDE.md / spec §0). .gitignore already excludes models/, *.gguf, and runtime/.
  • The app stays fully usable offline. Sidecars bind 127.0.0.1 only (loopback); nothing the app spawns listens on a routable interface.

Drive layout (spec §6 — canonical detail in drive-layout.md)

<drive root>/
  runtime/
    llama.cpp/
      win/    llama-server.exe  (+ DLLs — Vulkan full build, incl. all CPU backends)
              .hilbertraum-runtime.json            (install marker: version/backend/os/arch + every file's SHA-256)
        cpu/  llama-server.exe  (+ DLLs — pure-CPU safety net) + .hilbertraum-runtime.json
      mac/    llama-server      (Metal build) + .hilbertraum-runtime.json
      linux/  llama-server      (Vulkan full build) + .hilbertraum-runtime.json
        cpu/  llama-server      (pure-CPU safety net) + .hilbertraum-runtime.json
    whisper.cpp/
      {win,mac,linux}/  whisper-cli[.exe]  (audio transcriber) + .hilbertraum-runtime.json
  models/
    chat/        qwen3-4b-instruct-q4.gguf  …
    embeddings/  multilingual-e5-small-q8.gguf
    reranker/    transcriber/               (optional reranker GGUF; whisper GGML .bin)
    vision/      qwen2.5-vl-3b-…q4.gguf + mmproj-…f16.gguf   (optional; the LM GGUF + its mmproj projector — TWO files)
  ocr/           {deu,eng,osd}.traineddata.gz   (OCR language + page-orientation files, sha256-verified)
  model-manifests/   (committed YAML — the only model metadata in git)
  workspace/   config/   logs/
  • Sidecar binaries — prebuilt llama.cpp llama-server executables, one folder per OS. The OS sub-dir (win/mac/linux) and the executable name (llama-server.exe on Windows, llama-server elsewhere) are resolved by resolveLlamaServerPath(rootPath, platform) in services/runtime/sidecar.ts. A HILBERTRAUM_LLAMA_BIN env var overrides the path for dev.
    • In-app engine install (services/runtime-download.ts). The same prebuilt binaries the DIY fetch-runtime scripts provision at build time can also be fetched from inside the app (the "Install the AI engine" banner on the AI Model screen) when a drive has model weights but no engine — otherwise a started model silently falls back to the demo runtime. The installer is engine-family-generic: SIDECAR_FAMILY_SPECS (services/assets.ts — the ONE registry the installer and the commercial-drive gate share) lists llama_cpp (the llama-server chat engine), whisper_cpp (the whisper-cli voice/transcription engine) and the OPTIONAL kiwix_tools (the knowledge-pack tools, #339 — never part of the default install), and a single default install fetches every missing REQUIRED family for the host. The banner is scoped per concern (ModelsScreen): it reads EngineStatus.missingFamilies and shows the strong "Install the AI engine — models run in demo mode" warning only when llama_cpp (the chat engine) is missing; when the chat engine is present and only whisper_cpp is absent it shows a quiet info note ("Add voice dictation (optional)") instead — chat already answers for real, so the demo-mode alarm would be false. To add a future engine family: add its <family>: block to model-manifests/runtime-sources.yaml (with a real host build + SHA-256) and one entry to SIDECAR_FAMILY_SPECS ({ family, binaryBase, … }); status, install, flatten and marker then cover it. The renderer does not generalize: the two engine banners and the knowledge-pack tools row are hard-coded per family in ModelsScreen.tsx, so a new family also needs its own copy and affordance. The OCR language files are not an engine family — plain hash-verified files, no archive, no marker — and have their own narrow in-app installer (services/ocr-install.ts, #410; drive-layout.md "OCR language files"). A family with no prebuilt host build (e.g. whisper.cpp on macOS/Linux, which ships Windows-only binaries — built from source by the drive builder) is simply skipped by the in-app installer. Extraction is bounded (F-33, full-audit 2026-07-16): extractWithTar runs under a 5-min deadline + SIGTERM→SIGKILL escalation and threads the job's abort signal, so a wedged tar can't pin the job in extracting forever, and a cancelled-but-still settling run() counts as busy. That NARROWS the second-install-into-the-same-dir window to the ≤2 s SIGKILL grace (the extractor rejects after signalling the child, not after its exit; a tar wedged in uninterruptible I/O can outlive even that) — an accepted residual: rejecting only after the child's exit would reintroduce the unbounded wait this fix removes. Since #986 such a late tar writes into the staging folder <os>.new/, never the install folder. tar runs from inside the target and gets -xf ./<archive>, with no -C (#856), on every host. Windows' tar (bsdtar) converts the paths on its command line through the ANSI code page, so under a Cyrillic or Japanese folder on a Western Windows an absolute archive path failed with "Error opening archive" and a -C with "could not chdir"; the child's working directory reaches tar intact. The installer downloads the archive into the target, so its name is all tar needs: ASCII when it comes from the URL (ARCHIVE_NAME_RULE), while the fallback name built from the yaml's version is not checked. The ./ keeps a name starting with - from meaning stdin and one holding a : from meaning GNU tar's host:file. extractWithTar refuses an archive kept anywhere else, since its path would have to go on the command line again. The in-use guard is per family (F-32): a llama_cpp (re-)install replaces the dir EVERY llama-server sidecar runs from (chat + embedder + reranker + vision + translation), so it is refused while any of them has a live child; a whisper_cpp install is refused mid-transcription/ dictation. Installs touching only the OTHER family still proceed. Staged swap (#986). The install never deletes first: each archive is moved into <extract_to>.new/, extracted and checked there and marked last, then swapped in by rename (<extract_to> → .old, .new → <extract_to>, the cpu/ net carried over, .old deleted after the job); a failure leaves the installed copy as it was. Before anything is touched the job checks the drive's free space against the archives' unpacked size, read from the archives themselves (main.engine.notEnoughSpace). The next start finishes or rolls back an interrupted swap. Design: architecture.md "In-app engine updates" §6; layout: drive-layout.md.
  • Model weights — GGUF files under models/, resolved from each manifest's declared paths (local_path plus, since #310, any files: entries — every one relative to the drive root) via weightPath(rootPath, manifest) / manifestFiles(rootPath, manifest). They are git-ignored; a real drive is built by the prepare-drive scripts (and verified against each file's manifest sha256). The bundled Qwen3 + E5 manifests now carry real pinned hashes; a model you add yourself starts as a REPLACE_WITH_REAL_HASH placeholder until you capture it with verify-models --generate.
  • A multi-file weight shares one modelId across its files (image understanding V1–V5; generalised by #310). A role: vision manifest names the language GGUF (top-level local_path/sha256/download) plus an mmproj projector sub-block (its own local_path/sha256/download, resolved by mmprojPath(...)) — today's only committed multi-file case, always exactly two files. The schema is more general: a manifest's optional files: list (#310) declares any further required files of the same weight (e.g. a GGUF shard set's shards 2..N), each with its own path/hash/download. The download topology is N already-atomic single-file DownloadJobs under one modelId (DIST-1): each is .part-staged
    • verify-before-rename by the existing single-file machinery — no cross-file progress aggregation, no two-phase verify. Install = EVERY declared file present + SHA-256-verified (computeInstallState). Vision is in the --with-assets default set (since 2026-07-01 it is in $DefaultModelIds/DEFAULT_MODEL_IDS), but it is never auto-recommended in-app (rank 0); a hand-built drive pulls every file with --only <vision-id> or --all-models. See model-policy.md "The vision role + mmproj projector" and "Manifest fields (required)" for the files: shape.

How the app uses them at runtime

  • The runtime factory (createSelectingRuntimeFactory) and the embedder factory (createSelectedEmbedder) each return the real backend (LlamaRuntime / E5Embedder) only when both the llama-server binary and the relevant GGUF weights exist; otherwise they fall back to the mock. So with an empty runtime/ + models/ (the repo's default, and CI), the app launches and every test passes on the mocks — the real backends are a drop-in the moment the files appear.
  • Both real backends spawn llama-server on a random loopback port and talk to it over HTTP (/v1/chat/completions streaming for chat, /v1/embeddings for the embedder). The processes are killed on stop() and on will-quit (no orphaned llama-server).

Acquiring the binaries / weights — scripted or manual

The live path needs artifacts not in the repo:

  • a llama.cpp llama-server build for your OS (under runtime/llama.cpp/<os>/), and
  • the GGUF weights named by the manifests (under models/...).

The fetch-* scripts automate this (below) — prepare-drive --with-assets downloads + SHA-256-verifies the artifacts in one command. By default it fetches a small but complete default set (~10.4 GB) — the default chat model (Ministral 3 8B), the embeddings model, the reranker, the Whisper transcriber model, and the Qwen2.5-VL vision model — plus both sidecar runtimes (llama.cpp

  • whisper.cpp) and the OCR files (deu/eng traineddata + the osd page-orientation data, ~8 MB, OS-independent), so chat, document Q&A, retrieval quality, audio, image understanding, and scanned-PDF/photo OCR work out of the box. The user grabs any other models (larger chat models) from the app's AI Model screen on demand; add -AllModels/--all-models to provision every model up front (the runtimes + OCR files are fetched either way). The whisper.cpp runtime is prebuilt for Windows only, so on a macOS/Linux build host --with-assets skips it with a note (build it from source); the OCR files are plain verified downloads and are fetched on every OS. You can still drop everything in by hand. Then start a chat model on the AI Model screen to get real on-device inference and real tokens/sec.

Portable build (electron-builder)

The app is packaged with electron-builder (apps/desktop/electron-builder.yml). The primary target is a portable Windows .exe that launches from an external drive; macOS (dir) and Linux (AppImage) targets are defined for architecture parity (spec rule: keep all three supported), even though only Windows is produced on the current dev machine.

npm run package        # electron-vite build + electron-builder (current OS targets)
npm run package:win    # build + a Windows portable .exe specifically

Key config points:

  • executableName: HilbertRaum is pinned at the top level (PR #30). electron-builder derives the per-platform executable / AppImage name from the npm package name, which in this monorepo is the scoped @hilbertraum/desktop → @hilbertraumdesktop; the @ is an unsafe path char that electron-builder rejects, so the build fails (first seen on the Linux AppImage target, then mac/win once the desktop package was renamed to the scoped name). The explicit executableName gives every platform a path-safe binary name. Keep it in sync with productName (both are HilbertRaum); tests/integration/packaging.test.ts asserts they match and that the name carries no @.
  • The Linux AppImage uses electron-builder's legacy FUSE 2 toolset, because electron-builder.yml sets no toolsets.appimage. Three consequences, read off the v0.1.62 artifact on 2026-10-01: its runtime dlopens libfuse.so.2, which Ubuntu 22.04 and later do not install by default; its .desktop entry is Exec=AppRun --no-sandbox %U, the legacy toolset's default when linux.executableArgs is unset; and the generated AppRun runs unshare -Ur true and adds --no-sandbox when that fails. User-facing side: troubleshooting.md "Linux: the AppImage does not start" and known-limitations.md "Security & privacy". The static-runtime toolset (toolsets.appimage: 1.0.3) would drop the host libfuse2 requirement and the desktop-entry flag but keeps the same AppRun probe; it has not been tried here.
  • The Linux floor is the AI engine's, not the AppImage's (#530). Electron runs on Ubuntu 18.04+, but the pinned llama.cpp/whisper.cpp Linux builds need glibc 2.34, GCC 12's libstdc++ and OpenSSL 3, which means Ubuntu 22.04, Debian 12 or Fedora 36 and newer. They also take libgomp.so.1 from the host; desktop images include it, and it is not bundled (owner decision 2026-10-01). The Windows engine builds likewise take the Visual C++ 2015–2022 runtime from the host. The app classifies a refused engine and names the cause (architecture.md "Engine load failures"), and the user-facing minimum is stated in README, user-guide.md §1, troubleshooting.md and launchers/READ ME FIRST.txt.
    • Sidecar environment. The app sets no LD_LIBRARY_PATH of its own, so every sidecar inherits the parent's environment. Under the AppImage that includes the AppRun export LD_LIBRARY_PATH=$APPDIR/usr/lib (measured on the v0.1.62 AppImage for the #530 bundling study).
  • The renderer CSP <meta> tags are generated at build time (BE-2, ocr-audit 2026-07-18): the hilbertraum:csp-meta transform in electron.vite.config.ts rewrites the Content-Security-Policy meta in index.html/ocr.html from the single source of truth window-security.ts buildMetaCsp(isDev, page). The checked-in HTML carries the dev policy (Vite HMR needs ws://localhost:*/http://localhost:* in connect-src); electron-vite build bakes the strict prod policy — same directives with the localhost entries stripped. The transform throws if a page has no CSP meta tag, and tests/integration/csp-build-output.test.ts asserts the built HTML matches buildMetaCsp(false, …) byte-for-byte (CI builds before it tests, so the guard runs on every PR). Measured on a packaged Windows build (2026-07-18): the onHeadersReceived response-header CSP does attach and enforce on file:// loads in both windows, so the header is the load-bearing prod policy and the meta is the defence-in-depth second layer — see docs/security-model.md "Content-Security-Policy". Since #560 the pages load from hilbertraum://app/ instead (next point), where the scheme's handler and the session hook each attach the header (measured 2026-10-03).
  • The app's pages are served from hilbertraum://app/, and the packaged binary turns the GrantFileProtocolExtraPrivileges fuse off (#560). src/main/app-protocol.ts serves the built out/renderer (inside app.asar) from an allowlist taken at startup, with a content-type table of its own: html, js/mjs, css, svg, woff2, woff and ttf. A new asset type in the renderer build needs a row there: tests/integration/app-protocol-assets.test.ts fails the gate when the build emits a file the handler would not serve, or when a page or stylesheet references one. The fuse is set in electron-builder.yml electronFuses, which electron-builder flips with @electron/fuses before signing; tests/integration/packaging.test.ts pins the block and checks that the installed electron-builder still maps the option (an unmapped name is ignored silently). Since #562 the block also sets four more fuses; see "Electron fuses" below.
  • Electron ≥ 37 (Node 22.x) is required so the packaged main process has node:sqlite (electron is pinned ^43.8.3). A downgraded/stripped runtime would lose it — do not downgrade. Because electron is pinned as a range and hoisted to the repo-root node_modules, electron-builder 26 cannot auto-detect it from apps/desktop — so electron-builder.yml pins electronVersion explicitly (keep it in sync with the electron devDependency when bumping).
  • Production dependencies ship inside app.asar (pdfjs-dist / mammoth / jszip / papaparse / yaml / @noble/hashes), so the require()s in the parsers, manifest loader, the vault KDF, and the same-format DOCX writer resolve at runtime. jszip was already in the tree transitively under mammoth; it is now a direct dependency (D77) because services/export/docx-rewrite.ts imports it to rewrite <w:t> nodes (pure-JS, no native addon — the closure is unchanged). electron-builder 26's collector follows hoisted/nested node_modules trees (e.g. mammoth's transitive deps) by default — the old includeSubNodeModules: true option was removed in eb 26 (it now errors as an unknown property) and is no longer needed. npmRebuild: false (no native addons). These are externalized, so a missing one only fails at RUNTIME, not in the green gate — after packaging, smoke-test importing a PDF, a DOCX, and a CSV, AND creating/unlocking an encrypted workspace (exercises @noble/hashes argon2id), from the produced .exe.
  • The mermaid chain is not in the tree at all (since streamdown 2.6, #550). streamdown (the chat Markdown renderer) used to hard-depend on mermaid (~136 MB unpacked incl. cytoscape / the d3 suite / dagre-d3-es / roughjs) without ever importing it, and ~40 files negations kept that chain out of app.asar (DEP-3; ≈ 68 MB vs ≈ 204 MB without). 2.6 made mermaid an opt-in plugin (@streamdown/mermaid, not installed), so the chain and its negations are gone. tests/integration/packaging.test.ts fails if mermaid re-enters the production graph (adopting the plugin is a decision, not an accident), and checks every remaining negation where electron-builder packs each package: the collector re-hoists the production graph and matches the negations against that layout, so a package nested under a negated parent can land at node_modules/<name> and ship (#548; tinyexec did until #536). Negate a package by its own name. tests/helpers/asar-layout.ts replays the hoisting with electron-builder's own hoister; after a package build, HILBERTRAUM_PACKED_ASAR=release/win-unpacked/resources/app.asar npm test -- tests/integration/packaging.test.ts compares it with the real archive, and release.yml's build-win does so on every build it packages (#769).
  • The dev-only screenshot-verify preview harness is excluded from app.asar via a !out/preview/** negation (CODE-1, full-audit 2026-07-12b): npm run preview:build/screenshot emit it to out/preview/ and electron-vite build clears only out/main|preload|renderer, so a local package run after a screenshot run would otherwise fold the harness (incl. staged demo chats) into the artifact; tests/integration/packaging.test.ts pins the negation.
  • The asarUnpack list is the tesseract.js worker's require-graph CLOSURE, derived by a test: the OCR engine spawns its Node worker via worker_threads, which loads the worker script and everything it requires through real filesystem reads that cannot see inside the asar archive; the engine rewrites app.asar → app.asar.unpacked in the resolved workerPath, and every module on the worker's graph must be unpacked too. tests/integration/asar-unpack-closure.test.ts resolves the worker entry, walks its literal require() graph and asserts every resolved module path matches an asarUnpack glob — today tesseract.js, tesseract.js-core, regenerator-runtime, is-url, bmp-js, wasm-feature-detect, node-fetch and node-fetch's own deps whatwg-url, tr46, webidl-conversions — nested under node-fetch in the source tree but FLATTENED to top level inside the asar by electron-builder 26's collector, so the test checks every module at both destinations (the PR #269 review caught a source-path-only check passing while those three sat packed at top level), and at the one electron-builder's hoister actually gives it (#548). History (#232, PRs #268/#269; merged 2026-09-02): with only the two tesseract packages listed, the worker's hoisted deps stayed inside app.asar (measured 2026-07-19 on a real packaged Windows build) and the load failure killed the whole app while ocrAvailable still reported true — tesseract.js sets the browser-only worker.onerror, inert on a Node Worker, so the 'error' event had no listener and Node rethrew it as uncaughtException. PR #268 contained it: the engine captures the raw worker through Node's process.on('worker') hook, bounds the start, passes tesseract's errorHandler, so a load failure rejects the recognition per document and latches the engine unavailable; a packaged build runs an execution probe at startup (one bounded worker start, released on success) and reports OCR unavailable until it passes — photos import without text and carry a per-document note, "Make searchable (OCR)" is not offered, the Documents screen shows a banner. PR #269 closed the gap with the test + globs above; measured 2026-09-02 on a packaged Windows build (HilbertRaum-0.1.59-portable, win-unpacked, scratch drive root with deu+eng language files): OCR execution probe {ok: true, ms: 277} — worker script, hoisted deps, WASM core and both language files load from app.asar.unpacked. The interactive recognition smoke (photo import + "Make searchable (OCR)" on a packaged build; BUILD_STATE §5 item 18(c)) is still to be recorded per platform before a kit for that platform is certified — the probe proves the load chain, the smoke proves recognition end to end. If the probe ever fails again the app degrades as above instead of crashing. Registered as follow-up 2 in architecture.md "Dependency remediation — design record (wave DEP-1, PR #77)" §5. Dev-mode OCR was never affected (the raster → IPC → recognize pipeline was proven end to end on Electron 39); the other runtime-only-failure smokes above (parsers, encrypted workspace) still apply. Unpacked files sit outside the asar integrity check (#562, measured), so keep this list to the worker closure and nothing else.
  • The OCR rasterizer ships pdf.js's JS image decoders under their own names (#551, fix/ocr-pdfjs-in-page). pdf.js 6 decodes CCITT fax, JBIG2 and JPEG 2000 images only through modules it loads at run time as ${wasmUrl}<file name>. The rasterizer runs pdf.js in-page under the OCR page's CSP, which has no 'wasm-unsafe-eval', so it forces the JS build (useWasm: false) and the renderer build emits only pdfjs-dist's *_nowasm_fallback.js jbig2 and openjpeg modules (no .wasm) unhashed into out/renderer/pdfjs-wasm/, with ocr.html passing that directory as wasmUrl. Without them a black-and-white office scan rendered blank and OCR found no text. tests/integration/ocr-decoder-assets.test.ts pins both (and that no .wasm and no separate pdf.worker-*.mjs asset ship). Run the recognition smoke on a black-and-white (CCITT) scan as well: a JPEG scan decodes without these modules, so it cannot catch their loss.
  • A packaged build that Smart App Control will not start. SAC refuses fresh unsigned HilbertRaum.exe builds (CodeIntegrity 3077/3118), though not every time: on 2026-10-03 it ran a fresh master build and refused the fuse-flipped #560 build. It runs the repo's node_modules/electron/dist/electron.exe. Up to #560 the packaged exe was that binary with a rewritten resource section: the same code sections and fuse wire (measured on 43.7.7, #551). So a copy of win-unpacked with that binary copied in as HilbertRaum.exe runs the packaged app's code against its app.asar, with app.isPackaged true. The packaged exe's fuses differ from the stock binary's (wire 000011001 since #564, 001011001 from #562 to #564; the stock binary 101100011), so that copy runs the packaged app with Electron's default fuses. That is fine for everything except the fuses themselves: no asar integrity check, RunAsNode and --inspect still honoured. To reproduce the shipped fuses, first add electron-builder's integrity resource to the copy (app-builder-lib addWinAsarIntegrity with computeData over its resources/), then flip it with @electron/fuses and decode the wire (below). A copy with the integrity fuse on but no resource refuses to start. Smart App Control's verdict is per file: on 2026-10-03 it ran the fresh master and branch builds, and refused every new copy of the stock electron.exe, byte-identical ones included. A file it has once allowed keeps running, and so do hard links to it. Probe first. Do not compare startup timings across binaries. On the reference desktop any binary whose hash differs from the stock electron.exe (the real packaged exe, the flipped copy, even the stock binary with one byte appended) shows its first window about 600–700 ms later than the stock binary, whatever the app code. A timing A/B must run both sides on equally modified binaries (architecture.md #560 record §7).
  • model-manifests/ ship as extraResources (beside app.asar). The packaged main process finds them for the model list via resolveManifestsDir(app.getAppPath()), which walks up to resources/model-manifests; HILBERTRAUM_MANIFESTS_DIR (the launchers set it to the drive's copy) overrides that. The AI-engine pins (install, repair, the update notice) and the OCR installer's second source list (per file, where the drive's list lacks it or pins another file, #841) read this bundled copy only, by resolveBundledManifestsDir: exactly <process.resourcesPath>/model-manifests, no walk-up and no override, and none when it is missing (#842). Engine entries added to a drive's runtime-sources.yaml therefore reach the scripts, never the app. Weights + sidecar binaries + the ocr/ language files are never bundled — they live on the prepared drive.
  • THIRD-PARTY-NOTICES.md ships as an extraResource too (beside model-manifests, LIC-2): the aggregated license texts + copyright notices for every npm package that lands in app.asar or the Vite-compiled bundles (Apache-2.0 NOTICE preservation for pdfjs-dist/tesseract.js, the SIL-OFL-1.1 notice for the KaTeX fonts, MIT/BSD/ISC attribution). The committed file is generated — after any dependency change, regenerate with node scripts/generate-third-party-notices.mjs and commit the result; tests/integration/third-party-notices.test.ts runs the generator's own builder (scripts/lib/third-party-notices.mjs, over the shipped set scripts/lib/shipped-packages.mjs computes from package-lock.json + the files: negations) and fails the gate while the committed file differs from a regeneration by a single byte (#769), as drive-notices.test.ts does for DRIVE-NOTICES.md. The two builders share their text helpers (scripts/lib/notice-text.mjs, #770). Electron's own LICENSE.electron.txt / LICENSES.chromium.html are placed beside the executable by electron-builder itself.
  • The project's own LICENSE ships as an extraResource too (as LICENSE.txt, LIC-2 full-audit 2026-07-12b): the root GPL-3.0-or-later text sits outside the apps/desktop build context, so without this entry the artifact would carry the GPL only as the package.json SPDX string. third-party-notices.test.ts pins the entry.
  • The build output goes to apps/desktop/release/ (git-ignored).

Electron fuses (#560, #562, #564)

electron-builder.yml electronFuses sets six fuses, measured and explained in architecture.md "Electron fuses — design record (#562)" (§8 for #564):

  • runAsNode: false: ELECTRON_RUN_AS_NODE no longer turns the exe into a Node.js runtime.
  • enableNodeCliInspectArguments: false: --inspect, --inspect-brk and SIGUSR1 open no debugger. Chromium's --remote-debugging-port, which the CDP harnesses use, is a different switch and still works.
  • enableNodeOptionsEnvironmentVariable: false (#564): the exe reads neither NODE_OPTIONS nor NODE_EXTRA_CA_CERTS. TLS-scanning antivirus and corporate proxies used to get their root trusted through that variable; they also install it in the operating system's certificate store, and since #564 the in-app downloads trust that store's usable roots (src/main/services/net/trust.ts: self-signed CAs whose signature verifies with their own key, valid now, RSA ≥ 2048, P-256/P-384/ P-521 or Ed25519; added once before the first download's first request, never at startup). A root that is only in NODE_EXTRA_CA_CERTS no longer counts in a packaged build. Until #564 the fuse stayed on (owner decision 2026-10-03), because with it off the downloads failed behind Norton (measured).
  • enableEmbeddedAsarIntegrityValidation: true + onlyLoadAppFromAsar: true: a modified app.asar ends the app, and only app.asar is ever loaded. They need asar: true and the header hash that electron-builder writes on every build: the exe's integrity resource on Windows, Info.plist on macOS. Never set disableAsarIntegrity: the binary would refuse to start. Windows and macOS only; files in app.asar.unpacked are not checked.
  • grantFileProtocolExtraPrivileges: false (#560): file:// pages lose Electron's extra privileges (fetch/XHR of any local file, among others). The app's own pages moved to hilbertraum://app/ for this; with the fuse off, the old file:// layout's module scripts are refused by CORS from origin null (measured), so do not move a page back to file://. Since #563 no window loads file:// at all: the evidence-pack print window prints from memory on hilbertraum://print/<token>.
  • resetAdHocDarwinSignature: true re-signs a macOS arm64 binary ad hoc after the flip, before any Developer ID signature (not measured, no Mac).

tests/integration/packaging.test.ts pins the block, checks that the installed electron-builder maps every option and still writes the integrity hash, and fails on asar: false or disableAsarIntegrity.

Re-check the built binary's fuse wire after an Electron bump or a change to electronFuses. Decode it with the library, not by hand. Expected for 43.8.10 (as for 43.8.6 and 43.8.7 since #564): 000011001. Before #564 it was 001011001 (43.7.7 through 43.8.6). release.yml's build-win decodes the Windows exe it packages against verify-mac-build.sh's EXPECTED_WIRE on every run (#769); by hand:

# from the repo root; prints index → state ('0' off, '1' on)
node -e "require('@electron/fuses').getCurrentFuseWire(process.argv[1]).then((w) => console.log(Object.keys(w).filter((k) => /^\d+$/.test(k)).map((k) => String.fromCharCode(w[k])).join('')))" apps/desktop/release/win-unpacked/HilbertRaum.exe

The nine positions on Electron 43.8.10 (unchanged since 43.7.7), as shipped: 0 RunAsNode (off, #562), 1 EnableCookieEncryption (off), 2 EnableNodeOptionsEnvironmentVariable (off, #564), 3 EnableNodeCliInspectArguments (off, #562), 4 EnableEmbeddedAsarIntegrityValidation (on, #562), 5 OnlyLoadAppFromAsar (on, #562), 6 LoadBrowserProcessSpecificV8Snapshot (off), 7 GrantFileProtocolExtraPrivileges (off, #560), 8 (unnamed in @electron/fuses 1.8.0; the binary carries WasmTrapHandlersEnabled) (on). A flipped binary has a new hash; under Smart App Control see "A packaged build that Smart App Control will not start" above.

Check a packaged build's fuses by behaviour too (manual, Windows; the CDP harnesses do it): ELECTRON_RUN_AS_NODE=1 HilbertRaum.exe -e "console.log(1)" must start the app instead of printing, --inspect=127.0.0.1:9229 must leave http://127.0.0.1:9229/json/version unanswered, and a copy of the build with one byte changed inside app.asar must stop with "ASAR Integrity Violation".

Launching from a drive

Copy the portable .exe to the drive root next to the prepared layout, then launch it with HILBERTRAUM_DRIVE_ROOT pointing at the drive root (the drive's launcher sets this; resolvePaths keys off config/drive.json). The app then reads models/, workspace/, config/, etc. from the drive.

⚠️ Producing the actual artifact is a MANUAL step (R2/R5). electron-builder may download the platform Electron binary at build time (R2, dev-only network), and a real USB-drive launch with a live model needs the weights + sidecar binaries that are not in the repo (R5). With npm workspaces, production deps are hoisted to the root node_modules; if electron-builder can't collect them, build from apps/desktop or temporarily disable hoisting. None of this affects npm test / typecheck / npm run build (the green gate), which do not invoke electron-builder.

Module format & renderer bundle — design record (ESM main + code-split)

The TypeScript source is ESM throughout (module: ESNext, moduleResolution: Bundler, noEmit); only the electron-vite output format is a choice. As built:

  • Main process ships ESM (out/main/index.mjs). electron.vite.config.ts sets main.build.rollupOptions.output.format: 'es'; apps/desktop/package.json main points at the .mjs. __dirname doesn't exist in an ESM module, so src/main/index.ts and services/ocr/rasterizer.ts reconstruct it via dirname(fileURLToPath(import.meta.url)) (the same idiom the test suite already uses). db.ts's createRequire(process.execPath) for node:sqlite is unaffected (createRequire is the ESM-native escape hatch).
  • Preload STAYS CommonJS (out/preload/index.js, ocr.js). This is not an oversight: Electron only supports ESM preload scripts when sandbox: false, and both windows deliberately run sandbox: true (spec §0 / "Process model & security"). So format: 'es' is scoped to main only, and "type": "module" is NOT set on the package (which would force .js → ESM and break the CJS preload). A "pure ESM" app is therefore not reachable while sandboxed — main-ESM + preload-CJS is the end state. Main still references ../preload/index.js (CJS) at runtime.
  • Tree-shaking keys off the ESM input graph, which was already ESM — so the ESM-output flip buys none of it. package.json carries "sideEffects": ["*.css"] so Rollup may drop unused exports from our own modules while preserving the side-effectful CSS imports.
  • Renderer code-split (the actual bundle win). streamdown + katex + @streamdown/math (~2 MB) were eager in the initial renderer chunk because AssistantMarkdown — used on the chat, translate, documents-preview, and images screens — statically imported them. AssistantMarkdown now lives in its own module (src/renderer/chat/AssistantMarkdown.tsx) behind a React.lazy wrapper (AssistantMarkdownLazy.tsx, re-exported as AssistantMarkdown from the chat barrel), so that weight loads as a separate async chunk on first answer render. Initial index-*.js: 3,196 kB → 1,194 kB (−63%). The async chunk is Vite-named mermaid-* after a streamdown internal module but contains only streamdown+katex — no real mermaid/cytoscape/d3 (no longer in the tree at all since streamdown 2.6, see above). The fallback renders the raw text in a .md container during the (local, offline, few-ms) load — no blank flash. Tests render markdown synchronously: vitest.config.ts aliases the two specifiers the app imports the wrapper by (./AssistantMarkdownLazy from the chat barrel and Transcript, ../chat/AssistantMarkdownLazy from ReviewScreen; one regex, #815) → the real component, so render assertions don't have to await Suspense. tests/unit/assistant-markdown-lazy.test.tsx imports the wrapper by a longer path the alias doesn't match, so it alone drives the real lazy chunk, and it pins both sides.
  • Route-level code split (full-audit 2026-07-10 PF-6). Six screens — Documents, Settings, Models, Images, Skills, Translate — are React.lazy in App.tsx, each a separate async chunk fetched on first navigation. Initial index-*.js: 1,255 kB → 998 kB (−20.5%); the split-out chunks are DocumentsScreen 124 kB, SettingsScreen 41 kB, ModelsScreen 31 kB, ImagesScreen 27 kB, SkillsScreen 24 kB, TranslateScreen 15 kB. Deliberately eager: the workspace gate + HomeScreen (the first frame) and ChatScreen — Chat is the primary surface (first-run lands there), and splitting it would pull the shared chat components out of the initial chunk, which this record keeps as an explicitly separate decision (same for the two i18n catalogs, the other big initial resident — unminifiable string tables). The suspense point is a quiet localized .screen fallback inside the existing per-screen ErrorBoundary (a failed chunk import lands on the boundary's localized retry fallback); tests/renderer/LazyScreens.test.tsx pins the fallback → content sequence. The −30% aspiration of the finding is therefore not reached screens-only; the remaining headroom is exactly those two exclusions.

Build paths — design record (#646)

One source file, one module, whatever the working directory is called. Built from a working directory spelled with a lower-case drive letter (c:\work\HilbertRaum, which some terminals hand out, VS Code's among them), the main bundle carried 41 of its modules twice, and each copy had its own module-level state.

The facts the design rests on (measured 2026-10-12 on 0ba4ab54, Vite 6.4.3, electron-vite 3.1.0, Vitest 4.1.11, Windows 11):

  • Vite's resolver changes spelling mid-build on Windows. A resolved file becomes its module id through safeRealpathSync. That is fs.realpathSync, which keeps the letter case it is given, until an exec("net use") it fires on first use calls back. After that it is fs.realpathSync.native, the file system's own spelling (C:\…). macOS and Linux use the native call from the start.
  • The configs handed Vite the cwd's spelling. electron-vite (and Vite for the tools and preview configs) finds the config from process.cwd() and sets the config's __dirname from that path, so resolve(__dirname, 'src/main/index.ts') was c:\….
  • What a build from c:\… produced.
    • The entry and its direct imports resolved as c:/…; deeper imports resolved as C:/….
    • Main: 302 modules transformed instead of 261. The 41 duplicated files included i18n, logging, binary-verifier, runtime/sidecar, ipc/inflight and runtime/factory.
    • In every one of the 41, the c: copy had exactly one importer, src/main/index.ts, and everything else bound to the C: copy. So whatever index.ts initialised or registered directly, the rest of the app never saw, and vice versa.
    • Preload, renderer and the tools build came out byte-identical either way.
  • What that broke in such a build (code reading, verified; only the language was observed in the running app):
    • Language. initMainI18n set the OS locale on a copy no message reads: with "system" on a German OS, every main-side message was English.
    • Logging. initLogging configured a copy nothing else logs through. The log never reached disk (app.log.enc untouched), and lock no longer cleared the in-memory buffer (the F14 wipe).
    • Binary verification. initBinaryVerification enforced a copy no spawner checks, so a packaged lower-case build ran its sidecars without the pre-spawn SHA-256 checks.
    • Quit reaper. The last-resort reaper on quit (killRegisteredSidecarChildren) read an empty registry.
    • Chat streaming flag. isChatStreaming was always false, so a document task was not refused while a chat answer streamed.
    • Smaller effects:
      • The answer-speed observer, the engine-problems push and the moved-drive notice never fired.
      • Lock and quit could not cancel the post-unlock benchmark.
      • The "Verify checksum", "Check again" and engine-install re-arms of a latched model cleared the wrong latches.
      • The local API answered its busy race with 502 instead of 429.
  • Who was affected. Local npm run dev / build / package from such a terminal. Not the releases: CI and release.yml build from D:\a\…, and the v0.1.62 Windows portable (SHA-256 as in its SHA256SUMS.txt) has a single i18n copy, as did a local package of 2026-10-05.
  • Vitest has the same split, and the config cannot repair it. The fork's runner keeps the CLI's spelling (file:///c:/…/@vitest/runner), while Vitest canonicalises the setup files and Vite canonicalises the node_modules ids it resolves (C:/…). A second runner instance loads, and every file fails with "Vitest failed to find the current suite". A canonical root and resolve.preserveSymlinks were both tried and both still failed.

The design as built:

  1. Canonical paths. Every Vite config (electron.vite.config.ts, vite.tools.config.ts, vite.preview.config.ts) builds its paths from canonicalCase(__dirname) (apps/desktop/path-casing.ts), and so does each target's root, which otherwise defaults to the cwd as typed.

    • When the path differs from the file system's spelling only in letter case, it returns the file system's spelling; any other path is left as given.
    • Paths that differ in more than case (a junction, a subst drive, a mapped network drive) are not rewritten on purpose: for a mapped drive Vite's own canonical form is the drive letter, not the UNC path native realpath returns.
    • Every target built from c:\… is now byte-identical to the same target built from C:\…. Main, preload and renderer also match the canonical build from before the fix byte for byte, so CI and release output do not change.
  2. The guard. oneModulePerFile() (hilbertraum:one-module-per-file) runs in all five Rollup builds: main, preload, renderer, tools and preview.

    • At buildEnd it maps every module id that names a file to the file's native realpath (plus its ?query) and fails the build if two ids land on one file, listing both spellings.
    • So a split from any cause (the cwd, an import spelled in another case than its file, a link) can no longer ship silently.
    • With the canonical paths reverted, a lower-case build fails it naming all 41 files.
    • Cost: one native realpath per file id, about 120 ms for the ~800 ids of a full build on a Windows box with a virus scanner (about 1 % of the build).
  3. Vitest refuses instead of failing 491 files. vitest.config.ts throws at load when either of these differs from the file system's spelling only in letter case:

    • the working directory;
    • the Vitest CLI path, checked only when argv[1] is Vitest's own vitest.mjs. Another launcher, such as an IDE extension's worker, says nothing about the runner's spelling.

    A lower-case CLI path breaks a run from a canonical cwd too (measured). The message names the real spelling and the way out (CONTRIBUTING "Faster test iteration").

  4. Tests. tests/unit/path-casing.test.ts runs the guard on real Vite builds, with one file reached through a link and, on Windows, through a c: spelling. On Windows it also loads all three configs through their own loaders (electron-vite's and Vite's loadConfigFromFile) from the lower-cased app directory, and asserts that every path they hand Vite has the file system's spelling.

    • A real build is not the regression test: whether it splits depends on when Vite's net use probe answers, so it can pass without the fix.

Real app, before and after (dev build from c:\work\HilbertRaum, a German Windows, uiLanguage: system, a scratch root with D:'s encrypted-drive config):

master fix
Main modules 302 261
Locked-settings and wrong-password errors English German
logs\app.log.enc never written written (2,559 B)
perf.log 5 marks (index.ts's only) 15 marks

Residual (not observed): a build from a junction, subst or mapped-drive spelling that Vite resolves into two forms is not repaired, only refused, by the guard.

Preparing a drive — scripts

scripts/ provisions and verifies a drive. The scripts are self-contained (a drive can be laid out on a fresh machine with no Node/npm); their layout + config shapes mirror the unit-tested apps/desktop/src/main/services/drive.ts (the canonical reference — keep them in sync).

Script Purpose
prepare-drive.{ps1,sh} Create the directory tree, copy manifests + the committed app-skills/ product skills (wholesale, like manifests — S9; user-skills/ is left empty) + user docs + the root license/attribution notices (LICENSE, THIRD-PARTY-NOTICES.md, DRIVE-NOTICES.md — LIC-1), generate config/{drive,policy}.json. -DryRun/--dry-run prints the plan. -Dev/--dev → a plaintext developer drive. -WithAssets/--with-assets then runs fetch-models + fetch-runtime (forwarding -AcceptLicense/--accept-license) for a launch-ready drive — by default fetching a small default set (~10.4 GB: chat model Ministral 3 8B + embeddings + reranker + Whisper transcriber + Qwen2.5-VL vision) plus both sidecar runtimes (llama.cpp + whisper.cpp, the latter Windows-only/best-effort); -AllModels/--all-models fetches every model instead (runtimes either way).
fetch-models.{ps1,sh} Download + resume + SHA-256-verify each weight with a download: block to its models/... path. -Only <id>/--only for one model (exit 2 when no manifest has that id, or its manifest declares no download: block, #767); -Bundled/--bundled for the Kit's bundled set only (#766); -AcceptLicense/--accept-license for the license gate; -DryRun/--dry-run. Real-hash mismatch → delete partial + exit 1. Half a download pair (a top-level download: without one on mmproj or a files: member, or the other way round, which the app refuses) → BLOCK with the validator's message, nothing of that model fetched, exit 1 (#767). Idempotent (present + verified → skip).
fetch-runtime.{ps1,sh} Read runtime-sources.yaml, pick the host build (-Os/-Arch/-Backend overrides; default = the first listed build: Vulkan on win/linux, Metal on mac; -Backend cpu fetches the pure-CPU safety net into runtime/llama.cpp/<os>/cpu/), download + verify the archive, extract into the build's extract_to (chmod +x on mac/linux), and write a .hilbertraum-runtime.json install marker. Idempotent via the marker (version + backend must match — a missing/stale marker re-fetches, so a CPU-era drive actually upgrades). An engine newer than the drive's pin — one the app's in-app update installed while the drive's yaml stayed behind — is kept, whatever its backend, with a line naming both versions (#873; the app's compareRuntimeVersions order, so 3.10.0 is newer than 3.8.1; a version that cannot be ordered re-fetches as before). -AllowDowngrade/--allow-downgrade replaces it anyway, and -Commercial/--commercial always does (a sold drive carries its app's pin; the commercial match stays exact); -DryRun/--dry-run. -Family/--family selects the asset family: llama_cpp (default), whisper_cpp (the transcriber CLI), kiwix_tools (optional; the knowledge-pack tools — kiwix-serve/kiwix-manage/kiwix-search plus, on Windows, the five ICU DLLs; never part of --with-assets, only fetched by an explicit --family kiwix_tools, #339 P8-3), or ocr (the language files + the osd page-orientation data, #538). The DRIVE's runtime-sources.yaml wins over the repo's, so on a drive whose manifests predate a pin bump it re-installs the OLD pin; since #516 it prints a Note when the two pin different versions. To move a drive to the repo's pin: re-run prepare-drive on it (it overwrites model-manifests/ and leaves config/ alone unless -Force), then fetch-runtime (plus -Backend cpu for the safety net and -Family whisper_cpp). The app offers the same update in-app (AI Model screen, #516; architecture.md "In-app engine updates").
verify-models.{ps1,sh} SHA-256 each present weight vs its manifest hash (placeholder → UNVERIFIED; real mismatch → fail/exit 1; no runtime, or a runtime/format pair the app does not run → UNSUPPORTED, #767). -Generate/--generate writes config/checksums.json (entries: [] when there is no manifest, #767). -Strict/--strict fails unless every manifest's weight is VERIFIED; -Kit/--kit is the same gate over what a Kit ships (the bundled set + any model with a file on the drive; the rest is listed as CATALOG, #766).
setup-dev.{ps1,sh} Dev bootstrap: NODE_OPTIONS=--use-system-ca npm ci (R6, set only when Node ≥ 22.15 supports the flag; skipped gracefully otherwise; npm ci = lockfile-exact, never rewrites package-lock.json — issue #49, the dev half of hardening L-8) + build + test smoke.
release-issues-section.sh Not drive prep: .github/workflows/release.yml runs it while building a tag and appends its output to the release notes. It emits an "Issues resolved" section — the ISSUES closed by the PRs merged since the last published release (the same baseline GitHub's own generated "What's Changed" uses, so the two agree), resolved via each commit's associated PRs + closingIssuesReferences rather than by parsing "(#N)" out of subjects (which would miss true merge commits). Read-only gh API calls, so it is locally testable: scripts/release-issues-section.sh HilbertraumAI/HilbertRaum master. Best-effort by design — a failure is downgraded to a workflow warning, so release notes can never block a release build.
verify-electron.mjs Root postinstall (runs on every npm install). Detects a genuine HALF-EXTRACT — path.txt present but dist/version or the platform binary missing, or the binary zero-length (the silent NTFS-on-Linux failure) — force-re-extracts it, and otherwise fails with an actionable message instead of leaving the opaque electron-vite Electron uninstall error for later. Since wave DEP-4 it is version-aware: on Electron ≥ 42 an absent path.txt is NORMAL (lazy download) and the script exits 0 silently, even beside a dist/version (#769: Electron's own install.js reads that as not installed and extracts again on first use); on ≤ 41, which still ships the postinstall, an absent path.txt is still a broken install. Cross-platform Node (not a shell mirror); the decision half is pure and unit-tested in tests/unit/verify-electron.test.ts, which also runs the script from a scratch copy against a stub electron package. Skips via HILBERTRAUM_SKIP_ELECTRON_CHECK / ELECTRON_OVERRIDE_DIST_PATH / ELECTRON_SKIP_BINARY_DOWNLOAD (the last honoured by this script only — Electron ≥ 42 ignores it).
verify-mac-build.sh + lib/packaged-app-probe.mjs Not drive prep, not CI: the owner-run check of a packaged build (#560, #562). On a Mac the shell script builds (or takes) the .app, checks the fuse wire, the signature, the entitlements and the app.asar integrity hash, exercises the fuses, then launches the app and runs the probe; on Windows and Linux the probe runs alone against a packaged build started with --remote-debugging-port on a scratch drive root. "Verifying a packaged build on macOS" below.

The asset download / verify / plan logic is mirrored from the unit-tested apps/desktop/src/main/services/assets.ts (the canonical reference for that logic — keep in sync), exactly as prepare-drive mirrors drive.ts. The default-set model-id list itself, however, is NOT in assets.ts: it lives only in scripts/prepare-drive.ps1 ($DefaultModelIds) and scripts/prepare-drive.sh (DEFAULT_MODEL_IDS), and must be kept in sync between those two shells and with the manifests under model-manifests/ — editing assets.ts does not change which models --with-assets fetches (a parity test, tests/unit/prepare-drive-default-set.test.ts, asserts the two shells' lists match and that every id is a committed manifest --with-assets can fetch; tests/integration/script-orchestration.test.ts runs both twins' --with-assets --dry-run and checks that each fetches these ids, then both runtimes and the ocr family, so a Windows-vs-mac/linux drive can't silently drift on OCR provisioning). (scripts/ also holds two benchmark/RAM-calibration helpers that are NOT part of drive prep — benchmark-speed.ps1 (decode speed) and measure-peak-rss.ps1 (co-resident peak RSS); see model-benchmarks.md for how they are run.) The scripts use the OS-native downloader (curl / wget) — no new npm/script deps. The fetch-models scripts additionally prefer aria2c when it is installed; fetch-runtime uses curl only. The .sh twins fall back to wget; the .ps1 twins have no fallback and stop with "No downloader found" (fetch-models: that file fails, exit 1; fetch-runtime: exit 3), because every Windows from 10 1803 on ships curl.exe (PowerShell 7 on macOS/Linux runs the system curl). They carry no PowerShell download line on purpose (#767): their old last resort, Invoke-WebRequest, has no literal -OutFile in PowerShell 5.1 (a [ in the drive path broke it), and its replacement, (New-Object System.Net.WebClient).DownloadFile(…), got a copy of fetch-models.ps1 quarantined by Norton (IDP.HELU.PSD11) — the shape antivirus heuristics read as a malware download cradle, on a script that ships on every Kit. script-drift.test.ts keeps both out.

Resilient downloads (flaky-connection hardening). curl's own --retry does not retry a mid-transfer drop (exit 18/56/28) on older curl, so a beta tester whose link dropped during a curl lost the whole download. Every curl call now goes through a small wrapper (Invoke-CurlResilient in the .ps1 scripts, curl_resilient in the .sh scripts) that runs an outer retry loop (5 attempts, growing back-off) and resumes the partial file with -C - on each attempt — so a download survives several disconnects rather than restarting from zero. Per-call flags were also strengthened: --retry 3 --retry-delay 2 --retry-connrefused --connect-timeout 30 (all available on the curl that ships with Win10 1803+/git-bash). Integrity is still enforced by the SHA-256 pin AFTER download, so resuming a partial transfer can never weaken verification. aria2c (when present) already resumes via --continue=true; wget via -c.

Extracting a runtime archive (#767). fetch-runtime unpacks a .tar.gz (the macOS/Linux builds) with tar, and a .zip with unzip/ditto (.sh) or .NET's ZipFile (.ps1). Windows has three traps, each avoided on purpose: the .ps1 runs Windows' own bsdtar (%SystemRoot%\System32\tar.exe, Windows 10 1803+) by full path, because in a PowerShell started from Git Bash the first tar on PATH is Git's GNU tar, which reads the C: of an archive path as a remote host; the .sh hands tar the archive on stdin (-f -) for the same reason under Git Bash; and the .ps1 avoids Expand-Archive, which in Windows PowerShell 5.1 reads its destination as a wildcard pattern and stops on a drive path holding [. Windows and FAT/exFAT cannot hold the tarballs' version symlinks, so tar fails there and each missing link is copied from its target. Any other tar failure (an archive it cannot read, a member it could not write) fails the run with tar's own message, and a link whose name or target leaves the extract dir is refused. script-fetch-runtime.test.ts runs both twins through these steps over archives served from file:// URLs, offline, on a drive root whose name holds [ (#769).

End-to-end (Windows example). -WithAssets alone provisions the default chat model for a fast, launch-ready drive; add -AllModels to pre-load every model (a fully provisioned commercial drive):

.\scripts\prepare-drive.ps1 -Target E:\ -WithAssets -AllModels -AcceptLicense  # layout + download + verify (all models)
.\scripts\verify-models.ps1 -Target E:\ -Generate                              # record real hashes
npm run package:win                                                            # build the portable .exe
copy ".\apps\desktop\release\HilbertRaum-*-portable.exe" E:\                    # place the launcher on the drive

✅ runtime-sources.yaml is pinned to a real release (ggml-org/llama.cpp b12110 — the build named by upstream's stable v0.9.0, bumped from b11146 under #729; real per-OS URLs + SHA-256 checksums from the official GitHub Releases API digest metadata, all five also confirmed by local download) — fetch-runtime downloads, verifies, extracts (zip and tar.gz) and flattens the binaries for all three OSes from any host, and leaves out llama-connect, the peer-to-peer tunnel program every archive carries since v0.8.0 (neverInstalled, model-policy.md licence record). A real fetch + the manual smokes on the pin are REQUIRED (they cannot run in offline CI; #729 records what ran on b12110 and what is still open — the MTP start on the 24 GB rig, the other five catalog chat models' quality gate on ps-work, and the macOS asset). The win/linux default is the Vulkan full build (GPU acceleration with built-in CPU degradation) plus a pure-CPU safety net at runtime/llama.cpp/<os>/cpu/ — see drive-layout.md and the architecture.md GPU record. The chat/embeddings model URLs are real Hugging Face links and the bundled manifests now carry real pinned sha256 hashes (captured from verified downloads via verify-models --generate); a model you add yourself stays REPLACE_WITH_REAL_HASH until you capture its hash the same way. To bump the runtime pin later, see model-policy.md.

Or the older manual flow (no download): prepare-drive (no -WithAssets) → drop GGUF weights into E:\models\… + llama-server into E:\runtime\llama.cpp\win\ by hand → verify-models -Generate.

Build-time network ≠ runtime network. The fetch-* scripts make the project's first deliberate network access, but they run on the builder's machine at build time. The app stays 100% offline by default; the in-app downloader is triple-gated (policy ceiling ∧ user setting ∧ per-download confirmation) and downloads are policy-permitted in both prepare-drive postures — update checks + telemetry stay denied, matching the commercial final check below (gate semantics: model-policy.md "The in-app downloader"). This does not weaken the offline guarantee.

These artifacts (weights, sidecar binaries, the workspace DB, logs, the portable .exe) are all git-ignored — they live on the drive, never in the repo.

Plug-and-play commercial drive

A non-technical buyer must be able to plug in, double-click one icon, and chat — no Docker, no installer, no terminal. The chosen mechanism is the portable bundled app + a tiny native launcher:

Approach Plug-and-play for a non-technical buyer? Verdict
Docker container ❌ Needs Docker Desktop (multi-GB install, admin rights, daemon, paid for larger orgs); GPU passthrough painful on Win/Mac Rejected
System installer (.msi/.pkg) ⚠️ Admin rights, writes to the host, breaks "your data lives on the drive, move it between laptops" (success criterion #10) Rejected as default
Portable bundled app on the drive (electron-builder portable + launcher) ✅ Plug in → double-click → runs; nothing written to the host; drive movable Chosen

The classic portable-Electron pitfall (settings leaking into %APPDATA%) does not apply: resolvePaths() redirects all state (workspace DB, logs, config, models) onto the drive. First-run polish is services/preflight.ts (writable/free-space/slow-drive checks, friendly + non-blocking, surfaced on Home); encrypted-by-default onboarding is kept.

The launcher (sets HILBERTRAUM_DRIVE_ROOT from its OWN location)

The drive root ships an obvious, double-clickable launcher (spec §6 names). Source templates live in launchers/ and are copied to the drive root by the pipeline:

OS File What it does
Windows Start HilbertRaum.cmd %~dp0 → drive root → set HILBERTRAUM_DRIVE_ROOT → spawn the portable .exe.
macOS Start HilbertRaum.command cd "$(dirname "$0")" → export HILBERTRAUM_DRIVE_ROOT → exec the .app binary. exFAT holds no symlinks, so a drive normally carries the HilbertRaum-<version>-mac-arm64.app.zip: the launcher unpacks it once with ditto into $HOME/Library/Caches/HilbertRaum/<zip name without .zip>/, and runs the bundle from there. Each start unpacks into its own <zip name without .zip>.partial.<pid> folder beside it and publishes that folder only when an .app with its app binary landed in it (#769, #887). Every start, also once the cache is published, first removes the partial folders of its zip whose start has ended, and only those: a PID that is no longer running, another user's, or the start's own, and a name that is no PID (empty, starting with 0, or holding anything but digits). So a second double-click during the first unpack leaves that unpack alone, and the next start removes what a stopped one left, a copy it left nested inside the published cache included; the second start then uses whichever copy was published first, drops a copy of its own that a concurrent publish nested inside the cache, and drops its own copy when a concurrent publish won the rename (#887). A start never reuses a partial folder: one of its own PID that the sweep could not remove stops it with "An earlier unpack at '…' could not be removed", naming the folder to delete. A partial folder that cannot be created at all (a full disk, a cache folder that cannot be written) stops it with "Could not create '…'" instead (#919). An archive with no .app stops with "found no .app inside it", an .app without its app binary with "the app inside it lacks its program file", and a publish that fails with no copy published with "Could not finish unpacking" (#887). An extracted .app at the root runs in place.
Linux start-hilbertraum.sh same, next to the AppImage.
all READ ME FIRST.txt friendly first-run + SmartScreen/Gatekeeper instructions.

All three launchers refuse to start while more than one app artifact of their kind sits at the drive root (two portable .exes, two AppImages, two .app.zips, or an extracted .app beside a zip), naming the files to delete and never deleting anything themselves (#235); --check (/check on Windows) prints the drive root, the manifests folder the app will read and the app it resolved, and exits without starting it. tests/integration/launcher-execution.test.ts executes all three in scratch roots.

The Mac unpack cache is shared by every start and every version (#887, a contract for #849). Anything that prunes $HOME/Library/Caches/HilbertRaum/ must leave each *.partial.<pid> folder alone while its PID is running, whatever version it unpacks: a start is still writing into it, and two Kits of different versions can unpack on one Mac at the same time. The launcher itself removes, on every start, only the dead partial folders of the zip it starts; another version's partials and caches stay for #849.

⚠️ No hardcoded paths — drive letters change per machine. The launcher derives the root from its own location every launch (%~dp0 / dirname "$0"), so the same drive works on a second laptop with a different letter/mount and continues the same encrypted workspace (success criterion #10). tests/integration/launcher-execution.test.ts runs each launcher in a scratch root.

Autorun is dead. Windows disabled autorun.inf from removable drives, so the app cannot auto-launch on plug-in (and must not try — it looks like malware). The drive opens a file window and the buyer double-clicks the well-named launcher.

Code signing & notarization (the make-or-break, mostly-manual task)

An unsigned .exe/.app launched from USB trips Windows SmartScreen / macOS Gatekeeper, and a non-technical user gives up. The electron-builder.yml hooks are wired but driven entirely by env vars / a git-ignored secrets file on the build machine — secrets NEVER enter the repo, and the green gate does not sign (it never invokes electron-builder).

  • Windows (win.signtoolOptions): supply the OV/EV cert via WIN_CSC_LINK (path/URL to the .pfx or base64) + WIN_CSC_KEY_PASSWORD. Signing lets SmartScreen build reputation for the publisher; Microsoft's current guidance treats certificate types alike for this, so an OV certificate or a cloud signing service (Microsoft's Artifact Signing, formerly Trusted Signing) is the cost-effective choice — confirm against Microsoft's code-signing documentation before buying. The launcher .cmd is a script (not signed); the portable .exe it spawns is signed — that is what SmartScreen evaluates.
  • macOS (mac.notarize + hardenedRuntime + build/entitlements.mac.plist): supply the Developer ID Application cert via CSC_LINK/CSC_KEY_PASSWORD and the notarization creds via APPLE_ID / APPLE_APP_SPECIFIC_PASSWORD / APPLE_TEAM_ID. electron-builder auto-notarizes when those are present. Without notarization a USB-launched .app is quarantined.
  • Unsigned DIY fallback ("More info → Run anyway" / right-click → Open) is documented in docs/troubleshooting.md — acceptable for technical users, not for the commercial drive.
  • .gitignore excludes *.pfx/*.p12/*.cer/*.key/signing.env/*.provisionprofile.
  • Procurement risk R7: code-signing certs (esp. EV / Apple Developer) cost money + lead time, and block only the commercial acceptance, not the DIY path.

The build-commercial-drive master pipeline

One self-contained, dual-shell script (scripts/build-commercial-drive.{ps1,sh}) runs the ordered steps; the order lives in the two twins alone (tests/integration/script-orchestration.test.ts runs their dry pipeline). The final "is this sellable?" verdict comes from calling assertCommercialDrive itself (apps/desktop/src/main/services/commercial-drive.ts; see "The builders refuse to proceed" below, #233).

prepare-drive  --force            # commercial policy (encrypted, plaintext off, no phone-home)
                                  # + the root license/attribution notices (LICENSE,
                                  # THIRD-PARTY-NOTICES.md, DRIVE-NOTICES.md — LIC-1)
fetch-models   --bundled          # the bundled set's verified weights (#766; a preloaded weight needs an approved,
                                  # redistributable license — spec §13); every other manifest is the in-app catalog
fetch-runtime                     # verified llama.cpp sidecar builds: per OS the default (Vulkan/Metal)
                                  # + the pure-CPU safety net on win/linux
[--kiwix-source-dir <dir>]        # OPTIONAL, un-numbered (#339 P8-4): install the kiwix-tools
                                  # corresponding-source bundle (SOURCE FIRST), then fetch the
                                  # kiwix_tools binaries for every Kit platform. Omitted = this
                                  # Kit ships no kiwix-tools at all.
package + sign + notarize         # MANUAL — secrets never in the repo (pass --app-artifact / --skip-package)
copy launcher + portable app + user docs -> drive root
verify-models  --generate         # capture real hashes -> config/checksums.json
final check: THE canonical gate — node apps/desktop/out/tools/assert-commercial-drive.mjs (built by npm run build)
             commercial posture (encrypted, no phone-home — downloads OK, update-checks + telemetry denied)
             + every shipped weight VERIFIED and approved, at least one model bundled (#766)
             + runtime install markers match the pin AND record a matching binary hash (#234),
               and every further file a marker records is there with its bytes (#998)
             + exactly one app artifact + the launcher per declared platform (--platforms; #233)
             + no user data: nothing but empty folders in workspace/ and logs/,
               no config/workspace.json or config/working-copy-lost.json (exact, or
               with a .<suffix>, any case), and every
               one of those folders readable (#893)
             + app skills provisioned (app-skills/) + user-skills/ empty (Skills S9)
             + root license/attribution artifacts present + non-empty (LIC-1)
# Windows (supply the pre-built, signed artifact(s); or -SkipPackage to assemble + sign yourself — NOT SELLABLE until the apps are on the drive)
.\scripts\build-commercial-drive.ps1 -Target E:\ -AcceptLicense -Platforms win-x64 -AppArtifact .\apps\desktop\release\HilbertRaum-0.1.0-portable.exe
.\scripts\build-commercial-drive.ps1 -Target E:\ -AcceptLicense -DryRun        # print the plan; the gate still runs and prints its verdict
.\scripts\build-commercial-drive.ps1 -Target E:\ -VerifyOnly                    # only the gate, against the drive as it is
.\scripts\build-commercial-drive.ps1 -Target E:\ -AcceptLicense -KiwixSourceDir D:\kiwix-source-archive -AppArtifact .\apps\desktop\release\HilbertRaum-0.1.0-portable.exe -Platforms win-x64
# macOS / Linux (--app-artifact repeats, one per platform in --platforms)
scripts/build-commercial-drive.sh --target /Volumes/HILBERTRAUM --accept-license --platforms mac-arm64,linux-x64 \
    --app-artifact ./apps/desktop/release/HilbertRaum-0.1.0-mac-arm64.app.zip --app-artifact ./apps/desktop/release/HilbertRaum-0.1.0.AppImage \
    --kiwix-source-dir ~/kiwix-source-archive

The builders refuse to proceed when a differently named HilbertRaum-* artifact (or an extracted .app) already sits at the drive root — delete the old build first (#233; the launchers must never find two) — and when an --app-artifact path does not exist. Both refusals come before step 1, so no download runs first (#769: the missing artifact used to surface at step 4). --platforms declares the platforms the kit is sold for (default all three: win-x64, mac-arm64, linux-x64 — decision #229 on its default); the kit's label names them and the gate requires the artifact + launcher for each and none for any other. Every fetch-runtime run gets --commercial (#234): a placeholder hash is refused before any download, a hashless install marker is re-fetched instead of skipped, and the marker records the file hashes only after a verified archive. Since #998 every fetch-runtime run records the hash of every file the archive put in the install folder (never the cpu/ net's, which has its own marker), and re-fetches an install whose marker records a file that is gone.

What a Kit ships: its bundled set, with the rest as an in-app catalog (#766, owner call 2026-11-02). A Kit preloads only the manifests flagged bundled_on_preconfigured_drive: true: today Qwen3 4B Instruct (chat), multilingual E5 small (embeddings) and Whisper small (transcriber), 3.2 GB together. Every other manifest stays on the drive as the catalog the buyer downloads from in-app, behind the app's own license gate (TranslateGemma's acknowledgement checkbox among them). Before #766 the flag was advisory: step 2 fetched every downloadable weight (310 GB over 31 manifests), and the gate demanded every manifest VERIFIED and approved, so no Kit could pass while the catalog held TranslateGemma's deliberately pending review. The rule, the same in assertCommercialDrive and in the native pre-flight (verify-models --kit): a model ships when it is bundled or has any file on the drive (its weight, projector or an extra file: a half-installed preload is still a shipped model). Every shipped model must be VERIFIED with its review approved, and at least one model must be bundled. A model with no file on the drive is catalog, listed and not checked. The native license pre-flight looks at the weight file only; a model with just its projector or an extra file on the drive fails the weight check and the canonical gate instead. A non-bundled model with an open review and its weight on the drive (a drive built before #766) is reported with the fix, which is deleting the weight rather than approving the review. fetch-models --bundled exits 1 when it plans nothing, so a lost flag stops step 2 before the runtime downloads. The committed set is pinned in committed-catalog.test.ts, where each member must be approved, with real hashes and a live source.

The corresponding-source bundle (a preloaded Kit only, #339 P8-4). -KiwixSourceDir / --kiwix-source-dir <archive dir> is an OPTIONAL, un-numbered step that runs right after the OCR fetch: it points at a maintainer-local directory holding the five pinned kiwix-tools copyleft source tarballs (never committed to this repo) and runs scripts/install-kiwix-source-bundle.mjs, which copies + re-verifies each archive against runtime-sources.yaml's kiwix_tools.source_bundle pin into runtime/kiwix-tools/source/ and writes a generated SOURCES.md there. SOURCE FIRST: only once that succeeds does the builder run fetch-runtime --family kiwix_tools for the three Kit platforms (win-x64, mac-arm64, linux-x64 — explicit -Os/-Arch each, never inherited from the yaml's build order), so a failed or aborted install can never leave kiwix-tools binaries on the drive without their source. Omitting the flag means this Kit ships no kiwix-tools at all: a commercial build that cannot carry the source archives must not ship the binaries; the buyer installs the (unbundled) family in-app instead — their own download, their own consent. The sell gate's checkSourceBundle (assertCommercialDrive) fails a drive that carries any kiwix_tools binary — including a hand-placed, marker-less one — without a complete, hash-matching bundle plus a non-empty SOURCES.md beside it.

The final automated check asserts the commercial posture (policy.json: encryption required, plaintext off, models must verify, no phone-home — model downloads are a permitted user action, but update-checks + telemetry are denied) and that every weight the Kit ships is VERIFIED (#766) and that no user data is present (spec §12.2: workspace/ and logs/ hold nothing but empty folders, and config/ holds no workspace.json or working-copy-lost.json, exact or with a .<suffix>, in any case; the gate names each leftover, OS litter such as a Finder .DS_Store in those folders counts too, and a folder it cannot list or a file in a folder's place fails the check as unreadable, #893) and that at least one trusted product skill is provisioned under app-skills/ while user-skills/ ships empty (Skills S9) and that every declared platform has exactly one app artifact of the version being built plus its launcher (#233) and that every sidecar binary matches the SHA-256 its install marker records (#234), as does every further file a marker records (#998: an engine copy that lost a DLL fails; a marker that records only the binary passes) — the canonical gate is assertCommercialDrive(...), and since PR #271 both scripts call it (through the built apps/desktop/out/tools/assert-commercial-drive.mjs; npm run build produces it, node runs it): SELLABLE is printed only from its verdict, the scripts' own native checks are a pre-flight, not a second gate. (#1028: their marker pre-flight reads only the version and backend, loosely, and can pass a marker that is cut short or damaged; the canonical gate refuses it and is the authority.) Run by hand, the tool takes --target <root> --platforms <list> --app-version <v> [--json] and exits 0 (sellable, or --help), 1 (not sellable) or 2 (a usage error, an unknown platform included); --json prints the verdict as one { ok, problems, checks } line on stdout and sends any log line to stderr (#767). "Every weight VERIFIED" spans every shipped runtime family (2026-07-01): the verifier + verify-models.{ps1,sh} gate on the canonical (runtime → format) support table (models.ts SUPPORTED_RUNTIME_FORMATS), so the bundled ggml / whisper_cpp transcriber verifies by SHA-256 like any GGUF — previously it was reported UNSUPPORTED, which meant a drive that bundles Whisper could never pass -Strict / the sell gate. The gate also requires the three root license/attribution artifacts (LIC-1, full-audit 2026-07-12b): LICENSE (the app's GPL-3.0-or-later text), THIRD-PARTY-NOTICES.md (bundled npm packages), and DRIVE-NOTICES.md (GENERATED — runtime-binary + model-weight attribution derived from model-manifests/** and the pinned texts under licenses/, plus the GPLv3 source-availability statement; regenerate with node scripts/generate-drive-notices.mjs). prepare-drive copies them to the drive root in step 1; a missing or empty artifact fails the SELLABLE verdict (assertCommercialDrive, which both scripts call; freshness/coverage enforced by tests/integration/drive-notices.test.ts, list parity by script-drift.test.ts, the scripts' behaviour by script-execution.test.ts). Remaining manual acceptance (R5/R7): a real signed build + notarization + a USB-drive §17 demo on a fresh laptop with Wi-Fi off, and the second-laptop continuity check.

Continuous integration (CI) — the automated green gate

.github/workflows/ci.yml runs the exact pre-release command chain — npm ci → npm run typecheck → npm run build → npm test — on every pull request and on pushes to master, on ubuntu-latest and windows-latest (Windows is first-class for this project) × Node 22.x and 24.x, plus one macos-15 leg on Node 24.x (#753, below). It is the machine backstop the audit asked for (TEST-N1): before CI, the suite was green only by author discipline, and the repo's own anti-false-green check (tests/full-suite-guard.ts) only mattered if something ran it. The legs are deliberately asymmetric since #458: each windows leg is split into two --shard jobs, the ubuntu legs and the macOS leg run the whole suite. So seven legs (build-and-test (ubuntu 22.x) / (windows 24.x, 1 of 2) / …) plus a tiny ci-success aggregate job that passes only when every leg passes — mark ci-success the required status check on master. Its name is stable even when the matrix labels, the Node list or the shard count change (#458 renamed all six legs), so branch protection never silently stops matching; never mark an individual leg required.

Why one macOS leg (#753, the TS-7 owner call, 2026-11-01). macOS is a supported platform, and until this leg no test had ever run on one: the release workflow's build-mac packages without running npm test. One leg, on the runner and the Node that job builds with (macos-15, Apple Silicon, Node 24), is enough for what only a Mac can show: the POSIX-only rows on a real one, and script-execution's .sh leg under stock Bash 3.2, at PR time rather than at a tag (v0.1.60's mapfile failed only once the tag was pushed). It proves the suite, not the app: nothing here launches Electron, so the packaged-app checks under "Platform verification" stay manual.

The macOS label is pinned, and shared with build-mac, on purpose. GitHub keeps the latest two macOS images and fails a retiring one in scheduled brownouts before removing it. macos-14 went that way on 2026-11-02 (runner-images#13518), and build-mac was the only thing using it, so nothing showed the notice: a release in a brownout window or after the retirement would have failed at the Mac build. The PR leg now shows a brownout months ahead, as a cancelled macos 24.x job with a "runner image brownout" annotation and a red ci-success: it is not a test failure. Move both labels together.

Why the windows legs are sharded and the ubuntu ones are not (#458). The npm test step was 483–542 s of a 10–14 min windows leg against ~5 min for a whole ubuntu leg, so the windows legs ran at their budget and any unlucky file failed a run no code change could have broken — five such flakes in two days, each costing a full re-run. Two shards halve the wall clock and with it the window a noisy neighbour can hit; runner minutes are free on a public repo, so the extra jobs cost only queue time.

What it actually bought, measured (run 34662589439 — the first run in which the shard flag really reached vitest; see the forwarding note below for why the earlier ones did not):

before after
windows Test step 483–542 s 221–239 s
windows job 10–13 min 5.3–5.7 min
critical path windows, 13.3 min 5.7 min — windows is no longer the long pole (ubuntu 4.9–5.3 min)

The gain beats a halving, because per-file overheads fall too: per-file test cost went 2.22 s → 1.65/1.99 s, and the two shards together spend less total test time than the single unsharded run (816 s vs 997 s). So the earlier framing here — "sharding halves exposure, not crowding" — was too strong: pressure per runner genuinely eases, plausibly because each runner now accumulates only half the leaked sqlite handles and locked temp roots of #460 (correlation, not a proven cause). Each shard at first still ran vitest's default availableParallelism() - 1 forks — three, plus the main process, on a 4-core runner (now capped at two on these legs; see "The windows CI legs run one fork fewer" below) — so the CI-aware testTimeout/hookTimeout above are still what buy tolerance when a fork is starved; the two changes address different halves of the problem. Ubuntu stays whole for a reason beyond cost: one leg per Node version still runs all 449 files in a single vitest process, so cross-file interference (shared module state, a leaked global, an ordering dependency) keeps a leg that can still see it; a fully sharded matrix would partition that surface away everywhere at once.

#460 has since been fixed (2026-09-13): the leaked handles and locked roots above no longer accumulate. The per-file test teardown (tests/setup-temp-roots.ts) now closes every node:sqlite handle a test file left open — 1,709 of the 2,306 a full run opens, across 120 files — before it removes that file's temp roots, so on Windows the post-run sweep went from ~1,500 roots per run to 1, and that one is the harness's own temp-roots.test.ts exercising the deferral on purpose (design: tests/helpers/sqlite-handles.ts). Locally it bought no speed worth quoting (201 → 189 s, within noise), as #458 predicted: this is hygiene, not a CI-budget lever. What to look for on a run: the temp roots: N deferred root(s) line at the end of the Test step reads 1 on the ubuntu legs and on whichever windows shard owns temp-roots.test.ts, and is absent on the other shard. A higher count is a new leak — worth a look, not a re-run.

The collection guard is shard-aware — and must stay that way. tests/full-suite-guard.ts asserts vitest actually collected every file it should, which is what makes a silently dropped suite fail instead of passing by not running. A shard legitimately collects half, so the guard reproduces vitest's own split (shardTestFiles) and asserts the shard's expected subset; the union of the shards is still every file, so a dropped file fails whichever shard owned it. Three traps, all already paid for:

  • Never "shard" by passing a path (npm test -- tests/unit). A positional argument reads as a filter, so the guard switches itself off silently — retiring the exact protection it exists for, with no signal. --shard is a flag, so the guard stays on and merely narrows. The space form --shard 1/2 puts its value in argv looking like a path, which the config now skips explicitly; CI uses --shard=1/2.
  • The split is hashed over / + the POSIX root-relative path — vitest resolves paths with pathe, which normalises away from \, so the assignment is identical on every platform. Reproducing it with node's native path.resolve type-checks and looks equivalent but hashes \tests\unit\x.test.ts on Windows and assigns a different half: the first implementation here did exactly that and agreed with a real --shard=1/2 run on 109 of 225 files, i.e. chance. Fixed sha1 vectors in tests/unit/full-suite-guard.test.ts pin the hashed string so the mistake cannot return unnoticed on a machine where sep === '/'.
  • A vitest upgrade can switch the guard off without a type error. Vitest 4 removed the onFinished hook the guard implemented; the old method still compiled, and the guard went inert until it was ported (wave DEP-6, architecture.md "Dependabot triage — wave DEP-6" §5). The hook is now typed through Reporter['onTestRunEnd'], and a unit test compares shardTestFiles with the installed vitest's own BaseSequencer.shard, so either kind of drift fails at the desk instead of on the sharded legs.

Passing a flag through npm test needs the root script's trailing -- (#458). The root test script forwards to the workspace — npm run test --workspace apps/desktop -- — and that trailing -- is load-bearing. A positional survives two npm layers (npm test -- tests/unit has always worked), but a flag does not: without the --, the inner npm run swallows --shard=1/2 as an npm config and only prints npm warn Unknown cli config "--shard". The first sharded CI run hit exactly this and silently did nothing — all six legs ran the whole 449-file suite and merely looked slow (run 34660709148; every leg reported (449)). Nothing failed, because the guard was correctly enforcing all 449 and all 449 had run. When adding a CI leg that passes vitest a flag, check the leg's Test Files line really shows the reduced count, and treat an Unknown cli config warning in a run log as an error.

Why both Node majors, and why the explicit pinned-npm install (AUD-26). The two versions are the two ends of what the repo claims, and each was previously an unexercised claim: 22.x is the engines.node >= 22.12 floor the app promises to run on (raised from 22.5 by Electron 43 — wave DEP-4, architecture.md "Electron 39 → 43" record; node:sqlite itself only needs 22.5), and 24.x is what every release.yml leg builds under — including the Windows leg that re-runs the full suite on the tagged commit. Gating only one leaves the other a declaration nothing tests. A npm install -g [email protected] step (right after actions/setup-node, before npm ci) makes the pinned packageManager: [email protected] the npm that actually installs on every leg: Node 22 bundles npm 10.9, which is below the root engines.npm >= 11 floor, and Node 24 bundles a different 11.x — neither is the pin. The step prints node -v / npm -v so the run log carries the evidence. corepack enable was tried first and does NOT work here — the PR run log proved its npm shim did not take precedence, so the bundled npm ran on every leg (10.9.8 on Node 22, 11.16.0 on Node 24); the explicit global install is the reliable mechanism and replaced it.

Why it can run with zero weights / zero network / zero binaries: the unit + integration suite is offline by construction — mock runtime, mock embedder, electron mocked — and nothing in typecheck/build/test launches Electron. So the ~100 MB Electron platform binary is never needed in CI. One test broke that from 2026-09-17 until #795: reranker-callbacks-composition reached ipcMain unmocked, and loading the real electron package made every leg download the binary from GitHub mid-run; a GitHub 504 on 2026-11-08 turned four legs red. It mocks electron now, and ELECTRON_MIRROR (table below) makes any such test fail at once instead of downloading.

How that works changed with Electron 42 (wave DEP-4, 2026-08-18). Electron removed the postinstall binary download as supply-chain hardening: the package declares no scripts at all, install.js survives only as an install-electron bin, and index.js downloads lazily — it reads path.txt and, when that or the binary is missing, spawns the installer on first use of the electron bin. Two consequences worth stating plainly, because both have already bitten:

  • ELECTRON_SKIP_BINARY_DOWNLOAD is dead. Electron ≥ 42 does not read it anywhere. It was removed from ci.yml rather than left in place advertising an effect it no longer has. scripts/verify-electron.mjs still honours it as its own knob for older checkouts.
  • A fresh npm ci legitimately leaves NO path.txt. Anything that treats an absent path.txt as a broken install is now wrong. verify-electron.mjs did exactly that until DEP-4 rewrote it, and would have re-created the very download Electron had just removed, on every clean install, while printing a false NTFS diagnosis. Its check is now version-aware — Electron 39 and 41 still HAVE the postinstall, 42 and 43 do not — because the documented Electron-43 fallback ladder includes ^41.7.2.
Env var (CI only) Effect
HILBERTRAUM_SKIP_ELECTRON_CHECK=1 scripts/verify-electron.mjs early-exits. Now belt-and-braces rather than load-bearing: the script already exits 0 when the binary is merely not downloaded yet. It stays because it also skips the check on a genuinely half-extracted tree, which CI can neither repair nor usefully diagnose.
ELECTRON_OVERRIDE_DIST_PATH Points at an out-of-tree Electron build; the one env var Electron ≥ 42's index.js still reads. Not set in CI.
ELECTRON_MIRROR=http://127.0.0.1:9/, force_no_cache=true #795: Electron's lazy download goes to a dead local port and skips @electron/get's cache, so the suite can never fetch the binary. A test that loads the real electron package unmocked fails at once, on every leg, with "Electron failed to install correctly"; mock electron in that file.

Getting the binary on a dev box: it arrives by itself the first time anything runs the electron bin (npm run dev, npm run package:win). To materialize it deliberately — e.g. so tests/integration/evidence-pack-pdf-smoke.test.ts (the only automated coverage of real Chromium printToPDF) does not skip — run npx electron --version once. That test now says so out loud when it skips for this reason; before DEP-4 it went silent, and the E43 bump dropped 6 tests with no failing signal at all.

npm downloads are cached via actions/setup-node (cache: npm, keyed off the root package-lock.json); concurrency: cancel-in-progress cancels a superseded run when a branch/PR is pushed again. All third-party actions in ci.yml and release.yml are pinned to full commit SHAs with a # vX.Y.Z comment (the cla.yml idiom — a movable tag like @v4 would let a compromised action repo inject code into CI; full-audit 2026-07-10 SC-1). This is dev infrastructure only — it ships nothing to users, adds no telemetry/analytics, and performs no network egress beyond the registry install (the "no cloud / no telemetry" hard rule governs the shipped app at runtime).

Both vitest budgets are CI-aware, for the starvation described above (#458). A fork on a saturated runner can be descheduled for 10+ seconds, so whichever file is unlucky fails a run no code change could have broken. The budgets therefore widen on CI (vitest.config.ts; GitHub Actions sets CI=true): testTimeout 15 s → 60 s, and since #458 hookTimeout likewise — before that it sat on vitest's 10 s default, six times tighter than the tests, and two of the five windows flakes investigated in #458 were hook timeouts rather than test timeouts. Neither widening loosens any evidence: timing PROOFS live in explicit assertions (the FTS 500 ms bound, #84), never in a vitest budget, and a hook is setup, not proof. Locally both stay at 15 s so a real hang still fails fast at the desk. A hand-rolled wall-clock bound does NOT widen with them — a Date.now() - start > N poll guard, a fixture's own waitFor default, or a child-process timeout is invisible to vitest's config, so each one needs its own CI headroom (the header of tests/helpers/hang-budget.ts records the case that taught it). The two library defaults are the same trap (#915): vitest's vi.waitFor and testing-library's waitFor / find* both give up after 1 s and follow neither testTimeout nor CI. testing-library's is raised once for every jsdom file in tests/setup.ts (configure({ asyncUtilTimeout: hangBudgetMs(5_000) }), asserted by hang-budget.dom.test.ts); vitest has no such config key, so every vi.waitFor passes { timeout: hangBudgetMs(n) } (5000 is the usual n), a testing-library wait passes one only to go above its default (n of 5000 or more), and a literal timeout: on any wait is refused. A repo-hygiene row enforces all of it. A heavy row (real hashing, process spawns, hundreds of fs calls) takes testBudgetMs as its per-test timeout instead. Prefer asserting what a deadline GUARANTEES (a bound, an exclusion) over how far concurrent work got inside it; the latter is a property of the runner, not of the code (#457, #389).

Hand-rolled wall-clock bounds are CI-aware via one helper (#458 step 3). The paragraph above warned that a Date.now() - start > N guard does not widen with testTimeout; the suite's 29 such bounds across 16 files, plus the two fixture waitFor defaults, now all go through tests/helpers/hang-budget.ts: hangBudgetMs(5_000) stays 5 s at a desk and becomes 20 s on CI. The multiplier is 4× — exactly the ratio testTimeout already uses (15 s → 60 s) — capped at 45 s so a widened detector still fires inside the 60 s CI test budget and you keep its named error instead of a bare Test timed out. Every one of those bounds is a hang detector, not a measurement: exceeding it means "it never finished", never "it was slow".

What must NOT go through it: a bound that is itself the evidence. fts-rowid-sync's 500 ms (#84) is a timing PROOF, so widening it would stop it discriminating; it is marked as a deliberate exception in place. A test whose subject is a product timer does not race it on the wall clock at all: it drives the shipped constant with fake timers (CONTRIBUTING "Pin the bound that ships").

A literal per-test timeout does not widen either — testBudgetMs (#458 residual). The third shape of the same trap: it('…', fn, 60_000) replaces the config's testTimeout, so it is as blind to CI=true as a hand-rolled bound. Every such literal in the suite was written to give a heavy test more room than the default, and each silently became the opposite when the CI default rose to 60 s: docs-ipc BE-1's 60_000 (4× the desk default, on purpose) was exactly the CI default — no extra room on the one platform it was added for — and the renderer suites' 8000/10000 (wider than vitest's old 5 s) are 6–7× tighter than what an unannotated test gets on CI. BE-1 paid for it in run 35099769260: 64 s in setup on a runner that froze twice (24 s + 18 s with no output from any process), timed out before its OCR was queued; the timed-out body then ran on into the next test's handlers, which is why that log shows a misleading Unknown document rejection. The 50 literals ≤ 60 s across 10 files now read testBudgetMs(n): unchanged at a desk, on CI 4× and never under the CI default. When adding a per-test timeout, use it.

The windows CI legs run one fork fewer (#458 residual). Everything above buys tolerance for a starved fork. The failure that survived it is the main process going unanswered: a fork's onTaskUpdate RPC timed out at birpc's hardcoded 60 s (vitest 3.2.6 had no knob for it) and the run exited 1 with every test green — 3 of the 4 first-push reds in the week after steps 1–3 landed (27 of 31 first attempts green, against ~74 % before the wave; runs 34723764047, 35038224383, 35335961954 — always a 1 of 2 shard, on both Node versions). Those logs show four whole-runner output gaps of 16–45 s where a healthy shard shows at most one: a noisy host. The suite cannot fix the host, but it can stop filling every core, so vitest.config.ts sets maxWorkers: 2 when CI is set on win32 (poolOptions.forks.maxForks until vitest 4 removed poolOptions, wave DEP-6) — ubuntu and the desk keep the default. What to look for on a run: the Test step of a windows leg prints [vitest.config] windows CI leg: forks capped at 2 (#458); if that line is missing the cap did not apply (step 2's first sharded run silently did nothing, so no lever on these legs is trusted without its log line). Since vitest 4 the worker-side RPC has no timeout at all, so Timeout calling "onTaskUpdate" can no longer end a run; a starved main process now shows up as a slow leg, and ci.yml caps each leg at 30 minutes so a hang still fails.

Vitest 4's own all-green red: EnvironmentTeardownError: [vitest-worker]: Closing rpc while "onUserConsoleLog" was pending (vitest-dev/vitest#11153). Vitest 3 sent console output from a worker as a fire-and-forget event; vitest 4 sends it as a call it never awaits, and when the worker closes it rejects any such call still pending. So a test whose async work outlives it and then logs (here: through log.*, which writes to the console) can fail a run in which every test passed, on whichever leg is slow enough. The file the error names is the one that was closing. The first case (a Dependabot PR's windows leg, 2026-10-02) was vision-security.test.ts: four tests let an image's history write run on after they ended, into the database the file had already closed. They now wait for the streamed done event. What to do on a run: re-run the failed job once. If it comes back, find the writer: a temporary setup file that wraps console.* and records any write made after the file's last afterAll (setup-file hooks run last), run over the full suite through a mergeConfig copy of vitest.config.ts, names it with a stack. --detectAsyncLeaks is too blunt for this, reporting about 360 leaks, nearly all promises that never log.

When a test that is NOT about timing depends on a budget inside the PRODUCT, keep the timer from racing it instead of loosening the assertion. A test whose subject IS the timer drives the shipped constant with fake timers instead (CONTRIBUTING "Pin the bound that ships"). The sixth flake of this wave was zim-arm's collectPackCandidates L3-b case (run 34659678616): the arm's title lookup and document-frequency probes ran against a real 3 s DF_PROBE_TIMEOUT_MS, and on a starved runner that timer won — the list article was never read, so rawReads came back holding only the plain reads. The assertion was about which articles get read, not latency, so the fix was a probeTimeoutMs test seam (mirroring the existing articleTimeoutMs) that the expansion cases pass, while the #353 cases that prove the short budget fires keep the real default. Verified by setting the seam to 1 ms: exactly those six expansion cases fail, which is what makes the seam's wiring provable rather than assumed. SUPERSEDED 2026-09-14 by the §17 discovery port (Phase 4 PR-A): the #353 document-frequency ladder this paragraph's expansion cases exercised (DF_PROBE_MAX_TERMS, DF_PROBE_TIMEOUT_MS, narrowByFrequency) was removed with the L3-b {concepts,listTitle} expander it belonged to; probeTimeoutMs then gated the discovery port's own title-index /suggest lookups (PROBE_TIMEOUT_MS = 3_000) until the October 2026 ZIM test campaign removed it: a 50 ms seam proved the seam, not the shipped bound. zim-arm.test.ts "a /suggest title lookup still open just short of PROBE_TIMEOUT_MS is kept; held past it, it is cut off and discovery completes without that title's hit" now drives the shipped 3 s bound with fake timers.

There are TWO shapes of hand-rolled bound, and the counted one is nastier. The first sweep caught only Date.now() - start > N. CI then failed vision-security.test.ts (run 34664328086) on the other shape — a loop bounded by ITERATION COUNT: for (let i = 0; i < 200; i++) { if (cond) break; await sleep(5) }. That is a 1 s detector hard-coded in disguise, and worse than the wall-clock form in two ways: it does not widen on CI and it falls through silently, leaving the next assertion to fail with something opaque — here expected [] to have a length of 1, which says nothing about the event that never arrived. A count of loop turns is not a time bound either, and its length depends on the platform (#895). A 0 or 1 ms setTimeout step lasts about 1.1 ms on Linux but about 15.6 ms on Windows (its timer resolution), and a 5 ms step 5 ms vs 15.6 ms, so for (i < 200) await setTimeout(r, 0) is a ~0.23 s detector on the ubuntu runner and a ~3 s one at a Windows desk: ~14× narrower exactly where CI runs. The flake was a skill-run poll waiting on real file and database work (model-occupancy-ipc). #895 moved every counted poll onto until (a sync condition) or untilValue (a sync or async probe whose answer the caller wants back; each probe call is raced against the time left, so a probe that never settles still fails by name), both of which read the real clock, and retired the counted-loop helper. When adding a poll loop, bound it in wall-clock terms through one of these helpers and make its exhaustion an error, never a break into the next assertion.

Widening does not help a race the desk loses too: start the clock at the event (#549). Both helpers widen only on CI, and wave DEP-6's two flakes lost at a desk under full-suite load. ocr.test.ts's worker-load case raced a 2 s clock that started before the Worker spawned, so thread start-up counted against it; the clock now starts at the dead worker's 'exit', which comes after the engine has already rejected on its 'error'. A worker that takes 3 s to fail reproduces the old failure and passes the new shape. zim-client's T19 stall block ran a 300 ms per-attempt total under the default 1 s idle timer, the reverse of production's 1 s idle inside 4 s, so a stalled machine timed attempts out before their headers arrived, and healthy answers were exposed the same way. It now runs production's shape (a 300 ms idle timer, armed by the headers, inside a 3 s total); a 500 ms freeze in the fixture server failed six of the block's tests before and none after. Choose where the clock starts and which timer trips so that only the behaviour under test can trip it; size it after that. A fake that waits for an AbortSignal must check signal.aborted before it subscribes: when the code under test arms its deadline and then awaits something, the abort can land first, and 'abort' is not dispatched twice. dictation-ipc's "wedged child" fake hung that way for a whole 120 s budget, and its earlier timeouts had been put down to starved runners.

What CI does NOT cover — the manual HILBERTRAUM_* matrix stays a separate human gate. A green CI run says nothing about the real-spawn / real-binary / real-weights surface: that is the HILBERTRAUM_* manual harness matrix below (audit M-A5), which is env-gated and skips in CI. CI is the automated floor; the manual pre-ship checklist and harness matrix remain a required, human-run pre-release gate. The two do not substitute for each other.

The release workflow — release.yml (tag-triggered prebuilt packages)

One workflow, .github/workflows/release.yml, builds and draft-publishes the prebuilt packages (it supersedes the earlier mac-build/win-build pair; ad-hoc builds = its workflow_dispatch trigger, which runs the build legs but skips the tag-gated release job). Trigger: a push of a v* tag (or manual dispatch). Five jobs:

  • test-win — windows-latest, two shards like CI's windows legs (#458): npm ci → typecheck → build → the full test suite, on the first-class OS: belt-and-braces on the exact tagged commit.
  • build-win — windows-latest, after test-win: npm ci → typecheck → build → npm run package:win → HilbertRaum-<version>-portable.exe, then checks the packaged app (#769, blocking): packaging.test.ts, third-party-notices.test.ts and asar-unpack-closure.test.ts run against release/win-unpacked (HILBERTRAUM_PACKED_ASAR / HILBERTRAUM_PACKED_EXE): the layout model's package directories and the notices' name@version list against the real app.asar, the shipped THIRD-PARTY-NOTICES.md and LICENSE.txt against the committed files, the OCR worker closure inside app.asar.unpacked, and the exe's fuse wire. HILBERTRAUM_PACKED_REQUIRED=1 fails the step when either path is missing, so those rows cannot skip; packaging.test.ts also reads the step itself on every PR (a workflow change first runs at a tag). Also fetches the win Vulkan runtime via scripts/fetch-runtime.sh (git-bash; the SAME pinned, SHA-256-verified upstream build the in-app engine installer fetches — runtime-sources.yaml first win/x64 match) and zips the extracted install tree (Compress-Archive; root entry win/ incl. the .hilbertraum-runtime.json marker) as llama-runtime-win-x64.zip — the mac Metal zip's twin (issue #102 item 1): parity for the win release + an offline/air-gapped engine install path without the repo scripts (unzip into runtime/llama.cpp/). No symlink-dereference concern on win (the Vulkan build carries none).
  • build-mac — macos-15 (Apple Silicon): npm ci → typecheck → npm run package (dir target) → ad-hoc sign (codesign --force --deep --sign -, required to launch on Apple Silicon) → ditto-zip (HilbertRaum-<version>-mac-arm64.app.zip — it must STAY zipped on exFAT, which can't hold the .app's framework symlinks; the drive launcher extracts to a local cache). Also fetches the mac Metal runtime via scripts/fetch-runtime.sh and zips it with symlinks dereferenced (llama-runtime-mac-arm64.zip) so it drops straight onto exFAT under runtime/llama.cpp/mac/.
  • build-linux — ubuntu-latest: npm ci → typecheck → npm run package → HilbertRaum-<version>.AppImage (community-tested until the GPU-matrix Linux leg runs).
  • release (tag-gated, needs all three) — asserts tag == apps/desktop/package.json version (fail fast on mismatch), aggregates SHA256SUMS.txt, builds the release notes from the CHANGELOG section for the version being tagged — ## [<version>], with [Unreleased] as the fallback if the bump PR has not renamed it yet, so a release page shows THAT release instead of an ever-growing block (prefixed with the "this download is the app only — models are fetched separately" line, which now also points offline installers at the llama-runtime-*.zip assets), and creates a DRAFT GitHub release (prerelease: true while 0.x) with everything attached (both runtime zips included). The notes are fully automated below the curated block, in two appended layers computed against the latest published release (drafts don't count, so an abandoned draft folds into the next tag's notes): an "Issues resolved" section from scripts/release-issues-section.sh — compare PREV...TAG → each commit's associated PRs (robust against squash AND true merge commits) → each PR's closingIssuesReferences (the links GitHub tracks from "Fixes #N" keywords in PR bodies, so those keywords are what feeds the list); then GitHub's generated notes (generate_release_notes: true — "What's Changed" PR list with authors, "New Contributors", Full Changelog link). The issues step is best-effort: on API failure it warns and the draft is created without the section — notes never block a release build. The script is locally testable: scripts/release-issues-section.sh HilbertraumAI/HilbertRaum master.

The ritual is draft → owner smoke → publish. The workflow never publishes: the owner downloads the draft's artifacts, runs the applicable "Manual pre-ship checklist" below (at minimum item 1 — the post-package smoke — plus model start/stop with no orphaned llama-server), then clicks Publish. (A packaged OCR run was part of this minimum until 2026-07-19, when it was measured to crash the app — see the asarUnpack bullet above; it is not a gate again until that fix bundle lands.) A failed smoke → delete the draft, fix, re-tag. A bad build never becomes publicly linkable.

Signing posture — staged, all via env secrets (no repo change when certs arrive):

Stage Secrets (GitHub Actions → the env electron-builder.yml reads) Result
0 — now none unsigned .exe (SmartScreen "More info → Run anyway"), ad-hoc-signed .app (macOS 15+: System Settings → Privacy & Security → "Open Anyway"), SHA256SUMS.txt as the integrity floor — flows documented in troubleshooting.md
1 — Apple CSC_LINK / CSC_KEY_PASSWORD + APPLE_ID / APPLE_APP_SPECIFIC_PASSWORD / APPLE_TEAM_ID Developer ID-signed + notarized .app (electron-builder auto-notarizes; hardenedRuntime + entitlements already wired). Also remove the CSC_IDENTITY_AUTO_DISCOVERY: 'false' line from release.yml
2 — Windows WIN_CSC_LINK / WIN_CSC_KEY_PASSWORD (OV/EV .pfx or Microsoft's Artifact Signing, formerly Trusted Signing, via signtool env) signed .exe; SmartScreen reputation builds

Non-clash with ci.yml: release.yml never fires on pull_request/push: master — only tags and manual dispatch. It runs on Node 24 (electron-builder ships its own pinned Electron runtime), which ci.yml's matrix now also covers, does not set the skip knobs (packaging needs the binary), and installs with npm ci (lockfile-pinned — the CI half of hardening L-8). Since Electron 42 the mechanism there differs from what this used to describe: npm ci downloads nothing, and the binary reaches a release leg either lazily on the first electron-bin invocation or — for the artifact itself — via electron-builder's own @electron/get fetch, which is independent of the npm package. The outcome is unchanged. It does not pin the exact npm: Node 24 already bundles npm 11.x, so the engines.npm >= 11 floor holds there on the bundled npm; only CI installs the exact [email protected]. Pinning here too would make the two installs byte-identical, at the cost of exercising a new step for the first time on a tag (a release leg has no PR gate ahead of it) — a deliberate, registered residual.

Manual pre-ship checklist (real hardware — not covered by CI)

The green gate (typecheck/test/build) runs on mocks with zero weight files, so real-runtime / real-drive behaviour never shows up in CI. Before any drive ships (commercial or a DIY hand-off), run one real-model session covering the items below.

These sessions create a workspace, documents and logs. Run them on a scratch drive, not the Kit that ships. If they ran on the Kit, wipe it afterwards (delete everything inside workspace/ and logs/ but keep the two folders, and delete config/workspace.json, config/working-copy-lost.json and any .<suffix> copy of either), then run build-commercial-drive with -VerifyOnly (--verify-only) again: the sell gate names every file the wipe missed (#893). On a Mac, Finder writes a .DS_Store into each folder you open on the stick, and macOS writes ._<name> companion files beside files it copies or tags there (exFAT keeps no extended attributes); the gate counts both. Delete them too before that final check, or do not browse workspace/ and logs/ in Finder.

  1. Post-package smoke on the produced .exe: import a PDF, a DOCX, and a CSV; create + unlock an encrypted workspace (exercises the externalized parser libs and @noble/hashes argon2id, which only fail at runtime if packaging missed them).
  2. Switch models mid-load and quit mid-load — confirm no orphaned llama-server process survives (Task Manager / ps).
  3. Import a 50+-page DOCX, and lock the workspace during an import — confirm the import stops cleanly and the stuck rows are re-indexable after unlock.
  4. A > 2 GiB workspace: lock/unlock round-trip (exercises the streaming file crypto + chunked shred).
  5. Models / Chat screen latency with real multi-GB GGUFs on the drive (exercises the checksum cache — screens must not re-hash weights per navigation).
  6. The spec §17 USB demo on a fresh laptop with Wi-Fi off, plus the second-laptop continuity check (same encrypted workspace under a different drive letter/mount).
  7. The GPU hardware matrix (canonical list in BUILD_STATE §5): discrete NVIDIA/AMD happy paths, Iris-Xe-only laptop (no profile bump), no-GPU/RDP silent CPU, pre-Vulkan-1.2 degradation, the mid-generation driver-crash auto-fallback, and the machine-move re-probe (1↔4). Measured tok/s feed the release notes.
  8. (If a vision model ships) open Images, analyze a PNG and a JPEG from the produced .exe (the vision-smoke harness covers the runtime mechanics; this is the packaged-app pass) and confirm the calm unavailable state on a drive with no vision model.
  9. One exFAT crash-cut before the first kit ships (#243; owner decision #223, 2026-09-03; repeating it per shipping platform is recommended, not ruled): on a scratch exFAT kit — never the kit that ships or a drive holding the only copy of a workspace, since a hard unplug can leave FOUND.000/repaired files behind — unlock an encrypted workspace large enough that the lock takes several seconds (item 4's > 2 GiB workspace pairs well), start Lock now and hard-unplug the drive during the lock (no safe eject). Quit or kill the still-running app instance BEFORE re-plugging and relaunching (it is holding a vanished volume). Re-plug, let the OS scan if it asks, relaunch and unlock. Pass = the workspace opens cleanly in either of two states: at the last successfully locked snapshot (a cut in the rename window, the documented exFAT case), or with the cut session rolled forward through .recovery (a cut in the encrypt phase — the failed-lock signature, security-model.md "Lock failure & durability"); a vault_recovery_blocked refusal is a retry-on-next-unlock, not a failure. Fail = a workspace that refuses every unlock or opens torn. The unplug lands at an arbitrary point of the lock, so record the outcome as evidence, not a proof. Record machine, OS, date and outcome in the release notes (drive-layout.md Filesystem for the caveat).
  10. Scheme and fuse verification on each shipping platform (#560, #562): run scripts/verify-mac-build.sh on a Mac, and on Windows and Linux start the packaged build with --remote-debugging-port on a scratch drive root and run scripts/lib/packaged-app-probe.mjs against it (next section).
  11. The app.asar layout model against a real archive (#548). release.yml's build-win runs it on every Windows build it packages (#769, "The release workflow" above): check that step passed. By hand, after an electron-builder bump or a local npm run package:win, from apps/desktop: set HILBERTRAUM_PACKED_ASAR=release/win-unpacked/resources/app.asar and HILBERTRAUM_PACKED_EXE=release/win-unpacked/HilbertRaum.exe, then npm test -- tests/integration/packaging.test.ts tests/integration/third-party-notices.test.ts tests/integration/asar-unpack-closure.test.ts.
  12. The menu and DevTools of the packaged build (#912). On Windows and Linux the window has no menu bar, and Alt does not bring one up. Ctrl+R, Ctrl+Shift+R and Ctrl+Shift+I do nothing (no reload, no developer tools). Ctrl+= and Ctrl+Shift+= zoom in (on a German keyboard, Ctrl and the + key), Ctrl+- zooms out, Ctrl+0 resets, F11 toggles full screen, Ctrl+M minimizes, and Ctrl+W closes through the save before closing. On Linux, Ctrl+Q quits. On a Mac: ⌘C and ⌘V work in a text field, ⌘Q quits through the save before closing, and ⌘R does nothing. The off-screen real-Electron row (tests/integration/app-menu-electron-smoke.test.ts) presses the Windows keys against the production menu with webContents.sendInputEvent, but only a packaged build and a physical keyboard prove the shipped binary.
  13. A download behind TLS inspection, and the fuse wire (#564). Decode the packaged binary's fuse wire ("Electron fuses" above; 000011001 for 43.8.10). Then, on a computer whose antivirus or proxy re-signs HTTPS (Norton's web protection does), start the packaged build with NODE_EXTRA_CA_CERTS removed from its environment and begin one in-app download from github.com or huggingface.co: the AI engine or a model, not an OCR file (jsDelivr is not re-signed by Norton, so it proves nothing). It must get past the first megabytes; cancel it then. The app's log then holds the line "Download trust: the system certificate store is trusted too". Before

#564 such a download failed with "fetch failed".

Platform verification of the app scheme and the fuses (#560, #562)

What has been run, per platform, on the build that carries both changes. That build is the release.yml workflow_dispatch run on fix/562-electron-fuses (run 37135092030, 2026-10-03: real artifacts, nothing published) plus the local electron-builder --win dir build of the same branch.

check Windows 11 (packaged exe) Linux (the real AppImage, ubuntu:24.04 container, non-root, APPIMAGE_EXTRACT_AND_RUN=1) macOS arm64 (the real .app.zip)
fuse wire, decoded with @electron/fuses 001011001 001011001 (the inner binary) 001011001 (Electron Framework)
ELECTRON_RUN_AS_NODE / --inspect / NODE_OPTIONS=--require ignored / no debugger / not loaded ignored / no debugger / not loaded not run
asar integrity: a changed byte in app.asar the app ends ("ASAR Integrity Violation") not detected (Electron has no Linux check) Info.plist ElectronAsarIntegrity = the recomputed header hash; not run
only app.asar loads (planted resources/app/, app.asar removed) the planted code does not run the planted code does not run not run
signature unsigned (stage 0) n/a ad-hoc: codesign --verify "valid on disk, satisfies its Designated Requirement" on the runner, after release.yml's own codesign --force --deep --sign -; resetAdHocDarwinSignature alone not tested
page on hilbertraum://app; local fetch/XHR and a planted script refused; 13 traversal vectors 404 pass pass not run
KaTeX fonts, fake-mic getUserMedia, Copy through the bridge pass KaTeX, mic pass (clipboard not run) not run
PDF text, OCR of a JPEG and a CCITT G4 scan through the OCR page on the scheme pass PDF text and CCITT OCR pass not run
encrypted workspace: create, lock, unlock pass pass not run
evidence-pack PDF export pass (dialog stubbed) pass, through the real GTK save dialog (xdotool), PDF text checked not run
AppRun --no-sandbox when user namespaces are unavailable n/a unchanged (main process carries it; .desktop Exec=AppRun --no-sandbox %U) n/a

The Windows column is the #562 record's measurement plus packaged-app-probe.mjs (13 pass, the export skipped). The Linux column ran a scratch harness with the same checks.

Found on the way, filed as #567: at start the Linux AppImage requests Chromium's Hunspell dictionary (https://redirector.gvt1.com/edgedl/chrome/dict/en-us-10-1.bdic; in the container at every start, because the download kept failing), and the Windows build probes http://wpad/wpad.dat. Windows downloads a dictionary too, for a language it cannot spell-check itself (measured later with Polish). Both requests come from Chromium's own network stack and were measured with --log-net-log. The v0.1.62 AppImage does the same. Fixed in #567 (spell checker off in every session, no-proxy-server); see security-model.md "Chromium background fetches".

Open (moved here from the retired BUILD_STATE 2026-10-03 #560/#562 entry): the owner's run of verify-mac-build.sh on a Mac. Until then the macOS column above is inspection only, and the signed build's audio-input entitlement (below) is unverified.

Verifying a packaged build on macOS (owner-run, #560, #562)

There is no Mac in the project's test setup, so this is the protocol for one. From a checkout with npm ci done, on macOS with Node ≥ 22.12:

# build `--mac dir` from the checkout and verify it (no Developer ID: tests resetAdHocDarwinSignature)
scripts/verify-mac-build.sh
# or verify an existing build / the release download
scripts/verify-mac-build.sh ~/Downloads/HilbertRaum-<version>-mac-arm64.app.zip
# with OCR (a drive's ocr/ folder) and a real black-and-white office scan
HILBERTRAUM_OCR_DIR=/Volumes/HILBERTRAUM/ocr PROBE_ARGS='--scan ~/scan.pdf --scan-words "INVOICE"' scripts/verify-mac-build.sh

It works in scratch folders under $TMPDIR, never on a real drive. It prints PASS / FAIL / NOTE lines for:

  1. The fuse wire, expected 000011001 (001011001 before #564).
  2. The signature: codesign -dv (ad hoc, and whether the hardened-runtime flag is set) and codesign --verify --deep --strict.
  3. The entitlements: whether com.apple.security.device.audio-input is present.
  4. Asar integrity: Info.plist's ElectronAsarIntegrity against the recomputed hash of app.asar's header.
  5. The fuses at work: ELECTRON_RUN_AS_NODE ignored, --inspect without a debugger, a changed byte in a copy's app.asar ending the app, and a planted resources/app/ that does not run.
  6. The running app over CDP (packaged-app-probe.mjs):
    • the page on hilbertraum://app;
    • local reads and a planted script refused, the traversal vectors;
    • KaTeX fonts;
    • the microphone: a real macOS prompt, allow it;
    • Copy through the bridge read back with pbpaste;
    • PDF text, OCR of a drawn JPEG scan (and --scan);
    • an evidence-pack PDF: a save dialog opens, save it exactly where the script says;
    • lock and unlock, no [ERROR] lines.
  7. No request off the machine during that session: the app runs with --log-net-log, and scripts/check-netlog.mjs fails on any request or host-name lookup that leaves it (#567). Expected on macOS: none (no spell-check dictionary; WPAD only with "Auto Proxy Discovery" on, which no-proxy-server should silence; not measured).

Report the output, plus two things only eyes see: which app the microphone prompt names (the drive launcher starts the binary from Terminal, as this script does), and whether Gatekeeper interfered with the first launch.

Expected to need attention on a signed build: the stage-1 build (Developer ID, notarized) is signed with the hardened runtime (hardenedRuntime: true). Under the hardened runtime, Apple requires the com.apple.security.device.audio-input entitlement for microphone access, and build/entitlements.mac.plist does not grant it. Dictation is therefore expected to be refused on that build until it is added. Unverified (no Mac). The stage-0 build is re-signed ad hoc without the hardened-runtime option, so it is not affected.

The canonical USB demo (original spec §17)

The acceptance walkthrough that checklist item 6 (and the R5/R7 gate) refers to — transferred verbatim-in-substance from the retired original spec, §17. The active-model name in step 4 tracks whatever the drive bundles as its default chat model (Ministral 3 8B today; the spec's example was Qwen3 4B), and assumes drive preparation selected that model once (a factory-fresh tree has no active model until "Use this model" is clicked on the AI Model screen):

  1. Laptop has Wi-Fi turned off.
  2. User plugs in HilbertRaum.
  3. User launches the app.
  4. Home screen shows: Offline Mode: ON, the active default chat model, Workspace: Encrypted.
  5. User opens Documents.
  6. User imports sample-contract.pdf.
  7. App indexes the file locally.
  8. User asks: "What are the termination rights in this contract?"
  9. App responds with a concise answer, citations to pages/sections, and source snippets.
  10. User asks: "Draft a polite email summarizing the risk."
  11. App drafts the email locally.
  12. User closes the app.
  13. The runtime stops.
  14. No network activity occurred.

The HILBERTRAUM_* manual harness matrix — a REQUIRED pre-release gate (audit M-A5)

The riskiest integration surface — real spawn, the llama-server SSE stream, GPU --list-devices parsing, whisper-cli, WASM OCR, real weights, real retrieval quality — is deliberately not in CI (the zero-binary / zero-network green-gate posture, audit M-A5). It is covered instead by the tests/manual/*.test.ts harnesses, each gated behind a HILBERTRAUM_* env var that points at a provisioned drive / binary / model. They are skipped unless that env var is set, so a green CI run says nothing about them.

Before any drive ships, run the applicable subset against the real artifacts (a locally provisioned smoke drive with a llama.cpp binary + a small chat GGUF; see BUILD_STATE). Treat this as part of the gate, not optional polish. NOTE (#729): the runtime pin moved to b12110 (= upstream v0.9.0), so re-run fetch-runtime on the smoke drive (both the default build and --backend cpu; refresh the drive's model-manifests first, or fetch-runtime follows the drive's old yaml) before these harnesses prove the current pin (the previous binary was b11146, before it b9849).

Harness Env var(s) Proves
bringup-smoke HILBERTRAUM_BRINGUP_SMOKE the runtime starts + streams against the real binary
gpu-smoke HILBERTRAUM_GPU_SMOKE rung-1 GPU start and the placement record its real load log yields, the #380 label when the probe gives no answer (the load log names the card), forced-CPU rung, rung-3 safety net (#656: the smoke used to drop the parser's stderr feed; b11146 on a GTX 1070 Ti, 2026-10-13: 37/37 layers, 5/5 legs); the app's start applies neither a host llama.cpp config file nor a LLAMA_ARG_* variable, with a control that shows both reach an unfiltered start (#730)
thinking-smoke / gemma-thinking HILBERTRAUM_THINKING_SMOKE / HILBERTRAUM_GEMMA_THINKING deep-mode reasoning channel
prompt-cache-smoke HILBERTRAUM_PROMPT_CACHE_SMOKE whether the pinned server RESTORES a chat GGUF's evicted conversation from its host-RAM prompt cache (the #399 evict-and-return protocol with the app's chat argv; the evicting conversation shares the system message, as every app chat does); prints prompt_n on return, RESTORED / RE-PREFILLED, restore == cache_prompt: false recompute, and the manifest advice for disable_prompt_cache (#512). Run it for every new chat manifest
rerank-smoke HILBERTRAUM_RERANK_SMOKE the reranker sidecar reorders retrieval
whisper-smoke / dictation-smoke HILBERTRAUM_WHISPER_SMOKE / HILBERTRAUM_DICTATION_SMOKE whisper-cli transcription + dictation; with HILBERTRAUM_WHISPER_869=1 also the #869 Windows layout matrix (non-ASCII roots and originals; see the file header)
ocr-smoke HILBERTRAUM_OCR_SMOKE WASM OCR over a real scan
vision-smoke HILBERTRAUM_VISION_SMOKE the vision sidecar (--mmproj) cold-starts, analyzes a fixture image, streams, reuses the prefill, idle-tears-down + cold-restarts
compare-smoke HILBERTRAUM_COMPARE_SMOKE the shipping compare prompts (mode-(a) full compare EN + DE, a mode-(b) pair map, a reduce over planted notes) on a real chat GGUF through a bare LlamaRuntime, printing the R-T2 format/placement/language findings — not the DocTaskManager pipeline (the earlier chat-model translation-smoke went away with the chat-model translation pipeline; translategemma-smoke below covers translation)
translategemma-smoke HILBERTRAUM_TRANSLATEGEMMA_SMOKE the TranslateGemma sidecar (NO --jinja, raw /completion) LOADS on the pin (Vulkan and CPU safety-net), DE↔EN translates, keeps invoice numbers/model codes verbatim (numbers/dates localize), resists embedded-instruction injection, leaks no <end_of_turn>; prints tokens/sec + peak RSS. The TG-2 go/no-go gate — since TG-3 the doc-task's production translation backend. Extended at TG-6: per-language round-trip + verbatim-token check for the curated 10, /tokenize tokens-per-word (the planner-constant calibration), and a co-residency-RSS leg (translation + E5 + a resident chat, needs models/{embeddings,chat}/*.gguf). CPU-safety-net leg needs runtime/llama.cpp/<os>/cpu/
rag-quality / minsim-measure HILBERTRAUM_RAG_QUALITY / HILBERTRAUM_MINSIM_MEASURE retrieval quality + the similarity floor
resident-cache-real HILBERTRAUM_RESIDENT_REAL (the drive root) real E5 vectors stored through the production codec on the drive: the resident cache's cold build, its warm scan, and a full searchText query (a real E5 query embed + the scan)
resident-cache-bench RUN_RESIDENT_BENCH=1 the resident vector cache's warm scan against the uncached scan, on synthetic unit vectors (mock only, no sidecar)
script-execution -DryRun pipeline HILBERTRAUM_SCRIPT_DRY_RUN the whole builder, dry, on both shells, reaching the canonical verdict on an empty target (needs npm run build; ~30 s per leg)
server-concurrency-probe HILBERTRAUM_CONCURRENCY_PROBE the one-at-a-time sidecar invariant
model-eval HILBERTRAUM_MODEL_EVAL the model-recommendation ladder on real hardware
zim-real HILBERTRAUM_ZIM_SMOKE real kiwix-manage registration, the real kiwix-serve sidecar, Xapian search, the offline article viewer read — fully offline; plus the non-ASCII launch layouts (#787: a pack registered and served under a non-ASCII root and from another folder of that account, and on Windows a non-ASCII file name and a non-ASCII folder outside the app's own refused as nonAsciiArgv). FAIL-CLOSED (#301 P5, finding L8): requested with a missing/invalid tools dir, either binary absent, a non-ZIM file or an unset query FAILS the run instead of silently skipping it

Installing the pinned kiwix-tools bundle. The user path is the in-app consent dialog (#339 P8-2): the Knowledge-packs panel's tools-missing notice, or the mirror row on the AI Model screen, states the size, the GPL-3.0-or-later license and the source, and installs the family once you accept. The builder/DIY path is fetch-runtime --family kiwix_tools (#339 P8-3), which downloads, SHA-256-verifies and extracts the pinned kiwix-tools 3.8.1 archive for the host (or --os/--arch to provision another OS's dir), writes a .hilbertraum-runtime.json install marker hashing every required file (kiwix-serve, kiwix-manage, kiwix-search, and on Windows the five ICU DLLs), and chmod +xs the executables on mac/linux — exactly like the llama_cpp/whisper_cpp families, except it is never fetched by prepare-drive --with-assets (the family is optional). A manual unzip of the pinned zip (see model-policy.md "Sidecar binaries — kiwix-tools" for the exact bundle/hashes) under runtime/kiwix-tools/<os>/ is the last-resort fallback: it still works, but leaves no install marker and so resolves through the hashless skip-legacy verifier path (residual R-1) instead of integrity verification — prefer the in-app install or the script. kiwix-serve and kiwix-manage verify normally against a marker from either the script or an in-app install.

Optional harness inputs (point a harness at a specific artifact). Distinct from the on-switch env vars in the table above, several harnesses additionally read an artifact-pointer input, documented before only as inline test-file comments. All are optional — each has a default or is only needed by its harness:

Input var Read by Points at
HILBERTRAUM_SMOKE_MODEL bringup-smoke / gpu-smoke / thinking-smoke / prompt-cache-smoke one chat-model .gguf filename (else the smallest chat model)
HILBERTRAUM_PROMPT_CACHE_SMOKE_DISABLE prompt-cache-smoke 1 spawns the model as disable_prompt_cache: true (--cache-ram 0) — the control run, which must come back RE-PREFILLED
HILBERTRAUM_PROMPT_CACHE_SMOKE_MTP prompt-cache-smoke 1 adds rung 1a's MTP flags (--spec-type draft-mtp --spec-draft-n-max 2), for a manifest with speculative_decoding: mtp that the app starts that way on a GPU
HILBERTRAUM_GEMMA_MODEL gemma-thinking the Gemma model filename (default gemma4-12b-it-qat-q4.gguf)
HILBERTRAUM_OCR_IMAGE ocr-smoke a real German scan image (png/jpg) — never committed
HILBERTRAUM_REAL_MODEL_PATH real-model/wave3 the chat GGUF path (the assertions were tuned on qwen3.5-4b-ud-q4kxl.gguf); sibling HILBERTRAUM_LLAMA_BIN points at the binary. No defaults: the on-switch is HILBERTRAUM_REAL_MODEL=1, and once it is set both paths are required (a missing one fails the run)
HILBERTRAUM_RESIDENT_REAL_N resident-cache-real real chunk count to embed (default 2000)
RESIDENT_BENCH_DIR resident-cache-bench a directory for the bench database, e.g. the drive, so the cold build reads real USB I/O (default: the OS temp dir)
RESIDENT_BENCH_N resident-cache-bench comma-separated corpus sizes (default 100000)
HILBERTRAUM_EVAL_DIR model-eval override the eval/ data dir
HILBERTRAUM_ZIM_TOOLS_DIR zim-real a directory holding the WHOLE unzipped kiwix-tools bundle (both kiwix-serve/kiwix-manage binaries plus their ICU DLLs) — required once zim-real is requested
HILBERTRAUM_ZIM_FILE zim-real an existing .zim archive whose 80-byte header readZimHeader accepts — required once requested; it must carry a full-text index (the smoke asserts search hits — an index-less archive fails the run by design; index-less behaviour is covered by zim-packs' T14 leg and was accepted on real tools at P7)
HILBERTRAUM_ZIM_QUERY zim-real a non-empty search term the archive's index will hit — required once requested; deliberately has NO default (the old hardcoded 'Treibhausgas' fallback let an unset query pass silently)
HILBERTRAUM_ZIM_EXPECT_ARTICLE zim-real optional — a known entry key; when set, the harness also asserts the viewer reads it with a non-empty title
HILBERTRAUM_ZIM_FIXTURES_DIR zim-html.test.ts (unit, env-gated: skipped unless set) optional realism leg — a dir holding the real mwoffliner articles kontaktverfahren.html, treibhausgas.html and georgia.html, re-extracted from a German Wikipedia pack over a loopback kiwix-serve (/raw/<book>/content/<Title>); set but missing a file FAILS the run. The committed fixture pins the contract regardless
HILBERTRAUM_KIWIX_BIN zim-real / dev runs dev-only resolver override for kiwix-serve (kiwix-manage resolves as its sibling); ignored in packaged builds

Canned-real-output regression-fixture policy: because these never run in CI, an upstream format change (SSE shape, --list-devices lines, whisper JSON) would otherwise slip past the green gate and only surface on real hardware. So whenever a HILBERTRAUM_* run observes an upstream output format change — or a new format worth pinning — capture the verbatim real output into apps/desktop/tests/fixtures/ and assert a pure parser against it in a CI unit test (the bytes are kept binary via .gitattributes). The first such fixture was the b9585 --list-devices capture parsed by gpu.test.ts (audit L19; re-taken at b11146, #518); add SSE and whisper-JSON fixtures the same way as those formats are observed.