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
fix(peer-sync): per-peer snapshot scoping replaces coarse whole-category skip (P1)
Adam Eivy8bbf1c11afa8
diff --git a/server/routes/dataSync.js b/server/routes/dataSync.jsindex 1d369b7f3b..bcb7c17080 100644--- a/server/routes/dataSync.js+++ b/server/routes/dataSync.js@@ -41,10 +41,23 @@ router.post('/tombstones/sweep', asyncHandler(async (req, res) => {res.json(result);}));+// Optional `?forPeer=<instanceId>` — the REQUESTING peer's instanceId. When+// present, the snapshot/checksum is scoped to EXCLUDE records that peer+// already receives from us per-record via the push pipeline (its inbound+// coverage), so the snapshot carries only un-subscribed records + tombstones+// for torn-down subs. Absent (older peers, non-peer callers) → full snapshot,+// applied idempotently by the receiver. Express returns an array for repeated+// query keys; the `typeof === 'string'` guard drops those so only a single+// scalar instanceId scopes the request.+const forPeerOf = (req) =>+ typeof req.query.forPeer === 'string' && req.query.forPeer.length > 0+ ? req.query.forPeer+ : undefined;+// GET /api/sync/:category/checksum — return checksum only (lightweight)router.get('/:category/checksum', asyncHandler(async (req, res) => {const category = categoryParam.parse(req.params.category);- const result = await dataSync.getChecksum(category);+ const result = await dataSync.getChecksum(category, { forPeerId: forPeerOf(req) });if (!result) throw new ServerError('Category not found', { status: 404 });res.json(result);}));@@ -52,7 +65,7 @@ router.get('/:category/checksum', asyncHandler(async (req, res) => {// GET /api/sync/:category/snapshot — return category data + checksumrouter.get('/:category/snapshot', asyncHandler(async (req, res) => {const category = categoryParam.parse(req.params.category);- const snapshot = await dataSync.getSnapshot(category);+ const snapshot = await dataSync.getSnapshot(category, { forPeerId: forPeerOf(req) });if (!snapshot) throw new ServerError('Category not found', { status: 404 });res.json(snapshot);}));diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex af14b8573d..47f7c56e9b 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -41,6 +41,14 @@ const PIPELINE_ISSUES_DIR = join(PATHS.data, 'pipeline-issues');// fingerprint walker descends into the dir so per-record edits invalidate.const UNIVERSE_BUILDER_DIR = join(PATHS.data, 'universes');const MEDIA_COLLECTIONS_FILE = join(PATHS.data, 'media-collections.json');+// Outbound peer subscriptions drive the per-peer snapshot exclude-set (see+// getSnapshot's `forPeerId` scoping). A subscribe/unsubscribe changes which+// records ride the scoped snapshot, so it must invalidate the per-peer+// checksum cache for the universe / pipeline / mediaCollections categories+// even when no record file itself moved (e.g. ephemeralize-then-delete tears+// down a sub WITHOUT touching the other records). Added to those categories'+// CHECKSUM_PATHS below.+const PEER_SUBSCRIPTIONS_FILE = join(PATHS.data, 'sharing', 'peer_subscriptions.json');const MEATSPACE_FILES = {'daily-log.json': { arrayKey: 'entries', idField: 'date' },@@ -359,12 +367,32 @@ async function applyMeatspaceRemote(remoteData) {// --- Category: Universe ----async function getUniverseSnapshot() {+// Normalize an `excludeRecordIds` option into a Set. Accepts a Set, an array,+// or null/undefined (→ empty Set = no exclusion = legacy full snapshot).+function toExcludeSet(exclude) {+ if (exclude instanceof Set) return exclude;+ if (Array.isArray(exclude)) return new Set(exclude);+ return new Set();+}++async function getUniverseSnapshot({ exclude } = {}) {// listUniverses() loads via the collection store — every per-record JSON// under `data/universes/<id>/index.json` plus the sanitizer pass. Same// input shape sanitizeStateForWire expects (it reads `state.universes`).const universes = await listUniverses({ includeDeleted: true });- const { data } = sanitizeStateForWire('universe', { universes });+ // Drop records the requesting peer already receives per-record via the+ // push pipeline (its INBOUND coverage). The filter runs on the RAW records+ // by `id` BEFORE sanitize so a subscribed-but-deleted record's tombstone is+ // also excluded here (the push pipeline carries that tombstone). Everything+ // un-subscribed — including tombstones for records whose sub was torn down+ // (ephemeralize-then-delete) — still rides the snapshot. This is the single+ // mechanism that fixes BOTH the partial-subscription gap (Item A) and the+ // stranded-tombstone stall (Item B).+ const excludeSet = toExcludeSet(exclude);+ const scoped = excludeSet.size > 0+ ? universes.filter((u) => !excludeSet.has(u?.id))+ : universes;+ const { data } = sanitizeStateForWire('universe', { universes: scoped });return { data, checksum: computeChecksum(data) };}@@ -385,15 +413,29 @@ async function applyUniverseRemote(remoteData) {// --- Category: Pipeline ----async function getPipelineSnapshot() {+async function getPipelineSnapshot({ exclude } = {}) {const [series, issues] = await Promise.all([listSeries({ includeDeleted: true }),listIssues({ includeDeleted: true }),]);+ // The pipeline category bundles series + their child issues — a `series`+ // subscription covers the whole sub-tree via the per-record push (which+ // ships the series + every child issue). So excluding a covered series id+ // ALSO drops every issue whose `seriesId` matches; otherwise the snapshot+ // would still carry the child issues the push pipeline already delivers,+ // re-introducing the redundant transfer this fix removes. Un-subscribed+ // series (and their issues), plus tombstones for torn-down subs, still ride.+ const excludeSet = toExcludeSet(exclude);+ const scopedSeries = excludeSet.size > 0+ ? series.filter((s) => !excludeSet.has(s?.id))+ : series;+ const scopedIssues = excludeSet.size > 0+ ? issues.filter((i) => !excludeSet.has(i?.seriesId))+ : issues;// Wire-projection lives in `server/lib/syncWire.js` — see getUniverseSnapshot.const { data } = sanitizeStateForWire('pipeline', {- series,- issues,+ series: scopedSeries,+ issues: scopedIssues,});return { data, checksum: computeChecksum(data) };}@@ -436,7 +478,7 @@ async function applyPipelineRemote(remoteData) {// so image bytes flow via the existing asset-pull worker — the snapshot path// covers the JSON, the push path covers the image bytes.-async function getMediaCollectionsSnapshot() {+async function getMediaCollectionsSnapshot({ exclude } = {}) {// listCollections re-reads + sanitizes from disk; we don't cache here since// the checksum cache (`CHECKSUM_PATHS` fingerprint check) already short-// circuits the I/O when the file hasn't moved.@@ -463,7 +505,13 @@ async function getMediaCollectionsSnapshot() {.filter((s) => s?.ephemeral === true).map((s) => s.id),);+ // Exclude collections the requesting peer already receives per-record via+ // the push pipeline (its INBOUND coverage). Keyed on the collection's own+ // id — `mediaCollection` subscriptions target the collection record itself.+ // Un-subscribed collections + tombstones for torn-down subs still ride.+ const excludeSet = toExcludeSet(exclude);const filtered = collections.filter((c) => {+ if (excludeSet.has(c?.id)) return false;if (c.universeId && ephemeralUniverseIds.has(c.universeId)) return false;if (c.seriesId && ephemeralSeriesIds.has(c.seriesId)) return false;return true;@@ -541,14 +589,18 @@ const CHECKSUM_PATHS = {character: [CHARACTER_FILE],digitalTwin: Object.values(DIGITAL_TWIN_FILES).map((f) => f.path),meatspace: Object.keys(MEATSPACE_FILES).map((f) => join(MEATSPACE_DIR, f)),- universe: [UNIVERSE_BUILDER_DIR],- pipeline: [PIPELINE_SERIES_DIR, PIPELINE_ISSUES_DIR],+ // PEER_SUBSCRIPTIONS_FILE is in the scoped categories' paths so a+ // subscribe/unsubscribe invalidates the per-peer snapshot checksum cache —+ // the exclude-set is derived from subscriptions, so the scoped snapshot's+ // content (and checksum) can change even when no record file moved.+ universe: [UNIVERSE_BUILDER_DIR, PEER_SUBSCRIPTIONS_FILE],+ pipeline: [PIPELINE_SERIES_DIR, PIPELINE_ISSUES_DIR, PEER_SUBSCRIPTIONS_FILE],// mediaCollections invalidates on its own file AND on the parent record// files — `getMediaCollectionsSnapshot` filters collections whose linked// universe/series is ephemeral, so a "mark ephemeral" PATCH on a universe// must re-checksum the collections snapshot even though// media-collections.json itself didn't move. Same goes for un-ephemeral.- mediaCollections: [MEDIA_COLLECTIONS_FILE, UNIVERSE_BUILDER_DIR, PIPELINE_SERIES_DIR],+ mediaCollections: [MEDIA_COLLECTIONS_FILE, UNIVERSE_BUILDER_DIR, PIPELINE_SERIES_DIR, PEER_SUBSCRIPTIONS_FILE],};const CATEGORIES = {@@ -626,28 +678,79 @@ export function getSupportedCategories() {return Object.keys(CATEGORIES);}-export async function getChecksum(category) {+// Map a `dataSync` category to the `getOutboundCoverageForPeer` coverage key.+// Only the three per-record-subscribable categories scope by peer; everything+// else (goals/character/digitalTwin/meatspace) has no per-record sub path, so+// it never excludes and never needs the dynamic peerSync import.+const SCOPED_COVERAGE_KEY = {+ universe: 'universe',+ pipeline: 'pipeline',+ mediaCollections: 'mediaCollections',+};++/**+ * Resolve the per-peer exclude-set for a scoped snapshot. Returns a+ * `Set<recordId>` of records the requesting peer (`forPeerId`) already+ * receives from us via the per-record push pipeline — those are excluded+ * from the snapshot we serve it. Returns an EMPTY set (→ full snapshot,+ * legacy behavior) when:+ * - the category isn't peer-scoped, or+ * - `forPeerId` is absent (a non-peer caller, or an OLDER peer that doesn't+ * send `forPeer` — it gets the full snapshot, applied idempotently), or+ * - the peerSync lookup fails (best-effort; full snapshot is always safe).+ *+ * Dynamic import keeps `sharing/peerSync.js` (and its transitive merge*FromSync+ * graph) OUT of dataSync's module-load path — same rationale as the+ * orchestrator's dynamic import of the same module.+ */+async function resolveExcludeSet(category, forPeerId) {+ const coverageKey = SCOPED_COVERAGE_KEY[category];+ if (!coverageKey || typeof forPeerId !== 'string' || forPeerId.length === 0) return new Set();+ const { getOutboundCoverageForPeer } = await import('./sharing/peerSync.js');+ const coverage = await getOutboundCoverageForPeer(forPeerId).catch(() => null);+ return coverage?.[coverageKey] instanceof Set ? coverage[coverageKey] : new Set();+}++export async function getChecksum(category, { forPeerId } = {}) {const cat = CATEGORIES[category];if (!cat) return null;+ const exclude = await resolveExcludeSet(category, forPeerId);const paths = CHECKSUM_PATHS[category];if (paths) {const fingerprints = await readFingerprintMap(paths);- const cached = checksumCache.get(category);+ // Cache keyed by (category, forPeerId): different requesting peers get+ // different exclude-sets → different scoped snapshots → different+ // checksums. A single per-category cache slot would let peer-B's checksum+ // mask peer-C's. `*` is the unscoped key (no forPeerId).+ const cacheKey = `${category}:${forPeerId || '*'}`;+ const cached = checksumCache.get(cacheKey);if (cached && fingerprintsEqual(cached.fingerprints, fingerprints)) {return { checksum: cached.checksum };}- const snapshot = await cat.getSnapshot();- checksumCache.set(category, { fingerprints, checksum: snapshot.checksum });+ const snapshot = await cat.getSnapshot({ exclude });+ checksumCache.set(cacheKey, { fingerprints, checksum: snapshot.checksum });return { checksum: snapshot.checksum };}- const snapshot = await cat.getSnapshot();+ const snapshot = await cat.getSnapshot({ exclude });return { checksum: snapshot.checksum };}-export async function getSnapshot(category) {+/**+ * Produce a category snapshot + checksum + portosMeta envelope.+ *+ * `options.forPeerId` (the requesting peer's instanceId) scopes the snapshot+ * to EXCLUDE records that peer already receives from us per-record via the+ * push pipeline (its inbound coverage). When absent — a non-peer caller, or+ * an OLDER peer that doesn't yet send `forPeer` — the snapshot is the full+ * category (legacy behavior), which the receiver applies idempotently. This+ * additive, ignore-if-unknown query param is what keeps the change+ * forward/backward compatible across independently-upgrading installs.+ */+export async function getSnapshot(category, { forPeerId } = {}) {const cat = CATEGORIES[category];if (!cat) return null;- const snap = await cat.getSnapshot();+ const exclude = await resolveExcludeSet(category, forPeerId);+ const snap = await cat.getSnapshot({ exclude });// Stamp the sender's PortOS version + schema versions on every outbound// snapshot. Receivers compare against their own PORTOS_SCHEMA_VERSIONS in// `applyRemote` and reject ahead-mismatches before any data is merged.diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex cf1632ff74..79929ade05 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -27,6 +27,23 @@ const SERIES_DIR = join(tempRoot, 'pipeline-series');const ISSUES_DIR = join(tempRoot, 'pipeline-issues');const UNIVERSES_DIR = join(tempRoot, 'universes');const MEDIA_COLLECTIONS_PATH = join(tempRoot, 'media-collections.json');+const PEER_SUBS_PATH = join(tempRoot, 'sharing', 'peer_subscriptions.json');++// Write the outbound peer-subscription store that drives the per-peer+// snapshot exclude-set. Each row is `{ peerId, recordKind, recordId }`.+function writePeerSubs(rows) {+ mkdirSync(join(tempRoot, 'sharing'), { recursive: true });+ writeFileSync(PEER_SUBS_PATH, JSON.stringify({+ subscriptions: rows.map((r) => ({+ id: `peer-${r.recordKind}-${r.recordId}-${r.peerId}`,+ peerId: r.peerId,+ recordKind: r.recordKind,+ recordId: r.recordId,+ createdAt: '2026-05-25T00:00:00Z',+ updatedAt: '2026-05-25T00:00:00Z',+ })),+ }, null, 2));+}function writeJSON(path, obj) {mkdirSync(tempRoot, { recursive: true });@@ -513,3 +530,142 @@ describe('dataSync — mediaCollections category', () => {expect(b.checksum).toBe(a.checksum);});});++// ---------------------------------------------------------------------------+// Per-peer snapshot scoping (`forPeerId`) — the Item A / Item B fix.+//+// When the requesting peer is passed via `forPeerId`, the source EXCLUDES the+// records it already pushes that peer per-record (the records THIS instance+// has outbound subscriptions for to that peer) — leaving un-subscribed records+// and torn-down-sub tombstones to ride the snapshot. With NO forPeerId, the+// snapshot is the full category (legacy behavior).+// ---------------------------------------------------------------------------+describe('dataSync — per-peer snapshot scoping (forPeerId exclude-set)', () => {+ it('universe: excludes the requesting peer\'s subscribed ids, keeps un-subscribed (partial-subscription gap)', async () => {+ writeUniverseState({+ universes: [+ { id: 'u-a', name: 'A', updatedAt: '2026-05-25T10:00:00Z' },+ { id: 'u-b', name: 'B', updatedAt: '2026-05-25T10:00:00Z' },+ { id: 'u-d', name: 'D', updatedAt: '2026-05-25T10:00:00Z' }, // never subscribed+ ],+ });+ // We push u-a + u-b to peer-A per-record; u-d has no sub.+ writePeerSubs([+ { peerId: 'peer-A', recordKind: 'universe', recordId: 'u-a' },+ { peerId: 'peer-A', recordKind: 'universe', recordId: 'u-b' },+ ]);+ const scoped = await dataSync.getSnapshot('universe', { forPeerId: 'peer-A' });+ const ids = scoped.data.universes.map((u) => u.id).sort();+ // Subscribed records excluded; the un-subscribed one still rides.+ expect(ids).toEqual(['u-d']);++ // No forPeerId → full snapshot (legacy / all-or-none common case).+ const full = await dataSync.getSnapshot('universe');+ expect(full.data.universes.map((u) => u.id).sort()).toEqual(['u-a', 'u-b', 'u-d']);+ });++ it('universe: a tombstone for a torn-down sub rides the snapshot (ephemeralize-then-delete, Item B)', async () => {+ // u-x was shared, then marked ephemeral (sub torn down), then deleted →+ // the record is now a tombstone on disk and has NO peer subscription. It+ // must ride the snapshot so the peer converges the delete.+ writeUniverseState({+ universes: [+ { id: 'u-x', name: 'Gone', ephemeral: true, deleted: true, deletedAt: '2026-05-25T11:00:00Z', updatedAt: '2026-05-25T11:00:00Z' },+ { id: 'u-y', name: 'Live', updatedAt: '2026-05-25T10:00:00Z' },+ ],+ });+ // peer-A still subscribes to u-y only (u-x's sub was removed on ephemeralize).+ writePeerSubs([{ peerId: 'peer-A', recordKind: 'universe', recordId: 'u-y' }]);+ const scoped = await dataSync.getSnapshot('universe', { forPeerId: 'peer-A' });+ const byId = Object.fromEntries(scoped.data.universes.map((u) => [u.id, u]));+ // u-y excluded (covered per-record); u-x tombstone present so the delete converges.+ expect(byId['u-y']).toBeUndefined();+ expect(byId['u-x']).toBeDefined();+ expect(byId['u-x'].deleted).toBe(true);+ });++ it('pipeline: excluding a subscribed series ALSO drops its child issues; un-subscribed series + issues ride', async () => {+ writeSeriesState([+ { id: 'ser-sub', name: 'Subbed', updatedAt: '2026-05-25T10:00:00Z' },+ { id: 'ser-free', name: 'Free', updatedAt: '2026-05-25T10:00:00Z' },+ ]);+ writeIssueState([+ { id: 'iss-1', seriesId: 'ser-sub', title: 'child of subbed', updatedAt: '2026-05-25T10:00:00Z' },+ { id: 'iss-2', seriesId: 'ser-free', title: 'child of free', updatedAt: '2026-05-25T10:00:00Z' },+ ]);+ // series → pipeline category; we push ser-sub (+ its issues) per-record.+ writePeerSubs([{ peerId: 'peer-A', recordKind: 'series', recordId: 'ser-sub' }]);+ const scoped = await dataSync.getSnapshot('pipeline', { forPeerId: 'peer-A' });+ expect(scoped.data.series.map((s) => s.id)).toEqual(['ser-free']);+ // iss-1 (child of the excluded series) dropped; iss-2 (free series) rides.+ expect(scoped.data.issues.map((i) => i.id)).toEqual(['iss-2']);+ });++ it('mediaCollections: excludes the requesting peer\'s subscribed collection ids', async () => {+ writeJSON(MEDIA_COLLECTIONS_PATH, {+ collections: [+ { id: 'col-sub', name: 'Subbed', description: '', coverKey: null, universeId: null, seriesId: null, items: [], createdAt: '2026-05-25T00:00:00Z', updatedAt: '2026-05-25T01:00:00Z' },+ { id: 'col-free', name: 'Free', description: '', coverKey: null, universeId: null, seriesId: null, items: [], createdAt: '2026-05-25T00:00:00Z', updatedAt: '2026-05-25T01:00:00Z' },+ ],+ });+ writePeerSubs([{ peerId: 'peer-A', recordKind: 'mediaCollection', recordId: 'col-sub' }]);+ const scoped = await dataSync.getSnapshot('mediaCollections', { forPeerId: 'peer-A' });+ expect(scoped.data.collections.map((c) => c.id)).toEqual(['col-free']);+ });++ it('subscriptions to a DIFFERENT peer do not scope this peer\'s snapshot (per-peer isolation)', async () => {+ writeUniverseState({+ universes: [{ id: 'u-a', name: 'A', updatedAt: '2026-05-25T10:00:00Z' }],+ });+ // u-a is subscribed to peer-B, but peer-A pulls — peer-A must still get u-a.+ writePeerSubs([{ peerId: 'peer-B', recordKind: 'universe', recordId: 'u-a' }]);+ const scopedForA = await dataSync.getSnapshot('universe', { forPeerId: 'peer-A' });+ expect(scopedForA.data.universes.map((u) => u.id)).toEqual(['u-a']);+ const scopedForB = await dataSync.getSnapshot('universe', { forPeerId: 'peer-B' });+ expect(scopedForB.data.universes.map((u) => u.id)).toEqual([]);+ });++ it('checksum is per-peer: a peer\'s scoped checksum differs once any of its subs exclude a record', async () => {+ // Single universe so the (un-canonicalized) universe snapshot order can't+ // perturb the comparison — a peer that excludes the only record gets an+ // empty snapshot whose checksum necessarily differs from the 1-record one.+ // `createdAt` is set explicitly: without it, sanitizeTemplate backfills+ // `createdAt: now` on every read, making the snapshot non-deterministic+ // across calls (the comparison below relies on byte-stable snapshots).+ writeUniverseState({+ universes: [{ id: 'u-a', name: 'A', createdAt: '2026-05-25T09:00:00Z', updatedAt: '2026-05-25T10:00:00Z' }],+ });+ writePeerSubs([{ peerId: 'peer-A', recordKind: 'universe', recordId: 'u-a' }]);+ const full = await dataSync.getChecksum('universe');+ const scopedA = await dataSync.getChecksum('universe', { forPeerId: 'peer-A' });+ // peer-A's scoped checksum (u-a excluded → empty) differs from the full one.+ expect(scopedA.checksum).not.toBe(full.checksum);+ // A peer with NO subs excludes nothing → its scoped snapshot ids match the+ // full set (checksum equality would also assert ordering, which the+ // universe snapshot doesn't canonicalize — assert on content instead).+ const scopedC = await dataSync.getSnapshot('universe', { forPeerId: 'peer-C' });+ expect(scopedC.data.universes.map((u) => u.id)).toEqual(['u-a']);+ });++ it('checksum cache invalidates when a subscription changes even though no record file moved', async () => {+ // One universe so the empty-vs-present checksum comparison is unambiguous.+ // Explicit `createdAt` keeps the snapshot byte-stable across reads (see the+ // sanitizeTemplate backfill note in the previous test).+ writeUniverseState({+ universes: [{ id: 'u-a', name: 'A', createdAt: '2026-05-25T09:00:00Z', updatedAt: '2026-05-25T10:00:00Z' }],+ });+ writePeerSubs([{ peerId: 'peer-A', recordKind: 'universe', recordId: 'u-a' }]);+ const before = await dataSync.getChecksum('universe', { forPeerId: 'peer-A' });+ // Tear down the sub (ephemeralize-then-delete teardown) — no record file+ // moves, but the exclude-set shrinks so the scoped snapshot now includes+ // u-a again. PEER_SUBSCRIPTIONS_FILE is in CHECKSUM_PATHS, so the cache+ // must invalidate (otherwise the stale empty-snapshot checksum is served).+ await new Promise((r) => setTimeout(r, 5)); // distinct mtime for the subs file+ writePeerSubs([]);+ const after = await dataSync.getChecksum('universe', { forPeerId: 'peer-A' });+ expect(after.checksum).not.toBe(before.checksum);+ // And it now matches the full snapshot (nothing excluded).+ const full = await dataSync.getChecksum('universe');+ expect(after.checksum).toBe(full.checksum);+ });+});diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 85ef4ed5b6..49d1fa59e5 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -159,6 +159,45 @@ export async function findPeerSubscription(peerId, recordKind, recordId) {) || null;}+/**+ * Coverage map for the snapshot-sync exclude-set, grouped by snapshot+ * CATEGORY (universe / pipeline / mediaCollections) — NOT by record kind.+ * `series` subscriptions roll into the `pipeline` category (series + its+ * child issues are bundled by the per-record push pipeline), matching the+ * single composite `getPipelineSnapshot` produces.+ *+ * DIRECTION — this is the crux of the Item-A fix. The returned ids are the+ * records THIS instance has OUTBOUND subscriptions for to `peerId` (i.e.+ * records we push to that peer via the per-record pipeline). When THIS+ * instance is the SNAPSHOT SOURCE answering a pull from `peerId`, those+ * exact records are the ones the requester already receives from us via+ * push — so they are the requester's INBOUND coverage and must be excluded+ * from the snapshot we serve it. Everything NOT in these sets (un-subscribed+ * records, and tombstones for records whose sub was torn down) still rides+ * the snapshot, which is what fixes both the partial-subscription gap and+ * the ephemeralize-then-delete tombstone stall.+ *+ * Why outbound-at-the-source and not inbound-at-the-puller: only the source+ * authoritatively knows which records it pushes per-record to the requester.+ * The puller cannot infer that from its own subscription store (every local+ * sub is outbound from the puller's view; a local sub to peer-A does NOT+ * prove peer-A pushes back). Computing the exclude-set at the source closes+ * the inbound-vs-outbound conflation with zero extra round-trips.+ *+ * Returns `{ universe, pipeline, mediaCollections }`, each a `Set<recordId>`.+ */+export async function getOutboundCoverageForPeer(peerId) {+ const coverage = { universe: new Set(), pipeline: new Set(), mediaCollections: new Set() };+ if (!isNonEmptyStr(peerId)) return coverage;+ const subs = await listPeerSubscriptions({ peerId });+ for (const sub of subs) {+ const category = KIND_TO_CATEGORY[sub.recordKind];+ if (!category || !isNonEmptyStr(sub.recordId)) continue;+ coverage[category]?.add(sub.recordId);+ }+ return coverage;+}+/*** Create a peer subscription. Idempotent — re-subscribing returns the existing* record. The first subscribe also initializes the tombstone cursor with@@ -1894,17 +1933,19 @@ export function installPeerSyncListener() {});};recordEvents.on('updated', onUpdated);- // ALSO listen for `deleted` events so soft-deletes propagate via the- // per-record push pipeline. Without this, `deleteUniverse` /- // `deleteSeries` (which emit `recordEvents.deleted`, NOT `updated`) only- // reached peers via the 60s snapshot loop — and that loop is skipped for- // any (peer, kind) pair covered by a per-record sub- // (syncOrchestrator.categoriesCoveredByPeerSync). The result was that- // every soft-delete on a record with active peer subs got stranded- // locally. Route delete events through the same `triggerPushForRecord`- // path: pushRecordToPeer reads the record with `includeDeleted: true`- // and the wire sanitizer (now updated) lets tombstones cross even for- // ephemeral records.+ // ALSO listen for `deleted` events so soft-deletes propagate immediately via+ // the per-record push pipeline. `deleteUniverse` / `deleteSeries` emit+ // `recordEvents.deleted` (NOT `updated`); without this listener a delete on+ // a still-subscribed record would only reach peers on the next 60s snapshot+ // cycle (and historically not at all, when the snapshot category was skipped+ // wholesale for subscribed peers). Route delete events through the same+ // `triggerPushForRecord` path: pushRecordToPeer reads the record with+ // `includeDeleted: true` and the wire sanitizer lets tombstones cross even+ // for ephemeral records. (Tombstones for records whose sub was ALREADY torn+ // down — the ephemeralize-then-delete case — have no live sub to push, so+ // they ride the per-peer-scoped snapshot instead: the source no longer+ // excludes them once their sub is gone. See dataSync.getSnapshot's+ // `forPeerId` scoping.)onDeleted = ({ recordKind, recordId }) => {triggerPushForRecord(recordKind, recordId).catch((err) => {console.log(`⚠️ peerSync: delete listener error for ${recordKind}/${recordId}: ${err.message}`);diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex bde782a9c8..55dfedf2df 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -55,6 +55,7 @@ import {PEER_SUBSCRIBABLE_KINDS,listPeerSubscriptions,findPeerSubscription,+ getOutboundCoverageForPeer,subscribePeer,unsubscribePeer,unsubscribeAllForPeer,@@ -273,6 +274,46 @@ describe('peerSync', () => {});});+ describe('getOutboundCoverageForPeer', () => {+ beforeEach(() => {+ // No push side effects — we only assert on the returned coverage map.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo', updatedAt: '2026-01-01T00:00:00Z' });+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Ser', updatedAt: '2026-01-01T00:00:00Z' });+ vi.mocked(getCollection).mockResolvedValue({ id: 'c1', name: 'Col', updatedAt: '2026-01-01T00:00:00Z' });+ vi.mocked(listIssues).mockResolvedValue([]);+ vi.mocked(findCollectionByUniverseId).mockResolvedValue(null);+ vi.mocked(findCollectionBySeriesId).mockResolvedValue(null);+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });+ });++ it('groups outbound subs by snapshot category (series → pipeline)', async () => {+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });+ await subscribePeer({ peerId: 'peer-a', recordKind: 'series', recordId: 's1' });+ await subscribePeer({ peerId: 'peer-a', recordKind: 'mediaCollection', recordId: 'c1' });+ const cov = await getOutboundCoverageForPeer('peer-a');+ expect([...cov.universe]).toEqual(['u1']);+ // series rolls into the pipeline category (series + child issues bundle).+ expect([...cov.pipeline]).toEqual(['s1']);+ expect([...cov.mediaCollections]).toEqual(['c1']);+ });++ it('only reports subs for the named peer (per-peer isolation)', async () => {+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });+ await subscribePeer({ peerId: 'peer-b', recordKind: 'universe', recordId: 'u1' });+ const covA = await getOutboundCoverageForPeer('peer-a');+ const covB = await getOutboundCoverageForPeer('peer-b');+ expect([...covA.universe]).toEqual(['u1']);+ expect([...covB.universe]).toEqual(['u1']);+ const covC = await getOutboundCoverageForPeer('peer-c');+ expect(covC.universe.size).toBe(0);+ });++ it('returns empty coverage for a missing/blank peerId', async () => {+ const cov = await getOutboundCoverageForPeer('');+ expect(cov.universe.size + cov.pipeline.size + cov.mediaCollections.size).toBe(0);+ });+ });+describe('unsubscribePeer', () => {it('removes the subscription and the peer cursor when no other subs remain for that peer', async () => {vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 76aeb59b5b..e5f3e3d772 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -11,7 +11,7 @@ import { join } from 'path';import { readJSONFile, ensureDir, PATHS, dataPath, atomicWrite } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import { instanceEvents } from './instanceEvents.js';-import { getPeers, DEFAULT_SYNC_CATEGORIES, updatePeer } from './instances.js';+import { getPeers, DEFAULT_SYNC_CATEGORIES, updatePeer, getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';import { peerBaseUrl } from '../lib/peerUrl.js';import * as brainSync from './brainSync.js';import * as brainSyncLog from './brainSyncLog.js';@@ -25,6 +25,7 @@ const SYNC_INTERVAL_MS = 60000;const FETCH_TIMEOUT_MS = 15000;const withLock = createMutex();+const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;let syncTimer = null;let peerOnlineHandler = null;const syncingPeers = new Set();@@ -248,9 +249,18 @@ function getEffectiveCategories(peer) {* Sync a snapshot-based data category from a peer.* Fetches checksum first to avoid full data transfer when unchanged.*/-async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums) {+async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums, ourInstanceId) {+ // Pass our own instanceId as `forPeer` so the SOURCE peer can scope the+ // snapshot it serves us: it excludes records it already pushes to us+ // per-record (our inbound coverage) and includes everything else+ // (un-subscribed records + tombstones for torn-down subs). An older source+ // peer ignores the unknown param and returns the full snapshot — safe,+ // applied idempotently. The query string is only appended for the three+ // peer-record-subscribable categories; for goals/character/etc. it's inert+ // server-side, but we still pass it uniformly to keep the URL builder simple.+ const forPeerQs = isNonEmptyStr(ourInstanceId) ? `?forPeer=${encodeURIComponent(ourInstanceId)}` : '';// Lightweight checksum check first- const checksumRes = await fetchPeer(peer, `/api/sync/${category}/checksum`);+ const checksumRes = await fetchPeer(peer, `/api/sync/${category}/checksum${forPeerQs}`);if (!checksumRes?.checksum) return { totalApplied: 0, checksum: null };const lastChecksum = cachedChecksums?.[category] ?? null;@@ -258,8 +268,9 @@ async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums)return { totalApplied: 0, checksum: checksumRes.checksum };}- // Checksum changed — fetch full snapshot- const snapshot = await fetchPeer(peer, `/api/sync/${category}/snapshot`);+ // Checksum changed — fetch full snapshot (same forPeer scoping as checksum+ // so the snapshot we apply matches the checksum we just cached).+ const snapshot = await fetchPeer(peer, `/api/sync/${category}/snapshot${forPeerQs}`);if (!snapshot?.data) return { totalApplied: 0, checksum: null };// Forward the sender's portosMeta envelope so applyRemote can run the@@ -340,20 +351,40 @@ async function clearPeerSchemaGap(peerId, category) {const isPlainObjectShallow = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);/**- * For a given peerId, return the set of `dataSync` category names whose- * underlying record kind has at least one active peer subscription. Used by- * the per-peer sync loop to skip categories the per-record push pipeline- * already owns.+ * Per-direction peer-sync coverage for a peer, by snapshot CATEGORY.*- * Mapping:- * - recordKind 'universe' → category 'universe'- * - recordKind 'series' → category 'pipeline' (covers series + issues)+ * Returns `{ outbound, inbound }` where each is+ * `{ universe: Set<id>, pipeline: Set<id>, mediaCollections: Set<id> }`:*- * Series subscriptions bundle child issues in the push payload, so the- * 'pipeline' category (series + issues) is a single skip unit — same as- * how `dataSync.getPipelineSnapshot` produces them as one composite.+ * - `outbound` — records WE push to the peer per-record (our local+ * subscriptions targeting the peer). These flow to the peer via the push+ * pipeline regardless of the snapshot.+ * - `inbound` — records the PEER pushes to US per-record (the peer's+ * subscriptions targeting our instanceId). We can only learn these by+ * asking the peer, so this is populated from+ * `GET /api/peer-sync/subscriptions?peerId=<ourId>` on the peer; on any+ * failure (older peer, offline, network) it stays EMPTY → we pull the+ * full snapshot (safe, idempotent).+ *+ * This is the fix for the old conflation: the previous coarse boolean used+ * OUR OUTBOUND subs to suppress the INBOUND snapshot pull for an ENTIRE+ * category. Outbound proves only that WE push to the peer — NOT that the peer+ * pushes back. So we now drive the inbound snapshot-pull scoping off the+ * `inbound` set, never the `outbound` set.+ *+ * NOTE — in the live sync path the snapshot pull is actually scoped at the+ * SOURCE (we send `forPeer=<ourId>` and the source excludes records it pushes+ * to us, i.e. ITS outbound = OUR inbound), which needs no extra round-trip and+ * is the authoritative inbound signal. This function exists for callers /+ * tests / future transports that want the explicit per-direction breakdown+ * computed locally; `inbound` here is the best-effort peer-queried mirror of+ * what the source excludes.+ *+ * Mapping: recordKind 'universe' → 'universe'; 'series' → 'pipeline'+ * (series + child issues are one composite, same as getPipelineSnapshot);+ * 'mediaCollection' → 'mediaCollections'.*/-async function categoriesCoveredByPeerSync(peerId) {+export async function categoriesCoveredByPeerSync(peerId, peer = null, ourInstanceId = null) {// Dynamic import keeps `sharing/peerSync.js` (which transitively pulls// every merge*FromSync service + recordEvents) OUT of this orchestrator's// module-load graph. Two reasons: (1) shaves the startup cost of evaluating@@ -361,17 +392,33 @@ async function categoriesCoveredByPeerSync(peerId) {// against a future circular dep — peerSync's graph never needs the// orchestrator today, but a top-level import here would manifest as a// confusing "undefined" crash at boot the day that changes.- const { listPeerSubscriptions } = await import('./sharing/peerSync.js');- const subs = await listPeerSubscriptions({ peerId });- const skip = new Set();- for (const sub of subs) {- if (sub.recordKind === 'universe') skip.add('universe');- if (sub.recordKind === 'series') skip.add('pipeline');- if (sub.recordKind === 'mediaCollection') skip.add('mediaCollections');+ const { getOutboundCoverageForPeer } = await import('./sharing/peerSync.js');+ const outbound = await getOutboundCoverageForPeer(peerId).catch(() => emptyCoverage());++ // Inbound: ask the peer which records it subscribes US to. The peer's+ // /subscriptions endpoint lists ITS outgoing subs; filtering by our+ // instanceId yields the records it pushes to us. Best-effort — a null+ // response (older peer / offline) leaves inbound empty → full snapshot.+ const inbound = emptyCoverage();+ if (peer && isNonEmptyStr(ourInstanceId)) {+ const res = await fetchPeer(peer, `/api/peer-sync/subscriptions?peerId=${encodeURIComponent(ourInstanceId)}`);+ const subs = Array.isArray(res?.subscriptions) ? res.subscriptions : [];+ for (const sub of subs) {+ const cat = RECORD_KIND_TO_CATEGORY[sub?.recordKind];+ if (cat && isNonEmptyStr(sub?.recordId)) inbound[cat].add(sub.recordId);+ }}- return skip;+ return { outbound, inbound };}+const RECORD_KIND_TO_CATEGORY = Object.freeze({+ universe: 'universe',+ series: 'pipeline',+ mediaCollection: 'mediaCollections',+});++const emptyCoverage = () => ({ universe: new Set(), pipeline: new Set(), mediaCollections: new Set() });+/*** Sync all data from a single peer*/@@ -384,6 +431,15 @@ export async function syncWithPeer(peer) {if (syncingPeers.has(peerId)) return { brain: { totalApplied: 0 }, memory: { totalApplied: 0 } };syncingPeers.add(peerId);+ // Our own instanceId — sent as `forPeer` so the SOURCE peer can scope each+ // snapshot it serves us (excludes records it already pushes to us+ // per-record). Resolved once per sync, best-effort; null/UNKNOWN → no+ // scoping (full snapshots, legacy behavior).+ const ourInstanceId = await getInstanceId().catch(() => null);+ const scopedInstanceId = isNonEmptyStr(ourInstanceId) && ourInstanceId !== UNKNOWN_INSTANCE_ID+ ? ourInstanceId+ : null;+const categories = getEffectiveCategories(peer);const enabledNames = Object.entries(categories).filter(([, on]) => on).map(([k]) => k);console.log(`🔄 Sync starting with ${peer.name || peerId}: categories=${enabledNames.join(',') || 'none'}`);@@ -413,26 +469,29 @@ export async function syncWithPeer(peer) {// --- Snapshot-based category syncs (parallel) ---const dataCategoryResults = {};- // Drop any categories this peer is on the per-record peer-sync path for.- // When a peer has at least one peer subscription for the underlying- // record-kind (universe → 'universe' category; series → 'pipeline'- // category, which is series+issues bundled), the push pipeline is- // authoritative — keeping the 60s snapshot loop running on the same- // kind would re-apply the same records under a stale checksum and- // burn bandwidth for no gain. The snapshot path stays in place for- // non-subscribed peers and for kinds the peer hasn't subscribed yet- // (e.g. a peer subscribed to universes but not to any series still- // gets pipeline snapshots).- const skipCats = await categoriesCoveredByPeerSync(peerId).catch(() => new Set());+ // We no longer skip whole categories when a peer has SOME per-record+ // subscriptions. The old coarse skip dropped the inbound snapshot for an+ // ENTIRE category whenever ANY record in it had a sub — stranding edits+ // for every UN-subscribed record (partial-subscription gap) and every+ // tombstone whose sub was torn down (ephemeralize-then-delete stall).+ //+ // Instead we ALWAYS pull every enabled snapshot category, but pass our+ // instanceId as `forPeer` so the SOURCE peer excludes exactly the records+ // it already pushes to us per-record (our inbound coverage) — leaving+ // un-subscribed records + torn-down-sub tombstones to ride the snapshot.+ // In the all-or-none common case (every record covered) the source+ // excludes them all → an empty snapshot whose stable checksum the+ // checksum short-circuit skips, so the network cost collapses to one tiny+ // cached checksum fetch (vs. the old full skip). Source-side scoping needs+ // no inbound round-trip and is the authoritative inbound signal.const enabledDataCats = dataSync.getSupportedCategories()- .filter(cat => categories[cat])- .filter(cat => !skipCats.has(cat));+ .filter(cat => categories[cat]);const cachedChecksums = cursor.checksums || {};if (enabledDataCats.length > 0) {const settled = await Promise.allSettled(enabledDataCats.map(cat =>- syncDataCategoryFromPeer(peer, peerId, cat, cachedChecksums)+ syncDataCategoryFromPeer(peer, peerId, cat, cachedChecksums, scopedInstanceId).catch(err => {console.error(`⚠️ ${cat} sync with ${peer.name} failed: ${err.message}`);return { totalApplied: 0, checksum: null };diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex d099e4470c..cfedea4c53 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -3,6 +3,12 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Mock all dependenciesvi.mock('./instances.js', () => ({getPeers: vi.fn(),+ updatePeer: vi.fn().mockResolvedValue(undefined),+ // forPeer scoping resolves our own instanceId; the orchestrator catches a+ // throw/UNKNOWN and just omits the query param, so the default mock returns+ // a stable id to exercise the scoped path.+ getInstanceId: vi.fn().mockResolvedValue('our-inst-id'),+ UNKNOWN_INSTANCE_ID: 'unknown',DEFAULT_SYNC_CATEGORIES: {brain: false, memory: false, goals: false,character: false, digitalTwin: false, meatspace: false@@ -29,6 +35,9 @@ vi.mock('./dataSync.js', () => ({}));vi.mock('./sharing/peerSync.js', () => ({listPeerSubscriptions: vi.fn().mockResolvedValue([]),+ getOutboundCoverageForPeer: vi.fn().mockResolvedValue({+ universe: new Set(), pipeline: new Set(), mediaCollections: new Set(),+ }),}));vi.mock('./instanceEvents.js', () => ({instanceEvents: { on: vi.fn(), removeListener: vi.fn() }@@ -243,73 +252,113 @@ describe('syncOrchestrator', () => {expect(result.memory.totalApplied).toBe(0);});- it('skips snapshot categories the peer is on the per-record peer-sync path for', async () => {- // Stage 3 skip-when-subscribed: a peer with an active 'universe' peer- // subscription must NOT also hit /api/sync/universe/checksum on the- // 60s loop — the push pipeline is authoritative for that category.- // Same for 'series' subs → 'pipeline' category.+ it('ALWAYS pulls every enabled snapshot category, scoped with forPeer (no whole-category skip)', async () => {+ // Item A fix: a per-record subscription must NO LONGER suppress the+ // inbound snapshot pull for the whole category. The pull always fires,+ // but with `?forPeer=<ourId>` so the SOURCE excludes the records it+ // already pushes us. This is what lets UN-subscribed records (and+ // torn-down-sub tombstones) keep converging via the snapshot.const dataSync = await import('./dataSync.js');- const peerSync = await import('./sharing/peerSync.js');dataSync.getSupportedCategories.mockReturnValue(['universe', 'pipeline', 'character']);- peerSync.listPeerSubscriptions.mockResolvedValueOnce([- { peerId: 'peer-inst-1', recordKind: 'universe', recordId: 'u1' },- ]);const peerWithCats = {...mockPeer,syncCategories: { universe: true, pipeline: true, character: true },};- // Brain + memory return empty (we want to see only the snapshot calls).mockFetch.mockResolvedValue({ok: true,json: async () => ({ checksum: 'x', data: null }),});await syncWithPeer(peerWithCats);const urls = mockFetch.mock.calls.map((c) => c[0]);- // universe snapshot endpoints must NOT have been hit; pipeline + character must.- expect(urls.some((u) => u.includes('/api/sync/universe/'))).toBe(false);+ // Every category is pulled — none skipped.+ expect(urls.some((u) => u.includes('/api/sync/universe/'))).toBe(true);expect(urls.some((u) => u.includes('/api/sync/pipeline/'))).toBe(true);expect(urls.some((u) => u.includes('/api/sync/character/'))).toBe(true);+ // Snapshot/checksum URLs carry our instanceId so the source can scope.+ const universeUrls = urls.filter((u) => u.includes('/api/sync/universe/'));+ expect(universeUrls.length).toBeGreaterThan(0);+ expect(universeUrls.every((u) => u.includes('forPeer=our-inst-id'))).toBe(true);});- it('skips BOTH universe and pipeline categories when peer is subscribed to both kinds', async () => {+ it('omits forPeer when our instanceId is UNKNOWN (older/uninitialized install)', async () => {const dataSync = await import('./dataSync.js');- const peerSync = await import('./sharing/peerSync.js');- dataSync.getSupportedCategories.mockReturnValue(['universe', 'pipeline', 'character']);- peerSync.listPeerSubscriptions.mockResolvedValueOnce([- { peerId: 'peer-inst-1', recordKind: 'universe', recordId: 'u1' },- { peerId: 'peer-inst-1', recordKind: 'series', recordId: 's1' },- ]);- const peerWithCats = {- ...mockPeer,- syncCategories: { universe: true, pipeline: true, character: true },- };- mockFetch.mockResolvedValue({ ok: true, json: async () => ({ checksum: 'x' }) });+ const instances = await import('./instances.js');+ dataSync.getSupportedCategories.mockReturnValue(['universe', 'character']);+ instances.getInstanceId.mockResolvedValueOnce('unknown'); // === UNKNOWN_INSTANCE_ID+ const peerWithCats = { ...mockPeer, syncCategories: { universe: true, character: true } };+ mockFetch.mockResolvedValue({ ok: true, json: async () => ({ checksum: 'x', data: null }) });await syncWithPeer(peerWithCats);const urls = mockFetch.mock.calls.map((c) => c[0]);- expect(urls.some((u) => u.includes('/api/sync/universe/'))).toBe(false);- expect(urls.some((u) => u.includes('/api/sync/pipeline/'))).toBe(false);- expect(urls.some((u) => u.includes('/api/sync/character/'))).toBe(true);+ // Categories still pulled, but WITHOUT the forPeer param (full snapshot).+ expect(urls.some((u) => u.includes('/api/sync/universe/'))).toBe(true);+ expect(urls.some((u) => u.includes('forPeer='))).toBe(false);});+ });- it('skips mediaCollections snapshot category when peer has a mediaCollection per-record subscription', async () => {- // Task 1.9: a mediaCollection subscription must prevent the 60s snapshot- // loop from also hitting /api/sync/mediaCollections/ — the per-record- // push pipeline owns that category.- const dataSync = await import('./dataSync.js');+ describe('categoriesCoveredByPeerSync (per-direction coverage)', () => {+ it('returns outbound from our local subs, grouped by snapshot category', async () => {const peerSync = await import('./sharing/peerSync.js');- dataSync.getSupportedCategories.mockReturnValue(['mediaCollections', 'character']);- peerSync.listPeerSubscriptions.mockResolvedValueOnce([- { peerId: 'peer-inst-1', recordKind: 'mediaCollection', recordId: 'col-1' },- ]);- const peerWithCats = {- ...mockPeer,- syncCategories: { mediaCollections: true, character: true },- };- mockFetch.mockResolvedValue({ ok: true, json: async () => ({ checksum: 'x', data: null }) });- await syncWithPeer(peerWithCats);- const urls = mockFetch.mock.calls.map((c) => c[0]);- expect(urls.some((u) => u.includes('/api/sync/mediaCollections/'))).toBe(false);- expect(urls.some((u) => u.includes('/api/sync/character/'))).toBe(true);+ peerSync.getOutboundCoverageForPeer.mockResolvedValueOnce({+ universe: new Set(['u1', 'u2']),+ pipeline: new Set(['s1']),+ mediaCollections: new Set(),+ });+ const { categoriesCoveredByPeerSync } = await import('./syncOrchestrator.js');+ // No peer/ourId → inbound stays empty (no peer query).+ const { outbound, inbound } = await categoriesCoveredByPeerSync('peer-inst-1');+ expect([...outbound.universe].sort()).toEqual(['u1', 'u2']);+ expect([...outbound.pipeline]).toEqual(['s1']);+ expect(inbound.universe.size).toBe(0);+ expect(inbound.pipeline.size).toBe(0);+ });++ it('populates inbound from the peer\'s subscriptions targeting our instanceId (NOT our outbound)', async () => {+ const peerSync = await import('./sharing/peerSync.js');+ // Our OUTBOUND coverage is EMPTY — proving inbound is sourced separately+ // (the inbound-vs-outbound distinction). The peer pushes us s9 (series →+ // pipeline) and col-7 (mediaCollection).+ peerSync.getOutboundCoverageForPeer.mockResolvedValueOnce({+ universe: new Set(), pipeline: new Set(), mediaCollections: new Set(),+ });+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ subscriptions: [+ { peerId: 'our-inst-id', recordKind: 'series', recordId: 's9' },+ { peerId: 'our-inst-id', recordKind: 'mediaCollection', recordId: 'col-7' },+ ],+ }),+ });+ const { categoriesCoveredByPeerSync } = await import('./syncOrchestrator.js');+ const { outbound, inbound } = await categoriesCoveredByPeerSync(+ 'peer-inst-1',+ { ...mockPeer, instanceId: 'peer-inst-1' },+ 'our-inst-id',+ );+ // Outbound empty; inbound carries the peer-pushed records.+ expect(outbound.pipeline.size).toBe(0);+ expect([...inbound.pipeline]).toEqual(['s9']);+ expect([...inbound.mediaCollections]).toEqual(['col-7']);+ // The peer's /subscriptions endpoint was queried filtered by our id.+ const calledUrl = mockFetch.mock.calls.map((c) => c[0]).find((u) => u.includes('/api/peer-sync/subscriptions'));+ expect(calledUrl).toContain('peerId=our-inst-id');+ });++ it('inbound stays empty when the peer query fails (older/offline peer → full snapshot)', async () => {+ const peerSync = await import('./sharing/peerSync.js');+ peerSync.getOutboundCoverageForPeer.mockResolvedValueOnce({+ universe: new Set(), pipeline: new Set(), mediaCollections: new Set(),+ });+ mockFetch.mockRejectedValueOnce(new Error('peer offline'));+ const { categoriesCoveredByPeerSync } = await import('./syncOrchestrator.js');+ const { inbound } = await categoriesCoveredByPeerSync(+ 'peer-inst-1',+ { ...mockPeer, instanceId: 'peer-inst-1' },+ 'our-inst-id',+ );+ expect(inbound.universe.size).toBe(0);+ expect(inbound.pipeline.size).toBe(0);+ expect(inbound.mediaCollections.size).toBe(0);});});diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 9a1150e819..8cdfae2583 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -1204,10 +1204,11 @@ export async function updateUniverse(id, patchOrMutator = {}) {// peer_subscriptions.json free of orphan rows.// true→false: fire autoSubscribeRecordToAllPeers so the now-shareable// record reaches every peer with the universe category- // enabled. The 60s snapshot loop is skipped for kinds covered- // by per-record subs (see syncOrchestrator.categoriesCoveredByPeerSync),- // so without this re-subscribe the record would be silently- // invisible to those peers.+ // enabled via the responsive per-record push pipeline. (The 60s+ // snapshot loop would also carry it now — the source only+ // 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// microtask AFTER the synchronous emitRecordUpdated below, so the// peerSync 'updated' listener would schedule pushes against subs the