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: tombstone deleted social accounts so a peer sync can't resurrect them (#3532)
[._.]/ Adam Eivye857585e2dc0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b55e8bb671..67ff28727b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -148,3 +148,5 @@- **[issue-3520] The goal progress slider no longer sits on a percentage the server never stored.** Releasing the slider fired the update and left the dragged number on screen, and the only thing that ever corrected it was an effect that re-synced the slider the instant the drag ended — so on a normal save the percentage visibly snapped back to the old value while the request was still in flight and then jumped forward again when the refresh landed, and on a rejected save it was only that same flap that happened to leave the right number showing. Moving the slider with the keyboard never committed at all: arrow keys never produce a mouse release, so the value the user set stayed on screen, unsaved, until the panel was closed and re-opened — the reported symptom, reached by a different route than the drag. The slider now keeps the value it committed until the stored percentage actually changes underneath it, and resets to what is stored the moment the update reports it failed; the update handler reports that outcome rather than throwing it away. Arrow, Home/End and moving focus off the track all commit like a mouse release does. Releasing again on a percentage that is already saved or already on its way — a touch release fires both a touch end and a synthesized mouse release, and a blur can follow either — no longer sends it a second time, while a percentage the user sets *while* a save is still in flight is held and sent as soon as that save answers, so the value on screen is always one that was actually sent. The "Progress" label is now paired to the slider, so screen readers and click-to-focus find it.- **[issue-3533] Deleting a Twin persona no longer leaves it to be resurrected by your other machines.** Peer sync merged the personas add-only, so whichever machine still had a persona you deleted put it straight back into `meta.json` on the next cycle — and every cycle after that. A delete now records a tombstone on the persona id, and those tombstones union in both directions, so the machine that still holds the persona drops it too instead of the deleting machine merely defending itself against a peer that keeps re-sending. The id is the right key here (unlike identity documents, which tombstone on filename) because a persona id is minted once by the machine that created it and then travels with the record. Personas also now take the more recently edited copy on a collision rather than always keeping the local one: that is what lets a persona you edited after another machine deleted it survive — the newer stamp supersedes the tombstone, the stale tombstone is dropped, and a third machine holding an old copy can no longer reap the persona against a delete that has since been overruled. If the persona a peer's delete removes was the active one, the active-persona pointer is cleared rather than left dangling. A peer running an older build ignores the new field and keeps offering its copy; the upgraded machine still refuses it, so nothing is corrupted while the two versions differ.++- **[issue-3532] Deleting a social account from your Digital Twin no longer leaves your other machines to put it back.** Peer sync merged the account list add-only: whichever machine still had the account re-inserted it, so an account you removed on one machine reappeared on the next sync cycle, every cycle. A delete now records a tombstone on the account's id, and those tombstones union in both directions — so the machine that still holds the account drops it, instead of the deleting machine merely defending itself while the peer keeps re-sending. The id is the right key here, unlike the identity documents that tombstone on filename: an account id is minted once by the machine that created the account and then travels verbatim between peers, and re-adding the same handle after a delete mints a fresh id, which a platform-and-handle key would have wrongly kept suppressed. An account edited after another machine deleted it also survives — the edit is the user's later word, and the now-obsolete tombstone is dropped so it cannot bounce back from a peer that has not caught up. A peer running an older build simply ignores the new field and keeps offering its copy; the upgraded machine still refuses it, so nothing is corrupted while the two versions differ, and no migration is needed because a file without the field reads as an empty list.diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.jsindex e5ebc1490e..7ee78112f0 100644--- a/server/services/digital-twin-sync.js+++ b/server/services/digital-twin-sync.js@@ -26,6 +26,7 @@* - autobiography/ — stories union by id (LWW); config (the prompt* schedule) is NOT synced — it's machine-local* - social-accounts.json — the user's own social accounts, union by id (LWW)+ * MINUS anything either side tombstoned (see below)** Merge philosophy mirrors the rest of dataSync: union semantics, no data is* ever lost, and every field is key-presence guarded so an OLDER peer that only@@ -46,6 +47,9 @@* Personas carry the same tombstone (#3533) as `meta.deletedPersonas`, keyed on* the persona id — a persona lives only in meta.json, so the merge alone* completes the delete with no file to reap.+ *+ * Social accounts carry the same machinery on `deletedAccounts`, keyed on the+ * account id (#3532) — see mergeSocialAccounts.*/import crypto from 'crypto';@@ -583,11 +587,35 @@ export function mergeMeta(local, remote) {return { merged, changed };}+// Social-account tombstones (#3532) key on the account id, NOT a platform/handle+// natural key: the id is minted once by whichever machine created the account+// and then travels verbatim as the `accounts` map key, so every peer agrees on+// it — and re-adding the same handle after a delete mints a FRESH id, which a+// natural key would wrongly suppress.+const ACCOUNT_TOMBSTONE_OPTS = { keyField: 'id' };++/**+ * The instant an account was last asserted to EXIST — its creation stamp, or a+ * later edit. A delete only wins over an account older than the delete: an edit+ * made after another machine deleted it is the user's latest word (#3532).+ */+function accountLiveStamp(account) {+ return newerStamp(account?.updatedAt, account?.createdAt);+}+/*** Merge the user's own social accounts (social-accounts.json: `{ accounts: { id:- * {...} } }`). Accounts union by id, LWW on updatedAt — an account added on- * either machine survives, and the more-recently-edited copy wins a collision.+ * {...} }, deletedAccounts: [{ id, deletedAt }] }`). Accounts union by id, LWW on+ * updatedAt — an account added on either machine survives, and the+ * more-recently-edited copy wins a collision.* Key-presence guarded: a peer that sends no socialAccounts can't blank local.+ *+ * DELETES ride the `deletedAccounts` tombstone list (#3532), which unions in+ * BOTH directions before the account union is filtered — so a delete performed+ * on either machine converges: the deleting side stops resurrecting the account,+ * and the side that still has it drops it. An account whose own live stamp is+ * strictly newer than the tombstone supersedes it, and that now-obsolete+ * tombstone is pruned so it can't bounce back from a peer that hasn't caught up.*/export function mergeSocialAccounts(local, remote) {if (!isPlainObject(remote)) return { merged: local, changed: false };@@ -595,15 +623,31 @@ export function mergeSocialAccounts(local, remote) {const lAcc = isPlainObject(local.accounts) ? local.accounts : {};const rAcc = isPlainObject(remote.accounts) ? remote.accounts : {};+ const { merged: tombstones } = mergeTombstones(local.deletedAccounts, remote.deletedAccounts, ACCOUNT_TOMBSTONE_OPTS);+const accounts = { ...lAcc };- let changed = false;for (const [id, rv] of Object.entries(rAcc)) {if (!isPlainObject(rv)) continue;const lv = accounts[id];- if (!isPlainObject(lv)) { accounts[id] = rv; changed = true; continue; }- if ((rv.updatedAt || '') > (lv.updatedAt || '')) { accounts[id] = rv; changed = true; }+ if (!isPlainObject(lv)) { accounts[id] = rv; continue; }+ if ((rv.updatedAt || '') > (lv.updatedAt || '')) accounts[id] = rv;}- return { merged: { ...local, accounts }, changed };+ for (const [id, account] of Object.entries(accounts)) {+ if (isTombstoned(tombstones, id, accountLiveStamp(account), 'id')) delete accounts[id];+ }++ // Prune against the same live stamp the filter used, or an account kept alive+ // by an edit would leave its tombstone behind to retry on every cycle.+ const survivors = Object.entries(accounts).map(([id, account]) => ({ id, createdAt: accountLiveStamp(account) }));+ const deletedAccounts = pruneTombstones(tombstones, survivors, { ...ACCOUNT_TOMBSTONE_OPTS, timestampField: 'createdAt' });++ // The account map is rebuilt from the two sides' own objects, so identity+ // comparison catches an add, a replacement, AND a reap.+ const localIds = Object.keys(lAcc);+ const changed = localIds.length !== Object.keys(accounts).length+ || localIds.some((id) => lAcc[id] !== accounts[id])+ || !tombstonesEqual(deletedAccounts, normalizeTombstones(local.deletedAccounts, 'id'), 'id');+ return { merged: { ...local, accounts, deletedAccounts }, changed };}/**diff --git a/server/services/socialAccounts.js b/server/services/socialAccounts.jsindex 9b06c58af7..c79504433c 100644--- a/server/services/socialAccounts.js+++ b/server/services/socialAccounts.js@@ -13,9 +13,14 @@ import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import EventEmitter from 'events';import { PATHS, createCachedStore } from '../lib/fileUtils.js';+import { recordTombstone } from '../lib/tombstones.js';const DATA_FILE = join(PATHS.digitalTwin, 'social-accounts.json');-const store = createCachedStore(DATA_FILE, { accounts: {} }, { context: 'socialAccounts' });+// `deletedAccounts` holds `{ id, deletedAt }` tombstones for accounts the user+// removed (#3532). Peer sync unions accounts add-only, so without them a machine+// that still has the account re-adds it forever. No migration is needed: an+// existing file simply has no key, and every reader treats that as an empty list.+const store = createCachedStore(DATA_FILE, { accounts: {}, deletedAccounts: [] }, { context: 'socialAccounts' });export const socialAccountEvents = new EventEmitter();@@ -242,6 +247,13 @@ export async function deleteAccount(id) {if (!data.accounts[id]) return data;account = data.accounts[id];delete data.accounts[id];+ // Tombstone the id so peer sync — which unions accounts add-only — can't+ // resurrect it from a machine that still has it, and so the delete+ // PROPAGATES to that machine rather than only being defended here (#3532).+ // The account id is the right key: unlike Digital Twin document ids it is+ // minted once by whichever machine created the account and then travels+ // verbatim as the `accounts` map key, so every peer agrees on it.+ data.deletedAccounts = recordTombstone(data.deletedAccounts, id, { keyField: 'id' });return data;});diff --git a/server/services/socialAccounts.tombstone.test.js b/server/services/socialAccounts.tombstone.test.jsnew file mode 100644index 0000000000..94b464a142--- /dev/null+++ b/server/services/socialAccounts.tombstone.test.js@@ -0,0 +1,165 @@+/**+ * End-to-end cover for the deleted-social-account tombstone (#3532): an account+ * the user deletes must stay deleted across a peer sync with a machine that+ * still has it, the delete must PROPAGATE to that machine, and re-adding the+ * same handle afterwards must not be suppressed.+ *+ * Exercises the real disk path (social-accounts.json) with PATHS pointed at a+ * temp dir, so the service's cached store, the merge, and the sync apply all run.+ */++import { describe, it, expect, beforeEach, afterAll } from 'vitest';+import { rmSync } from 'fs';+import { join } from 'path';+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++// socialAccounts.js and digital-twin-sync.js both capture PATHS.digitalTwin at+// module load, so the root is fixed for the whole file and per-test isolation+// comes from wiping the dir + the store cache in beforeEach.+const tempRoot = createTempDataRoot('portos-social-tombstone-');+const twinDir = join(tempRoot, 'digital-twin');++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makePathsProxy(actual, {+ dataRoot: tempRoot,+ extraOverrides: (root) => ({ digitalTwin: join(root, 'digital-twin') }),+ });+});++const { createAccount, updateAccount, deleteAccount, getAllAccounts, loadAccounts, invalidateCache } =+ await import('./socialAccounts.js');+const { applyDigitalTwinRemote, getDigitalTwinSnapshot, mergeSocialAccounts } = await import('./digital-twin-sync.js');++const newAccount = () => createAccount({ platform: 'github', username: 'example-user' });++// createAccount returns `{ id, ...account }`; on disk the id is the map key only.+const stripId = ({ id, ...rest }) => rest;++/** The snapshot a peer that still holds the account would ship. */+const peerSnapshotWith = (account) => ({+ socialAccounts: { accounts: { [account.id]: stripId(account) }, deletedAccounts: [] },+});++const accountIds = async () => (await getAllAccounts()).map((a) => a.id);+const tombstoneIds = async () => ((await loadAccounts()).deletedAccounts || []).map((t) => t.id);++beforeEach(() => {+ rmSync(twinDir, { recursive: true, force: true });+ invalidateCache();+});++afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));++describe('social account tombstones (#3532)', () => {+ it('records a tombstone on delete and keeps the account deleted through a peer sync', async () => {+ const created = await newAccount();+ const peer = peerSnapshotWith(created);++ expect(await deleteAccount(created.id)).toBe(true);+ expect(await accountIds()).not.toContain(created.id);+ expect(await tombstoneIds()).toEqual([created.id]);++ // The peer still has the account and ships it back — the pre-#3532 bug.+ await applyDigitalTwinRemote(peer);+ expect(await accountIds()).not.toContain(created.id);++ // …and it stays deleted on every subsequent cycle, not just the first.+ await applyDigitalTwinRemote(peer);+ expect(await accountIds()).not.toContain(created.id);+ expect(await tombstoneIds()).toEqual([created.id]);+ });++ it('ships tombstones in the snapshot so peers can see the delete', async () => {+ const created = await newAccount();+ await deleteAccount(created.id);++ const { data } = await getDigitalTwinSnapshot();+ expect(data.socialAccounts.deletedAccounts.map((t) => t.id)).toEqual([created.id]);+ expect(Object.keys(data.socialAccounts.accounts)).not.toContain(created.id);+ });++ it("propagates a peer's delete: removes the local account entry", async () => {+ const created = await newAccount();++ const { applied } = await applyDigitalTwinRemote({+ socialAccounts: {+ accounts: {},+ deletedAccounts: [{ id: created.id, deletedAt: new Date(Date.now() + 60_000).toISOString() }],+ },+ });++ expect(applied).toBe(true);+ expect(await accountIds()).not.toContain(created.id);+ expect(await tombstoneIds()).toEqual([created.id]);+ });++ it('does not suppress an account re-added after the delete', async () => {+ const created = await newAccount();+ await deleteAccount(created.id);+ const staleTombstones = (await loadAccounts()).deletedAccounts;+ expect(staleTombstones).toHaveLength(1);++ // Re-adding the same handle mints a FRESH id, so a natural (platform+handle)+ // key would have wrongly suppressed it — the id key does not.+ const readded = await newAccount();+ expect(readded.id).not.toBe(created.id);++ // A peer that has not seen the re-add still ships the old tombstone.+ await applyDigitalTwinRemote({ socialAccounts: { accounts: {}, deletedAccounts: staleTombstones } });++ expect(await accountIds()).toContain(readded.id);+ expect(await tombstoneIds()).toEqual([created.id]);+ });++ it('keeps an account edited here after another machine deleted it, and drops the stale tombstone', async () => {+ const created = await newAccount();+ const edited = await updateAccount(created.id, { username: 'renamed-user' });++ // The peer's delete predates our edit, so the edit is the user's last word.+ const deletedAt = new Date(Date.parse(edited.updatedAt) - 1_000).toISOString();+ await applyDigitalTwinRemote({ socialAccounts: { accounts: {}, deletedAccounts: [{ id: created.id, deletedAt }] } });++ expect(await accountIds()).toContain(created.id);+ expect(await tombstoneIds()).toEqual([]);+ });++ it('still accepts an account the peer has that was never deleted here', async () => {+ await applyDigitalTwinRemote({+ socialAccounts: {+ accounts: { 'peer-1': { platform: 'x', username: 'example-user', updatedAt: '2026-01-01T00:00:00.000Z' } },+ deletedAccounts: [],+ },+ });+ expect(await accountIds()).toContain('peer-1');+ });+});++describe('mergeSocialAccounts tombstone semantics (#3532)', () => {+ const T1 = '2026-01-01T00:00:00.000Z';+ const T2 = '2026-02-01T00:00:00.000Z';++ it('unions tombstones in both directions and reaps the covered account', () => {+ const local = { accounts: { a1: { username: 'alice', createdAt: T1, updatedAt: T1 } }, deletedAccounts: [] };+ const remote = { accounts: {}, deletedAccounts: [{ id: 'a1', deletedAt: T2 }] };++ const { merged, changed } = mergeSocialAccounts(local, remote);+ expect(changed).toBe(true);+ expect(merged.accounts).toEqual({});+ expect(merged.deletedAccounts).toEqual([{ id: 'a1', deletedAt: T2 }]);+ });++ it('reports no change when neither the accounts nor the tombstones move', () => {+ const local = { accounts: { a1: { username: 'alice', updatedAt: T2 } }, deletedAccounts: [{ id: 'a2', deletedAt: T1 }] };+ const remote = { accounts: { a1: { username: 'older', updatedAt: T1 } }, deletedAccounts: [{ id: 'a2', deletedAt: T1 }] };+ expect(mergeSocialAccounts(local, remote).changed).toBe(false);+ });++ it('treats an older peer that sends no deletedAccounts as an empty list, not a clear', () => {+ const local = { accounts: {}, deletedAccounts: [{ id: 'a1', deletedAt: T1 }] };+ const { merged, changed } = mergeSocialAccounts(local, { accounts: { a1: { username: 'alice' } } });+ expect(changed).toBe(false);+ expect(merged.deletedAccounts).toEqual([{ id: 'a1', deletedAt: T1 }]);+ expect(merged.accounts).toEqual({});+ });+});