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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-1150]): decouple peerSync from domain services via a subscription adapter
[._.]/ Adam Eivy1318d8c9f43d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c814422622..2f252e88ed 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -35,6 +35,8 @@## Changed+- **[issue-1150] Sturdier federation internals** — the machinery that auto-shares newly created universes, series, and collections with your other machines no longer depends on fragile module load ordering. No change to how syncing behaves.+- **[issue-1149] Calendar errors are now consistent everywhere** — calendar sync, discovery, and Google OAuth setup failures all come back in the same structured shape the rest of the app uses (instead of a mix of formats), and a failed Google sign-in now lands you back on the Calendar Config page with a clear error message instead of a raw error page.- **[issue-1148] Internal reorganization of the scheduled-task prompt catalog** — the default prompts and their cross-install upgrade bookkeeping now live in separate files, with a new integrity check that guarantees the prompts your install upgrades against are exactly the shipped ones. No behavior change.diff --git a/CLAUDE.md b/CLAUDE.mdindex d9c920ebe1..181a71e1c0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -221,7 +221,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` **and** mock `services/sharing/peerSync.js` with `mockNoPeerSync()` in the same suite. Those create paths can fire a background `autoSubscribeRecordToAllPeers` import and also trigger the `peerSync` dynamic-import path; mocking only `getPeers → []` suppresses peer discovery, but can still leave background auto-subscribe / peer-sync noise running. Only rely on `mockNoPeers()` alone when the suite provably never exercises the `peerSync` import path.+- **Record-creating tests and peer fan-out.** Record create/update paths reach peer-sync only through the subscription adapter in `server/services/sharing/recordEvents.js` (`autoSubscribeRecordToAllPeers` etc.) — a silent no-op until `peerSync.js` registers the real implementation at module load. A suite that never loads `peerSync.js` therefore gets no fan-out without mocking anything. Suites that DO load the peer-sync graph (importing `peerSync.js` or `sharing/index.js`, directly or transitively) must still mock `services/instances.js` with `mockNoPeers()` from `server/lib/mockPathsDataRoot.js` and `services/sharing/peerSync.js` with `mockNoPeerSync()` — the mock keeps the real module's registration side effect from wiring live fan-out into the adapter. To assert auto-subscribe behavior in a domain test, register a test double via `registerSubscriptionAdapter({...})` and clean up with `__resetSubscriptionAdapter()`.- **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/mockPathsDataRoot.js b/server/lib/mockPathsDataRoot.jsindex 2ffb6f941b..1a9538c1fd 100644--- a/server/lib/mockPathsDataRoot.js+++ b/server/lib/mockPathsDataRoot.js@@ -108,12 +108,19 @@ export function mockNoPeers(actual = {}, overrides = {}) {}/**- * Build a `sharing/peerSync.js` mock that disables create-time peer fan-out.+ * Build a `sharing/peerSync.js` mock that disables peer fan-out for suites+ * that load the peer-sync module graph (directly or via sharing/index.js).*- * This is intentionally separate from `mockNoPeers`: stubbing `getPeers → []`- * prevents live registry reads once `peerSync.js` loads, while this helper- * prevents record-creating tests from loading the peer-sync module graph at- * all through the fire-and-forget dynamic import.+ * NOTE: record CREATE paths no longer need this — they reach peer-sync only+ * through the `recordEvents.js` subscription adapter, a silent no-op until+ * peerSync.js registers itself at module load. A suite that never loads+ * peerSync gets no fan-out without mocking anything. Keep this helper for+ * suites that DO import peerSync (its module-load registration would+ * otherwise wire live fan-out into the adapter).+ *+ * Intentionally separate from `mockNoPeers`: stubbing `getPeers → []`+ * prevents live registry reads once `peerSync.js` loads; this helper prevents+ * the real module (and its registration side effect) from loading at all.*/export function mockNoPeerSync(actual = {}, overrides = {}) {return {diff --git a/server/services/instances.js b/server/services/instances.jsindex be43fc2369..f23299c8dc 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -16,6 +16,7 @@ import { DEFAULT_PEER_PORT } from '../lib/ports.js';import { peerBaseUrl } from '../lib/peerUrl.js';import { peerFetch } from '../lib/peerHttpClient.js';import { getSelfHost } from '../lib/peerSelfHost.js';+import { autoSubscribePeerToAllRecords } from './sharing/recordEvents.js';const INSTANCES_FILE = dataPath('instances.json');const PROBE_TIMEOUT_MS = 5000;@@ -388,23 +389,21 @@ export async function updatePeer(id, updates) {// Backfill-subscribe every local record of any kind whose category just// flipped on. Fire-and-forget — `autoSubscribePeerToAllRecords` is// idempotent + per-record-error tolerant, and we don't want to block the- // PATCH response on a slow peer's initial-push round-trip. Dynamic import- // dodges a static cycle (peerSync.js statically imports getPeers from us).+ // PATCH response on a slow peer's initial-push round-trip. Goes through the+ // recordEvents subscription adapter (peerSync statically imports getPeers+ // from us, so importing it back would close a cycle). Per-kind catch so a+ // transient failure in one kind's backfill (e.g. universe) doesn't abort+ // the loop and leave the peer with no series subscriptions either; the next+ // category-toggle PATCH or peer-online event re-fires any kind that didn't+ // land.if (turnedOnKinds.length > 0 && backfillPeerInstanceId) {- import('./sharing/peerSync.js').then(async ({ autoSubscribePeerToAllRecords }) => {- // Per-kind try/catch so a transient failure in one kind's backfill- // (e.g. universe) doesn't abort the loop and leave the peer with no- // series subscriptions either. Each kind is best-effort + logged- // independently; the next category-toggle PATCH or peer-online- // event re-fires the backfill for any kind that didn't land.+ (async () => {for (const kind of turnedOnKinds) {await autoSubscribePeerToAllRecords(backfillPeerInstanceId, kind).catch((err) => {console.log(`⚠️ peer: backfill-subscribe ${kind} after category toggle failed: ${err.message}`);});}- }).catch((err) => {- console.log(`⚠️ peer: backfill-subscribe after category toggle failed: ${err.message}`);- });+ })();}// Mirror the category change back to the peer so sync is bidirectional.// Fire-and-forget, but SERIALIZED per peer (see enqueueReciprocalSync): two@@ -805,13 +804,13 @@ export async function applyReciprocalSync(instanceId, categories) {// Mirror updatePeer's backfill-subscribe so a reciprocally-enabled// per-record category (universe/pipeline) pushes our existing records too.if (changed && turnedOnKinds.length > 0 && backfillInstanceId) {- import('./sharing/peerSync.js').then(async ({ autoSubscribePeerToAllRecords }) => {+ (async () => {for (const kind of turnedOnKinds) {await autoSubscribePeerToAllRecords(backfillInstanceId, kind).catch((err) => {console.log(`⚠️ peer: reciprocal backfill-subscribe ${kind} failed: ${err.message}`);});}- }).catch((err) => console.log(`⚠️ peer: reciprocal backfill-subscribe failed: ${err.message}`));+ })();}if (changed) console.log(`🔁 Reciprocal sync applied for peer ${peer.name}: ${Object.keys(sanitized).filter(k => sanitized[k]).join(',') || 'none'}`);return { changed, peer };diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex c949656480..d4b83102d5 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -29,7 +29,7 @@ import { createCollectionStore } from '../lib/collectionStore.js';import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';import { sanitizeOrigin } from '../lib/sharingOrigin.js';import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';-import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from './sharing/recordEvents.js';import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,} from '../lib/conflictJournal.js';@@ -212,15 +212,14 @@ export async function getCollection(id, { includeDeleted = false } = {}) {// emit the 'updated' event so any existing subscription pushes it, AND// auto-subscribe every mediaCollections-enabled peer so brand-new collections// (and their later tombstones) propagate even when that peer has universe/series-// sync disabled. Dynamic import avoids a module cycle — peerSync imports-// mergeMediaCollectionsFromSync from here, so a static import would close one.-// Call ONLY when a brand-new record was persisted — never on a find-existing-// hit, or every render would re-announce and churn the pipeline.+// sync disabled. Goes through the recordEvents subscription adapter — peerSync+// imports mergeMediaCollectionsFromSync from here, so importing it back (even+// dynamically) would close a cycle. Call ONLY when a brand-new record was+// persisted — never on a find-existing hit, or every render would re-announce+// and churn the pipeline.const announceNewCollection = (id) => {emitRecordUpdated('mediaCollection', id);- import('./sharing/peerSync.js')- .then(({ autoSubscribeRecordToAllPeers }) => autoSubscribeRecordToAllPeers('mediaCollection', id))- .catch(() => {});+ autoSubscribeRecordToAllPeers('mediaCollection', id).catch(() => {});};export async function createCollection({ name, description = '' }) {diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex e2f0d97e37..f74a2087c6 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -21,7 +21,10 @@ import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,deleteSyncBaseHash,} from '../../lib/conflictJournal.js';-import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js';+import {+ emitRecordUpdated, emitRecordDeleted,+ autoSubscribeRecordToAllPeers, unsubscribeAllForRecord,+} from '../sharing/recordEvents.js';import { renameCollectionForSeries, unlinkCollectionsForSeries } from '../mediaCollections.js';// Storage backend dispatcher (#1015). Series records moved from per-record@@ -219,12 +222,10 @@ export async function createSeries(input = {}) {// circuit via sanitizeRecordForWire anyway, but not creating the sub up// front keeps the subscription store clean.if (!created.ephemeral) {- // Fire-and-forget auto-subscribe to every peer with pipeline-sync enabled.- // Dynamic import to dodge a static cycle (peerSync imports merge entry- // points from this module).- import('../sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>- autoSubscribeRecordToAllPeers('series', created.id)- ).catch((err) => {+ // Fire-and-forget auto-subscribe to every peer with pipeline-sync enabled,+ // via the recordEvents subscription adapter (peerSync registers the real+ // implementation at boot — importing it from here would close a cycle).+ autoSubscribeRecordToAllPeers('series', created.id).catch((err) => {console.log(`⚠️ series: auto-subscribe after create failed: ${err.message}`);});}@@ -272,9 +273,7 @@ export async function insertSeriesWithId(input = {}) {// peers that still have the deleted record need the resurrection propagated.if (wasResurrection && !next.ephemeral) {emitRecordUpdated('series', next.id);- import('../sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>- autoSubscribeRecordToAllPeers('series', next.id)- ).catch((err) => {+ autoSubscribeRecordToAllPeers('series', next.id).catch((err) => {console.log(`⚠️ series: auto-subscribe after resurrection failed: ${err.message}`);});}@@ -401,22 +400,17 @@ export async function updateSeries(id, patch = {}) {// shareable series reaches every peer with the pipeline category enabled.// Must run BEFORE emitRecordUpdated so the peerSync 'updated' listener// doesn't schedule pushes against subs that are about to be torn down.- // The dynamic import is awaited (NOT fire-and-forget .then) — otherwise- // the unsubscribe resolves on a microtask after emitRecordUpdated has- // already fired the listener and pushes get scheduled against the- // about-to-be-deleted subs.+ // Awaited (NOT fire-and-forget) — otherwise the unsubscribe resolves on a+ // microtask after emitRecordUpdated has already fired the listener and+ // pushes get scheduled against the about-to-be-deleted subs.if (prevEphemeral && !nextEphemeral) {- await import('../sharing/peerSync.js')- .then(({ autoSubscribeRecordToAllPeers }) => autoSubscribeRecordToAllPeers('series', merged.id))- .catch((err) => {- console.log(`⚠️ series: re-subscribe after un-ephemeralizing failed: ${err.message}`);- });+ await autoSubscribeRecordToAllPeers('series', merged.id).catch((err) => {+ console.log(`⚠️ series: re-subscribe after un-ephemeralizing failed: ${err.message}`);+ });} else if (!prevEphemeral && nextEphemeral) {- await import('../sharing/peerSync.js')- .then(({ unsubscribeAllForRecord }) => unsubscribeAllForRecord('series', merged.id))- .catch((err) => {- console.log(`⚠️ series: unsubscribe after ephemeralizing failed: ${err.message}`);- });+ await unsubscribeAllForRecord('series', merged.id).catch((err) => {+ console.log(`⚠️ series: unsubscribe after ephemeralizing failed: ${err.message}`);+ });}// Cascade rename onto the linked per-series media collection (if any) —// log but don't fail the save. Runs OUTSIDE the queue so the media-diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.jsindex c07402ca6f..dd6ec998bd 100644--- a/server/services/pipeline/series.test.js+++ b/server/services/pipeline/series.test.js@@ -21,8 +21,7 @@ vi.mock('../instances.js', () => mockNoPeers());vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());const svc = await import('./series.js');-const peerSyncMock = await import('../sharing/peerSync.js');-const { recordEvents } = await import('../sharing/recordEvents.js');+const { recordEvents, registerSubscriptionAdapter, __resetSubscriptionAdapter } = await import('../sharing/recordEvents.js');describe('pipeline series service', () => {beforeEach(() => {@@ -171,17 +170,21 @@ describe('pipeline series service', () => {await svc.deleteSeries(id);const emitSpy = vi.spyOn(recordEvents, 'emit');- const subscribeSpy = vi.spyOn(peerSyncMock, 'autoSubscribeRecordToAllPeers');+ // The auto-subscribe flows through the recordEvents subscription+ // adapter (peerSync registers the real impl at boot) — register a+ // test double to observe the call.+ const subscribeSpy = vi.fn().mockResolvedValue([]);+ registerSubscriptionAdapter({ autoSubscribeRecordToAllPeers: subscribeSpy });await svc.insertSeriesWithId({ id, name: 'Resurrected' });- // Allow the fire-and-forget peerSync dynamic import to settle.+ // Allow the fire-and-forget adapter call to settle.await new Promise((r) => setTimeout(r, 0));expect(emitSpy).toHaveBeenCalledWith('updated', { recordKind: 'series', recordId: id });expect(subscribeSpy).toHaveBeenCalledWith('series', id);emitSpy.mockRestore();- subscribeSpy.mockRestore();+ __resetSubscriptionAdapter();});it('insertSeriesWithId fresh insert does NOT fire emitRecordUpdated', async () => {diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 50b0f5a280..5871c4b521 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -50,7 +50,7 @@ import { setSyncBaseHash, contentHashForRecord, flushBaseHashes, withBaseHashFluimport { collectAssetReferences } from './exporter.js';import { imageSidecarName, sanitizeAssetFilename } from './buckets.js';import { pullSidecarForImage } from './sidecarSync.js';-import { recordEvents } from './recordEvents.js';+import { recordEvents, registerSubscriptionAdapter } from './recordEvents.js';import {PORTOS_SCHEMA_VERSIONS,RECORD_KIND_SCHEMA_CATEGORIES,@@ -2441,3 +2441,16 @@ export async function __drainForTests() {await new Promise((r) => setTimeout(r, 0));await writeTail.catch(() => {});}++// Register the subscription-lifecycle implementation with the import-light+// adapter in recordEvents.js. Domain services (universeBuilder, series,+// mediaCollections, instances) call the adapter instead of importing this+// module — peerSync statically imports their merge entry points, so an import+// in the other direction (even a dynamic one) formed a load-order-sensitive+// cycle. Module-load registration is safe: sharing/index.js imports this file+// during server boot, before any HTTP write can fire an adapter call.+registerSubscriptionAdapter({+ autoSubscribeRecordToAllPeers,+ unsubscribeAllForRecord,+ autoSubscribePeerToAllRecords,+});diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 820eacef3e..37a3371d9a 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -531,6 +531,17 @@ describe('peerSync', () => {vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });});+ it('is registered with the recordEvents subscription adapter at module load', async () => {+ // Domain services (universeBuilder/series/mediaCollections/instances)+ // reach these functions only through the adapter — this pins the+ // module-scope registerSubscriptionAdapter(...) call that wires it.+ const adapter = await import('./recordEvents.js');+ vi.mocked(getPeers).mockResolvedValue([]);+ // Registered → the real implementation's no-peers [] (an unregistered+ // adapter would resolve to undefined instead).+ await expect(adapter.autoSubscribeRecordToAllPeers('universe', 'u1')).resolves.toEqual([]);+ });+it('subscribes the record to every peer with the matching category enabled', async () => {vi.mocked(getPeers).mockResolvedValue([{ instanceId: 'peer-a', name: 'A', enabled: true, syncCategories: { universe: true } },diff --git a/server/services/sharing/recordEvents.js b/server/services/sharing/recordEvents.jsindex 046a594dac..83bbf2106e 100644--- a/server/services/sharing/recordEvents.js+++ b/server/services/sharing/recordEvents.js@@ -59,3 +59,44 @@ export async function withReexportSuppressed(recordKind, recordId, fn) {export function __resetReexportSuppression() {suppressedReexports.clear();}++// === Subscription adapter (registration-based) =============================+// Subscription lifecycle calls flow domain → sharing like the events above,+// but two call sites must AWAIT completion (an ephemeral flip has to settle+// BEFORE emitRecordUpdated fires, or pushes get scheduled against subs that+// are about to be torn down) — so these go through a registered adapter that+// returns the implementation's promise rather than the fire-and-forget+// EventEmitter. peerSync.js registers the real implementation at module load+// (sharing/index.js imports it during server boot, before any HTTP write can+// land). Until registration every call is a silent no-op — which is exactly+// what record-creating tests want: no peer fan-out without mocking anything.+//+// This replaces the old `await import('./sharing/peerSync.js')` sites in+// universeBuilder/series/mediaCollections/instances — peerSync statically+// imports their merge entry points, so importing it back (even dynamically)+// formed a load-order-sensitive cycle.+let subscriptionAdapter = null;++export function registerSubscriptionAdapter(adapter) {+ subscriptionAdapter = adapter;+}++/** Test-only: detach the adapter so later suites see the unregistered state. */+export function __resetSubscriptionAdapter() {+ subscriptionAdapter = null;+}++/** Subscribe one record to every peer with its category enabled. */+export async function autoSubscribeRecordToAllPeers(recordKind, recordId) {+ return subscriptionAdapter?.autoSubscribeRecordToAllPeers?.(recordKind, recordId);+}++/** Tear down every per-record subscription (e.g. record turned ephemeral). */+export async function unsubscribeAllForRecord(recordKind, recordId) {+ return subscriptionAdapter?.unsubscribeAllForRecord?.(recordKind, recordId);+}++/** Backfill-subscribe every local record of a kind to one peer. */+export async function autoSubscribePeerToAllRecords(peerInstanceId, recordKind) {+ return subscriptionAdapter?.autoSubscribePeerToAllRecords?.(peerInstanceId, recordKind);+}diff --git a/server/services/sharing/recordEvents.test.js b/server/services/sharing/recordEvents.test.jsnew file mode 100644index 0000000000..ec68d79772--- /dev/null+++ b/server/services/sharing/recordEvents.test.js@@ -0,0 +1,63 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import {+ registerSubscriptionAdapter,+ __resetSubscriptionAdapter,+ autoSubscribeRecordToAllPeers,+ unsubscribeAllForRecord,+ autoSubscribePeerToAllRecords,+} from './recordEvents.js';++afterEach(() => {+ __resetSubscriptionAdapter();+});++describe('recordEvents subscription adapter', () => {+ it('is a silent no-op before any adapter registers (test/partial-boot state)', async () => {+ await expect(autoSubscribeRecordToAllPeers('universe', 'u1')).resolves.toBeUndefined();+ await expect(unsubscribeAllForRecord('series', 's1')).resolves.toBeUndefined();+ await expect(autoSubscribePeerToAllRecords('peer-1', 'universe')).resolves.toBeUndefined();+ });++ it('delegates to the registered adapter and returns its result (callers can await completion)', async () => {+ const adapter = {+ autoSubscribeRecordToAllPeers: vi.fn().mockResolvedValue(['peer-a']),+ unsubscribeAllForRecord: vi.fn().mockResolvedValue({ removed: ['peer-a'], failed: [] }),+ autoSubscribePeerToAllRecords: vi.fn().mockResolvedValue(3),+ };+ registerSubscriptionAdapter(adapter);++ await expect(autoSubscribeRecordToAllPeers('universe', 'u1')).resolves.toEqual(['peer-a']);+ expect(adapter.autoSubscribeRecordToAllPeers).toHaveBeenCalledWith('universe', 'u1');++ await expect(unsubscribeAllForRecord('series', 's1')).resolves.toEqual({ removed: ['peer-a'], failed: [] });+ expect(adapter.unsubscribeAllForRecord).toHaveBeenCalledWith('series', 's1');++ await expect(autoSubscribePeerToAllRecords('peer-1', 'series')).resolves.toBe(3);+ expect(adapter.autoSubscribePeerToAllRecords).toHaveBeenCalledWith('peer-1', 'series');+ });++ it('propagates adapter rejections so callers can .catch and log them', async () => {+ registerSubscriptionAdapter({+ autoSubscribeRecordToAllPeers: vi.fn().mockRejectedValue(new Error('peer offline')),+ });+ await expect(autoSubscribeRecordToAllPeers('universe', 'u1')).rejects.toThrow('peer offline');+ });++ it('tolerates a partial adapter (missing methods no-op)', async () => {+ registerSubscriptionAdapter({});+ await expect(autoSubscribeRecordToAllPeers('universe', 'u1')).resolves.toBeUndefined();+ });++ it('reset detaches the adapter', async () => {+ const spy = vi.fn().mockResolvedValue([]);+ registerSubscriptionAdapter({ autoSubscribeRecordToAllPeers: spy });+ __resetSubscriptionAdapter();+ await autoSubscribeRecordToAllPeers('universe', 'u1');+ expect(spy).not.toHaveBeenCalled();+ });+});++// peerSync.js's module-scope registerSubscriptionAdapter(...) is pinned in+// peerSync.test.js (which already imports the real module with its heavy+// deps mocked) — importing it here would drag the full peer-sync graph into+// this unit suite.diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 30184dbd2e..1606c7d29c 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -42,7 +42,10 @@ import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,deleteSyncBaseHash,} from '../lib/conflictJournal.js';-import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';+import {+ emitRecordUpdated, emitRecordDeleted,+ autoSubscribeRecordToAllPeers, unsubscribeAllForRecord,+} from './sharing/recordEvents.js';import { renameCollectionForUniverse, unlinkCollectionsForUniverse } from './mediaCollections.js';import {clearPendingSheetSlot, clearPendingSheetSlotsForUniverse,@@ -942,18 +945,15 @@ export async function createUniverse(input = {}) {await store().writeRecord(next.id, next);return next;});- // Fire-and-forget auto-subscribe to every peer with universe-sync enabled.+ // Fire-and-forget auto-subscribe to every peer with universe-sync enabled,+ // via the recordEvents subscription adapter (peerSync registers the real+ // implementation at boot — importing peerSync from here would close a cycle).// Skip the auto-subscribe entirely for ephemeral universes — the push// would short-circuit anyway via sanitizeRecordForWire returning null, but// not creating the subscription in the first place keeps peer_subscriptions.json// free of orphan rows tied to records the user explicitly excluded.- // Dynamic import keeps peerSync.js OUT of the universeBuilder module-load- // graph — peerSync already imports getUniverse / mergeUniversesFromSync- // from here, so a static import would close a cycle.if (!created.ephemeral) {- import('./sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>- autoSubscribeRecordToAllPeers('universe', created.id)- ).catch((err) => {+ autoSubscribeRecordToAllPeers('universe', created.id).catch((err) => {console.log(`⚠️ universe: auto-subscribe after create failed: ${err.message}`);});}@@ -996,9 +996,7 @@ export async function insertUniverseWithId(input = {}) {// peers that still have the deleted record need the resurrection propagated.if (wasResurrection && !next.ephemeral) {emitRecordUpdated('universe', next.id);- import('./sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>- autoSubscribeRecordToAllPeers('universe', next.id)- ).catch((err) => {+ autoSubscribeRecordToAllPeers('universe', next.id).catch((err) => {console.log(`⚠️ universe: auto-subscribe after resurrection failed: ${err.message}`);});}@@ -1325,23 +1323,19 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {// excludes records it ALREADY pushes per-record, so an// un-subscribed record rides the snapshot — but the push path// converges it immediately instead of waiting up to a cycle.)- // Await the dynamic import — fire-and-forget .then() resolves on a+ // Awaited (not fire-and-forget) — a .catch()-only call settles on a// microtask AFTER the synchronous emitRecordUpdated below, so the// peerSync 'updated' listener would schedule pushes against subs the// user just disabled. The await keeps the documented "BEFORE// emitRecordUpdated" contract honest.if (prevEphemeral && !nextEphemeral) {- await import('./sharing/peerSync.js')- .then(({ autoSubscribeRecordToAllPeers }) => autoSubscribeRecordToAllPeers('universe', merged.id))- .catch((err) => {- console.log(`⚠️ universe: re-subscribe after un-ephemeralizing failed: ${err.message}`);- });+ await autoSubscribeRecordToAllPeers('universe', merged.id).catch((err) => {+ console.log(`⚠️ universe: re-subscribe after un-ephemeralizing failed: ${err.message}`);+ });} else if (!prevEphemeral && nextEphemeral) {- await import('./sharing/peerSync.js')- .then(({ unsubscribeAllForRecord }) => unsubscribeAllForRecord('universe', merged.id))- .catch((err) => {- console.log(`⚠️ universe: unsubscribe after ephemeralizing failed: ${err.message}`);- });+ await unsubscribeAllForRecord('universe', merged.id).catch((err) => {+ console.log(`⚠️ universe: unsubscribe after ephemeralizing failed: ${err.message}`);+ });}if (!silent) {emitRecordUpdated('universe', merged.id);diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex 5b40489b7f..0eef6de2b6 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -80,8 +80,7 @@ vi.mock("crypto", async () => {});const svc = await import("./universeBuilder.js");-const peerSyncMock = await import("./sharing/peerSync.js");-const { recordEvents } = await import("./sharing/recordEvents.js");+const { recordEvents, registerSubscriptionAdapter, __resetSubscriptionAdapter } = await import("./sharing/recordEvents.js");// Default universe with non-empty influences. Override `influences` for tests// that need isolation from the seed tokens.@@ -721,17 +720,21 @@ describe("universeBuilder service", () => {await svc.deleteUniverse(id);const emitSpy = vi.spyOn(recordEvents, "emit");- const subscribeSpy = vi.spyOn(peerSyncMock, "autoSubscribeRecordToAllPeers");+ // The auto-subscribe flows through the recordEvents subscription+ // adapter (peerSync registers the real impl at boot) — register a+ // test double to observe the call.+ const subscribeSpy = vi.fn().mockResolvedValue([]);+ registerSubscriptionAdapter({ autoSubscribeRecordToAllPeers: subscribeSpy });await svc.insertUniverseWithId({ id, name: "Resurrected" });- // Allow the fire-and-forget peerSync dynamic import to settle.+ // Allow the fire-and-forget adapter call to settle.await new Promise((r) => setTimeout(r, 0));expect(emitSpy).toHaveBeenCalledWith("updated", { recordKind: "universe", recordId: id });expect(subscribeSpy).toHaveBeenCalledWith("universe", id);emitSpy.mockRestore();- subscribeSpy.mockRestore();+ __resetSubscriptionAdapter();});it("insertUniverseWithId fresh insert does NOT fire emitRecordUpdated", async () => {