Files
capri-core-rust/docs/spec/09-runtime-lifecycle.md

102 KiB
Raw Permalink Blame History

09 — Runtime lifecycle, CLI, paths & data layout, setup/updates, diagnostics, privacy logs, migration, test inventory

Source of truth: CapriCore 1.0.4 tree ~/Capri (read-only; code wins over docs). Target: one Rust binary capri for Arch Linux, KDE Plasma 6.8 Wayland (companion windows via XWayland) and i3 4.25 (X11). Ollama stays an external process (host has ollama 0.40.15 + ollama-cuda from pacman; Capri pins a minimum of 0.40.10). Feature prefix: RT. Paths in tables are relative to the Capri folder ("legacy root") unless prefixed by a Rust root (CONFIG, DATA, STATE, CACHE, RUN, SHARE, see RT-25).


1. Purpose and scope

This spec defines how Capri is launched, supervised, stopped, located on disk, configured on first run, repaired, purged, told about new versions, diagnosed and migrated, plus the privacy-preserving logging every other subsystem must use, and the inventory of Capri's tests.

Capri file(s) Role in Capri Rust disposition
package.json scripts (63 entries), 15 root *.cmd Command surface capri subcommands; dev-only scripts → cargo xtask (table in RT-13)
packages/runtime/bin/core.mjs init/ollama/start/stop/restart/status/chat/image/cli RT-02..RT-07, RT-11
packages/runtime/bin/capri.mjs doctor/profiles/setup/desktop/models/setup-spotify/spotify/help, delegates to core.mjs RT-01, RT-06, RT-08..RT-10
packages/runtime/bin/models.mjs (followed) Model download command RT-10
packages/runtime/bin/gateway-host.mjs (followed) OpenClaw stdin-lifeline host Dropped (no OpenClaw); lifeline semantics kept for external services (RT-18)
packages/runtime/bin/prepare-desktop.mjs, src/host/desktop-identity.mjs, src/host/electron-bundle.mjs Windows branded Capri.exe copy of Electron, Electron completeness Dropped; Linux identity = app_id/WM_CLASS capri (§8)
packages/runtime/bin/response-timing-preload.mjs --import preload into OpenClaw to time provider calls In-process timing (RT-31)
packages/runtime/bin/run-node.ps1, patch-openclaw.mjs Node selection, npm postinstall patcher Dropped
packages/runtime/src/desktop-launcher.mjs Desktop preconditions, single-instance show, detached launch RT-06, RT-20
packages/runtime/src/host/{paths,executables,environment,processes,readiness,launch-receipt,ollama-bundle,registry-network}.mjs, stop-windows-process.ps1 Paths, executable discovery, child env, markers, launch/stop, readiness, receipts, Ollama runtime checks, registry TLS compat RT-14..RT-20, RT-24..RT-26
packages/runtime/src/{privacy-log,atomic-json,safe-file}.mjs (+ followed response-timing*.mjs, technical-model-id.mjs, http.mjs) Allowlist log records, atomic/private writes, bounded HTTP RT-16, RT-27, RT-29..RT-33
followed: src/providers/{core,services,model-plan,pull-model,pull-service-recovery,registry-tls-recovery,embedding-model,native-model}.mjs, src/context.mjs (runtime,initialize), src/config/settings.mjs, src/hardware/{profiles,model-catalog,model-profile,memory-budget,responsiveness}.mjs Core start/stop order, model presence, settings validation, profiles RT-08..RT-11, RT-19, RT-23, RT-24 (semantics of inference/hardware owned by other specs)
packages/installer/** (bin, src, windows: 65 files) Windows Setup.exe bootstrap, PowerShell/WinForms wizard, Node install engine, uninstaller RT-39..RT-45 (first-run setup, component engine, purge, PKGBUILD)
packages/updater/**, apps/desktop/update-service.mjs (+ renderer/update-notification.mjs, IPC in main.mjs:5266-5332) GitHub release check, download, staged transactional apply RT-46 (passive notice), RT-47 (apply not ported)
apps/desktop/diagnostics/{report,redact,archive,state,resources,developer,response-timeline}.mjs (+ main/companion-ipc.mjs:159-205) Bug-report ZIP, redaction, developer log viewer/timelines RT-34..RT-38
config/installer*.json, uninstaller-text.json, release.json, community.json, hall-of-fame.json Wizard/uninstall catalogs (50 locales), release identity, links, credits RT-39, RT-44, RT-46, RT-49
scripts/* (89 files) Compatibility shims (2–13 lines) re-exporting tools/* and packages/* None (dev aliases in xtask)
data/**, logs/** Private state (schemas only were inspected) §3 inventory, RT-48 migration
tests/** (274 files), tools/** (≈220 files) Qualification §11

Out of scope (other specs; consumed through interfaces in §9): agent/LLM turns and tools, memory content, voice/ASR engines, desktop actions (capri_linux), avatar/UI rendering, filesystem-permission semantics, Spotify, request router internals.

The local Linux bridge (tag FWS-LINUX-BRIDGE) touches this subsystem in three places: desktop-launcher.mjs:53-56 adds --ozone-platform=x11 on Linux; apps/desktop/main.mjs installs a Linux cursor and enables the native escape/action helpers on linux; the out-of-tree launcher ~/.local/bin/capri runs Electron directly with --ozone-platform=x11 and appends raw main-process output to logs/electron-main.log (0644). That last behavior violates Capri's own log policy and must not be reproduced (§7).


2. Feature catalog

Priorities: P0 companion broken without it, P1 expected by a Capri user, P2 optional/niche. "Rust/Linux" lines are normative for the rewrite.

A. Command-line surface

RT-01 capri dispatcher — P0

  • Source: packages/runtime/bin/capri.mjs:22-116, core.mjs:23-119.
  • Capri: capri.mjs <cmd> defaults to help; core.mjs defaults to status. Commands start stop status init chat image cli restart ollama are forwarded to core.mjs (capri.mjs:95-100). capri.mjs errors print Capri: <message> to stderr, exit 1; core.mjs errors print <message>, exit 1. Unknown command → Unknown command: <cmd>. Help text (verbatim): Capri commands: doctor, profiles, setup [--profile=balanced], models, desktop, start, stop, status, chat. See docs/installation.md.
  • Rust/Linux: single binary with clap. capri without arguments runs the GUI in the foreground (the .desktop Exec=capri). Every error prints Capri: <message> to stderr. Exit codes: 0 success, 1 runtime error, 2 usage error. Global environment only (no global flags): CAPRI_HOME, CAPRI_SHARE_DIR, CAPRI_OLLAMA_PATH (RT-25/26).

RT-02 capri status — P0

  • Source: core.mjs:46-87.
  • Capri: never starts anything. Probes (in this order):
    1. GET <ollamaUrl>/api/version, timeout 3 s → ollama: <version> or "stopped".
    2. Gateway only if marker capri is alive and the token file exists: GET <gatewayUrl>/v1/models with bearer, 3 s → openclaw: "ready" | "stopped".
    3. If Ollama answered: GET /api/ps (default 10 s) → loadedModels: [{name, vramGiB: round2(size_vram / 2^30)}].
    4. Voice: GET http://127.0.0.1:<voicePort>/health with authorization: Bearer <data/speech/companion-voice-token>, 3 s → the health JSON or "stopped" (errors swallowed: voice is optional). Prints JSON.stringify(obj, null, 2) with keys desktop (running|stopped from the desktop marker), ollama, openclaw, naturalVoice, ui ("Capri desktop companion (capri.cmd)"), agent (agentId), model, session (sessionKey), loadedModels.
  • Rust/Linux: same object, keys in the same order, with openclaw replaced by core ("ready" when the running GUI/headless core answers status on the control socket with core: ready, else "stopped") and ui = "Capri desktop companion (capri)". Voice probe sends the bearer only after an unauthenticated probe proves the port belongs to the managed voice marker (RT-17).

Synthetic example:

{
  "desktop": "running",
  "ollama": "0.40.15",
  "core": "ready",
  "naturalVoice": { "ready": true, "protocolVersion": 2, "engine": "chatterbox-turbo", "activeEngine": "turbo" },
  "ui": "Capri desktop companion (capri)",
  "agent": "capri",
  "model": "capri-qwen3.5:4b",
  "session": "agent:capri:main",
  "loadedModels": [{ "name": "capri-qwen3.5:4b", "vramGiB": 3.21 }]
}

RT-03 capri start (headless core) — P1

  • Source: core.mjs:32-38 → providers/core.mjs:17-83 (startCore, preload = settings.preloadModels).
  • Capri prints (verbatim): Capri is ready. OpenClaw <openclawVersion>; Ollama <version>. / Control UI: <gatewayUrl>/ / Chat API: <gatewayUrl>/v1/chat/completions / Run capri.cmd to open the desktop companion. / API token is stored privately in data/openclaw/gateway-token.
  • Rust/Linux: runs the core start sequence RT-23 without a window (start/adopt managed Ollama, ensure model aliases and presence, prewarm when preloadModels), then prints Capri is ready. Ollama <version>. and Run capri to open the desktop companion. and exits; the managed Ollama keeps running (marker) and is adopted by the GUI later. No Gateway lines.

RT-04 capri stop — P0

  • Source: core.mjs:39-41, providers/core.mjs:216-232 (stopCore), providers/services.mjs:18-35 (stopManaged).
  • Capri order: desktop (graceful) → companion-voice ∥ gateway (Promise.allSettled, first rejection rethrown after both settle) → ollama (models unloaded first, RT-19). Each stop logs Capri service shutdown: <name> <ms> ms. Success message: Capri and its Ollama instance stopped.
  • Rust/Linux: desktop (control socket stop, fallback SIGTERM — RT-18) → every other registered external service (voice, optional ASR/router workers) concurrently → ollama last. Exit 1 if any stop fails; failed services keep their markers. Same success message.

RT-05 capri restart — P2

  • Source: core.mjs:42-45 (stops and restarts only the Gateway: Capri restarted with its saved state.).
  • Rust/Linux: if the GUI runs, send control restart (RT-22 restart path); otherwise stop then start of the headless core. Same message.

RT-06 Desktop launch (capri, capri desktop) — P0

  • Source: desktop-launcher.mjs:10-66, capri.mjs:85-91.
  • Capri preconditions, in order (no file is written before step 4 succeeds or fails — tests/desktop-launcher.test.mjs):
    1. .runtime/updates/active.json exists → An update is in progress or was interrupted. Wait for it to finish, or repair this folder with the full installer.
    2. process.arch !== 'x64' → This desktop preview currently targets x64.
    3. config/core.local.json missing → Run npm run setup first to choose a hardware profile.
    4. Live desktop marker → write data/run/desktop.show = {"show":true,"launchNonce":<CAPRI_LAUNCH_NONCE|null>}, return {...marker, alreadyRunning:true} without initializing config, memory or credentials.
    5. Electron bundle incomplete → The Capri desktop download is incomplete. Open Capri Setup again, select this installation folder and choose Retry or Repair. Keep Setup open until it finishes; microphone and voice are optional.
    6. initialize(rt); Windows identity copy; delete stale data/run/desktop.{stop,show}; unset ELECTRON_RUN_AS_NODE; launch('desktop', electron, ['--ozone-platform=x11' (Linux only), 'apps/desktop/main.mjs']) detached. --wait blocks until the child exits. Output: Showing the running Capri. or Capri companion started (process <pid>).
  • Rust/Linux:
    • capri (no args) and capri desktop --wait: run the GUI in this process. Steps: migration guard (an unfinished migration journal, RT-48, blocks with A data import is incomplete. Run "capri migrate --resume" or "capri migrate --rollback".) → single instance (RT-20; duplicate sends show and prints Showing the running Capri., exit 0, touching no file) → if no CONFIG/core.local.json, open first-run setup (RT-39) instead of erroring → create dirs → write RUN/run/desktop.json marker for this process → GUI.
    • capri desktop (P2 convenience): spawns a detached capri desktop --wait (setsid, null stdio), waits ≤25 s for window-ready on the control socket, prints Capri companion started (process <pid>)..
    • Windowing backend: on a KDE Wayland session force the X11 backend (XWayland) for all companion windows; if WAYLAND_DISPLAY is set and DISPLAY is not, fail with Capri needs XWayland on Wayland sessions; DISPLAY is not set. On i3 use X11 natively.

RT-07 capri chat / capri image — P1

  • Source: core.mjs:88-109, src/client.mjs:10-45.
  • Capri: chat <text…> joins argv with spaces and prints one reply; without text it runs a REPL: banner Capri — общий локальный диалог. Для выхода: /exit, prompt \nВы: , reply printed as \nCapri: <text>, empty input ignored, /exit ends. Request: POST /v1/chat/completions, timeout 240 s, headers bearer + x-openclaw-session-key: <sessionKey> + x-openclaw-message-channel: webchat, body {model:"openclaw/<agentId>", stream:false, messages:[{role:"system",content:personaPrompt()},{role:"user",content}]}; reply passed through plainDialogueText(...).trim(). image <file> [prompt…]: reads the file, MIME image/jpeg if bytes start FF D8 else image/png, content = [{type:"text",text},{type:"image_url",image_url:{url:"data:<mime>;base64,…"}}], default prompt Опиши это изображение.
  • Rust/Linux: if the GUI runs, send control chat (§5.2) so the same session/history is used; otherwise run the agent headless in-process (agent spec API) while holding the instance lock (refuse with Capri is running but not responding. if the lock is held and the socket is dead). Keep the REPL strings verbatim (they are Capri's only CLI-localized strings; see open question Q9).

RT-08 capri doctor / capri profiles — P1

  • Source: capri.mjs:25-44; hardware/probe.mjs:205-310; hardware/profiles.mjs:53-120; hardware/model-catalog.mjs.
  • Capri: JSON {hardware, recommendation, software:{node,ollama,openclaw}, current:{model, contextTokens}}, plus profiles: MODEL_CHOICES for profiles. hardware = {platform, arch, osRelease, cpu, cpuThreads, ramBytes, availableRamBytes, gpus:[{name, vendor, vramMiB, memoryKind:"dedicated"|"shared"|"unknown", freeVramMiB, cudaCandidate, driver?}], warnings:[]}; NVIDIA via nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv,noheader,nounits. Recommendation rules (exact): RAM check ram ≥ required − max(0.5, min(2, required/16)); unsupported below the 8 GiB rule (The first supported profile requires at least 8 GiB RAM.); largest dedicated GPU only (never summed, shared memory never counted); quality if RAM ok and VRAM ≥ 11.875 GiB, else desktop if ≥ 7.875, else balanced if RAM ok, else minimal; cpuThreads = max(1, min(profile.cpuThreads, floor(threads/2) || 1)); reasons: Detected <x.x> GiB RAM., Largest confirmed dedicated GPU: <x.x> GiB. or Dedicated VRAM is unknown; a conservative text profile is selected., Ollama decides actual text acceleration. CUDA speech must be installed and checked separately. (Required RAM per profile comes from profileRamRequirement: gpuSystemRamGiB of config/memory-estimates.json when a dedicated GPU ≥ threshold−0.125 GiB exists, else profile.ramGiB.)
  • Rust/Linux: same JSON. software becomes {ollama: bool, ollamaPath, ollamaVersion|null, session: "kde-wayland"|"i3-x11"|"other", xwayland: bool, python: bool, uv: bool}. Linux GPU probe = nvidia-smi (if on PATH) + /sys/class/drm/card*/device/{vendor,device,mem_info_vram_total,mem_info_vram_used} (AMD dedicated), Intel/AMD APUs memoryKind:"shared"; RAM from /proc/meminfo (MemTotal, MemAvailable). Remove the warning The desktop is currently qualified for Windows x64 only.

