Navigation
ELOWEN · Documentation

Last updated: October 27, 2026

Browse documentation · Isolated fixtures and CLI evidence
Developer reference

Isolated fixtures and CLI evidence

Released-client upgrade artifact preflight

scripts/tests/d5-client-upgrade-e2e/prepare.mjs prepares local artifact evidence for the released Linux/x64 0.30.6 client and an isolated 0.30.7 candidate. It never builds, extracts, installs, starts a daemon/client, accesses a publisher, or signs anything.

Its required inputs are a clean frozen source checkout and full commit, a separately authorized copied native build below the temporary directory (not a worktree), the candidate client archive and publisher-signed descriptor, the original released archive, and a new output file. Run node scripts/tests/d5-client-upgrade-e2e/prepare.mjs with --source, --head, --candidate, --archive, --descriptor, --old-archive and --output. There is no trust override or signing-key input.

Preflight uses the copied candidate's native verifyClientRelease and verifyFileBytes without a key override. A new test signing key therefore fails the same release verification required by the untouched old updater. Daemon test licence injection does not change client-release trust. The old archive has a fixed byte pin from local release-store inspection; its publisher descriptor signature is unavailable and is explicitly not claimed. Neither artifact is rebuilt or patched by preflight. The source commit is rechecked before and after verification and the complete compiled-tree digest must remain unchanged. The receipt records status: prepared and runtimeAcceptance: not-run; it does not establish that the selected build was produced from that source or that any runtime scenario passed.

The runtime scenario in run.mjs is implemented but is not runtime acceptance until it has actually run against an explicitly frozen and authorized candidate. It requires: the genuine old client bootstraps its own installed prefix and pairs through the native device-code owner; it is offline during the candidate cut; the unchanged process receives HTTP 409 and still commits the signed 0.30.7 package; a documented one-time restart launches the new client from that same prefix; the new strict ready/policy contract, a real command and a fresh 0.30.7 pairing all succeed. The intended owners are native build-client.mjs, daemonHarness.mjs ephemeral PostgreSQL, the test-only licence/daemon entry, and production pairing/admission, updater and executor code. No replacement installer, handshake or decoder is used. The daemon may run only from the copied built candidate inside the approved bwrap boundary with production roots and privileged sockets hidden, never from a worktree. Version 0.30.7 is the authorized synthetic test-candidate identity, staged only in a new scratch copy; receipts label it synthetic-test-candidate, not a published release. Source package/lock files remain untouched. A trusted signature for the exact new client bytes remains mandatory for the released-updater proof; it is independent of fixture metadata. No release preparation, publishing or signing happens here.

After explicit freeze and actual-run authorization, use the same preparation inputs plus --old-core-archive for the pinned original 0.30.6 core archive:

heavy-gate node scripts/tests/d5-client-upgrade-e2e/run.mjs --source <frozen-checkout> --head <full-commit> --candidate <copied-built-tree> --archive <0.30.7-linux-x64.tgz> --descriptor <publisher-signed.json> --old-archive <released-0.30.6-linux-x64.tgz> --old-core-archive <released-core-0.30.6.tgz> --output <new-evidence.json>

The copied built tree must include its native scripts, compiled database testing package and available existing dependencies. The runner copies it again, binds bare workspace imports to that copy's own database/shared modules, and asserts those module identities before boot. It never installs dependencies. Release archives are inspected and extracted as data by a separate python3 -I script into new empty directories with the standard tar data filter. Original byte pins are rechecked; client bundles and trust are never patched.

The runner launches a new network/PID namespace and hides production instance, privileged socket, install and nginx state. Only owned temporary state and the new private raw-log directory are writable. Both daemons run from copied release/build trees, on one loopback port over the same ephemeral PostgreSQL cluster. The full cutover passes the released core's shipped migration directory to startHarnessPostgres(migrationsDirectory): the first daemon must receive its own schema epoch, not a database already migrated by the candidate. The candidate then performs its ordinary forward migrations at boot; no ledger is rewritten. Omitting the directory retains the selected build's native default for fresh-only and other same-version harnesses. Native device-code pairing and first-run bootstrap install the real extracted client. A transparent gate cuts its network during the 0.30.6-to-candidate daemon handoff; its standard HTTP/WebSocket parsers only observe unchanged native responses. Policy controls are validated by the candidate's shared strict schema. HTTP 409 is produced by native admission, never by the gate. The updater's original PID must remain alive until its native journal says committed, with the installed version 0.30.7 and the executor still disconnected.

The one-time rollout restart stops only that owned client, then launches the same prefix's stable bin/elowen connect. Admission observations are correlated by the native request's target identity. Strict ready must match that target's strict policy-bearing ticket, actual policy cache, and the native client's complete Connected to Elowen. line, emitted only after its admission promise resolves. Cache adoption is checked again after an authenticated configuration change emits retry-policy for the same target. Command execution uses the real Terminal API/socket through Sandbox and cliConnections.control.openShell; its exit, output and client-owned effect file must agree. A separate home/prefix then pairs, bootstraps, connects and executes from the actual 0.30.7 archive. No synthetic executor or success-shaped handshake is used. The old updater's real cadence is unchanged; a failed check can require five minutes, so committed-package observation has an eight-minute deadline.

The evidence file is exclusive-created and raw logs remain beside it in <output>.logs (private directory; pairing-code stdout is discarded). It claims runtime success only after every ordered milestone, clean owned-process/PG teardown and unchanged final artifact/source identities. Missing signatures fail before any extraction or process startup; skipped, failed and cleanup-failed runs cannot report acceptance. Neither signing nor candidate fixture version staging is performed here.

Focused tests use native source release parsers/verifiers and pure-helper rejection inputs only, without a daemon, database or client process:

