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): Stage 2 — subscription store + push pipeline + tombstone cursors (#434)

[._.]/ Adam Eivy4061e7e5ea2c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0a0b0e31f6..15cd0ece1e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,6 +1,7 @@
# Unreleased Changes
## Added
+- 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.
## Changed
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index d5203eddbc..95261f6591 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -256,8 +256,13 @@ async function exportMediaJobAndAsset(jobId, bucketPath, mediaRecordsDir, cache)
* Walk a record and collect every (imageJobId, imageRefs, videoPath, sceneVideoJobId)
* it references. Used by the series exporter to enumerate what to copy. The
* caller decides whether to fetch + write the media-job records.
+ *
+ * Exported so the peer-sync push pipeline (services/sharing/peerSync.js) can
+ * build its asset manifest from the same field-walk used for share-bucket
+ * exports — both transports MUST agree on what counts as "an asset of this
+ * record" so a missing-assets diff matches what the sender actually owns.
*/
-function collectAssetReferences(record) {
+export function collectAssetReferences(record) {
const jobIds = new Set();
const directImageFilenames = new Set();
const directVideoFilenames = new Set();
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
new file mode 100644
index 0000000000..0366358f6e
--- /dev/null
+++ b/server/services/sharing/peerSync.js
@@ -0,0 +1,726 @@
+/**
+ * Federated peer-sync: per-record subscription store + push pipeline.
+ *
+ * Sibling of `subscriptions.js` (which targets share-buckets exported to
+ * Google Drive). This module targets *other PortOS instances over Tailnet*
+ * — when you subscribe Universe X to Peer B, every local edit fires a push
+ * to B with the record (sanitized through `syncWire.sanitizeRecordForWire`)
+ * plus a manifest of every asset filename the record references. The
+ * receiver merges via the existing `merge*FromSync` LWW path and responds
+ * with the subset of asset filenames it doesn't yet have on disk; it then
+ * pulls those over HTTP from the sender's `/data/images/*` static mount
+ * (no sender push — receiver-pulls per the user's locked-in decision).
+ *
+ * Soft-deletes ride the same push (the record carries `deleted: true,
+ * deletedAt`); receiver advances its `peerTombstoneCursors` cursor for the
+ * 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.
+ *
+ * State files (under `data/sharing/`):
+ * - `peer_subscriptions.json` — outgoing subscriptions FROM this instance.
+ * Receiver-side auto-created reverse subscriptions also live here.
+ * - `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.
+ */
+
+import { join, basename } from 'path';
+import { existsSync } from 'fs';
+import { PATHS, atomicWrite, readJSONFile, ensureDir, sha256File } from '../../lib/fileUtils.js';
+import { isStr } from '../../lib/storyBible.js';
+import { isPlainObject } from '../../lib/objects.js';
+import { peerBaseUrl } from '../../lib/peerUrl.js';
+import { peerFetch } from '../../lib/peerHttpClient.js';
+import { getOrComputeImageSha256 } from '../../lib/assetHash.js';
+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 { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';
+import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';
+import { listIssues, mergeIssuesFromSync } from '../pipeline/issues.js';
+import {
+ initCursor,
+ ackDeletesUpTo,
+ removeCursor as removeTombstoneCursor,
+} from './peerTombstoneCursors.js';
+
+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series']);
+
+export const ERR_NOT_FOUND = 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND';
+export const ERR_VALIDATION = 'PEER_SYNC_SUBSCRIPTION_VALIDATION';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+const STATE_PATH = () => join(PATHS.data, 'sharing', 'peer_subscriptions.json');
+const DEBOUNCE_MS = 3000;
+const PUSH_TIMEOUT_MS = 30000;
+
+const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;
+
+function subscriptionId({ peerId, recordKind, recordId }) {
+ return `peer-${recordKind}-${recordId}-${peerId}`;
+}
+
+async function readState() {
+ await ensureDir(join(PATHS.data, 'sharing'));
+ const raw = await readJSONFile(STATE_PATH(), { subscriptions: [] }, { logError: false });
+ const subs = Array.isArray(raw?.subscriptions) ? raw.subscriptions : [];
+ return { subscriptions: subs };
+}
+
+async function writeState(state) {
+ await ensureDir(join(PATHS.data, 'sharing'));
+ await atomicWrite(STATE_PATH(), state);
+}
+
+// Serialize every readState→modify→writeState pair through a single tail
+// promise. The push pipeline runs fire-and-forget after each subscribe; its
+// `persistPushSuccess` writes race the subscribe's own writes for the same
+// file, and a naive concurrent run can clobber a just-persisted record
+// (subscribe-s1 reads [u1] from file, push-u1 finishes by writing [u1+meta],
+// subscribe-s1 writes [u1, s1] from its stale in-memory copy, AND VICE VERSA
+// where push-u1 reads [u1] mid-write and clobbers [u1, s1] with [u1+meta]).
+// Single-user / single-instance app, so a module-level tail is sufficient.
+let writeTail = Promise.resolve();
+function withStateLock(fn) {
+ const next = writeTail.then(() => fn(), () => fn());
+ writeTail = next.catch(() => {});
+ return next;
+}
+
+// --- Subscription CRUD --------------------------------------------------
+
+export async function listPeerSubscriptions(filter = {}) {
+ const { subscriptions } = await readState();
+ return subscriptions.filter((s) => {
+ if (filter.peerId && s.peerId !== filter.peerId) return false;
+ if (filter.recordKind && s.recordKind !== filter.recordKind) return false;
+ if (filter.recordId && s.recordId !== filter.recordId) return false;
+ return true;
+ });
+}
+
+export async function findPeerSubscription(peerId, recordKind, recordId) {
+ if (!peerId || !recordKind || !recordId) return null;
+ const { subscriptions } = await readState();
+ return subscriptions.find(
+ (s) => s.peerId === peerId && s.recordKind === recordKind && s.recordId === recordId,
+ ) || null;
+}
+
+/**
+ * Create a peer subscription. Idempotent — re-subscribing returns the existing
+ * record. The first subscribe also initializes the tombstone cursor with
+ * `subscribedSince=now` so tombstones older than the subscription aren't
+ * replayed to the peer.
+ *
+ * `opts.adoptedFromReverse` marks the subscription as auto-created by the
+ * receiver-side reverse-subscribe path; it suppresses the immediate push so
+ * we don't ping-pong (the peer that triggered the reverse just pushed us
+ * the latest state by definition).
+ */
+export async function subscribePeer({ peerId, recordKind, recordId }, opts = {}) {
+ if (!PEER_SUBSCRIBABLE_KINDS.includes(recordKind)) {
+ throw makeErr(`subscribable kinds are ${PEER_SUBSCRIBABLE_KINDS.join(', ')} (got "${recordKind}")`, ERR_VALIDATION);
+ }
+ if (!isNonEmptyStr(peerId) || !isNonEmptyStr(recordId)) {
+ throw makeErr('peerId and recordId are required', ERR_VALIDATION);
+ }
+
+ const sub = 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);
+ if (!existing) {
+ existing = {
+ id,
+ peerId,
+ recordKind,
+ recordId,
+ createdAt: now,
+ updatedAt: now,
+ lastPushedAt: null,
+ lastPushedHash: null,
+ adoptedFromReverse: opts.adoptedFromReverse === true,
+ };
+ state.subscriptions.push(existing);
+ await writeState(state);
+ }
+ return existing;
+ });
+ // 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) {
+ pushRecordToPeer(sub).catch((err) => {
+ console.log(`⚠️ peerSync: initial push failed for ${sub.id}: ${err.message}`);
+ });
+ }
+ return sub;
+}
+
+export async function unsubscribePeer(id) {
+ if (!isNonEmptyStr(id)) throw makeErr('subscription id required', ERR_VALIDATION);
+ const { sub, stillSubscribed } = await withStateLock(async () => {
+ const state = await readState();
+ const idx = state.subscriptions.findIndex((s) => s.id === id);
+ if (idx < 0) throw makeErr(`Peer subscription not found: ${id}`, ERR_NOT_FOUND);
+ const removedSub = state.subscriptions[idx];
+
+ // Cancel any pending debounced push for this subscription so the timer
+ // doesn't fire ~3s later trying to look up a now-deleted sub.
+ const pending = pendingTimers.get(removedSub.id);
+ if (pending) {
+ clearTimeout(pending);
+ pendingTimers.delete(removedSub.id);
+ }
+
+ state.subscriptions.splice(idx, 1);
+ await writeState(state);
+ return {
+ sub: removedSub,
+ stillSubscribed: state.subscriptions.some((s) => s.peerId === removedSub.peerId),
+ };
+ });
+
+ // If this peer no longer has ANY subscriptions, drop its tombstone cursor.
+ // The cursor exists to gate tombstone GC against subscribed peers — once
+ // the peer is fully unsubscribed it has no further claim on tombstones.
+ if (!stillSubscribed) {
+ await removeTombstoneCursor(sub.peerId).catch(() => {});
+ }
+ return { id, removed: true };
+}
+
+/**
+ * Drop every subscription targeting a given peer. Used when removing a peer
+ * from the federation entirely (and by tests).
+ */
+export async function unsubscribeAllForPeer(peerId) {
+ const matching = await listPeerSubscriptions({ peerId });
+ const removed = [];
+ for (const sub of matching) {
+ await unsubscribePeer(sub.id).catch((err) => {
+ console.log(`⚠️ peerSync: unsubscribe-all failed for ${sub.id}: ${err.message}`);
+ });
+ removed.push(sub.id);
+ }
+ return { removed };
+}
+
+// --- Asset manifest -----------------------------------------------------
+
+/**
+ * Given a record, produce a flat manifest `[{ filename, kind, sha256 }]`
+ * the receiver can diff against its local `data/images/` (and friends).
+ *
+ * Stage 2 scope: direct asset filenames only (`imageRefs`, character sheet
+ * pointers, `videoPath`). Job-id resolution (looking up media-job records
+ * to find their result filenames) lands alongside the HTTP route wiring in
+ * Stage 3 — pulling in the media-job-queue dependency would broaden this
+ * module's import graph without a corresponding push-path consumer yet.
+ *
+ * Assets with no readable SHA (file missing, unreadable) are skipped
+ * silently: a sender can't ship bytes it doesn't have on disk, and
+ * including a null-hash entry in the manifest would make every receiver
+ * diff report the asset as missing even though the sender can't fulfill.
+ */
+export async function buildAssetManifest(record) {
+ const refs = collectAssetReferences(record);
+ const out = [];
+ // Each kind maps to a different on-disk directory. We compute SHA only
+ // for images via the sidecar cache (the canonical content-addressed path);
+ // image-refs + videos use `sha256File` on demand and DON'T persist a
+ // sidecar — they don't carry the gen-params provenance images do, and
+ // adding cache writes here would surprise the broader system.
+ for (const filename of refs.directImageFilenames) {
+ const entry = await hashImageForManifest(filename);
+ if (entry) out.push(entry);
+ }
+ for (const filename of refs.directImageRefFilenames) {
+ const entry = await hashSimpleAsset(filename, 'image-ref', PATHS.imageRefs);
+ if (entry) out.push(entry);
+ }
+ for (const filename of refs.directVideoFilenames) {
+ const entry = await hashSimpleAsset(filename, 'video', PATHS.videos);
+ if (entry) out.push(entry);
+ }
+ return out;
+}
+
+async function hashImageForManifest(filename) {
+ if (!isStr(filename)) return null;
+ const fullPath = join(PATHS.images, filename);
+ const result = await getOrComputeImageSha256(fullPath);
+ if (!result) return null;
+ return { filename, kind: 'image', sha256: result.hash };
+}
+
+async function hashSimpleAsset(filename, kind, sourceDir) {
+ if (!isStr(filename) || !isStr(sourceDir)) return null;
+ const fullPath = join(sourceDir, filename);
+ if (!existsSync(fullPath)) return null;
+ const hash = await sha256File(fullPath).catch(() => null);
+ if (!hash) return null;
+ return { filename, kind, sha256: hash };
+}
+
+// --- Receiver-side asset diff -------------------------------------------
+
+/**
+ * Given an incoming asset manifest, return the subset the local instance
+ * does NOT have on disk OR whose local hash differs (peer has a newer
+ * render under the same UUID — rare but possible during concurrent edits).
+ *
+ * The receiver will background-fetch each missing asset from the sender's
+ * `/data/{images,image-refs,videos}/<filename>` static mount.
+ */
+export async function diffAssetManifestAgainstLocal(manifest) {
+ if (!Array.isArray(manifest)) return [];
+ const missing = [];
+ for (const entry of manifest) {
+ if (!isPlainObject(entry) || !isStr(entry.filename) || !isStr(entry.kind)) continue;
+ const dir = directoryForAssetKind(entry.kind);
+ if (!dir) continue;
+ // Peer-supplied filenames go straight into a local `join(dir, name)` here
+ // and via the receiver's reverse-pull GET in Stage 3 — a malicious peer
+ // could probe / hash arbitrary local files with a `../etc/passwd` style
+ // entry. Reject anything that isn't a bare basename before any FS op.
+ const safeName = sanitizeAssetFilename(entry.filename);
+ if (!safeName) continue;
+ // Build a sanitized projection: only the three fields the sender needs
+ // back to pull. Echoing the raw peer-supplied entry would amplify any
+ // junk fields it shipped (large strings, extra kinds, prototype-pollution
+ // attempts) into the response — wire-symmetry should not let untrusted
+ // input round-trip through our process untouched.
+ const sanitizedEntry = {
+ filename: safeName,
+ kind: entry.kind,
+ ...(isStr(entry.sha256) ? { sha256: entry.sha256 } : {}),
+ };
+ const fullPath = join(dir, safeName);
+ if (!existsSync(fullPath)) {
+ missing.push(sanitizedEntry);
+ continue;
+ }
+ // Compare SHA when the manifest carries one — for ALL kinds, not just
+ // images. The image path uses the sidecar cache (fast for the common
+ // ~200-asset universe case); image-ref/video stream-hash on demand.
+ // Existence-only would let a renamed-in-place asset on the receiver
+ // silently mismatch the sender, and the snapshot-sync fallback is the
+ // ONLY thing that would catch it 60s later — better to detect on push.
+ if (isStr(entry.sha256)) {
+ const localHash = entry.kind === 'image'
+ ? (await getOrComputeImageSha256(fullPath))?.hash ?? null
+ : await sha256File(fullPath).catch(() => null);
+ if (localHash !== entry.sha256) missing.push(sanitizedEntry);
+ }
+ }
+ return missing;
+}
+
+function directoryForAssetKind(kind) {
+ if (kind === 'image') return PATHS.images;
+ if (kind === 'image-ref') return PATHS.imageRefs;
+ if (kind === 'video') return PATHS.videos;
+ return null;
+}
+
+/**
+ * Returns the filename if it's safe to use as a path segment under the asset
+ * directory, otherwise null. Rejects path separators, parent-directory
+ * tokens, and any value that doesn't match its own basename — same posture
+ * as `jobFromSidecar` in services/sharing/exporter.js for symmetry with
+ * how the share-bucket importer validates inbound asset filenames.
+ */
+function sanitizeAssetFilename(name) {
+ if (typeof name !== 'string' || !name) return null;
+ if (name.includes('/') || name.includes('\\') || name.includes('..')) return null;
+ if (basename(name) !== name) return null;
+ return name;
+}
+
+// --- Push pipeline (sender side) ----------------------------------------
+
+/**
+ * Load the live record, sanitize for wire, build the asset manifest, and
+ * POST to the peer's `/api/peer-sync/push`. Updates `lastPushedAt` +
+ * `lastPushedHash` on success.
+ *
+ * `lastPushedHash` lets the listener short-circuit no-op edits — if the
+ * sanitized record is byte-for-byte identical to what we last pushed, skip
+ * the network round-trip. (Useful when the snapshot-sync path and the
+ * per-record push path both fire for the same merge.)
+ *
+ * For series subscriptions, the push payload bundles the child issues in
+ * `record.issues` so the receiver applies the series + every issue
+ * atomically per merge cycle. Issue records are filtered through
+ * `sanitizeRecordForWire('issue', ...)` too.
+ */
+export async function pushRecordToPeer(sub) {
+ if (
+ !isPlainObject(sub)
+ || !isNonEmptyStr(sub.peerId)
+ || !isNonEmptyStr(sub.recordKind)
+ || !isNonEmptyStr(sub.recordId)
+ ) {
+ return { pushed: false, reason: 'invalid-subscription' };
+ }
+ const peer = await findPeerById(sub.peerId);
+ if (!peer) return { pushed: false, reason: 'peer-not-found' };
+
+ const ourInstanceId = await getInstanceId().catch(() => null);
+ if (!isNonEmptyStr(ourInstanceId) || ourInstanceId === UNKNOWN_INSTANCE_ID) {
+ return { pushed: false, reason: 'unknown-local-instance' };
+ }
+
+ const payload = await buildPushPayload(sub, ourInstanceId);
+ if (!payload) return { pushed: false, reason: 'record-not-found' };
+
+ // No-op short-circuit: don't re-push bytes we already pushed. Hash the
+ // FULL logical payload (record + bundled issues + asset manifest) — not
+ // just the record — so an issue-only edit, an asset-only re-render, or a
+ // new image landing under the same series still propagates instead of
+ // collapsing to "unchanged" because the parent series didn't move.
+ // sourceInstanceId is intentionally excluded: it's an envelope field, not
+ // a content field, and hashing it would force a re-push every time we
+ // bumped instance metadata.
+ const hash = simplePayloadHash({
+ record: payload.record,
+ issues: payload.issues ?? null,
+ assetManifest: payload.assetManifest ?? [],
+ });
+ if (sub.lastPushedHash && sub.lastPushedHash === hash) {
+ return { pushed: false, reason: 'unchanged', hash };
+ }
+
+ const url = `${peerBaseUrl(peer)}/api/peer-sync/push`;
+ // peerFetch wraps node-fetch with the Tailnet-insecure agent. fetchWithTimeout
+ // can't be reused here because it always calls global fetch (no custom-client
+ // hook), so the timeout is enforced inline with an AbortController so a
+ // hung peer can't keep the push promise pending forever and block subsequent
+ // debounced pushes for the same sub.
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), PUSH_TIMEOUT_MS);
+ const res = await peerFetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ signal: controller.signal,
+ }).catch((err) => {
+ console.log(`⚠️ peerSync: push to ${peer.name || peer.instanceId} failed: ${err.message}`);
+ return null;
+ }).finally(() => clearTimeout(timeoutId));
+ if (!res || !res.ok) {
+ return { pushed: false, reason: res ? `http-${res.status}` : 'network' };
+ }
+ const body = await res.json().catch(() => null);
+
+ // Persist push metadata to peer_subscriptions.json, then advance the
+ // tombstone cursor in peer_tombstone_cursors.json if the receiver acked
+ // any deletions. These are two separate files; a crash between them
+ // leaves the cursor un-advanced for one push cycle, which is safe —
+ // `ackDeletesUpTo` is monotonic + idempotent, so the receiver re-acks
+ // the same deletedAt on the next push and the cursor catches up.
+ await persistPushSuccess(sub.id, hash);
+ if (Number.isFinite(body?.ackedDeletesUpTo) && body.ackedDeletesUpTo > 0) {
+ await ackDeletesUpTo(sub.peerId, body.ackedDeletesUpTo).catch(() => {});
+ }
+ return {
+ pushed: true,
+ hash,
+ response: body || {},
+ missingAssets: Array.isArray(body?.missingAssets) ? body.missingAssets : [],
+ };
+}
+
+async function persistPushSuccess(subId, hash) {
+ await withStateLock(async () => {
+ const state = await readState();
+ const sub = state.subscriptions.find((s) => s.id === subId);
+ if (!sub) return;
+ const now = new Date().toISOString();
+ sub.lastPushedAt = now;
+ sub.lastPushedHash = hash;
+ sub.updatedAt = now;
+ await writeState(state);
+ });
+}
+
+async function buildPushPayload(sub, sourceInstanceId) {
+ if (sub.recordKind === 'universe') {
+ const record = await getUniverse(sub.recordId, { includeDeleted: true }).catch(() => null);
+ if (!record) return null;
+ const sanitized = sanitizeRecordForWire('universe', record);
+ if (!sanitized) return null;
+ const assetManifest = await buildAssetManifest(record);
+ return { kind: 'universe', record: sanitized, assetManifest, sourceInstanceId };
+ }
+ if (sub.recordKind === 'series') {
+ const record = await getSeries(sub.recordId, { includeDeleted: true }).catch(() => null);
+ if (!record) return null;
+ const sanitized = sanitizeRecordForWire('series', record);
+ if (!sanitized) return null;
+ // Bundle child issues — the series + its issues form one unit of edit
+ // for downstream consumers (panels, comic pages), so the receiver
+ // applies them atomically per merge cycle.
+ const childIssues = await listIssues({ seriesId: sub.recordId, includeDeleted: true }).catch(() => []);
+ const sanitizedIssues = childIssues
+ .map((i) => sanitizeRecordForWire('issue', i))
+ .filter(Boolean);
+ const assetManifest = await buildAssetManifestForSeries(record, childIssues);
+ return {
+ kind: 'series',
+ record: sanitized,
+ issues: sanitizedIssues,
+ assetManifest,
+ sourceInstanceId,
+ };
+ }
+ return null;
+}
+
+async function buildAssetManifestForSeries(series, issues) {
+ const seriesAssets = await buildAssetManifest(series);
+ const dedup = new Map(seriesAssets.map((a) => [`${a.kind}:${a.filename}`, a]));
+ for (const issue of issues) {
+ const issueAssets = await buildAssetManifest(issue);
+ for (const a of issueAssets) {
+ dedup.set(`${a.kind}:${a.filename}`, a);
+ }
+ }
+ return [...dedup.values()];
+}
+
+// Tiny stable-string hash for the push short-circuit. NOT a cryptographic
+// hash — we just need "is this the same record we last pushed". Collisions
+// at this size mean we MIGHT skip a real edit, but the snapshot sync would
+// catch it within 60s, so the cost is bounded.
+function simplePayloadHash(record) {
+ // JSON.stringify is key-order sensitive, and sanitizeRecordForWire
+ // guarantees a canonical key order — so two identical logical records
+ // produce identical hashes here.
+ const json = JSON.stringify(record);
+ let h = 0;
+ for (let i = 0; i < json.length; i++) {
+ h = ((h << 5) - h + json.charCodeAt(i)) | 0;
+ }
+ return h.toString(16);
+}
+
+async function findPeerById(peerId) {
+ const peers = await getPeers().catch(() => []);
+ return peers.find((p) => p.instanceId === peerId) || null;
+}
+
+// --- Receiver-side push handler -----------------------------------------
+
+/**
+ * Apply an incoming push to local state. Wraps the existing `merge*FromSync`
+ * dispatch + computes the asset-diff response + (best-effort) creates a
+ * reverse subscription back to the sender so subsequent edits flow both
+ * ways without manual re-configuration.
+ *
+ * The HTTP route in Stage 3 will be a thin wrapper around this — validate
+ * the body shape, call this function, return the response.
+ */
+export async function applyIncomingPush(payload) {
+ if (!isPlainObject(payload)) {
+ throw makeErr('payload must be an object', ERR_VALIDATION);
+ }
+ const { kind, record, issues, assetManifest, sourceInstanceId } = payload;
+ if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {
+ throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);
+ }
+ // sourceInstanceId is the key we hang the per-peer tombstone cursor on;
+ // empty / "unknown" would poison the cursor table with a synthetic entry
+ // that never gets cleaned up.
+ if (!isNonEmptyStr(sourceInstanceId) || sourceInstanceId === UNKNOWN_INSTANCE_ID) {
+ throw makeErr('sourceInstanceId required (and not "unknown")', ERR_VALIDATION);
+ }
+ if (!isPlainObject(record) || !isNonEmptyStr(record.id)) {
+ throw makeErr('record must be an object with a string id', ERR_VALIDATION);
+ }
+
+ // Merge into local state via the existing LWW path. The merge functions
+ // honor `deleted: true` + bump `updatedAt`, so this is the single
+ // tombstone-aware reconciliation point.
+ if (kind === 'universe') {
+ await mergeUniversesFromSync([record]);
+ } else if (kind === 'series') {
+ await mergeSeriesFromSync([record]);
+ if (Array.isArray(issues) && issues.length > 0) {
+ await mergeIssuesFromSync(issues);
+ }
+ }
+
+ // Diff incoming asset manifest against local disk. We (the receiver) are
+ // the ones that will background-pull `missingAssets` from the sender's
+ // `/data/{images,image-refs,videos}/<filename>` static mount in Stage 3
+ // — the sender just needs to keep those files served, no action required
+ // from it here. We return the list to the sender in the response so it
+ // can surface progress in its UI ("N/M assets still syncing to peer X").
+ const missingAssets = await diffAssetManifestAgainstLocal(assetManifest);
+
+ // Compute the deletedAt water-mark we can ack. Use the maximum across the
+ // record + its issues (a single push can carry multiple tombstones).
+ const ackedDeletesUpTo = computeAckedDeletesFromPayload(record, issues);
+ if (ackedDeletesUpTo > 0) {
+ await ackDeletesUpTo(sourceInstanceId, ackedDeletesUpTo).catch(() => {});
+ }
+
+ // Best-effort reverse subscription. Failures don't fail the push — the
+ // record is already merged and the response will tell the sender what
+ // assets to push next. The reverse subscription only affects whether
+ // future edits flow BACK; the user can also create one manually.
+ const reverseSubscriptionCreated = await maybeCreateReverseSubscription({
+ peerId: sourceInstanceId,
+ recordKind: kind,
+ recordId: record.id,
+ }).catch(() => false);
+
+ return {
+ missingAssets,
+ reverseSubscriptionCreated,
+ ackedDeletesUpTo,
+ };
+}
+
+function computeAckedDeletesFromPayload(record, issues) {
+ let max = 0;
+ const consider = (rec) => {
+ if (!rec?.deleted || !isStr(rec.deletedAt)) return;
+ const ms = Date.parse(rec.deletedAt);
+ if (Number.isFinite(ms) && ms > max) max = ms;
+ };
+ consider(record);
+ if (Array.isArray(issues)) for (const i of issues) consider(i);
+ return max;
+}
+
+async function maybeCreateReverseSubscription({ peerId, recordKind, recordId }) {
+ // Skip if a subscription back to the sender already exists.
+ const existing = await findPeerSubscription(peerId, recordKind, recordId);
+ if (existing) return false;
+
+ // Honor the per-peer `directions` flag. A peer marked inbound-only is one
+ // we accept pushes FROM but never push back TO — auto-creating a reverse
+ // subscription would break that explicit configuration.
+ const peer = await findPeerById(peerId);
+ if (!peer) return false;
+ const directions = Array.isArray(peer.directions) ? peer.directions : [];
+ if (directions.length > 0 && !directions.includes('outbound')) return false;
+
+ await subscribePeer({ peerId, recordKind, recordId }, { adoptedFromReverse: true });
+ return true;
+}
+
+// --- Listener install + debounced trigger -------------------------------
+
+const pendingTimers = new Map(); // subId → Timeout
+
+/**
+ * Schedule a debounced push for every subscription whose record was just
+ * updated. The 3s window matches the share-bucket subscriptions debounce
+ * so a flurry of edits coalesces into one push per ~3s.
+ *
+ * Issues piggyback on their series' subscription: an issue update triggers
+ * a push of the parent series (which re-bundles every issue). This keeps
+ * the subscription model simple — users subscribe at universe/series
+ * granularity, and child issue edits flow automatically.
+ */
+export async function triggerPushForRecord(recordKind, recordId) {
+ const subs = await collectSubscriptionsForUpdate(recordKind, recordId);
+ for (const sub of subs) {
+ const existing = pendingTimers.get(sub.id);
+ if (existing) clearTimeout(existing);
+ const subId = sub.id;
+ const t = setTimeout(() => {
+ pendingTimers.delete(subId);
+ // Re-load the subscription by id rather than reusing the snapshot
+ // captured when this timer was scheduled. Three things can have moved
+ // since: (1) lastPushedHash advanced (the no-op short-circuit would
+ // miss otherwise and re-push redundantly), (2) the sub was unsubscribed
+ // (we'd be pushing for nothing), (3) a subsequent edit landed under a
+ // newer hash. Reading the live record by id makes the debounced fire
+ // safe against all three.
+ pushFromFreshSubscription(subId).catch((err) => {
+ console.log(`⚠️ peerSync: scheduled push failed for ${subId}: ${err.message}`);
+ });
+ }, DEBOUNCE_MS);
+ if (typeof t.unref === 'function') t.unref();
+ pendingTimers.set(sub.id, t);
+ }
+}
+
+async function pushFromFreshSubscription(subId) {
+ const { subscriptions } = await readState();
+ const fresh = subscriptions.find((s) => s.id === subId);
+ if (!fresh) return; // unsubscribed between schedule and fire
+ return pushRecordToPeer(fresh);
+}
+
+/**
+ * For an `(updated)` event on `(recordKind, recordId)`, return every
+ * subscription that should fire a push:
+ * - Direct subscriptions on the record itself.
+ * - For issue updates, the subscription on the parent series (resolved
+ * via `getIssueSeriesId` — see below).
+ */
+async function collectSubscriptionsForUpdate(recordKind, recordId) {
+ if (recordKind === 'universe' || recordKind === 'series') {
+ return listPeerSubscriptions({ recordKind, recordId });
+ }
+ if (recordKind === 'issue') {
+ const seriesId = await getIssueSeriesId(recordId);
+ if (!seriesId) return [];
+ return listPeerSubscriptions({ recordKind: 'series', recordId: seriesId });
+ }
+ return [];
+}
+
+async function getIssueSeriesId(issueId) {
+ // Avoid pulling in `getIssue` directly (cyclic risk during init): list
+ // the cohort of issues and pick the matching id. The issues file is
+ // small (low hundreds at most), so this is fine for the debounce path.
+ const issues = await listIssues({ includeDeleted: true }).catch(() => []);
+ const found = issues.find((i) => i.id === issueId);
+ return found?.seriesId || null;
+}
+
+let onUpdated = null;
+
+/** Attach the `recordEvents` listener — call once during sharing init. */
+export function installPeerSyncListener() {
+ if (onUpdated) return;
+ onUpdated = ({ recordKind, recordId }) => {
+ triggerPushForRecord(recordKind, recordId).catch((err) => {
+ console.log(`⚠️ peerSync: listener error for ${recordKind}/${recordId}: ${err.message}`);
+ });
+ };
+ recordEvents.on('updated', onUpdated);
+}
+
+/**
+ * Test-only: clear pending debounces, detach our listener, and await any
+ * in-flight state writes so the test can rm-rf the tmpdir without an
+ * ENOTEMPTY race. Async so callers can `await __resetForTests()`.
+ */
+export async function __resetForTests() {
+ for (const t of pendingTimers.values()) clearTimeout(t);
+ pendingTimers.clear();
+ if (onUpdated) recordEvents.off('updated', onUpdated);
+ onUpdated = null;
+ await writeTail.catch(() => {});
+}
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
new file mode 100644
index 0000000000..a977866661
--- /dev/null
+++ b/server/services/sharing/peerSync.test.js
@@ -0,0 +1,607 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdir, rm, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+// We test peerSync.js by stubbing the external dependencies:
+// - getPeers / getInstanceId from services/instances
+// - merge*FromSync + getUniverse + getSeries + listIssues
+// - peerFetch (network)
+// All other logic (subscription store, asset manifest, diff, cursor advance)
+// runs against the real on-disk paths via the tmpdir-redirect pattern below.
+
+import { PATHS } from '../../lib/fileUtils.js';
+
+vi.mock('../instances.js', async () => {
+ return {
+ UNKNOWN_INSTANCE_ID: 'unknown',
+ DEFAULT_SYNC_CATEGORIES: {},
+ getInstanceId: vi.fn(),
+ getPeers: vi.fn(),
+ };
+});
+
+vi.mock('../universeBuilder.js', async () => ({
+ getUniverse: vi.fn(),
+ mergeUniversesFromSync: vi.fn(),
+}));
+
+vi.mock('../pipeline/series.js', async () => ({
+ getSeries: vi.fn(),
+ mergeSeriesFromSync: vi.fn(),
+}));
+
+vi.mock('../pipeline/issues.js', async () => ({
+ listIssues: vi.fn(),
+ mergeIssuesFromSync: vi.fn(),
+}));
+
+vi.mock('../../lib/peerHttpClient.js', async () => ({
+ peerFetch: vi.fn(),
+ peerSocketOptions: {},
+}));
+
+import {
+ PEER_SUBSCRIBABLE_KINDS,
+ listPeerSubscriptions,
+ findPeerSubscription,
+ subscribePeer,
+ unsubscribePeer,
+ unsubscribeAllForPeer,
+ pushRecordToPeer,
+ applyIncomingPush,
+ diffAssetManifestAgainstLocal,
+ buildAssetManifest,
+ __resetForTests,
+} from './peerSync.js';
+
+import { getInstanceId, getPeers } from '../instances.js';
+import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';
+import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';
+import { listIssues, mergeIssuesFromSync } from '../pipeline/issues.js';
+import { peerFetch } from '../../lib/peerHttpClient.js';
+import { listCursors } from './peerTombstoneCursors.js';
+
+let originalDataPath;
+let originalImagesPath;
+let originalImageRefsPath;
+let originalVideosPath;
+let tmp;
+
+beforeEach(async () => {
+ // Capture EVERY PATHS field we (or any test in this file) might mutate so
+ // the afterEach restoration is total. The sha-mismatch-for-all-kinds test
+ // points PATHS.imageRefs / PATHS.videos at the per-test tmpdir; without
+ // restoring them here, later tests in unrelated files inherit the deleted
+ // tmpdir and get ENOENT on real asset reads.
+ originalDataPath = PATHS.data;
+ originalImagesPath = PATHS.images;
+ originalImageRefsPath = PATHS.imageRefs;
+ originalVideosPath = PATHS.videos;
+ tmp = join(tmpdir(), `portos-peer-sync-${Date.now()}-${Math.random()}`);
+ await mkdir(join(tmp, 'sharing'), { recursive: true });
+ await mkdir(join(tmp, 'images'), { recursive: true });
+ PATHS.data = tmp;
+ PATHS.images = join(tmp, 'images');
+
+ // Reset mocks
+ 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'] },
+ ]);
+ vi.mocked(peerFetch).mockReset();
+ vi.mocked(mergeUniversesFromSync).mockResolvedValue({ applied: true, count: 1 });
+ vi.mocked(mergeSeriesFromSync).mockResolvedValue({ applied: true, count: 1 });
+ vi.mocked(mergeIssuesFromSync).mockResolvedValue({ applied: true, count: 1 });
+ vi.mocked(getUniverse).mockReset();
+ vi.mocked(getSeries).mockReset();
+ vi.mocked(listIssues).mockReset();
+
+ await __resetForTests();
+});
+
+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();
+ await rm(tmp, { recursive: true, force: true });
+ PATHS.data = originalDataPath;
+ PATHS.images = originalImagesPath;
+ PATHS.imageRefs = originalImageRefsPath;
+ PATHS.videos = originalVideosPath;
+});
+
+describe('peerSync', () => {
+ describe('PEER_SUBSCRIBABLE_KINDS', () => {
+ it('exposes the canonical kinds (universe + series only)', () => {
+ // Issues piggyback on series subscriptions — direct issue subs are
+ // intentionally rejected per the Stage 2 design.
+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series']);
+ });
+ });
+
+ describe('subscribePeer', () => {
+ it('creates a subscription, initializes the tombstone cursor, and schedules a push', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo', updatedAt: '2026-01-01T00:00:00Z' });
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });
+ const sub = await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ expect(sub.id).toBe('peer-universe-u1-peer-a');
+ expect(sub.peerId).toBe('peer-a');
+ expect(sub.adoptedFromReverse).toBe(false);
+ // Cursor initialized
+ const cursors = await listCursors();
+ expect(cursors['peer-a']).toBeDefined();
+ expect(cursors['peer-a'].subscribedSince).toBeGreaterThan(0);
+ });
+
+ it('is idempotent — re-subscribing returns the existing record without duplicating', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo', updatedAt: '2026-01-01T00:00:00Z' });
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });
+ 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);
+ const all = await listPeerSubscriptions();
+ expect(all).toHaveLength(1);
+ });
+
+ it('rejects invalid kind', async () => {
+ await expect(
+ subscribePeer({ peerId: 'peer-a', recordKind: 'issue', recordId: 'i1' }),
+ ).rejects.toThrow(/subscribable kinds/);
+ });
+
+ it('rejects missing peerId / recordId', async () => {
+ await expect(
+ subscribePeer({ peerId: '', recordKind: 'universe', recordId: 'u1' }),
+ ).rejects.toThrow(/required/);
+ await expect(
+ subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: '' }),
+ ).rejects.toThrow(/required/);
+ });
+
+ it('does NOT push when adoptedFromReverse=true (avoids ping-pong with the peer that just pushed us)', async () => {
+ // Regression: receiver auto-creates a reverse sub on each incoming push.
+ // If that reverse sub triggered an initial push, we'd ping-pong forever.
+ 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' },
+ { adoptedFromReverse: true },
+ );
+ // peerFetch may have been called for some other reason, but NOT
+ // synchronously from this code path. Allow a small wait to be sure.
+ await new Promise((r) => setTimeout(r, 10));
+ expect(peerFetch).not.toHaveBeenCalled();
+ });
+ });
+
+ 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' });
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ const sub = await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ await unsubscribePeer(sub.id);
+ const cursors = await listCursors();
+ expect(cursors['peer-a']).toBeUndefined();
+ });
+
+ it('keeps the peer cursor when other subscriptions to the same peer remain', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Bar' });
+ vi.mocked(listIssues).mockResolvedValue([]);
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ const sub1 = await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'series', recordId: 's1' });
+ await unsubscribePeer(sub1.id);
+ const cursors = await listCursors();
+ expect(cursors['peer-a']).toBeDefined();
+ });
+
+ it('throws ERR_NOT_FOUND for unknown id', async () => {
+ await expect(unsubscribePeer('peer-universe-x-peer-a')).rejects.toMatchObject({
+ code: 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND',
+ });
+ });
+ });
+
+ describe('unsubscribeAllForPeer', () => {
+ it('removes every subscription targeting a peer', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1' });
+ vi.mocked(getSeries).mockResolvedValue({ id: 's1' });
+ vi.mocked(listIssues).mockResolvedValue([]);
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' });
+ await subscribePeer({ peerId: 'peer-a', recordKind: 'series', recordId: 's1' });
+ const result = await unsubscribeAllForPeer('peer-a');
+ expect(result.removed).toHaveLength(2);
+ expect(await findPeerSubscription('peer-a', 'universe', 'u1')).toBeNull();
+ });
+ });
+
+ describe('buildAssetManifest', () => {
+ it('hashes direct image filenames via the sidecar cache', async () => {
+ await writeFile(join(PATHS.images, 'asset-1.png'), Buffer.from('image bytes'));
+ const record = {
+ id: 'u1',
+ characters: [{ imageRefs: ['asset-1.png'] }],
+ };
+ const manifest = await buildAssetManifest(record);
+ expect(manifest).toHaveLength(1);
+ expect(manifest[0].filename).toBe('asset-1.png');
+ expect(manifest[0].kind).toBe('image');
+ expect(manifest[0].sha256).toMatch(/^[a-f0-9]{64}$/);
+ });
+
+ it('skips assets whose file is missing (sender cant ship bytes it doesnt have)', async () => {
+ // Regression: a null-hash entry would make every receiver diff
+ // report this as "missing" even though the sender cant fulfill the
+ // pull, producing a permanent "asset pending" badge in the UI.
+ const record = { id: 'u1', characters: [{ imageRefs: ['ghost.png'] }] };
+ const manifest = await buildAssetManifest(record);
+ expect(manifest).toEqual([]);
+ });
+
+ it('returns an empty manifest for records with no asset refs', async () => {
+ const manifest = await buildAssetManifest({ id: 'u1', name: 'Bare' });
+ expect(manifest).toEqual([]);
+ });
+ });
+
+ describe('diffAssetManifestAgainstLocal', () => {
+ it('returns assets we dont have on disk', async () => {
+ const missing = await diffAssetManifestAgainstLocal([
+ { filename: 'ghost.png', kind: 'image', sha256: 'a'.repeat(64) },
+ ]);
+ expect(missing).toHaveLength(1);
+ expect(missing[0].filename).toBe('ghost.png');
+ });
+
+ it('skips assets we already have with matching sha', async () => {
+ await writeFile(join(PATHS.images, 'have.png'), Buffer.from('hello world'));
+ // "hello world" sha256
+ const local = 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9';
+ const missing = await diffAssetManifestAgainstLocal([
+ { filename: 'have.png', kind: 'image', sha256: local },
+ ]);
+ expect(missing).toEqual([]);
+ });
+
+ it('reports assets with mismatched sha as missing (peer has newer bytes)', async () => {
+ await writeFile(join(PATHS.images, 'stale.png'), Buffer.from('old bytes'));
+ const missing = await diffAssetManifestAgainstLocal([
+ { filename: 'stale.png', kind: 'image', sha256: 'b'.repeat(64) },
+ ]);
+ expect(missing).toHaveLength(1);
+ });
+
+ it('ignores malformed manifest entries silently', async () => {
+ const missing = await diffAssetManifestAgainstLocal([
+ null,
+ 'not-an-object',
+ { filename: '', kind: 'image' },
+ { filename: 'foo.png', kind: 'mystery' },
+ ]);
+ expect(missing).toEqual([]);
+ });
+
+ it('strips junk fields from echoed missingAssets entries (no untrusted round-trip)', async () => {
+ // Regression: the diff originally pushed the raw peer-supplied entry
+ // into the missing list, so a malicious peer could amplify response
+ // size or smuggle prototype-pollution attempts by attaching extra
+ // fields. The receiver MUST project to {filename, kind, sha256?} only.
+ const evil = {
+ filename: 'absent.png',
+ kind: 'image',
+ sha256: 'a'.repeat(64),
+ __proto__: { polluted: true },
+ gigantic: 'x'.repeat(10000),
+ nested: { evil: true },
+ };
+ const missing = await diffAssetManifestAgainstLocal([evil]);
+ expect(missing).toHaveLength(1);
+ expect(Object.keys(missing[0]).sort()).toEqual(['filename', 'kind', 'sha256']);
+ expect(missing[0].gigantic).toBeUndefined();
+ expect(missing[0].nested).toBeUndefined();
+ });
+
+ it('rejects path-traversal filenames silently (cant be used to probe local FS)', async () => {
+ // Regression: a malicious peer sending `../../etc/passwd` (or backslash
+ // variants on Windows checkouts) would otherwise let us join arbitrary
+ // paths and reveal whether they exist via the missing/present split.
+ const missing = await diffAssetManifestAgainstLocal([
+ { filename: '../../etc/passwd', kind: 'image', sha256: 'a'.repeat(64) },
+ { filename: '..\\windows\\system32\\config', kind: 'image' },
+ { filename: 'sub/dir/asset.png', kind: 'image' },
+ { filename: '/etc/hosts', kind: 'image' },
+ ]);
+ expect(missing).toEqual([]);
+ });
+
+ it('reports sha-mismatched videos AND image-refs as missing (not just images)', async () => {
+ // Regression: stage 2 originally only sha-checked the 'image' kind,
+ // letting an image-ref / video drift silently when bytes diverged
+ // under the same filename — the snapshot-sync fallback was the only
+ // thing that would catch it 60s later.
+ await mkdir(join(tmp, 'image-refs'), { recursive: true });
+ await mkdir(join(tmp, 'videos'), { recursive: true });
+ // Re-route PATHS by writing into the locations the resolver uses.
+ const localImageRefBytes = Buffer.from('local image-ref bytes');
+ const localVideoBytes = Buffer.from('local video bytes');
+ const { PATHS: livePaths } = await import('../../lib/fileUtils.js');
+ livePaths.imageRefs = join(tmp, 'image-refs');
+ livePaths.videos = join(tmp, 'videos');
+ const { writeFile: writeFileFs } = await import('fs/promises');
+ await writeFileFs(join(livePaths.imageRefs, 'ref.png'), localImageRefBytes);
+ await writeFileFs(join(livePaths.videos, 'clip.mp4'), localVideoBytes);
+ const remoteFakeSha = 'f'.repeat(64);
+ const missing = await diffAssetManifestAgainstLocal([
+ { filename: 'ref.png', kind: 'image-ref', sha256: remoteFakeSha },
+ { filename: 'clip.mp4', kind: 'video', sha256: remoteFakeSha },
+ ]);
+ expect(missing).toHaveLength(2);
+ expect(missing.map((m) => m.filename).sort()).toEqual(['clip.mp4', 'ref.png']);
+ });
+ });
+
+ describe('pushRecordToPeer', () => {
+ it('refuses to push when our instance id is unknown', async () => {
+ vi.mocked(getInstanceId).mockResolvedValue('unknown');
+ const result = await pushRecordToPeer({
+ id: 's', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
+ });
+ expect(result.pushed).toBe(false);
+ expect(result.reason).toBe('unknown-local-instance');
+ expect(peerFetch).not.toHaveBeenCalled();
+ });
+
+ it('refuses to push when the target peer is missing from the registry', async () => {
+ const result = await pushRecordToPeer({
+ id: 's', peerId: 'peer-ghost', recordKind: 'universe', recordId: 'u1',
+ });
+ expect(result.pushed).toBe(false);
+ expect(result.reason).toBe('peer-not-found');
+ });
+
+ it('returns record-not-found when the record id no longer exists', async () => {
+ vi.mocked(getUniverse).mockResolvedValue(null);
+ const result = await pushRecordToPeer({
+ id: 's', peerId: 'peer-a', recordKind: 'universe', recordId: 'gone',
+ });
+ expect(result.pushed).toBe(false);
+ expect(result.reason).toBe('record-not-found');
+ });
+
+ it('short-circuits when the record hashes match the last push (no-op edits dont round-trip)', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ // Subscribe with adoptedFromReverse=true to suppress the auto-push so
+ // we control timing explicitly — relying on a sleep to drain the
+ // fire-and-forget push is flaky on slower CI runners.
+ const sub = await subscribePeer(
+ { peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' },
+ { adoptedFromReverse: true },
+ );
+ const first = await pushRecordToPeer(sub);
+ expect(first.pushed).toBe(true);
+ expect(first.hash).toBeTruthy();
+ vi.mocked(peerFetch).mockClear();
+ const refreshed = await findPeerSubscription('peer-a', 'universe', 'u1');
+ const result = await pushRecordToPeer(refreshed);
+ expect(result.pushed).toBe(false);
+ expect(result.reason).toBe('unchanged');
+ expect(peerFetch).not.toHaveBeenCalled();
+ });
+
+ it('persists ackedDeletesUpTo from the peer response to the tombstone cursor', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ vi.mocked(peerFetch).mockResolvedValue({
+ ok: true,
+ json: async () => ({ missingAssets: [], ackedDeletesUpTo: 5000 }),
+ });
+ const sub = await subscribePeer(
+ { peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' },
+ { adoptedFromReverse: true },
+ );
+ await pushRecordToPeer(sub);
+ const cursors = await listCursors();
+ expect(cursors['peer-a'].lastAckedDeleteAt).toBe(5000);
+ });
+
+ it('handles a network-level failure without throwing (returns pushed:false)', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ vi.mocked(peerFetch).mockRejectedValue(new Error('ECONNREFUSED'));
+ const result = await pushRecordToPeer({
+ id: 's', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
+ });
+ expect(result.pushed).toBe(false);
+ expect(result.reason).toBe('network');
+ });
+
+ it('does NOT short-circuit when the parent series record is identical but a bundled issue changed', async () => {
+ // Regression: simplePayloadHash originally hashed only payload.record,
+ // so a series push where only an issue field changed (a common case —
+ // every panel edit propagates as an issue update under a series sub)
+ // would collapse to reason: 'unchanged' and never propagate.
+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });
+ vi.mocked(listIssues).mockResolvedValueOnce([
+ { id: 'i1', seriesId: 's1', number: 1, title: 'First' },
+ ]);
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ const sub = await subscribePeer(
+ { peerId: 'peer-a', recordKind: 'series', recordId: 's1' },
+ { adoptedFromReverse: true },
+ );
+ const first = await pushRecordToPeer(sub);
+ expect(first.pushed).toBe(true);
+
+ // Series record identical, but child issue title changed → MUST re-push.
+ vi.mocked(listIssues).mockResolvedValueOnce([
+ { id: 'i1', seriesId: 's1', number: 1, title: 'Revised' },
+ ]);
+ vi.mocked(peerFetch).mockClear();
+ const refreshed = await findPeerSubscription('peer-a', 'series', 's1');
+ const second = await pushRecordToPeer(refreshed);
+ expect(second.pushed).toBe(true);
+ expect(second.reason).not.toBe('unchanged');
+ expect(peerFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('bundles child issues with a series push', async () => {
+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });
+ vi.mocked(listIssues).mockResolvedValue([
+ { id: 'i1', seriesId: 's1', number: 1 },
+ { id: 'i2', seriesId: 's1', number: 2 },
+ ]);
+ let captured = null;
+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {
+ captured = JSON.parse(opts.body);
+ return { ok: true, json: async () => ({}) };
+ });
+ await pushRecordToPeer({
+ id: 's', peerId: 'peer-a', recordKind: 'series', recordId: 's1',
+ });
+ expect(captured.kind).toBe('series');
+ expect(captured.issues).toHaveLength(2);
+ expect(captured.issues.map((i) => i.id)).toEqual(['i1', 'i2']);
+ });
+ });
+
+ describe('applyIncomingPush', () => {
+ it('rejects payloads without a known kind', async () => {
+ await expect(applyIncomingPush({ kind: 'mystery', record: { id: 'x' }, sourceInstanceId: 'peer-a' }))
+ .rejects.toThrow(/unknown kind/);
+ });
+
+ it('rejects pushes from sourceInstanceId="unknown"', async () => {
+ // The sender's instance id is the identity we hang the cursor on.
+ // Accepting an "unknown" sourceInstanceId would poison the cursor
+ // table with a synthetic key that never gets cleaned up.
+ await expect(applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1' },
+ sourceInstanceId: 'unknown',
+ })).rejects.toThrow(/sourceInstanceId required/);
+ });
+
+ it('rejects payloads with a missing/malformed record', async () => {
+ await expect(applyIncomingPush({
+ kind: 'universe',
+ record: 'not-an-object',
+ sourceInstanceId: 'peer-a',
+ })).rejects.toThrow(/object with a string id/);
+ });
+
+ it('dispatches universe pushes through mergeUniversesFromSync', async () => {
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1', name: 'Foo', deleted: false, deletedAt: null },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(mergeUniversesFromSync).toHaveBeenCalledWith([
+ expect.objectContaining({ id: 'u1' }),
+ ]);
+ });
+
+ it('dispatches series pushes through mergeSeriesFromSync AND mergeIssuesFromSync for bundled issues', async () => {
+ await applyIncomingPush({
+ kind: 'series',
+ record: { id: 's1', deleted: false, deletedAt: null },
+ issues: [{ id: 'i1', seriesId: 's1', deleted: false, deletedAt: null }],
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(mergeSeriesFromSync).toHaveBeenCalled();
+ expect(mergeIssuesFromSync).toHaveBeenCalledWith([
+ expect.objectContaining({ id: 'i1' }),
+ ]);
+ });
+
+ it('reports missing assets in the response', async () => {
+ const result = await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1' },
+ assetManifest: [{ filename: 'absent.png', kind: 'image', sha256: 'a'.repeat(64) }],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(result.missingAssets).toHaveLength(1);
+ });
+
+ it('advances the sender cursor when the payload carries a tombstone', async () => {
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1', deleted: true, deletedAt: '2026-01-01T00:00:00Z' },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ const cursors = await listCursors();
+ expect(cursors['peer-a'].lastAckedDeleteAt).toBe(Date.parse('2026-01-01T00:00:00Z'));
+ });
+
+ it('picks the MAX deletedAt across record + bundled issues for the cursor advance', async () => {
+ // Regression: if only `record.deletedAt` is considered, a series push
+ // bundling multiple tombstoned issues would advance the cursor only
+ // by the series' own deletion time — newer issue tombstones in the
+ // same push would never be acknowledged until a separate push lands.
+ await applyIncomingPush({
+ kind: 'series',
+ record: { id: 's1', deleted: true, deletedAt: '2026-01-01T00:00:00Z' },
+ issues: [
+ { id: 'i1', deleted: true, deletedAt: '2026-03-01T00:00:00Z' },
+ { id: 'i2', deleted: false },
+ ],
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ const cursors = await listCursors();
+ expect(cursors['peer-a'].lastAckedDeleteAt).toBe(Date.parse('2026-03-01T00:00:00Z'));
+ });
+
+ it('auto-creates a reverse subscription back to the sender', async () => {
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1' },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ const sub = await findPeerSubscription('peer-a', 'universe', 'u1');
+ expect(sub).not.toBeNull();
+ expect(sub.adoptedFromReverse).toBe(true);
+ });
+
+ it('does NOT create a reverse subscription when the sender peer is configured as inbound-only', async () => {
+ // peer-b-inbound-only has directions: ['inbound']. The user explicitly
+ // told this instance not to push back to them — auto-creating a
+ // reverse subscription would override that intent.
+ const result = await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1' },
+ assetManifest: [],
+ sourceInstanceId: 'peer-b-inbound-only',
+ });
+ expect(result.reverseSubscriptionCreated).toBe(false);
+ const sub = await findPeerSubscription('peer-b-inbound-only', 'universe', 'u1');
+ expect(sub).toBeNull();
+ });
+
+ it('does NOT duplicate a reverse subscription on subsequent pushes', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1' },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1', updatedAt: '2026-01-02T00:00:00Z' },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ const all = await listPeerSubscriptions({ peerId: 'peer-a' });
+ expect(all).toHaveLength(1);
+ });
+ });
+});
diff --git a/server/services/sharing/peerTombstoneCursors.js b/server/services/sharing/peerTombstoneCursors.js
new file mode 100644
index 0000000000..53ff10746f
--- /dev/null
+++ b/server/services/sharing/peerTombstoneCursors.js
@@ -0,0 +1,168 @@
+/**
+ * Per-peer tombstone ack cursors for federated peer sync.
+ *
+ * When a record is soft-deleted (the Stage 1 tombstone refactor), it stays in
+ * the JSON file with `{ deleted: true, deletedAt: <iso> }` so the LWW merge
+ * can keep it from being resurrected by an out-of-date peer. The tombstone
+ * itself is GC'd only once every currently-subscribed peer has acked that it
+ * received and applied the deletion — otherwise pruning the tombstone too
+ * early lets the next snapshot-sync from a not-yet-aware peer resurrect the
+ * record by re-inserting it under its older `updatedAt`.
+ *
+ * Each cursor tracks two values per peer:
+ * - `lastAckedDeleteAt` — the latest `deletedAt` (ms epoch) the peer has
+ * confirmed receiving. Used by `getMinAckAcrossPeers` to decide which
+ * tombstones are safe to prune.
+ * - `subscribedSince` — the horizon at which the peer first subscribed (ms
+ * epoch). The push pipeline never replays tombstones older than this —
+ * a new peer joining a long-lived federation shouldn't have to ingest
+ * every historical deletion, just the live state plus tombstones it
+ * might still see referenced by stale peers.
+ *
+ * State file: `data/sharing/peer_tombstone_cursors.json`. The whole file is
+ * a small object keyed by peerId, so each write rewrites the file — that's
+ * fine at sharing scale (dozens of peers max).
+ */
+
+import { join } from 'path';
+import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
+import { isPlainObject } from '../../lib/objects.js';
+
+const STATE_PATH = () => join(PATHS.data, 'sharing', 'peer_tombstone_cursors.json');
+
+/**
+ * Load the full cursor map. Tolerates a missing or malformed file by
+ * returning `{}` — peers that have never sync'd carry no cursor.
+ */
+async function readState() {
+ await ensureDir(join(PATHS.data, 'sharing'));
+ const raw = await readJSONFile(STATE_PATH(), {}, { logError: false });
+ if (!isPlainObject(raw)) return {};
+ // Defensive: a hand-edited file could contain non-object entries.
+ const out = {};
+ for (const [peerId, cursor] of Object.entries(raw)) {
+ if (typeof peerId !== 'string' || !peerId) continue;
+ if (!isPlainObject(cursor)) continue;
+ out[peerId] = {
+ lastAckedDeleteAt: Number.isFinite(cursor.lastAckedDeleteAt) ? cursor.lastAckedDeleteAt : 0,
+ subscribedSince: Number.isFinite(cursor.subscribedSince) ? cursor.subscribedSince : 0,
+ };
+ }
+ return out;
+}
+
+async function writeState(state) {
+ await ensureDir(join(PATHS.data, 'sharing'));
+ await atomicWrite(STATE_PATH(), state);
+}
+
+// Serialize every readState→modify→writeState pair through a single tail
+// promise. Push-pipeline ackDeletesUpTo + receiver-side applyIncomingPush +
+// subscribe-driven initCursor all mutate this file and can race: without
+// serialization, two concurrent acks of different `deletedAtMs` both read
+// the pre-existing cursor, each chooses the higher value (correctly) but
+// the LATER writer clobbers the EARLIER writer's update — only one of the
+// two `lastAckedDeleteAt` advances survives, defeating the monotonic
+// guarantee. Single-instance app, so a module-level tail suffices.
+let writeTail = Promise.resolve();
+function withCursorLock(fn) {
+ const next = writeTail.then(() => fn(), () => fn());
+ writeTail = next.catch(() => {});
+ return next;
+}
+
+/** Returns a snapshot of every peer's cursor. */
+export async function listCursors() {
+ return readState();
+}
+
+/** Returns the cursor for a single peer, or `null` if none is stored. */
+export async function getCursor(peerId) {
+ if (typeof peerId !== 'string' || !peerId) return null;
+ const state = await readState();
+ return state[peerId] || null;
+}
+
+/**
+ * Initialize a peer's cursor on first subscribe. `subscribedSince` sets the
+ * horizon so tombstones older than this are never pushed to this peer. If a
+ * cursor already exists, keep it — re-subscribing must not reset progress.
+ *
+ * Pass `now` for testability; defaults to `Date.now()`.
+ */
+export async function initCursor(peerId, { now = Date.now() } = {}) {
+ if (typeof peerId !== 'string' || !peerId) return null;
+ return withCursorLock(async () => {
+ const state = await readState();
+ if (state[peerId]) return state[peerId];
+ state[peerId] = { lastAckedDeleteAt: 0, subscribedSince: now };
+ await writeState(state);
+ return state[peerId];
+ });
+}
+
+/**
+ * Advance the peer's `lastAckedDeleteAt`. Never moves backward — an out-of-
+ * order ack from a delayed retransmit must not retract progress.
+ *
+ * Returns the persisted cursor (or `null` if `peerId` is invalid).
+ */
+export async function ackDeletesUpTo(peerId, deletedAtMs, { now = Date.now() } = {}) {
+ if (typeof peerId !== 'string' || !peerId) return null;
+ if (!Number.isFinite(deletedAtMs) || deletedAtMs < 0) return null;
+ return withCursorLock(async () => {
+ const state = await readState();
+ const existing = state[peerId] || { lastAckedDeleteAt: 0, subscribedSince: now };
+ if (deletedAtMs <= existing.lastAckedDeleteAt) return existing;
+ state[peerId] = { ...existing, lastAckedDeleteAt: deletedAtMs };
+ await writeState(state);
+ return state[peerId];
+ });
+}
+
+/**
+ * Remove a peer's cursor entirely — used when the last subscription to that
+ * peer is torn down. Returns `true` if a cursor was removed.
+ */
+export async function removeCursor(peerId) {
+ if (typeof peerId !== 'string' || !peerId) return false;
+ return withCursorLock(async () => {
+ const state = await readState();
+ if (!(peerId in state)) return false;
+ delete state[peerId];
+ await writeState(state);
+ return true;
+ });
+}
+
+/**
+ * Test-only: await any in-flight cursor writes so a test can rm-rf its
+ * tmpdir without an ENOTEMPTY race against a fire-and-forget ackDeletesUpTo
+ * call from the push pipeline.
+ */
+export async function __drainForTests() {
+ await writeTail.catch(() => {});
+}
+
+/**
+ * Across the provided peer ids, return the lowest `lastAckedDeleteAt`. A
+ * tombstone with `deletedAt <= minAck` is safe to prune — every subscribed
+ * peer has acked it. Returns `Infinity` when the peer list is empty (no
+ * subscribers → no ack constraint, prune freely after grace).
+ *
+ * Peers in the list that have no stored cursor count as ack=0 (they haven't
+ * received any deletion yet). This is intentional: an in-flight subscriber
+ * shouldn't allow GC of a tombstone it might still need.
+ */
+export async function getMinAckAcrossPeers(peerIds) {
+ if (!Array.isArray(peerIds) || peerIds.length === 0) return Infinity;
+ const state = await readState();
+ let min = Infinity;
+ for (const peerId of peerIds) {
+ if (typeof peerId !== 'string' || !peerId) continue;
+ const cursor = state[peerId];
+ const ack = cursor?.lastAckedDeleteAt ?? 0;
+ if (ack < min) min = ack;
+ }
+ return min;
+}
diff --git a/server/services/sharing/peerTombstoneCursors.test.js b/server/services/sharing/peerTombstoneCursors.test.js
new file mode 100644
index 0000000000..61fa0cbb5c
--- /dev/null
+++ b/server/services/sharing/peerTombstoneCursors.test.js
@@ -0,0 +1,180 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdir, rm, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+// Redirect PATHS.data to a per-test tmpdir so each test gets a clean
+// peer_tombstone_cursors.json without stomping on real data.
+import { PATHS } from '../../lib/fileUtils.js';
+import {
+ listCursors,
+ getCursor,
+ initCursor,
+ ackDeletesUpTo,
+ removeCursor,
+ getMinAckAcrossPeers,
+ __drainForTests,
+} from './peerTombstoneCursors.js';
+
+let originalDataPath;
+let tmp;
+
+beforeEach(async () => {
+ originalDataPath = PATHS.data;
+ tmp = join(tmpdir(), `portos-peer-cursors-${Date.now()}-${Math.random()}`);
+ await mkdir(join(tmp, 'sharing'), { recursive: true });
+ PATHS.data = tmp;
+});
+
+afterEach(async () => {
+ // Drain any in-flight cursor writes before rm-rf'ing the tmpdir.
+ await __drainForTests();
+ await rm(tmp, { recursive: true, force: true });
+ PATHS.data = originalDataPath;
+});
+
+describe('peerTombstoneCursors', () => {
+ describe('readState resilience', () => {
+ it('returns {} for a missing file', async () => {
+ expect(await listCursors()).toEqual({});
+ });
+
+ it('tolerates a non-object root and returns {} (defensive against hand-edits)', async () => {
+ await writeFile(join(PATHS.data, 'sharing', 'peer_tombstone_cursors.json'), '"not an object"');
+ expect(await listCursors()).toEqual({});
+ });
+
+ it('skips non-object cursor entries from a corrupted file', async () => {
+ await writeFile(
+ join(PATHS.data, 'sharing', 'peer_tombstone_cursors.json'),
+ JSON.stringify({ ok: { lastAckedDeleteAt: 5, subscribedSince: 1 }, bad: 'string' }),
+ );
+ const state = await listCursors();
+ expect(state.ok).toEqual({ lastAckedDeleteAt: 5, subscribedSince: 1 });
+ expect(state.bad).toBeUndefined();
+ });
+
+ it('defaults non-finite numeric fields to 0', async () => {
+ await writeFile(
+ join(PATHS.data, 'sharing', 'peer_tombstone_cursors.json'),
+ JSON.stringify({ p: { lastAckedDeleteAt: 'not-a-num', subscribedSince: null } }),
+ );
+ expect(await getCursor('p')).toEqual({ lastAckedDeleteAt: 0, subscribedSince: 0 });
+ });
+ });
+
+ describe('initCursor', () => {
+ it('creates a cursor with subscribedSince=now and lastAckedDeleteAt=0', async () => {
+ const result = await initCursor('peer-a', { now: 1000 });
+ expect(result).toEqual({ lastAckedDeleteAt: 0, subscribedSince: 1000 });
+ // Verify persisted
+ expect(await getCursor('peer-a')).toEqual({ lastAckedDeleteAt: 0, subscribedSince: 1000 });
+ });
+
+ it('is idempotent — re-init never resets progress', async () => {
+ await initCursor('peer-a', { now: 1000 });
+ await ackDeletesUpTo('peer-a', 5000);
+ // Re-subscribe; cursor must NOT be reset (would lose ack progress).
+ const reInited = await initCursor('peer-a', { now: 9999 });
+ expect(reInited).toEqual({ lastAckedDeleteAt: 5000, subscribedSince: 1000 });
+ });
+
+ it('null for invalid peerId', async () => {
+ expect(await initCursor('')).toBeNull();
+ expect(await initCursor(null)).toBeNull();
+ expect(await initCursor(42)).toBeNull();
+ });
+ });
+
+ describe('ackDeletesUpTo', () => {
+ it('advances lastAckedDeleteAt when newer', async () => {
+ await initCursor('peer-a', { now: 1000 });
+ const result = await ackDeletesUpTo('peer-a', 5000);
+ expect(result.lastAckedDeleteAt).toBe(5000);
+ expect(result.subscribedSince).toBe(1000);
+ });
+
+ it('never moves backward — an out-of-order ack from a delayed retransmit is ignored', async () => {
+ await initCursor('peer-a', { now: 1000 });
+ await ackDeletesUpTo('peer-a', 5000);
+ const result = await ackDeletesUpTo('peer-a', 3000);
+ expect(result.lastAckedDeleteAt).toBe(5000);
+ });
+
+ it('treats equal-value ack as a no-op (returns current state)', async () => {
+ await initCursor('peer-a', { now: 1000 });
+ await ackDeletesUpTo('peer-a', 5000);
+ const result = await ackDeletesUpTo('peer-a', 5000);
+ expect(result.lastAckedDeleteAt).toBe(5000);
+ });
+
+ it('initializes a cursor on first ack if one does not exist', async () => {
+ const result = await ackDeletesUpTo('peer-a', 5000, { now: 2000 });
+ expect(result).toEqual({ lastAckedDeleteAt: 5000, subscribedSince: 2000 });
+ });
+
+ it('null for invalid args', async () => {
+ expect(await ackDeletesUpTo('', 100)).toBeNull();
+ expect(await ackDeletesUpTo('peer-a', NaN)).toBeNull();
+ expect(await ackDeletesUpTo('peer-a', -1)).toBeNull();
+ expect(await ackDeletesUpTo('peer-a', 'not-a-number')).toBeNull();
+ });
+
+ it('serializes concurrent acks so the highest deletedAtMs always wins (no clobber)', async () => {
+ // Regression: without the cursor write-lock, two concurrent acks both
+ // read the pre-existing lastAckedDeleteAt, each correctly chooses the
+ // higher value, but the LATER writer clobbers the EARLIER writer's
+ // update. The persisted cursor then reflects only one of the two acks.
+ await Promise.all([
+ ackDeletesUpTo('peer-a', 100),
+ ackDeletesUpTo('peer-a', 5000),
+ ackDeletesUpTo('peer-a', 2500),
+ ackDeletesUpTo('peer-a', 9999),
+ ackDeletesUpTo('peer-a', 750),
+ ]);
+ const cursor = await getCursor('peer-a');
+ expect(cursor.lastAckedDeleteAt).toBe(9999);
+ });
+ });
+
+ describe('removeCursor', () => {
+ it('removes an existing cursor and returns true', async () => {
+ await initCursor('peer-a', { now: 1000 });
+ expect(await removeCursor('peer-a')).toBe(true);
+ expect(await getCursor('peer-a')).toBeNull();
+ });
+
+ it('returns false when no cursor exists for the peer', async () => {
+ expect(await removeCursor('peer-a')).toBe(false);
+ });
+ });
+
+ describe('getMinAckAcrossPeers', () => {
+ it('returns Infinity for an empty peer list (no GC constraint when nobody is subscribed)', async () => {
+ // Critical: tombstones with no subscribers can be pruned freely after
+ // grace. Returning 0 here would block all GC forever.
+ expect(await getMinAckAcrossPeers([])).toBe(Infinity);
+ expect(await getMinAckAcrossPeers(null)).toBe(Infinity);
+ });
+
+ it('returns the minimum across known peers', async () => {
+ await ackDeletesUpTo('peer-a', 1000, { now: 0 });
+ await ackDeletesUpTo('peer-b', 5000, { now: 0 });
+ await ackDeletesUpTo('peer-c', 3000, { now: 0 });
+ expect(await getMinAckAcrossPeers(['peer-a', 'peer-b', 'peer-c'])).toBe(1000);
+ });
+
+ it('counts a peer with no stored cursor as ack=0 (in-flight subscriber must not unblock GC)', async () => {
+ // Regression: if a new peer just subscribed but hasn't acked anything,
+ // pruning every tombstone deletedAt > 0 would silently drop deletions
+ // the peer should still receive.
+ await ackDeletesUpTo('peer-a', 1000, { now: 0 });
+ expect(await getMinAckAcrossPeers(['peer-a', 'peer-b-fresh'])).toBe(0);
+ });
+
+ it('skips invalid peer-id entries silently', async () => {
+ await ackDeletesUpTo('peer-a', 1000, { now: 0 });
+ expect(await getMinAckAcrossPeers(['peer-a', '', null])).toBe(1000);
+ });
+ });
+});