RT-09 capri setup (CLI profile selection) — P1

  • Source: capri.mjs:45-84, hardware/model-profile.mjs:12-103.
  • Capri:
    • Refuses if markers desktop, capri or ollama are alive: Stop Capri with npm stop before changing model profiles. Existing settings were preserved.
    • Unsupported hardware → reasons joined by spaces.
    • Selected = --profile=<id> else recommended. Interactive (stdin is a TTY and no --yes): prints Model profiles change quality, memory use and latency. Speech packs are optional and are installed separately., then for each choice <id>: <model>, <ramGiB>+ GiB RAM, ~<recommendedVramGiB> GiB VRAM for acceleration[ (BETA)]. <description>; asks Profile [<id>]: ; if core.local.json exists asks Replace existing local model settings? Type yes: (must be exactly yes, else Setup cancelled; existing settings were preserved.). Non-interactive with existing local settings requires --replace (Local settings already exist. Use --replace only to deliberately change this installation.).
    • Writes overrides transactionally (restores previous core.local.json and gateway config on failure): model=alias, modelSetupRequired:false, upstreamModel, contextTokens = largest allowed choice ≤ min(current, model limit) (fallback 8192), cpuThreads, preloadModels (true only for quality), keepAlive:300, resourceProfile, modelCapabilities, modelContextLimit, thinkingDefault (off if capabilities lack thinking, else low).
    • Message: Saved <id> locally. Next: npm run models:pull, then npm run desktop. No models were downloaded by setup. Never downloads.
  • Rust/Linux: identical semantics; npm stop → capri stop; message Saved <id> locally. Next: capri models pull, then capri. No models were downloaded by setup. No gateway config to patch (the agent spec reads settings directly).

RT-10 capri models pull — P0

  • Source: bin/models.mjs:1-52, providers/model-plan.mjs:3-25, providers/pull-model.mjs:1-203, providers/{embedding-model,native-model,pull-service-recovery,registry-tls-recovery}.mjs.
  • Plan (side-effect free): models = unique([...(embeddingOnly ? [] : args || [upstreamModel ?? model]), "bge-m3:latest"]). --embedding-only with explicit names → Choose models or embeddings only. Name regex ^[a-z0-9][a-z0-9._/-]*(?::[a-zA-Z0-9._-]+)?$ else Invalid model name (CLI flags can never become model names). --plan prints {"models":[...],"preview":true[,"embeddingOnly":true]} and exits.
  • Execution: start managed Ollama (RT-24); for each model print Downloading <m>... then pull (§5.1 /api/pull): print <model>: <status>[ <pct>%] when status changes or a new 10 % step is reached; stream line {"error":…} → fail with URL-redacted message (https?://… → origin+path + ?[redacted] if a query existed; ≤1800 chars); success requires a status:"success" line, else retryable Model pull ended before verification completed. HTTP non-2xx → error, retryable for 408/429/500/502/503/504.
  • Retry: transient = error codes ECONNRESET ETIMEDOUT EAI_AGAIN ENOTFOUND UND_ERR_SOCKET UND_ERR_CONNECT_TIMEOUT ECONNREFUSED ENETUNREACH EHOSTUNREACH (walking cause/errors ≤4 deep) or message regex (lookup … i/o timeout|no such host, connection reset, unexpected EOF, TLS handshake timeout, temporary failure in name resolution, dial|read|write tcp … (connectex|wsarecv|wsasend|i/o timeout|connection timed out|network is unreachable), tls handshake eof). At most 4 attempts; backoff 2000·2^n ms (2, 4, 8 s); message Model download connection interrupted: <msg> [codes]. Retrying <n>/4 in <s>s; Ollama retains verified layers and partial downloads. After the 4th failure with codes: The local model download connection failed (<codes>). Downloaded layers are retained. Retry setup and include the Ollama logs from Save report (ZIP) if it continues. (code: CAPRI_MODEL_PULL_CONNECTION_FAILED). One registry-TLS recovery on TLS handshake timeout (RT-24); connection refused/reset → restart the managed Ollama only if it is dead and owned (pull-service-recovery.mjs:7-25). Pause file (installer only): abort the stream, print Model download paused. Progress is retained. / Resuming model download.; whole request deadline 2 h.
  • Then (unless --embedding-only) ensure the native chat alias (LLM spec: /api/show + /api/create, must expose tools+thinking, vision when the upstream has a projector), then create the CPU embedding alias capri-embed:latest (Capri runs ollama create <embeddingModel> -f config/Embedding.Modelfile, file = FROM bge-m3:latest / PARAMETER num_gpu 0), then write data/model-inventory.json = pretty /api/tags response, print Models ready. Memory embeddings are configured for CPU.
  • Rust/Linux: same; create the alias through POST /api/create {"model":"capri-embed:latest","from":"bge-m3:latest","parameters":{"num_gpu":0},"stream":false} (already used by embedding-model.mjs:21-31) so no ollama CLI subprocess is needed. Subcommand spelled capri models pull [NAME…] [--plan] [--embedding-only].

RT-11 capri init — P1

  • Source: core.mjs:27-29, context.mjs:254-333.
  • Capri: creates data/openclaw, data/workspace, data/workspace/memory, data/models, data/run, logs, .runtime/tmp; creates the gateway token (O_EXCL, 0600, 32 random bytes hex); initializes personality and owner memory (repairing only shipped defaults in managed installs); creates/reconciles the OpenClaw config (logging silent, diagnostics off). Message Capri configuration and private workspace initialized.
  • Rust/Linux: create every Rust root with mode 0700 (RT-25), call the memory spec's initialize_workspace() (persona templates from SHARE/workspace-templates), no token, no gateway config; idempotent; same message.

RT-12 capri maintenance clean-cache — P2

  • Source: tools/maintenance/clean-cache.mjs:7-145, tests/cleanup.test.mjs.
  • Capri: preview by default; --apply deletes; --package-caches adds .downloads, .runtime/uv-cache, .runtime/npm-cache; fixed candidate list (27 verification folders, .ruff_cache, .pytest_cache, __pycache__ under maintained source); any symlink in a candidate's ancestry aborts the whole plan before the first deletion; links inside a cache are unlinked, never traversed; never touches data/. Output JSON {applied, logicalBytes, files, paths:[{path,bytes,files,links}]}, then (preview) Preview only. Add --apply to remove these caches. Stop verification/install jobs first. Unknown args → Usage: node scripts/clean-cache.mjs [--apply] [--package-caches].
  • Rust/Linux: same contract over CACHE/ (tmp/, downloads/ (verified archives), verification/) and, with --package-caches, CACHE/uv/. DATA is never a candidate.

RT-13 Legacy command mapping — P1

Capri command (npm script / .cmd) Rust equivalent
npm start, start.cmd capri start
npm stop, stop.cmd capri stop
npm run status, status.cmd capri status
npm run chat, chat.cmd capri chat [text] (+ capri image FILE [prompt])
npm run desktop, capri.cmd (run-node.ps1 desktop) capri / capri desktop [--wait]
npm run doctor / capri.mjs profiles capri doctor / capri profiles
npm run setup, setup.cmd capri setup [--profile=ID] [--yes] [--replace] (CLI) — GUI first-run is RT-39
npm run models:pull capri models pull [NAME…] [--plan] [--embedding-only]
`core.mjs init ollama
core.mjs cli … (OpenClaw CLI passthrough) Not ported (no OpenClaw)
npm run setup:spotify, setup-spotify.cmd, spotify.cmd capri spotify setup, capri spotify … (Spotify spec)
setup-streaming-asr.cmd, setup-multilingual.cmd, setup-request-router.cmd / npm run setup:routing, setup-voice-training.cmd `capri components install recognition
voice.cmd (.runtime/voice-training-venv/Scripts/python.exe -m integrations.voice_training) capri voice-training … → external Python (voice spec)
Install Capri.cmd (wizard) pacman/AUR package + in-app first-run setup (RT-39/RT-45)
Save setup report.cmd capri diagnostics export (RT-38)
npm run clean:cache capri maintenance clean-cache
npm run configure:{perception,files,applications,dialogue,performance,context} Obsolete: they patch OpenClaw openclaw.json (plugins/tools allowlists, sampling, context policy, native alias) after backing it up to data/config-backups/. Rust registers tools statically; permissions decide availability.
npm test, test:runtime, test:assets, check, format, format:check cargo test, cargo test -p capri-runtime, cargo test --features assets, cargo clippy, cargo fmt
npm run verify, verify:* (34 scripts), benchmark:latency, build:sprites, build:locales, verify:locales cargo xtask verify <name> / bench / assets (dev only, never shipped)
release:source, release:check, release:installer, verify:installer, postinstall makepkg + PKGBUILD checks (RT-45); postinstall (OpenClaw patcher) dropped

B. Process supervision

Managed service names in Capri: desktop (Electron), capri (Gateway host = rt.logPrefix), ollama, companion-voice (Python TTS server), plus test prefixes verification, desktop-verification. ASR and router workers are children of the desktop process, not marker-managed. In Rust: desktop (the GUI process itself), ollama, companion-voice (if the voice spec keeps the Python server), and any worker another spec chooses to run detached.

RT-14 Process markers and identity — P0

  • Source: host/processes.mjs:23-85.
  • Marker path data/run/<name>.json; name must match ^[a-z0-9-]{1,64}$ (case-insensitive) else Invalid managed process name.
  • Marker JSON: {"pid":int,"startedAt":"<decimal ticks>","executable":"<abs>","args":[...],"projectRoot":"<abs root>","privateLogSchema":1,"deviceKey"?:"<≤128 chars>"}.
  • Read rules: file ≤ 65 536 bytes, valid JSON, "belongs here" (projectRoot absolute and equal to this root — case-insensitive on Windows; legacy markers without projectRoot only if executable or args[0] lies inside the root), pid positive integer, startedAt all digits; otherwise the marker is ignored (treated as absent).
  • managedProcess(name) = marker valid and current start time of pid equals startedAt. Linux start time: /proc/<pid>/stat, take text after the last ) + 2 chars, split on spaces, element 19 (= stat field 22 starttime, clock ticks since boot) — same as capri_linux/common.py:80-87 started_ticks.
  • requiresPrivacyRestart(marker) = marker.privateLogSchema !== 1: such a service is stopped and relaunched before adoption (it may hold raw stdout descriptors from an older build).
  • Rust/Linux: keep the schema, rename projectRoot → dataRoot (canonical DATA path) and keep privateLogSchema:1. Markers live in RUN/run/<name>.json (tmpfs; vanishes at reboot/logout together with the processes). After validating identity, open a pidfd (pidfd_open) and use it for waiting and signalling, pinning the identity like the Windows handle in stop-windows-process.ps1:12-25.

