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

fix(tests): stub getPeers in universe-creating tests to stop peer-sync fan-out leaking fixtures into real data/

Adam Eivya8dd4b4d5fa1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b5034ea7b8..9138c825b3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -19,5 +19,6 @@
## Fixed
- Providers (`/ai`) and Prompts (`/prompts`) pages now render the same Settings sub-nav tabbed header as the other settings pages, so users can hop between Backup / Database / General / MortalLoom / Prompts / Providers / Sharing / Telegram / Voice without going back to the sidebar. Extracted a shared `SettingsTabsHeader` component used by `Settings.jsx`, `AIProviders.jsx`, and `PromptManager.jsx`.
+- **Test fixtures no longer leak into the real `data/universes/` via peer-sync fan-out.** `createUniverse` fires a non-awaited `autoSubscribeRecordToAllPeers`, which reads the live peer registry through `instances.js#getPeers` — a `dataPath` closure that resolves to the REAL `PATHS.data` once the post-return microtask escapes a test's `fileUtils` mock window. Three universe-creating suites (`universeBuilder.test.js`, `universeBuilderPromote.test.js`, `universeCanon.test.js`) created non-ephemeral fixtures without stubbing `getPeers`, so their "Moebius SciFi" universes were pushed across the federation and persisted into real `data/` by receiving instances (and re-leaked intermittently on every run). Each suite now mocks `getPeers → []`, matching the existing guard in `importer.test.js` / `promoteToPipeline.test.js`. Remaining series/issue-creating suites with the same latent gap are tracked in PLAN.md (`[test-autosubscribe-fanout-getpeers-guard-remaining]`).
## Removed
diff --git a/PLAN.md b/PLAN.md
index d782c7aaea..639abff4d3 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -7,7 +7,8 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
- [ ] [data-versioning-split-pipeline-issues] **Split `data/pipeline-issues.json` → `data/pipeline-issues/{id}/index.json` via `collectionStore`.** Highest-value follow-up from the data-versioning POC (PR #458). File is ~1MB / 173 records and every panel/page edit rewrites the whole thing through `server/services/pipeline/issues.js`'s `issueWriteTail` single-file queue. Per-record split gives the comic pipeline real concurrent-write headroom — multiple `PATCH /api/pipeline/issues/:id` calls against different issues stop blocking each other. Migration `035-split-pipeline-issues-to-per-id.js` mirrors `034-split-universe-builder-to-per-uuid.js`: pre-flight scan, atomic per-record writes, monolithic file renamed to `pipeline-issues.json.bak-035`. Bump `PORTOS_SCHEMA_VERSIONS.pipelineIssues` (new key) in `server/lib/schemaVersions.js` and register the store in `server/index.js`'s `verifyCollectionVersions` boot call. Per-record `schemaVersion` (record shape) stays where it is. Audit consumers of `loadIssues()` / `saveIssues()`: every caller must move to `store.loadOne` / `store.saveOne` / `store.listIds` + parallel load. Cross-record state in `pipeline-issues.json` (if any beyond the array — check before migrating) moves into `data/pipeline-issues/index.json`'s `config` slot.
- [ ] [data-versioning-split-pipeline-series] **Split `data/pipeline-series.json` → `data/pipeline-series/{id}/index.json`.** Lower record count than issues (21 records) but same structural fix; do it in the same PR as `[data-versioning-split-pipeline-issues]` so the pipeline area lands at one consistent layout. Same migration shape (`036-split-pipeline-series-to-per-id.js`) — mostly a copy-paste of the issues migration with type swapped.
- [ ] [data-versioning-history-jsonl] **`data/history.json` → `data/history.jsonl` — proactive structural fix.** Data shape is append-only by definition; rewriting the whole array on every append is the wrong shape regardless of current size. Convert to line-delimited JSON so appends are O(1) instead of O(N) and `tail`-based reads / log rotation become trivial. Migration `037-history-json-to-jsonl.js`: read `data/history.json`, emit one line per entry, rename old file to `history.json.bak-037`. Add `appendJsonLine(path, obj)` + `readJsonLines(path, { from, limit })` helpers to `server/lib/fileUtils.js` (barrel + README) so `data/brain/digests.jsonl` and `data/brain/inbox_log.jsonl` (already JSONL but hand-rolled) can adopt the same primitives. Pair with a quick audit of other append-only-shaped monolithic files (`client-errors.json`?, `media-jobs.json`?) — convert any that match the shape in the same PR or a follow-up.
-- [ ] [ai-fallback-coalesce-concurrent-failures] **Coalesce concurrent AI provider failures so N simultaneous calls don't all re-read `providers.json` and re-mark the same provider.** Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22). When a stuck provider has N simultaneous in-flight calls, each failure independently runs `pickFallbackProvider` → `getAllProviders()` → `loadProviders()` (which reads `providers.json` from disk every time — no in-memory cache) → `markUnavailable` (writing `provider-status.json`). Two fixes that compound: (a) add a tiny TTL cache (~1s) to `aiToolkit/providers.js#loadProviders` so the read cost is amortized; (b) coalesce per-provider failure handling in `promptRunner.js` with a `Map<providerId, Promise>` so subsequent failures for the same provider await the first's mark-and-pick result and skip the duplicate work. Together they cut N-way failure storms to one disk-write + one mark. Acceptance: under a simulated 10-concurrent-failure load, providers.json is read at most twice and provider-status.json is written once.
+- [ ] [test-autosubscribe-fanout-getpeers-guard-remaining] **Apply the `getPeers → []` test stub to the remaining record-creating test files (and consider a shared guard).** Root-caused 2026-05-23: `createUniverse` (universeBuilder.js:939) and `createSeries` (pipeline/series.js:223) fire a non-awaited `import('./sharing/peerSync.js').then(autoSubscribeRecordToAllPeers)`. `autoSubscribeRecordToAllPeers` reads the live peer registry via `getPeers()` (instances.js, `dataPath` closure to the REAL PATHS), so any test that creates a non-ephemeral universe/series and does NOT mock `getPeers` fans the fixture out to real peers (void/null/NaN), which persist it into real `data/`. Fixed in `universeBuilder.test.js`, `universeBuilderPromote.test.js`, `universeCanon.test.js` (this is how the "Moebius SciFi"/uuid-0000 leak happened). **Still unguarded** (create subscribable records, no `getPeers` mock — verified via `grep -L getPeers` against the createUniverse/createSeries/createIssue caller set): `pipeline/arcPlanner.test.js`, `pipeline/autoRunner.test.js`, `pipeline/coverUniverseFiler.test.js`, `pipeline/episodeVideo.test.js`, `pipeline/issues.test.js`, `pipeline/migrateSeriesCanon.test.js`, `pipeline/seasons.test.js`, `pipeline/series.test.js`, `pipeline/textStages.test.js`, `pipeline/volumeBeatsRunner.test.js`, `sharing/subscriptions.test.js`, `sharing/integration.test.js`, `universeBuilderAutoSort.test.js` (the last is safe-by-accident: its synthetic in-memory fileUtils mock lacks `dataPath`, which breaks the peerSync import chain — but that's fragile). These create *series*, so they'd pollute `data/pipeline-series/` not `data/universes/` (no residue found yet, but same race). The `sharing/*` ones likely set up real peers intentionally — handle carefully (don't blanket-stub). **Better fix to evaluate:** a shared `mockNoPeers()` helper in `server/lib/mockPathsDataRoot.js` (or a vitest `setupFiles` default stub that individual sharing tests can override) so every new record-creating test is protected by default instead of relying on each author remembering. Add the `getPeers→[]` convention to CLAUDE.md's test section.
+- [ ] [prune-orphan-subscriptions-for-deleted-records] **Sweep orphaned peer subscriptions left by tombstone prune.** `pruneTombstonedUniverses` / `pruneTombstonedSeries` rm the record dir but leave its rows in `data/peer_subscriptions.json`. After the 2026-05-23 leaked-fixture cleanup (22 universes force-pruned), the matching subs are now orphaned — on `peer:online`, `retryPendingPushesForPeer` walks them, `loadOne` returns null, and the push no-ops (harmless but inflates the "retrying N pending pushes" count — saw 141). Add an orphan-subscription sweep (drop subs whose `recordKind/recordId` no longer resolves to an on-disk record) to the tombstone GC path, or call it from the prune helpers. Low urgency; cosmetic + minor wasted work per sync cycle. Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22). When a stuck provider has N simultaneous in-flight calls, each failure independently runs `pickFallbackProvider` → `getAllProviders()` → `loadProviders()` (which reads `providers.json` from disk every time — no in-memory cache) → `markUnavailable` (writing `provider-status.json`). Two fixes that compound: (a) add a tiny TTL cache (~1s) to `aiToolkit/providers.js#loadProviders` so the read cost is amortized; (b) coalesce per-provider failure handling in `promptRunner.js` with a `Map<providerId, Promise>` so subsequent failures for the same provider await the first's mark-and-pick result and skip the duplicate work. Together they cut N-way failure storms to one disk-write + one mark. Acceptance: under a simulated 10-concurrent-failure load, providers.json is read at most twice and provider-status.json is written once.
- [ ] [propagate-runner-errorAnalysis-into-onRunFailed-context] **Propagate `metadata.errorAnalysis` into the `onRunFailed` event context** so `promptRunner.js#markProviderUnavailableFromError` doesn't re-run `analyzeError` on the same text the runner already analyzed. The runner writes `errorAnalysis` to `metadata` (`server/lib/aiToolkit/runner.js:245`, 343, 433) but `server/index.js:202` only forwards a subset to the error event, so the analysis pass is duplicated on every failure. Either add `errorAnalysis` to the event context AND to the rejected error thrown to promptRunner, or attach it to the metadata object that the rejection carries. Microsecond-class perf, but cleaner. Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22).
- [ ] [upcoming-tasks-widget-drop-catch-to-empty] **Drop the `.catch(() => [])` in `UpcomingTasksWidget.jsx:21`.** Pre-existing tech debt (not touched in v2.6.0): `useAutoRefetch(() => api.getCosUpcomingTasks(6).catch(() => []), 60000)` wipes the prior list on transient errors. The seven sibling callers (Brain, DigitalTwin, QuickSummary, ActionableInsightsBanner, ProcessesTab, SystemHealthPage, CyberCity) were fixed during the v2.6.0 release review by dropping the catch and passing `{ silent: true }` to the API helper instead. Apply the same pattern here: add an `options` parameter to `getCosUpcomingTasks` (in `client/src/services/apiAgents.js`, mirroring `getCosQuickSummary`), drop the catch, and pass `{ silent: true }` in the call site. Surfaced by reviewer-4 in the v2.6.0 release review (2026-05-21).
- [ ] [extract-compare-helpers-once-eight-callers] **Extract `equalByKeys` / `equalListByKeys` once `useAutoRefetch`'s `compare` reaches ~8 widget callers.** With the dashboard rollout (PR #421) there are now 5 widget callers (Backup, Chief of Staff, Decision Log, Goal Progress, Proactive Alerts) on top of EpisodeVideoStage / Brain / Digital Twin from PR #425, using two emerging shapes — (a) scalar-object key equality (BackupWidget status, DecisionLogWidget last24Hours, ProactiveAlertsWidget counts) and (b) array equality by length + per-item key tuple (BackupWidget snapshots, GoalProgressWidget goals, ProactiveAlertsWidget alerts list, DecisionLogWidget impactfulDecisions). Inline forms are noisy but each has an explanatory comment that an `equalByKeys(prev, next, ['status', 'lastRun', …])` would lose. Defer until enough more callers appear that the abstraction pays for itself, then add helpers to `client/src/lib/compareHelpers.js` (register in `index.js` + `README.md`) and migrate the flat callers — leave CosDashboardWidget's nested-optional-chain shape inline. Surfaced by /simplify reuse review during `[useautorefetch-compare-caller-rollout-widgets]` claim 2026-05-21.
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 56398279a2..2a7dcf4323 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -36,6 +36,18 @@ vi.mock("../lib/fileUtils.js", async (importOriginal) => {
};
});
+// Stub instances.js so createUniverse's fire-and-forget autoSubscribeRecordToAllPeers
+// doesn't fan out to real peers. getPeers reads the live peer registry through a
+// dataPath closure that resolves to the REAL PATHS once the post-return microtask
+// runs outside this file's fileUtils mock window — so without this stub, creating a
+// 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([]) };
+});
+
// Pre-seed state into the new per-record layout. Mirrors what migration 034
// produces — each universe lands in `universes/<id>/index.json` and the
// cross-record `runs[]` lives in `universes/index.json` under `config.runs`.
diff --git a/server/services/universeBuilderPromote.test.js b/server/services/universeBuilderPromote.test.js
index 435d03b70a..8fabb3821a 100644
--- a/server/services/universeBuilderPromote.test.js
+++ b/server/services/universeBuilderPromote.test.js
@@ -24,6 +24,15 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => mockUuid(++uuidCounter) };
});
+// Stub instances.js so createUniverse's fire-and-forget autoSubscribeRecordToAllPeers
+// 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([]) };
+});
+
// Stub the LLM dispatch so tests don't need a live runner. The
// `runPromptThroughProvider` mock is overridden per-test to return the
// per-kind JSON shape we expect from the LLM. `resolveProviderAndModel`
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index 4e98105915..99faf1adf0 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -29,6 +29,15 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => mockUuid(++uuidCounter) };
});
+// Stub instances.js so createUniverse's fire-and-forget autoSubscribeRecordToAllPeers
+// 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([]) };
+});
+
// The bible extractor + staged-LLM runner + prompt-refine helpers all reach
// out to live AI providers. Stub them to return deterministic shapes so we
// can test lock semantics without spinning up a model.