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: key digital-twin test-history peer merge on runId so a sync no longer collapses every run (#3529)
[._.]/ Adam Eivy3fb7bcaf6239
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a58afeba6f..074595e8ac 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -105,6 +105,7 @@- **[issue-3517] A failed "Schedule Time Blocks" left the goal's scheduling buttons stuck on "Scheduling..." until you reloaded the page.** Scheduling, rescheduling, and removing a goal's time blocks each raised a shared busy flag before their request and lowered it afterwards, but nothing caught a rejection — so a server error or a dropped connection aborted the handler before the flag came back down, and all three buttons stayed disabled with no way to retry short of reloading. The three now share one runner that always clears the flag, and the panel refreshes afterwards whether or not the request succeeded, because a scheduling run can write some blocks before it fails and leaving that half-written state off screen is the more confusing outcome. The failure itself still surfaces exactly once, from the shared request helper, rather than picking up a second toast of its own.- **[issue-3525] Tapping "edit bucket" on a phone in Bookmarks often deleted the bucket instead.** The edit and delete icons in a bucket's header were 13px glyphs with 4px of padding — roughly 17px of tappable area each, sitting right next to each other — so on a narrow screen a thumb aimed at edit landed on delete and opened its confirmation instead. Both now use the standard 44px minimum tap target with the icon centered inside it, which is what the rest of PortOS uses for icon-only buttons, and the header's own vertical padding drops to compensate so the taller buttons don't inflate the card. The bucket's "add a URL" submit button had the same problem and gets the same treatment.+- **[issue-3529] Syncing two machines wiped your Digital Twin's evaluation history down to a single run.** Every persona test, values-alignment run, adversarial-boundary run and multi-turn run is recorded with a `runId`, but the peer merge was unioning those four histories on an `id` field none of them has. Every entry therefore resolved to the same empty key: the local runs overwrote each other until one was left, and every run arriving from the other machine was then discarded as a duplicate of it. Both machines lost their history on the first sync, permanently. The merge now keys on `runId`, so runs recorded on either machine survive and a run both machines already have is not duplicated. The union helper underneath no longer collapses records at all when the field it was pointed at is missing — records with no usable key are matched on their content instead, so the next time a key field is named wrong the result is a harmless duplicate rather than silent destruction, and re-syncing the same records adds nothing. Merged histories are also re-sorted newest-first, because the recorders keep only the fifty most recent runs and take them off the front: a peer's runs appended to the end would have read as the oldest, and the next local run would have trimmed away the newest entries instead of the oldest.## Three.js Modelsdiff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.jsindex 650699169f..79cf226a81 100644--- a/server/services/digital-twin-sync.js+++ b/server/services/digital-twin-sync.js@@ -38,7 +38,7 @@ import { join, basename } from 'path';import { readdir, readFile } from 'fs/promises';import { existsSync } from 'fs';import { atomicWrite, readJSONFile, ensureDir, PATHS } from '../lib/fileUtils.js';-import { isPlainObject } from '../lib/objects.js';+import { canonicalStringify, isPlainObject } from '../lib/objects.js';const DIR = PATHS.digitalTwin;const IDENTITY_FILE = join(DIR, 'identity.json');@@ -117,20 +117,36 @@ export function mergeDeepUnion(local, remote, timestampField = 'derivedAt') {return { merged, changed };}+// Resolve the dedupe key for one record. A record that carries no usable value+// under `keyField` must NOT fall through to a shared `undefined` Map key —+// every such record would collide, collapsing the whole array down to one+// survivor and silently destroying history on the next sync. That is exactly+// what #3529 did: the four digital-twin test histories were unioned on 'id'+// while the schema stores 'runId', so a single peer merge wiped every run but+// the last. Unkeyed records fall back to a canonical content signature instead+// — they survive the merge, and re-syncing the same record stays idempotent.+function unionKeyFor(item, keyField) {+ const key = item[keyField];+ if (typeof key === 'string' && key !== '') return key;+ if (typeof key === 'number' && Number.isFinite(key)) return key;+ return `\u0000sig:${canonicalStringify(item)}`;+}+/*** Union two arrays of records by a key field. Records unique to either side are* kept; on a key collision the local record is kept (ADD-ONLY) unless a- * timestampField is given and remote's is strictly newer (LWW).+ * timestampField is given and remote's is strictly newer (LWW). Records missing+ * the key field are deduped by content signature rather than collapsing.*/export function unionByKey(localArr, remoteArr, keyField, timestampField = null) {const local = Array.isArray(localArr) ? localArr : [];const remote = Array.isArray(remoteArr) ? remoteArr : [];const map = new Map();- for (const item of local) if (isPlainObject(item)) map.set(item[keyField], item);+ for (const item of local) if (isPlainObject(item)) map.set(unionKeyFor(item, keyField), item);let changed = false;for (const item of remote) {if (!isPlainObject(item)) continue;- const key = item[keyField];+ const key = unionKeyFor(item, keyField);const existing = map.get(key);if (!existing) { map.set(key, item); changed = true; continue; }if (timestampField) {@@ -328,11 +344,34 @@ export function mergeConfidence(local, remote) {return { merged, changed };}+// The four digital-twin evaluation-run histories on meta.json. Each entry is+// identified by `runId` — NOT `id`.+export const TEST_HISTORY_KEYS = ['testHistory', 'valuesTestHistory', 'adversarialTestHistory', 'multiTurnTestHistory'];++// The run recorders (digital-twin-*-testing.js) `unshift` each new run and then+// `slice(0, 50)`, so these arrays are newest-first and the readers' `slice(0,+// limit)` means "most recent N". A union appends the peer's runs at the END, so+// without re-sorting a freshly-synced peer run would read as the oldest — and+// the next local run's slice(0, 50) would discard the newest entries instead of+// the oldest. Sort descending on the ISO `timestamp` to restore the invariant;+// entries with no timestamp sort last rather than jumping to the front. `runId`+// breaks ties so both peers land on the SAME order for the same set of runs+// (each merges its own side first, so insertion order alone would diverge).+function sortRunsNewestFirst(runs) {+ const at = (r) => (typeof r?.timestamp === 'string' ? r.timestamp : '');+ const id = (r) => (typeof r?.runId === 'string' ? r.runId : '');+ return [...runs].sort((a, b) => {+ if (at(a) !== at(b)) return at(a) > at(b) ? -1 : 1;+ if (id(a) === id(b)) return 0;+ return id(a) < id(b) ? -1 : 1;+ });+}+/*** Merge digital-twin meta.json: documents union by filename (ADD-ONLY — a local- * doc entry is never replaced), the four test histories + personas union by id,- * enrichment deep-unions, settings fill missing keys (local values win), and the- * analyzed personality-trait confidence max-per-dimension.+ * doc entry is never replaced), the four test histories union by runId, personas+ * union by id, enrichment deep-unions, settings fill missing keys (local values+ * win), and the analyzed personality-trait confidence max-per-dimension.*/export function mergeMeta(local, remote) {if (!isPlainObject(remote)) return { merged: local, changed: false };@@ -344,9 +383,12 @@ export function mergeMeta(local, remote) {const docs = unionByKey(local.documents, remote.documents, 'filename');if (docs.changed) { merged.documents = docs.merged; changed = true; }- for (const key of ['testHistory', 'valuesTestHistory', 'adversarialTestHistory', 'multiTurnTestHistory']) {- const u = unionByKey(local[key], remote[key], 'id');- if (u.changed) { merged[key] = u.merged; changed = true; }+ // Test-history entries identify a run by `runId` (see digitalTwinValidation.js)+ // — they carry no `id`. Unioning them on 'id' collapsed every history to a+ // single entry on the first peer merge (#3529).+ for (const key of TEST_HISTORY_KEYS) {+ const u = unionByKey(local[key], remote[key], 'runId');+ if (u.changed) { merged[key] = sortRunsNewestFirst(u.merged); changed = true; }}const personas = unionByKey(local.personas, remote.personas, 'id');diff --git a/server/services/digital-twin-sync.test.js b/server/services/digital-twin-sync.test.jsindex 7d1a6510bd..3def54f03c 100644--- a/server/services/digital-twin-sync.test.js+++ b/server/services/digital-twin-sync.test.js@@ -11,8 +11,13 @@ import {mergeTasteObserved,mergeChronotypeObserved,safeMdName,+ TEST_HISTORY_KEYS,} from './digital-twin-sync.js';+// Minimal shape of a digital-twin evaluation-run history entry — the real+// schemas (digitalTwinValidation.js) key each run on `runId`, never `id`.+const run = (runId, timestamp) => ({ runId, timestamp, providerId: 'example-provider', model: 'example-model', score: 0.5 });+describe('mergeObjectLWW', () => {it('takes remote when local is missing', () => {expect(mergeObjectLWW(null, { updatedAt: '2026-01-01' })).toEqual({@@ -155,6 +160,37 @@ describe('unionByKey', () => {it('tolerates non-array inputs', () => {expect(unionByKey(null, undefined, 'id')).toEqual({ merged: [], changed: false });});++ // Regression guard for the whole class of bug behind #3529: a keyField that+ // no record actually carries must not silently collapse the array.+ it('keeps every record when NONE of them carry the key field', () => {+ const { merged } = unionByKey(+ [{ runId: 'a' }, { runId: 'b' }],+ [{ runId: 'c' }],+ 'nonexistentKey'+ );+ expect(merged.map((x) => x.runId).sort()).toEqual(['a', 'b', 'c']);+ });++ it('treats a blank-string key as unkeyed rather than collapsing on it', () => {+ const { merged } = unionByKey([{ id: '', v: 1 }, { id: '', v: 2 }], [], 'id');+ expect(merged).toHaveLength(2);+ });++ it('is idempotent for unkeyed records — re-merging the same remote adds nothing', () => {+ const local = [{ runId: 'a' }];+ const remote = [{ runId: 'b' }];+ const first = unionByKey(local, remote, 'nonexistentKey');+ const second = unionByKey(first.merged, remote, 'nonexistentKey');+ expect(second.merged).toHaveLength(2);+ expect(second.changed).toBe(false);+ });++ it('signature-matches unkeyed records regardless of property order', () => {+ const { merged, changed } = unionByKey([{ a: 1, b: 2 }], [{ b: 2, a: 1 }], 'id');+ expect(merged).toHaveLength(1);+ expect(changed).toBe(false);+ });});describe('mergeTaste', () => {@@ -233,23 +269,84 @@ describe('mergeMeta', () => {expect(changed).toBe(true);});- it('unions all four test histories and personas by id', () => {- const local = { testHistory: [{ id: 't1' }], personas: [{ id: 'p1' }] };+ it('unions all four test histories by runId and personas by id', () => {+ const local = { testHistory: [run('t1', '2026-01-01T00:00:00.000Z')], personas: [{ id: 'p1' }] };const remote = {- testHistory: [{ id: 't2' }],- valuesTestHistory: [{ id: 'v1' }],- adversarialTestHistory: [{ id: 'a1' }],- multiTurnTestHistory: [{ id: 'm1' }],+ testHistory: [run('t2', '2026-01-02T00:00:00.000Z')],+ valuesTestHistory: [run('v1', '2026-01-01T00:00:00.000Z')],+ adversarialTestHistory: [run('a1', '2026-01-01T00:00:00.000Z')],+ multiTurnTestHistory: [run('m1', '2026-01-01T00:00:00.000Z')],personas: [{ id: 'p2' }],};const { merged } = mergeMeta(local, remote);- expect(merged.testHistory.map((x) => x.id).sort()).toEqual(['t1', 't2']);+ expect(merged.testHistory.map((x) => x.runId).sort()).toEqual(['t1', 't2']);expect(merged.valuesTestHistory).toHaveLength(1);expect(merged.adversarialTestHistory).toHaveLength(1);expect(merged.multiTurnTestHistory).toHaveLength(1);expect(merged.personas.map((x) => x.id).sort()).toEqual(['p1', 'p2']);});+ // #3529: these arrays were unioned on 'id', which no run entry carries, so+ // every entry collided on the `undefined` map key and the merge collapsed+ // each history down to a single record on the FIRST peer sync.+ it('preserves multi-entry test histories from BOTH peers without collapsing', () => {+ const local = Object.fromEntries(TEST_HISTORY_KEYS.map((key) => [key, [+ run(`${key}-L1`, '2026-01-03T00:00:00.000Z'),+ run(`${key}-L2`, '2026-01-01T00:00:00.000Z'),+ ]]));+ const remote = Object.fromEntries(TEST_HISTORY_KEYS.map((key) => [key, [+ run(`${key}-R1`, '2026-01-04T00:00:00.000Z'),+ run(`${key}-R2`, '2026-01-02T00:00:00.000Z'),+ ]]));++ const { merged, changed } = mergeMeta(local, remote);+ expect(changed).toBe(true);+ for (const key of TEST_HISTORY_KEYS) {+ expect(merged[key].map((x) => x.runId).sort()).toEqual(+ [`${key}-L1`, `${key}-L2`, `${key}-R1`, `${key}-R2`].sort()+ );+ }+ });++ it('re-sorts a merged history newest-first so the readers\' slice(0, N) stays "most recent N"', () => {+ const local = { testHistory: [run('L1', '2026-01-03T00:00:00.000Z'), run('L2', '2026-01-01T00:00:00.000Z')] };+ const remote = { testHistory: [run('R1', '2026-01-04T00:00:00.000Z'), run('R2', '2026-01-02T00:00:00.000Z')] };+ const { merged } = mergeMeta(local, remote);+ expect(merged.testHistory.map((x) => x.runId)).toEqual(['R1', 'L1', 'R2', 'L2']);+ });++ it('orders same-timestamp runs identically on both peers (runId tiebreak)', () => {+ const a = run('aaa', '2026-01-01T00:00:00.000Z');+ const b = run('bbb', '2026-01-01T00:00:00.000Z');+ const onPeerA = mergeMeta({ testHistory: [a] }, { testHistory: [b] }).merged.testHistory;+ const onPeerB = mergeMeta({ testHistory: [b] }, { testHistory: [a] }).merged.testHistory;+ expect(onPeerA.map((x) => x.runId)).toEqual(['aaa', 'bbb']);+ expect(onPeerB.map((x) => x.runId)).toEqual(onPeerA.map((x) => x.runId));+ });++ it('sorts timestamp-less legacy runs last instead of ahead of dated ones', () => {+ const local = { testHistory: [{ runId: 'legacy' }] };+ const remote = { testHistory: [run('R1', '2026-01-04T00:00:00.000Z')] };+ const { merged } = mergeMeta(local, remote);+ expect(merged.testHistory.map((x) => x.runId)).toEqual(['R1', 'legacy']);+ });++ it('keeps the local copy of a run that both peers already have (add-only)', () => {+ const local = { testHistory: [{ ...run('shared', '2026-01-01T00:00:00.000Z'), score: 0.9 }] };+ const remote = { testHistory: [{ ...run('shared', '2026-01-01T00:00:00.000Z'), score: 0.1 }] };+ const { merged, changed } = mergeMeta(local, remote);+ expect(merged.testHistory).toHaveLength(1);+ expect(merged.testHistory[0].score).toBe(0.9);+ expect(changed).toBe(false);+ });++ it('leaves histories the peer did not send untouched (key-presence guarded)', () => {+ const local = { testHistory: [run('L1', '2026-01-01T00:00:00.000Z'), run('L2', '2026-01-02T00:00:00.000Z')] };+ const { merged, changed } = mergeMeta(local, { documents: [] });+ expect(merged.testHistory.map((x) => x.runId)).toEqual(['L1', 'L2']);+ expect(changed).toBe(false);+ });+it('deep-unions enrichment (categories, max question counts, newest session)', () => {const local = { enrichment: { completedCategories: ['core'], lastSession: '2026-01-01', questionsAnswered: { core: 3 } } };const remote = { enrichment: { completedCategories: ['social'], lastSession: '2026-02-01', questionsAnswered: { core: 5, social: 2 } } };