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: tombstone deleted autobiography stories so a peer sync can't resurrect them (#3531)

[._.]/ Adam Eivyb858600d7a8f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 67ff28727b..84fa8c6692 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -150,3 +150,5 @@
- **[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.
+
+- **[issue-3531] Deleting an autobiography life story no longer leaves it to be resurrected by your other machines.** Peer sync merged the stories add-only, so a story you deleted on one machine was put straight back by any machine that still had it, on the next sync cycle and every cycle after that — there was no way to permanently remove a story you had written. A delete now records a tombstone against the story, and those tombstones union in both directions, so the machine that still holds the story drops it too rather than the deleting machine merely defending itself while the peer keeps re-sending. The tombstone keys on the story's own id, which is safe here in a way it was not for identity documents: a story id is minted once when the story is written and travels with the record, so every machine knows the same story under the same id. A story that was edited after another machine deleted it is kept rather than reaped — that edit is the user's later word on it — and the now-obsolete tombstone is dropped so it cannot bounce back from a peer that has not seen the edit. 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. Separately, a fresh install's first story read handed back the shared default record by reference, so anything written into it lingered in memory for the next reader; that record is now copied per read.
diff --git a/server/services/autobiography.js b/server/services/autobiography.js
index f5b06abe0f..f6858bba51 100644
--- a/server/services/autobiography.js
+++ b/server/services/autobiography.js
@@ -10,6 +10,7 @@
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { recordTombstone } from '../lib/tombstones.js';
import { addNotification, NOTIFICATION_TYPES, exists as notificationExists } from './notifications.js';
import { getActiveProvider, getProviderById } from './providers.js';
import { callProviderAISimple, parseLLMJSON } from '../lib/aiProvider.js';
@@ -164,12 +165,20 @@ const DEFAULT_CONFIG = {
const DEFAULT_DATA = {
version: 1,
stories: [],
- usedPrompts: []
+ usedPrompts: [],
+ // Tombstones for stories the user deleted (#3531) — peer sync unions stories
+ // add-only, so without these a machine that still holds the story resurrects
+ // it on the next cycle. Keyed on the story `id` (see deleteStory).
+ deletedStories: []
};
async function loadStories() {
await ensureDir(DATA_DIR);
- return readJSONFile(STORIES_FILE, DEFAULT_DATA);
+ // Deep clone the default — readJSONFile hands the fallback back BY REFERENCE
+ // on a missing file, so `data.stories.push(...)` / the deletedStories rewrite
+ // below would otherwise mutate the module-level DEFAULT_DATA and leak the
+ // previous caller's stories into the next fresh-install read.
+ return readJSONFile(STORIES_FILE, structuredClone(DEFAULT_DATA));
}
async function saveStories(data) {
@@ -322,6 +331,14 @@ export async function updateStory(storyId, content) {
/**
* Delete a story
+ *
+ * Records a `deletedStories` tombstone alongside the removal so peer sync —
+ * which unions stories ADD-ONLY by id — can't resurrect it from a machine that
+ * still has the story, and so the delete propagates to that machine (#3531).
+ * The tombstone keys on the story `id` rather than a derived natural key: story
+ * ids are minted once by `saveStory` and travel with the record through sync
+ * (`mergeAutobiographyStories` unions on `id`), so the same logical story
+ * carries the same id on every peer.
*/
export async function deleteStory(storyId) {
const data = await loadStories();
@@ -329,6 +346,7 @@ export async function deleteStory(storyId) {
if (idx === -1) return null;
const removed = data.stories.splice(idx, 1)[0];
+ data.deletedStories = recordTombstone(data.deletedStories, removed.id, { keyField: 'id' });
await saveStories(data);
console.log(`📖 Autobiography story deleted: ${removed.themeLabel}`);
diff --git a/server/services/autobiography.tombstone.test.js b/server/services/autobiography.tombstone.test.js
new file mode 100644
index 0000000000..b83c4f37a8
--- /dev/null
+++ b/server/services/autobiography.tombstone.test.js
@@ -0,0 +1,156 @@
+/**
+ * End-to-end cover for the deleted-autobiography-story tombstone (#3531): a
+ * story the user deletes must stay deleted across a peer sync with a machine
+ * that still has it, and the delete must PROPAGATE to that machine.
+ *
+ * Exercises the real disk paths (autobiography/stories.json) with PATHS pointed
+ * at a temp dir, so `deleteStory`, the snapshot, and the merge all run for real.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { rmSync } from 'fs';
+import { join } from 'path';
+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+// `autobiography.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 in beforeEach.
+const tempRoot = createTempDataRoot('portos-autobio-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') }),
+ });
+});
+
+// The prompt scheduler is the only reason autobiography.js touches these — none
+// of the tombstone paths call an AI provider or raise a notification.
+vi.mock('./notifications.js', () => ({
+ addNotification: vi.fn(),
+ NOTIFICATION_TYPES: { AUTOBIOGRAPHY_PROMPT: 'autobiography_prompt' },
+ exists: vi.fn(() => false),
+}));
+
+const { saveStory, updateStory, deleteStory, getStories } = await import('./autobiography.js');
+const { applyDigitalTwinRemote, getDigitalTwinSnapshot, mergeAutobiographyStories } = await import('./digital-twin-sync.js');
+
+const storiesFile = join(twinDir, 'autobiography', 'stories.json');
+const newStory = (content = 'An example childhood memory.') => saveStory({ promptId: 'childhood-0', content });
+
+const readStoriesFile = async () => {
+ const { readJSONFile } = await import('../lib/fileUtils.js');
+ return readJSONFile(storiesFile, null);
+};
+
+/** The snapshot a peer that still holds the story would ship. */
+const peerSnapshotWith = (stories) => ({ autobiography: { stories: { version: 1, stories, usedPrompts: [], deletedStories: [] } } });
+
+beforeEach(() => {
+ rmSync(twinDir, { recursive: true, force: true });
+});
+
+afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));
+
+describe('autobiography story tombstones (#3531)', () => {
+ it('records a tombstone on delete and keeps the story deleted through a peer sync', async () => {
+ const story = await newStory();
+ const peer = peerSnapshotWith([story]);
+
+ expect(await deleteStory(story.id)).toMatchObject({ id: story.id });
+ const afterDelete = await readStoriesFile();
+ expect(afterDelete.stories).toEqual([]);
+ expect(afterDelete.deletedStories.map((t) => t.id)).toEqual([story.id]);
+
+ // The peer still has the story and ships it back — the pre-#3531 bug.
+ await applyDigitalTwinRemote(peer);
+ expect(await getStories()).toEqual([]);
+
+ // …and it stays deleted on every subsequent cycle, not just the first.
+ await applyDigitalTwinRemote(peer);
+ expect(await getStories()).toEqual([]);
+ });
+
+ it('ships tombstones in the snapshot so peers can see the delete', async () => {
+ const story = await newStory();
+ await deleteStory(story.id);
+
+ const { data } = await getDigitalTwinSnapshot();
+ expect(data.autobiography.stories.deletedStories.map((t) => t.id)).toEqual([story.id]);
+ expect(data.autobiography.stories.stories).toEqual([]);
+ });
+
+ it('propagates a peer\'s delete: removes the story this machine still has', async () => {
+ const story = await newStory();
+ expect(await getStories()).toHaveLength(1);
+
+ const { applied } = await applyDigitalTwinRemote({
+ autobiography: {
+ stories: {
+ stories: [],
+ deletedStories: [{ id: story.id, deletedAt: new Date(Date.now() + 60_000).toISOString() }],
+ },
+ },
+ });
+
+ expect(applied).toBe(true);
+ expect(await getStories()).toEqual([]);
+ expect((await readStoriesFile()).deletedStories.map((t) => t.id)).toEqual([story.id]);
+ });
+
+ it('keeps a story edited here after another machine deleted it, and drops the stale tombstone', async () => {
+ const story = await newStory();
+ const edited = await updateStory(story.id, 'A longer, revised memory.');
+ expect(edited.updatedAt).toBeTruthy();
+
+ // 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({
+ autobiography: { stories: { stories: [], deletedStories: [{ id: story.id, deletedAt }] } },
+ });
+
+ expect((await getStories()).map((s) => s.id)).toEqual([story.id]);
+ expect((await readStoriesFile()).deletedStories).toEqual([]);
+ });
+
+ it('still accepts a story the peer has that was never deleted here', async () => {
+ await applyDigitalTwinRemote(peerSnapshotWith([
+ { id: 'peer-story-1', themeId: 'family', content: 'Example', createdAt: '2026-01-01T00:00:00.000Z' },
+ ]));
+ expect((await getStories()).map((s) => s.id)).toEqual(['peer-story-1']);
+ });
+});
+
+describe('mergeAutobiographyStories tombstones (#3531)', () => {
+ const deletedAt = '2026-02-01T00:00:00.000Z';
+
+ it('unions tombstones in both directions', () => {
+ const local = { stories: [], deletedStories: [{ id: 's1', deletedAt }] };
+ const remote = { stories: [], deletedStories: [{ id: 's2', deletedAt }] };
+ expect(mergeAutobiographyStories(local, remote).merged.deletedStories.map((t) => t.id).sort()).toEqual(['s1', 's2']);
+ expect(mergeAutobiographyStories(remote, local).merged.deletedStories.map((t) => t.id).sort()).toEqual(['s1', 's2']);
+ });
+
+ it('reaps a story a peer tombstoned after it was created', () => {
+ const local = { stories: [{ id: 's1', createdAt: '2026-01-01T00:00:00.000Z' }], deletedStories: [] };
+ const { merged, changed } = mergeAutobiographyStories(local, { stories: [], deletedStories: [{ id: 's1', deletedAt }] });
+ expect(merged.stories).toEqual([]);
+ expect(changed).toBe(true);
+ });
+
+ it('does not rewrite the file when the peer only re-sends a story we tombstoned', () => {
+ const local = { stories: [], usedPrompts: [], deletedStories: [{ id: 's1', deletedAt }] };
+ const remote = { stories: [{ id: 's1', createdAt: '2026-01-01T00:00:00.000Z' }], usedPrompts: [], deletedStories: [] };
+ expect(mergeAutobiographyStories(local, remote).changed).toBe(false);
+ });
+
+ it('tolerates a legacy peer that sends no tombstone key at all', () => {
+ const local = { stories: [{ id: 's1', createdAt: '2026-01-01T00:00:00.000Z' }], usedPrompts: [] };
+ const { merged, changed } = mergeAutobiographyStories(local, { stories: [{ id: 's1', createdAt: '2026-01-01T00:00:00.000Z' }], usedPrompts: [] });
+ expect(changed).toBe(false);
+ expect(merged.stories.map((s) => s.id)).toEqual(['s1']);
+ expect(merged.deletedStories).toEqual([]);
+ });
+});
diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.js
index 7ee78112f0..49d36efd04 100644
--- a/server/services/digital-twin-sync.js
+++ b/server/services/digital-twin-sync.js
@@ -23,7 +23,8 @@
* - *.md documents — content shipped by filename, ADD-ONLY on the
* receiver (a local doc is never overwritten) MINUS
* anything either side tombstoned (see below)
- * - autobiography/ — stories union by id (LWW); config (the prompt
+ * - autobiography/ — stories union by id (LWW) MINUS anything either
+ * side tombstoned (see below); 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)
@@ -39,8 +40,10 @@
* list that unions in BOTH directions, suppressing the document metadata entry
* and reaping the `.md` file on whichever peer still has it. A document
* re-created after a delete carries a `createdAt` that supersedes the tombstone,
- * so it is never permanently suppressed. This stays additive too: an older peer
- * simply drops the unknown `deletedDocuments` key (Zod strips it), keeps
+ * so it is never permanently suppressed. Autobiography stories carry the same
+ * mechanism (#3531) as `deletedStories` inside autobiography/stories.json, keyed
+ * on the story id. This stays additive too: an older peer simply drops the
+ * unknown tombstone key (Zod strips it, or it never reads it), keeps
* resurrecting its own copy, and the upgraded peer defends locally — degraded,
* but never corrupting, so still no schemaVersions bump. See lib/tombstones.js.
*
@@ -650,35 +653,73 @@ export function mergeSocialAccounts(local, remote) {
return { merged: { ...local, accounts, deletedAccounts }, changed };
}
+// Autobiography story tombstones key on the story `id` (#3531). Unlike the
+// per-install document ids of #3530, a story id is minted ONCE by
+// `autobiography.saveStory` and travels with the record through sync — every
+// peer holds the same logical story under the same id, which is also what this
+// merge already unions on.
+const STORY_TOMBSTONE_OPTS = { keyField: 'id' };
+
+/** The instant a story was last asserted to EXIST — creation, or a later edit. */
+function storyLiveStamp(story) {
+ return newerStamp(story?.updatedAt, story?.createdAt);
+}
+
/**
* Merge autobiography stories: union by id (LWW on updatedAt||createdAt), union
- * usedPrompts. Both outputs are sorted by a stable key — this file feeds the
- * snapshot checksum (via JSON.stringify), and union-by-Map preserves insertion
- * order, so without a stable sort two peers with identical stories would emit
- * different array orders → different checksums → never converge. (getStories
- * re-sorts by createdAt for display, so the on-disk order is presentation-free.)
+ * usedPrompts, minus anything either side tombstoned in `deletedStories`. Both
+ * outputs are sorted by a stable key — this file feeds the snapshot checksum
+ * (via JSON.stringify), and union-by-Map preserves insertion order, so without a
+ * stable sort two peers with identical stories would emit different array orders
+ * → different checksums → never converge. (getStories re-sorts by createdAt for
+ * display, so the on-disk order is presentation-free.)
+ *
+ * DELETES need the tombstone because the story union is add-only: the deleting
+ * machine would otherwise re-import the story from any peer that still has it.
+ * `deletedStories` unions in BOTH directions, so the delete also propagates to
+ * that peer. A story whose own live stamp is strictly newer than the tombstone
+ * supersedes it — an edit made after another machine deleted the story is the
+ * user's latest word — and the now-obsolete tombstone is pruned so it can't
+ * bounce back from a peer that has not seen the edit yet.
*/
export function mergeAutobiographyStories(local, remote) {
if (!isPlainObject(remote)) return { merged: local, changed: false };
if (!isPlainObject(local)) return { merged: remote, changed: true };
+ const { merged: tombstonesUnion } = mergeTombstones(local.deletedStories, remote.deletedStories, STORY_TOMBSTONE_OPTS);
+
const byId = new Map((Array.isArray(local.stories) ? local.stories : []).map((s) => [s.id, s]));
- let changed = false;
for (const rs of Array.isArray(remote.stories) ? remote.stories : []) {
if (!isPlainObject(rs)) continue;
const ls = byId.get(rs.id);
- if (!ls) { byId.set(rs.id, rs); changed = true; continue; }
+ if (!ls) { byId.set(rs.id, rs); continue; }
const lt = ls.updatedAt || ls.createdAt || '';
const rt = rs.updatedAt || rs.createdAt || '';
- if (rt > lt) { byId.set(rs.id, rs); changed = true; }
+ if (rt > lt) byId.set(rs.id, rs);
}
+ const stories = Array.from(byId.values())
+ .filter((s) => !isTombstoned(tombstonesUnion, s.id, storyLiveStamp(s), 'id'))
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
+
const localUsed = Array.isArray(local.usedPrompts) ? local.usedPrompts : [];
const usedPrompts = [...new Set([...localUsed, ...(Array.isArray(remote.usedPrompts) ? remote.usedPrompts : [])])].sort();
- if (usedPrompts.length !== localUsed.length) changed = true;
-
- const stories = Array.from(byId.values()).sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
- return { merged: { ...local, stories, usedPrompts }, changed };
+ let changed = usedPrompts.length !== localUsed.length;
+
+ // Prune against the same live stamp the filter used, or a story kept alive by
+ // an edit would leave its tombstone behind to retry on every cycle.
+ const survivorStamps = stories.map((s) => ({ id: s.id, createdAt: storyLiveStamp(s) }));
+ const deletedStories = pruneTombstones(tombstonesUnion, survivorStamps, { ...STORY_TOMBSTONE_OPTS, timestampField: 'createdAt' });
+ if (!tombstonesEqual(deletedStories, normalizeTombstones(local.deletedStories, 'id'), 'id')) changed = true;
+
+ // The union preserves the local story objects, so identity comparison tells
+ // whether anything was added, replaced, reaped, or reordered. Comparing the
+ // survivors (rather than flagging inside the union loop) keeps a remote story
+ // this machine already tombstoned from forcing a no-op write every cycle.
+ const localStories = Array.isArray(local.stories) ? local.stories : [];
+ if (stories.length !== localStories.length || stories.some((s, i) => s !== localStories[i])) changed = true;
+
+ return { merged: { ...local, stories, usedPrompts, deletedStories }, changed };
}
// Sanitize a peer-supplied document name down to a safe `*.md` basename so a