RT-15 Launching a managed service — P0

  • Source: host/processes.mjs:86-195, host/environment.mjs:8-48.
  • If the service is already managed: call onExit immediately and return the existing marker (adoption).
  • Executable must exist: Executable for <name> is missing. Run npm run doctor.
  • Create logs/ and data/run/; delete data/run/<name>.stop (only the launcher may clear a stop request; a slow child must never erase a fresh one).
  • Log files logs/<name>.stdout.log / .stderr.log: private-path check; if present must be a regular file with nlink == 1 (Service log storage is unavailable.); truncate to empty, mode 0600. Child output is never written: stdio: 'ignore'. Only lifecycle records are appended (RT-30).
  • Spawn: cwd = root, env = environment(rt) (+ registry-TLS adjustment for Ollama, + per-service extras such as OLLAMA_GPU_OVERHEAD, device variables), detached: true on non-Windows (new session), hidden window on Windows.
  • Events: spawn → record stdout {event:"started"}, read start time; if unreadable → <name> exited during startup; see logs.; write marker atomically (failure → kill child, reject). error → stderr {event:"spawn-failed", code}. exit → {event:"exited", exitCode?} to stderr when code ≠ 0, else stdout (signal exits have no exitCode).
  • Rust/Linux: std::process::Command with process_group(0) + setsid in pre_exec, stdin/stdout/stderr = Stdio::null(), current_dir(DATA). Children survive GUI exit (no PR_SET_PDEATHSIG); the GUI reaps children it spawned (tokio::process::Child::wait) and uses pidfd polling for adopted ones. Env: inherit the parent environment minus *TOKEN*, *SECRET*, *PASSWORD*, *API_KEY* variables (defense in depth; Capri leaked OPENCLAW_GATEWAY_TOKEN into every child), then add the service env.

RT-16 Readiness waiting and bounded local HTTP — P0

  • Source: http.mjs:2-62, host/readiness.mjs:6-55.
  • request(url, {timeout=10 s, maxBytes=16 MiB}): redirects are errors; non-2xx → body discarded, error HTTP <status> from <origin> (never the body); body > limit → Service response exceeds limit; empty body → null; else JSON.
  • waitFor(check, {timeout=90 s, interval=1 s, label}): returns first truthy result; errors remembered; timeout → <label> did not become ready. <last error message>; abortable.
  • waitForOwnedService(check, {name, label, timeout=10 min, interval=1 s, ownershipInterval=5 s}): captures the marker at start (absent → CAPRI_SERVICE_EXITED); every 5 s re-checks pid+startedAt (changed/absent → <label> stopped during startup. Check its local logs and reconnect., code CAPRI_SERVICE_EXITED); deadline → <label> is still not ready after <ceil(s)> seconds. Check its local logs and reconnect.[ <last>], code CAPRI_SERVICE_STARTUP_TIMEOUT. Rationale: cold imports on a fresh machine can take minutes; never relaunch a live slow service.
  • Rust/Linux: wait_for / wait_for_owned_service with identical constants and codes; LocalHttp = reqwest client (rustls, redirect::Policy::none(), per-request timeout, streamed size cap).

RT-17 Port ownership and allocation — P0

  • Source: providers/services.mjs:50-57,104-127, installer/src/ports.mjs:3-18, installer/src/engine.mjs:589-606, config/settings.mjs:41-44, integrations/voice_runtime/host.mjs:73-91.
  • Settings validation: gatewayPort, ollamaPort integers 1024–65535 and different (Service ports must be different).
  • Ollama: before launching, GET /api/version (1.5 s). Answer + no managed marker → Ollama port <p> is already in use. Select a free managed port in config/core.local.json. Capri never stops an unmanaged/system Ollama.
  • Authenticated services: probe without credentials first so a token is never sent to a foreign process (Gateway /readyz without auth; answer + unmanaged → Gateway port <p> is occupied by another installation. Choose a free local port.). The voice host sends its bearer directly and maps 401/403 to Voice port belongs to another installation. Close its voice service before starting this one.; a healthy answer without marker → Voice port belongs to an unmanaged process.
  • Allocation (first install only, when core.local.json does not exist): findFreePort(first, reserved) scans first … min(first+100, 65536)−1, skips reserved ports, tests with an exclusive listen(127.0.0.1); result added to reserved; none → No free local service port was found. Allocated: gatewayPort (base 18789), ollamaPort (base 11435) into core.local.json, voice port (base 8101) into config/companion-voice.json.
  • Rust/Linux: allocate ollamaPort and voice port at first-run with the same algorithm; gatewayPort is kept only as an ignored legacy key unless the optional loopback API (Q4) is enabled. Unauthenticated probe first for every authenticated local service (voice health), then authenticated. The Arch system ollama.service (port 11434, /var/lib/ollama, enabled on the host) is never touched.

RT-18 Graceful stop and lifelines — P0

  • Source: host/processes.mjs:196-243, stop-windows-process.ps1, bin/gateway-host.mjs:9-53, apps/desktop/main.mjs control timer (~7000-7019), integrations/voice_runtime/server.py:44-80,240-251.
  • stopProcess(name): no valid marker → return. graceful = supervised Gateway host (args[0] ends with gateway-host.mjs) or name ∈ {desktop, companion-voice}. Timeout: 350 s supervised Gateway, 60 s other graceful, 20 s otherwise. Linux: if identity matches, graceful → write data/run/<name>.stop = stop\n, else SIGTERM; then waitFor(!managedProcess(name), timeout, interval 100 ms, label "Stopping <name>"). Timeout throws and the marker is preserved (Windows text: The managed service did not finish its shutdown. Its process marker was preserved.). No SIGKILL ever. After the wait, re-read the marker and delete it only if pid and startedAt are unchanged (a concurrent relaunch keeps its new marker); a stale marker (identity mismatch) is simply deleted.
  • Lifelines (who watches what):
    Service Watch Poll On request
    Gateway host data/run/capri.stop + SIGINT/SIGTERM 250 ms closes OpenClaw's stdin (OPENCLAW_GATEWAY_HOST_LIFELINE=stdin, OPENCLAW_NO_RESPAWN=1); deletes stop file on exit; exit code = child's
    Desktop data/run/desktop.stop 400 ms unlink + app.quit() (core keeps running)
    Voice server data/run/companion-voice.stop 250 ms finishes current request, shuts down; returns immediately if the file exists at startup; deletes it on exit
    Ollama — — SIGTERM after unloading models (RT-19)
  • Rust/Linux: StopPolicy::{ControlSocket, StopFile{poll:250 ms}, Signal(SIGTERM)} with the same timeouts. GUI: control stop (5 s connect/answer budget) then SIGTERM fallback; the GUI installs SIGTERM/SIGINT/SIGHUP handlers that run the normal quit path (not "unload models"). Voice (Python): stop file. Ollama: SIGTERM. A forced kill is not provided (Q6).

RT-19 Shutdown order and model unload — P0

  • Source: providers/core.mjs:216-232, providers/services.mjs:18-35.
  • stopManaged('ollama') when managed: GET /api/ps (3 s; failure = empty list), then in parallel for every loaded model POST /api/generate {"model":<name>,"keep_alive":0,"stream":false} (30 s each), then stopProcess('ollama').
  • Order: desktop → (voice ∥ Gateway) → Ollama. Comment preserved as rationale: "Voice and Gateway have independent lifelines. Drain both concurrently; leave Ollama available until Gateway has released its SQLite/session state."
  • Rust/Linux: in-app quit = cancel turn → flush/close agent, memory and journal stores (replaces Gateway drain) ∥ stop voice and other workers → unload + stop Ollama. CLI capri stop = stop GUI first, then the same.

RT-20 Single instance, show/stop channel, launch receipts — P0

  • Source: apps/desktop/main.mjs:312-331 (Electron requestSingleInstanceLock, duplicate → app.exit(0), owner second-instance → restore), desktop-launcher.mjs:19-26, host/launch-receipt.mjs:5-29, packages/installer/windows/install-discovery.ps1:55-81.
  • Show request carries a launch nonce (^[a-f0-9]{32}$, env CAPRI_LAUNCH_NONCE). The desktop publishes data/run/launch-<nonce>.json = {"schemaVersion":1,"nonce":"…","phase":"window-ready","pid":N,"at":<ms epoch>} on first ready-to-show and after each handled show request; refuses symlinked ancestors (Linked launch receipt folder) or a non-regular existing receipt (Invalid launch receipt). Setup's "Launch Capri" waits ≤25 s (100 ms poll), deletes the receipt, else Capri was installed, but its window did not confirm startup. Retry opening Capri or save a diagnostic report.
  • Rust/Linux:
    • Instance id = first 16 hex chars of SHA-256(canonical DATA path) (mirrors applicationId = "Overyx.Capri." + sha256(lowercase root)[0..16], desktop-identity.mjs:11-13). Instance dir RUN = $XDG_RUNTIME_DIR/capri/<id>/ (0700).
    • Lock: flock(LOCK_EX|LOCK_NB) on RUN/instance.lock, held for the GUI lifetime.
    • Control socket RUN/control.sock, created under umask 0177; every accepted connection must pass SO_PEERCRED uid == own uid (pattern of capri_linux/input_daemon.py:165-207). Protocol §5.2.
    • Duplicate launch: connect, send show (+ nonce), print Showing the running Capri., exit 0. Lock held but no answer within 5 s → Capri is already running but not responding. exit 1; never start a second GUI.
    • Receipt files are replaced by the show reply {"ok":true,"phase":"window-ready","pid":N}. Optional compat (P2): when CAPRI_LAUNCH_NONCE is set, also write RUN/run/launch-<nonce>.json with the Capri schema.

RT-21 Desktop startup sequence — P0

  • Source: apps/desktop/main.mjs:300-470 (setup), ~6940-7060 (whenReady), 2439-2490 (connectBackend), model-startup.mjs:6-21, startup-progress.mjs:1-66.
  • Order: verification guard (see RT-50) → app name/identity → private profile paths → single-instance → initializeDesktop: response-timing log logs/response-desktop.jsonl (RT-31) → read API inference config → model-selection log (RT-32) → initialize(rt) → window, tray, global shortcut CommandOrControl+Shift+Space (toggle) → on ready-to-show: show, publish receipt, updates.checkOnStartup() (RT-46) → on ready: brain index start, user tools refresh (warn User tools could not be listed. Open Settings to retry.), lock/suspend hooks, 400 ms control timer, startup stages, startModelServices (core, then recognition/voice per memory policy), startup.finish().
  • First launch preload: data/desktop/first-start.json = {"schemaVersion":1,"preloadModels":<bool>} written by Setup's finish page. consumeFirstLaunchPreload: missing/invalid → true; valid → delete file, return value (warn Could not clear the first-launch model preference. if deletion fails for a reason other than ENOENT).
  • Startup stages: ['core', ...(preload ? ['models'] : []), ...(warmRecognition ? ['recognition'] : []), ...(warmVoice ? ['voice'] : [])]. Progress object {type:"startup.progress", started, stages:[{id, state:"waiting"|"running"|"ready"|"failed", estimate, started?}], finished}; default estimates seconds {core:15, models:12, recognition:8, voice:25}, overridden by measured history in data/desktop/startup-times.json ({"core":14.2,"models":9.8}; clamp 1–600; updated only on successful stage end; saved atomically at finish()).
  • connectBackend gates (in order): voice training busy → no-op; modelSetupRequired and not API → backend offline with Choose a language model in Settings → Language model.; API setupRequired → offline API connections; shutting down → error. Backend phases/texts: starting Starting local core…, ready Ready, failure offline The local core is unavailable. Reconnect to try again. (or the Ollama bundle repair message), sleep asleep Sleeping. Send a message to wake Capri.
  • Fatal init failure: stderr CAPRI_DESKTOP_INIT, error box title Capri could not start. body Your saved data has been preserved. Repair Capri with the installer and try again., exit 1.
  • Rust/Linux: same order and texts, except body Your saved data has been preserved. Reinstall or repair the capri package and try again.; global shortcut and tray belong to the UI spec (see §8 for KDE vs i3 constraints).

