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-journal-deep-diff]): per-sub-entry diffing in the Conflicts tab

[._.]/ Adam Eivy3d8523706bd8
diff --git a/client/src/components/sharing/ConflictsTab.jsx b/client/src/components/sharing/ConflictsTab.jsx
index 347c60253c..5610ba6b2d 100644
--- a/client/src/components/sharing/ConflictsTab.jsx
+++ b/client/src/components/sharing/ConflictsTab.jsx
@@ -118,8 +118,24 @@ function ConflictEntry({ entry, onResolved }) {
<input type="checkbox" checked={selectedFields.has(d.field)} onChange={() => toggleField(d.field)} />
{d.field} <span className="text-[10px] text-gray-500">({d.changed})</span>
</label>
- {/* old = your archived local value, new = the version that synced in */}
- <InlineDiff oldText={asText(d.localValue)} newText={asText(d.remoteValue)} />
+ {/* old = your archived local value, new = the version that synced in.
+ A deep-diffable field (object map / array of canon entries) carries
+ `parts` — one focused diff per changed sub-entry, labelled by its
+ key/name — instead of one giant JSON blob. */}
+ {Array.isArray(d.parts) ? (
+ <div className="space-y-2">
+ {d.parts.map((p) => (
+ <div key={p.path} className="pl-2 border-l-2 border-port-border">
+ <div className="font-mono text-[10px] text-gray-400 mb-1">
+ {p.path} <span className="text-gray-600">({p.changed})</span>
+ </div>
+ <InlineDiff oldText={asText(p.localValue)} newText={asText(p.remoteValue)} />
+ </div>
+ ))}
+ </div>
+ ) : (
+ <InlineDiff oldText={asText(d.localValue)} newText={asText(d.remoteValue)} />
+ )}
</div>
))}
<div className="flex justify-end">
diff --git a/client/src/components/sharing/ConflictsTab.test.jsx b/client/src/components/sharing/ConflictsTab.test.jsx
index 113042940c..53ac04cc4a 100644
--- a/client/src/components/sharing/ConflictsTab.test.jsx
+++ b/client/src/components/sharing/ConflictsTab.test.jsx
@@ -69,4 +69,37 @@ describe('ConflictsTab', () => {
await user.click(screen.getByRole('button', { name: /Discard/ }));
await waitFor(() => expect(api.resolveConflict).toHaveBeenCalledWith('entry-1', { action: 'discard' }, expect.anything()));
});
+
+ it('renders per-sub-entry diffs for a field carrying `parts`, and still merges at field granularity', async () => {
+ const deepEntry = {
+ id: 'entry-2', recordKind: 'universe', recordId: 'u-deep0000000', detectedAt: '2026-05-25T10:00:00Z',
+ source: { via: 'sync' },
+ diffSummary: [{
+ field: 'characters', changed: 'both',
+ parts: [
+ { path: 'Alice', changed: 'both', localValue: { bio: 'mine' }, remoteValue: { bio: 'theirs' } },
+ { path: 'Bob', changed: 'local-only', localValue: { bio: 'gone' }, remoteValue: undefined },
+ ],
+ }],
+ status: 'pending',
+ };
+ api.listConflicts.mockResolvedValue({ conflicts: [deepEntry] });
+ api.resolveConflict.mockResolvedValue({ status: 'resolved' });
+ const user = userEvent.setup();
+ render(<ConflictsTab />);
+ await waitFor(() => expect(screen.getByText(/1 field\(s\)/)).toBeInTheDocument());
+
+ await user.click(screen.getByText(/u-deep0000000/)); // expand
+ // Each changed sub-entry is labelled and rendered as its own diff.
+ expect(await screen.findByText(/Alice/)).toBeInTheDocument();
+ expect(screen.getByText(/Bob/)).toBeInTheDocument();
+ expect(screen.getAllByTestId('diff')).toHaveLength(2); // one InlineDiff per part, not one blob
+
+ // Merge still selects the whole field (one checkbox for the field, not per-part).
+ const checkboxes = screen.getAllByRole('checkbox');
+ expect(checkboxes).toHaveLength(1);
+ await user.click(checkboxes[0]);
+ await user.click(screen.getByRole('button', { name: /Merge 1 selected field/ }));
+ await waitFor(() => expect(api.resolveConflict).toHaveBeenCalledWith('entry-2', { action: 'merge-fields', fields: ['characters'] }, expect.anything()));
+ });
});
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index 8678e25ca6..16dcf2af5b 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -221,9 +221,81 @@ export const RESTORABLE_FIELDS = Object.freeze({
issue: ['title', 'status', 'seasonId', 'arcPosition', 'arcRole', 'lengthProfile', 'pageTarget', 'minutesTarget', 'stages'],
});
-// Top-level shallow diff over the kind's restorable content fields — enough for
-// the UI to render "Name, Premise differ" with InlineDiff and offer each as a
-// selectable merge-field. Deep field diffing is a follow-up.
+const isPlainObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
+const present = (v) => v !== undefined;
+const changedFlag = (lv, rv) => (present(lv) && present(rv) ? 'both' : (present(rv) ? 'remote-only' : 'local-only'));
+
+// Stable key used to PAIR two array elements across the local/remote sides
+// (prefer an explicit id so a reorder/insert doesn't cascade); falls back
+// through the other identity-ish fields. Returns null when an element carries
+// none — in which case the array isn't deep-diffable by identity.
+const entryMatchKey = (el) => {
+ for (const k of ['id', 'key', 'slug', 'name']) {
+ if (typeof el?.[k] === 'string' && el[k].trim()) return el[k];
+ }
+ return null;
+};
+// Human-friendly LABEL for a changed sub-entry (a uuid id is a poor label, so a
+// name/title is preferred for display even when the match used the id).
+const entryLabel = (el, fallback) => {
+ for (const k of ['name', 'title', 'label', 'key', 'slug', 'id']) {
+ if (typeof el?.[k] === 'string' && el[k].trim()) return el[k];
+ }
+ return fallback;
+};
+
+/**
+ * One-level structural diff of a single restorable field, used to render the
+ * Conflicts tab as "which sub-entry changed" instead of one giant JSON blob.
+ * Returns an array of changed sub-entries `[{ path, localValue, remoteValue,
+ * changed }]`, or `null` when the field isn't deepenable — a scalar, an array
+ * of scalars, an array of objects without any stable identity, or a
+ * shape-mismatch (object vs array) — in which case the caller keeps the
+ * whole-field diff. Only entries that actually differ are emitted.
+ *
+ * - Object map / structured object (`categories`, `stages`, `arc`): one part
+ * per key whose value differs.
+ * - Array of identity-bearing objects (`characters`, `places`, `seasons`):
+ * paired by `entryMatchKey`; one part per identity that differs (a side
+ * missing ⇒ added/removed). The `path` is a human label.
+ */
+export function deepFieldDiff(localVal, remoteVal) {
+ if (isPlainObj(localVal) && isPlainObj(remoteVal)) {
+ const parts = [];
+ for (const key of new Set([...Object.keys(localVal), ...Object.keys(remoteVal)])) {
+ const lv = localVal[key];
+ const rv = remoteVal[key];
+ if (canonicalStringify(lv) === canonicalStringify(rv)) continue;
+ parts.push({ path: key, localValue: lv, remoteValue: rv, changed: changedFlag(lv, rv) });
+ }
+ return parts.length ? parts : null;
+ }
+ if (Array.isArray(localVal) && Array.isArray(remoteVal)) {
+ // Require every present element to carry a match key on BOTH sides — a
+ // mixed/identity-less array (e.g. array of strings) text-diffs fine as a
+ // whole, so bail to the whole-field path for those.
+ const keyed = (arr) => arr.every((el) => entryMatchKey(el) !== null);
+ if (!keyed(localVal) || !keyed(remoteVal) || (localVal.length === 0 && remoteVal.length === 0)) return null;
+ const lMap = new Map(localVal.map((el) => [entryMatchKey(el), el]));
+ const rMap = new Map(remoteVal.map((el) => [entryMatchKey(el), el]));
+ const parts = [];
+ for (const matchKey of new Set([...lMap.keys(), ...rMap.keys()])) {
+ const lv = lMap.get(matchKey);
+ const rv = rMap.get(matchKey);
+ if (canonicalStringify(lv) === canonicalStringify(rv)) continue;
+ parts.push({ path: entryLabel(lv ?? rv, matchKey), localValue: lv, remoteValue: rv, changed: changedFlag(lv, rv) });
+ }
+ return parts.length ? parts : null;
+ }
+ return null;
+}
+
+// Per-field diff over the kind's restorable content fields. A scalar field
+// carries its whole-field `localValue`/`remoteValue` for InlineDiff; an
+// object-map or array-of-objects field instead carries `parts` (the changed
+// sub-entries) so the UI renders one focused diff per entry rather than a
+// single giant JSON blob. The merge-fields selection stays at FIELD granularity
+// (the resolver applies whole snapshot fields) — `parts` is display-only.
const diffSummary = (kind, local, remote) => {
const fields = RESTORABLE_FIELDS[kind] || [];
const out = [];
@@ -231,13 +303,10 @@ const diffSummary = (kind, local, remote) => {
const lv = local?.[field];
const rv = remote?.[field];
if (canonicalStringify(lv) === canonicalStringify(rv)) continue;
- const present = (v) => v !== undefined;
- out.push({
- field,
- localValue: lv,
- remoteValue: rv,
- changed: present(lv) && present(rv) ? 'both' : (present(rv) ? 'remote-only' : 'local-only'),
- });
+ const changed = changedFlag(lv, rv);
+ const parts = deepFieldDiff(lv, rv);
+ if (parts) out.push({ field, changed, parts });
+ else out.push({ field, localValue: lv, remoteValue: rv, changed });
}
return out;
};
diff --git a/server/lib/conflictJournal.test.js b/server/lib/conflictJournal.test.js
index c4de6cc717..ee386967b3 100644
--- a/server/lib/conflictJournal.test.js
+++ b/server/lib/conflictJournal.test.js
@@ -101,6 +101,77 @@ describe('conflictJournal', () => {
expect(fields).not.toContain('id');
});
+ describe('deepFieldDiff (per-sub-entry diffing)', () => {
+ it('object map → one part per changed key, only the differing keys', () => {
+ const local = { tone: { v: 'dark' }, palette: { v: 'warm' }, era: { v: 'now' } };
+ const remote = { tone: { v: 'light' }, palette: { v: 'warm' }, mood: { v: 'tense' } };
+ const parts = cj.deepFieldDiff(local, remote);
+ const byPath = Object.fromEntries(parts.map((p) => [p.path, p]));
+ expect(Object.keys(byPath).sort()).toEqual(['era', 'mood', 'tone']); // palette unchanged → absent
+ expect(byPath.tone.changed).toBe('both');
+ expect(byPath.era.changed).toBe('local-only'); // removed on remote
+ expect(byPath.mood.changed).toBe('remote-only'); // added on remote
+ });
+
+ it('array of identity-bearing objects → paired by id, labelled by name', () => {
+ const local = [{ id: 'c1', name: 'Alice', age: 30 }, { id: 'c2', name: 'Bob', age: 40 }];
+ const remote = [{ id: 'c1', name: 'Alice', age: 31 }, { id: 'c3', name: 'Cara', age: 22 }];
+ const parts = cj.deepFieldDiff(local, remote);
+ const byPath = Object.fromEntries(parts.map((p) => [p.path, p]));
+ // c1 changed (age) → labelled 'Alice'; c2 removed → 'Bob'; c3 added → 'Cara'.
+ expect(Object.keys(byPath).sort()).toEqual(['Alice', 'Bob', 'Cara']);
+ expect(byPath.Alice.changed).toBe('both');
+ expect(byPath.Bob.changed).toBe('local-only');
+ expect(byPath.Cara.changed).toBe('remote-only');
+ });
+
+ it('reordering identity-bearing objects with no content change → null (no spurious parts)', () => {
+ const local = [{ id: 'a', name: 'A' }, { id: 'b', name: 'B' }];
+ const remote = [{ id: 'b', name: 'B' }, { id: 'a', name: 'A' }];
+ expect(cj.deepFieldDiff(local, remote)).toBeNull();
+ });
+
+ it('returns null for scalars, arrays of scalars, identity-less arrays, and shape mismatches', () => {
+ expect(cj.deepFieldDiff('a', 'b')).toBeNull();
+ expect(cj.deepFieldDiff(['x', 'y'], ['x', 'z'])).toBeNull();
+ expect(cj.deepFieldDiff([{ foo: 1 }], [{ foo: 2 }])).toBeNull(); // no id/key/slug/name
+ expect(cj.deepFieldDiff({ a: 1 }, [1, 2])).toBeNull(); // object vs array
+ });
+ });
+
+ it('diffSummary emits `parts` for object-map + array-of-object fields, whole-field for scalars', async () => {
+ const base = uni({
+ starterPrompt: 'base',
+ categories: { tone: { v: 'dark' } },
+ characters: [{ id: 'c1', name: 'Alice', bio: 'old' }],
+ });
+ await cj.setSyncBaseHash('universe', 'u-1', cj.contentHashForRecord('universe', base));
+ const local = uni({
+ starterPrompt: 'LOCAL prompt',
+ categories: { tone: { v: 'LOCAL tone' } },
+ characters: [{ id: 'c1', name: 'Alice', bio: 'LOCAL bio' }],
+ updatedAt: '2026-05-02T00:00:00Z',
+ });
+ const remote = uni({
+ starterPrompt: 'REMOTE prompt',
+ categories: { tone: { v: 'REMOTE tone' } },
+ characters: [{ id: 'c1', name: 'Alice', bio: 'REMOTE bio' }],
+ updatedAt: '2026-05-03T00:00:00Z',
+ });
+ await cj.maybeJournalBeforeOverwrite({ kind: 'universe', id: 'u-1', local, remote, source: { via: 'sync' } });
+ const [entry] = await pendingEntries();
+ const byField = Object.fromEntries(entry.diffSummary.map((d) => [d.field, d]));
+ // scalar field → whole-field values, no parts.
+ expect(byField.starterPrompt.parts).toBeUndefined();
+ expect(byField.starterPrompt.localValue).toBe('LOCAL prompt');
+ // object-map field → parts keyed by category.
+ expect(byField.categories.localValue).toBeUndefined();
+ expect(byField.categories.parts.map((p) => p.path)).toEqual(['tone']);
+ // array-of-objects field → parts labelled by name.
+ expect(byField.characters.parts.map((p) => p.path)).toEqual(['Alice']);
+ expect(byField.characters.parts[0].remoteValue.bio).toBe('REMOTE bio');
+ });
+
it('issue content hash ignores the renumber-managed `number` (no false divergence on a sibling renumber)', () => {
// A local sibling-delete shifts this issue's `number` in place WITHOUT
// bumping updatedAt — that must NOT register as a content divergence.