node --import ./scripts/registerTsResolve.mjs --experimental-transform-types --disable-warning=ExperimentalWarning --test scripts/tests/d5-client-upgrade-e2e/*.test.mjs

Fresh pairing without a release-feed descriptor

scripts/tests/d5-client-upgrade-e2e/pairing.mjs is a separate, explicitly fresh-only actual phase. After joint freeze and actual-run authorization:

heavy-gate node scripts/tests/d5-client-upgrade-e2e/pairing.mjs --source <frozen-checkout> --head <full-commit> --candidate <copied-built-tree> --archive <locally-built-0.30.7-linux-x64.tgz> --output <new-fresh-evidence.json>

It needs no released archive or client-release descriptor. The local candidate archive is byte-pinned for reproducibility, not authenticated as a release. The receipt names the synthetic identity and descriptorSignature: not-supplied-or-authenticated. The real extracted CLI performs its own native device-code login, approval, credential/policy persistence and first-run standalone bootstrap. No credentials, prefix metadata, installer, admission reply or executor are fabricated. This proves native pairing/install-from-local-package behavior, not customer installer authentication or the old client's upgrade.

The separate phase uses the same isolation.mjs boundary and copied-runtime bindings as the full runner. Both consume nativeClients.mjs, the sole test-fixture owner for native pairing/bootstrap, strict-ready acknowledgement and the real Terminal-to-Sandbox command. Fresh pairing additionally checks the native enrollment policy cache before connecting, then observes authenticated strict admission and a real command's exit/output/effect file. No release publisher is started or descriptor supplied; independent background updater feed checks can fail natively against the isolated unavailable licence-server address. Client-release trust and update cadence remain unchanged.

Its exclusive receipt is always scope: fresh-pairing-only and fullUpgradeAcceptance: not-run; only pairingAcceptance can pass after all three fresh milestones and clean teardown. The mandatory full runner has no skip option and still refuses a missing or untrusted signed descriptor before starting anything. A fresh-only pass cannot satisfy or relabel that blocked full proof. Neither entry builds a candidate or authorizes its own execution.

Isolated daemon test preparation

The API, brain, migration, licence and web E2E harnesses share test-only preparation in scripts/tests/lib/daemonHarness.mjs: call isolatedChildEnv(dataDir, scenarioValues), allocate freePort(), then await waitForHealth(baseUrl, timeoutMs, readinessPredicate). Inherited production ELOWEN_* and agent configuration paths are stripped; HOME, DB, project state and logs point into the temporary scenario directory. Explicit scenario values remain caller-owned. The sole inherited Elowen key is ELOWEN_E2E_DIST, made absolute before children change working directory. resolveTestEntry.mjs checks the selected build's daemon/main.js for test-licence boot, or daemon/index.js for the licence scenario's real locked boot. Without a selector it uses the checkout's own dist/; a missing selected entry throws before spawn without switching builds. Brain also imports its restart exit code from that same selected build.

brain-e2e/spawn-daemon.mjs additionally accepts optional synchronous prepareDataDir(dataDir), called once before PostgreSQL, test-licence minting and first daemon boot. It writes fixtures only below that isolated instance directory; without it, preparation is unchanged. The registry's tests/e2e/harness/spawn-daemon.mjs uses this seam to install plugins and collect their licence entitlements, delegating to the exact native lifecycle through existing coreContract/register-loader. It retains the same database observation handle, filtered child environment, restart and teardown owners. Selection is explicit per-call env.ELOWEN_E2E_DIST, then the process selector, then the selected core's dist; a missing selected entry fails before native spawn, never by falling back to another build. Selecting dist or TypeScript paths alone does not retarget bare runtime packages: verify candidate bytes and one module/class identity for bare and relative imports inside the isolated runtime before daemon acceptance. No dependency installation, new loader or host dependency mutation is part of this preparation.

Minimal use, as brain-e2e/spawn-daemon.mjs does it:

const port = await freePort();
const baseUrl = `http://127.0.0.1:${port}`;
const env = isolatedChildEnv(dataDir, { ELOWEN_PORT: String(port) });
const entry = resolveTestDaemonEntry('main.js', env); // throws before spawn if the selected build is missing
// Spawn `entry` with `env`, then wait for readiness:
await waitForHealth(baseUrl, 30_000, (body) => body?.ok === true && body.platformsReady === true);

Ports are released ephemeral IPv4 loopback ports, not reserved leases. Readiness polls every 100 ms and bounds requests and response-body reads by the total deadline. Brain requires platformsReady: true; the locked licence scenario accepts ok: true alone. A readiness timeout reports the last failure. Spawn, licence minting, restart, logs and teardown remain scenario-local. These helpers never ship or run on normal boot. Preparation regression tests mock child processes and build artifacts, so they do not execute a daemon or touch live state; full E2E proof still requires a separately built, isolated test environment. The preparation behavior is tested in tests/shared/daemonHarness.int.test.ts, and the entry selection rules have their own test in tests/contract/resolveTestEntry.test.ts. The transport helpers in scripts/tests/lib/sseStream.mjs and scriptedOpenAi.mjs are also test-only. openSseStream(baseUrl, path, token, observers) opens authenticated HTTP and incrementally decodes UTF-8 and LF-separated SSE frames. Scenario adapters own their counters, readiness promises, predicates and timeout messages: for example, delegate-e2e/run.mjs awaits openEventCollector's connected promise, which the collector resolves from the : connected subscription comment, while hooks reads the idle counter openSessionStream keeps through onEvent. The parity and lazy-MCP watchers use onLine to retain raw-line idle counting and their historical lack of an HTTP status assertion. Readers discard incomplete/non-JSON frames and tolerate transport teardown as before; abort() cancels immediately and close(deadlineMs) bounds reader teardown for the API lifecycle assertion. Memory follows the current incomplete frame or line, while scenario event collections remain scenario-owned.

Minimal stream use, as continuity-e2e/run.mjs does it:

const transport = await openSseStream(baseUrl, `/brain/stream?session=${encodeURIComponent(session)}`, token, {
  onEvent(evt) { if (evt.type === 'idle') idles += 1; },
});
// ...when the scenario is finished:
transport.abort();

Scripted model servers import readJson, chunkFrame, contentText, startCompletionStream and endCompletionStream directly. Empty or malformed request bodies record null; valid JSON scalars are retained. Content matching preserves spaces for non-text parts, and response headers, data bytes and the terminal [DONE] marker are shared. Scenario modes, chunk ids, usage, tool calls, held-response timing and server teardown remain local, for example in recovery-e2e/model.mjs. These helpers only run when a test explicitly opens a stream or starts a fixture; they add no daemon startup work or external services. Continuity waits for both native idle and the host's non-streaming turn control, so automatic compaction finishes before the next send. Its prompt probe selects the first chat completion after admission, skipping independent model-catalog requests and excluding later summary requests; it still reads only that request's final user message. The helper contracts are tested in tests/contract/e2eTransport.int.test.ts, and the probe in tests/contract/continuityPrompt.test.ts. Run the continuity suite with npm run test:e2e:continuity. Each turn gets 40 seconds to settle, and the suite adds at most 14 filler turns while it waits for a compaction (scripts/tests/continuity-e2e/run.mjs:108 and :145).

Recovery E2E keeps scripts/tests/recovery-e2e/run.mjs as the sequential package and CI entrypoint. It runs the registered numbered scenarios under recovery-e2e/scenarios/ by default; RECOVERY_E2E_ONLY=1,7 selects explicit scenario numbers. Each scenario owns its scripted model, real daemon, restart sequence and finally teardown. The test-only recovery-e2e/lib.mjs owns shared read-only DB observations, the store's display projection, provider-wire checks, silent-resume assertions and the attached client's real transcript fold. setCurrentDaemon(daemon) updates the timeout log source as soon as a scenario boots. Failure counts and restart timing evidence are shared with the runner; polling deadlines, log tails and the three-second pause bound are unchanged. The recovery, subagent and parity suites assert the forked-runner path unconditionally and fail when no fork served the delegated turn. The scripts no longer read ELOWEN_SUBAGENT_RUNNER. Daemon preparation continues through spawnRealDaemon, including its selected scratch build; these modules add no production entrypoints, persistence or background work. Run it with npm run test:e2e:recovery. CI runs the same entrypoint in the recovery-e2e job (.github/workflows/ci.yml:268). Polling waits default to a 60 second deadline (scripts/tests/recovery-e2e/lib.mjs:13), and the pause check allows 3 seconds for a clean exit (lib.mjs:16).

Paired-computer recovery preparation

recovery-e2e/paired-executor.mjs takes the isolated spawnRealDaemon handle, not a database URL. It enrolls through native users.apiTokens.createCliDevice in a serializable transaction, obtains POST /cli/connections/ticket, and uses one-shot /ws/cli/executor admission. It reuses shared createLocalExecutor and the selected candidate's process watchdog. Files remain below the scenario root; no physical computer, production database or service belongs to this fixture.

The sequential recovery runner prepares the following additional cases:

Selector Prepared scenario
13,14,15,16 Owner live/boot mutation loss and live/boot model-only loss
17,18,19,20 The same four variants for a delegated call
21,22,23,24 The same four variants for a workflow node
25 Owner Stop while offline, followed by boot/reconnect
26,27 Queued/committed child-result receipts while the parent computer is offline
28 Native MCP HTTP discovery/boot with unknown SDK response-stream progress
29 Authenticated policy API and native CLI-chat policy/SSE parity

For example, RECOVERY_E2E_ONLY=13,14,15,16 selects the owner variants against the isolated built candidate selected by ELOWEN_E2E_DIST; selectors are comma-separated numbers, not ranges. Case 13's first two attempts FAILED (exit 1 each). The first failed when a raw JSONB execution-target observation bypassed the repository's serialized authority row. Awaited/asserted source ordering places that failure after the mutation, lost final ACK, one effect and durable computer wait; those values were not separately serialized. Budget, resume, settlement and final journal ACK/Read checks were NOT REACHED; native finally cleanup followed. That first failure is a fixture observation defect, not an established product recovery defect.

In the second attempt, the canonical authority assertion passed. Four JSON milestones retained session/Project/target and prerequisite identities, one effect with its dropped final process-exit ACK, a conversation prerequisite waiting at generation 1, and the before-budget worker-request count 1, park count 0, delivery rows 0 and attempt total 0. After two authenticated replacement sockets, the required COMPUTER_DONE journal-answer wait timed out at 60 seconds. Logs report accepted-turn connection loss followed by an already-ended/nothing-to-continue park message; the timeout's root cause and product/fixture classification were UNKNOWN in that retained run. Final completion, prerequisite settlement, Read/mutation verification and completed-milestone checks were NOT REACHED; there is no final effect-count, no-replay or exactly-once journal ACK proof. Live case 13 has no restart, so offline-after budget comparison is not applicable. Native finally cleanup and absence of remaining owned processes/namespace holders were verified; this does not change the FAILED outcome. Cases 14–29 remain PREPARED, NOT EXECUTED. Neither of these historical attempts establishes passing recovery acceptance.

Separately, tests/brain/recovery/localExecutionRecovery.int.test.ts reproduced a native product integration defect: after a committed computer wait, accepted-send failure publication appended a terminal chat event, causing the continuation tail classifier to return nothing without a resumed provider request. Publication variants with one or two replacement sockets failed; their non-publication controls passed, with original completion joined before reconnect. The proven-wait outcome now keeps that publication nonterminal. Regression coverage includes delayed publication after resume, native Stop, exactly-once API settlement, raw terminal errors and refused/failed/stale/revoked park proofs. This is source-unit causal evidence, not the historical E2E's unretained raw journal/model tail. Both earlier actual case-13 attempts remain FAILED.

A later rebuilt-candidate attempt 1 also FAILED (exit 1): it emitted prerequisite settlement, then failed the old unknown-outcome prose substring assertion. The actual wire/native result body was not retained before cleanup, so its body and product/fixture classification remain UNKNOWN. The native-contract checks below do not reconstruct that historical body or relabel the failure.

On 19 October 2026, the final rebuilt candidate's attempt 2 PASSED actual LIVE owner mutation/reconnect case 13 (RECOVERY_E2E_ONLY=13), with runner process exit 0 after native finally/cleanup. All seven structured milestones were retained: session start, dropped mutation ACK, computer wait, waiting budget, prerequisite settlement, mutation verification and completion. The final counts were one effect, one mutation dispatch, one verification Read and one wire result. The prerequisite retained its exact id/generation as it settled; the original local Project target was retained and cancelled stayed false.

The native checks passed for exactly one original Bash journal result, isError: true, exact projected wire/native text, the applicable producer contract, wire ordering and model/executor health. The successful run did not serialize which accepted uncertainty-text producer supplied that result; it does not establish a specific producer branch or recover attempt 1's body. The private failure capture was not triggered, so actual failure-file I/O was not exercised by this success.

The fresh canonical package-binding proof matched the candidate; the complete 2,498-file compiled artifact stayed byte-identical before the run and after cleanup, with no remaining owned native process or namespace holder. This acceptance covers only LIVE owner case 13, not restart/boot, delegated/child-inbox recovery, cases 14–29 or any of the 16 prepared platform cases. The generic runner PASS banner and restart-timings heading do not prove those paths executed. Focused source-fixture passes below remain separate evidence.

Mutation cases flush one operation-ID append and drop only its final process acknowledgement. The scripted model answers the original tool-call ID and verifies with Read, never by repeating the mutation. Assertions retain the original target, call/node/session, durable prerequisite generation and parent inbox/journal ACK. Two independently authenticated replacement sockets race native wake paths; offline boot must spend no model, origin-recovery or delivery budget. Model-only and Stop cases introduce no mutation. Each scenario owns executor/model teardown.

Initial/final target assertions and platform session selection read native transcript.getProjectExecution(sessionId) authority rows inside read-only repeatable-read transactions, preserving the native parser and one-generation invariant. Raw session observations select only counters or candidate IDs, never feed a SELECT * JSONB object into the serialized authority parser.

Both paired and platform mutation checks require exactly one native journal toolResult matching the original toolCallId and toolName: 'Bash', with isError: true, plus one wire answer equal to native extractText(result). The compiled isNonUserSession classifier selects the native session context, not the scenario's origin label. Platform channels remain non-user sessions even on a local Project. The accepted producer contracts are:

  • Live dispatched connection loss, in either context: The local connection was lost after dispatch; the mutation outcome is unknown. Do not replay it.
  • Synthetic local owner-chat interruption: [interrupted] This Bash call was interrupted by a daemon restart; its mutation outcome on the computer is unknown. Verify the computer's current state before repeating it. It requires details.interrupted: true and details.mutationOutcome: 'unknown'.
  • Synthetic non-user interruption, including delegated and platform sessions: [interrupted] This Bash call was interrupted by a daemon restart; it may or may not have taken effect. Verify the current state before repeating it. It requires details.interrupted: true.

Text equality and producer-contract checks assert boolean comparisons rather than printing value diffs, so unredacted wire/native text cannot enter assertion stacks.

The paired and platform fixtures emit bounded JSON stdout at reached milestones only, never from polling iterations. Records identify native session/child/tool/ workflow, Project/target and prerequisite identity/generation/state where applicable, plus observed effect counts and dropped ACK ID/type/result-kind/final. Before/offline budget records retain park/origin/model counts and exact delivery-row/attempt totals; delivery ID/attempt samples are capped at eight rows, not a complete anomalous list. Full arrays remain in assertions. At most nine milestone records appear per scenario. Mutation verification, inbox ACK, cancellation, settlement and completion appear only if reached; a milestone is an observation, not whole-scenario acceptance. Platform records retain envelope presence, never its payload. No configuration, credentials, commands, provider/transcript/HTTP/executor-result payloads or external artifacts are written by this evidence seam. Completion precedes unchanged native finally teardown and is not cleanup-success evidence; executor, daemon/pool/cluster and model owners still dispose their resources.

Separately, a paired-scenario native-result check failure retains bounded private evidence in .artifacts/recovery-e2e-*/unknown-outcome.jsonl, outside scenario cleanup and compiled-artifact hash roots. The platform helper does not write this file. A unique directory and exclusive wx creation use mode 0600; both the first write and optional append flush before native teardown.

At most two JSONL records retain the wire observation first, then at most one cached native result plus its match count, error flag and interruption markers. Samples use native redactProblemText and stay within 500 characters; each has originalBytes, originalSha256 and sampleChanged, not the complete raw body. Native observation is never reread for capture. If that read fails, the wire-only record survives and the original error remains visible. A capture-write failure throws AggregateError containing both the original and evidence errors rather than masking either. Retained failure evidence is not a passing scenario or cleanup-success proof.

