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-issues]): journal child-issue sync conflicts
[._.]/ Adam Eivyedf94f2f753b
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex 053cceef8a..8678e25ca6 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -69,20 +69,41 @@ export const conflictJournalStore = () => store();// 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']);+// Fields dropped from the conflict-detection hash, per kind. These are+// server-managed values that mutate WITHOUT a user edit (and without bumping+// `updatedAt`), so leaving them in the hash would read as a false divergence+// and journal a spurious conflict. Issue `number` is renumber-managed:+// `applyVolumeOrderedNumbers` shifts it in place when a *sibling* issue is+// added/removed, so a local sibling-delete would otherwise make this issue's+// `localHash !== base` even though no restorable content changed (the resulting+// conflict card would have an empty diffSummary, since `number` isn't+// restorable). Excluding it keeps the hash aligned with the restorable-field+// set the UI actually shows. (mediaCollection narrows via its own scalar+// projection below; universe/series exclude nothing, so their already-seeded+// base hashes stay valid across upgrade.)+const HASH_EXCLUDED_FIELDS = Object.freeze({ issue: ['number'] });+/*** 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. 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".+ * MEDIA_COLLECTION_SCALAR_FIELDS); for issue the renumber-managed `number` is+ * dropped (see HASH_EXCLUDED_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;- const hashInput = kind === 'mediaCollection' ? projectCollectionScalars(wire) : wire;+ let hashInput = wire;+ if (kind === 'mediaCollection') {+ hashInput = projectCollectionScalars(wire);+ } else if (HASH_EXCLUDED_FIELDS[kind]) {+ const excluded = HASH_EXCLUDED_FIELDS[kind];+ hashInput = Object.fromEntries(Object.entries(wire).filter(([k]) => !excluded.includes(k)));+ }return createHash('sha256').update(canonicalStringify(hashInput)).digest('hex');}@@ -192,6 +213,12 @@ export const RESTORABLE_FIELDS = Object.freeze({// 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'],+ // Issue: the user-authored content the merge can restore. `stages` carries+ // the bulk of the work (prose, comic pages, render metadata). Server-owned /+ // structural fields are excluded deliberately — `number` is renumber-managed,+ // `seriesId` is the immutable parent link, `origin` is share provenance —+ // and `mergeIssuePatch` accepts every field listed here.+ issue: ['title', 'status', 'seasonId', 'arcPosition', 'arcRole', 'lengthProfile', 'pageTarget', 'minutesTarget', 'stages'],});// 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 f7b8b7a9ae..58998b2ae0 100644--- a/server/lib/conflictJournal.test.js+++ b/server/lib/conflictJournal.test.js@@ -17,6 +17,11 @@ afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));// adds the soft-delete pair). Distinct content → distinct content hashes.const uni = (over = {}) => ({ id: 'u-1', name: 'X', starterPrompt: 'base', updatedAt: '2026-05-01T00:00:00Z', ...over });+// Minimal issue-shaped record — sanitizeRecordForWire('issue', …) passes the+// content through verbatim (it does NOT run sanitizeIssue), so `stages` and+// `number` round-trip as-is for the content hash.+const iss = (over = {}) => ({ id: 'iss-1', seriesId: 'ser-1', title: 'T', number: 1, status: 'draft', stages: {}, updatedAt: '2026-05-01T00:00:00Z', ...over });+const pendingEntries = async () => cj.conflictJournalStore().loadAll();describe('conflictJournal', () => {@@ -95,6 +100,27 @@ describe('conflictJournal', () => {expect(fields).not.toContain('id');});+ it('journals an issue 3-way divergence; diffSummary covers title + stages, never number/seriesId', async () => {+ const base = iss();+ await cj.setSyncBaseHash('issue', 'iss-1', cj.contentHashForRecord('issue', base));+ // Both sides diverge on the title AND the prose stage content (and a+ // server-owned `number` that must NOT surface in the diff).+ const local = iss({ title: 'LOCAL', number: 9, stages: { prose: { status: 'ready', output: 'mine' } }, updatedAt: '2026-05-02T00:00:00Z' });+ const remote = iss({ title: 'REMOTE', number: 4, stages: { prose: { status: 'ready', output: 'theirs' } }, updatedAt: '2026-05-03T00:00:00Z' });+ await cj.maybeJournalBeforeOverwrite({ kind: 'issue', id: 'iss-1', local, remote, source: { via: 'share-bucket', bucketId: 'b-1' } });+ const entries = await pendingEntries();+ expect(entries).toHaveLength(1);+ expect(entries[0]).toMatchObject({ recordKind: 'issue', recordId: 'iss-1', status: 'pending' });+ expect(entries[0].localSnapshot.title).toBe('LOCAL');+ const fields = entries[0].diffSummary.map((d) => d.field);+ expect(fields).toContain('title');+ expect(fields).toContain('stages');+ expect(fields).not.toContain('number');+ expect(fields).not.toContain('seriesId');+ // Base advanced to remote → an idempotent replay must NOT re-journal.+ expect(await cj.getSyncBaseHash('issue', 'iss-1')).toBe(cj.contentHashForRecord('issue', remote));+ });+it('does NOT journal when the local side is a tombstone (no content to lose)', async () => {const base = uni({ starterPrompt: 'base' });await cj.setSyncBaseHash('universe', 'u-1', cj.contentHashForRecord('universe', base));diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.jsindex 531ce569d6..ce459c306c 100644--- a/server/services/conflictJournalResolver.js+++ b/server/services/conflictJournalResolver.js@@ -30,6 +30,7 @@ import { conflictJournalStore, RESTORABLE_FIELDS } from '../lib/conflictJournal.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';+import { updateIssue, ERR_NOT_FOUND as ISSUE_NOT_FOUND } from './pipeline/issues.js';export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';export const ERR_VALIDATION = 'CONFLICT_JOURNAL_VALIDATION';@@ -68,7 +69,8 @@ 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 || err?.code === COLLECTION_NOT_FOUND) {+ if (err?.code === UNIVERSE_NOT_FOUND || err?.code === SERIES_NOT_FOUND+ || err?.code === COLLECTION_NOT_FOUND || err?.code === ISSUE_NOT_FOUND) {throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);}throw err;@@ -91,6 +93,12 @@ async function applyToRecord(kind, recordId, patch) {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 if (kind === 'issue') {+ // updateIssue deep-merges `stages` per-stage (mergeIssuePatch), so a+ // restore re-applies the archived stage content without clobbering a+ // sibling stage the live record gained since detection — same additive+ // overlay semantics as universe categories (see the NOTE above).+ await updateIssue(recordId, patch).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 f249659935..213d229dd2 100644--- a/server/services/conflictJournalResolver.test.js+++ b/server/services/conflictJournalResolver.test.js@@ -20,15 +20,16 @@ vi.mock('crypto', async () => {const resolver = await import('./conflictJournalResolver.js');const universeSvc = await import('./universeBuilder.js');const collSvc = await import('./mediaCollections.js');+const issueSvc = await import('./pipeline/issues.js');const cj = await import('../lib/conflictJournal.js');afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));// Seed a pending journal entry whose localSnapshot holds the "lost" values.-const seedEntry = async (recordId, localSnapshot) => {+const seedEntry = async (recordId, localSnapshot, recordKind = 'universe') => {const id = `entry-${++uuidCounter}`;await cj.conflictJournalStore().saveOne(id, {- id, recordKind: 'universe', recordId, detectedAt: '2026-05-01T00:00:00Z',+ id, recordKind, 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,@@ -67,6 +68,43 @@ describe('conflictJournalResolver', () => {expect(fresh.starterPrompt).toBe('REMOTE prompt'); // untouched});+ it('restore-all re-applies an archived ISSUE snapshot (title + prose stage)', async () => {+ const issue = await issueSvc.createIssue({ seriesId: 'ser-restore', title: 'Remote Title' });+ // Remote LWW-overwrote both the title and the prose output.+ await issueSvc.updateIssue(issue.id, { title: 'Remote Title', stages: { prose: { status: 'ready', output: 'REMOTE prose' } } });+ const entryId = await seedEntry(+ issue.id,+ { id: issue.id, seriesId: 'ser-restore', title: 'MY Title', stages: { prose: { status: 'ready', output: 'MY prose' } } },+ 'issue',+ );++ const resolved = await resolver.resolveConflict(entryId, { action: 'restore-all' });+ expect(resolved.status).toBe('resolved');++ const fresh = await issueSvc.getIssue(issue.id);+ expect(fresh.title).toBe('MY Title');+ expect(fresh.stages.prose.output).toBe('MY prose');+ });++ it('issue merge-fields overlays only the chosen field; unsupported kind is rejected', async () => {+ const issue = await issueSvc.createIssue({ seriesId: 'ser-merge', title: 'Keep Title' });+ await issueSvc.updateIssue(issue.id, { stages: { prose: { status: 'ready', output: 'REMOTE prose' } } });+ const entryId = await seedEntry(+ issue.id,+ { id: issue.id, seriesId: 'ser-merge', title: 'IGNORED local title', stages: { prose: { status: 'ready', output: 'MY prose' } } },+ 'issue',+ );+ await resolver.resolveConflict(entryId, { action: 'merge-fields', fields: ['stages'] });+ const fresh = await issueSvc.getIssue(issue.id);+ expect(fresh.stages.prose.output).toBe('MY prose'); // overlaid+ expect(fresh.title).toBe('Keep Title'); // untouched++ // `number` is server-owned — not in RESTORABLE_FIELDS.issue, so it's rejected.+ const e2 = await seedEntry(issue.id, { id: issue.id, number: 99 }, 'issue');+ await expect(resolver.resolveConflict(e2, { action: 'merge-fields', fields: ['number'] }))+ .rejects.toMatchObject({ code: resolver.ERR_VALIDATION });+ });+it('merge-fields rejects fields outside the restorable allowlist', async () => {const u = await universeSvc.createUniverse({ name: 'X' });const entryId = await seedEntry(u.id, { id: u.id, name: 'X' });diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex c0721459a5..797af63aa0 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -36,6 +36,7 @@ import { isStr, trimTo } from '../../lib/storyBible.js';import { sanitizeCoverLike } from '../../lib/renderSlot.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';import { applyVolumeOrderedNumbers, UNSCOPED_ANCHOR } from '../../lib/pipelineIssueOrder.js';+import { maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes } from '../../lib/conflictJournal.js';import * as seriesSvc from './series.js';// TYPE-level (storage layout) schema version stamped on@@ -1091,7 +1092,7 @@ export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPri* valid id format). LWW by `updatedAt`; returns `{ applied, count }` where* `count` is the number of issues actually changed/added.*/-export async function mergeIssuesFromSync(remoteIssues) {+export async function mergeIssuesFromSync(remoteIssues, { source = { via: 'sync', peerId: null } } = {}) {if (!Array.isArray(remoteIssues)) return { applied: false, count: 0 };// Series IDs whose issue set saw at least one delete-transition — drives a// post-write renumber so the receiver's issue numbering catches up with the@@ -1142,6 +1143,11 @@ export async function mergeIssuesFromSync(remoteIssues) {// to compact; firing `emitRecordUpdated('series', …)` for a series// we may not even own would spuriously re-export.localById.set(sanitized.id, sanitized);+ // Seed the conflict-journal base hash so a FUTURE divergence on this+ // issue is detected. Issues are pushed under their parent series'+ // subscription, so peerSync never seeds an `issue`-keyed base hash —+ // this merge path (and the importer) own it.+ await setSyncBaseHash('issue', sanitized.id, contentHashForRecord('issue', sanitized));changed++;} else if (local.ephemeral === true) {// Local-ephemeral issues are immune to inbound merges. See@@ -1151,6 +1157,10 @@ export async function mergeIssuesFromSync(remoteIssues) {const localTs = local.updatedAt || '';const remoteTs = sanitized.updatedAt || '';if (remoteTs > localTs) {+ // Non-blocking conflict journal — archive the losing local issue on+ // a true 3-way divergence; always advances the base hash. Never+ // throws into the merge (convergence wins).+ await maybeJournalBeforeOverwrite({ kind: 'issue', id: sanitized.id, local, remote: sanitized, source });localById.set(sanitized.id, sanitized);// Renumber on EITHER direction of the transition: a delete leaves// a gap, a resurrection (deleted→live) reintroduces a previously-@@ -1183,6 +1193,9 @@ export async function mergeIssuesFromSync(remoteIssues) {for (const seriesId of seriesNeedingRenumber) {emitRecordUpdated('series', seriesId);}+ // Persist the batched conflict-journal base-hash updates (seeds on insert,+ // advances on overwrite) accumulated in the loop above.+ await flushBaseHashes();return { applied: true, count: changed };});}diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex beb25ba0ae..a2a53feb7e 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -34,6 +34,7 @@ vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());const svc = await import('./issues.js');const seriesSvc = await import('./series.js');const seasonsSvc = await import('./seasons.js');+const cj = await import('../../lib/conflictJournal.js');const { recordEvents } = await import('../sharing/recordEvents.js');describe('pipeline issues service', () => {@@ -891,6 +892,51 @@ describe('pipeline issues service', () => {expect(live.map((i) => i.title)).toEqual(['A', 'C']);expect(live.map((i) => i.number)).toEqual([1, 2]);});++ describe('conflict journaling', () => {+ beforeEach(() => cj.__resetBaseHashCacheForTests());++ it('seeds a base hash for an issue inserted via sync (so a future divergence is detectable)', async () => {+ const t0 = '2026-05-01T00:00:00Z';+ const rec = { id: 'iss-seed-1', seriesId: 'ser-seed', title: 'Seeded', number: 1, status: 'draft', stages: {}, createdAt: t0, updatedAt: t0 };+ const r = await svc.mergeIssuesFromSync([rec]);+ expect(r).toEqual({ applied: true, count: 1 });+ const stored = await svc.getIssue('iss-seed-1');+ expect(await cj.getSyncBaseHash('issue', 'iss-seed-1')).toBe(cj.contentHashForRecord('issue', stored));+ // No overwrite happened → nothing journaled.+ expect(await cj.conflictJournalStore().loadAll()).toHaveLength(0);+ });++ it('archives the losing local issue on a true 3-way divergence before the LWW overwrite', async () => {+ const t0 = '2026-05-01T00:00:00Z';+ // Insert a base record from sync — seeds base = H(base).+ const base = { id: 'iss-conf-1', seriesId: 'ser-conf', title: 'Base', number: 1, status: 'draft', stages: {}, createdAt: t0, updatedAt: t0 };+ await svc.mergeIssuesFromSync([base]);+ // Local diverges from base (title edit bumps updatedAt to ~now).+ await svc.updateIssue('iss-conf-1', { title: 'LOCAL edit' });+ // Remote also diverges AND is newer → overwrite wins; the divergence+ // is a true 3-way conflict → the local edit is archived.+ const remoteTs = new Date(Date.now() + 60_000).toISOString();+ const r = await svc.mergeIssuesFromSync([{ ...base, title: 'REMOTE edit', updatedAt: remoteTs }], { source: { via: 'peer-push', peerId: 'peer-A' } });+ expect(r.applied).toBe(true);+ expect((await svc.getIssue('iss-conf-1')).title).toBe('REMOTE edit');+ const entries = await cj.conflictJournalStore().loadAll();+ expect(entries).toHaveLength(1);+ expect(entries[0]).toMatchObject({ recordKind: 'issue', recordId: 'iss-conf-1', status: 'pending' });+ expect(entries[0].localSnapshot.title).toBe('LOCAL edit');+ expect(entries[0].source).toMatchObject({ via: 'peer-push', peerId: 'peer-A' });+ });++ it('does NOT journal a clean sequential sync update (local matches the base)', async () => {+ const t0 = '2026-05-01T00:00:00Z';+ const base = { id: 'iss-clean-1', seriesId: 'ser-clean', title: 'Base', number: 1, status: 'draft', stages: {}, createdAt: t0, updatedAt: t0 };+ await svc.mergeIssuesFromSync([base]);+ // Local untouched since base; remote is just a newer edit → clean LWW.+ const remoteTs = new Date(Date.now() + 60_000).toISOString();+ await svc.mergeIssuesFromSync([{ ...base, title: 'Remote-only edit', updatedAt: remoteTs }]);+ expect(await cj.conflictJournalStore().loadAll()).toHaveLength(0);+ });+ });});describe('pruneTombstonedIssues', () => {diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex 450a01da8b..f03bc25d65 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -43,6 +43,12 @@ import { isStr } from '../../lib/storyBible.js';import { isPlainObject } from '../../lib/objects.js';import { maybeJournalBeforeOverwrite, flushBaseHashes, setSyncBaseHash, contentHashForRecord } from '../../lib/conflictJournal.js';+// Record kinds that participate in the non-blocking conflict journal. Universe,+// series, AND issue all seed a base hash on first import and archive a losing+// local version before an LWW overwrite. (Media collections are journaled+// separately via their own merge path; see mediaCollections.js.)+const JOURNALED_KINDS = new Set(['universe', 'series', 'issue']);+function isSelfAuthored(senderInstanceId, localInstanceId) {return !!localInstanceId&& !!senderInstanceId@@ -493,7 +499,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =// seed on their insert branch too; without this a bucket-imported// record has base==null and the first conflict would be missed). Hash// the STORED record so the base matches a future `local` hash exactly.- if (kind === 'universe' || kind === 'series') {+ if (JOURNALED_KINDS.has(kind)) {const stored = await getFn(record.id).catch(() => null);if (stored) await setSyncBaseHash(kind, record.id, contentHashForRecord(kind, stored));}@@ -511,11 +517,11 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =if (kind === 'series' && !record.universeId && existing.universeId) {record = { ...record, universeId: existing.universeId };}- // Non-blocking conflict journal for the two synced top-level kinds — a+ // Non-blocking conflict journal for every synced record kind — a// share-bucket import that LWW-overwrites a locally-diverged record- // archives the losing local version first. Issues ride LWW silently- // (child-issue conflict journaling is a v1 follow-up).- if (kind === 'universe' || kind === 'series') {+ // archives the losing local version first. Issues are included now+ // (they previously rode LWW silently).+ if (JOURNALED_KINDS.has(kind)) {await maybeJournalBeforeOverwrite({kind, id: record.id, local: existing, remote: record,source: { via: 'share-bucket', bucketId: bucket.id, peerId: manifest.senderInstanceId ?? null },