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

fix: propagate goal deletions through snapshot federation (#9816)

[._.]/ Adam Eivy9a3f91e7449c
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index f2f5f9650e..fa4b6d06dc 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -15,6 +15,7 @@ import { canonicalStringify, isEmptyScalar, isPlainObject } from '../lib/objects
import { snapshotChecksum } from '../lib/snapshotChecksum.js';
import { parseTsMs } from '../lib/lwwTimestamp.js';
import { isTombstoned, mergeTombstones, pruneTombstones } from '../lib/tombstones.js';
+import { GOAL_TOMBSTONES_KEY, reconcileGoalTombstones } from './identity/goalTombstones.js';
import {
DAILY_LOG_TOMBSTONES_KEY,
dailyLogEventLiveStamp,
@@ -414,21 +415,33 @@ async function getGoalsSnapshot() {
return { data, checksum: computeChecksum(data) };
}
+// 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
+// goal copy the union covers is dropped here, children reparented. See
+// identity/goalTombstones.js for the restoration rule and resurrection horizon.
async function applyGoalsRemote(remoteData) {
const { editGoals } = await import('./identity/store.js');
return editGoals(local => {
- // Merge goals array by ID with LWW on updatedAt
- const { merged: mergedGoals, changed: goalsChanged } = mergeArraysByKey(
- local.goals || [],
- remoteData.goals || [],
- 'id',
- 'updatedAt'
+ const localGoals = local.goals || [];
+ const { merged: tombstones } = mergeTombstones(
+ local[GOAL_TOMBSTONES_KEY],
+ remoteData[GOAL_TOMBSTONES_KEY],
+ { keyField: 'id' },
);
+ // A tombstoned remote copy is filtered BEFORE the union so it neither counts
+ // as a change nor as proof the remote document is fresher.
+ const remoteGoals = reconcileGoalTombstones(remoteData.goals || [], tombstones).goals;
+ // Merge goals array by ID with LWW on updatedAt
+ const { merged: unionGoals } = mergeArraysByKey(localGoals, remoteGoals, 'id', 'updatedAt');
+ const { goals: mergedGoals, tombstones: liveTombstones } = reconcileGoalTombstones(unionGoals, tombstones);
+ 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 = (local.goals || []).reduce((max, g) => Math.max(max, new Date(g.updatedAt || 0).getTime()), 0);
- const remoteMaxTs = (remoteData.goals || []).reduce((max, g) => Math.max(max, new Date(g.updatedAt || 0).getTime()), 0);
+ 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 = {
@@ -439,8 +452,11 @@ async function applyGoalsRemote(remoteData) {
goals: mergedGoals
};
- if (goalsChanged || remoteMaxTs > localMaxTs) {
+ if (goalsChanged || tombstonesChanged || remoteMaxTs > localMaxTs) {
Object.assign(local, merged);
+ // 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];
console.log(`🔄 Goals sync: merged ${mergedGoals.length} goals`);
return { applied: true, count: mergedGoals.length };
}
diff --git a/server/services/goalDeletionSync.test.js b/server/services/goalDeletionSync.test.js
new file mode 100644
index 0000000000..13e4304540
--- /dev/null
+++ b/server/services/goalDeletionSync.test.js
@@ -0,0 +1,152 @@
+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
+import { mkdir, readFile, writeFile, rm } from 'fs/promises';
+import { dirname, join } from 'path';
+import { mockPathsDataRoot, mockNoPeers, mockNoPeerSync, mockTestIdentity } from '../lib/mockPathsDataRoot.js';
+
+// Two peers are simulated on one temp data root by swapping which document sits
+// in goals.json: the REAL deleteGoal writes it, the REAL dataSync snapshot and
+// merge carry it across, and no database or live peer is touched (#9816).
+const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-goal-delete-sync-' });
+vi.mock('../lib/fileUtils.js', async (original) => new Proxy(makeProxy(await original()), {
+ get: (target, key) => key === 'dataPath' ? (...parts) => join(tempRoot, ...parts) : target[key],
+}));
+vi.mock('./instances.js', async (importOriginal) => mockNoPeers({}, {
+ peerLogLabel: (await importOriginal()).peerLogLabel,
+ resolveEffectiveCategories: () => ({}),
+ updatePeer: async () => {},
+}));
+vi.mock('./instanceIdentity.js', () => mockTestIdentity());
+vi.mock('./sharing/peerSync.js', () => mockNoPeerSync({}, {
+ getOutboundCoverageForPeer: async () => ({ universe: new Set(), pipeline: new Set(), mediaCollections: new Set() }),
+}));
+vi.mock('./mediaJobQueue/index.js', () => ({ getJob: () => null }));
+vi.mock('./sharing/annotationIdentity.js', () => ({ resolveBucketSourceName: async () => 'Test' }));
+vi.mock('../lib/peerHttpClient.js', () => ({ peerFetch: vi.fn(() => { throw new Error('Unexpected network request'); }) }));
+vi.mock('./meatspaceCalendar.js', () => ({ getActivities: async () => [] }));
+
+const dataSync = await import('./dataSync.js');
+const goalService = await import('./identity/goals.js');
+const { PATHS } = await import('../lib/fileUtils.js');
+
+const goalsPath = join(PATHS.digitalTwin, 'goals.json');
+const read = async () => JSON.parse(await readFile(goalsPath, 'utf8'));
+const seed = async (doc) => {
+ await mkdir(dirname(goalsPath), { recursive: true });
+ await writeFile(goalsPath, JSON.stringify(doc));
+};
+const goal = (id, extra = {}) => ({
+ id, title: `Goal ${id}`, status: 'active', parentId: null, progress: 0,
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', ...extra,
+});
+const ids = (doc) => doc.goals.map((g) => g.id);
+
+// Run `action` as the peer whose document is `doc`; return that peer's new document.
+const asPeer = async (doc, action) => {
+ await seed(doc);
+ await action();
+ return read();
+};
+const DELETED_AT = '2026-01-05T09:00:00.000Z';
+const deleteOnPeer = (doc, goalId) => asPeer(doc, async () => {
+ vi.useFakeTimers({ toFake: ['Date'], now: new Date(DELETED_AT) });
+ await goalService.deleteGoal(goalId);
+ vi.useRealTimers();
+});
+const snapshotOf = async (doc) => {
+ await seed(doc);
+ const { data } = await dataSync.getSnapshot('goals');
+ return data;
+};
+const pull = (doc, remote) => asPeer(doc, () => dataSync.applyRemote('goals', remote));
+
+beforeEach(async () => {
+ await rm(tempRoot, { recursive: true, force: true });
+});
+afterEach(() => vi.useRealTimers());
+afterAll(cleanup);
+
+describe('goal deletion across snapshot-federated peers (#9816)', () => {
+ const shared = () => ({ goals: [goal('goal-example'), goal('goal-other', { progress: 40 })], updatedAt: '2026-01-01T00:00:00.000Z' });
+
+ it('keeps a deleted goal deleted on both peers, through repeated stale redelivery', async () => {
+ const staleB = shared();
+ const peerA = await deleteOnPeer(shared(), 'goal-example');
+ expect(ids(peerA)).toEqual(['goal-other']);
+ expect(peerA.goalTombstones).toEqual([{ id: 'goal-example', deletedAt: DELETED_AT }]);
+
+ // B was offline for the delete; A's snapshot carries the tombstone to it.
+ const peerB = await pull(staleB, await snapshotOf(peerA));
+ expect(peerB.goals).toEqual([goal('goal-other', { progress: 40 })]);
+ expect(peerB.goalTombstones).toEqual(peerA.goalTombstones);
+
+ // B's answer back, and B's pre-delete snapshot replayed any number of times,
+ // never bring the goal back to A.
+ const backOnA = await pull(peerA, await snapshotOf(peerB));
+ expect(ids(backOnA)).toEqual(['goal-other']);
+ const stale = await snapshotOf(staleB);
+ expect(ids(await pull(backOnA, stale))).toEqual(['goal-other']);
+ await seed(backOnA);
+ expect(await dataSync.applyRemote('goals', stale)).toEqual({ applied: false, count: 0 });
+ expect(await read()).toEqual(backOnA);
+ });
+
+ it('rejects a stale goal from an older peer that omits tombstones, and keeps the tombstone', async () => {
+ const peerA = await deleteOnPeer(shared(), 'goal-example');
+ const legacyPayload = { goals: shared().goals, updatedAt: '2026-01-01T00:00:00.000Z' };
+ expect(legacyPayload).not.toHaveProperty('goalTombstones');
+
+ const after = await pull(peerA, legacyPayload);
+ expect(ids(after)).toEqual(['goal-other']);
+ expect(after.goalTombstones).toEqual(peerA.goalTombstones);
+ });
+
+ it('lets a goal edited after the deletion win, and retires the tombstone', async () => {
+ const peerA = await deleteOnPeer(shared(), 'goal-example');
+ const editedOnB = shared();
+ editedOnB.goals[0] = goal('goal-example', { title: 'Edited on B', updatedAt: '2026-01-06T09:00:00.000Z' });
+
+ const merged = await pull(peerA, await snapshotOf(editedOnB));
+ expect(merged.goals.find((g) => g.id === 'goal-example')).toMatchObject({ title: 'Edited on B' });
+ expect(merged.goalTombstones).toBeUndefined();
+
+ // The converse hop: B receives A's already-retired list and keeps its edit.
+ const onB = await pull(editedOnB, await snapshotOf(merged));
+ expect(onB.goals.find((g) => g.id === 'goal-example')).toMatchObject({ title: 'Edited on B' });
+ });
+
+ it('keeps unrelated goals and re-parents a child edited on the offline peer', async () => {
+ const tree = () => ({
+ goals: [
+ goal('goal-root'),
+ goal('goal-parent', { parentId: 'goal-root' }),
+ goal('goal-child', { parentId: 'goal-parent' }),
+ goal('goal-other', { progress: 40 }),
+ ],
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ });
+ const peerA = await deleteOnPeer(tree(), 'goal-parent');
+ expect(peerA.goals.find((g) => g.id === 'goal-child').parentId).toBe('goal-root');
+
+ // B never saw the delete and kept working on the child after it happened.
+ const peerB = tree();
+ Object.assign(peerB.goals[2], { progress: 70, updatedAt: '2026-01-06T09:00:00.000Z' });
+ const onB = await pull(peerB, await snapshotOf(peerA));
+ expect(ids(onB)).toEqual(['goal-root', 'goal-child', 'goal-other']);
+ expect(onB.goals.find((g) => g.id === 'goal-child')).toMatchObject({ parentId: 'goal-root', progress: 70 });
+ expect(onB.goals.find((g) => g.id === 'goal-other').progress).toBe(40);
+
+ // A then adopts B's newer child; the deleted parent stays gone on both.
+ const onA = await pull(peerA, await snapshotOf(onB));
+ expect(ids(onA)).toEqual(['goal-root', 'goal-child', 'goal-other']);
+ expect(onA.goals.find((g) => g.id === 'goal-child')).toMatchObject({ parentId: 'goal-root', progress: 70 });
+ expect(onA.goalTombstones).toEqual(onB.goalTombstones);
+ });
+
+ it('loads and merges a legacy document without tombstones, adding the field only on a delete', async () => {
+ const legacy = shared();
+ const merged = await pull(legacy, { goals: [goal('goal-remote', { updatedAt: '2026-01-03T00:00:00.000Z' })] });
+ expect(ids(merged)).toEqual(['goal-example', 'goal-other', 'goal-remote']);
+ expect(merged).not.toHaveProperty('goalTombstones');
+ expect(await deleteOnPeer(merged, 'goal-remote')).toHaveProperty('goalTombstones', [{ id: 'goal-remote', deletedAt: DELETED_AT }]);
+ });
+});
diff --git a/server/services/identity/goalTombstones.js b/server/services/identity/goalTombstones.js
new file mode 100644
index 0000000000..72309918d6
--- /dev/null
+++ b/server/services/identity/goalTombstones.js
@@ -0,0 +1,118 @@
+/**
+ * Goal deletion tombstones for the `goals` snapshot category (#9816).
+ *
+ * The goals snapshot merges by union (a goal present on either peer survives),
+ * which cannot represent a delete: absence is not a signal, so the peer that
+ * still holds the goal re-adds it on the next sync. A deletion therefore leaves
+ * `{ id, deletedAt }` in the goals document itself (under `goalTombstones`,
+ * written inside the same serialized goals queue as the delete). The list rides
+ * every snapshot, unions in both directions, and suppresses a stale live copy.
+ *
+ * Rules, all inherited from `lib/tombstones.js`:
+ * - Timestamps parse to epoch ms; an unparseable stamp never wins.
+ * - A goal survives its tombstone only when its own live stamp (the newer of
+ * `createdAt` / `updatedAt`) is STRICTLY newer than `deletedAt` — i.e. it was
+ * edited or re-created after the deletion. That edit is the explicit
+ * "restoration" rule: a delete beats every copy that has not been touched
+ * since, and an edit made after it beats the delete and retires the
+ * tombstone so it cannot bounce back from a peer that has not seen the edit.
+ * - A legacy document with no `goalTombstones` field is an empty list. No
+ * migration invents past deletions, and the field is only written once a
+ * delete (or a peer's tombstone) puts something in it.
+ *
+ * Resurrection horizon: the list is capped at `DEFAULT_TOMBSTONE_LIMIT` (200)
+ * deletions, oldest dropped first. A peer that stays offline across more than
+ * that many later goal deletions can resurrect an old one — a bounded document
+ * is preferred over unbounded growth. An older (pre-#9816) receiver ignores the
+ * field entirely, so it cannot enforce a deletion until it is upgraded; an
+ * upgraded receiver keeps the tombstones it already holds when such a peer omits
+ * them.
+ */
+
+import { compareNewerWins, parseTsMs } from '../../lib/lwwTimestamp.js';
+import {
+ isTombstoned,
+ pruneTombstones,
+ recordTombstone,
+ supersedingTimestamp,
+ tombstoneTimestamp,
+} from '../../lib/tombstones.js';
+
+/** Top-level `goals.json` field holding `{ id, deletedAt }` goal tombstones. */
+export const GOAL_TOMBSTONES_KEY = 'goalTombstones';
+
+const KEY_FIELD = 'id';
+
+/**
+ * The newer of a goal's `createdAt` and `updatedAt` — the instant a deletion has
+ * to beat. Null for a legacy goal carrying neither stamp.
+ */
+export function goalLiveStamp(goal) {
+ const { createdAt, updatedAt } = goal || {};
+ if (compareNewerWins(createdAt, updatedAt)) return createdAt;
+ return parseTsMs(updatedAt) === null ? null : updatedAt;
+}
+
+/**
+ * Record that `goal` was deleted from `doc` (the goals document). The stamp is
+ * kept past the goal's own live stamp so the deletion wins over the copy the
+ * user was looking at even when a peer that last edited it ran a clock ahead.
+ * Mutates `doc`; call it inside the goals write queue.
+ */
+export function tombstoneGoal(doc, goal, now = new Date().toISOString()) {
+ if (typeof goal?.id !== 'string' || !goal.id) return;
+ const deletedAt = supersedingTimestamp(goalLiveStamp(goal), now);
+ doc[GOAL_TOMBSTONES_KEY] = recordTombstone(doc[GOAL_TOMBSTONES_KEY], goal.id, { keyField: KEY_FIELD, deletedAt });
+}
+
+/**
+ * Apply a tombstone list to a goals array. Pure: returns new arrays and never
+ * mutates its inputs.
+ *
+ * 1. Goals the tombstones cover (and that were not edited after the deletion)
+ * are removed.
+ * 2. Their children are reparented to the deleted goal's own parent (walking up
+ * through any other removed goal) — the same cleanup `deleteGoal` performs
+ * locally, replayed when a deletion arrives from a peer. The reparent is
+ * stamped deterministically (`supersedingTimestamp` over the child's own
+ * stamp, anchored on the tombstone) so every peer computes the same record
+ * and a replay settles instead of ping-ponging. It only runs when this side
+ * still holds the removed goal's record: without it the parent is unknown and
+ * the child is left as it is (a missing parent already renders as a root).
+ * 3. Tombstones a surviving goal has superseded are pruned.
+ *
+ * @returns {{ goals: object[], tombstones: object[] }}
+ */
+export function reconcileGoalTombstones(goals, tombstones) {
+ const list = Array.isArray(goals) ? goals : [];
+ const removed = new Map();
+ const survivors = [];
+ for (const goal of list) {
+ if (typeof goal?.id === 'string' && goal.id && isTombstoned(tombstones, goal.id, goalLiveStamp(goal), KEY_FIELD)) {
+ removed.set(goal.id, goal);
+ } else {
+ survivors.push(goal);
+ }
+ }
+
+ const reparented = removed.size === 0 ? survivors : survivors.map((goal) => {
+ const parent = removed.get(goal?.parentId);
+ if (!parent) return goal;
+ // Nearest ancestor still alive; `seen` also stops a corrupt parent cycle.
+ const seen = new Set([goal.id, goal.parentId]);
+ let nextParentId = parent.parentId || null;
+ while (nextParentId && removed.has(nextParentId) && !seen.has(nextParentId)) {
+ seen.add(nextParentId);
+ nextParentId = removed.get(nextParentId).parentId || null;
+ }
+ if (nextParentId && seen.has(nextParentId)) nextParentId = null;
+ const deletedAt = tombstoneTimestamp(tombstones, goal.parentId, KEY_FIELD);
+ return { ...goal, parentId: nextParentId, updatedAt: supersedingTimestamp(goal.updatedAt, deletedAt) };
+ });
+
+ const stamps = reparented.map((goal) => ({ id: goal?.id, stamp: goalLiveStamp(goal) }));
+ return {
+ goals: reparented,
+ tombstones: pruneTombstones(tombstones, stamps, { keyField: KEY_FIELD, timestampField: 'stamp' }),
+ };
+}
diff --git a/server/services/identity/goalTombstones.test.js b/server/services/identity/goalTombstones.test.js
new file mode 100644
index 0000000000..6fc36cf2b8
--- /dev/null
+++ b/server/services/identity/goalTombstones.test.js
@@ -0,0 +1,62 @@
+import { describe, it, expect } from 'vitest';
+import { goalLiveStamp, reconcileGoalTombstones, tombstoneGoal } from './goalTombstones.js';
+
+const goal = (id, parentId = null, updatedAt = '2026-01-01T00:00:00.000Z') => ({ id, parentId, updatedAt });
+const tombstone = (id, deletedAt = '2026-01-05T00:00:00.000Z') => ({ id, deletedAt });
+
+// The cases the offline-peer cycle in goalDeletionSync.test.js cannot reach
+// cheaply: ancestor chains, a corrupt cycle, and a parent record this side lost.
+describe('reconcileGoalTombstones', () => {
+ it('re-parents a survivor to the nearest ancestor that is still alive', () => {
+ const { goals } = reconcileGoalTombstones(
+ [goal('root'), goal('mid', 'root'), goal('leaf', 'mid'), goal('child', 'leaf')],
+ [tombstone('mid'), tombstone('leaf')],
+ );
+ expect(goals.map((g) => g.id)).toEqual(['root', 'child']);
+ expect(goals[1]).toMatchObject({ parentId: 'root', updatedAt: '2026-01-05T00:00:00.000Z' });
+ });
+
+ it('terminates on a corrupt parent cycle and detaches to the root', () => {
+ const { goals } = reconcileGoalTombstones(
+ [goal('a', 'b'), goal('b', 'a'), goal('child', 'a')],
+ [tombstone('a'), tombstone('b')],
+ );
+ expect(goals).toEqual([expect.objectContaining({ id: 'child', parentId: null })]);
+ });
+
+ it('leaves a child alone when the deleted parent record is not held here', () => {
+ const child = goal('child', 'gone');
+ const { goals, tombstones } = reconcileGoalTombstones([child], [tombstone('gone')]);
+ expect(goals).toEqual([child]);
+ expect(tombstones).toEqual([tombstone('gone')]);
+ });
+
+ it('stamps a re-parent past a child that was edited after the deletion', () => {
+ const { goals } = reconcileGoalTombstones(
+ [goal('parent'), goal('child', 'parent', '2026-01-06T00:00:00.000Z')],
+ [tombstone('parent')],
+ );
+ expect(goals).toEqual([expect.objectContaining({ parentId: null, updatedAt: '2026-01-06T00:00:00.001Z' })]);
+ });
+});
+
+describe('tombstoneGoal', () => {
+ it('stamps the deletion past a goal edited by a peer whose clock ran ahead', () => {
+ const doc = { goals: [] };
+ tombstoneGoal(doc, { id: 'g', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-03-01T00:00:00.000Z' }, '2026-02-01T00:00:00.000Z');
+ expect(doc.goalTombstones).toEqual([tombstone('g', '2026-03-01T00:00:00.001Z')]);
+ });
+
+ it('ignores a goal without an id rather than writing a keyless tombstone', () => {
+ const doc = {};
+ tombstoneGoal(doc, { title: 'No id' });
+ expect(doc).toEqual({});
+ });
+});
+
+describe('goalLiveStamp', () => {
+ it('is the newer of createdAt and updatedAt, and null when neither parses', () => {
+ expect(goalLiveStamp({ createdAt: '2026-02-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' })).toBe('2026-02-01T00:00:00.000Z');
+ expect(goalLiveStamp({ createdAt: 'nope' })).toBeNull();
+ });
+});
diff --git a/server/services/identity/goals.js b/server/services/identity/goals.js
index fec85da65e..24662959fd 100644
--- a/server/services/identity/goals.js
+++ b/server/services/identity/goals.js
@@ -17,6 +17,7 @@ import {
mutateGoals
} from './store.js';
import { applyFreshTimeHorizons, deriveLongevity } from './longevity.js';
+import { tombstoneGoal } from './goalTombstones.js';
/**
* Read the longevity snapshot with `timeHorizons` re-derived against today (#4122).
@@ -393,7 +394,10 @@ export async function deleteGoal(goalId) {
}
goals.goals.splice(idx, 1);
- goals.updatedAt = new Date().toISOString();
+ // Leave a tombstone so a peer that still holds the goal drops it on sync
+ // instead of sending it back (#9816). Same document, same write queue.
+ tombstoneGoal(goals, deletedGoal, now);
+ goals.updatedAt = now;
return true;
});
}