Cases 26/27 extend resultInboxRestart.mjs and result-restart-model.mjs, not a new receipt mechanism. They disconnect only after the child result already exists, compare the original inbox identity/attempts and settledResultIds across offline restart, then require one journal delivery after duplicate reconnect hints without rerunning the child. The read-only snapshot observes journal and inbox together.

Case 28 uses the real MCP SDK against a loopback HTTP wire fixture through the public instance-server API: initialize/tools/list discovery and supervised boot retain sdkResponseStream counters/deadlines as null and readiness as unknown. It prepares visibility/discovery checks, not SDK response-resume timing or hidden internal retry-counter proof. Case 29 uses the selected compiled BrainClient with real authenticated /connection-policy and instanceEvents: default delays are 2/4/8 seconds without jitter; a revision-CAS update to maxRetries: 0 and baseDelayMs: 1500 must arrive through retry-policy SSE without reopening the healthy episode. This is CLI-chat/API parity, not paired-client retry-loop proof.

The shared test-only recovery-e2e/platform-computer.mjs exports scenarioPlatformComputerRecovery({ daemon, token, platform, command, send, texts, restart, modelOnly }). Existing registry Discord gateway/slash, Telegram polling, WhatsApp bridge and Teams signed-webhook callers each prepare live/boot crossed with mutation/model-only loss: 16 cases total. Transport fixtures deliver /new, a setup turn, /project and the task through actual adapters; native readers locate the original session/Project and durable platform envelope. Assertions cover the same authenticated executor/lost ACK, stable offline budgets/envelope, two reconnect sockets, one answer to the original room and settled journal/delivery. No direct brain send, forged envelope, private wake or second database owner replaces that path. All 16 cases are PREPARED, NOT EXECUTED; they prove no live-platform acceptance.

The focused provider check is npx vitest run scripts/tests/recovery-e2e/computer-model.test.mjs --maxWorkers=2 inside the required isolation boundary. The root vitest.config.ts selects this provider fixture in integration and the source-only recovery fixture in unit. Knip's native Vitest integration reads their entry points from that root configuration; there is no separate recovery configuration. Its nine passing cases cover the scripted provider, actual local append commands and a task following an earlier platform setup turn, not authenticated real-daemon recovery. computer-recovery.test.mjs has 18 source-fixture checks through the actual paired/platform scenario source and compiled native authority/session/text helpers, trapping daemon, executor and transport boundaries. Named JSDoc types bind the VM-loaded scenario calls to the actual exported function signatures; this also makes these real source-fixture consumers visible to static analysis. They cover live producer text in both callers, context-correct synthetic acceptance, wrong-context or non-error/text-mismatch rejection, bounded failure capture and error/cleanup preservation. Their 18 passing cases are source-fixture evidence, not actual daemon, client or platform acceptance; all 16 native-adapter cases remain unexecuted.

Registry source fixtures also retain the candidate's actual ConnectionStatus through the existing Vitest alias and tests/ui/hostRuntime.tsx. Teams turn parity supplies native retry context and awaits disconnect; its ShareFile provider swap uses native connections/routing credentials. harness-source.test.ts checks missing-dist rejection and exact native lifecycle/preparation/licence delegation without spawning a daemon. finalDeliveryFailure.test.ts uses the selected core's actual logger, sink and console emission while retaining exactly one cs/sk/en notice and HTTP 503 diagnostics. platformTurnParity.test.ts keeps exact code/reporting metadata and Discord's original failure identity, including toBe(failure). These focused fixture checks and a successful source build do not establish passing daemon/platform E2E, browser or physical Linux/Windows acceptance.

CLI tmux driver and evidence ownership

The CLI tmux scenarios share test-only process and input primitives in scripts/tests/lib/tmuxDriver.mjs. Bind createTmuxInput(server, session) to the private server returned by createTmuxServer(label); use shellQuote for launch arguments and startMock(fixture, spawnOptions) for the fixture's child and output snapshots. The private tmux server inherits only PATH, HOME, LANG, LC_ALL and TMPDIR when present. This fake-daemon harness models a human terminal: ambient agent-shell access markers, daemon credentials and URLs never enter the server. Each scenario supplies its isolated CLI home, fake daemon URL and fake token explicitly; cli-tmux-goal.mjs is one consumer. This does not change the production CLI's agent-shell guard. Creating a server snapshots the five permitted environment variables once, with no extra process or network request. Readiness parsing, fixture environment, teardown and scenario assertions remain caller-owned. Deadline polling keeps each scenario's existing interval, strict or retrying predicate errors and timeout capture. Rail polling separately preserves its 200 attempts and final 50 ms sleep. No helper starts a daemon or builds code. The default deadline interval is 30 ms. The driver's tests, including a real pane probe for inherited agent access and credentials, are in scripts/tests/lib/tmuxDriver.test.mjs.

Evidence has six direct owners under scripts/tests/tmux-evidence/: artifacts creates fresh scenario directories, cleans process-owned temporary directories and writes reports; frames reads strict or live JSONL and validates diagnosed frames; capture binds plain/ANSI/state triplets within one completed frame and owns pane analysis; diagnostics summarizes timing and viewport work; metadata binds the Git commit, complete dist hash and run identity; aggregate revalidates all raw evidence against those owners. Capture retries remain capped at six, ordinary frames remain below 50 ms, and required labels and report fields are unchanged. Scrollbar visibility and drag coordinates use one isolated-cell finder restricted to transcript rows. That finder is scrollbarThumb in tmux-evidence/capture.mjs:121, and the drag in cli-tmux.mjs:553 takes its coordinates from it.

For example, cli-tmux.mjs imports capture analysis and the input driver directly; cli-tmux-built.mjs runs support, driver and native fake-daemon contract tests before its four evidence scenarios and validates the completed root through aggregateTmuxReports. The fake daemon serves authenticated GET /connection-policy with Cache-Control: no-store and sends the same fixed policy as the initial retry-policy event on /events. The built BrainClient requires that policy before opening either stream; a missing route fails connection bootstrap rather than selecting defaults. Goal timestamps use the repository's ISO 8601 UTC wire format, not zone-less database text. cli-tmux-brain.test.mjs exercises both native streams, policy authentication and goal timestamp serialization without tmux. Missing, stale, malformed or inconsistent evidence still fails the gate. The fake daemon closes foreground Delegate calls with tool_end when POST /brain/subagents/background detaches them, while their child sessions remain running. This matches the production detach contract and lets the long scenario assert zero idle animation timers after returning to the parent. These modules run only in the test harness. Support tests use independent expected capture labels, analysis, performance and build-identity fixtures, not the analyzers' own output as their oracle. Full CLI proof requires a separately built test checkout with tmux. CI runs the gate with npm run test:cli-tmux:built (.github/workflows/ci.yml:134). When ELOWEN_TMUX_RUN_ID is unset, the gate generates a local- run ID once and passes it to every scenario. The gate also refuses a configured ELOWEN_TMUX_ARTIFACT_ROOT that already holds files (scripts/tests/cli-tmux-built.mjs:13-21).

Brain service scenario fakes share the tool loadout through fakePiToolState() in tests/helpers/fakePiSession.ts. Spread its result into the fake session; the existing createSession callback fills __tools, __active and model for each spawn. Each call creates independent empty tool and active-name arrays, an empty rendered system prompt, an unset model slot and a tool-selection spy. It acts only in tests that explicitly include it and installs no runtime hooks. Without it, a scenario supplies its own tool surface. It does not model prompts, events, persistence, queues, thinking, compaction or billing. The shared BrainService fixture in tests/brain/brainService/fixtures.ts, plus idleLiveSessionLifecycle.test.ts, multiClientContract.test.ts and sessionTeardown.test.ts, are current consumers of that fixture rather than parallel session fakes.

Attachment fixtures such as tests/brain/toolMediaAttachments.int.test.ts allocate one temporary instance root and inject its chat-images child, not the root itself. chatFilesDir() derives a sibling chat-files directory from that image path; both namespaces must stay inside the fixture root and be removed together. Passing a top-level temporary directory as the image path instead shares chat-files with other tests, so a sweep can reclaim files absent from its own database.

Workflow engine fakes supply the required host methods even when their capability results are null: captureToolOutputWriter, delegatedTurnsOutOfProcess, delegatedWorkflowExpansionAvailable, subagentSessionForChannel, workflowExpansionRpc, delegationCompletionEmitter, toolResultInlineBytes and currentWorkDir. createWorkflowFixture in tests/plugins/workflowEngine/fixtures.ts supplies per-test result files and delegated state; focused background, execution and expansion scenarios provide their own contexts. The single completion sink accepts kind: 'subagent' | 'workflow' and returns an awaited typed durable outcome; a workflow sends only its whole-run summary. Completion acceptance is not delivery proof: only a settled parent custom_message with details.resultId proves delivery, with journal append and inbox acknowledgement in one transaction (including failed boot recovery results). tests/plugins/pluginContextDelegationCompletion.test.ts exercises both payload kinds, parent-scope capture and unchanged outcome/error propagation through the real plugin context. Recovery hooks include continueNode, the existing continuation entry point exercised by the models and workflow recovery suites. These fakes install no production hooks or external transport.

tests/brain/session/subagentCompletionSpill.int.test.ts runs the real loaded Subagent plugin through captured output writers, the immutable spill store, bounded formatter, completion ingress and PostgreSQL parent journal. Its twelve cases cover child results and whole-workflow summaries in host and managed session namespaces: an oversized UTF-8 body, a body one byte below the live limit, and an explicit spill-write failure with a DelegateRead recovery hint. It holds the parent turn open through injection and journal commit, compares the complete file bytes and excludes the unread tail from the parent journal. PI execution and managed transport are fixtures; host filesystem writes and database commits are real.

The real-daemon delegation harness includes scripts/tests/delegate-e2e/midturn.mjs and its held scripted provider in midturn-model.mjs. It runs single-result, simultaneous-result, whole-workflow-summary, user-steer FIFO and large-result spill scenarios with runtime.subagentRunnerEnabled both enabled and disabled (runner cap 2). Provider arrivals and terminal child/workflow SSE frames release each boundary; there are no sleep or polling barriers. Assertions check append order after tool results, one final idle, hidden result bodies, completion badges and commit acknowledgement before idle. Run the built harness through its isolated test boundary; --scenario=single|several|workflow|fifo|spill and --pool=enabled|disabled select a focused case, while the default runs all ten. The spill case compares the complete UTF-8 bytes with the parent-session file, verifies that the provider request and parent journal contain only the bounded path/byte-count/preview placeholder, then has the real parent Read a tail line absent from that preview before idle. It covers the host spill namespace; the real-daemon fixture does not provide a managed execution target. DELEGATE_E2E_ARTIFACT_DIR retains request and SSE evidence. The fixture explicitly uses openai-completions and disables tool deferral so its scripted calls exercise the real PI queue rather than a test queue. delegate-e2e/run.mjs includes these scenarios after its existing delegation checks.

