Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([conflict-journal-media-collections]): journal media-collection scalar overwrites via scalar-subset hashing
[._.]/ Adam Eivyb156b255382d
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex c25776af85..053cceef8a 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -56,17 +56,46 @@ export const conflictJournalStore = () => store();// ---- content hashing (matches the sender/receiver wire convention) ----+// mediaCollection divergence is detected over a SCALAR SUBSET, not the whole+// wire record. The merge (`mergeMediaCollectionsFromSync`) union-merges `items`+// — neither side ever loses a render it knows about — and bumps `updatedAt` on+// every `addItem`. So hashing the full record would false-positive whenever two+// peers independently added different items to the same collection (items ++// updatedAt differ, yet NOTHING was overwritten). The journal only cares about+// the LWW-overwritten scalars; we hash exactly those so an item-only divergence+// is invisible to detection while a real name/description/cover/link overwrite+// still trips it. `updatedAt` is the LWW *key*, not content, so it's excluded+// too. Soft-delete fields stay in (a remote delete that erases a diverged local+// edit is a real conflict — mirrors the universe/series delete-vs-edit case).+const MEDIA_COLLECTION_SCALAR_FIELDS = Object.freeze(['name', 'description', 'coverKey', 'universeId', 'seriesId']);+/**- * sha256 of the canonical wire projection. Reuses sanitizeRecordForWire ++ * sha256 of the canonical content projection. Reuses sanitizeRecordForWire +* canonicalStringify so the sender hashing what it pushes and the receiver- * hashing its local copy agree byte-for-byte. Returns null when the record has- * no wire form (ephemeral non-tombstone, or invalid) — callers treat a null- * hash as "cannot compare".+ * hashing its local copy agree byte-for-byte. For mediaCollection the wire form+ * is further narrowed to its overwritable scalars (see+ * MEDIA_COLLECTION_SCALAR_FIELDS) — both sides apply the same narrowing, so the+ * base hash stays consistent across peers. Returns null when the record has no+ * wire form (ephemeral non-tombstone, or invalid) — callers treat a null hash+ * as "cannot compare".*/export function contentHashForRecord(kind, record) {const wire = sanitizeRecordForWire(kind, record);if (!wire) return null;- return createHash('sha256').update(canonicalStringify(wire)).digest('hex');+ const hashInput = kind === 'mediaCollection' ? projectCollectionScalars(wire) : wire;+ return createHash('sha256').update(canonicalStringify(hashInput)).digest('hex');+}++// Narrow a wire-form collection to the scalars whose overwrite the journal+// tracks, plus the (already-normalized) soft-delete pair. `items`/`updatedAt`/+// `id` and all other fields are dropped. canonicalStringify sorts keys, so the+// insertion order here is irrelevant to the resulting hash.+function projectCollectionScalars(wire) {+ const out = {};+ for (const f of MEDIA_COLLECTION_SCALAR_FIELDS) if (f in wire) out[f] = wire[f];+ out.deleted = wire.deleted === true;+ out.deletedAt = out.deleted ? (wire.deletedAt ?? null) : null;+ return out;}// ---- base-hash side store (in-memory cache, batched write-through) ----@@ -158,6 +187,11 @@ export async function detectConflict({ kind, id, local, remote }) {export const RESTORABLE_FIELDS = Object.freeze({universe: ['name', 'starterPrompt', 'logline', 'premise', 'styleNotes', 'categories', 'compositeSheets', 'influences', 'characters', 'places', 'objects'],series: ['name', 'logline', 'premise', 'styleNotes', 'titleLogo', 'author', 'stylePromptOverride', 'stylePromptOverrideMode', 'targetFormat', 'issueCountTarget', 'arc', 'seasons'],+ // mediaCollection restores only the user-authored content scalars. `items`+ // are union-merged (never lost, nothing to restore); `universeId`/`seriesId`+ // are structural links managed by the link/unlink helpers, not `updateCollection`+ // patches — so they're hashed for DETECTION but not offered for restore.+ mediaCollection: ['name', 'description', 'coverKey'],});// Top-level shallow diff over the kind's restorable content fields — enough fordiff --git a/server/lib/conflictJournal.test.js b/server/lib/conflictJournal.test.jsindex 57bbe798dc..f7b8b7a9ae 100644--- a/server/lib/conflictJournal.test.js+++ b/server/lib/conflictJournal.test.js@@ -129,3 +129,60 @@ describe('conflictJournal', () => {expect(await cj.getSyncBaseHash('universe', 'nonexistent')).toBeNull();});});++// A minimal collection-shaped record (sanitizeRecordForWire('mediaCollection')+// needs an id; the merge LWWs name/description/coverKey/universeId/seriesId and+// union-merges items). `items`/`updatedAt` must NOT affect the conflict hash.+const coll = (over = {}) => ({+ id: 'c-1', name: 'Bucket', description: 'd', coverKey: null, universeId: null, seriesId: null,+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-01T00:00:00Z' }],+ createdAt: '2026-05-01T00:00:00Z', updatedAt: '2026-05-01T00:00:00Z', ...over,+});++describe('conflictJournal — mediaCollection scalar-subset hashing', () => {+ beforeEach(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(TEST_DATA_ROOT, { recursive: true });+ cj.__resetBaseHashCacheForTests();+ });++ it('hash ignores items and updatedAt (union-merged / LWW-key, never lost)', () => {+ const base = cj.contentHashForRecord('mediaCollection', coll());+ // Add an item + bump updatedAt — exactly what addItem does. Same scalars.+ const withItem = cj.contentHashForRecord('mediaCollection', coll({+ items: [+ { kind: 'image', ref: 'a.png', addedAt: '2026-05-01T00:00:00Z' },+ { kind: 'image', ref: 'b.png', addedAt: '2026-05-02T00:00:00Z' },+ ],+ updatedAt: '2026-05-02T00:00:00Z',+ }));+ expect(withItem).toBe(base);+ });++ it('hash changes when a tracked scalar (name) changes', () => {+ expect(cj.contentHashForRecord('mediaCollection', coll({ name: 'Renamed' })))+ .not.toBe(cj.contentHashForRecord('mediaCollection', coll()));+ });++ it('item-only divergence is NOT a 3-way conflict (no false-positive journal)', async () => {+ await cj.setSyncBaseHash('mediaCollection', 'c-1', cj.contentHashForRecord('mediaCollection', coll()));+ // Both peers added different items; neither touched a scalar. updatedAt bumps.+ const local = coll({ items: [{ kind: 'image', ref: 'L.png', addedAt: '2026-05-02T00:00:00Z' }], updatedAt: '2026-05-02T00:00:00Z' });+ const remote = coll({ items: [{ kind: 'image', ref: 'R.png', addedAt: '2026-05-03T00:00:00Z' }], updatedAt: '2026-05-03T00:00:00Z' });+ await cj.maybeJournalBeforeOverwrite({ kind: 'mediaCollection', id: 'c-1', local, remote, source: { via: 'sync' } });+ expect(await pendingEntries()).toHaveLength(0);+ });++ it('true scalar divergence (both renamed) journals exactly one entry', async () => {+ await cj.setSyncBaseHash('mediaCollection', 'c-1', cj.contentHashForRecord('mediaCollection', coll()));+ const local = coll({ name: 'LOCAL name', updatedAt: '2026-05-02T00:00:00Z' });+ const remote = coll({ name: 'REMOTE name', updatedAt: '2026-05-03T00:00:00Z' });+ await cj.maybeJournalBeforeOverwrite({ kind: 'mediaCollection', id: 'c-1', local, remote, source: { via: 'sync' } });+ const entries = await pendingEntries();+ expect(entries).toHaveLength(1);+ expect(entries[0].localSnapshot.name).toBe('LOCAL name');+ expect(entries[0].diffSummary.some((d) => d.field === 'name')).toBe(true);+ // diffSummary only offers restorable content fields, never items/updatedAt.+ expect(entries[0].diffSummary.some((d) => d.field === 'items' || d.field === 'updatedAt')).toBe(false);+ });+});diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.jsindex f02e22631b..531ce569d6 100644--- a/server/services/conflictJournalResolver.js+++ b/server/services/conflictJournalResolver.js@@ -29,6 +29,7 @@ import { isSafeRecordId } from '../lib/validation.js';import { conflictJournalStore, RESTORABLE_FIELDS } from '../lib/conflictJournal.js';import { updateUniverse, ERR_NOT_FOUND as UNIVERSE_NOT_FOUND } from './universeBuilder.js';import { updateSeries, ERR_NOT_FOUND as SERIES_NOT_FOUND } from './pipeline/series.js';+import { updateCollection, getCollection, ERR_NOT_FOUND as COLLECTION_NOT_FOUND } from './mediaCollections.js';export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';export const ERR_VALIDATION = 'CONFLICT_JOURNAL_VALIDATION';@@ -67,7 +68,7 @@ async function applyToRecord(kind, recordId, patch) {// resolution. Translate the services' not-found codes into ERR_TARGET_GONE so// the route maps it to a clean 409 ("discard the entry") instead of a 500.const translateGone = (err) => {- if (err?.code === UNIVERSE_NOT_FOUND || err?.code === SERIES_NOT_FOUND) {+ if (err?.code === UNIVERSE_NOT_FOUND || err?.code === SERIES_NOT_FOUND || err?.code === COLLECTION_NOT_FOUND) {throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);}throw err;@@ -78,6 +79,18 @@ async function applyToRecord(kind, recordId, patch) {await updateUniverse(recordId, () => patch).catch(translateGone);} else if (kind === 'series') {await updateSeries(recordId, patch).catch(translateGone);+ } else if (kind === 'mediaCollection') {+ // A linked collection (universeId/seriesId set) locks its `name` to the+ // owner record — updateCollection rejects a name change, and a name+ // "conflict" on such a collection is really an owner-rename cascade+ // artifact (the universe/series conflict is journaled separately). Drop+ // `name` from the patch for a linked collection so restore still applies+ // the freely-editable scalars (description, coverKey) instead of 500ing.+ // A standalone collection restores all three.+ const cur = await getCollection(recordId, { includeDeleted: true }).catch(translateGone);+ const { name: _lockedName, ...withoutName } = patch;+ const effective = (cur?.universeId || cur?.seriesId) ? withoutName : patch;+ if (Object.keys(effective).length > 0) await updateCollection(recordId, effective).catch(translateGone);} else {throw makeErr(`Unsupported conflict kind: ${kind}`, ERR_VALIDATION);}diff --git a/server/services/conflictJournalResolver.test.js b/server/services/conflictJournalResolver.test.jsindex 5ca87af8c0..f249659935 100644--- a/server/services/conflictJournalResolver.test.js+++ b/server/services/conflictJournalResolver.test.js@@ -19,6 +19,7 @@ vi.mock('crypto', async () => {const resolver = await import('./conflictJournalResolver.js');const universeSvc = await import('./universeBuilder.js');+const collSvc = await import('./mediaCollections.js');const cj = await import('../lib/conflictJournal.js');afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));@@ -111,4 +112,44 @@ describe('conflictJournalResolver', () => {await expect(resolver.deleteConflict('../../etc/passwd')).rejects.toMatchObject({ code: resolver.ERR_NOT_FOUND });await expect(resolver.deleteConflict('..')).rejects.toMatchObject({ code: resolver.ERR_NOT_FOUND });});++ // --- mediaCollection conflicts ---++ const seedCollectionEntry = async (recordId, localSnapshot) => {+ const id = `entry-${++uuidCounter}`;+ await cj.conflictJournalStore().saveOne(id, {+ id, recordKind: 'mediaCollection', recordId, detectedAt: '2026-05-01T00:00:00Z',+ source: { via: 'sync' }, baseHash: 'b', localHash: 'l', remoteHash: 'r',+ localSnapshot, remoteSnapshot: {}, localUpdatedAt: null, remoteUpdatedAt: null,+ diffSummary: [], status: 'pending', resolvedAt: null, resolution: null,+ });+ return id;+ };++ it('restore-all re-applies a STANDALONE collection’s archived scalars (name, description)', async () => {+ const c = await collSvc.createCollection({ name: 'Remote Name', description: 'remote desc' });+ const entryId = await seedCollectionEntry(c.id, { id: c.id, name: 'Local Name', description: 'local desc', coverKey: null });+ await resolver.resolveConflict(entryId, { action: 'restore-all' });+ const fresh = await collSvc.getCollection(c.id);+ expect(fresh.name).toBe('Local Name'); // standalone → name restorable+ expect(fresh.description).toBe('local desc');+ });++ it('restore-all on a LINKED collection skips the locked name but applies description', async () => {+ const u = await universeSvc.createUniverse({ name: 'Verse' });+ const c = await collSvc.findOrCreateUniverseCollection({ universeId: u.id, universeName: 'Verse', description: 'remote desc' });+ const ownerName = c.name; // universe-derived, locked+ const entryId = await seedCollectionEntry(c.id, { id: c.id, name: 'Stale Name', description: 'local desc', coverKey: null });+ // Must NOT throw on the locked name — name is dropped, description applies.+ await resolver.resolveConflict(entryId, { action: 'restore-all' });+ const fresh = await collSvc.getCollection(c.id);+ expect(fresh.name).toBe(ownerName); // unchanged (locked to universe)+ expect(fresh.description).toBe('local desc'); // freely-editable scalar restored+ });++ it('translates a deleted collection target into ERR_TARGET_GONE', async () => {+ const entryId = await seedCollectionEntry('ghost-collection', { id: 'ghost-collection', name: 'Ghost', description: 'x', coverKey: null });+ await expect(resolver.resolveConflict(entryId, { action: 'restore-all' }))+ .rejects.toMatchObject({ code: resolver.ERR_TARGET_GONE });+ });});diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex 9c9908c4b6..98ca78b88e 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -29,6 +29,9 @@ import { createCollectionStore } from '../lib/collectionStore.js';import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';import { sanitizeOrigin } from '../lib/sharingOrigin.js';import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';+import {+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,+} from '../lib/conflictJournal.js';export const ERR_NOT_FOUND = 'NOT_FOUND';export const ERR_DUPLICATE = 'DUPLICATE';@@ -923,7 +926,7 @@ export async function pruneTombstonedCollections(olderThanMs) {* against the SAME collection can't interleave, while merges of DIFFERENT* collections proceed in parallel.*/-export async function mergeMediaCollectionsFromSync(remoteCollections) {+export async function mergeMediaCollectionsFromSync(remoteCollections, { source = { via: 'sync', peerId: null } } = {}) {if (!Array.isArray(remoteCollections)) return { applied: false, count: 0 };let changed = 0;for (const remote of remoteCollections) {@@ -933,6 +936,9 @@ export async function mergeMediaCollectionsFromSync(remoteCollections) {const local = await store().loadOne(sanitized.id);if (!local) {await store().saveOneNow(sanitized.id, sanitized);+ // No local counterpart to lose — nothing to journal, but seed the base+ // hash so a FUTURE scalar divergence on this collection is detected.+ await setSyncBaseHash('mediaCollection', sanitized.id, contentHashForRecord('mediaCollection', sanitized));return true;}const mergedItems = mergeCollectionItems(local.items, sanitized.items);@@ -948,6 +954,19 @@ export async function mergeMediaCollectionsFromSync(remoteCollections) {const localTs = local.updatedAt || '';const remoteTs = sanitized.updatedAt || '';const remoteWins = compareNewerWins(remoteTs, localTs);+ if (remoteWins) {+ // Remote's scalars are about to overwrite local's. Non-blocking conflict+ // journal: archive the about-to-be-lost local version when BOTH sides+ // diverged from the last synced base — but only over the SCALAR SUBSET+ // (contentHashForRecord narrows mediaCollection to its overwritable+ // scalars, so an item-only divergence — items are union-merged, never+ // lost — does NOT false-positive here). Always advances the base hash+ // (clean or conflict) so the next snapshot cycle doesn't re-journal the+ // same divergence. Never throws into the merge. Skipped when local wins:+ // local scalars are KEPT, so there's nothing to lose (and the base stays+ // put — it advances only on an accepted overwrite, mirroring universe).+ await maybeJournalBeforeOverwrite({ kind: 'mediaCollection', id: sanitized.id, local, remote: sanitized, source });+ }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@@ -975,6 +994,9 @@ export async function mergeMediaCollectionsFromSync(remoteCollections) {});if (didChange) changed++;}+ // Persist the batched conflict-journal base-hash updates accumulated above in+ // one write (seeds on insert + advances on accepted overwrite).+ await flushBaseHashes();if (changed === 0) return { applied: false, count: 0 };return { applied: true, count: changed };}diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.jsindex fda9386df6..c1a719d5b3 100644--- a/server/services/mediaCollections.test.js+++ b/server/services/mediaCollections.test.js@@ -30,13 +30,24 @@ vi.mock('crypto', async () => {});const svc = await import('./mediaCollections.js');+const cj = await import('../lib/conflictJournal.js');// Wipe + recreate the collections dir before every test so each starts clean.// The empty dir means collectionStore's readdir is the source of truth and its// process-local knownIds fallback never leaks ids across tests.+//+// Also wipe the conflict-journal + base-hash side store and reset the+// conflictJournal in-memory base-hash cache: mergeMediaCollectionsFromSync now+// seeds/advances per-collection base hashes, and that Map is module-level — so+// without a reset a base hash seeded by an earlier test's insert would bleed+// into a later test that reuses the same collection id and spuriously trip the+// 3-way divergence detector (base==null is the correct first-merge state).function resetStore() {rmSync(COLLECTIONS_DIR, { recursive: true, force: true });+ rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });+ rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });mkdirSync(COLLECTIONS_DIR, { recursive: true });+ cj.__resetBaseHashCacheForTests();uuidCounter = 0;}@@ -1426,6 +1437,71 @@ describe('mergeMediaCollectionsFromSync', () => {});});+describe('mergeMediaCollectionsFromSync — conflict journal', () => {+ const baseColl = (over = {}) => ({+ id: 'c1', name: 'Bucket', description: 'd', coverKey: null,+ universeId: null, seriesId: null,+ items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-01T00:00:00Z' }],+ createdAt: '2026-05-01T00:00:00Z', updatedAt: '2026-05-01T00:00:00Z', ...over,+ });+ const journalEntries = () => cj.conflictJournalStore().loadAll();++ it('seeds a base hash on first insert (new record) so a future divergence is detectable', async () => {+ await svc.mergeMediaCollectionsFromSync([baseColl()]);+ expect(await cj.getSyncBaseHash('mediaCollection', 'c1'))+ .toBe(cj.contentHashForRecord('mediaCollection', baseColl()));+ expect(await journalEntries()).toHaveLength(0);+ });++ it('item-only divergence does NOT journal (items union-merged, never lost)', async () => {+ // Establish a shared base, then both sides add different items only.+ await svc.mergeMediaCollectionsFromSync([baseColl()]);+ // Local adds an item directly on disk; remote arrives with a different item.+ await seedState({ collections: [baseColl({+ items: [+ { kind: 'image', ref: 'a.png', addedAt: '2026-05-01T00:00:00Z' },+ { kind: 'image', ref: 'local.png', addedAt: '2026-05-02T00:00:00Z' },+ ],+ updatedAt: '2026-05-02T00:00:00Z',+ })] });+ const before = (await journalEntries()).length;+ await svc.mergeMediaCollectionsFromSync([baseColl({+ items: [+ { kind: 'image', ref: 'a.png', addedAt: '2026-05-01T00:00:00Z' },+ { kind: 'image', ref: 'remote.png', addedAt: '2026-05-03T00:00:00Z' },+ ],+ updatedAt: '2026-05-03T00:00:00Z',+ })]);+ expect((await journalEntries()).length).toBe(before);+ // ...and both items survived the union (the whole reason scalars-only is safe).+ const [merged] = await svc.listCollections();+ expect(merged.items.map((i) => i.ref).sort()).toEqual(['a.png', 'local.png', 'remote.png']);+ });++ it('journals when a newer remote overwrites a diverged local scalar (name)', async () => {+ await svc.mergeMediaCollectionsFromSync([baseColl()]); // seed base+ await seedState({ collections: [baseColl({ name: 'LOCAL rename', updatedAt: '2026-05-02T00:00:00Z' })] });+ await svc.mergeMediaCollectionsFromSync([baseColl({ name: 'REMOTE rename', updatedAt: '2026-05-03T00:00:00Z' })]);+ const entries = await journalEntries();+ expect(entries).toHaveLength(1);+ expect(entries[0]).toMatchObject({ recordKind: 'mediaCollection', recordId: 'c1', status: 'pending' });+ expect(entries[0].localSnapshot.name).toBe('LOCAL rename');+ // Remote won LWW; local archived.+ const [merged] = await svc.listCollections();+ expect(merged.name).toBe('REMOTE rename');+ });++ it('does NOT journal when local wins LWW (its scalars are kept, nothing lost)', async () => {+ await svc.mergeMediaCollectionsFromSync([baseColl()]); // seed base+ await seedState({ collections: [baseColl({ name: 'LOCAL rename', updatedAt: '2026-05-05T00:00:00Z' })] });+ // Older remote — local wins; no overwrite, no journal.+ await svc.mergeMediaCollectionsFromSync([baseColl({ name: 'REMOTE rename', updatedAt: '2026-05-03T00:00:00Z' })]);+ expect(await journalEntries()).toHaveLength(0);+ const [merged] = await svc.listCollections();+ expect(merged.name).toBe('LOCAL rename');+ });+});+describe('createCollection — event emission', () => {it('emits a mediaCollection updated event with the created record id', async () => {const { recordEvents } = await import('./sharing/recordEvents.js');diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 30b98d8c85..393ada2c4d 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -1006,7 +1006,12 @@ export async function pushRecordToPeer(sub, options = {}) {// like a divergence. Best-effort; never block the push result on it — the// stamp + filesystem flush run fire-and-forget so a slow disk can't delay the// push loop. The `.catch()` keeps the rejection from escaping as unhandled.- if ((sub.recordKind === 'universe' || sub.recordKind === 'series') && payload.record) {+ if (PEER_SUBSCRIBABLE_KINDS.includes(sub.recordKind) && payload.record) {+ // For mediaCollection, contentHashForRecord hashes only the scalar subset+ // (items are union-merged on the receiver, so the post-push collections are+ // NOT byte-identical — but their scalars converge, which is what the base+ // hash tracks). For universe/series it's the full wire record. Same call+ // either way; the narrowing lives in contentHashForRecord.setSyncBaseHash(sub.recordKind, sub.recordId, contentHashForRecord(sub.recordKind, payload.record)).then(() => flushBaseHashes()).catch((err) => console.log(`⚠️ peerSync: base-hash stamp after push failed: ${err?.message || err}`));