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

feat(peer-sync): auto-subscribe records on category toggle and creation (#443)

[._.]/ Adam Eivycb57af7b5c0f
diff --git a/server/services/instances.js b/server/services/instances.js
index 6e267932a8..14b71257f0 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -219,6 +219,12 @@ export async function removePeer(id) {
export async function updatePeer(id, updates) {
let hostChanged = false;
+ // Track false→true transitions for the per-record-subscribable categories
+ // so we can backfill-subscribe existing local records after the data write
+ // settles. Set inside withData (where we have the merged before/after
+ // peer object) and consumed after the lock releases.
+ const turnedOnKinds = [];
+ let backfillPeerInstanceId = null;
const result = await withData(async (data) => {
const peer = data.peers.find(p => p.id === id);
if (!peer) return null;
@@ -226,7 +232,17 @@ export async function updatePeer(id, updates) {
if (updates.enabled !== undefined) peer.enabled = updates.enabled;
if (updates.syncEnabled !== undefined) peer.syncEnabled = updates.syncEnabled;
if (updates.syncCategories !== undefined) {
- peer.syncCategories = { ...(peer.syncCategories || DEFAULT_SYNC_CATEGORIES), ...updates.syncCategories };
+ const prev = peer.syncCategories || DEFAULT_SYNC_CATEGORIES;
+ const incoming = updates.syncCategories;
+ // Detect false→true flips for kinds the per-record push pipeline owns
+ // (universe → 'universe' kind; pipeline → 'series' kind, which bundles
+ // child issues at push time). enabled + outbound-allowed gating is
+ // enforced inside peerSync.autoSubscribePeerToAllRecords.
+ for (const [cat, kind] of [['universe', 'universe'], ['pipeline', 'series']]) {
+ if (prev[cat] !== true && incoming[cat] === true) turnedOnKinds.push(kind);
+ }
+ peer.syncCategories = { ...prev, ...incoming };
+ if (turnedOnKinds.length > 0) backfillPeerInstanceId = peer.instanceId || null;
}
if (updates.host !== undefined) {
const normalized = validHost(updates.host);
@@ -247,6 +263,20 @@ export async function updatePeer(id, updates) {
// reconnect using the new URL on the next probe cycle. Invalid/no-op host
// writes no longer disrupt an already-healthy connection.
if (updates.enabled === false || hostChanged) disconnectFromPeer(id);
+ // 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).
+ if (turnedOnKinds.length > 0 && backfillPeerInstanceId) {
+ import('./sharing/peerSync.js').then(async ({ autoSubscribePeerToAllRecords }) => {
+ for (const kind of turnedOnKinds) {
+ await autoSubscribePeerToAllRecords(backfillPeerInstanceId, kind);
+ }
+ }).catch((err) => {
+ console.log(`⚠️ peer: backfill-subscribe after category toggle failed: ${err.message}`);
+ });
+ }
return result;
}
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 59648fe154..e757ba3521 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -179,7 +179,7 @@ export async function getSeries(id, { includeDeleted = false } = {}) {
export async function createSeries(input = {}) {
const name = trimTo(input.name, NAME_MAX);
if (!name) throw makeErr(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);
- return queueSeriesWrite(async () => {
+ const created = await queueSeriesWrite(async () => {
const state = await readState();
const now = new Date().toISOString();
const next = sanitizeSeries({
@@ -207,6 +207,15 @@ export async function createSeries(input = {}) {
await writeState(state);
return next;
});
+ // 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) => {
+ console.log(`⚠️ series: auto-subscribe after create failed: ${err.message}`);
+ });
+ return created;
}
/**
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index dd32964e1e..8d991a8275 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -16,7 +16,8 @@
* sender to allow GC of the tombstone once every subscribed peer has seen
* it. Snapshot sync (`dataSync.js` 60s loop) remains the safety net for
* (peer, kind) pairs that DON'T have per-record subscriptions; the
- * orchestrator skip-when-subscribed wiring lands in Stage 3.
+ * `syncOrchestrator` consults `listPeerSubscriptions` per cycle and skips
+ * the snapshot category for any kind a peer-sub already covers.
*
* State files (under `data/sharing/`):
* - `peer_subscriptions.json` — outgoing subscriptions FROM this instance.
@@ -24,11 +25,14 @@
* - `peer_tombstone_cursors.json` — per-peer tombstone ack water-marks
* (managed by `peerTombstoneCursors.js`, this module advances it).
*
- * Stage 2 boundary: the push uses `peerFetch` (an HTTPS-or-HTTP client) and
- * targets a `/api/peer-sync/push` endpoint that doesn't exist yet — the
- * actual HTTP route + the orchestrator wiring land in Stage 3. Until then
- * pushes fail closed (logged + retried on next event), which is the right
- * behavior even in the deployed system.
+ * Transport: pushes POST to the peer's `/api/peer-sync/push` (wired in
+ * `server/routes/peerSync.js`) via `peerFetch` — an HTTPS-or-HTTP node-fetch
+ * variant that accepts the Tailnet's self-signed certs. Receiver pulls
+ * missing assets back over the sender's `/data/{images,image-refs,videos}/`
+ * static mounts (accept-ranges enabled). All five stages of the federated
+ * peer-sync project are live: subscription store + asset manifest (this
+ * module), HTTP routes (Stage 3), UI + receiver-side asset pull (Stage 4),
+ * and tombstone GC (Stage 5; `sharing/tombstoneGc.js`).
*/
import { join, basename } from 'path';
@@ -44,6 +48,7 @@ import { sanitizeRecordForWire } from '../../lib/syncWire.js';
import { collectAssetReferences } from './exporter.js';
import { recordEvents } from './recordEvents.js';
import { getInstanceId, getPeers, UNKNOWN_INSTANCE_ID } from '../instances.js';
+import { instanceEvents } from '../instanceEvents.js';
import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';
import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';
import { listIssues, mergeIssuesFromSync } from '../pipeline/issues.js';
@@ -145,11 +150,12 @@ export async function subscribePeer({ peerId, recordKind, recordId }, opts = {})
throw makeErr('peerId and recordId are required', ERR_VALIDATION);
}
- const sub = await withStateLock(async () => {
+ const { sub, created } = await withStateLock(async () => {
const state = await readState();
const id = subscriptionId({ peerId, recordKind, recordId });
const now = new Date().toISOString();
let existing = state.subscriptions.find((s) => s.id === id);
+ let wasCreated = false;
if (!existing) {
existing = {
id,
@@ -164,21 +170,36 @@ export async function subscribePeer({ peerId, recordKind, recordId }, opts = {})
};
state.subscriptions.push(existing);
await writeState(state);
+ wasCreated = true;
}
- return existing;
+ return { sub: existing, created: wasCreated };
});
// initCursor manages its own state file; no need to hold the subscription
- // lock across it.
- await initCursor(peerId);
-
- // Trigger initial push unless this was auto-created by a reverse-subscribe
- // (the peer just pushed us their latest, so pushing back is a no-op cycle).
- if (!opts.adoptedFromReverse) {
+ // lock across it. Callers that already initialized the cursor for this
+ // peerId (e.g. the backfill loop in `autoSubscribePeerToAllRecords`) can
+ // pass `skipCursorInit: true` to avoid N redundant cursor reads + lock
+ // acquisitions when subscribing many records to the same peer in sequence.
+ if (!opts.skipCursorInit) await initCursor(peerId);
+
+ // Trigger initial push ONLY on the first insert (created=true) — and not
+ // when this was auto-created by a reverse-subscribe (the peer just pushed
+ // us their latest, so pushing back is a no-op cycle). Idempotent re-hits
+ // (auto-subscribe paths walking N existing records, manual re-subscribe,
+ // peer:online convergence) MUST NOT re-push: the record's content hasn't
+ // moved, so buildPushPayload would burn an asset-manifest sha-pass for a
+ // result lastPushedHash will short-circuit anyway. Callers that need a
+ // forced re-push can call pushRecordToPeer(sub) directly.
+ if (created && !opts.adoptedFromReverse) {
pushRecordToPeer(sub).catch((err) => {
console.log(`⚠️ peerSync: initial push failed for ${sub.id}: ${err.message}`);
});
}
- return sub;
+ // `created` distinguishes a freshly-inserted subscription from an idempotent
+ // hit on an existing one. Auto-subscribe helpers use this to suppress
+ // "🔗 ... auto-subscribed" log spam (and inflated return arrays) on re-runs.
+ // The HTTP route forwards this through `{ subscription }` so REST clients
+ // can also branch on it.
+ return { ...sub, created };
}
export async function unsubscribePeer(id) {
@@ -214,6 +235,128 @@ export async function unsubscribePeer(id) {
return { id, removed: true };
}
+// Map a subscribable record kind to the per-peer `syncCategories` key that
+// controls whether auto-subscribe is allowed for that kind. Matches the
+// inverse mapping in syncOrchestrator.js `categoriesCoveredByPeerSync`.
+const KIND_TO_CATEGORY = Object.freeze({
+ universe: 'universe',
+ series: 'pipeline',
+});
+
+function peerAllowsOutbound(peer) {
+ if (!peer || peer.enabled === false) return false;
+ // `syncEnabled` is the global "sync this peer at all" toggle (separate from
+ // per-category `syncCategories.*`). When the user has globally disabled sync
+ // for a peer, auto-subscribe MUST NOT create subscriptions or fire pushes —
+ // doing so would leak records to a peer the user explicitly silenced. The
+ // per-category check (peerHasCategory) is necessary but not sufficient on
+ // its own, because syncCategories can be set independently.
+ if (peer.syncEnabled === false) return false;
+ const directions = Array.isArray(peer.directions) ? peer.directions : [];
+ if (directions.length > 0 && !directions.includes('outbound')) return false;
+ return true;
+}
+
+function peerHasCategory(peer, recordKind) {
+ const cat = KIND_TO_CATEGORY[recordKind];
+ if (!cat) return false;
+ const cats = peer?.syncCategories;
+ return !!(cats && cats[cat] === true);
+}
+
+/**
+ * When a new local record is created (universe / series), subscribe it to
+ * every peer that has the matching category enabled. Idempotent + best-effort
+ * — `subscribePeer` short-circuits if a sub already exists, and we swallow
+ * per-peer failures so a single offline peer can't block the creation path.
+ */
+export async function autoSubscribeRecordToAllPeers(recordKind, recordId) {
+ if (!PEER_SUBSCRIBABLE_KINDS.includes(recordKind) || !isNonEmptyStr(recordId)) return [];
+ const peers = await getPeers().catch(() => []);
+ const targets = peers.filter(p => isNonEmptyStr(p.instanceId) && peerAllowsOutbound(p) && peerHasCategory(p, recordKind));
+ if (targets.length === 0) return [];
+ // Only track + log subscriptions that were *newly created* on this call.
+ // `subscribePeer` is idempotent, so a re-run against already-subscribed
+ // peers would otherwise return the existing subs and emit misleading
+ // "🔗 auto-subscribed" lines on every retry / restart.
+ const created = [];
+ for (const peer of targets) {
+ const sub = await subscribePeer({ peerId: peer.instanceId, recordKind, recordId }).catch((err) => {
+ console.log(`⚠️ peerSync: auto-subscribe ${recordKind}/${recordId} → ${peer.name || peer.instanceId} failed: ${err.message}`);
+ return null;
+ });
+ if (sub && sub.created) {
+ created.push({ peerId: peer.instanceId, subscriptionId: sub.id });
+ console.log(`🔗 peerSync: auto-subscribed ${recordKind}/${recordId} → ${peer.name || peer.instanceId}`);
+ }
+ }
+ return created;
+}
+
+/**
+ * When a peer's syncCategories toggle flips false → true for a category,
+ * subscribe every existing local non-deleted record of the matching kind
+ * to that peer. Idempotent — re-running is safe.
+ *
+ * Dynamic imports for the listers avoid a static cycle (peerSync already
+ * imports merge entry points from universeBuilder / pipeline.series).
+ */
+export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
+ if (!isNonEmptyStr(peerId) || !PEER_SUBSCRIBABLE_KINDS.includes(recordKind)) return [];
+ // Re-check the peer is enabled + outbound-capable + still has the category
+ // turned on. The caller (instances.updatePeer) already saw the false→true
+ // flip inside withData, but this helper is also reachable from other
+ // backfill paths and we don't want to push to an inbound-only peer just
+ // because the category bit was set. Snapshot read is good enough — peer
+ // edits are infrequent compared to subscription pushes.
+ const peers = await getPeers().catch(() => []);
+ const peer = peers.find(p => p.instanceId === peerId);
+ if (!peer || !peerAllowsOutbound(peer) || !peerHasCategory(peer, recordKind)) return [];
+ let records = [];
+ if (recordKind === 'universe') {
+ const { listUniverses } = await import('../universeBuilder.js');
+ records = await listUniverses({ includeDeleted: false }).catch(() => []);
+ } else if (recordKind === 'series') {
+ const { listSeries } = await import('../pipeline/series.js');
+ records = await listSeries({ includeDeleted: false }).catch(() => []);
+ }
+ if (records.length === 0) return [];
+ // Compute the set difference up front: which local records aren't yet
+ // subscribed to this peer? The peer:online convergence path fires this
+ // helper on every online transition, so the steady-state case (all
+ // records already subscribed) must NOT walk N records and N subscribePeer
+ // readState calls. A single listPeerSubscriptions + Set diff collapses
+ // it to O(K) where K = existing-sub count, with the for-loop body
+ // running only for records that genuinely need a new sub.
+ const existingSubs = await listPeerSubscriptions({ peerId, recordKind });
+ const existingIds = new Set(existingSubs.map(s => s.recordId));
+ const missing = records.filter(r => isNonEmptyStr(r.id) && !existingIds.has(r.id));
+ if (missing.length === 0) return [];
+ // Initialize the tombstone cursor for this peer ONCE up front. Each
+ // subsequent subscribePeer call passes `skipCursorInit: true` ONLY when
+ // this pre-init succeeded — otherwise we'd silently create subscriptions
+ // without a cursor, which breaks the tombstone horizon contract
+ // (`subscribedSince` would be unset, so historical deletes could replay).
+ // On failure we fall back to per-call initCursor inside subscribePeer,
+ // paying the cost of N file reads but preserving correctness.
+ const cursorInited = await initCursor(peerId).then(() => true).catch(() => false);
+ // Only track newly-created subscriptions so re-runs of this helper (e.g. a
+ // second toggle on the same category) don't double-report or noise the
+ // backfill log line with already-subscribed records.
+ const created = [];
+ for (const rec of missing) {
+ const sub = await subscribePeer({ peerId, recordKind, recordId: rec.id }, { skipCursorInit: cursorInited }).catch((err) => {
+ console.log(`⚠️ peerSync: backfill-subscribe ${recordKind}/${rec.id} → ${peerId} failed: ${err.message}`);
+ return null;
+ });
+ if (sub && sub.created) created.push({ recordId: rec.id, subscriptionId: sub.id });
+ }
+ if (created.length > 0) {
+ console.log(`🔗 peerSync: backfill-subscribed ${created.length} ${recordKind} record(s) → ${peerId}`);
+ }
+ return created;
+}
+
/**
* Drop every subscription targeting a given peer. Used when removing a peer
* from the federation entirely (and by tests).
@@ -390,6 +533,15 @@ export async function pushRecordToPeer(sub) {
}
const peer = await findPeerById(sub.peerId);
if (!peer) return { pushed: false, reason: 'peer-not-found' };
+ // Re-gate on the same peer flags the auto-subscribe path checks. An
+ // existing subscription is NOT a license to keep pushing after the user
+ // has globally disabled sync (`syncEnabled: false`), disabled the peer
+ // (`enabled: false`), switched the peer to inbound-only (`directions:
+ // ['inbound']`), or toggled the matching category off (`syncCategories.*
+ // === false`). Without these guards, stale subs would silently outlive
+ // the user's intent and leak records on the next edit.
+ if (!peerAllowsOutbound(peer)) return { pushed: false, reason: 'peer-disallows-outbound' };
+ if (!peerHasCategory(peer, sub.recordKind)) return { pushed: false, reason: 'category-disabled' };
const ourInstanceId = await getInstanceId().catch(() => null);
if (!isNonEmptyStr(ourInstanceId) || ourInstanceId === UNKNOWN_INSTANCE_ID) {
@@ -860,9 +1012,36 @@ async function getIssueSeriesId(issueId) {
return found?.seriesId || null;
}
+/**
+ * Re-push every subscription targeting `peerId` whose initial push hasn't
+ * landed yet (`lastPushedAt == null`). Fires on `peer:online` so a record
+ * created while the peer was unreachable still reaches it the moment the
+ * peer comes back — without this retry, the new record would sit in limbo
+ * until the user edited it again (creation paths don't fire
+ * `recordEvents.updated`, so the existing debounce listener never sees it).
+ *
+ * Already-pushed subs are filtered out so this can't double-push under load.
+ * Failures stay non-fatal — the next `peer:online` (or the user's next edit)
+ * gets another attempt.
+ */
+export async function retryPendingPushesForPeer(peerId) {
+ if (!isNonEmptyStr(peerId)) return { retried: 0 };
+ const subs = await listPeerSubscriptions({ peerId });
+ const pending = subs.filter(s => !s.lastPushedAt);
+ if (pending.length === 0) return { retried: 0 };
+ console.log(`🔄 peerSync: retrying ${pending.length} pending push${pending.length === 1 ? '' : 'es'} → ${peerId}`);
+ for (const sub of pending) {
+ await pushRecordToPeer(sub).catch((err) => {
+ console.log(`⚠️ peerSync: retry push failed for ${sub.id}: ${err.message}`);
+ });
+ }
+ return { retried: pending.length };
+}
+
let onUpdated = null;
+let onPeerOnline = null;
-/** Attach the `recordEvents` listener — call once during sharing init. */
+/** Attach the `recordEvents` + `peer:online` listeners — call once during sharing init. */
export function installPeerSyncListener() {
if (onUpdated) return;
onUpdated = ({ recordKind, recordId }) => {
@@ -871,6 +1050,42 @@ export function installPeerSyncListener() {
});
};
recordEvents.on('updated', onUpdated);
+ // On peer:online, drive the local subscription state to convergence with
+ // the user's intent. Two cases:
+ //
+ // (1) Backfill missed at toggle time. `instances.updatePeer` runs the
+ // `autoSubscribePeerToAllRecords` backfill inline ONLY when the peer
+ // already has a known instanceId; for a freshly-added peer that
+ // hasn't been probed yet, instanceId is null and the inline backfill
+ // silently no-ops. By re-running it here for every category the peer
+ // has enabled, we recover that intent the moment the peer comes
+ // online and we learn its instanceId.
+ //
+ // (2) Initial-push retry. Subscriptions whose `lastPushedAt == null`
+ // (typically because the peer was offline when subscribePeer fired
+ // the initial push) get a second attempt now that the peer is
+ // reachable. Already-pushed subs are filtered inside the helper.
+ //
+ // Both helpers are idempotent: (1) calls subscribePeer which short-
+ // circuits on existing subs, (2) filters by lastPushedAt. Safe to fire
+ // both unconditionally per peer:online.
+ onPeerOnline = (peer) => {
+ if (!peer?.instanceId) return;
+ (async () => {
+ const cats = peer.syncCategories || {};
+ // KIND_TO_CATEGORY['universe']='universe', ['series']='pipeline'.
+ // Iterate the kind keys so the (kind, category) mapping stays single-
+ // sourced from KIND_TO_CATEGORY.
+ for (const kind of PEER_SUBSCRIBABLE_KINDS) {
+ const cat = KIND_TO_CATEGORY[kind];
+ if (cats[cat] === true) {
+ await autoSubscribePeerToAllRecords(peer.instanceId, kind).catch(() => {});
+ }
+ }
+ await retryPendingPushesForPeer(peer.instanceId).catch(() => {});
+ })().catch(() => {});
+ };
+ instanceEvents.on('peer:online', onPeerOnline);
}
/**
@@ -882,6 +1097,8 @@ export async function __resetForTests() {
for (const t of pendingTimers.values()) clearTimeout(t);
pendingTimers.clear();
if (onUpdated) recordEvents.off('updated', onUpdated);
+ if (onPeerOnline) instanceEvents.off('peer:online', onPeerOnline);
onUpdated = null;
+ onPeerOnline = null;
await writeTail.catch(() => {});
}
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index a977866661..be30f65641 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -24,11 +24,13 @@ vi.mock('../instances.js', async () => {
vi.mock('../universeBuilder.js', async () => ({
getUniverse: vi.fn(),
mergeUniversesFromSync: vi.fn(),
+ listUniverses: vi.fn(),
}));
vi.mock('../pipeline/series.js', async () => ({
getSeries: vi.fn(),
mergeSeriesFromSync: vi.fn(),
+ listSeries: vi.fn(),
}));
vi.mock('../pipeline/issues.js', async () => ({
@@ -52,15 +54,18 @@ import {
applyIncomingPush,
diffAssetManifestAgainstLocal,
buildAssetManifest,
+ autoSubscribeRecordToAllPeers,
+ autoSubscribePeerToAllRecords,
+ retryPendingPushesForPeer,
__resetForTests,
} from './peerSync.js';
import { getInstanceId, getPeers } from '../instances.js';
-import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';
-import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';
+import { getUniverse, mergeUniversesFromSync, listUniverses } from '../universeBuilder.js';
+import { getSeries, mergeSeriesFromSync, listSeries } from '../pipeline/series.js';
import { listIssues, mergeIssuesFromSync } from '../pipeline/issues.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
-import { listCursors } from './peerTombstoneCursors.js';
+import { listCursors, __drainForTests as __drainCursors } from './peerTombstoneCursors.js';
let originalDataPath;
let originalImagesPath;
@@ -84,11 +89,28 @@ beforeEach(async () => {
PATHS.data = tmp;
PATHS.images = join(tmp, 'images');
- // Reset mocks
+ // Reset mocks. The default peer fixture INTENTIONALLY INVERTS production
+ // defaults: `addPeer` in instances.js creates peers with `syncEnabled:
+ // false`, every `syncCategories.*` false, and `directions: ['outbound']`
+ // (the user has to explicitly opt them in via the Instances page).
+ // Tests in this file pre-enable everything so the new outbound/category
+ // gates in pushRecordToPeer don't short-circuit the broader push-pipeline
+ // assertions. Tests that exercise the gating paths explicitly override
+ // these mocks with the relevant flag flipped off.
vi.mocked(getInstanceId).mockResolvedValue('local-instance');
vi.mocked(getPeers).mockResolvedValue([
- { instanceId: 'peer-a', name: 'Peer A', host: null, address: '10.0.0.2', port: 5555, directions: ['outbound', 'inbound'] },
- { instanceId: 'peer-b-inbound-only', name: 'Peer B', host: null, address: '10.0.0.3', port: 5555, directions: ['inbound'] },
+ {
+ instanceId: 'peer-a', name: 'Peer A', host: null, address: '10.0.0.2', port: 5555,
+ enabled: true, syncEnabled: true,
+ directions: ['outbound', 'inbound'],
+ syncCategories: { universe: true, pipeline: true },
+ },
+ {
+ instanceId: 'peer-b-inbound-only', name: 'Peer B', host: null, address: '10.0.0.3', port: 5555,
+ enabled: true, syncEnabled: true,
+ directions: ['inbound'],
+ syncCategories: { universe: true, pipeline: true },
+ },
]);
vi.mocked(peerFetch).mockReset();
vi.mocked(mergeUniversesFromSync).mockResolvedValue({ applied: true, count: 1 });
@@ -104,7 +126,17 @@ beforeEach(async () => {
afterEach(async () => {
// Drain in-flight fire-and-forget pushes before tearing down the tmpdir —
// otherwise persistPushSuccess can race the rm and leave ENOTEMPTY.
- await __resetForTests();
+ // Drain BOTH writeTails (peerSync's subscription state AND the tombstone
+ // cursor module's separate writeTail, since initCursor writes happen
+ // outside peerSync's lock). Three drain cycles with a 5ms macrotask
+ // delay between them — pushes scheduled by an earlier drain (e.g.
+ // ackDeletesUpTo from a settled push) only enqueue on the next tick, so
+ // we need more than one pass to fully quiesce the writeTail chains.
+ for (let i = 0; i < 3; i++) {
+ await __resetForTests();
+ await __drainCursors();
+ await new Promise((r) => setTimeout(r, 5));
+ }
await rm(tmp, { recursive: true, force: true });
PATHS.data = originalDataPath;
PATHS.images = originalImagesPath;
@@ -141,10 +173,34 @@ describe('peerSync', () => {
const first = await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
const second = await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
expect(first.id).toBe(second.id);
+ // `created` distinguishes the first insert from the idempotent re-hit so
+ // auto-subscribe helpers can suppress duplicate "🔗 auto-subscribed" logs.
+ expect(first.created).toBe(true);
+ expect(second.created).toBe(false);
const all = await listPeerSubscriptions();
expect(all).toHaveLength(1);
});
+ it('does NOT re-push on idempotent re-subscribe (existing sub keeps its lastPushedAt)', async () => {
+ // Regression: subscribePeer used to fire pushRecordToPeer fire-and-
+ // forget on every call, even when the sub already existed. For the
+ // auto-subscribe paths that walk N records, that meant N
+ // buildAssetManifest sha-passes for already-pushed records — wasted
+ // work, since lastPushedHash short-circuits the wire I/O anyway.
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ await new Promise((r) => setTimeout(r, 10));
+ // First subscribe DID push.
+ expect(vi.mocked(peerFetch).mock.calls.length).toBeGreaterThan(0);
+ vi.mocked(peerFetch).mockClear();
+ // Second subscribe is idempotent — no push should fire.
+ const second = await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ await new Promise((r) => setTimeout(r, 10));
+ expect(second.created).toBe(false);
+ expect(vi.mocked(peerFetch)).not.toHaveBeenCalled();
+ });
+
it('rejects invalid kind', async () => {
await expect(
subscribePeer({ peerId: 'peer-a', recordKind: 'issue', recordId: 'i1' }),
@@ -219,6 +275,258 @@ describe('peerSync', () => {
});
});
+ describe('autoSubscribeRecordToAllPeers', () => {
+ beforeEach(() => {
+ // Default these so the push triggered by subscribePeer doesn't 500
+ // when the underlying buildPushPayload runs.
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1' });
+ vi.mocked(getSeries).mockResolvedValue({ id: 's1' });
+ vi.mocked(listIssues).mockResolvedValue([]);
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ });
+
+ 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 } },
+ { instanceId: 'peer-b', name: 'B', enabled: true, syncCategories: { universe: true } },
+ { instanceId: 'peer-c', name: 'C', enabled: true, syncCategories: { universe: false } },
+ ]);
+ const created = await autoSubscribeRecordToAllPeers('universe', 'u1');
+ expect(created.map(c => c.peerId).sort()).toEqual(['peer-a', 'peer-b']);
+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).not.toBeNull();
+ expect(await findPeerSubscription('peer-c', 'universe', 'u1')).toBeNull();
+ });
+
+ it('skips disabled peers and inbound-only peers', async () => {
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', name: 'A', enabled: false, syncCategories: { universe: true } },
+ { instanceId: 'peer-b', name: 'B', enabled: true, syncCategories: { universe: true }, directions: ['inbound'] },
+ { instanceId: 'peer-c', name: 'C', enabled: true, syncCategories: { universe: true }, directions: ['outbound'] },
+ ]);
+ const created = await autoSubscribeRecordToAllPeers('universe', 'u1');
+ expect(created.map(c => c.peerId)).toEqual(['peer-c']);
+ });
+
+ it('skips peers with syncEnabled=false (global toggle off)', async () => {
+ // Regression guard: the per-category bit is necessary but not sufficient
+ // — `syncEnabled` is the global "sync this peer at all" toggle. Without
+ // this check, a peer the user silenced would still be auto-subscribed
+ // and pushed to from createUniverse / createSeries.
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncEnabled: false, syncCategories: { universe: true } },
+ { instanceId: 'peer-b', enabled: true, syncEnabled: true, syncCategories: { universe: true } },
+ ]);
+ const created = await autoSubscribeRecordToAllPeers('universe', 'u1');
+ expect(created.map(c => c.peerId)).toEqual(['peer-b']);
+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).toBeNull();
+ });
+
+ it('maps series records to the pipeline category', async () => {
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncCategories: { universe: true, pipeline: false } },
+ { instanceId: 'peer-b', enabled: true, syncCategories: { universe: false, pipeline: true } },
+ ]);
+ const created = await autoSubscribeRecordToAllPeers('series', 's1');
+ expect(created.map(c => c.peerId)).toEqual(['peer-b']);
+ });
+
+ it('returns [] for invalid arguments', async () => {
+ expect(await autoSubscribeRecordToAllPeers('bogus', 'x')).toEqual([]);
+ expect(await autoSubscribeRecordToAllPeers('universe', '')).toEqual([]);
+ });
+
+ it('returns [] on re-run — only newly-created subs are reported', async () => {
+ // Idempotent re-subscribe must not re-log "🔗 auto-subscribed" or
+ // re-count existing subs as freshly created. This pins the
+ // `subscribePeer().created` plumbing.
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', name: 'A', enabled: true, syncCategories: { universe: true } },
+ ]);
+ const first = await autoSubscribeRecordToAllPeers('universe', 'u1');
+ expect(first.map(c => c.peerId)).toEqual(['peer-a']);
+ const second = await autoSubscribeRecordToAllPeers('universe', 'u1');
+ expect(second).toEqual([]);
+ });
+ });
+
+ describe('autoSubscribePeerToAllRecords', () => {
+ beforeEach(() => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1' });
+ vi.mocked(getSeries).mockResolvedValue({ id: 's1' });
+ vi.mocked(listIssues).mockResolvedValue([]);
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ // Default: peer is registered + outbound-capable + has both categories
+ // enabled. Individual tests override to verify the gating paths.
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', name: 'A', enabled: true, syncCategories: { universe: true, pipeline: true } },
+ ]);
+ });
+
+ it('subscribes every local non-deleted universe to the peer', async () => {
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }, { id: 'u2' }]);
+ const created = await autoSubscribePeerToAllRecords('peer-a', 'universe');
+ expect(created.map(c => c.recordId).sort()).toEqual(['u1', 'u2']);
+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).not.toBeNull();
+ expect(await findPeerSubscription('peer-a', 'universe', 'u2')).not.toBeNull();
+ });
+
+ it('subscribes every local non-deleted series to the peer', async () => {
+ vi.mocked(listSeries).mockResolvedValue([{ id: 's1' }, { id: 's2' }]);
+ const created = await autoSubscribePeerToAllRecords('peer-a', 'series');
+ expect(created.map(c => c.recordId).sort()).toEqual(['s1', 's2']);
+ });
+
+ it('returns [] when the peer is disabled', async () => {
+ // Guard against backfill pushing to a peer the user has explicitly
+ // disabled — the category bit can be stale even after `enabled: false`.
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', enabled: false, syncCategories: { universe: true } },
+ ]);
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ const created = await autoSubscribePeerToAllRecords('peer-a', 'universe');
+ expect(created).toEqual([]);
+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).toBeNull();
+ });
+
+ it('returns [] when syncEnabled is false (global toggle off)', async () => {
+ // Mirrors the autoSubscribeRecordToAllPeers test — both helpers go
+ // through `peerAllowsOutbound` which now consults syncEnabled.
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncEnabled: false, syncCategories: { universe: true } },
+ ]);
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ const created = await autoSubscribePeerToAllRecords('peer-a', 'universe');
+ expect(created).toEqual([]);
+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).toBeNull();
+ });
+
+ it('returns [] when the peer is inbound-only', async () => {
+ // Inbound-only peers must not get outbound subscriptions — that would
+ // trigger pushes in violation of the peer's configured directions.
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, directions: ['inbound'], syncCategories: { universe: true } },
+ ]);
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ const created = await autoSubscribePeerToAllRecords('peer-a', 'universe');
+ expect(created).toEqual([]);
+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).toBeNull();
+ });
+
+ it('returns [] when the matching category is no longer enabled', async () => {
+ // Race window: caller saw false→true flip, then the user toggled back
+ // to false before this helper ran. Re-check protects against that.
+ vi.mocked(getPeers).mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncCategories: { universe: false } },
+ ]);
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ const created = await autoSubscribePeerToAllRecords('peer-a', 'universe');
+ expect(created).toEqual([]);
+ });
+
+ it('returns [] when the peer id is unknown', async () => {
+ vi.mocked(getPeers).mockResolvedValue([]);
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ const created = await autoSubscribePeerToAllRecords('peer-ghost', 'universe');
+ expect(created).toEqual([]);
+ });
+
+ it('returns [] on re-run — only newly-created subs are reported', async () => {
+ // `subscribePeer` is idempotent; the helper must not double-count
+ // existing subs as freshly created on the second invocation.
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ const first = await autoSubscribePeerToAllRecords('peer-a', 'universe');
+ expect(first.map(c => c.recordId)).toEqual(['u1']);
+ const second = await autoSubscribePeerToAllRecords('peer-a', 'universe');
+ expect(second).toEqual([]);
+ });
+
+ it('returns [] for invalid arguments', async () => {
+ expect(await autoSubscribePeerToAllRecords('', 'universe')).toEqual([]);
+ expect(await autoSubscribePeerToAllRecords('peer-a', 'bogus')).toEqual([]);
+ });
+
+ it('short-circuits the for-loop when every record is already subscribed', async () => {
+ // Regression: peer:online fires this helper on every online
+ // transition. Without the pre-computed set-diff, a steady-state peer
+ // with all records already subscribed would still iterate N records
+ // and pay N subscribePeer readState calls per online transition.
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }, { id: 'u2' }]);
+ await autoSubscribePeerToAllRecords('peer-a', 'universe');
+ await new Promise((r) => setTimeout(r, 10));
+ vi.mocked(peerFetch).mockClear();
+ // Re-run on steady state — no push should fire because the set-diff
+ // is empty and the for-loop body never runs.
+ const second = await autoSubscribePeerToAllRecords('peer-a', 'universe');
+ expect(second).toEqual([]);
+ expect(vi.mocked(peerFetch)).not.toHaveBeenCalled();
+ });
+
+ it('converges from peer:online when the toggle fired before instanceId was known', async () => {
+ // Regression for the addPeer→toggle→probe ordering: addPeer creates
+ // a peer with instanceId=null. The user can flip syncCategories on
+ // before the first probe lands, in which case instances.updatePeer's
+ // inline backfill silently no-ops (no instanceId to subscribe to).
+ // The peer:online listener (wired in installPeerSyncListener) must
+ // re-run autoSubscribePeerToAllRecords once the probe assigns the
+ // instanceId, otherwise the user's intent is lost forever.
+ const { instanceEvents } = await import('../instanceEvents.js');
+ const { installPeerSyncListener } = await import('./peerSync.js');
+ installPeerSyncListener();
+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1' }]);
+ // Emit peer:online with a peer that has universe-sync turned on but
+ // was never seen by the inline backfill (the test never called
+ // updatePeer — that's the point).
+ instanceEvents.emit('peer:online', {
+ instanceId: 'peer-a',
+ name: 'A',
+ enabled: true,
+ syncEnabled: true,
+ directions: ['outbound'],
+ syncCategories: { universe: true },
+ });
+ // Allow the listener's fire-and-forget IIFE to settle.
+ await new Promise((r) => setTimeout(r, 30));
+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).not.toBeNull();
+ });
+ });
+
+ describe('retryPendingPushesForPeer', () => {
+ beforeEach(() => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1' });
+ vi.mocked(listIssues).mockResolvedValue([]);
+ });
+
+ it('re-pushes subs with lastPushedAt=null and skips already-pushed subs', async () => {
+ // Create a sub with the initial push FAILING — leaves lastPushedAt=null.
+ vi.mocked(peerFetch).mockResolvedValueOnce(null);
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ // Wait for the fire-and-forget initial push to settle so the
+ // persisted lastPushedAt is final before we re-check it.
+ await new Promise((r) => setTimeout(r, 10));
+ const stale = await findPeerSubscription('peer-a', 'universe', 'u1');
+ expect(stale.lastPushedAt).toBeNull();
+ // Peer comes back — retry must succeed and stamp lastPushedAt.
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ const result = await retryPendingPushesForPeer('peer-a');
+ expect(result.retried).toBe(1);
+ const updated = await findPeerSubscription('peer-a', 'universe', 'u1');
+ expect(updated.lastPushedAt).toBeTruthy();
+ // Second retry must be a no-op now that lastPushedAt is set.
+ const second = await retryPendingPushesForPeer('peer-a');
+ expect(second.retried).toBe(0);
+ });
+
+ it('returns {retried: 0} when the peer has no subscriptions', async () => {
+ const result = await retryPendingPushesForPeer('peer-without-subs');
+ expect(result).toEqual({ retried: 0 });
+ });
+
+ it('returns {retried: 0} for invalid peerId', async () => {
+ expect(await retryPendingPushesForPeer('')).toEqual({ retried: 0 });
+ expect(await retryPendingPushesForPeer(null)).toEqual({ retried: 0 });
+ });
+ });
+
describe('buildAssetManifest', () => {
it('hashes direct image filenames via the sidecar cache', async () => {
await writeFile(join(PATHS.images, 'asset-1.png'), Buffer.from('image bytes'));
@@ -363,6 +671,60 @@ describe('peerSync', () => {
expect(result.reason).toBe('peer-not-found');
});
+ it('refuses to push to a peer with syncEnabled=false (stale sub does not outlive the user toggle)', async () => {
+ // Regression: an existing subscription is not a license to keep pushing
+ // after the user has globally silenced the peer. Without this gate,
+ // every subsequent edit would still leak across the wire.
+ vi.mocked(getPeers).mockResolvedValue([
+ {
+ instanceId: 'peer-a', name: 'Peer A',
+ enabled: true, syncEnabled: false,
+ directions: ['outbound'],
+ syncCategories: { universe: true },
+ },
+ ]);
+ const result = await pushRecordToPeer({
+ id: 's', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
+ });
+ expect(result.pushed).toBe(false);
+ expect(result.reason).toBe('peer-disallows-outbound');
+ expect(peerFetch).not.toHaveBeenCalled();
+ });
+
+ it('refuses to push to a peer that has been switched to inbound-only', async () => {
+ vi.mocked(getPeers).mockResolvedValue([
+ {
+ instanceId: 'peer-a', name: 'Peer A',
+ enabled: true, syncEnabled: true,
+ directions: ['inbound'],
+ syncCategories: { universe: true },
+ },
+ ]);
+ const result = await pushRecordToPeer({
+ id: 's', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
+ });
+ expect(result.pushed).toBe(false);
+ expect(result.reason).toBe('peer-disallows-outbound');
+ });
+
+ it('refuses to push when the matching category has been toggled off', async () => {
+ // Stale sub on a universe but the user later toggled `syncCategories.universe`
+ // back off — stop pushing universes to this peer.
+ vi.mocked(getPeers).mockResolvedValue([
+ {
+ instanceId: 'peer-a', name: 'Peer A',
+ enabled: true, syncEnabled: true,
+ directions: ['outbound'],
+ syncCategories: { universe: false, pipeline: true },
+ },
+ ]);
+ const result = await pushRecordToPeer({
+ id: 's', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
+ });
+ expect(result.pushed).toBe(false);
+ expect(result.reason).toBe('category-disabled');
+ });
+
it('returns record-not-found when the record id no longer exists', async () => {
vi.mocked(getUniverse).mockResolvedValue(null);
const result = await pushRecordToPeer({
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index 39bfb1dd48..0be867d4e6 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -317,6 +317,8 @@ export async function syncWithPeer(peer) {
syncingPeers.add(peerId);
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'}`);
// Read cursor snapshot outside lock so network I/O doesn't block other peers
// Also detect and reset stale cursors (e.g. peer DB was rebuilt)
@@ -420,7 +422,27 @@ export async function syncAllPeers() {
const peers = await getPeers();
const online = peers.filter(p => p.enabled && hasAnySyncEnabled(p) && p.status === 'online' && p.instanceId);
- await Promise.allSettled(online.map(p => syncWithPeer(p)));
+ if (online.length > 0) {
+ const names = online.map(p => p.name || p.instanceId).join(', ');
+ console.log(`🔄 Sync cycle: ${online.length} peer${online.length === 1 ? '' : 's'} online (${names})`);
+ }
+
+ const settled = await Promise.allSettled(online.map(p => syncWithPeer(p)));
+
+ // Aggregate per-cycle change counts across peers so the heartbeat is loud
+ // about totals even when individual per-peer logs short-circuit on no-op.
+ let cycleChanges = 0;
+ for (const r of settled) {
+ if (r.status !== 'fulfilled' || !r.value) continue;
+ cycleChanges += (r.value.brain?.totalApplied || 0) + (r.value.memory?.totalApplied || 0);
+ for (const [k, v] of Object.entries(r.value)) {
+ if (k === 'brain' || k === 'memory') continue;
+ cycleChanges += v?.totalApplied || 0;
+ }
+ }
+ if (online.length > 0) {
+ console.log(`🔄 Sync cycle complete: ${cycleChanges} change${cycleChanges === 1 ? '' : 's'} applied across ${online.length} peer${online.length === 1 ? '' : 's'}`);
+ }
// Compact sync log below the minimum peer cursor to bound log growth
// Include all enabled peers with brain sync (not just online) so offline peers don't lose unsynced entries
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 45eeb8a73b..9822a9e61a 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -848,7 +848,7 @@ export async function needsEntryIdPersist(id) {
export async function createUniverse(input = {}) {
const name = trimTo(input.name, NAME_MAX_LENGTH);
if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);
- return queueUniverseWrite(async () => {
+ const created = await queueUniverseWrite(async () => {
const state = await readState();
const now = new Date().toISOString();
const next = sanitizeTemplate({
@@ -886,6 +886,16 @@ export async function createUniverse(input = {}) {
await writeState(state);
return next;
});
+ // Fire-and-forget auto-subscribe to every peer with universe-sync enabled.
+ // 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.
+ import('./sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>
+ autoSubscribeRecordToAllPeers('universe', created.id)
+ ).catch((err) => {
+ console.log(`⚠️ universe: auto-subscribe after create failed: ${err.message}`);
+ });
+ return created;
}
/**