Restart scenarios 11 and 12 in scripts/tests/recovery-e2e/run.mjs exercise the same result inbox around a real SIGTERM: a queued result not yet ingested is delivered once after recovery, while a journal-committed result is not replayed. RECOVERY_E2E_ONLY=11,12 selects both against an isolated built daemon. The held provider in result-restart-model.mjs exposes request barriers instead of elapsed-time guesses. tests/plugins/subagentResultRecovery.int.test.ts also covers both completion kinds, a lost PI queue and committed delivery across compaction.

Complete API and plugin disk fixtures reuse tests/helpers/fixturePlugin.ts writeFixturePlugins(root, specs); manifestOverrides preserves each fixture's declarations and moduleSource copies the complete module verbatim. Discovery-only manifests and malformed inputs stay local, and each suite still owns its roots, ancillary assets, loading options and cleanup.

For process-route authorization tests, setup({ ownerRoutes: true }) loads the terminal and subagent plugins, grants terminal to the ordinary account, and returns the in-memory UserStore as users so a test can create and grant a second administrator explicitly. Without ownerRoutes, no owner-operation plugins or extra terminal grant are installed. These are test-only fixtures with fresh stores per invocation; they do not change production permissions or perform provider requests. p34OperatorBoundary.test.ts exercises the ordinary-account denial and second-administrator success through the real plugin dispatcher and terminal gate.

Terminal capacity tests in tests/plugins/terminalPlugin.int.test.ts and the real-loader managed reader in tests/plugins/managedConsumers.int.test.ts inject a complete Sandbox control into the loaded registry. Besides prepareExecution and ENVIRONMENT_CONTROL_METHODS, the provider must expose resolveLocalTarget, bindLocalTurn, localFiles and localRequest; unused methods throw if called. Each fixture asserts that the real registry.control('sandbox') resolves before exercising its held preparation or managed read. A partial registered object remains unavailable under the production shape check, so it cannot stand in for a working provider. The capacity tests retain their real asynchronous preparation gate and background children: finally releases and awaits the held launch, and the existing awaited per-test registry sweep kills children before temporary directories are removed. These fixtures change no loader policy, enabled-plugin selection, grants or production runtime.

The managed recall and skill-catalog scenarios in tests/brain/memory.int.test.ts, tests/plugins/prompt.int.test.ts, tests/brain/dreamingFreshRequest.int.test.ts and tests/api/routes/managedProjectConsumers.int.test.ts use the same complete Sandbox registration contract and assert live control resolution before the scenario begins. Unused local operations throw. This keeps recall ACL changes, host/managed skill parity, fresh dream Project switches, guest icon validation and managed Git inspection reachable without weakening the registry's shape check. The unavailable-provider cases still remove that control explicitly.

Memory and plugin unit-test fixtures

tests/plugins/customerPluginBoot.int.test.ts boots the composed daemon over an old settings document without an authority-readiness marker or manual inventory. It verifies exact current enabled-manifest grants, no disabled or absent-plugin grants, and no regrant after revocation or later enablement. Receipted plugins with missing or incompatible shared-API declarations stay skipped and visible through the authenticated Plugins listing with their degraded reason.

tests/plugins/authorityMigrationLifecycle.int.test.ts exercises the same loader-owned seed over the real ConfigRepository: attached-role refusal, completed-marker no-op, failed historical mutation seed, filesystem failure, revision conflict and atomic settings-write rollback. Declaration construction and ingestion suites retain fatal filesystem/database cases and prove that invalid manifests cannot erase previously recorded lifecycle owners.

Native strict fixture compilation follows the existing runtime owners, not ambient module shims or test-only replacements for production contracts. The source-side type boundaries are:

Owner Native contract exercised by callers
plugins/mcp/serverPresentation.mjs Status-label dictionary reads can be absent; unknown status still returns undefined.
plugins/sandbox/web-src/runtime.ts The local sandbox strings hook derives known keys from its manifest; localized errors require the existing errorFallback.
plugins/sandbox/web-src/environmentRequest.ts Dispatch forwards the same strings contract through Parameters<typeof localizedError>[1].
web/lib/dateRange.ts A three-element tuple describes the dense split only after the exact-length guard.
web/lib/proxy.ts The first comma-separated protocol segment always exists, including for an empty header.
scripts/elowen-site-gateway.mjs Proxy settings accept bounded numbers/booleans; certificate IO uses only consumed string-path facets; commands carry numeric descriptors/timeouts; machine rendering accepts resolver and port values.
scripts/install-smoke/postgres-recorded.mjs Recorded cluster ports may be strings or numbers; applied/pool policy state is the native renderer result or null, with named string collections.
scripts/release-prepare.mjs The directory and optional date/product-line arguments are strings; a supplied product line reaches full release preparation.
scripts/elowen-privileged-worker.mjs Session registry injection requires native launch helpers and asynchronous cancellation settlement, with optional spawn, desktop verification, audit and admission bounds.
packages/plugin-shared/turnRunner.mjs One named options contract carries run/delivery promises, optional streaming/questions/reactions and original failure metadata.
plugins/subagent/lib/agentTypes.mjs Agent loading requires the host's model normalizer and accepts optional native logger and definition directories.

For example, tests/cli/install/databasePolicy.test.ts passes the real policy renderer into recordedPostgresHost and sets loaded policy state before testing restart-only reconciliation. The recorded host requires a new empty caller-owned directory; it does not run PostgreSQL commands or write outside that directory. tests/contract/execSessionRegistry.test.ts injects launcher and settlement callbacks into the real session state machine, while tests/contract/nspawnHelper.int.test.ts exercises descriptor pinning and resolver-specific firewall output through the declared-lock adapter. Neither fixture replaces the runtime owner's refusal, timeout or cleanup behavior.

These declarations and proven-index annotations introduce no runtime branch, fallback or extra IO. Erased TypeScript output is a different claim from minified artifact identity: the two Sandbox browser files can acquire different minified identifiers even when their type-erased runtime is unchanged. Raw installed privileged source bytes are digest inputs, including JSDoc; the authorized release/update cutover requirement is documented in infrastructure lifecycle.

