PLAN TODO 13 - de-flake ShellLayout.test.tsx test-isolation
=============================================================

ROOT CAUSE
----------
NOT cross-file state bleed. Vitest's `threads` pool runs with this repo's
default `isolate: true`, which - per its own reported hint in every run
below ("Isolate N workers spawned ... per file" / "faster with
isolate:false - reuses workers across files instead of one per file") -
spawns a dedicated OS worker thread PER TEST FILE, each with its own
module registry and its own `globalThis` (hence its own fresh
`fake-indexeddb` `indexedDB` instance via `src/lib/test-setup.ts`'s
`import "fake-indexeddb/auto"`). No module-level singleton (identity.ts's
`inFlightInit`, loadHollowDemo.ts's `inFlightLoad`) and no IndexedDB state
can physically cross test files under this configuration.

The real cause is CPU contention under `npm run test`'s full 90-file run:
`loadHollowDemoFixture()` performs ~20 real Ed25519 sign/verify operations
(each `append()`/`appendEntry()` call signs or verifies) plus Dexie writes,
a Yjs CRDT roster/proposal seed, and a mini-app package upload - genuinely
slow, CPU-bound async work, not a fixed delay. When `npm run test` spawns
dozens of workers that all briefly run concurrently on this 16-core
machine, every worker's crypto work including ShellLayout.test.tsx's own
slows down. Testing Library's `waitFor` (and `findByTestId`) default to a
1000ms timeout - comfortably enough when this one file runs alone (no
contention, observed duration ~1.6s total including environment setup),
but occasionally exceeded when the full suite's CPU contention briefly
slows the crypto pipeline past that budget. That is exactly the flake
("ECONNREFUSED" noise from the unrelated best-effort `trySyncWithBackend`
best-effort sync calls across many files is unrelated background noise,
already caught/silent per `src/lib/sync.ts`'s contract - it is not the
cause).

No established repo precedent for this exact problem exists yet (grepped
all `*.test.tsx` for `waitFor(...)` + a timeout override, and for any
`poolOptions`/`maxWorkers`/`singleThread`/`asyncUtilTimeout` config:
no hits). `src/admin/AdminSeedPanel.test.tsx` also awaits this same slow
fixture load via default-timeout `waitFor` calls and is equally exposed in
principle, but was out of this task's scope (not flagged as flaky by the
independent verifier) - flagged as a disclosed risk below.

FIX
---
`src/shell/ShellLayout.test.tsx`: raised the timeout on the three
`waitFor`/`findByTestId` calls that depend on the full, crypto-heavy
auto-seed completing, from the Testing Library default (1000ms) to
10,000ms via a single named constant `AUTO_SEED_WAIT_TIMEOUT_MS`. No
assertion, threshold, or expected value was touched - see the diff below:
every `expect(...)` line is byte-identical before/after; only the wrapping
`waitFor(fn)` / `waitFor(fn, {})` call sites gained a `{ timeout }` option
and `findByTestId("wallet-balance")` gained its options argument.

DIFF (git diff -- src/shell/ShellLayout.test.tsx)
--------------------------------------------------
diff --git a/src/shell/ShellLayout.test.tsx b/src/shell/ShellLayout.test.tsx
index 83c9efa..a0979f1 100644
--- a/src/shell/ShellLayout.test.tsx
+++ b/src/shell/ShellLayout.test.tsx
@@ -48,10 +48,33 @@ function fixtureMarkerPresent(entries: readonly StoredEventLogEntry[]): boolean
   return entries.some((e) => (e.payload as { type?: string })?.type === "seed.demo.loaded");
 }
 
