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
fix: address review round 2 — double-toast, empty-clobber federation, import-shape rollups (#2156)
Adam Eivyf9dd95dae3f1
diff --git a/client/src/components/digital-twin/ObservedTasteEvidence.jsx b/client/src/components/digital-twin/ObservedTasteEvidence.jsxindex a91435864d..a7abac6228 100644--- a/client/src/components/digital-twin/ObservedTasteEvidence.jsx+++ b/client/src/components/digital-twin/ObservedTasteEvidence.jsx@@ -104,7 +104,8 @@ export default function ObservedTasteEvidence() {const handleRecompute = async () => {setRecomputing(true);- const res = await api.recomputeTwinEvidence().catch(() => null);+ // silent: this handler owns its own failure toast (avoid a double toast).+ const res = await api.recomputeTwinEvidence({ silent: true }).catch(() => null);setRecomputing(false);if (!res) { toast('Recompute failed', { icon: '⚠️' }); return; }setEvidence(res.evidence);@@ -114,7 +115,8 @@ export default function ObservedTasteEvidence() {const handleInterpret = async () => {if (!selected?.providerId) { toast('Select an AI provider first', { icon: '⚠️' }); return; }setInterpreting(true);- const res = await api.interpretTwinConsumption(selected.providerId, selected.model || undefined)+ // silent: this handler surfaces the error message itself (avoid a double toast).+ const res = await api.interpretTwinConsumption(selected.providerId, selected.model || undefined, { silent: true }).catch((err) => { toast(err?.message || 'Interpretation failed', { icon: '⚠️' }); return null; });setInterpreting(false);if (!res?.interpretation) return;diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.jsindex 1de76eefac..bb067fdd2e 100644--- a/client/src/services/apiDigitalTwin.js+++ b/client/src/services/apiDigitalTwin.js@@ -312,13 +312,15 @@ export const compareTimeCapsuleSnapshots = (id1, id2) => request('/digital-twin/// Twin enrichment — observed taste + chronotype evidence (Phase 7, #2156)export const getTwinEvidence = (options) => request('/digital-twin/twin-evidence', options);-export const recomputeTwinEvidence = () => request('/digital-twin/twin-evidence/recompute', {+export const recomputeTwinEvidence = (options = {}) => request('/digital-twin/twin-evidence/recompute', {method: 'POST',- body: JSON.stringify({})+ body: JSON.stringify({}),+ ...options});-export const interpretTwinConsumption = (providerId, model) => request('/digital-twin/twin-evidence/interpret', {+export const interpretTwinConsumption = (providerId, model, options = {}) => request('/digital-twin/twin-evidence/interpret', {method: 'POST',- body: JSON.stringify({ providerId, model })+ body: JSON.stringify({ providerId, model }),+ ...options});// Soul aliases (used by digital-twin UI components)diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.jsindex 27ad6e1c23..650699169f 100644--- a/server/services/digital-twin-sync.js+++ b/server/services/digital-twin-sync.js@@ -142,17 +142,42 @@ export function unionByKey(localArr, remoteArr, keyField, timestampField = null)return { merged: Array.from(map.values()), changed };}+// True when an observed-taste record actually rolled up media (either window+// signal). The observed evidence is per-machine, so a machine with no media+// sources produces an empty rollup — and an empty rollup with a newer derivedAt+// must NOT clobber a peer's populated one under plain LWW (#2156 HIGH).+function tasteObservedHasSignal(rec) {+ const m = isPlainObject(rec) ? rec.windows?.month : null;+ return Boolean((m?.listen?.total || 0) > 0 || (m?.watch?.total || 0) > 0);+}++// True when an observed-chronotype record captured any activity.+function chronotypeObservedHasSignal(rec) {+ return isPlainObject(rec) && (rec.sampleSize || 0) > 0;+}++// LWW on `timestampField`, EXCEPT a record with signal always beats an empty+// one regardless of recency — so an idle/fresh peer's empty rollup can't+// overwrite a populated record. When both sides have signal (or both are+// empty) it degrades to plain LWW.+function signalAwareLWW(local, remote, hasSignal, timestampField) {+ if (isPlainObject(remote) && hasSignal(remote) && !hasSignal(local)) return { merged: remote, changed: true };+ if (isPlainObject(local) && hasSignal(local) && !hasSignal(remote)) return { merged: local, changed: false };+ return mergeObjectLWW(local, remote, timestampField);+}+/**- * Merge observed taste evidence (#2156). The rollup BODY is LWW on `derivedAt`- * (newest observation wins wholesale), but the AI `interpretation` block is the- * one piece of EXPLICIT user-triggered content on the record — so it's- * preserved separately: whichever side carries the newest interpretation (by- * its own `generatedAt`) is kept regardless of which body won. Without this, an- * unattended LLM-free daily recompute on another peer (newer `derivedAt`, no- * interpretation) would silently drop the user's interpretation cross-machine.+ * Merge observed taste evidence (#2156). The rollup BODY is signal-aware LWW on+ * `derivedAt` (newest observation wins, but a populated record always beats an+ * empty one — see signalAwareLWW), and the AI `interpretation` block is the one+ * piece of EXPLICIT user-triggered content on the record, preserved separately:+ * whichever side carries the newest interpretation (by its own `generatedAt`)+ * is kept regardless of which body won. Without that, an unattended LLM-free+ * recompute on another peer (newer `derivedAt`, no interpretation) would+ * silently drop the user's interpretation cross-machine.*/export function mergeTasteObserved(local, remote) {- const { merged, changed } = mergeObjectLWW(local, remote, 'derivedAt');+ const { merged, changed } = signalAwareLWW(local, remote, tasteObservedHasSignal, 'derivedAt');const li = isPlainObject(local) && isPlainObject(local.interpretation) ? local.interpretation : null;const ri = isPlainObject(remote) && isPlainObject(remote.interpretation) ? remote.interpretation : null;const newest = (ri?.generatedAt || '') > (li?.generatedAt || '') ? ri : li;@@ -165,6 +190,14 @@ export function mergeTasteObserved(local, remote) {return { merged: { ...merged, interpretation: newest }, changed: true };}+/**+ * Merge observed chronotype evidence (#2156): signal-aware LWW on `derivedAt`+ * so an idle peer's empty histogram can't overwrite a populated one.+ */+export function mergeChronotypeObserved(local, remote) {+ return signalAwareLWW(local, remote, chronotypeObservedHasSignal, 'derivedAt');+}+const TASTE_STATUS_RANK = { pending: 0, in_progress: 1, completed: 2 };function pickStatus(a, b) {return (TASTE_STATUS_RANK[b] ?? -1) > (TASTE_STATUS_RANK[a] ?? -1) ? b : a;@@ -535,7 +568,7 @@ export async function applyDigitalTwinRemote(remoteData) {// Observed evidence (Phase 7): regenerated derived records — body is LWW on// derivedAt; taste also preserves the newest user-triggered AI interpretation.count += await applyMerge(TASTE_OBSERVED_FILE, remoteData.tasteObserved, mergeTasteObserved);- count += await applyMerge(CHRONOTYPE_OBSERVED_FILE, remoteData.chronotypeObserved, (l, r) => mergeObjectLWW(l, r, 'derivedAt'));+ count += await applyMerge(CHRONOTYPE_OBSERVED_FILE, remoteData.chronotypeObserved, mergeChronotypeObserved);// Meta BEFORE documents: applyMeta()'s loadMeta() rebuilds meta from a disk// .md scan when no meta.json exists, creating DEFAULT document entries. If the// peer's .md files were written first, that rebuild would manufacture defaultdiff --git a/server/services/digital-twin-sync.test.js b/server/services/digital-twin-sync.test.jsindex 50bf76b508..7d1a6510bd 100644--- a/server/services/digital-twin-sync.test.js+++ b/server/services/digital-twin-sync.test.js@@ -9,6 +9,7 @@ import {mergeSocialAccounts,mergeAutobiographyStories,mergeTasteObserved,+ mergeChronotypeObserved,safeMdName,} from './digital-twin-sync.js';@@ -41,13 +42,38 @@ describe('mergeObjectLWW', () => {});describe('mergeTasteObserved (#2156 — preserve user AI interpretation across LWW)', () => {- const body = (derivedAt, extra = {}) => ({ source: 'observed', derivedAt, ...extra });+ // Signal = a populated month window; empty = zeroed rollups (idle peer).+ const withSignal = (derivedAt, extra = {}) => ({+ source: 'observed', derivedAt,+ windows: { month: { listen: { total: 5 }, watch: { total: 0 } } },+ ...extra,+ });+ const empty = (derivedAt, extra = {}) => ({+ source: 'observed', derivedAt,+ windows: { month: { listen: { total: 0 }, watch: { total: 0 } } },+ ...extra,+ });+ const body = (derivedAt, extra = {}) => withSignal(derivedAt, extra);const interp = (generatedAt, text = 'x') => ({ text, generatedAt });- it('LWW on derivedAt for the rollup body', () => {- const local = body('2026-07-01T00:00:00Z', { total: 1 });- const remote = body('2026-07-05T00:00:00Z', { total: 9 });- expect(mergeTasteObserved(local, remote).merged.total).toBe(9);+ it('LWW on derivedAt for the rollup body when both sides have signal', () => {+ const local = withSignal('2026-07-01T00:00:00Z', { windows: { month: { listen: { total: 1 }, watch: { total: 0 } } } });+ const remote = withSignal('2026-07-05T00:00:00Z', { windows: { month: { listen: { total: 9 }, watch: { total: 0 } } } });+ expect(mergeTasteObserved(local, remote).merged.windows.month.listen.total).toBe(9);+ });++ it('a populated record is never clobbered by a newer EMPTY one (idle peer)', () => {+ const local = withSignal('2026-07-01T00:00:00Z');+ const remoteEmptyNewer = empty('2026-07-09T00:00:00Z'); // newer, but no signal+ const { merged, changed } = mergeTasteObserved(local, remoteEmptyNewer);+ expect(merged.derivedAt).toBe('2026-07-01T00:00:00Z'); // local (populated) kept+ expect(changed).toBe(false);+ });++ it('a populated remote replaces an empty local regardless of recency', () => {+ const localEmptyNewer = empty('2026-07-09T00:00:00Z');+ const remotePopulatedOlder = withSignal('2026-07-01T00:00:00Z');+ expect(mergeTasteObserved(localEmptyNewer, remotePopulatedOlder).merged.windows.month.listen.total).toBe(5);});it('keeps the local interpretation when a newer remote recompute carries none', () => {@@ -76,6 +102,20 @@ describe('mergeTasteObserved (#2156 — preserve user AI interpretation across L});});+describe('mergeChronotypeObserved (#2156 — signal-aware LWW)', () => {+ const rec = (derivedAt, sampleSize, observedType) => ({ source: 'observed', derivedAt, sampleSize, observedType });+ it('LWW on derivedAt when both sides have activity', () => {+ const local = rec('2026-07-01T00:00:00Z', 40, 'morning');+ const remote = rec('2026-07-05T00:00:00Z', 60, 'evening');+ expect(mergeChronotypeObserved(local, remote).merged.observedType).toBe('evening');+ });+ it('a populated histogram is not clobbered by a newer empty one (sampleSize 0)', () => {+ const local = rec('2026-07-01T00:00:00Z', 40, 'morning');+ const remoteEmpty = rec('2026-07-09T00:00:00Z', 0, null);+ expect(mergeChronotypeObserved(local, remoteEmpty).merged.observedType).toBe('morning');+ });+});+describe('mergeDeepUnion', () => {it('unions nested marker objects, local wins per-key', () => {const local = { markers: { a: 1 }, derivedAt: '2026-01-01' };diff --git a/server/services/twinEnrichment.js b/server/services/twinEnrichment.jsindex 9c1ee150ac..c8f5483b3f 100644--- a/server/services/twinEnrichment.js+++ b/server/services/twinEnrichment.js@@ -84,15 +84,23 @@ export function noveltyRatio(keys) {return { total, distinct, repeats: total - distinct, noveltyRatio: ratio };}-// Flatten a listen event's artist names. Accepts metadata.artists as-// [{ name }] or [string], falling back to the summary line (spotifySync stores-// the comma-joined artist names there) so a leaner event still contributes.+// Flatten a listen event's artist names across the live-sync AND import shapes:+// - spotifySync: metadata.artists = [{ id, name }]+// - spotifyImport: metadata.artist = single (album-artist) string+// falling back to the comma-joined summary line only when neither is present.+// Reading metadata.artist directly avoids the import summary's "Artist — Album"+// form leaking the album into the artist tally.export function listenArtistNames(ev) {const artists = ev?.metadata?.artists;if (Array.isArray(artists)) {const names = artists.map((a) => String((typeof a === 'string' ? a : a?.name) || '').trim()).filter(Boolean);if (names.length) return names;}+ const single = ev?.metadata?.artist;+ if (single) {+ const names = String(single).split(',').map((s) => s.trim()).filter(Boolean);+ if (names.length) return names;+ }const summary = String(ev?.summary || '').trim();return summary ? summary.split(',').map((s) => s.trim()).filter(Boolean) : [];}@@ -106,9 +114,13 @@ export function listenGenreNames(ev) {return genres.map((g) => String((typeof g === 'string' ? g : g?.name) || '').trim()).filter(Boolean);}-// A stable per-play key for novelty counting (track id preferred, title fallback).+// A stable per-play key for novelty counting. Track identity across both source+// shapes: sync's `trackId`, import's `trackUri`, then isrc, then title —+// falling to dedupeKey only as a last resort (per-play, so it never collapses+// repeats, which is the safe direction). Using trackUri keeps two different+// imported tracks that share a title from collapsing into one "repeat".function listenNoveltyKey(ev) {- return ev?.metadata?.trackId || ev?.metadata?.isrc || ev?.title || ev?.dedupeKey || '';+ return ev?.metadata?.trackId || ev?.metadata?.trackUri || ev?.metadata?.isrc || ev?.title || ev?.dedupeKey || '';}function watchNoveltyKey(ev) {return ev?.metadata?.videoId || ev?.url || ev?.title || ev?.dedupeKey || '';diff --git a/server/services/twinEnrichment.test.js b/server/services/twinEnrichment.test.jsindex dc6a88a1c3..bbdef7a4ba 100644--- a/server/services/twinEnrichment.test.js+++ b/server/services/twinEnrichment.test.js@@ -63,6 +63,12 @@ describe('listenArtistNames / listenGenreNames', () => {it('accepts bare-string artists', () => {expect(listenArtistNames({ metadata: { artists: ['Solo'] } })).toEqual(['Solo']);});+ it('reads the import shape (metadata.artist single string) without leaking the album', () => {+ // spotifyImport stores metadata.artist + a "Artist — Album" summary; the+ // artist tally must be just the artist, never "Artist — Album".+ expect(listenArtistNames({ metadata: { artist: 'Radiohead' }, summary: 'Radiohead — OK Computer' }))+ .toEqual(['Radiohead']);+ });it('falls back to the comma-joined summary line when metadata is lean', () => {expect(listenArtistNames({ summary: 'A, B , C' })).toEqual(['A', 'B', 'C']);});@@ -90,6 +96,20 @@ describe('rollupListen / rollupWatch', () => {// 3 plays, t1 twice → 2 distinct.expect(r.novelty).toEqual({ total: 3, distinct: 2, repeats: 1, noveltyRatio: 0.667 });});+ it('handles imported listens (metadata.artist + trackUri) — artist tally + novelty by uri', () => {+ // Two DIFFERENT tracks that happen to share a title must not collapse as a+ // repeat — novelty keys on trackUri, not the title.+ const imported = [+ { kind: 'media.listen', title: 'Intro', metadata: { artist: 'A', trackUri: 'spotify:track:1' }, summary: 'A — Album1' },+ { kind: 'media.listen', title: 'Intro', metadata: { artist: 'B', trackUri: 'spotify:track:2' }, summary: 'B — Album2' },+ { kind: 'media.listen', title: 'Intro', metadata: { artist: 'A', trackUri: 'spotify:track:1' }, summary: 'A — Album1' },+ ];+ const r = rollupListen(imported);+ expect(r.total).toBe(3);+ expect(r.topArtists).toEqual([{ name: 'A', count: 2 }, { name: 'B', count: 1 }]);+ // 3 plays, 2 distinct URIs → not collapsed by shared title.+ expect(r.novelty).toEqual({ total: 3, distinct: 2, repeats: 1, noveltyRatio: 0.667 });+ });it('rolls up only media.watch events with channels + novelty', () => {const watches = [{ kind: 'media.watch', title: 'V1', metadata: { videoId: 'v1', channel: 'Chan', topics: ['tech'] } },