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

fix(sync): cascade unlink no longer out-races a collection tombstone on peers

Adam Eivy011fe4a026ad
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 20b8dc818a..78c9abf54a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,4 +12,6 @@ TBD
## Fixed
+- **Federated media collections: a merged-away duplicate no longer survives on peers.** When a universe (or series) *merge* tombstones the loser's auto-collection, a receiving peer applies the universe tombstone first — and its cascade (`unlinkCollectionsForUniverse` / `unlinkCollectionsForSeries`) was stamping the linked collection's `updatedAt` to "now", which then defeated the collection's own (older) tombstone under Last-Writer-Wins and left a live duplicate "Universe: X" collection on the peer. The cascade unlink now **preserves `updatedAt`** (it's a derived side-effect of the owner's deletion, not a user edit), so the collection tombstone still wins and both machines converge to deleted. Items are never lost — they're always unioned on merge.
+
## Removed
diff --git a/PLAN.md b/PLAN.md
index af828b0f7e..935d6f563d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -131,6 +131,10 @@ Surfaced while building the sync-hygiene feature (duplicate detection/merge, non
- [ ] [conflict-journal-push-flush-coalesce] **Coalesce per-push base-hash flushes.** `pushRecordToPeer` (`server/services/sharing/peerSync.js` ~947) stamps a base hash and calls `flushBaseHashes()` per pushed universe/series, so a large push loop rewrites `sync_base_hashes.json` once per record. Copilot (PR #489) suggested debouncing. A `setTimeout`-based debounce was tried and reverted because the real unref'd timer leaked into `peerSync.test.js`'s same-file settle-waits and made the suite flaky. A safe coalescing approach (e.g. a microtask/`queueMicrotask` batch within a single push burst, or a test-injectable scheduler) could land the optimization without the timer-leak flake. Low priority — the flush is serialized + fire-and-forget and the file is tiny.
- [ ] [conflict-journal-base-hash-prune] **`sync_base_hashes.json` grows unbounded.** `server/lib/conflictJournal.js` seeds a base hash per synced universe/series and never prunes entries for deleted/tombstoned records. Tiny per-entry, but a long-lived install accumulates dead keys. Add a sweep (drop keys whose record no longer resolves) to the tombstone GC path.
+### Storage scalability — deferred follow-ups (2026-05-26)
+
+- [ ] [media-collections-per-record-store] **Migrate `media-collections.json` to the per-record `createCollectionStore` layout (like universes / issues / series).** Today all collections live in one monolithic `data/media-collections.json`; every `addItem` / `bulkUpdateCollectionItems` rewrites the *entire* file (all collections) through a single `serializeFileWrite` tail — so high-frequency render-filing (cover filer, universe/series auto-collections) serializes unrelated writes and rewrites a ~200 KB doc per image. Convert to `createCollectionStore({ dir: join(PATHS.data,'media-collections'), type: 'mediaCollections', … })` → `data/media-collections/{id}/index.json` + a type-level `index.json`, mirroring migration 034 (`universeBuilder.js`). Cross-install work (per the distribution model): needs a `scripts/migrations/0NN-split-media-collections.js` that fans the monolith out into per-record dirs, a storage `schemaVersion` + boot-time `verifySchemaVersion` hook (`server/index.js`), seed handling, and a careful rewrite of every reader/writer — especially the sync layer (`mergeMediaCollectionsFromSync`, `listCollections({ includeDeleted })`, the push/subscription pipeline in `sharing/peerSync.js`, `pruneTombstonedCollections`) which all currently assume the single-file shape. NOTE: this is **independent of** the LWW cascade duplicate bug fixed 2026-05-26 (cascade unlink no longer bumps `updatedAt`) — migrating storage neither fixes nor requires that. Human-led: large, touches federation — brainstorm/plan before coding.
+
### Browser / Chrome-variant + commands hardening (review candidates, 2026-05-25)
Surfaced by a gemini review during PR #489 (sync-hygiene) that scoped beyond that PR's diff — these are in the already-merged Chrome-variant browser feature + the commands service, NOT in #489. Verified against the actual code where noted; out of scope for #489, land them in a separate hardening PR.
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index 6bf4c61ccf..0053aeb91e 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -478,6 +478,10 @@ export async function findOrCreateSeriesCollection({ seriesId, seriesName, descr
return result;
}
+// Series mirror of `unlinkCollectionsForUniverse` — same cascade semantics,
+// same reason for preserving `updatedAt` (see that function's note). A series
+// merge tombstones the loser series-collection and the loser series; the
+// series-tombstone cascade must not bump the collection past its own tombstone.
export async function unlinkCollectionsForSeries(seriesId) {
if (typeof seriesId !== 'string' || !seriesId) return [];
const needle = seriesId.slice(0, SERIES_ID_MAX);
@@ -487,11 +491,10 @@ export async function unlinkCollectionsForSeries(seriesId) {
.map((c, i) => (c.seriesId === needle ? i : -1))
.filter((i) => i >= 0);
if (!matches.length) return [];
- const now = new Date().toISOString();
const next = [...all];
const unlinkedIds = [];
for (const i of matches) {
- next[i] = { ...all[i], seriesId: null, updatedAt: now };
+ next[i] = { ...all[i], seriesId: null };
unlinkedIds.push(all[i].id);
}
await writeAll(next);
@@ -529,6 +532,17 @@ export async function renameCollectionForSeries(seriesId, newSeriesName) {
// becomes a normal user-owned collection (renamable, deletable, etc.). The
// items themselves are preserved — the user may still want the renders.
// Returns the list of unlinked collection ids (empty when none matched).
+//
+// Deliberately does NOT bump `updatedAt`. This is a CASCADED side-effect of
+// the owner universe's deletion, not a user edit — severing the link doesn't
+// change the collection's content (items are untouched). Advancing the LWW
+// clock here would make the unlinked bucket look "freshly edited" and out-race
+// the collection's OWN tombstone on a peer: a universe merge tombstones the
+// loser auto-collection (older `updatedAt`) AND tombstones the universe, whose
+// cascade lands first on the receiver. A bump here would defeat the (older)
+// collection tombstone under pure LWW and strand a live duplicate on the peer.
+// Items always union on merge (`mergeCollectionItems`), so preserving the
+// timestamp can't lose renders.
export async function unlinkCollectionsForUniverse(universeId) {
if (typeof universeId !== 'string' || !universeId) return [];
const needle = universeId.slice(0, UNIVERSE_ID_MAX);
@@ -538,11 +552,10 @@ export async function unlinkCollectionsForUniverse(universeId) {
.map((c, i) => (c.universeId === needle ? i : -1))
.filter((i) => i >= 0);
if (!matches.length) return [];
- const now = new Date().toISOString();
const next = [...all];
const unlinkedIds = [];
for (const i of matches) {
- next[i] = { ...all[i], universeId: null, updatedAt: now };
+ next[i] = { ...all[i], universeId: null };
unlinkedIds.push(all[i].id);
}
await writeAll(next);
diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.js
index 5497f542e8..bd61636f6c 100644
--- a/server/services/mediaCollections.test.js
+++ b/server/services/mediaCollections.test.js
@@ -416,6 +416,24 @@ describe('mediaCollections service', () => {
expect(await svc.unlinkCollectionsForUniverse(null)).toEqual([]);
});
+ it('unlinkCollectionsForUniverse preserves updatedAt (cascade side-effect, not a user edit)', async () => {
+ // The bump would let the unlinked bucket out-race its own tombstone on a
+ // peer during a universe merge — see unlinkCollectionsForUniverse's note.
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'uc-u1', name: 'Universe: Foo', description: '', coverKey: null,
+ universeId: 'u-1', seriesId: null,
+ items: [{ kind: 'image', ref: 'art.png', addedAt: '2026-05-26T13:00:00.000Z' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-26T13:00:00.000Z',
+ }],
+ });
+ await svc.unlinkCollectionsForUniverse('u-1');
+ const fresh = (await svc.listCollections()).find(c => c.id === 'uc-u1');
+ expect(fresh.universeId).toBeNull();
+ expect(fresh.updatedAt).toBe('2026-05-26T13:00:00.000Z');
+ expect(fresh.items).toHaveLength(1);
+ });
+
describe('findOrCreateUniverseCollection', () => {
it('mints a DETERMINISTIC id (uc-<universeId>) so federated peers converge, not a random UUID', async () => {
const c = await svc.findOrCreateUniverseCollection({ universeId: 'u-1', universeName: 'Foo' });
@@ -728,6 +746,22 @@ describe('mediaCollections service', () => {
expect(renamed.name).toBe('Orphan');
});
+ it('unlinkCollectionsForSeries preserves updatedAt (cascade side-effect, not a user edit)', async () => {
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'sc-ser1', name: 'Series: Foo', description: '', coverKey: null,
+ universeId: null, seriesId: 'ser-1',
+ items: [{ kind: 'image', ref: 'cover.png', addedAt: '2026-05-26T13:00:00.000Z' }],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-26T13:00:00.000Z',
+ }],
+ });
+ await svc.unlinkCollectionsForSeries('ser-1');
+ const fresh = (await svc.listCollections()).find(c => c.id === 'sc-ser1');
+ expect(fresh.seriesId).toBeNull();
+ expect(fresh.updatedAt).toBe('2026-05-26T13:00:00.000Z');
+ expect(fresh.items).toHaveLength(1);
+ });
+
it('addItem on a series-linked collection emits recordUpdated("series", seriesId)', async () => {
const events = [];
const { recordEvents } = await import('./sharing/recordEvents.js');
@@ -935,6 +969,54 @@ describe('mergeMediaCollectionsFromSync', () => {
expect(merged.items.map(i => i.ref).sort()).toEqual(['local.png', 'remote.png']);
});
+ it('universe-merge cascade race: an unlink does not out-race the collection tombstone', async () => {
+ // Repro of the real peer bug. A universe merge tombstones the loser auto-
+ // collection (with the merge-time updatedAt) AND tombstones the loser
+ // universe. On the receiving peer the UNIVERSE tombstone's cascade
+ // (unlinkCollectionsForUniverse) lands first and nulls the collection's
+ // universeId. If that unlink bumped updatedAt to "now", the collection's
+ // own (older) tombstone would then lose LWW and a live duplicate would
+ // survive. Because the cascade unlink preserves updatedAt, the tombstone
+ // still wins and converges to deleted.
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [{
+ id: 'uc-loser',
+ name: 'Universe: Clandestiny',
+ description: '',
+ coverKey: null,
+ universeId: 'u-loser',
+ seriesId: null,
+ items: [{ kind: 'image', ref: 'folded.png', addedAt: '2026-05-26T13:00:00.000Z' }],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-26T13:00:00.000Z', // last real edit, BEFORE the merge
+ }],
+ });
+ // 1. Universe tombstone cascade hits the receiver first.
+ await svc.unlinkCollectionsForUniverse('u-loser');
+ const afterUnlink = (await svc.listCollections()).find(c => c.id === 'uc-loser');
+ expect(afterUnlink.universeId).toBeNull();
+ expect(afterUnlink.updatedAt).toBe('2026-05-26T13:00:00.000Z'); // NOT bumped
+ // 2. The collection's own tombstone (merge-time, newer than the last edit) arrives.
+ await svc.mergeMediaCollectionsFromSync([{
+ id: 'uc-loser',
+ name: 'Universe: Clandestiny',
+ description: '',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [],
+ createdAt: '2026-05-22T00:00:00Z',
+ updatedAt: '2026-05-26T13:31:33.807Z',
+ deleted: true,
+ deletedAt: '2026-05-26T13:31:33.807Z',
+ }]);
+ // No live duplicate left behind.
+ expect((await svc.listCollections()).some(c => c.id === 'uc-loser')).toBe(false);
+ const tomb = (await svc.listCollections({ includeDeleted: true })).find(c => c.id === 'uc-loser');
+ expect(tomb.deleted).toBe(true);
+ expect(tomb.items).toEqual([]);
+ });
+
it('reports count:0 when nothing actually changes (no-op no-op)', async () => {
fileStore.set('/mock/data/media-collections.json', {
collections: [{