Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

test([test-autosubscribe-fanout-getpeers-guard-remaining]): guard record-creating suites from peer fan-out

Adam Eivy707896f790fa
diff --git a/CLAUDE.md b/CLAUDE.md
index 5df4b7cfdb..9f61866588 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -233,6 +233,7 @@ When CoS agents or AI tools work on managed apps outside PortOS, all research, p
- **Async PATCH races on shared records — serialize writes server-side.** When two write paths can mutate the same record concurrently (e.g. a blur-save plus an explicit "Render" button against `stages.comicPages.cover`), client-side guards (refs, `onMouseDown`, status checks) are unreliable — keyboard activation, status==='unknown' stalls, and `loadState → modify → saveState` interleaving all defeat them. The correct fix is to serialize writes at the *file* level on the server (every PATCH awaits the previous one to settle before reading state, so it merges against the freshest persisted record). See `issueWriteTail` in `server/services/pipeline/issues.js`. A `Map<recordId, Promise>` is *not* enough — two writes to different record ids share the same JSON state file and can still clobber each other; collapse the queue to a single tail per shared file.
- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.reference/prompts/stages/*.md` file, also add an entry to `scripts/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. The drift warning in `scripts/setup-data.js` distinguishes auto-updatable (matches old shipped hash) from customized (matches neither) — when adding to the migrated list, mirror both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` there too so the warning stays actionable. Migration scripts live in `scripts/migrations/`; the per-install applied-list is `data/migrations.applied.json` (gitignored runtime state). See `scripts/migrations/003-update-pipeline-stage-prompts.js`.
- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `cosAgents.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.
+- **Record-creating tests must disable live peer fan-out.** Any Vitest suite that calls `createUniverse` or `createSeries` for non-ephemeral fixtures must mock `services/instances.js` with `mockNoPeers()` from `server/lib/mockPathsDataRoot.js`. Those create paths fire a background `autoSubscribeRecordToAllPeers` import; without a `getPeers → []` guard, the post-return microtask can read the real peer registry and leak fixtures into real `data/`.
- **Socket event-driven state — don't pre-clear before the server confirms.** When swapping which entity a socket-driven UI is showing (shell session, agent run, etc.), wait for the server's success event to drive the swap atomically; the error event is the recovery point. Pre-clearing the local `*Ref` / visible state up front leaves the UI stranded on a dead URL when the success event never arrives (target died mid-request, server rejected the switch). Pair every `socket.on('X:error')` that follows a stateful request with a recovery branch that restores the previously-displayed state or falls back to a live alternative.
- **Single-subscriber socket resources need notify + recipient-relative advertise + filter + claim.** Some server-side resources (PTY shell sessions, etc.) intentionally store one attached socket and fan output to it. The contract: (1) emit `<resource>:detached` on the previous socket when a new socket takes over so the displaced client can drop its local view; (2) include an `attached: boolean` field on each list-entry payload, computed *relative to the recipient socket* (true only when bound to a different socket) — a globally-truthy `attached` makes a client's own sessions look unavailable to itself; (3) broadcast list updates from both attach AND detach paths; (4) auto-pick paths send `claim: true` and the server refuses to displace a different socket. Manual paths (tab click, deep-link URL) default to `claim: false` so explicit intent still wins. See `server/services/shell.js` for the canonical implementation.
- **Pending socket-request tracking — `{ target, generation }` ref.** When a stateful socket operation is in flight, track it as `{ target, generation }` and increment `generation` on every change. Response handlers gate on strict equality with `target` — null/stale/cancelled all fall through, so a cancelled-mid-flight response can't re-activate after the user moved on. Deferred work (`setTimeout` fallbacks) captures `generation` and aborts if it advanced. Pair every cancellation path with explicit `cancelPendingAttach()`-style helpers rather than overloading a `clearActiveSession()` helper — clearing the displayed entity and cancelling an in-flight request are *separate* concerns, and conflating them cancels user-initiated switches when an unrelated session dies. See `client/src/pages/Shell.jsx` `pendingAttachRef` for the pattern.
diff --git a/server/lib/README.md b/server/lib/README.md
index 0a1745b8e7..78f13f04c4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -173,5 +173,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
-| `mockPathsDataRoot.js` | Shared `vi.mock` factory for `PATHS.data → temp dir`. |
+| `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` and no-peer record creation guards. |
| `testHelper.js` | Test HTTP request helper. |
diff --git a/server/lib/mockPathsDataRoot.js b/server/lib/mockPathsDataRoot.js
index 8d62027962..c037017458 100644
--- a/server/lib/mockPathsDataRoot.js
+++ b/server/lib/mockPathsDataRoot.js
@@ -28,6 +28,8 @@
* - `makePathsProxy(actual, { dataRoot, extraOverrides? })` — used inside
* the test's own `vi.mock` factory. Returns the Proxy.
* - `createTempDataRoot()` — returns `{ tempRoot }` allocated under os.tmpdir().
+ * - `mockNoPeers(actual?, overrides?)` — shared `instances.js` mock guard
+ * for record-creating tests that should never auto-subscribe to live peers.
*
* Migration: tests that need MULTIPLE PATHS members redirected
* (e.g. `images`, `videos`) can pass `extraOverrides` (object or function)
@@ -84,6 +86,25 @@ export function makePathsProxy(actual, { dataRoot, extraOverrides = null, overri
});
}
+/**
+ * Build an `instances.js` mock that disables peer auto-subscribe fan-out.
+ *
+ * `createUniverse` / `createSeries` fire a non-awaited peerSync import after
+ * record creation. In tests, that background path can outlive local fileUtils
+ * mocks and read the real peer registry unless `getPeers` is explicitly
+ * guarded. Pass the real module as `actual` when a suite needs the other
+ * exports, and pass `overrides` for test-specific exports like getInstanceId.
+ */
+export function mockNoPeers(actual = {}, overrides = {}) {
+ return {
+ UNKNOWN_INSTANCE_ID: 'unknown',
+ getInstanceId: () => Promise.resolve('test-instance'),
+ ...actual,
+ getPeers: () => Promise.resolve([]),
+ ...overrides,
+ };
+}
+
/**
* Convenience wrapper for the most-common case: a single per-file temp dir
* plus a Proxy factory. Returns `{ tempRoot, makeProxy, cleanup }` where
diff --git a/server/lib/mockPathsDataRoot.test.js b/server/lib/mockPathsDataRoot.test.js
index 039dbb7960..ceaea73941 100644
--- a/server/lib/mockPathsDataRoot.test.js
+++ b/server/lib/mockPathsDataRoot.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect, afterAll } from 'vitest';
import { existsSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { createTempDataRoot, makePathsProxy, mockPathsDataRoot } from './mockPathsDataRoot.js';
+import { createTempDataRoot, makePathsProxy, mockNoPeers, mockPathsDataRoot } from './mockPathsDataRoot.js';
describe('mockPathsDataRoot', () => {
describe('createTempDataRoot', () => {
@@ -84,4 +84,16 @@ describe('mockPathsDataRoot', () => {
expect(existsSync(tempRoot)).toBe(false);
});
});
+
+ describe('mockNoPeers', () => {
+ it('preserves instances exports while forcing getPeers to []', async () => {
+ const mock = mockNoPeers(
+ { getPeers: async () => [{ instanceId: 'real-peer' }], getInstanceId: async () => 'real-id' },
+ { getInstanceId: async () => 'test-id' },
+ );
+
+ await expect(mock.getPeers()).resolves.toEqual([]);
+ await expect(mock.getInstanceId()).resolves.toBe('test-id');
+ });
+ });
});
diff --git a/server/services/importer.test.js b/server/services/importer.test.js
index f1c30bae35..2089d9b4e0 100644
--- a/server/services/importer.test.js
+++ b/server/services/importer.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync, readdirSync, unlinkSync, existsSync, statSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
+import { mockNoPeers } from '../lib/mockPathsDataRoot.js';
// Create the tempRoot at top-level so PATHS.data resolves before any
// service module runs its `const STATE_PATH = join(PATHS.data, ...)` at
@@ -50,10 +51,7 @@ vi.mock('../lib/fileUtils.js', async () => {
// bypassing our PATHS mock above). Defense-in-depth: even with explicit
// ephemeral:true on the direct fixtures, downstream production code may
// still create non-ephemeral records.
-vi.mock('./instances.js', async () => {
- const actual = await vi.importActual('./instances.js');
- return { ...actual, getPeers: () => Promise.resolve([]) };
-});
+vi.mock('./instances.js', () => mockNoPeers());
// Mock runStagedLLM so tests never hit a real provider — every importer
// LLM call resolves to a canned JSON shape we control per-test.
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 11a26e50bd..7cdaed8502 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
let stageRunnerSpy;
@@ -17,6 +18,8 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+vi.mock('../instances.js', () => mockNoPeers());
+
// Stub the staged-LLM runner so the test owns the LLM response shape.
// Each test sets `stageRunnerSpy = vi.fn(...)` to control what comes back.
vi.mock('../../lib/stageRunner.js', () => ({
diff --git a/server/services/pipeline/autoRunner.test.js b/server/services/pipeline/autoRunner.test.js
index 642868c080..3e52a75411 100644
--- a/server/services/pipeline/autoRunner.test.js
+++ b/server/services/pipeline/autoRunner.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
@@ -16,6 +17,8 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+vi.mock('../instances.js', () => mockNoPeers());
+
// Inline generator that flips the stage to ready without doing any real work.
// We're testing the coordinator, not the LLM call site.
const generated = [];
diff --git a/server/services/pipeline/coverUniverseFiler.test.js b/server/services/pipeline/coverUniverseFiler.test.js
index 80c3659f0f..61047664f5 100644
--- a/server/services/pipeline/coverUniverseFiler.test.js
+++ b/server/services/pipeline/coverUniverseFiler.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
@@ -18,6 +19,8 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+vi.mock('../instances.js', () => mockNoPeers());
+
const collections = await import('../mediaCollections.js');
const seriesSvc = await import('./series.js');
const universeSvc = await import('../universeBuilder.js');
diff --git a/server/services/pipeline/episodeVideo.test.js b/server/services/pipeline/episodeVideo.test.js
index a0382943be..19e93fcfdb 100644
--- a/server/services/pipeline/episodeVideo.test.js
+++ b/server/services/pipeline/episodeVideo.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
@@ -16,6 +17,8 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+vi.mock('../instances.js', () => mockNoPeers());
+
const cdCreated = [];
const cdTreatments = [];
vi.mock('../creativeDirector/local.js', () => ({
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index 6fd7327208..2a14d3ad14 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
@@ -16,6 +17,8 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+vi.mock('../instances.js', () => mockNoPeers());
+
const svc = await import('./issues.js');
const seriesSvc = await import('./series.js');
const seasonsSvc = await import('./seasons.js');
diff --git a/server/services/pipeline/migrateSeriesCanon.test.js b/server/services/pipeline/migrateSeriesCanon.test.js
index dd32e9e336..4dcf0fd8ad 100644
--- a/server/services/pipeline/migrateSeriesCanon.test.js
+++ b/server/services/pipeline/migrateSeriesCanon.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const ERR_DUPLICATE = 'DUPLICATE';
const ERR_NOT_FOUND = 'NOT_FOUND';
@@ -41,6 +42,7 @@ vi.mock('../../lib/fileUtils.js', () => ({
PATHS: { data: '/mock/data' },
readJSONFile: vi.fn(async (_p, fallback) => fallback),
}));
+vi.mock('../instances.js', () => mockNoPeers());
const { applyLegacySeriesCanonToUniverse, deriveOrphanUniverseId } = await import('./migrateSeriesCanon.js');
const universeBuilder = await import('../universeBuilder.js');
diff --git a/server/services/pipeline/seasons.test.js b/server/services/pipeline/seasons.test.js
index ea8b11d52c..f706c44e06 100644
--- a/server/services/pipeline/seasons.test.js
+++ b/server/services/pipeline/seasons.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
@@ -16,6 +17,8 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+vi.mock('../instances.js', () => mockNoPeers());
+
const seriesSvc = await import('./series.js');
const issuesSvc = await import('./issues.js');
const svc = await import('./seasons.js');
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index f87dcdf9a2..e62f87d679 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
@@ -16,6 +17,8 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+vi.mock('../instances.js', () => mockNoPeers());
+
const svc = await import('./series.js');
describe('pipeline series service', () => {
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
index f88dcf583c..5285abea99 100644
--- a/server/services/pipeline/textStages.test.js
+++ b/server/services/pipeline/textStages.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
@@ -16,6 +17,8 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+vi.mock('../instances.js', () => mockNoPeers());
+
const llmCalls = [];
vi.mock('../providers.js', () => ({
diff --git a/server/services/pipeline/volumeBeatsRunner.test.js b/server/services/pipeline/volumeBeatsRunner.test.js
index 5186f12b6b..70f72e46c6 100644
--- a/server/services/pipeline/volumeBeatsRunner.test.js
+++ b/server/services/pipeline/volumeBeatsRunner.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
@@ -16,6 +17,8 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+vi.mock('../instances.js', () => mockNoPeers());
+
// Inline generator that writes ready beats without making an LLM call —
// we're testing the coordinator, not the prompt.
const generated = [];
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 61337eeaba..c896d5e001 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -13,6 +13,7 @@ import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync, readFileSync
import { tmpdir } from 'os';
import { join } from 'path';
import { createHash } from 'crypto';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
function sha256Hex(buf) {
return createHash('sha256').update(buf).digest('hex');
@@ -41,7 +42,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
// Stub instances.getInstanceId so the exporter doesn't try to read the
// real identity.json. Returns a fixed id for assertions.
-vi.mock('../instances.js', () => ({
+vi.mock('../instances.js', () => mockNoPeers({}, {
getInstanceId: () => Promise.resolve('test-instance-id'),
UNKNOWN_INSTANCE_ID: 'unknown',
}));
diff --git a/server/services/sharing/subscriptions.test.js b/server/services/sharing/subscriptions.test.js
index bb0d526209..b41eda5d3f 100644
--- a/server/services/sharing/subscriptions.test.js
+++ b/server/services/sharing/subscriptions.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
+import { mockNoPeers } from '../../lib/mockPathsDataRoot.js';
// Universe builder evaluates PATHS.data at module top, so allocate a stable
// temp dir before any service imports. beforeEach wipes + reseeds inside.
@@ -22,7 +23,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
},
});
});
-vi.mock('../instances.js', () => ({
+vi.mock('../instances.js', () => mockNoPeers({}, {
getInstanceId: () => Promise.resolve('inst-test'),
UNKNOWN_INSTANCE_ID: 'unknown',
}));
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 2a7dcf4323..0511aabc21 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -3,6 +3,7 @@ import { mkdtempSync, rmSync, mkdirSync } from "fs";
import { writeFile, mkdir } from "fs/promises";
import { tmpdir } from "os";
import { join } from "path";
+import { mockNoPeers } from "../lib/mockPathsDataRoot.js";
// Real per-suite tmpdir backing the universes/ layout. Each test wipes the
// tree in beforeEach. The fileUtils mock below overrides PATHS.data so the
@@ -43,10 +44,7 @@ vi.mock("../lib/fileUtils.js", async (importOriginal) => {
// non-ephemeral fixture (e.g. "Moebius SciFi") initial-pushes it across the
// federation and the receiving instance persists it into the real data/universes/.
// Mirrors the same guard in importer.test.js and writersRoom/promoteToPipeline.test.js.
-vi.mock("./instances.js", async () => {
- const actual = await vi.importActual("./instances.js");
- return { ...actual, getPeers: () => Promise.resolve([]) };
-});
+vi.mock("./instances.js", () => mockNoPeers());
// Pre-seed state into the new per-record layout. Mirrors what migration 034
// produces — each universe lands in `universes/<id>/index.json` and the
diff --git a/server/services/universeBuilderAutoSort.test.js b/server/services/universeBuilderAutoSort.test.js
index f1aed602c9..4b33faec1f 100644
--- a/server/services/universeBuilderAutoSort.test.js
+++ b/server/services/universeBuilderAutoSort.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeers } from '../lib/mockPathsDataRoot.js';
// In-memory file store mirrors universeBuilderPromote.test.js so a single
// readState/writeState path roundtrips through the same code the real
@@ -19,6 +20,8 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+vi.mock('./instances.js', () => mockNoPeers());
+
const resolveProviderAndModelMock = vi.fn();
const runPromptThroughProviderMock = vi.fn();
vi.mock('../lib/promptRunner.js', () => ({
diff --git a/server/services/universeBuilderCollectionHook.test.js b/server/services/universeBuilderCollectionHook.test.js
index 2494afa108..66ccbddcc2 100644
--- a/server/services/universeBuilderCollectionHook.test.js
+++ b/server/services/universeBuilderCollectionHook.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
+import { mockNoPeers } from '../lib/mockPathsDataRoot.js';
const tempData = mkdtempSync(join(tmpdir(), 'portos-ubhook-test-data-'));
@@ -24,10 +25,7 @@ vi.mock('../lib/fileUtils.js', async () => {
// to real peers via peerSync's autoSubscribeRecordToAllPeers (instances.js
// uses dataPath whose closure points at REAL PATHS, bypassing the mock
// above).
-vi.mock('./instances.js', async () => {
- const actual = await vi.importActual('./instances.js');
- return { ...actual, getPeers: () => Promise.resolve([]) };
-});
+vi.mock('./instances.js', () => mockNoPeers());
const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
const collections = await import('./mediaCollections.js');
diff --git a/server/services/universeBuilderPromote.test.js b/server/services/universeBuilderPromote.test.js
index 8fabb3821a..65ece5b573 100644
--- a/server/services/universeBuilderPromote.test.js
+++ b/server/services/universeBuilderPromote.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import { rmSync, mkdirSync } from 'fs';
-import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
+import { mockNoPeers, mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
// `wrapExports: ['atomicWrite']` exposes a delegating vi.fn at
// `spies.atomicWrite` so the atomicity test can count writes WITHOUT
@@ -28,10 +28,7 @@ vi.mock('crypto', async () => {
// doesn't fan the fixture out to real peers (getPeers reads the live registry via a
// dataPath closure to the real PATHS once the post-return microtask runs outside this
// file's fileUtils mock window). Mirrors importer.test.js / promoteToPipeline.test.js.
-vi.mock('./instances.js', async () => {
- const actual = await vi.importActual('./instances.js');
- return { ...actual, getPeers: () => Promise.resolve([]) };
-});
+vi.mock('./instances.js', () => mockNoPeers());
// Stub the LLM dispatch so tests don't need a live runner. The
// `runPromptThroughProvider` mock is overridden per-test to return the
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index 99faf1adf0..07ef8c4553 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import { rmSync, mkdirSync } from 'fs';
-import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
+import { mockNoPeers, mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
// Real tmpdir backing the per-record store. `mockPathsDataRoot` redirects
// PATHS.data so collectionStore lands under tempRoot/universes/. Everything
@@ -33,10 +33,7 @@ vi.mock('crypto', async () => {
// doesn't fan the fixture out to real peers (getPeers reads the live registry via a
// dataPath closure to the real PATHS once the post-return microtask runs outside this
// file's fileUtils mock window). Mirrors importer.test.js / promoteToPipeline.test.js.
-vi.mock('./instances.js', async () => {
- const actual = await vi.importActual('./instances.js');
- return { ...actual, getPeers: () => Promise.resolve([]) };
-});
+vi.mock('./instances.js', () => mockNoPeers());
// The bible extractor + staged-LLM runner + prompt-refine helpers all reach
// out to live AI providers. Stub them to return deterministic shapes so we
diff --git a/server/services/writersRoom/promoteToPipeline.test.js b/server/services/writersRoom/promoteToPipeline.test.js
index 5cb3f5fcb0..66d2dc9bb0 100644
--- a/server/services/writersRoom/promoteToPipeline.test.js
+++ b/server/services/writersRoom/promoteToPipeline.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, rmSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+import { makePathsProxy, mockNoPeers } from '../../lib/mockPathsDataRoot.js';
let tempRoot;
@@ -15,10 +15,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
// createSeries/createIssue calls don't fan out to real peers via
// peerSync's autoSubscribeRecordToAllPeers (which reads the live peer
// registry through dataPath closure to the real PATHS).
-vi.mock('../instances.js', async () => {
- const actual = await vi.importActual('../instances.js');
- return { ...actual, getPeers: () => Promise.resolve([]) };
-});
+vi.mock('../instances.js', () => mockNoPeers());
const wrLocal = await import('./local.js');
const { promoteWorkToPipeline, ERR_NO_DRAFT_BODY } = await import('./promoteToPipeline.js');