RT-22 Quit, restart, sleep, close-to-tray, signals — P0

  • Source: apps/desktop/main.mjs:3350-3470 (queueDesktopRelaunch, shutdownForRestart, quitAndUnload), 6734-6741 (close → hide), 6795-6861 (before-quit, window-all-closed), power hooks (~6960-6990).
  • Window close → hide to tray unless quitting. window-all-closed → quit. before-quit closes every subsystem (recording indicator, user tools, workflows, private memory, brain, chips, viewers, music listening, call audio, computer control, timers, voice, microphone, router, initiative, observer…), saves window/layout/dimming, unregisters shortcuts, destroys tray; it defers quit while the audio-cable installer is busy.
  • Tray "Quit": refuses while the cable installer is busy (Wait for VB-CABLE setup to finish before closing or restarting Capri.); confirmation Quit Capri? / Capri will close and unload the local models. Any active reply will stop. with choices Cancel, Sleep, Restart, Quit and unload models (danger). Restart → shutdownForRestart('Preparing to restart Capri...') → relaunch (Capri.exe, else node packages/runtime/bin/capri.mjs desktop) → quit. Confirm → teardown, backend stopping Stopping Capri and freeing model memory…, await pending startups, stopCore({companion:false}), close speech installer, quit; on failure backend offline Some services could not be stopped. Use stop.cmd or try again.
  • Lock screen / suspend: every subsystem's privacy hook runs (memory lock, screen discard with reason screen-locked/system-suspended, computer-control stop, …).
  • Rust/Linux: identical flows and strings, except Use capri stop or try again. and the Windows-only cable check becomes "audio routing setup busy" (call-audio spec). Restart = release instance lock, spawn detached capri (it retries the lock for up to 10 s), exit. SIGTERM/SIGINT/SIGHUP → normal quit (no model unload). Lock/suspend sources: logind PrepareForSleep(true) and session Lock signals (both desktops), plus org.freedesktop.ScreenSaver.ActiveChanged(true) on KDE.

RT-23 Core start sequence — P0

  • Source: providers/core.mjs:17-214, hardware/responsiveness.mjs:5-24.
  • Steps: stage core running → start Ollama (RT-24) → API mode with skipLocalModelOnApi !== false and chat model ≠ embedding model: GET /api/ps (3 s), if the chat model is resident POST /api/generate {model, keep_alive:0, stream:false} (30 s) and require done === true (The idle local language model could not be unloaded.) → local mode: ensure native alias → ensure embedding alias (repair from bge-m3:latest if present, else Memory model <m> is missing. Run Capri Setup again to repair the installation.) → verify /api/tags contains chat model (local mode) and embedding model (Model <name> is missing. Run scripts/pull-models.mjs.) → start agent runtime (Capri: Gateway + admission probe) → stage core ready.
  • Preload (stage models): prewarm via Ollama directly (no conversation messages, no memories): POST /api/chat {model, messages:[{role:"user",content:"Hello."}], stream:false, think:false (if thinking-capable), truncate:false, shift:false, keep_alive: keepAlive ?? -1, options:{num_ctx: contextTokens, num_predict:1, ...runnerOptions}} unless already resident with the same context_length (and size_vram==0 when acceleration is cpu); POST /api/embed {model: embeddingModel, input:"Memory index warmup.", keep_alive, options:{num_gpu:0}} unless resident with size_vram==0; both 180 s. Agent warmup once per backend process: system Internal runtime warmup. Do not use tools, write files, or save memories., user Reply only with the word Ready., technical session key agent:<agentId>:internal-warmup-<uuid> deleted afterwards; timeout agentWarmupTimeoutMs (180 s when RAM ≤17 GiB, available <6 GiB, profile minimal or acceleration cpu; else 60 s); bookkeeping data/run/capri.primed.json {pid, startedAt, warmupMs} of the Gateway; failure → console Agent warmup unavailable: <msg> and stage failed (non-fatal).
  • Rust/Linux: same steps with the agent in-process; warmup sends the real system prompt + tool schema through the agent spec with num_predict:1 and a throw-away session; once per Ollama process: RUN/run/agent.primed.json {"ollamaPid":N,"ollamaStartedAt":"…","warmupMs":1234.5}. Missing-model message → Run capri models pull.

