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([conflict-source-attribution]): attribute sync conflicts to their origin peer

[._.]/ Adam Eivy7c4824e4cb4b
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index ea9d059007..3d3a2712b8 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -402,7 +402,7 @@ async function getUniverseSnapshot({ exclude } = {}) {
return { data, checksum: computeChecksum(data) };
}
-async function applyUniverseRemote(remoteData) {
+async function applyUniverseRemote(remoteData, source) {
if (!remoteData) return { applied: false, count: 0 };
// Routes through `mergeUniversesFromSync` so the read-modify-write runs
// INSIDE `queueUniverseWrite` (serialized against every other writer:
@@ -410,7 +410,7 @@ async function applyUniverseRemote(remoteData) {
// remote record passes through `sanitizeTemplate` for schema-version
// backfill — older peers landing pre-v4 records get them migrated on the
// way in instead of polluting disk with un-backfilled state.
- const result = await mergeUniversesFromSync(remoteData.universes || []);
+ const result = await mergeUniversesFromSync(remoteData.universes || [], { source });
if (result.applied) {
console.log(`🔄 Universe sync: merged ${result.count} universe(s)`);
}
@@ -446,13 +446,13 @@ async function getPipelineSnapshot({ exclude } = {}) {
return { data, checksum: computeChecksum(data) };
}
-async function applyPipelineRemote(remoteData) {
+async function applyPipelineRemote(remoteData, source) {
if (!remoteData) return { applied: false, count: 0 };
// Routes through the service merge entry points so each incoming record
// passes through the same sanitizer and LWW contract as local writes.
const [seriesResult, issuesResult] = await Promise.all([
- mergeSeriesFromSync(remoteData.series || []),
- mergeIssuesFromSync(remoteData.issues || []),
+ mergeSeriesFromSync(remoteData.series || [], { source }),
+ mergeIssuesFromSync(remoteData.issues || [], { source }),
]);
const seriesChanged = seriesResult.count;
@@ -540,7 +540,7 @@ async function getMediaCollectionsSnapshot({ exclude } = {}) {
return { data, checksum: computeChecksum(data) };
}
-async function applyMediaCollectionsRemote(remoteData) {
+async function applyMediaCollectionsRemote(remoteData, source) {
if (!remoteData) return { applied: false, count: 0 };
// Symmetric receiver-side guard. The sender filters collections linked
// to local-ephemeral parents in getMediaCollectionsSnapshot, but a
@@ -572,7 +572,7 @@ async function applyMediaCollectionsRemote(remoteData) {
// 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(filtered);
+ const result = await mergeMediaCollectionsFromSync(filtered, { source });
if (result.applied) {
console.log(`🔄 MediaCollections sync: merged ${result.count} collection(s)`);
}
@@ -942,6 +942,12 @@ export async function getSnapshot(category, { forPeerId } = {}) {
export async function applyRemote(category, remoteData, options = {}) {
const cat = CATEGORIES[category];
if (!cat) return { applied: false, count: 0 };
+ // Attribute any conflict the category's merge journals to the snapshot
+ // transport + the peer it came from. `options.peerId` is the source peer's
+ // instanceId (the snapshot orchestrator passes it; the manual REST apply
+ // route has none → null). Category appliers that don't journal ignore the
+ // extra arg.
+ const source = { via: 'snapshot', peerId: typeof options.peerId === 'string' && options.peerId ? options.peerId : null };
const portosMeta = isPlainObject(options.portosMeta) ? options.portosMeta : null;
const senderSchemaVersions = isPlainObject(portosMeta?.schemaVersions) ? portosMeta.schemaVersions : {};
const senderPortosVersion = typeof portosMeta?.portosVersion === 'string' ? portosMeta.portosVersion : null;
@@ -966,5 +972,5 @@ export async function applyRemote(category, remoteData, options = {}) {
},
};
}
- return cat.applyRemote(remoteData);
+ return cat.applyRemote(remoteData, source);
}
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index d78acbfeab..1a27ab61e6 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -22,6 +22,7 @@ vi.mock('../lib/fileUtils.js', async () => {
afterAll(cleanup);
const dataSync = await import('./dataSync.js');
+const conflictJournal = await import('../lib/conflictJournal.js');
const { PORTOS_SCHEMA_VERSIONS } = await import('../lib/schemaVersions.js');
const SERIES_DIR = join(tempRoot, 'pipeline-series');
@@ -255,6 +256,61 @@ describe('dataSync — universe category', () => {
});
});
+describe('dataSync — conflict-journal source attribution (snapshot path)', () => {
+ // The snapshot apply path (syncOrchestrator → dataSync.applyRemote → the
+ // service merge fns) must stamp journaled conflicts with `via: 'snapshot'`
+ // and the source peer's id. Before [conflict-source-attribution] the param
+ // was dropped, so the Conflicts tab showed `via: sync (peerId: null)` and
+ // couldn't say which peer collided.
+ const journalDir = () => join(tempRoot, 'conflict-journal');
+ const readJournalEntries = () => {
+ if (!existsSync(journalDir())) return [];
+ return readdirSync(journalDir(), { withFileTypes: true })
+ .filter((e) => e.isDirectory())
+ .map((e) => readJSON(join(journalDir(), e.name, 'index.json')));
+ };
+ // Seed local + a divergent base so the incoming remote is a true 3-way
+ // conflict (local ≠ base, remote ≠ base, remote ≠ local) and the merge
+ // journals before overwriting. Remote `updatedAt` is newer so it wins LWW.
+ async function seedConflict(id) {
+ writeUniverseState({
+ universes: [{ id, name: 'Local Edit', updatedAt: '2026-05-17T10:00:00Z' }],
+ });
+ await conflictJournal.setSyncBaseHash('universe', id, `base-hash-${id}-distinct`);
+ await conflictJournal.flushBaseHashes();
+ }
+
+ beforeEach(() => {
+ // The base-hash cache is module-level; reset it so the wiped temp root
+ // doesn't bleed seeds across tests.
+ conflictJournal.__resetBaseHashCacheForTests();
+ });
+
+ it('records via:snapshot + the source peerId when the orchestrator passes one', async () => {
+ await seedConflict('u-attr');
+ const result = await dataSync.applyRemote('universe', {
+ universes: [{ id: 'u-attr', name: 'Remote Edit', updatedAt: '2026-05-18T10:00:00Z' }],
+ }, { peerId: 'peer-zeta' });
+ expect(result.applied).toBe(true);
+
+ const entries = readJournalEntries();
+ expect(entries).toHaveLength(1);
+ expect(entries[0].recordKind).toBe('universe');
+ expect(entries[0].recordId).toBe('u-attr');
+ expect(entries[0].source).toEqual({ via: 'snapshot', peerId: 'peer-zeta' });
+ });
+
+ it('defaults peerId to null (not undefined) when the caller omits it — manual REST apply', async () => {
+ await seedConflict('u-anon');
+ await dataSync.applyRemote('universe', {
+ universes: [{ id: 'u-anon', name: 'Remote Edit', updatedAt: '2026-05-18T10:00:00Z' }],
+ });
+ const entries = readJournalEntries();
+ expect(entries).toHaveLength(1);
+ expect(entries[0].source).toEqual({ via: 'snapshot', peerId: null });
+ });
+});
+
describe('dataSync — pipeline category', () => {
it('snapshot bundles series + issues from their respective files', async () => {
writeSeriesState([{ id: 'ser-1', name: 'A', updatedAt: '2026-05-17T10:00:00Z' }]);
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 8d14debb16..025e77bfc2 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -1502,11 +1502,15 @@ export async function applyIncomingPush(payload) {
// Merge into local state via the existing LWW path. The merge functions
// honor `deleted: true` + bump `updatedAt`, so this is the single
- // tombstone-aware reconciliation point.
+ // tombstone-aware reconciliation point. Attribute any conflict journaled by
+ // the merge to THIS push's origin peer so the Conflicts tab can show which
+ // peer collided (without `source`, the merge fns fall back to
+ // `{ via:'sync', peerId:null }` and the attribution is lost).
+ const source = { via: 'peer-push', peerId: sourceInstanceId };
if (kind === 'universe') {
- await mergeUniversesFromSync([record]);
+ await mergeUniversesFromSync([record], { source });
} else if (kind === 'series') {
- await mergeSeriesFromSync([record]);
+ await mergeSeriesFromSync([record], { source });
// Bundled issues: skip the entire batch if the LOCAL series is
// ephemeral. mergeSeriesFromSync already refused the parent record on
// its own, but child issue merges are a separate code path —
@@ -1514,10 +1518,10 @@ export async function applyIncomingPush(payload) {
// the parent is marked ephemeral, so without this gate a stale reverse
// subscription could overwrite the private fork's issue stages.
if (!localEphemeral && Array.isArray(issues) && issues.length > 0) {
- await mergeIssuesFromSync(issues);
+ await mergeIssuesFromSync(issues, { source });
}
} else if (kind === 'mediaCollection') {
- await mergeMediaCollectionsFromSync([record]);
+ await mergeMediaCollectionsFromSync([record], { source });
}
// Apply the bundled collection (if any) — same LWW + union-of-items
@@ -1540,7 +1544,7 @@ export async function applyIncomingPush(payload) {
// explicitly opted out of sync for this record, so peer-pushed
// collection mutations must not land.
if (!localEphemeral && record.deleted !== true && isPlainObject(linkedCollection)) {
- await mergeMediaCollectionsFromSync([linkedCollection]).catch((err) => {
+ await mergeMediaCollectionsFromSync([linkedCollection], { source }).catch((err) => {
console.log(`⚠️ peerSync: linkedCollection merge failed: ${err.message}`);
});
}
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index ed8b4c7d12..49dfe81690 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -1776,9 +1776,10 @@ describe('peerSync', () => {
assetManifest: [],
sourceInstanceId: 'peer-a',
});
- expect(mergeUniversesFromSync).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'u1' }),
- ]);
+ expect(mergeUniversesFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'u1' })],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
});
it('routes a bundled linkedCollection through mergeMediaCollectionsFromSync', async () => {
@@ -1794,7 +1795,10 @@ describe('peerSync', () => {
assetManifest: [],
sourceInstanceId: 'peer-a',
});
- expect(mergeMediaCollectionsFromSync).toHaveBeenCalledWith([linkedCollection]);
+ expect(mergeMediaCollectionsFromSync).toHaveBeenCalledWith(
+ [linkedCollection],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
});
it('skips mergeMediaCollectionsFromSync when no linkedCollection is bundled', async () => {
@@ -1848,10 +1852,14 @@ describe('peerSync', () => {
assetManifest: [],
sourceInstanceId: 'peer-a',
});
- expect(mergeSeriesFromSync).toHaveBeenCalled();
- expect(mergeIssuesFromSync).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'i1' }),
- ]);
+ expect(mergeSeriesFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 's1' })],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
+ expect(mergeIssuesFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'i1' })],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
});
it('reports missing assets in the response', async () => {
@@ -2213,9 +2221,10 @@ describe('peerSync', () => {
sourceInstanceId: 'peer-a',
portosMeta: { portosVersion: '2.7.0', schemaVersions: { universes: 5 } },
});
- expect(mergeUniversesFromSync).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'u1' }),
- ]);
+ expect(mergeUniversesFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'u1' })],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
});
it('passes through when sender is BEHIND local (sanitizer handles the backfill)', async () => {
@@ -2228,9 +2237,10 @@ describe('peerSync', () => {
sourceInstanceId: 'peer-a',
portosMeta: { portosVersion: '2.6.0', schemaVersions: { universes: 4 } },
});
- expect(mergeUniversesFromSync).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'u1' }),
- ]);
+ expect(mergeUniversesFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'u1' })],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
});
it('passes through legacy peers that send NO portosMeta at all', async () => {
@@ -2260,9 +2270,10 @@ describe('peerSync', () => {
sourceInstanceId: 'peer-a',
portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, mediaCollections: 2 } },
});
- expect(mergeUniversesFromSync).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'u1' }),
- ]);
+ expect(mergeUniversesFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'u1' })],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
});
it('does NOT reject a series push with NO bundled issues when the sender is ahead on pipelineIssues only', async () => {
@@ -2324,9 +2335,10 @@ describe('peerSync', () => {
sourceInstanceId: 'peer-a',
portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 6 } },
});
- expect(mergeUniversesFromSync).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'u1', deleted: true }),
- ]);
+ expect(mergeUniversesFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'u1', deleted: true })],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
});
it('DOES reject a deleted-series push that bundles a LIVE issue when the sender is ahead on pipelineIssues', async () => {
@@ -2361,9 +2373,10 @@ describe('peerSync', () => {
portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 9, pipelineIssues: 9 } },
});
expect(mergeSeriesFromSync).toHaveBeenCalled();
- expect(mergeIssuesFromSync).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'i1', deleted: true }),
- ]);
+ expect(mergeIssuesFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'i1', deleted: true })],
+ { source: { via: 'peer-push', peerId: 'peer-a' } },
+ );
});
});
@@ -2693,9 +2706,10 @@ describe('peerSync', () => {
sourceInstanceId: 'peer-abc',
});
- expect(mergeMediaCollectionsFromSync).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'col-x', name: 'Synced' }),
- ]);
+ expect(mergeMediaCollectionsFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'col-x', name: 'Synced' })],
+ { source: { via: 'peer-push', peerId: 'peer-abc' } },
+ );
// Confirm the record landed on disk via the real listCollections.
const all = await real.listCollections();
@@ -2711,9 +2725,10 @@ describe('peerSync', () => {
assetManifest: [],
sourceInstanceId: 'peer-abc',
});
- expect(mergeMediaCollectionsFromSync).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'col-y' }),
- ]);
+ expect(mergeMediaCollectionsFromSync).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'col-y' })],
+ { source: { via: 'peer-push', peerId: 'peer-abc' } },
+ );
});
it('auto-creates a reverse subscription back to the sender for a syncable local collection', async () => {
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index 099f22a50e..149372e550 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -410,6 +410,9 @@ async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums,
// can't sync universes" and the user knows what to do.
const result = await dataSync.applyRemote(category, snapshot.data, {
portosMeta: snapshot.portosMeta,
+ // Attribute any journaled conflict to the peer this snapshot came from so
+ // the Conflicts tab shows `via: snapshot (<peerId>)` instead of peerId:null.
+ peerId,
});
if (result.blockedBySchema) {
await recordPeerSchemaGap(peerId, category, result.blockedBySchema)