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
feat(peer-sync): Stage 3 — HTTP routes + sharing listener + orchestrator skip-when-subscribed (#435)
[._.]/ Adam Eivy8cd3a314d97b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 15cd0ece1e..ea406aab21 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,7 @@# Unreleased Changes## Added+- Federated peer-sync HTTP routes and orchestrator wiring (Stage 3 of 5). New `server/routes/peerSync.js` mounts at `/api/peer-sync` with `POST /push` (receiver-side; wraps `applyIncomingPush` with Zod-validated payload + asset-manifest size cap of 2000), `GET/POST /subscriptions` (list + create local outgoing subs), and `DELETE /subscriptions/:id`. `installPeerSyncListener()` now runs alongside `installSubscriptionListener` in `initSharing` so one `recordEvents 'updated'` fan-out drives both the share-bucket and peer-sync transports. `syncOrchestrator` now consults `listPeerSubscriptions(peerId)` per cycle and skips the snapshot category for any `(peer, kind)` pair where a per-record peer subscription exists (universe-sub → skip 'universe' snapshot; series-sub → skip 'pipeline' snapshot) so the push pipeline owns the wire for subscribed pairs and the 60s loop stops re-applying the same records. Asset static mounts under `/data/{images,image-refs,videos,video-thumbnails}` now pass `acceptRanges: true` explicitly so the receiver's background asset-pull can resume partial downloads over flaky Tailnet links (default of serve-static, now encoded as a contract so it can't accidentally regress).- Federated peer-sync pipeline modules (Stage 2 of 5). New `server/services/sharing/peerSync.js` holds the per-record subscription store (`data/sharing/peer_subscriptions.json`), the asset-manifest builder, the push pipeline that serializes a record + its child issues + the SHA-manifest to a peer's `/api/peer-sync/push` endpoint, and the receiver-side `applyIncomingPush` that merges via the existing `merge*FromSync` LWW path, computes the asset-diff response, and best-effort auto-creates a reverse subscription back to the sender (honoring per-peer `directions: ['inbound']` to skip when explicitly inbound-only). New `server/services/sharing/peerTombstoneCursors.js` holds per-peer `lastAckedDeleteAt` water-marks so a tombstone is only GC'd once every subscribed peer has acked it (with a `subscribedSince` horizon so late-joining peers don't have to ingest every historical deletion). State writes serialize through a module-level `writeTail` so a fire-and-forget push can't clobber a concurrent subscribe write on the same JSON. The actual HTTP routes and orchestrator wiring land in Stage 3.- Foundation for federated peer sync of Universes, Series, and Issues (Stage 1 of 5). Soft-delete (`deleted` + `deletedAt` tombstone fields) is now part of the on-disk record for universes, series, and issues — so a delete propagates to other PortOS instances via the existing LWW snapshot merge instead of vanishing locally and resurrecting from a peer. `listUniverses` / `listSeries` / `listIssues` (and their per-id getters) filter tombstones by default; pass `{ includeDeleted: true }` to see them. `mergeUniversesFromSync` / `mergeSeriesFromSync` / `mergeIssuesFromSync` detect delete-transitions and fire the same orphan-cleanup cascades as a local delete (media-collection unlink, slot-map clear, issue renumber). New `server/lib/syncWire.js` is the single source of truth for what fields cross the peer wire (today it strips `runs[]` from universe state — shared by the 60s snapshot loop and the upcoming per-record push). New `server/lib/assetHash.js` persists SHA-256 hashes in each `data/images/{uuid}.metadata.json` sidecar so both the share-bucket exporter and the upcoming peer-sync push pipeline reuse the same value (no per-bucket recomputation, no per-transport cache). `insertUniverseWithId` / `insertSeriesWithId` / `insertIssueWithId` now overwrite a tombstoned record (re-import undeletes) but still reject DUPLICATE on a live record.diff --git a/server/index.js b/server/index.jsindex ad1b095a56..0a8004147d 100644--- a/server/index.js+++ b/server/index.js@@ -105,6 +105,7 @@ import lorasRoutes from './routes/loras.js';import sdapiRoutes from './routes/sdapi.js';import openclawRoutes from './routes/openclaw.js';import sharingRoutes from './routes/sharing.js';+import peerSyncRoutes from './routes/peerSync.js';import { initSharing } from './services/sharing/index.js';import askRoutes from './routes/ask.js';import { ensureSelf, startPolling } from './services/instances.js';@@ -420,6 +421,7 @@ app.use('/api/loras', lorasRoutes);app.use('/sdapi/v1', sdapiRoutes);app.use('/api/openclaw', openclawRoutes);app.use('/api/sharing', sharingRoutes);+app.use('/api/peer-sync', peerSyncRoutes);app.use('/api/ask', askRoutes);// initMediaJobQueue is awaited as part of the startup chain below so that@@ -512,15 +514,22 @@ startUpdateScheduler();// Restore any active loops from previous sessionrestoreLoops().catch(err => console.error(`❌ Loop restore failed: ${err.message}`));-// Serve generated images from configured images directory-app.use('/data/images', express.static(PATHS.images));+// Asset static mounts. `acceptRanges: true` is the serve-static default+// already, but we set it explicitly because the federated peer-sync receiver+// (services/sharing/peerSync.js) background-pulls missing assets from these+// URLs and relies on HTTP Range to resume partial downloads over flaky+// Tailnet links — losing range support here would silently force every+// retry to restart from byte 0 on a multi-MB PNG / video. Same posture for+// every kind below (image, image-ref, video, video-thumbnail).+const ASSET_STATIC_OPTS = { acceptRanges: true };+app.use('/data/images', express.static(PATHS.images, ASSET_STATIC_OPTS));// Reference images (multi-ref upload inputs + generated character reference// sheets) — served read-only so the UI can render thumbnails by URL.-app.use('/data/image-refs', express.static(PATHS.imageRefs));+app.use('/data/image-refs', express.static(PATHS.imageRefs, ASSET_STATIC_OPTS));// Serve generated videos + thumbnails so the Media UI and tailnet clients// can pull them by URL without going through an explicit download route.-app.use('/data/videos', express.static(PATHS.videos));-app.use('/data/video-thumbnails', express.static(PATHS.videoThumbnails));+app.use('/data/videos', express.static(PATHS.videos, ASSET_STATIC_OPTS));+app.use('/data/video-thumbnails', express.static(PATHS.videoThumbnails, ASSET_STATIC_OPTS));// Voice-over WAVs rendered by the pipeline audio stage — the AudioStage UI// pulls them inline via <audio src="/data/audio/<filename>">.app.use('/data/audio', express.static(PATHS.audio));diff --git a/server/lib/validation.js b/server/lib/validation.jsindex e37b1a5ced..7a2e68d14e 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1176,6 +1176,67 @@ export const subscriptionCreateSchema = z.object({recordId: z.string().trim().min(1).max(120),}).strict();+// =============================================================================+// PEER SYNC SCHEMAS+// =============================================================================++// Subscribe a record (universe / series) to a federated peer for live push.+// Sibling of share-bucket subscriptionCreateSchema; the difference is the+// destination — share-bucket subscriptions hit a cloud-synced folder, peer+// subscriptions target another PortOS instance over Tailnet.+export const peerSubscribeSchema = z.object({+ peerId: z.string().trim().min(1).max(120),+ recordKind: z.enum(['universe', 'series']),+ recordId: z.string().trim().min(1).max(120),+}).strict();++// Asset manifest entry the receiver gets in a push payload. Filename gets a+// second-pass scrub against path separators inside the service layer; this+// schema just constrains shape + caps so a malformed manifest doesn't bypass+// validation entirely. SHA-256 is hex-64 when present.+const peerAssetManifestEntrySchema = z.object({+ filename: z.string().trim().min(1).max(255),+ kind: z.enum(['image', 'image-ref', 'video']),+ sha256: z.string().regex(/^[a-f0-9]{64}$/i).optional(),+}).strict();++// One sanitized record on the wire. Mirrors sanitizeRecordForWire's output:+// id is required, soft-delete fields are tail-canonical, and the receiver's+// merge*FromSync paths handle everything else by shape. We don't `.strict()`+// because record shapes vary across kinds (universe vs series vs issue) and+// adding new fields shouldn't require a schema bump for every PR.+const peerWireRecordSchema = z.object({+ id: z.string().trim().min(1).max(120),+}).passthrough();++// Push payload from a sender. Modeled as a discriminated union on `kind` so+// only series payloads can carry `issues[]` — without the discrimination, an+// adversarial peer could send `kind: 'universe'` with a 100k-entry `issues`+// array and force the receiver to iterate it through `computeAckedDeletesFromPayload`+// and the sanitizers. The series branch caps issues at 1000 (well above any+// realistic series — most cap out at a few dozen) so neither branch is+// unbounded. `sourceInstanceId` is required + must be a real instance id+// (the receiver rejects "unknown" at the service layer; here we just enforce+// non-empty + length cap).+const peerSyncPushBase = {+ record: peerWireRecordSchema,+ assetManifest: z.array(peerAssetManifestEntrySchema).max(2000),+ sourceInstanceId: z.string().trim().min(1).max(120),+};+const universePushSchema = z.object({+ kind: z.literal('universe'),+ ...peerSyncPushBase,+}).strict();+const seriesPushSchema = z.object({+ kind: z.literal('series'),+ ...peerSyncPushBase,+ issues: z.array(peerWireRecordSchema).max(1000).optional(),+}).strict();+export const peerSyncPushSchema = z.discriminatedUnion('kind', [+ universePushSchema,+ seriesPushSchema,+]);+// =============================================================================// CREATIVE DIRECTOR SCHEMAS// =============================================================================diff --git a/server/routes/peerSync.js b/server/routes/peerSync.jsnew file mode 100644index 0000000000..c7f1ccb184--- /dev/null+++ b/server/routes/peerSync.js@@ -0,0 +1,106 @@+/**+ * Federated peer-sync HTTP routes.+ *+ * POST /api/peer-sync/push → receiver: apply incoming push+ * GET /api/peer-sync/subscriptions → list local outgoing subs (optional filter)+ * POST /api/peer-sync/subscriptions → subscribe a record to a peer+ * DELETE /api/peer-sync/subscriptions/:id → unsubscribe+ *+ * POST bodies flow through Zod schemas in `server/lib/validation.js`. Query+ * params on GET and the `:id` path param on DELETE are guarded inline:+ * - GET /subscriptions filter values are accepted only when `typeof === 'string'`+ * (Express returns arrays for repeated keys; the guard prevents those from+ * leaking into the filter).+ * - DELETE /:id is forwarded straight to the service layer, which validates+ * it via the same `isNonEmptyStr` check used by every other id-keyed+ * call (returns ERR_NOT_FOUND for missing, ERR_VALIDATION for malformed).+ *+ * Service errors carry an `ERR_*` code that maps to the HTTP status here;+ * anything un-mapped surfaces as a 500 via the global error handler.+ *+ * Stage 3 — the routes themselves; Stage 2 already provided the service+ * functions (`applyIncomingPush`, `subscribePeer`, etc.) that these wrap.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import {+ validateRequest,+ peerSubscribeSchema,+ peerSyncPushSchema,+} from '../lib/validation.js';+import {+ listPeerSubscriptions,+ subscribePeer,+ unsubscribePeer,+ applyIncomingPush,+ ERR_NOT_FOUND,+ ERR_VALIDATION,+} from '../services/sharing/peerSync.js';++const router = Router();++const PEER_SYNC_ERROR_STATUS = {+ [ERR_NOT_FOUND]: 404,+ [ERR_VALIDATION]: 400,+};++function mapAndRethrow(err) {+ const status = PEER_SYNC_ERROR_STATUS[err?.code];+ if (status) {+ throw new ServerError(err.message, { status, code: err.code });+ }+ throw err;+}++// --- POST /push --- receiver-side: apply an incoming record + asset manifest.+//+// This is the endpoint a *sender* peer hits when they push us their latest.+// Validation catches obvious shape errors at the boundary; the service layer+// owns the cross-instance rules (sourceInstanceId !== UNKNOWN_INSTANCE_ID,+// merge-time LWW, reverse-subscribe direction gating).+router.post('/push', asyncHandler(async (req, res) => {+ const payload = validateRequest(peerSyncPushSchema, req.body || {});+ const result = await applyIncomingPush(payload).catch(mapAndRethrow);+ res.json(result);+}));++// --- GET /subscriptions --- list outgoing peer subscriptions.+//+// Optional query filter: `?peerId=…&recordKind=…&recordId=…`. All filters+// AND together; absent filters match everything. Used by the Instances page+// to show "what am I syncing with peer X" + by the Universe / Series pages+// to render the SyncToPeerButton's current state.+router.get('/subscriptions', asyncHandler(async (req, res) => {+ const filter = {};+ if (typeof req.query.peerId === 'string') filter.peerId = req.query.peerId;+ if (typeof req.query.recordKind === 'string') filter.recordKind = req.query.recordKind;+ if (typeof req.query.recordId === 'string') filter.recordId = req.query.recordId;+ const subscriptions = await listPeerSubscriptions(filter);+ res.json({ subscriptions });+}));++// --- POST /subscriptions --- create a subscription + trigger initial push.+//+// Idempotent on the (peerId, recordKind, recordId) key — re-subscribing+// returns the existing record without throwing. The initial push fires+// fire-and-forget so the caller doesn't wait on a slow peer.+router.post('/subscriptions', asyncHandler(async (req, res) => {+ const input = validateRequest(peerSubscribeSchema, req.body || {});+ const subscription = await subscribePeer(input).catch(mapAndRethrow);+ // 201 even on idempotent re-subscribe — matches the share-bucket subscribe+ // convention in server/routes/sharing.js so REST clients can apply the same+ // status-code branching across both transports.+ res.status(201).json({ subscription });+}));++// --- DELETE /subscriptions/:id --- tear down a subscription.+//+// Also drops the per-peer tombstone cursor when this was the last remaining+// subscription to that peer (service-layer handles that cascade).+router.delete('/subscriptions/:id', asyncHandler(async (req, res) => {+ const result = await unsubscribePeer(req.params.id).catch(mapAndRethrow);+ res.json(result);+}));++export default router;diff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.jsnew file mode 100644index 0000000000..9d89edcc0f--- /dev/null+++ b/server/routes/peerSync.test.js@@ -0,0 +1,265 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/sharing/peerSync.js', () => ({+ listPeerSubscriptions: vi.fn(),+ subscribePeer: vi.fn(),+ unsubscribePeer: vi.fn(),+ applyIncomingPush: vi.fn(),+ ERR_NOT_FOUND: 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND',+ ERR_VALIDATION: 'PEER_SYNC_SUBSCRIPTION_VALIDATION',+}));++import * as svc from '../services/sharing/peerSync.js';+import peerSyncRoutes from './peerSync.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/peer-sync', peerSyncRoutes);+ app.use(errorMiddleware);+ return app;+};++const serviceError = (msg, code) => Object.assign(new Error(msg), { code });++describe('peer-sync routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('POST /api/peer-sync/push', () => {+ it('200s with the service result for a valid universe push', async () => {+ svc.applyIncomingPush.mockResolvedValue({+ missingAssets: [],+ reverseSubscriptionCreated: true,+ ackedDeletesUpTo: 0,+ });+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'universe',+ record: { id: 'u1', name: 'Foo' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(res.status).toBe(200);+ expect(res.body.reverseSubscriptionCreated).toBe(true);+ expect(svc.applyIncomingPush).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'universe',+ sourceInstanceId: 'peer-a',+ }));+ });++ it('accepts a series push with bundled issues', async () => {+ svc.applyIncomingPush.mockResolvedValue({ missingAssets: [], reverseSubscriptionCreated: false, ackedDeletesUpTo: 0 });+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'series',+ record: { id: 's1' },+ issues: [{ id: 'i1' }, { id: 'i2' }],+ assetManifest: [{ filename: 'a.png', kind: 'image', sha256: 'a'.repeat(64) }],+ sourceInstanceId: 'peer-a',+ });+ expect(res.status).toBe(200);+ expect(svc.applyIncomingPush).toHaveBeenCalledWith(expect.objectContaining({+ issues: expect.any(Array),+ }));+ });++ it('400s on an invalid kind (Zod boundary catches before service)', async () => {+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'mystery',+ record: { id: 'x' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(res.status).toBe(400);+ expect(svc.applyIncomingPush).not.toHaveBeenCalled();+ });++ it('400s when the record is missing an id', async () => {+ // Stage 1's schema-parity rule: validation must catch the malformed+ // record at the route boundary, not let the service throw.+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'universe',+ record: { name: 'No ID' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(res.status).toBe(400);+ });++ it('400s when sourceInstanceId is empty (the service-layer guard ALSO catches this, but the schema should reject first)', async () => {+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'universe',+ record: { id: 'u1' },+ assetManifest: [],+ sourceInstanceId: '',+ });+ expect(res.status).toBe(400);+ });++ it('maps the service-layer ERR_VALIDATION to a 400 (service-side guards beyond Zod)', async () => {+ // sourceInstanceId="unknown" is shape-valid but gets rejected by the+ // service for the cursor-poisoning reason — the route must surface that+ // as a 400, not a 500.+ svc.applyIncomingPush.mockRejectedValue(+ serviceError('sourceInstanceId required (and not "unknown")', 'PEER_SYNC_SUBSCRIPTION_VALIDATION'),+ );+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'universe',+ record: { id: 'u1' },+ assetManifest: [],+ sourceInstanceId: 'unknown',+ });+ expect(res.status).toBe(400);+ });++ it('rejects a universe push that smuggles an issues[] field (discriminated union)', async () => {+ // Regression: peerSyncPushSchema is a discriminated union on `kind`.+ // Only the series branch accepts `issues`; the universe branch is+ // .strict() so any `issues` field — even a single entry — fails Zod+ // parsing. Without this guard, a malicious peer could send+ // kind='universe' with a large issues array and force the receiver to+ // iterate it via computeAckedDeletesFromPayload before realizing the+ // kind mismatch. Body-parser limits catch the genuinely huge case;+ // the schema catches the moderately-sized-but-still-malicious case.+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'universe',+ record: { id: 'u1' },+ issues: [{ id: 'i1' }],+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(res.status).toBe(400);+ expect(svc.applyIncomingPush).not.toHaveBeenCalled();+ });++ it('caps the series-push issues[] at 1000 entries (defense in depth alongside body limit)', async () => {+ // Series can carry issues, but 1001+ is rejected by the schema. Body+ // parser limits would also catch genuinely huge payloads; this cap+ // catches the moderately-sized-but-still-too-big case (e.g. ~50k that+ // fits under the 55mb body cap but is still 50× larger than any+ // realistic series).+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'series',+ record: { id: 's1' },+ issues: Array.from({ length: 1001 }, (_, i) => ({ id: `i${i}` })),+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(res.status).toBe(400);+ });++ it('caps assetManifest at 2000 entries (memory-amplification guard)', async () => {+ // An adversarial peer could ship a manifest of 1M filenames and force+ // the receiver to stat each one. The schema caps at 2k entries (well+ // above any realistic universe size).+ const huge = Array.from({ length: 2001 }, (_, i) => ({+ filename: `f${i}.png`, kind: 'image',+ }));+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'universe',+ record: { id: 'u1' },+ assetManifest: huge,+ sourceInstanceId: 'peer-a',+ });+ expect(res.status).toBe(400);+ });+ });++ describe('GET /api/peer-sync/subscriptions', () => {+ it('returns subscriptions and honors query filters', async () => {+ svc.listPeerSubscriptions.mockResolvedValue([+ { id: 'peer-universe-u1-peer-a', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' },+ ]);+ const res = await request(buildApp())+ .get('/api/peer-sync/subscriptions?peerId=peer-a');+ expect(res.status).toBe(200);+ expect(res.body.subscriptions).toHaveLength(1);+ expect(svc.listPeerSubscriptions).toHaveBeenCalledWith({ peerId: 'peer-a' });+ });++ it('ignores non-string query values (no filter applied)', async () => {+ svc.listPeerSubscriptions.mockResolvedValue([]);+ // Repeated `peerId=` keys produce an array under default Express qs+ // parsing — the route guards on `typeof === 'string'` so neither value+ // leaks into the filter.+ const res = await request(buildApp())+ .get('/api/peer-sync/subscriptions?peerId=array&peerId=value');+ expect(res.status).toBe(200);+ expect(svc.listPeerSubscriptions).toHaveBeenCalledWith({});+ });+ });++ describe('POST /api/peer-sync/subscriptions', () => {+ it('201s with the new subscription (matches share-bucket subscribe convention)', async () => {+ svc.subscribePeer.mockResolvedValue({+ id: 'peer-universe-u1-peer-a',+ peerId: 'peer-a',+ recordKind: 'universe',+ recordId: 'u1',+ });+ const res = await request(buildApp())+ .post('/api/peer-sync/subscriptions')+ .send({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });+ expect(res.status).toBe(201);+ expect(res.body.subscription.peerId).toBe('peer-a');+ });++ it('400s when recordKind is "issue" (only universe + series subscribable)', async () => {+ const res = await request(buildApp())+ .post('/api/peer-sync/subscriptions')+ .send({ peerId: 'peer-a', recordKind: 'issue', recordId: 'i1' });+ expect(res.status).toBe(400);+ expect(svc.subscribePeer).not.toHaveBeenCalled();+ });++ it('maps service ERR_VALIDATION to 400', async () => {+ svc.subscribePeer.mockRejectedValue(+ serviceError('boom', 'PEER_SYNC_SUBSCRIPTION_VALIDATION'),+ );+ const res = await request(buildApp())+ .post('/api/peer-sync/subscriptions')+ .send({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });+ expect(res.status).toBe(400);+ });+ });++ describe('DELETE /api/peer-sync/subscriptions/:id', () => {+ it('200s when removed', async () => {+ svc.unsubscribePeer.mockResolvedValue({ id: 'peer-universe-u1-peer-a', removed: true });+ const res = await request(buildApp())+ .delete('/api/peer-sync/subscriptions/peer-universe-u1-peer-a');+ expect(res.status).toBe(200);+ expect(res.body.removed).toBe(true);+ });++ it('404 when the id is unknown', async () => {+ svc.unsubscribePeer.mockRejectedValue(+ serviceError('Peer subscription not found: x', 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND'),+ );+ const res = await request(buildApp())+ .delete('/api/peer-sync/subscriptions/x');+ expect(res.status).toBe(404);+ });+ });+});diff --git a/server/services/sharing/index.js b/server/services/sharing/index.jsindex f1868f0581..fd1090f6f3 100644--- a/server/services/sharing/index.js+++ b/server/services/sharing/index.js@@ -12,6 +12,7 @@ import { join } from 'path';import { attachAllWatchers, attachWatcher, detachWatcher, shutdownAllWatchers, listAttachedWatchers } from './watcher.js';import { sharingEvents } from './importer.js';import { installSubscriptionListener } from './subscriptions.js';+import { installPeerSyncListener } from './peerSync.js';import { initAnnotationsSync } from './annotationsSync.js';export { sharingEvents } from './importer.js';@@ -60,6 +61,10 @@ export async function initSharing({ io: socketIo } = {}) {}installSubscriptionListener();+ // Federated peer-sync listener — installs alongside the share-bucket+ // subscription listener so a single recordEvents `updated` fan-out drives+ // both transports. No state until at least one peer subscription exists.+ installPeerSyncListener();initAnnotationsSync();const result = await attachAllWatchers();console.log(`📡 sharing: initialized, watchers attached for ${result.attached} bucket(s)`);diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 87dc8f683b..d2f82bd23d 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -272,6 +272,38 @@ async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums)return { totalApplied: result.applied ? result.count : 0, checksum: snapshot.checksum };}+/**+ * 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.+ *+ * Mapping:+ * - recordKind 'universe' → category 'universe'+ * - recordKind 'series' → category 'pipeline' (covers series + issues)+ *+ * 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.+ */+async function categoriesCoveredByPeerSync(peerId) {+ // 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+ // those modules until the first sync cycle actually runs, (2) insurance+ // 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');+ }+ return skip;+}+/*** Sync all data from a single peer*/@@ -311,7 +343,20 @@ export async function syncWithPeer(peer) {// --- Snapshot-based category syncs (parallel) ---const dataCategoryResults = {};- const enabledDataCats = dataSync.getSupportedCategories().filter(cat => categories[cat]);+ // 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());+ const enabledDataCats = dataSync.getSupportedCategories()+ .filter(cat => categories[cat])+ .filter(cat => !skipCats.has(cat));const cachedChecksums = cursor.checksums || {};if (enabledDataCats.length > 0) {diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex ea1e198bd7..a1fee46c90 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -27,6 +27,9 @@ vi.mock('./dataSync.js', () => ({applyRemote: vi.fn().mockResolvedValue({ applied: false, count: 0 }),getSupportedCategories: vi.fn(() => ['goals', 'character', 'digitalTwin', 'meatspace'])}));+vi.mock('./sharing/peerSync.js', () => ({+ listPeerSubscriptions: vi.fn().mockResolvedValue([]),+}));vi.mock('./instanceEvents.js', () => ({instanceEvents: { on: vi.fn(), removeListener: vi.fn() }}));@@ -239,6 +242,54 @@ describe('syncOrchestrator', () => {expect(result.brain.totalApplied).toBe(0);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.+ 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);+ expect(urls.some((u) => u.includes('/api/sync/pipeline/'))).toBe(true);+ expect(urls.some((u) => u.includes('/api/sync/character/'))).toBe(true);+ });++ it('skips BOTH universe and pipeline categories when peer is subscribed to both kinds', 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' }) });+ 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);+ });});describe('syncAllPeers', () => {