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): sync media collections + fix stale 'behind' badge (#452)

[._.]/ Adam Eivy6ea09a0d774e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d5add3bc53..fd09f92c16 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,6 +1,7 @@
# Unreleased Changes
## Added
+- Peer-sync coverage for **media collections**, closing the gap where per-universe and per-series image/video buckets (the `data/media-collections.json` records that drive the "Universe: X" galleries with 74 / 124 / etc items) never propagated to peers. The file sat outside every sync category, and the per-record push pipeline couldn't help either: collection item adds emit `recordEvents.updated('universe', id)`, but the universe record itself doesn't move, so the `lastPushedHash` short-circuit treated every push as `unchanged` and the receiver's collection diverged permanently. Fix is in three layers — (1) new `mediaCollections` snapshot category in `server/services/dataSync.js` with a `mergeMediaCollectionsFromSync` entrypoint that LWWs scalars and **unions items by `kind:ref`** so neither side ever loses a render to a collection-level updatedAt race; the per-collection write goes through the same `serializeFileWrite` tail every other mediaCollections mutator uses. (2) The universe / series push payload in `server/services/sharing/peerSync.js` now bundles the linked collection (`findCollectionByUniverseId` / `findCollectionBySeriesId`) and the asset manifest includes each item's `ref` so image bytes flow through the existing receiver-side asset-pull worker — `simplePayloadHash` covers `linkedCollection` so the short-circuit can no longer collapse a collection-only edit. Tombstone pushes deliberately skip the collection bundle so a deleted universe doesn't re-create an empty bucket on the peer. (3) `applyIncomingPush` routes the bundled `linkedCollection` through `mergeMediaCollectionsFromSync` so the receiver's JSON converges atomically with the record merge. `DEFAULT_SYNC_CATEGORIES` in `services/instances.js`, the route enum in `routes/dataSync.js`, AND the `syncCategoriesSchema` Zod in `routes/instances.js` all gain `mediaCollections` (Zod's default object parsing strips unknown keys, so PATCH `syncCategories.mediaCollections` would otherwise silently no-op — same regression class the universe + pipeline schema fix patched earlier). The client's `SYNC_CATEGORY_META` adds the row.
- `ephemeral: true` field on universes, series, and issues — a local-only "don't sync to peers" marker. Set on POST (create) or PATCH; sanitizer normalizes anything non-true back to absent. The wire / push / subscribe / merge / asset layers ALL honor the flag end-to-end:
- **Wire (`sanitizeRecordForWire`)**: returns `null` for live ephemeral records so both transports (60s snapshot loop + per-record push) skip them. Tombstones for ephemeral records still cross the wire — a once-shared record marked ephemeral then deleted still propagates its delete so peers that still hold the live copy converge. The `ephemeral` field itself is stripped from every wire output so the byte-stable checksum invariant survives even when a stray `ephemeral: false` lives on disk.
- **Subscription lifecycle**: `createUniverse` / `createSeries` skip auto-subscribe for ephemeral records. `updateUniverse` / `updateSeries` PATCH transitions are wired: false→true tears down every per-record sub for the record (new `unsubscribeAllForRecord` helper); true→false re-fires `autoSubscribeRecordToAllPeers` so the now-shareable record reaches every peer with the matching category. `autoSubscribePeerToAllRecords` (peer:online backfill) filters ephemeral records out of the set-diff.
@@ -24,6 +25,7 @@
- Top-level `/reference-repos` global summary page and sidebar entry. Reference repos are now exclusively app-scoped — manage them via each app's "References" tab. Removed `client/src/pages/ReferenceRepos.jsx`, the route + lazy import from `client/src/App.jsx`, the sidebar entry from `client/src/components/Layout.jsx`, and the `nav.reference-repos` entry from `server/lib/navManifest.js` (the manifest's shape-invariant tests cover the deletion automatically). The `compact` / `initialRefs` props on `ReferenceReposPanel` are gone since the global summary was their only consumer.
## Fixed
+- Instances page no longer claims `Universe: behind` / `Pipeline: behind` for peers that are actually converged via the per-record push pipeline. When per-record subscriptions cover a category, the 60s snapshot loop intentionally skips it, so the `cursor.checksums[cat]` water-mark freezes at whatever it was when the first sub was created. The UI's `cursorChecksum !== remoteChecksum` test then flagged "behind" forever even though the push pipeline was keeping records in sync. `SnapshotSyncBadge` now takes a `livePushCovered` prop derived from the peer's actual subscriptions (`universe`-subs cover `'universe'`, `series`-subs cover `'pipeline'` — mirrors the inverse map in `peerSync.js`'s `KIND_TO_CATEGORY`) and renders a distinct `live-push` state instead. The subscription fetch is lifted from `PeerSyncSubscriptionsSection` to `PeerCard` so both children share one network call.
- macOS "Enable HTTPS" on the Instances page failed with `tailscale cert failed: ... operation not permitted` when the only Tailscale CLI on the machine was the Mac App Store / GUI app bundle. The MAS build runs under macOS App Sandbox and can't write the LE cert temp file outside its container. PortOS now: (1) reorders `TAILSCALE_CANDIDATES` in `server/lib/tailscale.js` so Homebrew (`/opt/homebrew/bin/tailscale`, `/usr/local/bin/tailscale`) is preferred over the App-bundle (kept as last-resort fallback); (2) detects the sandboxed-only state at boot via the new `hasOnlySandboxedTailscale()` helper and prints actionable `brew install tailscale` guidance from `scripts/setup-cert.js` before the doomed `tailscale cert` call; (3) rewrites the runtime EPERM toast in `server/services/certProvisioner.js` to point at the brew fix instead of surfacing raw sandbox stderr (new `tailscale-sandboxed` reason code); (4) on macOS, `./setup.sh` now detects the sandboxed-only state via the JS helper (single source of truth for the candidate paths) and unattended-installs `brew install tailscale` when available, with printed guidance when brew is missing. Non-fatal in every branch.
- Federated peer-sync category toggles for **Universe** and **Pipeline** silently no-op'd. The Zod `syncCategoriesSchema` in `server/routes/instances.js` was missing both keys; Zod's default object parsing strips unknown keys, so the PATCH validated as an empty `syncCategories` object, the service-side merge became a no-op, and the checkbox stayed unchecked with no server-side error. Added `universe` and `pipeline` to the schema to restore parity with `DEFAULT_SYNC_CATEGORIES` and the UI's `SYNC_CATEGORY_META`.
- Auto-run the world → universe data rename on server boot. The conversion previously shipped as a manual CLI script (`server/scripts/migrateWorldToUniverse.js`) that nobody knew to invoke, so installs upgrading from the World Builder era kept stale `data/world-builder.json` files and never saw their worlds appear as universes. The new migration `031-world-to-universe-data-rename.js` does the file rename, top-level key rename (`worlds`→`universes`), `worldId`→`universeId` rewrite in `pipeline-series.json`, `worldRun`→`universeRun` rewrite in `media-jobs.json`, and also relinks any `"World: <name>"` render collections in `media-collections.json` to their universe by canonical-name match.
diff --git a/PLAN.md b/PLAN.md
index 05b7f503fb..088a3f4133 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -22,6 +22,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
- [ ] [apple-health-integration-live-sync] **Apple Health integration for MeatSpace.** iOS live sync (HealthKit Shortcut → `POST /api/meatspace/apple-health` endpoint) plus a bulk historical import path for an exported `export.xml`. Wire into existing MeatSpace tabs so steps / sleep / heart rate / VO2 max / resting HR show alongside the alcohol / blood / body / epigenetic tracks already shipped. GOALS.md flags this as a documented Secondary Goal ("Apple Health integration planned") but no implementation tracking existed until this entry.
- [ ] [ref-watch-phosphene-mlx-post-decode-os-exit] **Bypass MLX post-decode deallocator hang via `os._exit(0)`.** From `reference-watch` review of phosphene (commits `adc1cd25` + `94bd6965`, 2026-05-22). At PortOS's current `LTX2_PIN=f8f20c83` the bug isn't reachable, but the moment a user updates `ltx-2-mlx` or PortOS bumps the pin past the May 9 refactor, every Distilled / Extend / two-stage render stalls 5–15 min after the upstream "Decoding done in X.Xs" log while Metal command-buffer completion handlers hold the GIL through frame teardown. Fix: in `scripts/generate_ltx2.py` `main()`, after `print(json.dumps(...))`, call `os._exit(0)` instead of returning normally — mp4 is on disk, stdout was flushed, skipping deallocator teardown saves up to 15 min. Document why in the file's docstring. Subsumes any in-helper watchdog approach.
- [ ] [ref-watch-phosphene-broaden-negative-prompt-override] **Broaden `DEFAULT_NEGATIVE_PROMPT` override to every module that defines it.** From `reference-watch` review of phosphene (commit `4e6129b7`, 2026-05-22). `scripts/generate_ltx2.py:55-70` `configure_negative_prompt()` only patches `ti2vid_one_stage.DEFAULT_NEGATIVE_PROMPT`. At PortOS's current pin this happens to cover every pipeline (the constant resolves against `ti2vid_one_stage` for the base class), but post-May-9 the constant moves to `ltx_pipelines_mlx._base` and `utils.constants` — and the PortOS override silently no-ops on Q8 / two-stage / HQ paths with no error for the user to chase. Fix: rewrite `configure_negative_prompt()` to probe `ti2vid_one_stage`, `_base`, and `utils.constants`, monkey-patch every module that has the constant. Keep PortOS's *replace* semantics (don't switch to phosphene's append-with-comma). No contextmanager needed — the helper is short-lived.
+- [ ] [tombstone-gc-manual-trigger-ui] **Wire a manual "GC tombstones now" button on the Instances page.** Today `sharing/tombstoneGc.js#sweepTombstones` only fires from the 60s `syncOrchestrator` interval and uses a hard-coded `GRACE_MS = 24 * 60 * 60 * 1000`, so a user who just mass-deleted records has to wait 24h for them to disappear from `data/universe-builder.json` / `data/pipeline-series.json` / `data/pipeline-issues.json` (even when every subscribed peer has already acked them). Wiring goals: (1) parameterize `sweepTombstones({ now, graceMs })` so callers can override the 24h buffer — keep the 24h default so the orchestrator path is unchanged. (2) Expose `POST /api/sync/tombstones/sweep` with optional `{ graceMs }` body (Zod-validated; clamp to `[0, 24*60*60*1000]` so the button can only shrink the grace, never bypass the ack horizon). The route still calls `cutoffForKind` for each kind so the existing safety checks (peer-ack horizon, refuse-when-snapshot-peer-uncovered) keep firing. (3) Add a "GC tombstones now" button under the Instances page's Sync Status section that POSTs with `graceMs: 0`. Disabled when any enabled peer has snapshot-mode coverage for a kind it isn't subscribed to (mirror the route's null-cutoff refusal). Surfaces the per-kind prune count in a toast (`pruned N universes / M series / K issues` — quiet when zero). (4) One-shot CLI script in `scripts/gc-tombstones-now.js` for headless cleanups (the inline-Node prune we ran 2026-05-23 for the post-Echoes-cleanup batch is the seed). Use `scripts/cleanup-test-data.js`'s pm2-stop-required wording in the header — the prune helpers serialize through per-file write tails that don't cross processes. Surfaced 2026-05-23 during the media-collections sync PR: peer null had acked 82 universe + 192 series tombstones from a same-day mass-delete and the user wanted them off-disk early.
- [ ] [ref-watch-phosphene-lazy-eval-env-bootstrap] **Lazy-eval env bootstrap for M-series perf.** From `reference-watch` review of phosphene (commit `a6e4573f`, context from `ec1437fe`, 2026-05-22). Phosphene measured ~15–25× perf loss on M4 Max with the upstream default `LTX2_DIT_EVAL_EVERY=8` vs `=0`/`=1`, caused by per-block Metal command-buffer churn. The env vars only exist post-May-9 upstream, so this is a "land it with the pin bump" item. Fix: at the very top of `scripts/generate_ltx2.py` (BEFORE any `ltx_*` import, because `ltx_core_mlx.model.transformer.model` reads `LTX2_DIT_EVAL_EVERY` at import time), add `os.environ.setdefault("LTX2_DIT_EVAL_EVERY", "0")` and `os.environ.setdefault("LTX2_GEMMA_EVAL_EVERY", "0")`. User-supplied env still wins via `setdefault`. Phosphene's matrix suggests `=1` is a slightly safer middle if `=0` produces a post-decode hang; use `=0` and revisit if regressions appear.
## Deferred Architecture (human-led planning)
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index cb6d8e12e4..2178b77bde 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -7,7 +7,7 @@ import {
Database, Brain, CheckCircle2, AlertCircle, Clock,
RefreshCcw, Timer,
Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,
- Lock, Globe, Info, Sparkles, Film
+ Lock, Globe, Info, Sparkles, Film, Images
} from 'lucide-react';
import toast from '../components/ui/Toast';
import socket from '../services/socket';
@@ -414,7 +414,8 @@ const SYNC_CATEGORY_META = [
{ key: 'digitalTwin', label: 'Digital Twin', icon: Fingerprint, description: 'Identity, chronotype, longevity, feedback' },
{ key: 'meatspace', label: 'Meatspace', icon: HeartPulse, description: 'Daily logs, blood tests, body metrics, eyes' },
{ key: 'universe', label: 'Universe', icon: Sparkles, description: 'Universe Builder canon: characters, places, objects' },
- { key: 'pipeline', label: 'Pipeline', icon: Film, description: 'Series + issues record state (no image/video blobs)' }
+ { key: 'pipeline', label: 'Pipeline', icon: Film, description: 'Series + issues record state (no image/video blobs)' },
+ { key: 'mediaCollections', label: 'Media Collections', icon: Images, description: 'Per-universe/series image + video buckets' }
];
// Snapshot categories (excludes delta-based brain/memory)
@@ -505,8 +506,15 @@ function SyncCategoriesPanel({ peer, onRefresh }) {
);
}
-function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum }) {
- // Only compare when remote reports checksums — local fallback is misleading
+function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum, livePushCovered }) {
+ // `livePushCovered` is true when this peer has at least one per-record
+ // peer-sync subscription for a record kind that maps to this category
+ // (universe-subs → 'universe', series-subs → 'pipeline'). The orchestrator
+ // intentionally SKIPS the 60s snapshot loop for those categories — the push
+ // pipeline is authoritative — so cursor.checksums[cat] stays frozen at
+ // whatever it was when peer-subs took over and the cursor-vs-remote diff
+ // would always read "behind" even when the records are actually converged.
+ // Render a distinct "live-push" state instead so the badge stops lying.
const synced = cursorChecksum && remoteChecksum && cursorChecksum === remoteChecksum;
const behind = cursorChecksum && remoteChecksum && cursorChecksum !== remoteChecksum;
@@ -514,7 +522,14 @@ function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum }
<div className="flex items-center gap-1.5 text-xs">
<Icon size={12} className="text-gray-500" />
<span className="text-gray-500">{label}:</span>
- {synced ? (
+ {livePushCovered ? (
+ <>
+ <ArrowLeftRight size={11} className="text-port-accent" />
+ <span className="text-port-accent" title="Per-record push pipeline owns this category; snapshot cursor is intentionally stale">
+ live-push
+ </span>
+ </>
+ ) : synced ? (
<>
<CheckCircle2 size={11} className="text-port-success" />
<span className="text-port-success">synced</span>
@@ -546,35 +561,12 @@ function SnapshotSyncBadge({ label, icon: Icon, cursorChecksum, remoteChecksum }
* record) never get reverse subscriptions auto-created — see
* services/sharing/peerSync.js `maybeCreateReverseSubscription`.
*/
-function PeerSyncSubscriptionsSection({ peer }) {
- const [subs, setSubs] = useState([]);
- const [loading, setLoading] = useState(true);
+function PeerSyncSubscriptionsSection({ peer, peerSubs, peerSubsLoaded, setPeerSubs }) {
const [busyId, setBusyId] = useState(null);
- useEffect(() => {
- if (!peer.instanceId) {
- setSubs([]);
- setLoading(false);
- return;
- }
- let cancelled = false;
- setLoading(true);
- listPeerSubscriptions({ peerId: peer.instanceId }, { silent: true })
- .then((r) => {
- if (!cancelled) setSubs(r?.subscriptions || []);
- })
- .catch(() => {
- if (!cancelled) setSubs([]);
- })
- .finally(() => {
- if (!cancelled) setLoading(false);
- });
- return () => { cancelled = true; };
- }, [peer.instanceId]);
-
if (!peer.instanceId) return null;
- if (loading) return null;
- if (subs.length === 0) return null;
+ if (!peerSubsLoaded) return null;
+ if (peerSubs.length === 0) return null;
const handleUnsubscribe = async (sub) => {
setBusyId(sub.id);
@@ -583,21 +575,21 @@ function PeerSyncSubscriptionsSection({ peer }) {
return null;
});
if (ok) {
- setSubs((prev) => prev.filter((s) => s.id !== sub.id));
+ setPeerSubs((prev) => prev.filter((s) => s.id !== sub.id));
toast.success(`Stopped syncing ${sub.recordKind} ${sub.recordId.slice(0, 8)} with ${peer.name}`);
}
setBusyId(null);
};
- const universeSubs = subs.filter((s) => s.recordKind === 'universe');
- const seriesSubs = subs.filter((s) => s.recordKind === 'series');
+ const universeSubs = peerSubs.filter((s) => s.recordKind === 'universe');
+ const seriesSubs = peerSubs.filter((s) => s.recordKind === 'series');
return (
<div className="mt-2 pt-2 border-t border-port-border/50">
<div className="flex items-center gap-1.5 mb-1.5">
<ArrowLeftRight size={12} className="text-gray-500" />
<span className="text-[10px] text-gray-500 uppercase tracking-wider font-medium">
- Live-pushed records ({subs.length})
+ Live-pushed records ({peerSubs.length})
</span>
</div>
<div className="space-y-1">
@@ -631,7 +623,7 @@ function PeerSyncSubscriptionsSection({ peer }) {
);
}
-function SyncStatusSection({ peer, syncStatus }) {
+function SyncStatusSection({ peer, syncStatus, peerSubs = [] }) {
if (!syncStatus || !peer.instanceId) return null;
const cursor = syncStatus.cursors?.[peer.instanceId];
@@ -649,6 +641,19 @@ function SyncStatusSection({ peer, syncStatus }) {
const cursorChecksums = cursor?.checksums || {};
const remoteChecksums = remoteSyncSeqs?.checksums || {};
+ // Derive the set of snapshot categories that are "covered" by the
+ // per-record peer-sync push pipeline. Mirrors the inverse mapping in
+ // `server/services/sharing/peerSync.js` KIND_TO_CATEGORY — universe-subs
+ // cover 'universe', series-subs cover 'pipeline' (which bundles series +
+ // issues). The orchestrator skips snapshot pulls for these, so the
+ // cursor checksum stays stale and the cursor-vs-remote diff is a lie.
+ // Render those categories as "live-push" instead.
+ const livePushCovered = new Set();
+ for (const s of peerSubs) {
+ if (s.recordKind === 'universe') livePushCovered.add('universe');
+ if (s.recordKind === 'series') livePushCovered.add('pipeline');
+ }
+
const enabledSnapshots = SNAPSHOT_CATEGORIES
.map(m => m.key)
.filter(cat => categories[cat]);
@@ -693,6 +698,7 @@ function SyncStatusSection({ peer, syncStatus }) {
icon={meta.icon}
cursorChecksum={cursorChecksums[cat]}
remoteChecksum={remoteChecksums[cat]}
+ livePushCovered={livePushCovered.has(cat)}
/>
);
})}
@@ -811,6 +817,35 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
const [probing, setProbing] = useState(false);
const [connecting, setConnecting] = useState(false);
const [confirmRemove, setConfirmRemove] = useState(false);
+ // Peer subs are loaded once at this level and shared with both
+ // PeerSyncSubscriptionsSection (renders the per-record list) and
+ // SyncStatusSection (uses the sub set to decide which snapshot badges
+ // should render as "live-push" instead of misleading "behind"). Without
+ // sharing, every card would issue two identical /sharing/peer-subs
+ // fetches.
+ const [peerSubs, setPeerSubs] = useState([]);
+ const [peerSubsLoaded, setPeerSubsLoaded] = useState(false);
+
+ useEffect(() => {
+ if (!peer.instanceId) {
+ setPeerSubs([]);
+ setPeerSubsLoaded(true);
+ return;
+ }
+ let cancelled = false;
+ setPeerSubsLoaded(false);
+ listPeerSubscriptions({ peerId: peer.instanceId }, { silent: true })
+ .then((r) => {
+ if (!cancelled) setPeerSubs(r?.subscriptions || []);
+ })
+ .catch(() => {
+ if (!cancelled) setPeerSubs([]);
+ })
+ .finally(() => {
+ if (!cancelled) setPeerSubsLoaded(true);
+ });
+ return () => { cancelled = true; };
+ }, [peer.instanceId]);
const StatusIcon = STATUS_ICONS[peer.status] || CircleDot;
const isInboundOnly = peer.directions?.includes('inbound') && !peer.directions?.includes('outbound');
@@ -947,9 +982,9 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
<SyncCategoriesPanel peer={peer} onRefresh={onRefresh} />
- <SyncStatusSection peer={peer} syncStatus={syncStatus} />
+ <SyncStatusSection peer={peer} syncStatus={syncStatus} peerSubs={peerSubs} />
- <PeerSyncSubscriptionsSection peer={peer} />
+ <PeerSyncSubscriptionsSection peer={peer} peerSubs={peerSubs} peerSubsLoaded={peerSubsLoaded} setPeerSubs={setPeerSubs} />
<PeerAppsList apps={peer.lastApps} peerAddress={peer.address} peerHost={peer.host} />
{peer.status === 'online' && (
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 230a7551d4..ae4930675d 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -90,6 +90,14 @@ export function sanitizeRecordForWire(kind, record) {
const { deleted: _deleted, deletedAt: _deletedAt, ephemeral: _ephemeral, ...rest } = record;
return { ...rest, ...sanitizeSoftDeleteFields(record) };
}
+ case 'mediaCollection': {
+ // Collections have no `ephemeral` / `deleted` semantics today — the
+ // record shape is already wire-safe as produced by sanitizeCollection.
+ // The case exists so future per-record push fan-out for collections has
+ // a single sanitizer to extend (e.g. stripping a future local-only
+ // field like a UI sort preference) without forking the wire contract.
+ return record;
+ }
default:
return null;
}
@@ -130,6 +138,14 @@ export function sanitizeStateForWire(kind, state) {
: [];
return { kind, data: { series, issues } };
}
+ case 'mediaCollections': {
+ const collections = Array.isArray(state.collections)
+ ? state.collections
+ .map((c) => sanitizeRecordForWire('mediaCollection', c))
+ .filter(Boolean)
+ : [];
+ return { kind, data: { collections } };
+ }
default:
return { kind, data: null };
}
diff --git a/server/routes/dataSync.js b/server/routes/dataSync.js
index cc1ef61142..fc2d05d2bc 100644
--- a/server/routes/dataSync.js
+++ b/server/routes/dataSync.js
@@ -12,7 +12,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
const router = Router();
-const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace', 'universe', 'pipeline']);
+const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace', 'universe', 'pipeline', 'mediaCollections']);
// GET /api/sync/:category/checksum — return checksum only (lightweight)
router.get('/:category/checksum', asyncHandler(async (req, res) => {
diff --git a/server/routes/instances.js b/server/routes/instances.js
index db9164f59b..848f716599 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -47,7 +47,13 @@ const syncCategoriesSchema = z.object({
digitalTwin: z.boolean().optional(),
meatspace: z.boolean().optional(),
universe: z.boolean().optional(),
- pipeline: z.boolean().optional()
+ pipeline: z.boolean().optional(),
+ // Default Zod object parsing strips unknown keys, so every key in
+ // DEFAULT_SYNC_CATEGORIES (server/services/instances.js) MUST appear
+ // here — otherwise PATCH/PUT updates from the Instances UI silently
+ // no-op for the missing category. Same regression class as the
+ // universe + pipeline omission tracked in .changelog/NEXT.md.
+ mediaCollections: z.boolean().optional()
}).optional();
const updatePeerSchema = z.object({
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index ec1b8e7cee..f8db4019f2 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -14,6 +14,7 @@ import { isPlainObject } from '../lib/objects.js';
import { mergeUniversesFromSync } from './universeBuilder.js';
import { mergeSeriesFromSync } from './pipeline/series.js';
import { mergeIssuesFromSync } from './pipeline/issues.js';
+import { mergeMediaCollectionsFromSync, listCollections, itemKey } from './mediaCollections.js';
import { sanitizeStateForWire } from '../lib/syncWire.js';
// --- Category Definitions ---
@@ -28,6 +29,7 @@ const MEATSPACE_DIR = PATHS.meatspace;
const PIPELINE_SERIES_FILE = join(PATHS.data, 'pipeline-series.json');
const PIPELINE_ISSUES_FILE = join(PATHS.data, 'pipeline-issues.json');
const UNIVERSE_BUILDER_FILE = join(PATHS.data, 'universe-builder.json');
+const MEDIA_COLLECTIONS_FILE = join(PATHS.data, 'media-collections.json');
const MEATSPACE_FILES = {
'daily-log.json': { arrayKey: 'entries', idField: 'date' },
@@ -416,6 +418,53 @@ async function applyPipelineRemote(remoteData) {
};
}
+// --- Category: Media Collections ---
+
+// Per-universe / per-series buckets of image + video refs. The collection
+// records carry the linkage (universeId / seriesId) and an items[] array of
+// `{ kind, ref, addedAt }` rows. We sync the JSON itself here (union of items
+// + LWW on scalars) so collection edits propagate even when the linked
+// universe / series record itself didn't move. The per-record push pipeline
+// (peerSync.js) ALSO bundles a record's linked collection in its push payload
+// so image bytes flow via the existing asset-pull worker — the snapshot path
+// covers the JSON, the push path covers the image bytes.
+
+async function getMediaCollectionsSnapshot() {
+ // listCollections re-reads + sanitizes from disk; we don't cache here since
+ // the checksum cache (`CHECKSUM_PATHS` fingerprint check) already short-
+ // circuits the I/O when the file hasn't moved.
+ const collections = await listCollections();
+ // Canonicalize ordering for the wire so two peers holding identical sets
+ // produce identical checksums regardless of write history. Without this
+ // sort, on-disk order is insertion-order — peer A and peer B can land the
+ // same items in different orders and end up with permanently different
+ // checksums, which the UI's cursor-vs-remote comparison reads as "behind"
+ // forever. Sort collections by id (stable, unique) and each collection's
+ // items by `<kind>:<ref>` (the same key used for set membership in
+ // `mergeCollectionItems`).
+ const canonical = collections
+ .map((c) => ({
+ ...c,
+ items: [...(c.items || [])].sort((a, b) => itemKey(a).localeCompare(itemKey(b))),
+ }))
+ .sort((a, b) => a.id.localeCompare(b.id));
+ const data = { collections: canonical };
+ return { data, checksum: computeChecksum(data) };
+}
+
+async function applyMediaCollectionsRemote(remoteData) {
+ if (!remoteData) return { applied: false, count: 0 };
+ // Routes through `mergeMediaCollectionsFromSync` so the read-modify-write
+ // runs INSIDE `serializeFileWrite` (same tail as addItem / removeItem /
+ // bulkUpdateCollectionItems) — a sync-driven write can't interleave with a
+ // concurrent local mutation on the same JSON file.
+ const result = await mergeMediaCollectionsFromSync(remoteData.collections || []);
+ if (result.applied) {
+ console.log(`🔄 MediaCollections sync: merged ${result.count} collection(s)`);
+ }
+ return result;
+}
+
// --- Public API ---
// Files each category reads, used to keep the in-process checksum cache
@@ -434,6 +483,7 @@ const CHECKSUM_PATHS = {
meatspace: Object.keys(MEATSPACE_FILES).map((f) => join(MEATSPACE_DIR, f)),
universe: [UNIVERSE_BUILDER_FILE],
pipeline: [PIPELINE_SERIES_FILE, PIPELINE_ISSUES_FILE],
+ mediaCollections: [MEDIA_COLLECTIONS_FILE],
};
const CATEGORIES = {
@@ -442,7 +492,8 @@ const CATEGORIES = {
digitalTwin: { getSnapshot: getDigitalTwinSnapshot, applyRemote: applyDigitalTwinRemote },
meatspace: { getSnapshot: getMeatspaceSnapshot, applyRemote: applyMeatspaceRemote },
universe: { getSnapshot: getUniverseSnapshot, applyRemote: applyUniverseRemote },
- pipeline: { getSnapshot: getPipelineSnapshot, applyRemote: applyPipelineRemote }
+ pipeline: { getSnapshot: getPipelineSnapshot, applyRemote: applyPipelineRemote },
+ mediaCollections: { getSnapshot: getMediaCollectionsSnapshot, applyRemote: applyMediaCollectionsRemote }
};
// Per-category `{ fingerprints, checksum }` cache. The orchestrator hits
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 73a214af1b..1d30869596 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -26,6 +26,7 @@ const dataSync = await import('./dataSync.js');
const SERIES_PATH = join(tempRoot, 'pipeline-series.json');
const ISSUES_PATH = join(tempRoot, 'pipeline-issues.json');
const UNIVERSE_PATH = join(tempRoot, 'universe-builder.json');
+const MEDIA_COLLECTIONS_PATH = join(tempRoot, 'media-collections.json');
function writeJSON(path, obj) {
mkdirSync(tempRoot, { recursive: true });
@@ -262,3 +263,157 @@ describe('dataSync — getChecksum cache', () => {
expect(after.checksum).not.toBe(before.checksum);
});
});
+
+describe('dataSync — mediaCollections category', () => {
+ it('is registered alongside the other categories', () => {
+ expect(dataSync.getSupportedCategories()).toContain('mediaCollections');
+ });
+
+ it('snapshot returns sanitized collections array', async () => {
+ writeJSON(MEDIA_COLLECTIONS_PATH, {
+ collections: [{
+ id: 'c1',
+ name: 'Universe: Echoes',
+ description: '',
+ coverKey: null,
+ universeId: 'u1',
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T01:00:00Z',
+ }],
+ });
+ const snap = await dataSync.getSnapshot('mediaCollections');
+ expect(snap.data.collections).toHaveLength(1);
+ expect(snap.data.collections[0].id).toBe('c1');
+ expect(snap.checksum).toBeTruthy();
+ });
+
+ it('snapshot checksum is stable across reads when state is unchanged', async () => {
+ writeJSON(MEDIA_COLLECTIONS_PATH, {
+ collections: [{
+ id: 'c1', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,
+ items: [], createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z',
+ }],
+ });
+ const a = await dataSync.getSnapshot('mediaCollections');
+ const b = await dataSync.getSnapshot('mediaCollections');
+ expect(a.checksum).toBe(b.checksum);
+ });
+
+ it('snapshot handles a missing file gracefully', async () => {
+ const snap = await dataSync.getSnapshot('mediaCollections');
+ expect(snap.data.collections).toEqual([]);
+ expect(snap.checksum).toBeTruthy();
+ });
+
+ it('applyRemote inserts a new collection', async () => {
+ writeJSON(MEDIA_COLLECTIONS_PATH, { collections: [] });
+ const result = await dataSync.applyRemote('mediaCollections', {
+ collections: [{
+ id: 'c-new', name: 'Universe: New', description: '', coverKey: null,
+ universeId: 'u-new', seriesId: null,
+ items: [{ kind: 'image', ref: 'new.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',
+ }],
+ });
+ expect(result.applied).toBe(true);
+ expect(result.count).toBe(1);
+ const persisted = readJSON(MEDIA_COLLECTIONS_PATH);
+ expect(persisted.collections).toHaveLength(1);
+ expect(persisted.collections[0].id).toBe('c-new');
+ });
+
+ it('applyRemote unions items by kind:ref — never loses a render', async () => {
+ writeJSON(MEDIA_COLLECTIONS_PATH, {
+ collections: [{
+ id: 'c1', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,
+ items: [{ kind: 'image', ref: 'local.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',
+ }],
+ });
+ await dataSync.applyRemote('mediaCollections', {
+ collections: [{
+ id: 'c1', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,
+ items: [{ kind: 'image', ref: 'remote.png', addedAt: '2026-05-22T02:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T02:00:00Z',
+ }],
+ });
+ const persisted = readJSON(MEDIA_COLLECTIONS_PATH);
+ const refs = persisted.collections[0].items.map(i => i.ref).sort();
+ expect(refs).toEqual(['local.png', 'remote.png']);
+ });
+
+ it('checksum changes after applyRemote bumps file mtime', async () => {
+ writeJSON(MEDIA_COLLECTIONS_PATH, {
+ collections: [{
+ id: 'c1', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,
+ items: [], createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',
+ }],
+ });
+ const before = await dataSync.getChecksum('mediaCollections');
+ await dataSync.applyRemote('mediaCollections', {
+ collections: [{
+ id: 'c1', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T02:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T02:00:00Z',
+ }],
+ });
+ const after = await dataSync.getChecksum('mediaCollections');
+ expect(after.checksum).not.toBe(before.checksum);
+ });
+
+ it('snapshot checksum is order-insensitive for collections and items', async () => {
+ // Regression: two peers can hold identical sets but write them to disk
+ // in different orders (insertion-order persistence). Without
+ // canonicalization in getMediaCollectionsSnapshot, their checksums
+ // diverge permanently and the UI reads "behind" forever even though
+ // they're converged.
+ writeJSON(MEDIA_COLLECTIONS_PATH, {
+ collections: [
+ {
+ id: 'c-b', name: 'B', description: '', coverKey: null, universeId: null, seriesId: null,
+ items: [
+ { kind: 'image', ref: 'z.png', addedAt: '2026-05-22T03:00:00Z' },
+ { kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' },
+ ],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T03:00:00Z',
+ },
+ {
+ id: 'c-a', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,
+ items: [
+ { kind: 'video', ref: 'v1', addedAt: '2026-05-22T02:00:00Z' },
+ { kind: 'image', ref: 'x.png', addedAt: '2026-05-22T01:00:00Z' },
+ ],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T02:00:00Z',
+ },
+ ],
+ });
+ const a = await dataSync.getSnapshot('mediaCollections');
+
+ // Same SET, reversed order at every level.
+ await new Promise((r) => setTimeout(r, 5)); // ensure mtime changes
+ writeJSON(MEDIA_COLLECTIONS_PATH, {
+ collections: [
+ {
+ id: 'c-a', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,
+ items: [
+ { kind: 'image', ref: 'x.png', addedAt: '2026-05-22T01:00:00Z' },
+ { kind: 'video', ref: 'v1', addedAt: '2026-05-22T02:00:00Z' },
+ ],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T02:00:00Z',
+ },
+ {
+ id: 'c-b', name: 'B', description: '', coverKey: null, universeId: null, seriesId: null,
+ items: [
+ { kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' },
+ { kind: 'image', ref: 'z.png', addedAt: '2026-05-22T03:00:00Z' },
+ ],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T03:00:00Z',
+ },
+ ],
+ });
+ const b = await dataSync.getSnapshot('mediaCollections');
+ expect(b.checksum).toBe(a.checksum);
+ });
+});
diff --git a/server/services/instances.js b/server/services/instances.js
index 14b71257f0..71fff3223e 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -165,7 +165,8 @@ const DEFAULT_SYNC_CATEGORIES = {
digitalTwin: false,
meatspace: false,
universe: false,
- pipeline: false
+ pipeline: false,
+ mediaCollections: false
};
export { DEFAULT_SYNC_CATEGORIES };
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index bcbe801b31..a8c8fbce52 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -56,6 +56,14 @@ const sanitizeItem = (raw) => {
// addressable via the REST surface — reject it here so persisted data
// always round-trips.
if (ref.includes(':')) return null;
+ // Path-traversal defense in depth. Refs persist to wire-syncable state
+ // (peer pushes carry collections via `linkedCollection`, snapshot sync
+ // carries the whole file), and downstream code joins the ref onto a
+ // PATHS dir to hash / pull the asset. A peer-supplied ref like
+ // `../etc/passwd` would otherwise let one peer make another peer hash
+ // (and leak the hash of) arbitrary local files. Same posture as
+ // `sanitizeAssetFilename` in `server/services/sharing/peerSync.js`.
+ if (ref.includes('/') || ref.includes('\\') || ref.includes('..')) return null;
// A hand-edited or corrupted `addedAt` would feed NaN into the cover
// resolver's Date sort — replace anything unparseable with now().
const parsed = typeof raw.addedAt === 'string' ? Date.parse(raw.addedAt) : NaN;
@@ -546,6 +554,12 @@ const validateItemInput = (item) => {
if (!ref || ref.length > REF_MAX_LENGTH || ref.includes(':')) {
throw makeErr('item.ref invalid (empty, too long, or contains ":")', ERR_VALIDATION);
}
+ // Mirror sanitizeItem's path-traversal rejection so the write path can't
+ // persist a ref that the next listCollections() read would silently drop
+ // (which would also churn coverKey/updatedAt for the dangling-cover guard).
+ if (ref.includes('/') || ref.includes('\\') || ref.includes('..')) {
+ throw makeErr('item.ref invalid (contains path separators or "..")', ERR_VALIDATION);
+ }
return { kind: item.kind, ref };
};
@@ -689,3 +703,144 @@ export async function removeItem(id, key) {
if (merged.seriesId) emitRecordUpdated('series', merged.seriesId);
return merged;
}
+
+/**
+ * Merge an incoming list of collections from a peer (snapshot sync OR the
+ * per-record push payload's `linkedCollection` field). Per-collection
+ * semantics:
+ *
+ * - New (unseen id): inserted verbatim after sanitization.
+ * - Existing id: top-level scalars (name, description, coverKey, universeId,
+ * seriesId) follow LWW on `updatedAt`. Items[] is **union by `kind:ref`**
+ * so neither side ever loses a render it knows about — collections are
+ * append-mostly in normal use, and a divergence (peer-A added image-X
+ * while peer-B added image-Y to the same collection on the same day)
+ * should retain both rather than discard whichever has the older
+ * collection-level updatedAt.
+ *
+ * Mutating writes go through the same `serializeFileWrite` tail as every
+ * other mediaCollections mutator so a concurrent local `addItem` and remote
+ * apply can't interleave on the JSON file.
+ */
+export async function mergeMediaCollectionsFromSync(remoteCollections) {
+ if (!Array.isArray(remoteCollections)) return { applied: false, count: 0 };
+ return serializeFileWrite(async () => {
+ const all = await listCollections();
+ const localById = new Map(all.map((c) => [c.id, c]));
+ let changed = 0;
+ for (const remote of remoteCollections) {
+ const sanitized = sanitizeCollection(remote);
+ if (!sanitized) continue;
+ const local = localById.get(sanitized.id);
+ if (!local) {
+ localById.set(sanitized.id, sanitized);
+ changed++;
+ continue;
+ }
+ const mergedItems = mergeCollectionItems(local.items, sanitized.items);
+ // LWW on collection-level scalars. Parse to epoch ms (not lexicographic
+ // compare on the raw strings): `sanitizeCollection` accepts any
+ // Date.parse-able string for `updatedAt`, so a hand-edit or older peer
+ // writing a non-ISO format could otherwise lose to a "newer" string
+ // that's actually an older moment in time. Unparseable side LOSES (a
+ // corrupted timestamp can't claim to be newer); both unparseable
+ // breaks to local-wins (no signal to override). `localTs`/`remoteTs`
+ // keep the original strings so the winning side's `updatedAt`
+ // round-trips to disk verbatim — only the comparison is numeric.
+ const localTs = local.updatedAt || '';
+ const remoteTs = sanitized.updatedAt || '';
+ const remoteWins = compareNewerWins(remoteTs, localTs);
+ const scalarSource = remoteWins ? sanitized : local;
+ // Cover key: only adopt the scalar source's coverKey if it points at an
+ // item that survives the union — otherwise sanitizeCollection on next
+ // read would drop it back to null and we'd churn updatedAt forever.
+ const presentKeys = new Set(mergedItems.map(itemKey));
+ const coverKey = scalarSource.coverKey && presentKeys.has(scalarSource.coverKey)
+ ? scalarSource.coverKey
+ : null;
+ const next = {
+ ...local,
+ name: scalarSource.name,
+ description: scalarSource.description,
+ coverKey,
+ universeId: scalarSource.universeId,
+ seriesId: scalarSource.seriesId,
+ items: mergedItems,
+ updatedAt: remoteWins ? remoteTs : localTs,
+ };
+ if (collectionsEqual(local, next)) continue;
+ localById.set(sanitized.id, next);
+ changed++;
+ }
+ if (changed === 0) return { applied: false, count: 0 };
+ await writeAll(Array.from(localById.values()));
+ return { applied: true, count: changed };
+ });
+}
+
+function mergeCollectionItems(localItems, remoteItems) {
+ const byKey = new Map();
+ for (const it of localItems || []) byKey.set(itemKey(it), it);
+ for (const it of remoteItems || []) {
+ const k = itemKey(it);
+ const existing = byKey.get(k);
+ if (!existing) {
+ byKey.set(k, it);
+ continue;
+ }
+ // Earliest addedAt wins — a sync replay shouldn't bump the addedAt of
+ // an item already in the collection. Parse to epoch ms instead of
+ // lexicographic compare: `sanitizeItem` keeps any Date.parse-able
+ // string (not strictly ISO-8601), so two parseable-but-different-format
+ // timestamps could compare incorrectly as strings. Tie → existing wins
+ // (matches the previous `<=` behavior — sync replay shouldn't churn).
+ const cmp = compareEarlierWins(existing.addedAt, it.addedAt);
+ const earlier = cmp <= 0 ? existing : it;
+ byKey.set(k, earlier);
+ }
+ return Array.from(byKey.values());
+}
+
+// Parse a timestamp string to epoch ms, or null when unparseable. The
+// "loses on null" semantics differ between the two LWW directions, so each
+// caller handles nulls explicitly rather than baking a polarity into this
+// helper (an Infinity / -Infinity fallback would invert behavior between
+// "earliest wins" and "newer wins").
+function parseTsMs(s) {
+ const n = typeof s === 'string' ? Date.parse(s) : NaN;
+ return Number.isFinite(n) ? n : null;
+}
+
+// "Earliest wins" tiebreak for two records of the same key. Used by
+// mergeCollectionItems when both sides claim to know an `addedAt` for the
+// same `<kind>:<ref>`. Returns -1 if `a` is earlier (a wins), 1 if `b` is
+// earlier, 0 on tie. Unparseable side LOSES — a corrupted timestamp can't
+// claim to be earliest; if both are unparseable the caller's default wins.
+function compareEarlierWins(a, b) {
+ const aMs = parseTsMs(a);
+ const bMs = parseTsMs(b);
+ if (aMs === null && bMs === null) return 0;
+ if (aMs === null) return 1; // a unparseable → b wins
+ if (bMs === null) return -1; // b unparseable → a wins
+ if (aMs < bMs) return -1;
+ if (aMs > bMs) return 1;
+ return 0;
+}
+
+// "Newer wins" comparison: returns true iff `candidate` is strictly newer
+// than `incumbent`. Used by mergeMediaCollectionsFromSync to decide whether
+// remote overrides local on scalar fields. Same null-loses-to-valid rule
+// as `compareEarlierWins`. Ties → incumbent (local) wins.
+function compareNewerWins(candidate, incumbent) {
+ const cMs = parseTsMs(candidate);
+ const iMs = parseTsMs(incumbent);
+ if (cMs === null) return false; // candidate unparseable → never overrides
+ if (iMs === null) return true; // incumbent unparseable, candidate valid → take valid
+ return cMs > iMs;
+}
+
+function collectionsEqual(a, b) {
+ // Both sides come through sanitizeCollection so key order is canonical and
+ // JSON.stringify is sufficient for "did anything actually move".
+ return JSON.stringify(a) === JSON.stringify(b);
+}
diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.js
index 5f2e0ee2a1..96bfdb2bf6 100644
--- a/server/services/mediaCollections.test.js
+++ b/server/services/mediaCollections.test.js
@@ -45,6 +45,25 @@ describe('mediaCollections service', () => {
.rejects.toMatchObject({ code: svc.ERR_DUPLICATE });
});
+ it('addItem rejects refs with path-traversal tokens up-front', async () => {
+ // Mirrors sanitizeItem's path-traversal rejection on the write boundary.
+ // Without this, an API call could persist an unsafe ref that
+ // listCollections() would then silently drop on the next read
+ // (churning coverKey / updatedAt and making items disappear).
+ const c = await svc.createCollection({ name: 'A' });
+ for (const ref of ['../etc/passwd', 'subdir/file.png', 'a\\b.png', 'foo..bar.png']) {
+ await expect(svc.addItem(c.id, { kind: 'image', ref }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ }
+ });
+
+ it('bulkUpdateCollectionItems rejects path-traversal refs up-front', async () => {
+ const c = await svc.createCollection({ name: 'A' });
+ await expect(svc.bulkUpdateCollectionItems(c.id, {
+ add: [{ kind: 'image', ref: '../etc/passwd' }],
+ })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
it('many-to-many: same item can live in multiple collections', async () => {
const a = await svc.createCollection({ name: 'A' });
const b = await svc.createCollection({ name: 'B' });
@@ -626,3 +645,326 @@ describe('mediaCollections service', () => {
expect(all[0].coverKey).toBeNull();
});
});
+
+describe('mergeMediaCollectionsFromSync', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ });
+
+ it('returns {applied:false,count:0} for empty / non-array input', async () => {
+ expect(await svc.mergeMediaCollectionsFromSync(null)).toEqual({ applied: false, count: 0 });
+ expect(await svc.mergeMediaCollectionsFromSync('nope')).toEqual({ applied: false, count: 0 });
+ expect(await svc.mergeMediaCollectionsFromSync([])).toEqual({ applied: false, count: 0 });
+ });
+
+ it('inserts a previously-unseen collection', async () => {
+ const remote = {
+ id: 'c-remote',
+ name: 'From Peer',
+ description: '',
+ coverKey: null,
+ universeId: 'u-1',
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'peer.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T01:00:00Z',
+ };
+ const result = await svc.mergeMediaCollectionsFromSync([remote]);
+ expect(result).toEqual({ applied: true, count: 1 });
+ const all = await svc.listCollections();
+ expect(all).toHaveLength(1);
+ expect(all[0].id).toBe('c-remote');
+ expect(all[0].items).toHaveLength(1);
+ expect(all[0].items[0].ref).toBe('peer.png');
+ });
+
+ it('unions items by kind:ref so neither side ever loses a render', async () => {
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'c1',
+ name: 'A',
+ description: '',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [
+ { kind: 'image', ref: 'local-only.png', addedAt: '2026-05-22T01:00:00Z' },
+ { kind: 'image', ref: 'shared.png', addedAt: '2026-05-22T01:00:00Z' },
+ ],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T01:00:00Z',
+ }],
+ });
+ const remote = {
+ id: 'c1',
+ name: 'A',
+ description: '',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [
+ { kind: 'image', ref: 'remote-only.png', addedAt: '2026-05-22T02:00:00Z' },
+ { kind: 'image', ref: 'shared.png', addedAt: '2026-05-22T02:00:00Z' },
+ ],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T02:00:00Z',
+ };
+ const result = await svc.mergeMediaCollectionsFromSync([remote]);
+ expect(result.applied).toBe(true);
+ const all = await svc.listCollections();
+ const refs = all[0].items.map(i => i.ref).sort();
+ expect(refs).toEqual(['local-only.png', 'remote-only.png', 'shared.png']);
+ // Shared item keeps the EARLIER addedAt (sync replay shouldn't bump it)
+ const shared = all[0].items.find(i => i.ref === 'shared.png');
+ expect(shared.addedAt).toBe('2026-05-22T01:00:00Z');
+ });
+
+ it('LWW: newer remote wins on top-level scalars (name, description, coverKey)', async () => {
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'c1',
+ name: 'Old Name',
+ description: 'old',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T01:00:00Z',
+ }],
+ });
+ const remote = {
+ id: 'c1',
+ name: 'New Name',
+ description: 'new',
+ coverKey: 'image:a.png',
+ universeId: null,
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T03:00:00Z',
+ };
+ await svc.mergeMediaCollectionsFromSync([remote]);
+ const [merged] = await svc.listCollections();
+ expect(merged.name).toBe('New Name');
+ expect(merged.description).toBe('new');
+ expect(merged.coverKey).toBe('image:a.png');
+ expect(merged.updatedAt).toBe('2026-05-22T03:00:00Z');
+ });
+
+ it('LWW: older remote loses on scalars, but items still union', async () => {
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'c1',
+ name: 'Local',
+ description: 'local',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'local.png', addedAt: '2026-05-22T02:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T03:00:00Z',
+ }],
+ });
+ const remote = {
+ id: 'c1',
+ name: 'Remote',
+ description: 'remote',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'remote.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T01:00:00Z',
+ };
+ await svc.mergeMediaCollectionsFromSync([remote]);
+ const [merged] = await svc.listCollections();
+ // Newer local wins on scalars
+ expect(merged.name).toBe('Local');
+ expect(merged.description).toBe('local');
+ expect(merged.updatedAt).toBe('2026-05-22T03:00:00Z');
+ // But items still union — that's the entire point of the merge
+ expect(merged.items.map(i => i.ref).sort()).toEqual(['local.png', 'remote.png']);
+ });
+
+ it('reports count:0 when nothing actually changes (no-op no-op)', async () => {
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'c1',
+ name: 'A',
+ description: '',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T01:00:00Z',
+ }],
+ });
+ const same = {
+ id: 'c1',
+ name: 'A',
+ description: '',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T01:00:00Z',
+ };
+ const result = await svc.mergeMediaCollectionsFromSync([same]);
+ expect(result).toEqual({ applied: false, count: 0 });
+ });
+
+ it('drops dangling coverKey that points at an item missing post-union', async () => {
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'c1',
+ name: 'A',
+ description: '',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'local.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T01:00:00Z',
+ }],
+ });
+ const remote = {
+ id: 'c1',
+ name: 'A',
+ description: '',
+ coverKey: 'image:nope.png', // points at an item that doesn't exist
+ universeId: null,
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'remote.png', addedAt: '2026-05-22T02:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T03:00:00Z',
+ };
+ await svc.mergeMediaCollectionsFromSync([remote]);
+ const [merged] = await svc.listCollections();
+ expect(merged.coverKey).toBeNull();
+ });
+
+ it('skips records that fail sanitization (missing id, empty name)', async () => {
+ const result = await svc.mergeMediaCollectionsFromSync([
+ { name: 'no-id', items: [] },
+ { id: 'has-id', name: '', items: [] },
+ { id: 'good', name: 'Real', description: '', coverKey: null, universeId: null, seriesId: null, items: [], createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z' },
+ ]);
+ expect(result).toEqual({ applied: true, count: 1 });
+ const all = await svc.listCollections();
+ expect(all).toHaveLength(1);
+ expect(all[0].id).toBe('good');
+ });
+
+ it('rejects items whose ref contains path-traversal tokens', async () => {
+ // Defense in depth — a peer can push a collection containing a ref
+ // like '../etc/passwd' via the linkedCollection field. sanitizeItem
+ // must drop these BEFORE they hit disk so the sender-side
+ // buildAssetManifestForCollection (and any future downstream consumer)
+ // never sees an unsafe ref.
+ const result = await svc.mergeMediaCollectionsFromSync([{
+ id: 'c-evil',
+ name: 'Evil',
+ description: '',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [
+ { kind: 'image', ref: '../etc/passwd', addedAt: '2026-05-22T01:00:00Z' },
+ { kind: 'image', ref: 'subdir/file.png', addedAt: '2026-05-22T01:00:00Z' },
+ { kind: 'image', ref: 'C:\\Windows\\System32', addedAt: '2026-05-22T01:00:00Z' },
+ { kind: 'image', ref: 'real.png', addedAt: '2026-05-22T01:00:00Z' },
+ ],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T01:00:00Z',
+ }]);
+ expect(result.applied).toBe(true);
+ const [merged] = await svc.listCollections();
+ // Only the safe ref survived sanitization
+ expect(merged.items).toHaveLength(1);
+ expect(merged.items[0].ref).toBe('real.png');
+ });
+
+ it('compares collection updatedAt as parsed milliseconds (not lexicographic)', async () => {
+ // Same hazard as the addedAt case: sanitizeCollection accepts any
+ // Date.parse-able string for `updatedAt`, so a non-ISO but valid
+ // timestamp could compare incorrectly as a string and flip LWW the
+ // wrong way. The slash-format timestamp here ('05/22/2026 18:00 UTC')
+ // sorts BEFORE the ISO timestamp lexicographically ('0' < '2'), but
+ // it's actually LATER in real time — so remote should win.
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'c1', name: 'Local', description: 'local', coverKey: null,
+ universeId: null, seriesId: null,
+ items: [],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T10:00:00Z',
+ }],
+ });
+ await svc.mergeMediaCollectionsFromSync([{
+ id: 'c1', name: 'Remote', description: 'remote', coverKey: null,
+ universeId: null, seriesId: null,
+ items: [],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '05/22/2026 18:00:00 UTC',
+ }]);
+ const [merged] = await svc.listCollections();
+ // Numeric compare: 18:00 > 10:00 → remote wins → name flips to "Remote"
+ expect(merged.name).toBe('Remote');
+ expect(merged.description).toBe('remote');
+ });
+
+ it('LWW: unparseable updatedAt never overrides a valid one', async () => {
+ // Defense in depth — a hand-edit or corrupted record shipping a
+ // garbage `updatedAt` shouldn't be able to claim "newer" than a valid
+ // local record and overwrite its scalars.
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'c1', name: 'Local', description: 'local', coverKey: null,
+ universeId: null, seriesId: null,
+ items: [],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T03:00:00Z',
+ }],
+ });
+ await svc.mergeMediaCollectionsFromSync([{
+ id: 'c1', name: 'Remote', description: 'remote', coverKey: null,
+ universeId: null, seriesId: null,
+ items: [],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: 'not a real timestamp',
+ }]);
+ const [merged] = await svc.listCollections();
+ expect(merged.name).toBe('Local');
+ expect(merged.description).toBe('local');
+ });
+
+ it('compares addedAt as parsed milliseconds (not lexicographic) when picking the earlier item', async () => {
+ // sanitizeItem accepts any Date.parse-able string, not strictly ISO-8601.
+ // Lexicographic compare would order "05/22/2026 ..." AFTER "2026-..." (the
+ // digit '0' sorts before '2'), but as parsed timestamps the slash-format
+ // is actually EARLIER here. Numeric compare keeps "earlier wins" honest
+ // across formats.
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'c1', name: 'A', description: '', coverKey: null,
+ universeId: null, seriesId: null,
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T10:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',
+ }],
+ });
+ await svc.mergeMediaCollectionsFromSync([{
+ id: 'c1', name: 'A', description: '', coverKey: null,
+ universeId: null, seriesId: null,
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '05/22/2026 08:00:00 UTC' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T02:00:00Z',
+ }]);
+ const [merged] = await svc.listCollections();
+ // The 08:00 slash-format timestamp is earlier than 10:00 ISO; numeric
+ // compare picks it. Lexicographic compare would have picked the ISO one.
+ expect(Date.parse(merged.items[0].addedAt)).toBe(Date.parse('05/22/2026 08:00:00 UTC'));
+ });
+});
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 16c0ff9f75..3ffc48fefe 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -52,6 +52,11 @@ import { instanceEvents } from '../instanceEvents.js';
import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';
import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';
import { listIssues, mergeIssuesFromSync } from '../pipeline/issues.js';
+import {
+ findCollectionByUniverseId,
+ findCollectionBySeriesId,
+ mergeMediaCollectionsFromSync,
+} from '../mediaCollections.js';
import {
initCursor,
ackDeletesUpTo,
@@ -594,16 +599,18 @@ export async function pushRecordToPeer(sub) {
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.
+ // FULL logical payload (record + bundled issues + linked collection +
+ // asset manifest) — not just the record — so an issue-only edit, an
+ // asset-only re-render, a collection-only item add, 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,
+ linkedCollection: payload.linkedCollection ?? null,
assetManifest: payload.assetManifest ?? [],
});
if (sub.lastPushedHash && sub.lastPushedHash === hash) {
@@ -669,6 +676,17 @@ async function buildPushPayload(sub, sourceInstanceId) {
if (!record) return null;
const sanitized = sanitizeRecordForWire('universe', record);
if (!sanitized) return null;
+ // Look up the linked media collection (auto-managed "Universe: X" bucket)
+ // and bundle it in the payload. Without this, collection-only edits (a
+ // new image added to the universe's gallery) wouldn't move the universe
+ // record itself, so the lastPushedHash short-circuit would treat the
+ // push as "unchanged" and the receiver's collection would diverge
+ // permanently. Tombstone pushes skip the collection bundle — a deleted
+ // universe's collection gets unlinked + orphaned locally, and shipping
+ // it would re-create an empty bucket on the receiver.
+ const linkedCollection = record.deleted === true
+ ? null
+ : await findCollectionByUniverseId(sub.recordId).catch(() => null);
// Tombstone push: deleted records carry no on-disk assets the receiver
// should pull. Sending an empty manifest avoids triggering
// pullMissingAssetsFromPeer for a record we're telling the peer to
@@ -676,8 +694,16 @@ async function buildPushPayload(sub, sourceInstanceId) {
// immediately orphan) and privacy-sensitive (e.g. a record deleted
// BECAUSE the user wanted the assets off-peer would otherwise still
// ship them with the tombstone push).
- const assetManifest = record.deleted === true ? [] : await buildAssetManifest(record);
- return { kind: 'universe', record: sanitized, assetManifest, sourceInstanceId };
+ const assetManifest = record.deleted === true
+ ? []
+ : await buildAssetManifestWithCollection(record, linkedCollection);
+ return {
+ kind: 'universe',
+ record: sanitized,
+ assetManifest,
+ sourceInstanceId,
+ ...(linkedCollection ? { linkedCollection } : {}),
+ };
}
if (sub.recordKind === 'series') {
const record = await getSeries(sub.recordId, { includeDeleted: true }).catch(() => null);
@@ -709,24 +735,32 @@ async function buildPushPayload(sub, sourceInstanceId) {
const manifestIssues = childIssues.filter(
(i) => i?.deleted !== true && i?.ephemeral !== true,
);
+ // Same collection-bundle reasoning as the universe branch: a "Series: X"
+ // collection's item changes don't move the series record, so without
+ // bundling the collection here the per-record push would short-circuit
+ // and the receiver's collection would diverge.
+ const linkedCollection = record.deleted === true
+ ? null
+ : await findCollectionBySeriesId(sub.recordId).catch(() => null);
// Tombstone push at the series level: same reasoning as universe above.
// When the series itself is deleted, send an empty asset manifest so
// the receiver doesn't pull bytes for a record it's about to tombstone.
const assetManifest = record.deleted === true
? []
- : await buildAssetManifestForSeries(record, manifestIssues);
+ : await buildAssetManifestForSeries(record, manifestIssues, linkedCollection);
return {
kind: 'series',
record: sanitized,
issues: sanitizedIssues,
assetManifest,
sourceInstanceId,
+ ...(linkedCollection ? { linkedCollection } : {}),
};
}
return null;
}
-async function buildAssetManifestForSeries(series, issues) {
+async function buildAssetManifestForSeries(series, issues, linkedCollection = null) {
const seriesAssets = await buildAssetManifest(series);
const dedup = new Map(seriesAssets.map((a) => [`${a.kind}:${a.filename}`, a]));
for (const issue of issues) {
@@ -735,9 +769,82 @@ async function buildAssetManifestForSeries(series, issues) {
dedup.set(`${a.kind}:${a.filename}`, a);
}
}
+ if (linkedCollection) {
+ const collectionAssets = await buildAssetManifestForCollection(linkedCollection);
+ for (const a of collectionAssets) {
+ dedup.set(`${a.kind}:${a.filename}`, a);
+ }
+ }
+ return [...dedup.values()];
+}
+
+/**
+ * Combined record + collection asset manifest for the universe push. Same
+ * dedup-by-`<kind>:<filename>` semantics as the series path so a render that
+ * lives in both the universe's canon (`imageRefs`) and the collection's
+ * `items[]` only ships once.
+ */
+async function buildAssetManifestWithCollection(record, linkedCollection) {
+ const recordAssets = await buildAssetManifest(record);
+ const dedup = new Map(recordAssets.map((a) => [`${a.kind}:${a.filename}`, a]));
+ if (linkedCollection) {
+ const collectionAssets = await buildAssetManifestForCollection(linkedCollection);
+ for (const a of collectionAssets) {
+ dedup.set(`${a.kind}:${a.filename}`, a);
+ }
+ }
return [...dedup.values()];
}
+/**
+ * Hash each item in a media collection so the receiver can pull missing
+ * bytes from `/data/images/` (or `/data/videos/`) via the existing asset-pull
+ * worker. Collections are append-mostly and items refer to filenames the
+ * sender has on disk; an item whose file is missing (e.g. half-imported
+ * from another peer) is skipped silently — including a null-hash entry
+ * would make every receiver re-request bytes the sender can't fulfill.
+ *
+ * Items with `kind: 'video'` route through the video PATHS dir; other kinds
+ * (today only 'image') route through the image PATHS dir. This mirrors
+ * `collectAssetReferences` and the `directoryForAssetKind` map.
+ */
+async function buildAssetManifestForCollection(collection) {
+ const out = [];
+ for (const it of collection?.items || []) {
+ if (!it || typeof it.ref !== 'string') continue;
+ // Path-traversal guard: collection items can arrive from a peer (via
+ // `linkedCollection` push or the snapshot-sync mediaCollections
+ // category), and a malicious `ref` like `../etc/passwd` would otherwise
+ // let `join(PATHS, ref)` read arbitrary local files when THIS instance
+ // is the sender — leaking the hash of the targeted file to peers. Same
+ // posture as the receiver-side `diffAssetManifestAgainstLocal`.
+ // `sanitizeItem` in mediaCollections.js also rejects path-traversal
+ // refs on the inbound merge boundary; this is defense in depth.
+ const safeName = sanitizeAssetFilename(it.ref);
+ if (!safeName) continue;
+ if (it.kind === 'video') {
+ // Video collection items store the bare video id (e.g. a UUID), while
+ // the on-disk file is `<id>.mp4` (today every PortOS-managed video is
+ // mp4 — confirmed by inspecting video-history.json). The image side
+ // stores refs WITH the extension already, so it works as-is. Append
+ // `.mp4` here unless the ref already carries an extension (defensive
+ // — older state may have stamped a filename instead of an id, and a
+ // future video format would land as `.webm` etc.).
+ const filename = /\.[a-z0-9]+$/i.test(safeName) ? safeName : `${safeName}.mp4`;
+ const entry = await hashSimpleAsset(filename, 'video', PATHS.videos);
+ if (entry) out.push(entry);
+ } else {
+ // Treat 'image' (and any unknown kind that isn't 'video') as a gallery
+ // image — the receiver's diff path will only accept entries whose kind
+ // maps to a known directory in `directoryForAssetKind`, so a junk kind
+ // gets filtered there without polluting disk.
+ const entry = await hashImageForManifest(safeName);
+ if (entry) out.push(entry);
+ }
+ }
+ return out;
+}
+
// 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
@@ -774,7 +881,7 @@ export async function applyIncomingPush(payload) {
if (!isPlainObject(payload)) {
throw makeErr('payload must be an object', ERR_VALIDATION);
}
- const { kind, record, issues, assetManifest, sourceInstanceId } = payload;
+ const { kind, record, issues, linkedCollection, assetManifest, sourceInstanceId } = payload;
if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {
throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);
}
@@ -800,6 +907,26 @@ export async function applyIncomingPush(payload) {
}
}
+ // Apply the bundled collection (if any) — same LWW + union-of-items
+ // semantics as the snapshot-sync mediaCollections category. Failures here
+ // don't fail the push: the record itself is already merged and the next
+ // snapshot-sync cycle will reconcile the collection if it diverged. The
+ // sanitizer in mediaCollections strips a peer-supplied `id` that isn't a
+ // string, so a bogus payload can't plant a malformed row.
+ //
+ // Defense in depth on the peer-supplied envelope: require a plain object
+ // (arrays would get wrapped and the sanitizer would drop them, but
+ // skipping early avoids the wasted call) AND refuse to merge when the
+ // record we just applied is a tombstone (`record.deleted === true`). The
+ // sender already skips bundling for tombstones, so a present
+ // `linkedCollection` on a tombstone push is either a bug or a malicious
+ // peer trying to resurrect a collection during a delete propagation.
+ if (record.deleted !== true && isPlainObject(linkedCollection)) {
+ await mergeMediaCollectionsFromSync([linkedCollection]).catch((err) => {
+ console.log(`⚠️ peerSync: linkedCollection merge failed: ${err.message}`);
+ });
+ }
+
// 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
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index a993b75635..cc8dc33bbc 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -38,6 +38,12 @@ vi.mock('../pipeline/issues.js', async () => ({
mergeIssuesFromSync: vi.fn(),
}));
+vi.mock('../mediaCollections.js', async () => ({
+ findCollectionByUniverseId: vi.fn(),
+ findCollectionBySeriesId: vi.fn(),
+ mergeMediaCollectionsFromSync: vi.fn(),
+}));
+
vi.mock('../../lib/peerHttpClient.js', async () => ({
peerFetch: vi.fn(),
peerSocketOptions: {},
@@ -65,6 +71,11 @@ import { getInstanceId, getPeers } from '../instances.js';
import { getUniverse, mergeUniversesFromSync, listUniverses } from '../universeBuilder.js';
import { getSeries, mergeSeriesFromSync, listSeries } from '../pipeline/series.js';
import { listIssues, mergeIssuesFromSync } from '../pipeline/issues.js';
+import {
+ findCollectionByUniverseId,
+ findCollectionBySeriesId,
+ mergeMediaCollectionsFromSync,
+} from '../mediaCollections.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
import { listCursors, __drainForTests as __drainCursors } from './peerTombstoneCursors.js';
@@ -129,6 +140,11 @@ beforeEach(async () => {
vi.mocked(getUniverse).mockReset().mockResolvedValue(undefined);
vi.mocked(getSeries).mockReset().mockResolvedValue(undefined);
vi.mocked(listIssues).mockReset().mockResolvedValue([]);
+ // Default: no linked collection for any record. Tests that exercise the
+ // bundle path override these per-call.
+ vi.mocked(findCollectionByUniverseId).mockReset().mockResolvedValue(null);
+ vi.mocked(findCollectionBySeriesId).mockReset().mockResolvedValue(null);
+ vi.mocked(mergeMediaCollectionsFromSync).mockReset().mockResolvedValue({ applied: false, count: 0 });
await __resetForTests();
});
@@ -932,6 +948,127 @@ describe('peerSync', () => {
expect(captured.issues.map((i) => i.id)).toEqual(['i1', 'i2']);
});
+ it('bundles the linked media collection with a universe push so collection-only edits propagate', async () => {
+ // Regression: collection items[] adds emit recordEvents.updated('universe', id)
+ // but the universe record content itself doesn't change, so the
+ // lastPushedHash short-circuit treated the push as 'unchanged' and the
+ // receiver's collection diverged permanently. Including the linked
+ // collection in both the payload AND the hash defeats the short-circuit.
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Universe' });
+ vi.mocked(findCollectionByUniverseId).mockResolvedValueOnce({
+ id: 'col-1',
+ name: 'Universe: U',
+ description: '',
+ coverKey: null,
+ universeId: 'u1',
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-22T01:00:00Z',
+ });
+ 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: 'universe', recordId: 'u1',
+ });
+ expect(captured.kind).toBe('universe');
+ expect(captured.linkedCollection).toBeTruthy();
+ expect(captured.linkedCollection.id).toBe('col-1');
+ expect(captured.linkedCollection.items).toHaveLength(1);
+ });
+
+ it('re-pushes when only the linked collection items change (universe record byte-identical)', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Universe' });
+ vi.mocked(findCollectionByUniverseId)
+ .mockResolvedValueOnce({
+ id: 'col-1', name: 'Universe: U', description: '', coverKey: null,
+ universeId: 'u1', seriesId: null,
+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',
+ })
+ .mockResolvedValueOnce({
+ id: 'col-1', name: 'Universe: U', description: '', coverKey: null,
+ universeId: 'u1', seriesId: null,
+ items: [
+ { kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' },
+ { kind: 'image', ref: 'b.png', addedAt: '2026-05-22T02:00:00Z' },
+ ],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T02:00:00Z',
+ });
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });
+ const sub = await subscribePeer(
+ { peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' },
+ { adoptedFromReverse: true },
+ );
+ const first = await pushRecordToPeer(sub);
+ expect(first.pushed).toBe(true);
+
+ vi.mocked(peerFetch).mockClear();
+ const refreshed = await findPeerSubscription('peer-a', 'universe', 'u1');
+ const second = await pushRecordToPeer(refreshed);
+ expect(second.pushed).toBe(true);
+ expect(second.reason).not.toBe('unchanged');
+ expect(peerFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('appends .mp4 when a collection video item ref is a bare id (no extension)', async () => {
+ // Regression: video collection items store the bare id (e.g. a UUID),
+ // while the on-disk file is `<id>.mp4`. Without the append, the file
+ // would never be found, no manifest entry would be emitted, and the
+ // receiver would never pull the video bytes.
+ PATHS.videos = join(tmp, 'videos');
+ await mkdir(PATHS.videos, { recursive: true });
+ await writeFile(join(PATHS.videos, 'vid-abc.mp4'), 'fake mp4 bytes');
+
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Universe' });
+ vi.mocked(findCollectionByUniverseId).mockResolvedValueOnce({
+ id: 'col-1', name: 'Universe: U', description: '', coverKey: null,
+ universeId: 'u1', seriesId: null,
+ items: [{ kind: 'video', ref: 'vid-abc', addedAt: '2026-05-22T01:00:00Z' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',
+ });
+ 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: 'universe', recordId: 'u1',
+ });
+ const videoEntries = captured.assetManifest.filter(a => a.kind === 'video');
+ expect(videoEntries).toHaveLength(1);
+ // The .mp4 must have been appended to the bare id when constructing the manifest entry.
+ expect(videoEntries[0].filename).toBe('vid-abc.mp4');
+ });
+
+ it('does NOT bundle a linked collection when the universe is a tombstone', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({
+ id: 'u1', name: 'Gone', deleted: true, deletedAt: '2026-05-22T03:00:00Z',
+ });
+ // If buildPushPayload still called findCollectionByUniverseId for a
+ // tombstoned record, we'd see this mock invoked. Guard against the
+ // bundle path firing for soft-deletes.
+ vi.mocked(findCollectionByUniverseId).mockResolvedValue({
+ id: 'col-1', name: 'Universe: U', description: '', coverKey: null,
+ universeId: 'u1', seriesId: null, items: [],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',
+ });
+ 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: 'universe', recordId: 'u1',
+ });
+ expect(captured.kind).toBe('universe');
+ expect(captured.linkedCollection).toBeUndefined();
+ expect(captured.assetManifest).toEqual([]);
+ });
+
it('drops ephemeral child issues from both the bundled issues AND the asset manifest', async () => {
// Regression: an earlier version filtered ephemeral issues out of
// `sanitizedIssues` but still walked the unfiltered `childIssues`
@@ -1082,6 +1219,65 @@ describe('peerSync', () => {
]);
});
+ it('routes a bundled linkedCollection through mergeMediaCollectionsFromSync', async () => {
+ const linkedCollection = {
+ id: 'col-1', name: 'Universe: U', items: [
+ { kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' },
+ ],
+ };
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1', name: 'Foo', deleted: false, deletedAt: null },
+ linkedCollection,
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(mergeMediaCollectionsFromSync).toHaveBeenCalledWith([linkedCollection]);
+ });
+
+ it('skips mergeMediaCollectionsFromSync when no linkedCollection is bundled', async () => {
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1', deleted: false, deletedAt: null },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(mergeMediaCollectionsFromSync).not.toHaveBeenCalled();
+ });
+
+ it('refuses to merge linkedCollection when the incoming record is a tombstone', async () => {
+ // Defense in depth: the sender's buildPushPayload already skips the
+ // bundle for tombstones, but a buggy or malicious peer could send
+ // one anyway. Receiving a collection during a delete propagation
+ // would resurrect collection state for a record being torn down.
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1', deleted: true, deletedAt: '2026-05-22T03:00:00Z' },
+ linkedCollection: { id: 'col-1', name: 'Universe: U', items: [] },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(mergeMediaCollectionsFromSync).not.toHaveBeenCalled();
+ });
+
+ it('refuses to merge linkedCollection when it is not a plain object (array, primitive)', async () => {
+ // Wrapping a non-plain-object in `[...]` and passing to the merge
+ // function would just produce a no-op (sanitizeCollection drops
+ // non-objects), but skipping early keeps the trust posture clean
+ // and the failure mode obvious.
+ for (const bogus of [[], ['a'], 'string', 42, true]) {
+ vi.mocked(mergeMediaCollectionsFromSync).mockClear();
+ await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1', deleted: false, deletedAt: null },
+ linkedCollection: bogus,
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(mergeMediaCollectionsFromSync).not.toHaveBeenCalled();
+ }
+ });
+
it('dispatches series pushes through mergeSeriesFromSync AND mergeIssuesFromSync for bundled issues', async () => {
await applyIncomingPush({
kind: 'series',