Migration fixtures replay the shipped SQL ladder instead of pinning a version number. packages/db/tests/migration/*.test.ts copy only the files below the version under test into a temporary directory, migrate, seed the old shape, then add that file and migrate again (packages/db/tests/migration/sessionDevice.int.test.ts). plugins/sandbox/tests/sandboxPreservingSchema.int.test.ts seeds a verbatim plugin ledger of versions 1–20 beneath Sandbox's shipped version-21 baseline, proves a re-run leaves those rows untouched and applies a version-22 migration on top; the file's second case reopens the plugin database over that saved state and checks leases, snapshots, publications and resource history survive. daemonBootWiring.test.ts awaits the maintenance stop handle before reading retention results; that existing handle acknowledges the in-flight asynchronous writer commits.

The dreaming scenarios in tests/brain/dreamingService.int.test.ts await MemoryStore.update when simulating concurrent user edits. Their runTurn callbacks complete only after those writes commit, so batch completion observes the actual edited rows rather than queued writes.

tests/helpers/memoryEmbedding.ts owns FakeMemoryEmbeddings, a table-backed fake used by the six memory ranking and recall suites. Known texts return fresh float vectors; unknown texts return three zero dimensions, or two when requested by the vitality suite. Its failFor option rejects only single-text embedding with embed boom; batches still use the table. Snapshot and memory-space identity come from fakeSnapshotConfig and fakeMemorySpace in the same file (memoryEmbedding.ts:6 and :10), which twelve embedding and brain test files import. It makes no network requests and has no production caller.

directEmbedBatch(embeddings) in the same file adapts a fake service's embedBatch to the worker's batch function, answered in-process, for suites that do not fork the background worker (memoryEmbedding.ts:46). A failing request fails the whole batch, as an outage would. Four test files use it: api/memoryRoutes.test.ts, api/memoryVitality.test.ts, brain/memoryMaintenanceService.test.ts and embeddings/embedQueue.test.ts.

tests/helpers/fixturePlugin.ts owns disk plugin preparation for loader, controls, alerts, daemon boot, update preflight and UI-route tests, and also config, system readiness, plugin skill manifest, licence snapshot, publisher gate, apply-change and API transition tests. writeFixturePlugins(root, specs) creates each plugin directory, writes the default manifest and then applies manifestOverrides after declaration blocks. The default manifest is name, version 1.0.0, apiVersion 2, the canonical PLUGIN_SHARED_API_VERSION in requiresSharedApi, a fixture plugin <name> description and entry index.mjs. Each spec supplies either a register body, wrapped in the existing function template, or moduleSource, copied byte-for-byte without source inspection. The optional provides, configSchema and userConfigSchema fields are written into the manifest verbatim (fixturePlugin.ts:8-18). For example, loader tests provide complete modules and set the manifest version, description and apiVersion through manifestOverrides (tests/shared/loader.int.test.ts:23-34). Without overrides, existing defaults stay unchanged; deliberately malformed JSON is still written directly by its test. fixturePlugins(specs, enabled?, recordSessionRunPlatforms?) creates a lazy provider for an authoritative test context with in-process delegation. Before loading the provider, callers must supply the third argument from the same caller-owned database used by their app. The loader awaits that journal writer for all discovered run-platform declarations, including disabled plugins and empty batches, before importing entries. Writer errors propagate; omitting the writer still fails when the provider is loaded. There is no default writer or extra pool.

The config, payload and readiness API suites pass their existing db.repositories.journal through this seam. useBrainPostgres owns pool closure through onTestFinished; the plugin fixture's synchronous cleanup() removes only its directory. Callers using only fixture.dir need no writer or database: daemon boot uses its own authoritative composition, and disk audits never load the provider. These fixtures never load installed plugins.

Minimal provider use with an already opened caller database and cleanup in finally:

const fixture = fixturePlugins([
  { name: 'ledger', register: 'ctx.registerText("system-prompt", "raw");' },
], undefined, input => db.repositories.journal.recordSessionRunPlatforms(input));
try {
  const registry = await fixture.provider.get();
  // Exercise the code under test with the loaded registry.
} finally {
  fixture.cleanup();
}

writeFixturePlugins(dir, specs) is the variant for a plugin root that already exists, such as a folder that appears while the daemon is running. It is used by daemon/daemonBootWiring.test.ts and update/apiTransition.test.ts. Use fixturePlugins when the test only needs a fresh root.

  • The test-only tmux driver exposes stopMock(child) for the CLI tmux scenarios. It ignores absent or already settled children, sends SIGTERM, waits up to one second, then sends SIGKILL if necessary. It clears its timer and exit listener. Session/server cleanup and owned temporary-directory removal stay in each scenario; cli-tmux-signals.mjs is a consumer.
  • daemonHarness.readDaemonLog(logDir) joins sorted daemon-* files and queryDaemonPid() returns the trimmed systemd MainPID output. Both propagate errors; each scenario retains its current unavailable-log/service and zero-PID policy. These helpers do not own boot, restart or teardown. Integration consumers are recovery/delegate diagnostics and the API/web PID safety checks; their migration must land with the helpers.
  • daemonHarness.configureInstanceMcp(baseUrl, token, name, args) creates an enabled instance-scoped stdio server using process.execPath, then reads the instance list and requires connected status. It checks both HTTP responses and exposes HTTP failures. It acts during parity/lazy-MCP preparation, never production boot. No server is configured unless a scenario calls it; lazy MCP is a current consumer.
  • sseStream.openEventCollector(baseUrl, path, token) collects parsed events in order, exposes connected after the subscription comment and retains deadline-bound predicate waiting with event evidence. abort is immediate; close waits for reader settlement. Scenario callers select their existing close policy and bound readiness waits. No stream is opened without a call; events are retained for the stream lifetime. Integration consumers are the API, brain and delegate harnesses, whose adapters must migrate together.
  • sseStream.watchIdle(baseUrl, token, session) preserves the raw-line idle counting shared by parity and lazy MCP. stop uses the existing bounded stream close. It does not parse JSON or change each suite's turn deadline; without a call there is no subscription. Both MCP suites consume it.
  • scriptedOpenAi.completionFrames({ id, created, model }) returns delta(value, finishReason) and usage(prompt, completion) SSE strings with the existing OpenAI completion envelopes. Metadata and token counts remain supplied by the scenario; stream headers, terminal markers, routing, held responses and socket lifetime remain separate. It has no network side effects. Parity and lazy MCP consume it; brain/hooks/workflow model migrations use the same seam.
  • Tmux evidence uses one ORDINARY_FRAME_LIMIT_MS policy of 50 ms for both raw frames and aggregate summaries. analyzeFrameDiagnostics(frames) and validateFrame(frame, prefix) have no budget override. aggregateTmuxReports accepts expectedRounds, repo, expectedCommit and expectedDistHash; it snapshots Date.now once and uses a fixed one-hour evidence window plus one-minute future skew. Forced frames retain their existing treatment. No evidence is checked until an analyzer runs; cli-tmux-support.test.mjs and the aggregate runner are consumers.

Shared browser fixtures

The worker harness fixture in web/tests/e2e/fixtures/worker.ts owns one fake daemon and one web server per Playwright worker: it derives both ports from the worker's slot in fixtures/env.ts, starts the pair through harnessServers/startServers in web/tests/e2e/harness.ts, performs that worker's real BFF login into tests/e2e/.auth/admin-worker-.json, and stops the pair when the worker ends. It replaces Playwright's per-run webServer and globalSetup, which cannot be per worker. It is the only owner of baseURL and storageState for a spec — fixtures/index.ts takes both from it — and the whole fake-daemon state stays process-global, so a second harness on the same ports is never safe. A spec must not start a pair, name a port or read another worker's state file.

ChatPage in web/tests/e2e/pages/ChatPage.ts scopes shared chat controls to the full surface by default. Pass new ChatPage(page, 'compact') for the advisor dock; the existing data-variant attribute and visibility select the interactive surface without changing navigation. Hidden server copies retained during Next hydration do not match shared controls; multiple visible surfaces still fail readiness. waitForReady() polls the fake daemon's /__test/streams on a [20, 40, 80, 160] ms ladder that repeats its last interval, instead of Playwright's [100, 250, 500, 1000] default: the surface's EventSource registers well after the DOM paints, so the default ladder spent a 100 ms first retry on each of the suite's ~1 800 navigations. goto() snapshots the highest open stream id before it navigates, so readiness waits for a NEWLY registered stream and never matches the previous test's lingering one; that snapshot stays a request of its own because one /__test/streams round trip measures about 2 ms. After a settled run folds, call openWorkRuns() before asserting interim text or tool output. It waits for the summary and opens closed runs through their real buttons; unused page objects perform no browser work. chat.long-tokens.e2e.ts uses both scopes to retain its prose, code and horizontal-overflow checks inside expanded work. users.project-permissions.e2e.ts waits for each grant PATCH acknowledgment before closing its context, so the next viewport checks the persisted final state rather than an interrupted autosave.

Browser specifications share collectErrors(page) from web/tests/e2e/fixtures/designReview.ts. Register it before navigation or interaction and assert the returned array after the flow. It records subsequent console errors and uncaught page errors only; it does not classify requests or expected HTTP failures. Without a call no listeners are registered. chat.upload-progress.e2e.ts is a consumer; richer plugin request diagnostics remain with collectPluginErrors.

observePolicyBootstrap(page) in web/tests/e2e/fixtures/policyBootstrap.ts is the ONE classification of the app's own bootstrap GET /api/connection-policy. useElowenEvents binds that load to the event lifetime, so an effect cleanup or a full navigation aborts it before its answer and the next lifetime re-issues it; elowenClient.loadConnectionPolicy keeps no error for an aborted load. A spec registers the observer before navigating and asks isCancelled(request) from its own requestfailed handler: only an abort of that exact request, with no query string, before the first answered 200 in the current document, is the app retrying itself. It records those in cancelled and the answered loads in statuses; every other failed request, including other aborts, stays the caller's evidence, and the caller keeps its own collector. observeConversationBrowser in conversationList.ts delegates to it and still requires a 200 whenever a cancellation was allowed. The specs that own a request-failure collector use it: chat.todo-blocked-help, chat.message-blocks, chat.plan-decision, chat.workflow-dag, chat.deliveries, chat.multiple-shares and dashboard-chat. mcp.register.e2e.ts and account.fast-models.e2e.ts still carry their own copy of the same rule; folding them in is a follow-up the owner has not agreed to, so both remain as documented below.

documentOverflow(page) in designReview.ts evaluates document.documentElement.scrollWidth minus document.documentElement.clientWidth once and returns horizontal overflow in CSS pixels. Callers keep their own zero- or one-pixel tolerance; pluginSettingsContract.noOverflow uses the one-pixel threshold. The helper has no observation or polling when unused. Compound document, region and offender geometry remains atomic in sidewaysOverflow and scenario-specific evaluations. Measurements against window.innerWidth remain viewport measurements.

The fake daemon's sseFrame(event) in web/tests/e2e/fake-daemon/emitters.ts accepts the production BrainEvent and ElowenEvent unions through type-only imports. It formats one non-replay SSE frame with event.type as the event name and JSON.stringify(event) as the complete payload, without an id or replay cursor. handlers/brain.ts and handlers/core.ts call it when emitting their events; core recipient filtering stays in the route. The helper neither subscribes nor emits when unused. Control and conversations streams with different payload shapes retain their own frame builders.

Guides browser acceptance

Core reader fixtures use tests/helpers/docsDatabaseFixture.ts to publish real ingestion output in an ephemeral PostgreSQL database with package-owned identity functions. The read service receives only search.corpora; source parsing/rendering stays in preparation. Frozen-corpus acceptance checks scope, coverage, citation identity and source-grounded correct answers: top three normally, top five for a justified broad question, defining section first for exact identifiers/error codes/API names. The no-model keyword path is a separate correctness gate. corpusGolden.test.ts uses the unchanged SHA4D recipe only for SQL mechanics: current eligible-row coverage, no-model/outage, partial vectors, projection isolation and citation identity. All explicit negatives and unanswerable projections must remain empty. Its 87 positive keyword contexts compare against the frozen native-main output in docsKeywordBaseline.json, not historical chunk IDs mapped onto new bodies. Each locale/projection cohort must retain at least its old correct count; all 27 answerable exact-identifier contexts independently require a defining chunk at rank1. Rank3/rank5 answer rules and recorded source quotes remain in docsAnswers.json.

tests/helpers/docsRelevanceFixture.ts owns the separate recorded-real-vector fixture boundary. docsRelevance.test.ts is opt-in through ELOWEN_DOCS_REAL_ACCEPTANCE=1; without that selector, ordinary CI reports this real relevance test skipped, not passed. A requested run additionally requires ELOWEN_DOCS_REAL_FIXTURE naming a manifest file. Missing, corrupt or incompatible inputs fail before corpus publication: there is no provider call or synthetic fallback.

Run inside the core test isolation boundary described in docs/TESTING.md:

ELOWEN_DOCS_REAL_ACCEPTANCE=1 ELOWEN_DOCS_REAL_FIXTURE=<manifest.json> npx vitest run tests/search/docsRelevance.int.test.ts --maxWorkers=2

The strict docs-relevance-v1 manifest pins the frozen source/main identities, source-file manifest hash, answer/query fixture hashes, exact opaque vector space, encoding: fp32-le, and documents, queries, baseline and vectors: [{data,index}] artifacts. Each artifact has a relative path, exact bytes and sha256; it must resolve inside the manifest directory, including through symlinks. Each file is bounded to 256 MiB. Binary exports, credentials and instance paths stay outside the repository.

Document JSONL contains textHash, exact embeddingText, oldDocumentIds and newDocumentIds; query JSONL contains textHash and exact query. Text hashes use unmodified UTF-8 input, never trimmed or re-prefixed. Binary indexes contain space, text_hash, offset, byte_length, dimensions and per-vector sha256. The loader validates contiguous bounds, exact space/width, finite little-endian FP32 coordinates, shared-hash byte identity and complete document/query coverage. One text is captured once, not once per locale, projection or state. Matching production vectors are reused unchanged; only missing union hashes and distinct queries belong in an explicitly authorized capture.

The old-baseline artifact has format: 1, algorithmCommit, sourceCommit, answersHash, inputFingerprint and rows. Rows contain mode: keyword|hybrid, locale, projection, exact query, answer-rule rule and source-judged rank (1–8 or null). The input fingerprint is SHA256 of JSON.stringify([space,documents.sha256,queries.sha256,vectors.map(v => [v.data.sha256,v.index.sha256])]). An isolated diagnostic executes the immutable observed main algorithm on its own original chunks with these same captured vectors and emits the baseline; no retired algorithm is imported into runtime or repository test helpers. Keyword rows must also match the committed old keyword baseline. The observed old fusion remains its original 1:1; PostgreSQL stays 2:1.

The real gate publishes current ingestion output, checks every current text/identity against the fixture, and ranks the same 87 positive contexts in each mode with the same 37 recorded query vectors. The captured model is qwen/qwen3-embedding-8b at 2048 dimensions. Each of the six locale/projection cohort totals must not regress, and all 27 exact contexts must independently pass rank1. All 18 excluded projections remain empty. Explicit negative queries and safety probes retain the all-state mechanics checks rather than receiving invented real query vectors. ELOWEN_DOCS_REAL_REPORT optionally retains per-query results, cohort deltas, exact failures and excluded-projection failures; a report does not imply a passing gate. Missing captures leave real acceptance unverified, regardless of SHA results.

web/tests/e2e/specs/guides.e2e.ts reuses the existing fake-daemon/Next harness. Its home/category/article matrix covers cs/sk/en, both Studio skins, 320/390 px touch and 1440 px desktop, and administrator/ordinary profiles. The sample slugs web-ui and projects-workflow are authored manual pages, not test copies. web/tests/e2e/fake-daemon/guidesDatabase.ts owns startGuidesDatabase(signal), returning {service,stop,root}. It starts a socket-only ephemeral PostgreSQL cluster, prepares a WorkerDatabase clone and opens a non-authoritative worker-role reader pool. A real forkWorker search-corpus job ingests the current documentation, bundled plugin guides and English-only fallback fixture once per harness; startup awaits successful publication and child closure before returning the bounded DocsSearchService. There is no handwritten retrieval index. Embeddings are explicitly disabled, and attempted provider calls throw rather than reaching an external service. No production database or product daemon is used.

handlers/guides.ts::startGuides(signal) installs that service and returns asynchronous teardown. The fake server awaits it before listening. SIGTERM/SIGINT abort startup ingestion or close live HTTP connections and drain fixture cleanup; teardown closes the pool, stops the cluster and removes its owned directory. web/tests/guidesDatabase.test.ts exercises current catalog/article reads, asset references, atomic search revision/section identity and developer keyword search without a model, then checks that stop() removed the cluster directory. /search/docs calls searchResult once, so its revision and passages come from the same database query snapshot.

GuidesFixture in web/tests/e2e/fixtures/guides.ts configures the daemon-only /__test/guides channel before navigation. Select catalog/article/search/ask faults, optionally for one exact query; hold: true waits for release() rather than sleeping. state() records started/completed reads and held count. Clear the hold configuration before release() when subsequent mounts must complete normally; release settles current reads, not future reads matching the same fault. Changing a query while an earlier request is held exercises browser cancellation and obsolete-reply handling. resetGuides() releases held reads, clears fault configuration and related-update state, and replaces request history, but retains the service and published revision without reingesting. Each read captures its recorder before awaiting a hold; an old completion writes only its old recorder, never the next test's history. A browser regression checks released requests, empty history and unchanged catalog/search revision after reset. With no configuration all reads use the ingested real documentation snapshot; emptyCatalog alone projects an empty article list for the empty-category case.

Documentation retrieval uses the real SQL reader; AI answer generation is scripted: localized neutral text passes through parseAskReply and citations resolve actual retrieved identities. Provider, account-refusal and rate-limit fixtures exercise UI states, not real model authorization or inference. Navigation semantic assistance is deliberately absent (/search/rank returns no suggestions); immediate navigation remains browser-owned. Product HTTP schemas remain shared imports. The actual Next/BFF browser flow runs against fixture handlers, not production daemon routes or an installed package. DocsSearch and ElowenApi search tool execution have separate core coverage; the browser scenarios do not invoke those tools.

An optional relatedUpdate: { slug, sectionId } writes neutral cs/sk/en note files into one owned temporary directory, then invokes the changelog owner's loadEntries and registerRoutes. The fake dispatch supplies the shared apiRequestParsers from each route's input contract, so the real handlers use parseParams, parseQuery and parseBody just as they do in the host. Files are removed after loading; no announcement is added to shipped entries. Normal plugin listing/bundles still determine availability. seenWrites() verifies that fetching article backlinks does not acknowledge updates. Without this option the existing changelog fixtures are unchanged.

The focused spec checks shared page/palette results, explicit clickable AI sources, direct bookmarks/refresh/history, screenshot decoding and overflow, English fallback, update round trips, loading/empty/error/retry and stale requests. Focused regressions return to a cancelled Ask question and open a same-article section from either a lexical result or an AI citation. Touch scenarios open a persisted section from the palette and resize to desktop without overflow; offline scenarios use the local destination list and keyboard selection without waiting for documentation retrieval. web/tests/components/shell/siteSearch.test.ts independently checks all three locales' instant navigation and that article bodies do not enter its navigation candidates. Route unmount/revision cancellation (net::ERR_ABORTED) is expected; other failed docs/search transports and all HTTP failures fail the navigation matrix. Test screenshots are local Playwright artifacts, not committed assets.

web/tests/e2e/specs/guides.screenshots.e2e.ts captures the manual's web images at a 1536 px viewport in English studio-light with neutral seeded fixtures: the Guides home and an article, the conversation Project picker with three seeded managed targets (switching targets never creates or starts a real environment), chat with the attach control framed, the Memory register with a record open, the System, Models and Plugins settings windows, Account → Memory with its switches framed, and a settled Guides search whose AI answer is a fixed grounded reply routed by the spec. Frames are pointer-inert overlays added after layout. Run it with the existing harness; set E2E_GUIDES_SHOTS to a local output directory (default /tmp/elowen-guides-captures). The capture never overwrites shipped documentation images: inspect each PNG before copying it into docs/site/images/, whose SCREENSHOTS.md lists every asset, its embedding page and its alt text. The viewport-sized home/article captures remain local review artifacts.

A collected spec is preparation only: run it against the integrated renderer, corpus, API/client, content, Guides UI and changelog revisions before claiming browser acceptance. Production transport, deployment and provider behavior are outside this fixture's evidence.

Chart unit-test teardown

web/tests/fixtures/recharts.ts exposes cleanupCharts(): await it in a suite's afterEach before restoring timer or frame mocks. It unmounts React trees, then completes one animation frame so Recharts' queued Redux notifications cancel their Node fallback timers before jsdom removes browser globals. Native frames use a frame-completion barrier; virtual enrollment clocks advance jsdom's 60 Hz scheduler. There is no fixed real-time delay, error interception or global setup hook.

Tests with an owned frame queue pass its pump explicitly: await cleanupCharts(() => { pumpFrames(); }), as ProjectCard.test.tsx does. ElowenCliSection.test.tsx uses the native barrier. The other suites rendering real host charts, resource meters and plugin resource surfaces use the same fixture; fully mocked charts and pure data helpers do not need it. It does nothing unless called, and does not replace a suite's MSW, QueryClient or other resource cleanup. web/tests/fixtures/recharts.test.tsx verifies native, virtual-clock and controlled queues, including zero remaining Redux frame callbacks and fallback timers.

Fetch-SSE unit fixtures

web/tests/fixtures/brainChatStream.ts supplies real response bodies consumed by readDaemonStream. In a suite's beforeEach, call installDaemonStreams(policy) with its explicit finite retry budget; it starts a fresh authentication generation, intercepts only the policy bootstrap and three daemon feeds, and restores fetch after each test. All REST traffic still reaches that suite's MSW handlers or client mock. Without installation it does nothing; native EventSource is not a product transport. BrainChatController.test.tsx exercises this boundary through the real provider. Await emit(event, payload) for a React-flushed frame; use queue inside one async act for frames racing cancellation. A feed is ready only after its authoritative snapshot, not after HTTP headers; end() closes the body and consumes the owner's retry budget. Cancellation closes the actual reader, so enqueueing after cancellation is invalid. The fixture owns no server, timers or product policy defaults.

web/tests/fixtures/mcpConnection.ts supplies the canonical MCP connection observation for unit-test server rows. Callers select transport and readiness explicitly; ChatTelemetry.test.tsx uses it for live, sleeping and disconnected servers. It starts no transport and supplies no admission or retry policy.

Connection-state browser fixtures

web/tests/e2e/fake-daemon/connections.ts owns connectionPolicy() and computerConnection(projectId, connected). Policy derives from the fixture's stored config and canonical limits; authenticated /connection-policy, the initial retry-policy core event and committed config events expose that same revision, 60000 ms cap and no jitter. Computer seeds supply typed server observations with retry: null, not an invented remote episode; callers can explicitly seed stale or missing observations. These helpers do no work outside the fake harness.

handlers/brain.ts includes modelRetry and executionState in authoritative control snapshots. Emitting a typed retry frame also updates that control before resync/reload, so a later snapshot cannot revert a live retry to an older seed. connections.retry-state.e2e.ts consumes these seams in 36 full-matrix cases: cs/sk/en, 320/1440 px and both Studio skins. It checks independent transport/model/ computer-wait lanes, status after resync/reload, live prose and unsent input across resync/background, initial loading, bounded 503 retries, exhaustion, keyboard manual retry and restored-auth recovery. Countdown changes stay outside live announcements; stale/unknown/offline observations expose neither remote retry buttons nor counters. Touch contexts are real Chromium isMobile/hasTouch; background/resume and auth refusal/restoration are simulated, not physical OS suspension or external login.

Existing Settings specs retain the canonical millisecond payload and the zero retry budget. Account/Project/dashboard and Terminal specs consume current typed status presentation. Desktop coverage uses the native loopback RFB fixture and real noVNC client: a held, expiring ticket exposes connecting state before existing framebuffer pixel/size assertions. MCP seeds expose SDK-owned null metadata; they do not observe a live SDK's hidden retry attempts. Resync has no blanket harness-noise exemptions. Fault cases allow only their exact injected route/status errors; the MCP error-state assertion waits up to 20 seconds for existing native request retries, without changing runtime policy.

mcp.register.e2e.ts retains its existing per-spec request-failure collector. It classifies only GET /api/connection-policy with an empty query and exact net::ERR_ABORTED, observed before the first policy HTTP 200, as bootstrap cancellation. The flow explicitly permits at most one such cancellation, requires a nonempty set of policy responses and asserts every response is HTTP 200. Other methods, paths, queries, failure kinds and aborts after the first HTTP 200 remain unexpected failures; existing console/page-error and final unexpected-network assertions are unchanged. A separate causal diagnostic traced the first abort to useElowenEvents effect cleanup, followed by a new effect lifetime and a successful policy request, not a timeout or auth callback. The higher-level React cause, including StrictMode, is not established; this test-only classification introduces no runtime fix. After paging back to default order, the ownership check expands the native Instance Settings group through its accessible button and requires aria-expanded=true before inspecting its label.

The historical full touched-flow matrix ran once: 120 of 129 passed, nine failed. The route-specific MCP error-state case subsequently passed at both 390 and 1440 px. After the runtime ordering/header fixes, the two English 1600 px computer-ring cases passed in both Studio skins with their original geometry assertion. A separate final MCP run passed all six register flows: cs/390, en/1440 and sk/320 in both Studio skins, with zero retries. Its exact six-case selection was listed and inspected before execution; a preceding anchored selector selected zero tests, not six runtime failures. All six flows passed loading/empty/search, global sort, drawer/auth, edit/toggle/bulk, native expansion/ownership, card-width/overflow/touch-target and final console/network assertions. Each trace observed one bootstrap cancellation and one policy HTTP 200. These focused passes clear the earlier two-ring/six-MCP blockers; they are not a fresh full-129 pass. The 36-case connection-state matrix remains separate passing source-browser evidence.

The candidate-bound typecheck:e2e passed. Plain-host compilation still resolves old database declarations and fails; that resolution failure is not a remaining E2E-source type defect or a passing plain-host gate. At that candidate, standard e2e:look was blocked by its networkidle wait on permanent fetch-SSE. The separate visible-readiness capture passed 48 screenshots; it is not a standard-look pass. The current look waits for finite requests and a 500 ms quiet interval, removing only responses whose actual MIME type is text/event-stream from that wait. A later focused standard look passed eight Account Security/Chat shots at 320/1440 px in both Studio skins in Czech, without console errors, failed requests, overflow or lingering visible loading. This does not rerun the historical MCP capture. Actual MCP register/sorted-tools screenshots were inspected across the six cases. Those historical checks do not establish coordinated packaged-artifact, physical-device or external-reauthentication acceptance.

A later focused browser proof passed four English cases with zero retries: real 320 CSS px mobile/touch and 1440 px desktop, each in Studio OLED and Studio Light. The real MCP and WhatsApp bundles loaded through the plugin loader with their complete SHA-256 verified. Captured public GET bodies were forwarded unchanged: MCP retained its 60-second delay, and unlinked WhatsApp retained its 30-second delay, enabled Pair device control and no Unpair control or pairing POST. Changing Date alone left remote countdowns absent and announcements stable. An actual HTTP 200 SSE EOF exercised native readDaemonStream: the local visual countdown changed from 10 to 8 seconds while its live announcement stayed unchanged.

Keyboard expansion, pointer/focus states, viewport geometry and screenshots were checked. Browser error collections were empty; initial bootstrap GET aborts were recorded separately and successful HTTP 200 replacements were required. Server public-theme bootstrap still logged HTTP 401 fallback warnings, so this was not a warning-free run.

The capture-based spec remains evidence only, not imported into default CI: it requires external GET captures and a registry checkout. No self-contained CI regression is delivered. This focused status proof does not establish complete application empty/loading/error coverage, a fresh full-matrix pass, coordinated packaged-artifact, physical-device or external-reauthentication acceptance.

Query-plan and runner instrumentation

Test timing uses the existing runner configuration boundary, not a custom reporter: the root and web Vitest configs pair default with built-in json; native root projects also own the database and plugin-shared selections; Playwright pairs its terminal reporter with built-in json. ELOWEN_TEST_REPORT is the caller-owned output filename, defaulting to distinct files inside checkout-root .reports/ resolved from each config's module URL. Vitest sets that destination through native test.outputFile.json, not reporter constructor options, so explicit CLI --outputFile=<path> wins over inherited environment and default paths. The nested web runner in tests/contract/coreCssRegistryPath.int.test.ts consumes this precedence to read its own temporary JSON without overwriting the parent report. tests/contract/testReports.int.test.ts exercises actual nested CLI runs for the root, web, database, repository and plugin-shared selections, checking explicit CLI isolation and the environment destination without CLI. This adds report I/O only: no fixture lifecycle, worker, timeout, retry or assertion changes.

scripts/ci-local.mjs consumes that boundary for each workflow step. Its tee runs outside bwrap while JSON writes remain inside the writable checkout; bwrap strips inherited ELOWEN_INSTANCE_ROOT before invoking the test. After a step the runner moves only its assigned JSON, preserving unrelated reports. Checkpointed steps.json records measured wall time (including the host queue), exit status, skip/block reason, command, working directory and artifact names; a finished run adds summary.md. Unique run directories carry a validated ownership/completion marker. Retention removes only marked completed runs beyond the newest 30, never active/foreign/symlinked entries. Interrupted runs remain inspectable; there is no automatic retry or rerun. Concurrent local gates may select the same expired completed run. Retention ignores only ENOENT if that run or its marker disappears during inspection/removal; permission and other filesystem errors still fail loudly. Marker parsing and ownership/completion checks remain mandatory, so active, foreign and symlinked directories stay protected. Deterministic child-process syscall-boundary fixtures cover disappearance at marker stat/read and run removal, plus EACCES/EIO at each boundary; no sleeps, retries or archive lock are involved.

The same run object owns an in-memory map of successful standalone npm run build and npm run build:web steps. Identity is the exact command, working directory and sorted effective environment, excluding only the runner's two report/log destinations; neither keys nor environment values are persisted. A later identical step records status: "reuse" and reusedFrom: { job, index, log }, prints the origin job and writes a reuse log without starting another build. The brain-E2E job consumes the daemon job's root build this way. Failed builds never enter the map, and each invocation starts empty. Different Next.js/build-web commands and directories remain separate; compound commands and the dist-integrity rebuild probe always execute. Host-limit checks still precede reuse. The contract assumes the current sequential workflow leaves source inputs unchanged between jobs; it is not persistent artifact freshness detection.

tests/contract/testReports.int.test.ts uses a fake npm executable that records each invocation, never a real build, to cover success reuse, failure non-caching, source job/log attribution, directory/command/environment separation, key-order invariance, per-run scope and repeated non-build/compound execution. Its read-only observations name only the recorded status, log and reuse-attribution fields; captured log paths and physical-start rows must exist before inspection. These fixture types do not change the runner's report storage or failure policy.

The runner's full-suite classifier recognizes unfiltered npm test workflow commands, including npm's --prefix form. It injects four workers by default; ELOWEN_TEST_WORKERS accepts exactly 2 or 4. Focused Vitest workflow commands retain all selectors and get two workers regardless of that full-suite override. A workflow-supplied CLI worker count is rejected so it cannot bypass admission.

Four-worker steps require two-slot admission outside the unchanged bwrap boundary. Before the first such step, the runner queries heavy-gate --supports-weighted-slots and remembers only a successful result for that run. Failure writes an explicit failed step/log directing the caller to ELOWEN_TEST_WORKERS=2, never an unweighted four-worker execution or automatic fallback. The legacy helper can forward -n 2 true to nice, so that command is deliberately not a capability probe. The worker-policy fixtures record fake gate argv and cover full/focused/env-two routing, invalid input, one capability query per run and unsupported hosts; they never launch a four-worker suite.

scripts/tests/slowest.mjs is a read-only consumer of built-in Vitest/Playwright JSON, JUnit XML and the step manifest. It validates consumed fields through Zod and parses XML with the existing fast-xml-parser dependency. File timing is a Vitest wall span or summed Playwright/JUnit test durations, not a whole-process profiler. Failed-file commands require the original config, environment and confinement; native Node JUnit omits filenames and therefore cannot supply file-level attribution. See Timing reports for commands.

tests/contract/testReports.int.test.ts exercises malformed inputs, nested/root-level JUnit cases, duration units, shell quoting, failed collections, Playwright attempts, step tee/exit preservation, blocked steps, isolation arguments and ownership-scoped retention using temporary synthetic jobs. It never imports the CLI entry as an instruction to run the workflow. A single PostgreSQL cluster started JSON identity after each physical start and the existing PostgreSQL reset cost counters allow baseline comparison without changing reset or cluster ownership.

PostgreSQL repository tests use the isolated cluster and async database harness exported by elowen-db/testing. Query and index assertions target the real PostgreSQL schema. Pool sizes come from DEFAULT_HARNESS_CONFIG. See Persistence for repository transaction and bounded-read rules.

Reusable worker access has one URL owner: WorkerDatabase.connectionUrl. openDb(':memory:') marks that worker touched; a caller opening its own process pool requests testDatabaseUrl() for that test instead, as tests/daemon/postgres.ts does. The setup calls resetIfTouched() in beforeEach: every isolated file resets first because its pool id may be recycled, then only boundaries after worker access reset. Untouched/fresh-only tests leave the clean worker alone. Fresh clones still contain migration seeds, while reset removes application rows and restarts identities without restoring seeds or schema. Finalizers close handles and drop fresh clones on the existing boundary; this optimization adds no pool, retry, isolation or timeout policy. packages/db/tests/workerLifecycle.int.test.ts covers direct URL access and recycled ids; workerSetup.test.ts verifies actual hook/reset counts across worker, pure and fresh-only cases.

Root caller fixtures share the injected PostgreSQL cluster rather than starting per-domain postmasters. freshTestConnectionUrl() delegates UUID clone creation and cleanup registration to the root worker without opening another pool; callers close their own core pools in onTestFinished callbacks registered after root setup. Vitest runs these callbacks LIFO, before the root clone-drop callback, even after a nested afterEach fails. Brain/API fixtures keep private suite instance directories; session fixtures use independent clones with migration readiness seeds and explicit user seeds. tests/contract/postgresFinalizer.int.test.ts exercises the failed-hook path against real PostgreSQL. Schema-changing fault tests must call the existing useBrainPostgres opener with { fresh: true }; row reset cannot undo a constraint, function, trigger or standalone sequence. tests/brain/persistence.int.test.ts and tests/brain/subagentCompletionAtomic.int.test.ts are real consumers. tests/contract/schemaFaultIsolation.int.test.ts runs these actual writers followed by a priced-usage consumer in separate isolated invocations, checks the recycled pool id and shared cluster identity, and proves the fault objects are absent. Its private cluster exists only to keep child pool ids distinct from the enclosing test run; it changes no worker, isolation, retry or timeout policy.

openPluginHostDatabase() in tests/plugins/fixtures/postgres.ts owns a separate WorkerDatabase clone registry over that same cluster. It never resets a reusable worker: beforeAll hosts retain rows and pools until afterAll closes all core pools, then drops their UUID clones. tests/plugins/alertSeam.int.test.ts needs this suite lifetime. Fresh-URL creation costs one template clone, not a new postmaster. With no caller there is no clone. Exclusive clusters remain necessary for installation database-policy tests that change server configuration, package migration-history fixtures and standalone daemon/browser/benchmark harnesses; sharing only applies to root callers.

Runner IPC tests use FakeChild from tests/subagent/fakeChild.ts to record daemon frames and kill signals without forking a brain. Instantiate FakeChild, pass child.asChild() to the host's fork seam, and drive replies through child.reply(frame). kill records a signal but does not emit exit; die defaults to code 1, sets connected=false and emits exit. Nothing happens unless a test drives the fake. The fake has pid 0 and starts no operating-system process; it only models the IPC/event surface used by these tests. Scenario-specific boot, turn and finish helpers stay local. queuedAbort specializes die to code 0, while elowenApiRpc preserves its no-op kill. A real consumer is tests/subagent/runnerHost.int.test.ts.

Shared brain, alert and fork fixtures

alertServiceFixture(store, catalog) in tests/helpers/alertService.ts builds a real AlertService over a caller-owned store and catalog, with one administrator and no project members. Every push title is collected in the returned sent list. The update and maintenance alert suites (tests/alerts/report.int.test.ts and tests/daemon/maintenanceAlerts.int.test.ts) use it. The caller still owns the database and any temporary directory.

createForkedChildHarness() in tests/helpers/forkedChild.ts returns a controllable child for a node:child_process fork mock. Each suite registers its own vi.mock inside its vi.hoisted import, and the child records its kill signals and sent messages. Its pid is 0, so code that renices by pid never touches the test process. tests/brain/backgroundWorkerFork.int.test.ts, tests/brain/embedBatchWorker.int.test.ts and tests/brain/bootRecoveryChain.test.ts are consumers.

spawnerHarness(runtime, registry, toolAuthority?) in tests/helpers/spawnerHarness.ts builds the brain spawner over a caller's model runtime and plugin registry. childScope(allow) in the same file returns the frozen boundary of a delegated child whose tool allow-list the test supplies. The spawner tool-policy and skill-loading suites share it.

projectSwitchFixture(beforeApply) in tests/helpers/projectSwitchFixture.ts opens an in-memory store with a session and two host Projects. The optional beforeApply callback runs before a switch commits, and the notice and refusal suites share the fixture.

expectSamePromptPrefix(previous, next) in tests/helpers/promptPrefix.ts asserts that a later provider request keeps the earlier system prompt, tool list and messages as an unchanged prefix. The cache-respawn suites use it.

bootstrapUsageRegistrations(keyExpression) in tests/helpers/bootstrapUsageRegistration.ts parses src/daemon/bootstrap.ts with the TypeScript compiler and returns every providerUsage registration whose computed key matches, with its initializer. The calling contract test states how many matches it expects, so nothing is picked silently and nothing is matched by regex.

Private brain characterization boundaries

These exports are private test boundaries, not plugin extension points. Their production logic stays in its owning module; importing them does not register a hook, start work, or add a fallback. No test-specific behavior is selected at runtime.

  • Conversation targets: call isEligibleConversationTarget(row) to characterize ancestry and session-kind eligibility. The host projection uses it during list and resolve; emptiness and account visibility remain separate checks. tests/brain/conversationTargets.int.test.ts imports the predicate directly. Without the test import, createConversationTargets still uses the same predicate.
  • Dashboard digest: buildDigestPrompt(input), parseDigestReply(text), and shapeDigestPayload(raw) expose the generator's existing prompt, parsing, and cleanup stages to tests/brain/dashDigest.int.test.ts. DashDigestGenerator.run calls these stages during one background inference; a reply that cannot be parsed returns null and the generator marks the row failed. Helpers do not perform inference or persistence themselves, and existing prompt and store budgets remain unchanged.
  • Delegated prompt truncation: PROMPT_TRUNCATION_MARKER exposes the exact marker used by packDelegatedPromptAppend when a section exceeds its fair share of the existing prompt budget. tests/plugins/platforms.test.ts and tests/brain/subagentContext.test.ts assert that shortened sections remain visibly marked. Sections that fit are not marked; importing the constant performs no work.
  • Embedding worker: embedBatchInWorker(config, inputs, deps) is exported for tests/brain/embedBatchWorker.int.test.ts to characterize IPC replies, timeout, stopping, and usage. The production entry is embedBatchThroughWorker. Its dependency injection permits a fake fork and bounded test deadlines; absent overrides use the real fork and existing deadlines. Stop admission, malformed replies, and whole-batch failures reject rather than fabricate vectors.
  • Tool reason description: REASON_DESC is private to toolReason.ts and exported for the schema assertion in tests/brain/toolReason.test.ts. withReason applies it when composing eligible local object schemas; excluded tools remain unchanged. Importing the description does not augment a tool or execute a call.
  • External tool caps: MAX_EXTERNAL_TOOL_BYTES and MAX_EXTERNAL_DESCRIPTION_BYTES expose the existing 8,000-byte definition and 1,000-byte description bounds to tests/brain/toolSchemaCap.test.ts. capExternalToolSchema applies these bounds during tool composition only when registration metadata marks a tool external; internal tools retain identity. Oversized schemas become permissive object schemas while the external owner still validates calls. The constants do not expose configuration or perform work.
  • Vision fallback: decideVisionHop(input) remains the production export; VisionHop is a module-private result type. service/visionHop.ts consumes the decision through ConversationLifecycle.maybeVisionHop, called by BrainTurnRunner.send under its session lock. A configured distinct vision route can request an in-place respawn for an image turn, and a text turn on the fallback requests a return. No eligible transition yields action none; the pure decision itself never touches a session.
  • Goal completion: judgeGoalCompletion(text) owns the explicit start-of-line GOAL_DONE evidence contract used by GoalLoopService. Placeholder echoes and fenced examples do not complete a goal. Its contract comment belongs directly above the function; the placeholder helper keeps its own separate explanation. No sentinel yields done false.
  • Workflow terminal projection: terminalizeWorkflow(run) is shared by WorkflowResumeRecovery.resumeWorkflow after unsuccessful recovery and service/statusService.ts after a workflow is found not live. Recovery publishes the terminal state; the status reader projects it without writing. Finished and errored nodes retain their states, other nodes become error, and the top-level projection is cancelled. Successful recovery and live workflows do not use this projection; a daemon restart alone is not proof that a journaled DAG is unrecoverable.

Provider-brand regression fixtures

settings.provider-brand-icons.e2e.ts uses the existing design/seed harness with error collection before navigation. Old remote candidates receive their blocking policy or wrong content, rather than a generic successful SVG. Custom API endpoints require the visible inline glyph in both row and drawer; individual model marks retain exact same-origin asset-byte assertions. Request and console diagnostics remain unfiltered. Retain actual Chromium errorText and classify ORB only when observed.

Required integration checks cover both Studio skins, cs/sk/en, desktop and real touch mobile, endpoint changes, loading, API errors, retry and empty statistics. Run the complete provider-brand and provider-model scenarios against the combined implementation and inspect screenshots; fixture assertions alone do not establish a passing browser matrix or production web build. See the production contract.

Ephemeral computer baseline and physical-device checklist

scripts/tests/computer-recovery-e2e/run.mjs prepares only an acknowledged-mutation baseline on an ephemeral Linux/x64 paired executor. It reuses recovery-e2e/paired-executor.mjs and computer-model.mjs, not a separate executor or recovery framework. It performs one acknowledged Bash append and one model-side Read, checks one side effect, and retains the original native Project target and journal tool-call identities. It introduces no disconnect, retry or restart.

Within the required isolation boundary, with an independently prepared candidate selected by ELOWEN_E2E_DIST, invoke:

node scripts/tests/computer-recovery-e2e/run.mjs --target ephemeral --scenario acknowledged-mutation --output <new-file.json>

The runner never builds or installs. All three options are required; duplicate or unknown options, physical targets, URLs and credentials are not accepted. Output is create-only with mode 0600; an existing file is not overwritten. Evidence records the candidate dist SHA-256 (checked before and after), actual core/client and Files/Terminal versions, host OS, canonical connection observations, milestones, native session/assistant-entry/tool-call IDs and observed executor/effect counts. Unknown counters remain null; server-observed remote retry stays null, not an invented retry counter. Failure evidence retains the failed stage and error name, not raw errors that can contain ticket URLs.

evidence.test.mjs contains six pure Node checks for parsing, help without candidate startup, missing-candidate evidence, create-only output, strict evidence validation and canonical connection observations. These source checks do not execute the real-daemon baseline. The baseline itself is prepared, not E2E-verified. Even a future baseline status: passed keeps both recoveryAcceptance and physicalAcceptance literally not-run.

Physical-device acceptance remains a separate, unexecuted checklist:

Device Acknowledged mutation Loss/retry/restart Physical acceptance
Linux PC not-run not-run not-run
Windows notebook not-run not-run not-run
  • Record each real device's OS, actual core/client/plugin versions and candidate identity.
  • Verify the original native Project and journal identities, one mutation, model-side verification and one side effect on each device.
  • Run the separately authorized loss/retry/restart matrix on each device and retain actual connection observations and durable results; unknown counters stay unknown.

The ephemeral Linux/x64 fixture is neither physical Linux acceptance nor Windows emulation. The runner has no physical target or loss/retry/restart scenario; source checks and a baseline pass cannot complete this checklist.

Public declaration tooling

Public plugin-shared declarations consumed outside core are exact entries in the packages/plugin-shared workspace of knip.json. For example, add gitSha.d.mts beside the existing runtime *.mjs entry when publishing the adjacent exported module and declaration. The same model covers httpClient.d.mts, waitUnlessAborted.d.mts, singleflight.d.mts, configScalars.d.mts and the shared message catalogue's messages.d.mts. This applies only during static analysis and changes no runtime loading or plugin registration. An omitted declaration remains unmodeled as a public entry; do not replace its entry with an ignore. tests/contract/publicDeclarationEntries.test.ts checks the real published subpaths, shipped declarations and exact tooling entries. The web workspace has no usage-summary analysis exemption; the retired lib/effectiveSpeed.ts mirror is removed.

Registry boundary fixtures

The registry's onedriveIncompleteScan test injects managedFor: async () => null for a host mirror and extraIgnore: [] for no additional ignore rules. SyncEngine requires this resolver even when no managed mirror is present; null selects the existing host path. The fixture keeps real storage and synchronization while forcing scanLocal.complete to false, proving that an incomplete scan preserves baselines and performs neither uploads nor deletions.

The githubP58Flow fixture uses the real confirmation store and a mocked device-login starter. Repeated GitHubService.confirm calls for replace_identity reject with invalid_action and status 400 without consuming consent; startDeviceAuth then accepts that same token and consumes it. A changed identity snapshot is rejected and consumed only by device authentication. These fixtures do not contact GitHub or migrate customer secrets; github.test.ts covers the corresponding HTTP route.

The registry repository's test-only SelectMenu in tests/ui/host/pickers.tsx exposes value, onChange, options, label and optional disabled. Without disabled it remains interactive; disabled locks the native select. It has no invalid option or aria-invalid projection. Registry plugin UI tests install it through tests/ui/hostRuntime.tsx, including GitHub Project tests. This native-select fixture checks selection and accessible names, while the real host's Radix keyboard, focus and styling contract requires browser acceptance.

Shared scripted transports and fixtures

sseStream.openSessionStream(baseUrl, token, session) returns { state, close }; state counts idle/compacted events and retains error messages/workflow events in arrival order. Minimal use is const { state, close } = await openSessionStream(baseUrl, token, session). Without a call, no stream opens. close aborts immediately without awaiting the reader; callers own predicates/deadlines. Continuity, hooks, subagent and workflow suites import it as openStream. managedWorkflowModel consumes readJson, contentText, startCompletionStream, endCompletionStream and completionFrames from scriptedOpenAi rather than duplicating the wire.

tmux-evidence/diagnostics.percentile(values, fraction) is the shared nearest-rank helper used by CLI pipeline/render benchmarks. percentile(samples, 0.95) returns zero for empty input; ordinary fractions are greater than zero and at most one.

Plugin tests use typed lookup/invocation from tests/helpers/pluginTool.ts, keeping call IDs, result types, scopes and execution contexts at the caller. tempDirs.ts registers per-suite cleanup while callers own DB/environment teardown order. environmentRuntimeFake.ts shares machine/disk state and base methods; transport, socket, readiness and resource overrides stay explicit. Importing it installs neither cleanup nor a module mock.

Monaco preparation checks source availability before touching public output. copyMonaco.test.ts executes the actual script in temporary fixtures, proving a missing installation preserves the destination. Root web compilation still reaches .ts-importing E2E helpers through Vitest dependencies; excluding entry globs does not remove those edges.

Production analysis and platform identity indexes

Production analysis includes scripts/**/*.mjs! and uses !scripts/tests/**! to exclude test harnesses while retaining existing entries and ignoreExportsUsedInFile. tests/contract/platformIdentityContract.int.test.ts opens an isolated PostgreSQL database through tests/api/postgres.ts and inspects pg_index, pg_class and pg_namespace for elowen.user_settings. It checks the generic unique (key,value) index under the literal platformLink: prefix. Migration fixtures in packages/db/tests/config/platformIdentityMigration.int.test.ts inspect actual ephemeral PostgreSQL indexes, absence of all four historical indexes, exact values/full-precision timestamps, collision rollback and ledger replay. Sender normalization fixtures belong to each plugin; repository fixtures supply canonical synthetic platform values. Never run these fixtures against a host database.

Persona wording contracts

Persona wording contracts use personaTemplatesFor({ scheduled: false, ownerChatShape: true }).parts to select the shipped default owner persona. renderTemplate.test.ts and promptTemplateContracts.test.ts retain their own wording assertions; promptAdoptedGuidance.md independently pins required guidance and must be updated explicitly when wording intentionally changes. The plugin-tool reference contract checks the unique default interactive parts, the returned platform overlay when present, and scheduled parts. With no overlay, no overlay template is checked. Plugin-selected work templates remain outside this default-template contract. personaRoute.test.ts owns exact part order and plugin work-template substitution; wording tests do not introduce another route resolver.