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: order goals metadata sync by the document clock, not child goals (#9818)
[._.]/ Adam Eivyfc7efb4a07dc
diff --git a/server/services/dataSync.goalsMetadata.test.js b/server/services/dataSync.goalsMetadata.test.jsnew file mode 100644index 0000000000..bcb16a0523--- /dev/null+++ b/server/services/dataSync.goalsMetadata.test.js@@ -0,0 +1,135 @@+/**+ * dataSync goals snapshot merge — document freshness for metadata (#9818).+ *+ * `setBirthDate` stamps the goals DOCUMENT's `updatedAt` and never restamps a+ * child goal, so a snapshot merge that ordered the metadata (birthDate /+ * lifeExpectancy / timeHorizons) by the newest child-goal timestamp ignored a+ * metadata-only edit — with no goals, or with unchanged goals, both sides+ * scored the same and the stale local value kept winning forever (the+ * orchestrator acks the snapshot checksum, so an unchanged source is never+ * retried). These cases drive the real goals store through `applyRemote` and+ * read the file back, so "no write on replay" is checked against disk.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { readFile, writeFile, mkdir, stat } from 'fs/promises';+import { join } from 'path';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';++const { makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-datasync-goals-meta-' });++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});++const { PATHS } = await import('../lib/fileUtils.js');+const dataSync = await import('./dataSync.js');++afterAll(cleanup);++const GOALS_PATH = () => join(PATHS.digitalTwin, 'goals.json');++const goal = (id, updatedAt) => ({ id, title: `Goal ${id}`, status: 'active', updatedAt });++const seedLocal = async doc => {+ await mkdir(PATHS.digitalTwin, { recursive: true });+ await writeFile(GOALS_PATH(), JSON.stringify(doc));+};+const readLocal = async () => JSON.parse(await readFile(GOALS_PATH(), 'utf8'));++// Placeholder birth dates — fixtures never carry a real one.+const OLD_META = { birthDate: '1990-01-01', lifeExpectancy: { adjusted: 80 }, timeHorizons: { yearsRemaining: 40 } };+const NEW_META = { birthDate: '1991-01-01', lifeExpectancy: { adjusted: 81 }, timeHorizons: { yearsRemaining: 41 } };++beforeEach(async () => {+ await seedLocal({ ...OLD_META, goals: [], updatedAt: '2026-01-10T00:00:00.000Z' });+});++describe('dataSync goals — metadata LWW on the document clock', () => {+ it('applies a newer metadata-only snapshot when both goal arrays are empty, carries its clock, and a replay is a no-op', async () => {+ const remote = { ...NEW_META, goals: [], updatedAt: '2026-02-10T00:00:00.000Z' };++ const first = await dataSync.applyRemote('goals', remote);+ expect(first.applied).toBe(true);+ const merged = await readLocal();+ expect(merged).toMatchObject({ ...NEW_META, updatedAt: remote.updatedAt });++ const before = await stat(GOALS_PATH());+ const replay = await dataSync.applyRemote('goals', remote);+ expect(replay).toEqual({ applied: false, count: 0 });+ expect(await readLocal()).toEqual(merged);+ expect((await stat(GOALS_PATH())).mtimeMs).toBe(before.mtimeMs);+ });++ it('applies a newer metadata-only snapshot when the shared child goal clock is unchanged', async () => {+ const shared = goal('goal-1', '2026-01-05T00:00:00.000Z');+ await seedLocal({ ...OLD_META, goals: [shared], updatedAt: '2026-01-10T00:00:00.000Z' });++ const result = await dataSync.applyRemote('goals', {+ ...NEW_META, goals: [shared], updatedAt: '2026-02-10T00:00:00.000Z'+ });++ expect(result.applied).toBe(true);+ expect(await readLocal()).toMatchObject({ birthDate: NEW_META.birthDate, updatedAt: '2026-02-10T00:00:00.000Z' });+ });++ it('keeps newer local metadata when an older document carries a newer child goal', async () => {+ await seedLocal({ ...NEW_META, goals: [goal('goal-1', '2026-01-05T00:00:00.000Z')], updatedAt: '2026-03-01T00:00:00.000Z' });++ const result = await dataSync.applyRemote('goals', {+ ...OLD_META,+ goals: [goal('goal-2', '2026-04-01T00:00:00.000Z')],+ updatedAt: '2026-01-20T00:00:00.000Z'+ });++ // The goal union still applies; the stale document must not take the metadata or the clock.+ expect(result.applied).toBe(true);+ const merged = await readLocal();+ expect(merged.goals.map(g => g.id).sort()).toEqual(['goal-1', 'goal-2']);+ expect(merged).toMatchObject({ ...NEW_META, updatedAt: '2026-03-01T00:00:00.000Z' });+ });++ it('falls back to the newest child goal clock only when a document has no usable clock', async () => {+ await seedLocal({ ...OLD_META, goals: [goal('goal-1', '2026-01-05T00:00:00.000Z')] });++ // Legacy remote (no document clock) with a newer child goal wins the metadata.+ const legacyNewer = await dataSync.applyRemote('goals', {+ ...NEW_META, goals: [goal('goal-1', '2026-02-05T00:00:00.000Z')]+ });+ expect(legacyNewer.applied).toBe(true);+ expect(await readLocal()).toMatchObject({ birthDate: NEW_META.birthDate });++ // A legacy remote whose newest child is older does not.+ const staleLegacy = await dataSync.applyRemote('goals', {+ ...OLD_META, goals: [goal('goal-1', '2026-01-01T00:00:00.000Z')]+ });+ expect(staleLegacy).toEqual({ applied: false, count: 0 });+ expect(await readLocal()).toMatchObject({ birthDate: NEW_META.birthDate });+ });++ it('does not let a goal the receiver already deleted stand in as proof of a fresher legacy document', async () => {+ await seedLocal({+ ...OLD_META,+ goals: [goal('goal-1', '2026-01-05T00:00:00.000Z')],+ goalTombstones: [{ id: 'goal-2', deletedAt: '2026-02-01T00:00:00.000Z' }]+ });++ // The only thing making this clockless remote look newer is a copy of the deleted goal.+ const result = await dataSync.applyRemote('goals', {+ ...NEW_META, goals: [goal('goal-2', '2026-01-20T00:00:00.000Z')]+ });++ expect(result).toEqual({ applied: false, count: 0 });+ expect(await readLocal()).toMatchObject({ birthDate: OLD_META.birthDate });+ });++ it('never lets a malformed document clock win', async () => {+ const result = await dataSync.applyRemote('goals', {+ ...NEW_META, goals: [], updatedAt: 'not-a-timestamp'+ });++ expect(result).toEqual({ applied: false, count: 0 });+ expect(await readLocal()).toMatchObject({ birthDate: OLD_META.birthDate, updatedAt: '2026-01-10T00:00:00.000Z' });+ });+});diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex f7412c4987..c2ad8cfe4f 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -10,6 +10,7 @@ import { meatspaceEvents } from './meatspaceEvents.js';import { dashboardEvents } from './dashboardEvents.js';import { stat, readdir } from 'fs/promises';import { join } from 'path';+import { isDeepStrictEqual } from 'util';import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';import { canonicalStringify, isEmptyScalar, isPlainObject } from '../lib/objects.js';import { snapshotChecksum } from '../lib/snapshotChecksum.js';@@ -416,6 +417,26 @@ async function getGoalsSnapshot() {return { data, checksum: computeChecksum(data) };}+const GOALS_METADATA_FIELDS = ['birthDate', 'lifeExpectancy', 'timeHorizons'];++/**+ * Freshness of a goals document for the metadata LWW. The document's own+ * `updatedAt` is the clock — `setBirthDate` and every goal write stamp it — so a+ * birth-date edit that never touches a child goal still orders correctly. The+ * newest goal `updatedAt` stands in only for a legacy document with no usable+ * document clock. `null` = no usable clock at all (never wins).+ */+function goalsDocumentClockMs(doc) {+ const docMs = parseTsMs(doc?.updatedAt);+ if (docMs !== null) return docMs;+ let newest = null;+ for (const goal of Array.isArray(doc?.goals) ? doc.goals : []) {+ const ms = parseTsMs(goal?.updatedAt);+ if (ms !== null && (newest === null || ms > newest)) newest = ms;+ }+ return newest;+}+// Goals merge by union, so a delete is only representable as a tombstone (#9816):// `deleteGoal` leaves `{ id, deletedAt }` in the goals document, the list unions in// both directions (a legacy peer that omits it leaves ours untouched), and any@@ -439,22 +460,26 @@ async function applyGoalsRemote(remoteData) {const goalsChanged = canonicalStringify(mergedGoals) !== canonicalStringify(localGoals);const tombstonesChanged = canonicalStringify(liveTombstones) !== canonicalStringify(local[GOAL_TOMBSTONES_KEY] ?? []);- // Merge top-level metadata (birthDate, lifeExpectancy, timeHorizons) via LWW- // Use the most recent goal's updatedAt as proxy for file freshness- const localMaxTs = localGoals.reduce((max, g) => Math.max(max, new Date(g.updatedAt || 0).getTime()), 0);- const remoteMaxTs = remoteGoals.reduce((max, g) => Math.max(max, new Date(g.updatedAt || 0).getTime()), 0);- const metaSource = remoteMaxTs > localMaxTs ? remoteData : local;-- const merged = {- ...local,- birthDate: metaSource.birthDate ?? local.birthDate,- lifeExpectancy: metaSource.lifeExpectancy ?? local.lifeExpectancy,- timeHorizons: metaSource.timeHorizons ?? local.timeHorizons,- goals: mergedGoals- };+ // Top-level metadata (birthDate, lifeExpectancy, timeHorizons) is LWW on the document+ // clock, independent of the goal-array merge: a metadata-only edit changes no goal.+ // A tie keeps local, so a replay of the same snapshot is a no-op. The legacy child-clock+ // fallback reads the tombstone-filtered remote goals, so a deleted copy is no proof of+ // a fresher document.+ const remoteClock = goalsDocumentClockMs({ ...remoteData, goals: remoteGoals });+ const localClock = goalsDocumentClockMs(local);+ const remoteWins = remoteClock !== null && (localClock === null || remoteClock > localClock);++ const winning = {};+ if (remoteWins) {+ for (const field of GOALS_METADATA_FIELDS) winning[field] = remoteData[field] ?? local[field];+ // Carry the winning clock itself — restamping on receipt would out-date the peer's+ // next edit, and leaving ours would let the same snapshot win again.+ if (parseTsMs(remoteData.updatedAt) !== null) winning.updatedAt = remoteData.updatedAt;+ }+ const metaChanged = Object.entries(winning).some(([field, value]) => !isDeepStrictEqual(value, local[field]));- if (goalsChanged || tombstonesChanged || remoteMaxTs > localMaxTs) {- Object.assign(local, merged);+ if (goalsChanged || tombstonesChanged || metaChanged) {+ Object.assign(local, winning, { goals: mergedGoals });// A legacy document stays free of the field until something is tombstoned.if (liveTombstones.length > 0) local[GOAL_TOMBSTONES_KEY] = liveTombstones;else delete local[GOAL_TOMBSTONES_KEY];