RT-24 Managed Ollama instance — P0

  • Source: providers/services.mjs:36-93, host/environment.mjs:8-48, host/registry-network.mjs:1-76, providers/registry-tls-recovery.mjs:7-41, host/ollama-bundle.mjs (Windows-only file checks).
  • Executable: CAPRI_OLLAMA_PATH (absolute existing file, else CAPRI_OLLAMA_PATH must point to an existing executable.), else ollama on PATH (+ Windows bundled/LocalAppData candidates). Missing → Ollama is not installed. See docs/installation.md or run npm run doctor. Windows bundle completeness (OLLAMA_BACKEND_FILES, ROCm list) is skipped on Linux (inspectOllamaBundle returns ready).
  • Relaunch conditions: marker deviceKey (default auto) ≠ data/desktop/model-devices.json language selection; marker privacy schema mismatch.
  • Environment (all children get environment(rt); Ollama-relevant subset): OLLAMA_HOST=127.0.0.1:<ollamaPort>, OLLAMA_MODELS=<data>/models, OLLAMA_NO_CLOUD=1, OLLAMA_NUM_PARALLEL=1, OLLAMA_MAX_LOADED_MODELS=2, OLLAMA_KEEP_ALIVE=<keepAlive>, OLLAMA_CONTEXT_LENGTH=<contextTokens>, OLLAMA_FLASH_ATTENTION=1, OLLAMA_KV_CACHE_TYPE=q8_0, LLAMA_ARG_THINK_BUDGET=max(reasoningBudget,4096), CAPRI_CPU_THREADS=max(1,min(cpuThreads??8, availableParallelism)), TEMP/TMP=<cache>/tmp, PYTHONUTF8=1, PYTHONIOENCODING=utf-8, GIT_CEILING_DIRECTORIES=<parent of workspace>, GIT_TERMINAL_PROMPT=0, CAPRI_PROJECT_ROOT, CAPRI_OLLAMA_PORT, plus at launch OLLAMA_GPU_OVERHEAD=<budget.overheadBytes> (GPU-budget spec) and device env (CUDA_VISIBLE_DEVICES/HIP_VISIBLE_DEVICES/ROCR_VISIBLE_DEVICES from the model-devices spec). Capri logs Qwen GPU budget: <json> to console.
  • Readiness: waitFor(GET /api/version) (90 s). Version gate: first x.y.z of version ≥ settings.ollamaVersion (0.40.10) else This build needs Ollama <min> or newer; found <v>. Update the selected Ollama executable.
  • Registry TLS compatibility: file data/network/registry-tls.json {"schemaVersion":1,"mode":"classical","registry":"https://registry.ollama.ai/v2/","verifiedAt":"<ISO>"} (regular, not a symlink, ≤4096 bytes) → append tlsmlkem=0 to GODEBUG (removing any previous tlsmlkem= flag) for the managed Ollama only. Created only during a pull that failed with TLS handshake timeout, when: not already classical, Ollama is owned, no model is loaded (checked before and after), and HEAD https://registry.ollama.ai/v2/ with certificate validation, TLS ≥1.2, curves X25519:P-256:P-384, 7 s timeout returns status 200–499 over TLS 1.2/1.3. Then it saves the flag, prints Registry TLS handshake compatibility confirmed. Restarting the idle owned Ollama with classical key exchange; TLS and certificate validation remain enabled., stops and restarts the idle Ollama. Certificate failures never trigger it.
  • Rust/Linux: identical environment and gates; ollama from PATH (/usr/bin/ollama from pacman ollama, ollama-cuda, ollama-rocm or ollama-vulkan, which replace Capri's Windows ROCm bundle logic). The registry probe uses reqwest+rustls with the same constraints.

C. Paths, executables, safe files

RT-25 Path layout (XDG) — P0

  • Source: host/paths.mjs:5-12 (Capri: everything under the checkout: data/, logs/, .runtime/, config/), context.mjs:18-41.
  • Rust/Linux roots (each created with mode 0700, never through a symlinked ancestor):
    Root Default Holds
    SHARE /usr/share/capri (read-only, package-owned; CAPRI_SHARE_DIR overrides for dev builds) shipped defaults config/*.json, catalogs (installer-text.json, uninstaller-text.json, locales), workspace-templates/, assets, Embedding.Modelfile equivalent constants, LICENSE, THIRD_PARTY_NOTICES.md
    CONFIG $XDG_CONFIG_HOME/capri (~/.config/capri) core.local.json, *.local.json voice overrides, user copies of mutable configs (companion-voice.json, companion-asr.json, voice-training.json, request-router.json)
    DATA $XDG_DATA_HOME/capri (~/.local/share/capri) everything under legacy data/ except run/ (same relative names: desktop/, workspace/, models/, speech/, voices/, secrets/, …) + runtimes/ (Python envs owned by speech specs)
    STATE $XDG_STATE_HOME/capri (~/.local/state/capri) logs/, setup/ (journal, receipts), migration/, crashes/
    CACHE $XDG_CACHE_HOME/capri (~/.cache/capri) tmp/ (child TMPDIR), downloads/ (verified archives), uv/, verification/
    RUN $XDG_RUNTIME_DIR/capri/<instance16> (fallback STATE/run + warning if XDG_RUNTIME_DIR is unset) instance.lock, control.sock, run/*.json markers, run/*.stop, receipts, agent.primed.json
  • CAPRI_HOME=<dir> (portable/test mode): CONFIG=<dir>/config, DATA=<dir>/data, STATE=<dir>/state, CACHE=<dir>/cache, RUN=<dir>/run. This is the only isolation switch (replaces Capri's verification folders under .runtime/).
  • Legacy relative paths stored in settings ("profileDir":"data/voices/capri/en/exports/capri-en-v1", "modelDir":"data/speech/…", "datasetDir":"data/voices/capri/en/imports/<uuid>") are resolved by Paths::legacy(rel): a value starting with data/ maps to DATA/<rest>; anything else (absolute, .., other prefixes) is rejected unless the owning spec allows it. New values are still written with the data/ prefix so configs stay portable between layouts.
  • Installation scope: Capri grants the agent read/write on its own installation folder by default (docs/installation.md, filesystem spec). Under XDG the package files are read-only; the filesystem spec must decide whether the default scope becomes DATA minus private folders (Q7).

RT-26 Executable discovery — P0

  • Source: host/paths.mjs:21-77, host/executables.mjs.
  • findExecutable(name, {extra}): candidates = extra (non-null) then each PATH entry joined with name (+.exe on Windows); first regular file wins; no shell expansion (paths with spaces work — runtime-foundation.test.mjs). Explicit overrides CAPRI_NODE_PATH, CAPRI_OLLAMA_PATH must be absolute existing files, else <VAR> must point to an existing executable. requireExecutable → <Name> is not installed. See docs/installation.md or run npm run doctor.
  • Rust/Linux: PATH search requiring a regular file with an execute bit; only CAPRI_OLLAMA_PATH remains (Node is gone). Python interpreters for external speech services come from their own envs under DATA/runtimes/ (speech specs), never from PATH implicitly.

RT-27 Safe file primitives — P0

  • Source: atomic-json.mjs:13-32, safe-file.mjs:16-53, installer/src/policy.mjs:19-39 (readJson, noLinks).
  • writeJsonAtomic(file, value): mkdir -p parent; temp <file>.<pid>.<uuid>.tmp opened O_EXCL mode 0600; content JSON.stringify(value, null, 2) + "\n"; fsync; rename; temp removed on any failure.
  • writePrivateBytesAtomic(file, bytes): assertPrivatePath (no symlink at the path or any ancestor: Private storage paths cannot contain filesystem links.); existing target must be a regular file with nlink == 1 (Private storage is unavailable.); parent created 0700; temp <file>.<pid>.<32 hex>.tmp; same fsync/rename.
  • Installer noLinks(path): walk to the filesystem root; a symlink, or a regular file with nlink != 1, anywhere on the chain → Installation paths cannot contain filesystem links. readJson(file, max=65536) rejects larger files (Installer metadata exceeds its limit) and strips a UTF-8 BOM.
  • Rust/Linux: fsx module with the same names/semantics, plus fsync of the parent directory after rename (crash durability on ext4/btrfs). Every settings/journal/marker write in every spec goes through these functions. Readers bound their input size (each file's limit is documented in §3).

RT-28 Data ownership boundaries — P0

  • Lifecycle owns the roots and the cross-cutting files (markers, logs, setup journal, migration journal, model-inventory.json, first-start.json, startup-times.json, updates.json, network/registry-tls.json). Every other file in §3 is owned by the listed spec; lifecycle only creates directories, migrates and purges them.

D. Privacy logs and diagnostics

RT-29 Allowlist log record (privateLogRecord) — P0

  • Source: privacy-log.mjs:10-148; tests tests/private-storage.test.mjs.
  • Principle (verbatim comment): "An allowlist, not a token-regex filter: ordinary prose, tool arguments and unknown JSON fields may themselves be private, even when they contain no key." Unknown text is never copied.
  • Algorithm for privateLogRecord(input, {service, stream, stage}):
    1. source = last 16 384 chars of input (non-strings → ""); try JSON.parse(source).
    2. If responseTimingRecord(parsed) is valid (RT-31) return it unchanged.
    3. record = {schemaVersion:1}; copy parsed.time only if it matches ^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$; service if ^[a-z0-9-]{1,64}$ (case-insensitive); stream if stdout|stderr; stage = stage ?? parsed.stage if in STAGES.
    4. event = parsed.event if in EVENTS; else failure if source matches /error|exception|failed|failure|traceback|could not|cannot|out of memory|timeout/i; else stage if a stage was kept; else activity.
    5. Model metadata only for parsed.event == "model-selected" with effective service desktop (argument, or parsed.service when parsed.schemaVersion === 1) and a valid diagnosticModelId(parsed.modelId) → event:"model-selected", service:"desktop", modelId.
    6. code = first token of /\b[A-Z][A-Z0-9_]{2,63}\b/g that is in ERROR_CODES; then overrides in this order: /CUDA.*out of memory|out of memory.*CUDA/i → CUDA_OUT_OF_MEMORY; /no kernel image|not compatible with the current PyTorch/i → CUDA_ARCH_UNSUPPORTED; /DLL load failed|VCRUNTIME|WinError 126/i → NATIVE_LIBRARY_LOAD_FAILED; /tls handshake eof/i → TLS_HANDSHAKE_EOF.
    7. exception = first of TypeError ReferenceError SyntaxError RangeError ImportError ModuleNotFoundError RuntimeError ValueError OSError MemoryError TimeoutError (word-bounded).
    8. httpStatus = 4xx/5xx captured by /\b(?:HTTP(?:\/\d(?:\.\d)?)?\s*|status(?:Code)?[\s"':=]+)([45]\d{2})\b/i.
    9. exitCode if parsed.exitCode is an integer in [−2147483648, 4294967295]; elapsedMs, received, total if safe non-negative integers.
  • Vocabularies (exact, privacy-log.mjs:10-74):
    • ERROR_CODES: ECONNREFUSED ECONNRESET ENOTFOUND EAI_AGAIN ETIMEDOUT ENOENT EACCES EPERM ENOSPC EIO EBUSY EPIPE EINVAL UND_ERR_CONNECT_TIMEOUT UND_ERR_HEADERS_TIMEOUT UND_ERR_BODY_TIMEOUT UND_ERR_SOCKET CERT_HAS_EXPIRED DEPTH_ZERO_SELF_SIGNED_CERT ERR_TLS_CERT_ALTNAME_INVALID UNABLE_TO_VERIFY_LEAF_SIGNATURE ERR_MODULE_NOT_FOUND MODULE_NOT_FOUND ERR_DLOPEN_FAILED CAPRI_VOICE_GPU_UNSUPPORTED CUDA_OUT_OF_MEMORY CUDA_ARCH_UNSUPPORTED NATIVE_LIBRARY_LOAD_FAILED TLS_HANDSHAKE_EOF
    • STAGES: checking preparing downloading installing verifying starting ready stopping stopped cancelled error interrupted complete voice-runtime voice-dependencies voice-models recognition request-router models runtime python node extracting
    • EVENTS: started exited spawn-failed stage progress failure activity
  • diagnosticModelId(v) (technical-model-id.mjs:3-18): string ≤200 chars matching ^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$; rejected if it starts with a drive (X:/), http(s):, file:, sk-/sk_, gh[pousr]_, github_pat_, hf_, AIza; contains //; has an empty, . or .. /-segment; looks like user@host.tld; or contains a segment like api-key, access_token, refresh-token, token, secret, password, passwd, bearer delimited by / : _ - or the ends.
  • privateLog(text): last 256 KiB, per non-blank line privateLogRecord(line); records with event:"activity" and no code/exception/stage are counted, not kept; at most 500 kept records; append {"schemaVersion":1,"event":"private-lines-omitted","count":N} if N>0; joined by \n.
  • Rust/Linux: privacy_log module reproducing the algorithm byte-for-byte (golden tests ported from private-storage.test.mjs). Recommended Linux addition to step 6: error while loading shared libraries|cannot open shared object file → NATIVE_LIBRARY_LOAD_FAILED. All Rust tracing output that reaches disk goes through a layer that emits only these structured records; free-form messages go to stderr only when attached to a terminal.

RT-30 Service lifecycle logs — P0

  • Source: host/processes.mjs:109-164.
  • Files logs/<service>.stdout.log, logs/<service>.stderr.log; truncated at each launch; mode 0600; each record = privateLogRecord(JSON.stringify(value), {service, stream}) + time (ISO ms). When a file exceeds 1 MiB it is reset to empty before the next append. Write errors are ignored ("Logging must not interrupt service shutdown.").
  • Example lines (synthetic):
    {"schemaVersion":1,"service":"ollama","stream":"stdout","event":"started","time":"2026-11-10T21:00:00.000Z"}
    {"schemaVersion":1,"service":"ollama","stream":"stderr","event":"exited","exitCode":1,"time":"2026-11-10T21:05:10.123Z"}
    
  • Rust/Linux: identical under STATE/logs/; the GUI process itself writes desktop.stdout.log records started/exited (exit recorded by the supervisor that launched it, or by capri stop).

RT-31 Response timing logs — P1

  • Source: response-timing.mjs:14-124, response-timing-schema.mjs:1-114, response-probe.mjs (provider tap), bin/response-timing-preload.mjs.
  • Record: {schemaVersion:1, event:"response-timing", traceId:<UUID 8-4-4-4-12 hex>, source:"desktop"|"gateway"|"provider"|"renderer", stage, requestId?:<UUID>, modelId?, time?:<ISO ms Z>, <counters>}. Stages (31): received chat_started model_start model_ready routing_start routing_ready intent_start intent_ready context_start context_ready gateway_dispatch gateway_received gateway_first_delta gateway_finished provider_request provider_headers provider_first_token provider_first_content provider_finished provider_failed gateway_headers gateway_first_token first_delta first_paint voice_text voice_queued voice_synthesis voice_audio completed failed cancelled. Counters (finite, 0…1e12, rounded to 3 decimals): contextShift truncate toolCount toolSchemaCharacters reasoningCharactersBeforeText threadCount batchSize gpuLayers predictTokens thinking linked availableRamBytes residentBytes residentGpuBytes residentContextTokens elapsedMs durationMs inputCharacters systemCharacters contextCharacters historyMessages messageCount payloadBytes outputCharacters contextTokens promptTokens outputTokens loadMs promptEvalMs evalMs totalMs rendererElapsedMs cold speechCharacters requestMs tokenMs decoderMs streaming status.
  • Writer: queue ≤128 lines (excess dropped), flush 25 ms after the first queued write, append mode 0600, rotate when size + batch > 512 KiB (rename to .1, removing an old .1 only if it is a regular file with one link), all errors swallowed ("disk I/O never gates a response"). Turn context: ≤128 tracked turns; first_paint accepted once per known turn with 0 ≤ rendererElapsedMs ≤ 600000.
  • Capri files: logs/response-desktop.jsonl (desktop/provider/renderer) and logs/response-provider.jsonl (gateway/provider, written inside OpenClaw via the preload, only when CAPRI_OLLAMA_PORT is valid).
  • Rust/Linux: one in-process writer, STATE/logs/response-timing.jsonl (+.1), same schema; the agent loop keeps emitting gateway_* stages so timelines stay comparable. Provider tap: parse Ollama NDJSON stream lines (≤1 MiB pending) for provider_first_token, provider_first_content (with reasoningCharactersBeforeText), provider_finished (load_duration, prompt_eval_duration, eval_duration, total_duration ns → ms; prompt_eval_count, eval_count) without retaining content.

RT-32 Model selection log — P1

  • Source: privacy-log.mjs:151-170, main.mjs:357-365.
  • At desktop start, if the active model ID (API model when API mode is enabled, else settings.model) passes diagnosticModelId, atomically replace logs/desktop-model.jsonl with one line {"schemaVersion":1,"service":"desktop","event":"model-selected","modelId":"capri-qwen3.5:4b","time":"…"}. Failures never block startup.
  • Rust/Linux: same file under STATE/logs/.

RT-33 Legacy log sanitizer — P2

  • Source: privacy-log.mjs:191-224.
  • For ≤256 entries of a log dir with extension .log|.jsonl|.txt, regular single-link files: replace content with privateLog(last 256 KiB) + "\n" atomically; returns {sanitized, skipped}.
  • Rust/Linux: not needed for runtime (logs are not migrated). Expose as capri maintenance sanitize-logs <dir> only if the migration keeps legacy logs (it does not, RT-48).

RT-34 Bug report ZIP — P1

  • Source: diagnostics/report.mjs:19-580, diagnostics/archive.mjs:7-72, main/companion-ipc.mjs:159-205, snapshot providers main.mjs:5605-5690; doc docs/diagnostic-reports.md.
  • Explicit user action only; nothing is uploaded.
  • Input (validateReport): string → {description}; allowed keys title(≤160) description(≤4000) steps(≤3000) expected(≤1500) actual(≤1500) category (voice recognition model startup interface installer other, default other) includeLogs (bool, default true); unknown key → Unknown report field; bad value → Invalid report <key> / Invalid report options; strings trimmed.
  • Save flow: validate first; one collection at a time (A diagnostic report is already being collected.); native save dialog title Save and review bug report, default name capri-diagnostics-<ISO timestamp with ':' and '.' replaced by '-'>.zip, filter Diagnostic ZIP archive (*.zip); cancel → false; write <dest>.<uuid>.tmp with O_EXCL, rename, reveal in file manager; return {saved:true, reportId, files, bytes}.
  • Secrets collected for redaction: values of env vars whose name matches /TOKEN|SECRET|PASSWORD|API_KEY/i and the contents of data/speech/companion-voice-token and data/openclaw/gateway-token (≤4096 bytes each); only values ≥8 chars are replaced.
  • ZIP entries: system.json, resources.json, voice.json, avatar.json, session.json, installation.json, problem.json, manifest.json, REPORT.md, logs/<label>-<n>-<name>.
    • system.json: platform arch osRelease cpu cpuThreads ramBytes availableRamBytes + hardware probe fields + osVersion runtimeArchitecture node electron chromium disk{availableBytes,totalBytes} installationPath{hasSpaces,hasNonAscii,length}.
    • resources.json: RT-37.
    • voice.json: config subset (engine enabled port precision decoderDevice mergeAdapter cudaGraph cpuThreads), profile subset (engine language), ≤40 file presence entries (names anonymized to voice-component-<i> except the Python path), adapterChecksum (matches profile | MISMATCH | not checked; only for adapters ≤32 MiB), Python probe (tools/diagnostics/voice-environment.py, 15 s, 512 KiB stdout, env without secret-like vars, last stdout line parsed as JSON, stderr tail 8000), voice health through diagnosticState.
    • avatar.json: runtime artwork state, expected manifest path, manifest subset (schemaVersion canvas defaultSprite), file presence (≤128 sprites; names ^[a-z0-9_-]+\.png$) — no images.
    • session.json: diagnosticState(snapshot) + processes for markers desktop capri ollama companion-voice ({owned:false} if projectRoot differs; else {pid, pidSeen (kill 0), savedCreationTime, ownership:"installation marker; PID existence does not verify creation time"}; unreadable → {marker:"missing or unreadable"}).
    • installation.json: identity subset (schemaVersion productId version) + installer journal subset (schemaVersion version status phase updatedAt failure completed steps) through diagnosticState.
    • manifest.json: {schemaVersion:1, id, createdAt, version, release, includedLogs, inventory:[{file,sourceBytes,capturedBytes,truncated}], warnings, exclusions:["chat-history files","long-term memory","personality","recordings","screenshots","model weights","credentials","environment dump"], limits:{bytesPerLog:262144,maxRuntimeLogs:24,maxArchiveUncompressedBytes:16777216}}.
    • Logs (if includeLogs): newest 24 of logs/, 4 installer UI logs, and for the 2 newest installer sessions whose request.json target equals this root, 3 files among events.jsonl, worker*.log, worker-guard.jsonl, ui-events.jsonl. Eligible names end in .log|.jsonl|.txt and do not match /history|transcript|memory|prompt|screenshot|recording|token|secret|verification|dataset|audition|chat|dialog/i. Each file: last 256 KiB through privateLog (so only allowlisted records enter the ZIP). Linked directories/files rejected (Linked diagnostic directory, Linked or invalid diagnostic source); warning <label>: included <max> newest files of <n>.
  • Findings (report.mjs:448-521, verbatim strings there): last computer task status in needs_user|incomplete|cancelled|stalled|limit; last reply failure phase/elapsed/error name; fallback artwork; missing avatar component; unreadable catalog; voice disabled; language → text-only speech; selected model offload cpu/partial; system RAM ≤10 % available; missing voice components; CUDA unavailable; Chatterbox Turbo module missing; adapter checksum mismatch; last voice startup/request failure; log patterns (CUDA OOM, architecture, DLL, ModuleNotFoundError).
  • REPORT.md template: report.mjs:569-573 (copy verbatim; sections # Capri diagnostic report, IDs/version/category/model ID, ## Problem, ## Steps to reproduce, ## Expected, ## Actual, ## Automatic findings (default No definitive cause identified. Inspect the captured state and logs.), ## System, ## Included files, ## Privacy and limits; empty fields print Not provided).
  • ZIP writer: ≤64 entries, names ^[a-zA-Z0-9_./-]+$, not absolute, no empty or .. segment, unique; total uncompressed ≤16 MiB (Diagnostics exceed the size limit); raw deflate (method 8), version 20, UTF-8 flag 0x800, local DOS time, CRC-32.
  • Rust/Linux: same files and rules. system.json gains osRelease from /etc/os-release PRETTY_NAME, kernel (uname), session (XDG_SESSION_TYPE, XDG_CURRENT_DESKTOP), xwayland (DISPLAY under Wayland), windowManager (i3 version via i3 IPC GET_VERSION; KWin version via D-Bus is optional), Ollama version; electron/chromium/node keys become capri (crate version) and rustc. installation.json = {package:{name:"capri", version, source:"pacman"|"dev"}, setupJournal: <subset of STATE/setup/state.json>}. Installer-session logs are replaced by STATE/setup/events.jsonl tail. Default save location: XDG portal FileChooser; without a portal (plain i3), $(xdg-user-dir DOWNLOAD) with the default file name.

RT-35 Diagnostic state filter and redactor — P1

  • Source: diagnostics/state.mjs:4-266, diagnostics/redact.mjs:4-75.
  • diagnosticState(value, key, depth): depth >12 → [DEPTH LIMIT]; receivedText boolean kept; model/modelId → diagnosticModelId or [PRIVATE TEXT OMITTED]; key matching PRIVATE_FIELD /(prompt|transcript|utterance|messages|history|personality|content|goal|query|parameters|arguments|clipboard|windowTitle|caption|fileName|filePath|executable|url|token|secret|password|headers|environment|recording|screenshot|image|audioData|text)/i → [PRIVATE DATA OMITTED] unless the value is a number and the key ends in Tokens|Bytes|Count|Ms; null/booleans kept; non-finite numbers → null; strings kept only if in STATES (state.mjs:6-115), ERRORS (Error TypeError … AbortError), CONTROL_VALUES for keys action|outcome|reason (state.mjs:133-212), code keys (code networkCode startupStage failureCode errorCode lastFailureCode) with values ^(?:ASR_|VOICE_|CAPRI_|COMPUTER_|UND_ERR_|ERR_|E[A-Z]{3,})[A-Z0-9_]{0,72}$, stage ∈ connect upstream response stream probe request, language keys (language interface conversation speech) matching ^[a-z]{2,3}(?:-[A-Z]{2})?$; otherwise a privateLogRecord object if it yields code|exception|httpStatus, else [PRIVATE TEXT OMITTED]; arrays/objects truncated to 150 items.
  • Redactor (redactor({root, home, secrets})): strip ANSI; replace secrets → [SECRET], install root → <INSTALL>, home → <USER> (raw, /-normalized, \\-escaped and encodeURI variants; longest first; case-insensitive); then: Authorization|Cookie|Set-Cookie [:=] … line → [PRIVATE HEADER]; key="…" for api_key access_token refresh_token client_secret password passwd token secret → "[SECRET]"; Bearer x → Bearer [SECRET]; unquoted key[:=]value → [SECRET]; URLs: userinfo → [SECRET]@, query/fragment → ?[REDACTED]; sk_|ghp_…|github_pat_|hf_ + ≥12 chars and sk- + ≥12 → [SECRET]; X:\Users\<name> and /home/<name>, /Users/<name> → <USER>; emails → [EMAIL]. value(): depth/150-item limits; keys authorization cookie set-cookie password passwd secret token api-key access-token refresh-token client-secret headers env environment messages prompt transcript content audio image personality utterance requestBody responseBody goal query parameters arguments clipboard windowTitle caption fileName filePath → [REDACTED]; keys error message reason stack stderr stdout warning with string values → kept only if a control value, else replaced by privateLogRecord(value).
  • Rust/Linux: port verbatim; the Linux home pattern also catches /root. Tests: diagnostic-report.test.mjs, private-storage.test.mjs.

RT-36 Developer diagnostics (log catalog and response timelines) — P2

  • Source: diagnostics/developer.mjs:9-196, diagnostics/response-timeline.mjs:15-109, IPC main.mjs:4853-4866; doc docs/developer-diagnostics.md.
  • Catalog roots: logs/ (group runtime), .runtime/updates (updates), installer logs and the 3 newest installer sessions (installer). Per dir ≤256 entries; file names ^[a-zA-Z0-9_.-]{1,140}$ ending .log|.jsonl|.txt (optionally .1) and not matching the private-name regex (plus sk-|ghp_|hf_); regular single-link files only; IDs = first 24 hex of SHA-256(absolute path); newest 80 plus every runtime timing file. Read: ID must be 24 hex and in the catalog; tail ≤64 KiB with open-handle inode/dev re-check; first partial line dropped when truncated; returned through privateLog. Snapshot cache 1 s with a shared in-flight read; timing files (≤512 KiB tail) re-parsed only when their (id, size, mtime) signature changes. Errors: Invalid log selection., This log is no longer available. Refresh the list., The logs folder is not available yet.
  • Timelines: group by traceId; dedupe by (traceId, requestId, source, stage, time, elapsedMs); origin = desktop received (else first record); terminal = last desktop completed|failed|cancelled (status else incomplete); durations use elapsedMs difference within one source, else wall-clock time difference, negative → null; phases dispatch (received→chat_started) model (model_start→model_ready) routing intent context gateway (gateway_dispatch→gateway_first_token) stream (first_delta→terminal) voice (first_delta→voice_audio); provider calls grouped by requestId with firstTokenMs firstContentMs wallMs loadMs promptEvalMs evalMs promptTokens outputTokens tokensPerSecond (outputTokens·1000/evalMs) failed; ≤40 newest turns, ≤200 events each; provider rows without a matching trace never get attached by time.
  • Rust/Linux: same logic over STATE/logs and STATE/setup; "Open logs folder" → org.freedesktop.FileManager1.ShowFolders or xdg-open STATE/logs.

RT-37 Resource probe — P2

  • Source: diagnostics/resources.mjs:4-60.
  • /api/ps counters only (≤32 models accepted, first 8 kept): {selected, totalBytes:size, gpuBytes:size_vram, offload:"cpu"|"gpu"|"partial"|"unknown", contextTokens (1…4 Mi)} + truncated; process working set sum (ramBytes, vramBytes from the process-load sampler) with the two verbatim basis strings. Only on explicit report creation.
  • Rust/Linux: same; working set = sum of VmRSS of the GUI + managed children (from /proc/<pid>/status).

RT-38 Setup diagnostics export (Save setup report.cmd) → capri diagnostics export — P1

  • Source: packages/installer/windows/diagnostic-export.cs:15-232, diagnostics.ps1, export-diagnostics.ps1.
  • Capri setup ZIP capri-setup-diagnostics-<yyyy-MM-ddTHH-mm-ss-fffZ>-<6 hex>.zip in Downloads (fallback Desktop; on error <%LOCALAPPDATA%>/Capri/Installer/reports): REPORT.md, setup.log (failure + log tails, 256 KiB each, 12 MiB total), setup.json (schemaVersion 2: system, installation release/package/identity/journal subsets, session/request/worker/heartbeat/pause subsets, log inventory, warnings). Unlike the app report, setup logs are raw text with best-effort redaction (secrets from env, auth headers, URL credentials, ?token=-style params, JSON keys incl. prompt messages history personality, HF_TOKEN=/*_API_KEY=, token patterns, path placeholders <SOURCE> <HOME> <SETUP> <INSTALL>). Works without Node.
  • Rust/Linux: one command for both cases: capri diagnostics export [--category C] [--title T] [--description D] [--no-logs] [--output FILE] builds the RT-34 ZIP headlessly (snapshot from the running GUI over the control socket if available, else session.json = {"desktop":"stopped"} + processes) and includes setup evidence through privateLog only (no raw text; stricter than Capri, by design).

E. First-run setup, components, repair, purge, packaging

RT-39 First-run setup wizard — P0

  • Source: packages/installer/windows/wizard-ui.ps1:1-1455 (options 56-72, recommendation 48-53, pages 546-819, install start 821-853, navigation 935-970), install-discovery.ps1:50-81, memory-budget.ps1, hardware/memory-budget.mjs:27-72, installer/src/storage-estimate.mjs:20-99, installer/src/policy.mjs:92-198 (validateRequest), catalogs config/installer-text.json (138 keys × 50 languages), installer-progress-text.json, installer-languages.json (50 {id,nativeName}), installer-glossary.json; doc docs/installation-wizard.md.
  • Capri page list (pages = Welcome, License, Location, Hardware, Components, Review, Installing, Finish) and defaults:
    # Page Behavior
    0 Welcome Installer language combo (`
    1 License Full GPL-3.0 text; checkbox I accept the GPL-3.0 license for Capri's own code gates Next (Please accept the license to continue.).
    2 Location Target path (default %ProgramFiles%\Capri or the newest existing install ≤ setup version); Browse proposes <parent>\Capri; list of detected installs `v
    3 Hardware & model Radio Use local LLMs / Use an API without installing local LLMs (BETA) / Choose a local model from Hugging Face after installation; conversation language; profile combo (disabled for API/HF/repair) with up to 2 starred language recommendations (model-language-benchmark.json, filtered by VRAM ≥ recommended−0.125 when recommended>4 and by RAM); storage estimate; hardware label; Next with local catalog requires enough RAM (This profile requires more RAM.).
    4 Components UI language, conversation language (both locked on repair), Install accurate microphone recognition (default on), CPU request classifier · included (cannot be deselected), Download the selected language model now (only local catalog; default on), voice mode off / bundled (Chatterbox + included pack; needs speech-capable language and supported GPU) / custom (pick voice-profile.json) / qwen (Qwen3-TTS CPU, BETA, language must be supported), shortcuts (desktop, start menu; default on).
    5 Review Summary (target, model or API/HF text, Models: Off note, languages, recognition, classifier, voice, storage estimate, data path) + consent checkbox Download and install the listed dependencies and models; Install enabled only when consent is checked and the estimate fits the free disk space.
    6 Installing Stage label, one overall bar, progress text (ETA), warning Keep this window open and do not shut down the PC during installation., log box, Pause/Resume, Cancel (confirmation), Save diagnostics / Open logs.
    7 Finish Success: The selected models are ready. You can launch Capri now. or deferred Application files are installed. Run this wizard again with model downloads selected before your first conversation. (API/HF variants), data/logs paths, Launch Capri (default on), Preload models on first launch (local catalog only, default on → data/desktop/first-start.json). Failure page: error text, Retry, Back to Review.
  • Recommendation used by the wizard: start at minimal; for balanced, desktop, quality in order, adopt the candidate if RAM passes the profile rule and (candidate is balanced or VRAM ≥ recommended−0.125).
  • Memory budget panel (pages 3–5): RAM and VRAM ranges from config/memory-estimates.json (base, per-model vram/cpuRam/hostRam/gpuSystemRamGiB, recognitionEnglish|Multilingual, router, voiceEnglish|Multilingual, voiceQwenCpu): GPU mode adds hostRam+vram for the downloaded model, CPU mode adds cpuRam; partial offload (VRAM need > free/total VRAM) adds the model's cpuRam upper bound to RAM; each row {estimate:[lo,hi], total, available, remaining:[avail−hi, avail−lo], exceedsAvailable}; HF model not yet chosen shows ?.
  • Request schema (validated twice: UI and engine): {schemaVersion:1, target, profile, inferenceMode:"local"|"api", modelSource:"catalog"|"huggingface", interfaceLanguage, conversationLanguage, recognition:bool, router:true, downloadModels:bool, desktopShortcut:bool, startMenuShortcut:bool, voiceMode:"off"|"bundled"|"custom"|"qwen", voicePack:"<abs dir>"|"", bundledVoicePack, acceptLicense:true, acceptDownloads:true}. Rules: both acceptances must be literally true (License acceptance and download consent are required); API or HF forces profile minimal and no model download; voice pack required for bundled/custom and forbidden with off; a pack needs a speech-ready conversation language; Chatterbox needs a supported GPU (This voice needs an NVIDIA GPU or a supported AMD ROCm GPU on Windows 11 (experimental).); disk check Not enough free space on <root>. Required: <x.xx> GiB. Available: <y.yy> GiB. (code CAPRI_DISK_SPACE).
  • Rust/Linux: the same wizard as the GUI's first screen when CONFIG/core.local.json is missing (and on demand from Settings → Repair). Pages: Welcome (interface language) → License (keep the explicit acceptance; Q8) → Import (replaces Location: shows DATA path read-only and offers RT-48 when a legacy Capri folder is detected at ~/Capri or a user-chosen folder) → Model → Components (no shortcut checkboxes; the package installs the .desktop file; no autostart option because Capri never adds one) → Review (consent + free space of the filesystem holding DATA) → Installing → Finish (Open Capri switches the same process to the companion; Preload models on first launch writes DATA/desktop/first-start.json). Voice GPU rule on Linux: NVIDIA CUDA or ROCm-supported AMD (voice spec defines the list). All strings come from the existing catalogs (installer-text.json keys); Windows-only keys (programFilesPermission, windowsRequiredError, bootstrap*, shortcuts) are unused.

RT-40 Component install engine and journal — P1

  • Source: packages/installer/src/engine.mjs:50-795, commands.mjs:6-107, pause.mjs, install-progress.ps1:1-59, speech-components.mjs:74-329 (in-app component repair), bin/install.mjs (NDJSON events + cancel file 200 ms poll; exit 2 when cancelled).
  • Capri stages: node source dependencies ollama configuration [python] [recognition] [router] [voice-runtime voice-pack] models verify [shortcuts] finalize. Before any write: refuse if markers desktop|capri|ollama|companion-voice point to a live PID (CAPRI_INSTALL_RUNNING: Capri is still running from this installation folder. In Capri, choose Quit and unload models. Keep this Setup window open, then click Retry here. Your settings, history and downloaded models will be preserved.). Always runs core.mjs stop (120 s) in finally and releases the lock.
  • Journal .runtime/installer/state.json: {schemaVersion:1, fingerprint: sha256(JSON(plan)+package-lock bytes), status:"installing"|"complete"|"failed"|"cancelled", steps:{<id>:{status:"running"|"complete"|"failed"|"cancelled", message?(≤2000)}}, plan, updatedAt}, saved atomically on every transition. A journal entry alone is never readiness evidence; repeat installs revalidate outputs (receipts {sha256, version, executableSha256, backendHashes?}).
  • Events (NDJSON, each with timestamp): stage-plan{stages}, stage{step}, stage-complete{step}, activity{step,action,component?} (checkTarget checkRuntime connectRuntime downloadRuntime verifyRuntime extractRuntime fetchRuntime checkSource copySource installDependencies), log{step,message≤1000}, percent{step,percent,message?}, fraction{step,fraction}, download{step,received,total,bytesPerSecond,secondsRemaining,stageFraction?}, paused, resumed, error{code,message≤2500}, failed|cancelled{step,message}, complete{target,modelsReady,inferenceMode,modelSource,modelSetupRequired,voiceInstalled}.
  • Commands (runCommand): stdout/stderr decoded per stream, lines split on CR/LF, VT codes stripped, ≤1000 chars; failure Component exited <code>. <last 2000 chars>; timeout counts active time only (pause file polled every 250 ms): 8 h for download steps (dependencies recognition router voice-runtime voice-pack models), 1 h otherwise (Installation component timed out); cancel/timeout → SIGTERM (Windows taskkill /T /F), then The owned installation command did not stop in time after 10 s. Pause = file <session>/pause; cancel = file <session>/cancel.
  • Configuration step (first install only): allocate ports (RT-17), capri setup --profile=<p> --yes --replace, voice port; data/desktop/languages.json if missing = {schemaVersion:1, settings:<validated languages>}; config/request-router.json.enabled = true.
  • Models step: capri models [--embedding-only] (embedding always, text model only when downloadModels). Verify step: avatar assets, capri doctor, model inventory contains required models (A required model is not ready: <m>). Finalize: voice selections (data/speech/voice-selections.json {schemaVersion:1, languages:{<lang>:"qwen3-tts-0.6b-base"}}, Chatterbox = key removed), languages.settings.speech = "follow", API mode → data/desktop/inference-api.json.setupRequired = true (never collects a key), local mode clears enabled/setupRequired, core.local.json.modelSetupRequired = (modelSource == "huggingface").
  • Progress bar: bootstrap 0–10 %, remaining stages split 10–100 % with boundaries rounded to multiples of 5; never above 99 before completion; ETA withheld when paused, <10 %, no advance for >30 s or <10 s elapsed; ETA = elapsed·(100−v)/v raised to the transfer ETA when that sample is ≤15 s old, rounded up to 5 s, hidden above 24 h.
  • Rust/Linux: setup::Engine with Linux stages configuration [python] [recognition] [router] [voice-runtime voice-pack] models verify finalize (no Node/npm/Electron/Ollama download/shortcuts). Same journal schema at STATE/setup/state.json (fingerprint = SHA-256 of the plan JSON + the binary's version string), events kept in memory and appended to STATE/setup/events.jsonl through privateLogRecord (never raw text), same command/timeout/pause/cancel rules (cancel = SIGTERM to the child's process group). Speech/router stages call the owning specs' installers; external Python setups (uv) are allowed only where those specs say Rust is not reasonable. capri components install <component> reuses the engine for in-app repairs (speech-components.mjs semantics: only missing parts, fixed component IDs, disk preflight, no source/language mutation).

RT-41 Verified resumable downloads — P1

  • Source: installer/src/download.mjs:24-173, resumable-download.mjs:18-229, npm-tarball.mjs (npm-only, dropped).
  • Pinned spec {url, mirrors?(≤3), sha256 (64 hex), bytes (>0)}; every URL (and every redirect hop, ≤6) must be https, no userinfo, port 443, host in the allowlist (Capri: nodejs.org github.com release-assets.githubusercontent.com objects.githubusercontent.com npmmirror.com cdn.npmmirror.com); duplicate sources rejected. Final file <folder>/<sha256>.zip; a complete hash-verified final file is reused without network. Partials: primary <final>.part, mirrors <final>.source-<sha256(url)[0..24]>.part; a complete verified partial is promoted without network; oversize partials deleted.
  • Request: accept-encoding: identity, credentials: omit, manual redirects; header deadline 30 s (validated 1–30 s), whole transfer 2 h. Range: bytes=<offset>-; a 206 must carry exactly bytes <offset>-<bytes−1>/<bytes>; a 200 restarts at 0; content-length must equal remaining bytes; overflow → Dependency exceeds pinned size; SHA-256 checked before rename (Dependency checksum verification failed, partial deleted).
  • Retry: ≤6 attempts total across sources; each failure rotates to the next source; after a full round wait min(1000·2^attempts, 15000) ms. Retryable: HTTP 408/429/500/502/503/504, network codes ECONNRESET ECONNREFUSED ETIMEDOUT EAI_AGAIN ENOTFOUND ENETUNREACH EHOSTUNREACH ERR_STREAM_PREMATURE_CLOSE UND_ERR_SOCKET UND_ERR_CONNECT_TIMEOUT UND_ERR_HEADERS_TIMEOUT UND_ERR_BODY_TIMEOUT, timeouts. Any certificate/TLS code in the cause chain → never retried. Cancellation never rotates. Pause keeps the same source and resumes its own range. Progress events every ≥250 ms.
  • Rust/Linux: download::fetch_verified(spec, folder, opts) used by every spec that downloads pinned artifacts (speech models, router model). Host allowlist is per catalog (e.g. Hugging Face hosts for speech catalogs), defined by the owning spec, enforced here.

RT-42 Installation lock — P1

  • Source: installer/src/lock.mjs:6-41 (+ Windows named mutex Local\CapriInstaller-<sha256(lower target)> in worker.ps1:129-132).
  • install.lock.json {pid, id} created O_EXCL 0600; existing lock with invalid pid → An interrupted installer lock could not be validated; dead pid (ESRCH) → removed, retried once; live → Another installation process is working on this folder; release deletes the file only if its id matches.
  • Rust/Linux: STATE/setup/setup.lock = flock(LOCK_EX|LOCK_NB) (kernel releases it on crash) plus the same JSON body for diagnostics. Held by setup, components install, migrate and purge; each refuses with Another installation process is working on this folder when busy.

RT-43 Repair — P1

  • Source: wizard repair mode (Load-CapriRepairSettings, wizard-ui.ps1:459-513), docs/installation.md (repair section).
  • Re-running setup on an existing installation keeps the hardware profile and languages (combos locked), never silently deselects components, re-verifies receipts, re-downloads only missing/invalid parts, and never touches history, memory or models. A completed repair clears an interrupted-update marker.
  • Rust/Linux: Settings → Maintenance → Repair components and capri setup --repair run RT-40 with the saved plan; program files are repaired by reinstalling the package (pacman -S capri).

RT-44 Purge (uninstall data groups) — P1

  • Source: packages/installer/windows/uninstall.ps1:56-418, uninstall-window.cs, config/uninstaller-text.json (24 keys × 50 languages).
  • Groups (selection dialog with measured sizes; unchecked groups are kept):
    1. Application (Capri, dependencies and shortcuts): owned source files (from .runtime/installer/source-files.json; modified files backed up to data/uninstall-backup/ unless personal data is also removed), node_modules, .runtime, shortcuts, Capri.exe, registry entry, teleport shell key.
    2. Models (Downloaded models and voice packs): data/models, data/huggingface, the shipped voice data/voices/capri/en/exports/capri-en-v1, every directory under data/speech/ and loose files there, except personal items.
    3. Personal data (Memory, history, settings and personal voices): data/desktop, data/desktop-profile, data/openclaw, data/workspace, data/applications, data/filesystem, data/perception, data/maintenance, data/config-backups, data/persona-backups, data/secrets, data/run, data/sounds, data/uninstall-backup, data/speech/training-jobs, data/brain, data/tools, data/workflows, data/user-tool-definitions.json, logs, config/*.local.json, data/speech/{voice-training-status.json,voice-selections.json,companion-voice-token}, every other data/voices/capri/en/* (imports, datasets, user exports).
    4. All three → also the whole data/, identity, uninstaller, recovery bundle and shared setup files (only if no other installation/active setup uses them).
  • Safety: preflight the complete plan before deleting anything; refuse if an install lock is live (Finish or cancel the installation before uninstalling.); stop Capri first (node core.mjs stop; failure → Could not stop Capri. No files were removed.); never traverse links: junction/symlink children are unlinked as leaves, other reparse points abort (Uninstall will not traverse filesystem links. Linked content was not removed.); every target must stay under the root (Removal escaped the managed installation.); sizes measured as allocated bytes, hardlinks counted once; empty parent folders removed afterwards.
  • Rust/Linux: capri purge [--models] [--personal] [--all] [--dry-run] [--yes] (and the same three checkboxes in Settings → Maintenance). Group mapping: models = DATA/models, DATA/huggingface, DATA/speech/* except personal items, DATA/voices/capri/en/exports/capri-en-v1, DATA/runtimes; personal = every other DATA entry, CONFIG, STATE/logs, STATE/migration; --all = all roots (CONFIG DATA STATE CACHE RUN). Program files belong to pacman (pacman -Rns capri removes them; pacman never removes $HOME data, so the uninstall dialog semantics live in capri purge). --dry-run prints {groups, trees, files, bytes} JSON (Capri -PlanOnly/-MeasureOnly). Same preflight, lock, stop-first, no-link-traversal and boundary rules; allocated bytes = st_blocks·512, inode (dev,ino) counted once.

RT-45 Packaging (PKGBUILD, desktop entry) — P0

  • Replaces: Setup.exe bootstrap (launcher.cs), register.ps1 (Capri.exe/uninstall.exe compilation, shortcuts Capri - <id8>.lnk, HKCU Uninstall key), payload manifests (SOURCE_MANIFEST.json, BUILD_MANIFEST.json), tools/release/*.
  • PKGBUILD essentials: pkgname=capri, arch=(x86_64), license=(GPL-3.0-only); depends=(ollama dbus libx11 libxcb libxtst libxkbcommon wayland alsa-lib at-spi2-core fontconfig hicolor-icon-theme) (ollama is satisfied by ollama-cuda/ollama-rocm/ollama-vulkan too; minimum 0.40.10 enforced at runtime because Arch rolls forward); optdepends=('python: external speech runtimes' 'uv: speech environment setup' 'nvidia-utils: GPU detection (nvidia-smi)' 'xdg-desktop-portal: save dialogs and URL opening' 'xdg-user-dirs: default report folder') (+ whatever the desktop-actions/voice specs require); build() = cargo build --release --locked (offline after cargo fetch in prepare()); check() = cargo test --release --locked; package() installs /usr/bin/capri, /usr/share/capri/** (defaults/catalogs/assets/templates), /usr/share/applications/capri.desktop, /usr/share/icons/hicolor/<size>/apps/capri.png (from assets/default/icon-source.png), /usr/share/licenses/capri/{LICENSE,THIRD_PARTY_NOTICES.md}. No install scriptlet downloads anything; no systemd unit, no autostart, no sudo at runtime.
  • Desktop entry: Name=Capri, Comment=AI desktop companion, Exec=capri, Icon=capri, Terminal=false, Categories=Utility;, StartupWMClass=capri, SingleMainWindow=true. The GUI sets X11 WM_CLASS = capri/Capri (and Wayland app_id capri for native surfaces) so KDE matches the entry and i3 users can write for_window [class="Capri"] rules.
  • Release hygiene to keep (from tools/release/source-export.mjs): the source tarball must not contain data/ logs/ .runtime/ node_modules/ *.local.json .env*, nor strings matching GitHub/HF/OpenRouter/OpenAI/AWS/Google key patterns or GitHub email_token links (source-release.test.mjs) — port as an xtask release-check.

F. Updates

RT-46 Passive new-version notice — P2

  • Source: apps/desktop/update-service.mjs:30-195, packages/updater/src/{github,releases}.mjs, renderer/update-notification.mjs:1-109, IPC main.mjs:5266-5330; tests startup-update-check.test.mjs, update-notification.test.mjs, updater-public-access.test.mjs.
  • Capri: preferences data/desktop/updates.json = {"schemaVersion":1,"settings":{"experimental":false}} (file ≤16 KiB; settings must be exactly {experimental:bool} else defaults + warning Saved settings could not be restored. Defaults are in use.). On first ready-to-show, one startup check (15 s deadline; superseded by any manual action, settings change, close or "remind later"): optional credential (GH_TOKEN/GITHUB_TOKEN without CR/LF, gh auth token --hostname github.com 5 s, or saved encrypted token; unreadable → anonymous), list releases (GET https://api.github.com/repos/CapriChooms/CapriCore/releases?per_page=100&page=N, ≤5 pages, 20 s each, ≤8 MiB each, must be an array), select the highest non-draft release with version > config/release.json tag, stable channel excluding GitHub prereleases and prerelease tags, having a verified asset of the install kind (Capri-<v>-source.zip managed / CapriSetup-<v>.exe otherwise; state:"uploaded", id>0, 0<size≤512 MiB, digest:"sha256:<64 hex>"). Found → phase:"available", release:{tag,experimental,bytes}, notification:{tag}; any failure → no state change, no error shown. Version rules: ^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$, ≤100 chars, numeric prerelease ids ≤15 digits without leading zero; SemVer precedence.
  • Notice UI: region label Updates, headline A new update is available: {version} (tag ≤80 chars, re-validated), buttons Update (busy text Downloading update...) and Remind me later (dismisses that tag for this run only); error The update could not be completed.
  • Rust/Linux: keep the same check, channel preference file and notice, but never download or install: Update opens https://github.com/<repo>/releases/tag/<tag> through the OpenURI portal (fallback xdg-open) and shows Update Capri with your package manager (pacman/AUR).. The repository is a build-time constant CAPRI_RELEASE_REPOSITORY; when unset (default until the Rust port publishes releases) the feature is compiled out (Q3). GitHub fetch rules kept: only api.github.com/repos/<repo>/releases, https, no credentials in URLs, manual redirects, user-agent: Capri-Updater, x-github-api-version: 2022-11-28, anonymous retry once on 401/403/404 when not rate-limited, token sent only to the API host.

RT-47 In-app download/stage/apply — not ported (P2, documented non-goal)

  • Source: update-service.mjs:264-490, packages/updater/src/{download,stage,transaction,payload-policy,npm-policy,launcher}.mjs, bin/apply.mjs, windows/update.ps1, update-host.cs.
  • Capri behavior for reference: resumable SHA-256-verified asset download, staged extraction (≤512 MiB, manifest of ≤10 000 files ≤20 MiB each), path policy, backup journal .runtime/updates/backups/<uuid>/journal.json + active.json marker, npm/Electron/Python dependency sync, rollback on failure, windowed host handshake (ready/proceed/cancel files, parent exit wait 900×200 ms), Capri.exe relaunch. The desktop refuses to start while active.json exists.
  • Rust/Linux: pacman owns program files; nothing of this is implemented. The only surviving invariant is "never run half-updated code", which pacman guarantees.

G. Migration

RT-48 Import an existing Capri folder — P1

  • Goal: a Capri 1.0.x user (Windows copy or this Linux checkout at ~/Capri) keeps history, memory, personality, settings, grants, voices, speech models and the Ollama model store.
  • Command: capri migrate --from <capri-root> [--dry-run] [--models copy|move|skip] [--include-backups] [--replace], capri migrate --resume, capri migrate --rollback; also offered by the setup Import page.
  • Preconditions: source has package.json with "name":"capri" or .capri-install.json with productId:"capri.desktop", and a data/ directory; no symlink on any source path used; no live Capri process for that source (Linux source: markers data/run/{desktop,capri,ollama,companion-voice}.json whose pid+starttime match → Stop the old Capri first (stop.cmd / npm stop).; Windows copies: markers are ignored); destination roots empty of user content, or --replace (existing DATA/CONFIG moved to DATA/../capri-pre-migration-<UTC stamp>/ first); setup lock (RT-42) held throughout; free space ≥ copied bytes + 1 GiB (not counted for --models move on the same filesystem).
  • Plan → --dry-run prints {items:[{source,target,action,bytes}], totalBytes, freeBytes, warnings}; execution writes STATE/migration/<uuid>.json journal {schemaVersion:1, id, source, startedAt, phase:"copying"|"post"|"complete"|"rolled-back", items:[{target, status:"pending"|"done"|"skipped", sha256?}]} so an interrupted run can resume or be rolled back (rollback deletes only targets it created). The source is never modified. Files are copied to <target>.<pid>.<rand>.tmp then renamed; SQLite databases are copied with the SQLite online-backup API (consistent snapshot including WAL), never by copying -wal/-shm files.
  • Item table (actions: copy, convert, drop, regen):
    Legacy path Action Target / notes
    config/core.local.json convert CONFIG/core.local.json; keep known keys (§4), drop gatewayPort; keep ollamaPort unless occupied (then reallocate)
    config/companion-voice.local.json, voice-training.local.json copy CONFIG/ (paths stay data/…, resolved by Paths::legacy)
    config/{companion-voice,companion-asr,voice-training,request-router}.json copy if different from the shipped default CONFIG/
    data/workspace/** (MEMORY.md, USER.md, PERSONALITY.md, memory/YYYY-MM-DD.md, .capri/communication.json) copy DATA/workspace/
    data/desktop/*.json settings and grants (see §3.3) copy DATA/desktop/; file-permissions.json scopes whose root equals the old Capri root are rewritten to the new installation scope (Q7)
    data/desktop/transcript.json copy if plain JSON sealed files (magic CAPRI-PRIVATE\0\1) are skipped with a warning (legacy encrypted history needs the old OS key)
    data/desktop/private-memory.enc.json, private-data-key.json copy as-is + warning readable only if the memory spec implements the legacy key path (Q10)
    data/desktop/*.sqlite (brain, desktop-operations, fixed-applications, time), data/filesystem/operations.sqlite, data/perception/commits.sqlite copy (backup API) same relative paths; operation journals keep idempotency/undo
    data/filesystem/recovery/**, data/desktop/{file-recovery,conversation-attachments,wake-audio}/** copy same relative paths
    data/desktop/{profile,crashes}/ drop Chromium profile/crash dumps
    data/openclaw/** convert (P2) / drop openclaw-agent.sqlite → import main-session transcript (§3.4) into the agent spec's store; gateway-token, openclaw.json*, cache/, media/, tmp/, plugin-skills/, state/ dropped
    data/secrets/*.json convert or drop credentials are Electron safeStorage ciphertext (base64); on a Linux source try the Chromium OSCrypt v11 scheme with the key from Secret Service/KWallet, else mark re-enter credential (Q2). desktop-actions.json dropped (regenerated)
    data/models/** (Ollama blobs/, manifests/, manifests-v2/, metadata/, request-router/, music-detector/) copy / move / skip DATA/models/ (Ollama layout is version-compatible); move = rename on the same filesystem, else copy+verify+delete only after success
    data/huggingface/**, data/speech/** (models, hf-cache, torch-cache, bundled-voice, candidates) copy/move with --models DATA/speech/…; companion-voice-token dropped (regenerated)
    data/speech/{voice-selections.json,voice-training-status.json,training-jobs/} copy personal
    data/voices/** copy personal + shipped voice
    data/{applications,brain,tools,workflows,screenshots,sounds,network}/**, data/user-tool-definitions.json copy same relative paths
    data/model-inventory.json regen from /api/tags after Ollama starts
    data/run/**, logs/**, .runtime/** (except below) drop runtime state, privacy (logs are not imported)
    .runtime/desktop-actions/portal-restore-token copy DATA/desktop-actions/portal-restore-token (KDE RemoteDesktop grant; may be rejected by the portal for a different app id → new consent)
    data/{config-backups,persona-backups,maintenance,uninstall-backup,vtuber}/** copy only with --include-backups DATA/legacy-backups/
  • Post steps: start managed Ollama, regenerate inventory, ensure aliases (RT-23), ask the memory spec to rebuild its index from the Markdown files (OpenClaw's embedding index is not imported), validate every imported settings file with its owner's validator (invalid → keep file, report warning, use defaults), write STATE/migration/<id>-report.json with counts/bytes only (never content), mark journal complete.

H. Miscellaneous

  • Source: apps/desktop/community-links.mjs:7-48, config/community.json, config/hall-of-fame.json, tools/community/update-hall-of-fame.mjs.
  • community.json keys boosty tiktok discord github website issues; each value must be an https URL without userinfo on the same origin as the built-in default, else the whole set falls back to defaults; an expired Discord invite path and the old CapriChooms/Capri repository paths are replaced by defaults. Renderer requests identifiers, never URLs.
  • hall-of-fame.json: {schemaVersion, team:[{name,role}], majorSupporters:[…], communityHelpers:[…], supporters:[…], epithets:{<login>:<text>}} — a static public snapshot shipped in SHARE/config/.
  • Rust/Linux: same validation; links opened through the OpenURI portal/xdg-open.

RT-50 Isolated instances and verification mode — P1

  • Source: apps/desktop/main.mjs:300-320 (--verification requires CAPRI_DESKTOP_VERIFICATION_DIR under .runtime/, separate Gateway port CAPRI_DESKTOP_VERIFICATION_PORT (18790), log prefix desktop-verification; disables lifeline files, GitHub auth, update install; CAPRI_DESKTOP_VERIFICATION_SKIP_START, _UPDATE_CHECK, _VOICE switches), tools/verify/verify.mjs (state under .runtime/verification/<stamp>, port 18790, prefix verification).
  • Rust/Linux: CAPRI_HOME=<tmpdir> gives a fully separate instance (own instance id, lock, socket, markers, ports allocated at its own first-run). Integration tests additionally set CAPRI_OFFLINE=1 (no update check, no registry probe, no downloads) and may point CAPRI_OLLAMA_PATH at a fake server binary.