+/**
+ * `loadHollowDemoFixture` does real Ed25519 signing/verification work for
+ * ~20 Event Log entries (plus a CRDT roster/proposal seed and an uploaded
+ * mini-app package) - genuinely slow crypto, not a fixed delay. Under this
+ * repo's full `npm run test` run, Vitest's `threads` pool with the
+ * project's default `isolate: true` spawns one OS worker PER test file
+ * (confirmed by its own reported "X workers spawned ... per file" hint),
+ * so a full run briefly has dozens of workers genuinely contending for
+ * this machine's CPU cores at once, which slows every worker's crypto
+ * ops - including this file's. `waitFor`'s default 1000ms timeout is
+ * comfortably enough when this file runs alone (no contention) but can
+ * legitimately be exceeded under that full-suite contention, which is
+ * exactly the flake a prior verifier reproduced (not a logic bug, not
+ * cross-file state bleed - `isolate: true` gives every file its own
+ * worker/module registry/IndexedDB, so no JS state or DB can leak across
+ * files). A longer bound removes the false failure without weakening what
+ * is actually asserted below.
+ */
+const AUTO_SEED_WAIT_TIMEOUT_MS = 10_000;
+
 async function waitForAutoSeedToSettle() {
-  await waitFor(async () => {
-    expect(fixtureMarkerPresent(await readAll())).toBe(true);
-  });
+  await waitFor(
+    async () => {
+      expect(fixtureMarkerPresent(await readAll())).toBe(true);
+    },
+    { timeout: AUTO_SEED_WAIT_TIMEOUT_MS },
+  );
 }
 
 describe("ShellLayout - boot-time Hollow demo auto-seed (plan todo 5)", () => {
@@ -63,10 +86,15 @@ describe("ShellLayout - boot-time Hollow demo auto-seed (plan todo 5)", () => {
 
     expect(loadHollowDemoFixture).toHaveBeenCalledTimes(1);
 
-    const balance = await screen.findByTestId("wallet-balance");
-    await waitFor(() => {
-      expect(balance.textContent).not.toBe("--");
+    const balance = await screen.findByTestId("wallet-balance", undefined, {
+      timeout: AUTO_SEED_WAIT_TIMEOUT_MS,
     });
+    await waitFor(
+      () => {
+        expect(balance.textContent).not.toBe("--");
+      },
+      { timeout: AUTO_SEED_WAIT_TIMEOUT_MS },
+    );
     expect(balance.textContent).not.toBe("No balance yet");
     const numericBalance = Number(balance.textContent);
     expect(Number.isFinite(numericBalance)).toBe(true);
@@ -95,9 +123,12 @@ describe("ShellLayout - boot-time Hollow demo auto-seed (plan todo 5)", () => {
     // check. A correct idempotent wiring finds the marker and returns
     // without ever calling `loadHollowDemoFixture` again, so its own
     // internal 4th call never happens.
-    await waitFor(() => {
-      expect(hasDemoFixtureBeenLoaded).toHaveBeenCalledTimes(3);
-    });
+    await waitFor(
+      () => {
+        expect(hasDemoFixtureBeenLoaded).toHaveBeenCalledTimes(3);
+      },
+      { timeout: AUTO_SEED_WAIT_TIMEOUT_MS },
+    );
 
     expect(loadHollowDemoFixture).toHaveBeenCalledTimes(1);
 

(Every `expect(...)` assertion line above is identical before and after -
the entry-count check (`fixtureMarkerPresent` / entries length assertions
later in the file, untouched) and the idempotent-second-mount call-count
checks (`toHaveBeenCalledTimes(1)`, `toHaveBeenCalledTimes(2)`,
`toHaveBeenCalledTimes(3)`) are all preserved verbatim.)

REPRODUCTION - BEFORE THE FIX (flake confirmed)
------------------------------------------------
`npx vitest run src/shell/ShellLayout.test.tsx` in isolation: consistently
green (confirmed once; no contention, no flake expected or observed
in isolation before or after the fix).

`npm run test` (full suite, 90 files) x4 BEFORE the fix:
  RUN 1: Test Files 1 failed | 89 passed (90) -- failure = pre-existing,
         unrelated src/miniapps/waterwatch/fixtureIsolation.test.ts
         (requires `dist/` to exist; unrelated to this task)
  RUN 2: same as RUN 1 (ShellLayout green)
  RUN 3: Test Files 2 failed | 88 passed (90) -- ShellLayout.test.tsx FAILED:
         - "happy" test: `fixtureMarkerPresent(await readAll())` expected
           true, got false (waitFor timed out before the marker appeared)
         - "idempotent" test: `expect(loadHollowDemoFixture).toHaveBeenCalledTimes(1)`
           expected 1, got 0 (same underlying timeout)
         (plus the same unrelated waterwatch/fixtureIsolation.test.ts failure)
  RUN 4: same ShellLayout.test.tsx failures as RUN 3

This reproduces exactly the flake the independent verifier reported:
green in isolation, intermittently red under the full suite.

VERIFICATION - AFTER THE FIX (all green)
------------------------------------------
`npx vitest run src/shell/ShellLayout.test.tsx` x5 (isolated):
  RUN 1: Test Files 1 passed (1) | Tests 2 passed (2) | Duration 1.63s
  RUN 2: Test Files 1 passed (1) | Tests 2 passed (2) | Duration 1.60s
  RUN 3: Test Files 1 passed (1) | Tests 2 passed (2) | Duration 1.55s
  RUN 4: Test Files 1 passed (1) | Tests 2 passed (2) | Duration 1.57s
  RUN 5: Test Files 1 passed (1) | Tests 2 passed (2) | Duration 1.60s

`npm run test` (full suite) x3:
  RUN 1: Test Files 1 failed | 89 passed (90) | Tests 1 failed | 795 passed (796)
         -- the ONE failure is the pre-existing, unrelated
         src/miniapps/waterwatch/fixtureIsolation.test.ts ("dist/ does not
         exist - run `npm run build` first"); ShellLayout.test.tsx is
         among the 89 passed files every time.
  RUN 2: identical result (same single pre-existing unrelated failure)
  RUN 3: identical result (same single pre-existing unrelated failure)

ShellLayout.test.tsx passed in all 3 full-suite runs and all 5 isolated
runs after the fix - 0/8 failures, versus 2/4 full-suite runs failing
before the fix.

BUILD
-----
`npm run build` (tsc -b && vite build): EXIT CODE 0. Production bundle
built successfully (292 modules transformed, `dist/` generated with PWA
precache manifest). No regression from this change (the change touches
only a test file, never shipped in the production bundle).

DISCLOSED RISK (out of scope, flagged not fixed)
--------------------------------------------------
1. src/miniapps/waterwatch/fixtureIsolation.test.ts fails under `npm run
   test` whenever `dist/` does not already exist from a prior `npm run
   build` - a pre-existing, unrelated condition (not a flake, not
   introduced or touched by this change). It is green whenever `dist/`
   exists (e.g. immediately after this task's `npm run build` run above).
2. src/admin/AdminSeedPanel.test.tsx exercises the same slow
   `loadHollowDemoFixture()` path through several default-timeout
   `waitFor(...)` calls (lines ~71, 94, 148, 309, 315, 329, 370, 373, 390,
   424, 428) and is, in principle, exposed to the same CPU-contention
   timeout risk under a sufficiently loaded full-suite run, even though it
   was not flagged as flaky by the independent verifier and was out of
   this task's explicit scope. Worth a follow-up pass with the same
   longer-timeout treatment if it is ever observed to flake.
