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 Twin personas so a peer sync can't resurrect them (#3533)

[._.]/ Adam Eivyb931dacc653a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6ab7ef55c7..b55e8bb671 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -146,3 +146,5 @@
- **[issue-3528] The Notes header controls in Brain are now big enough to hit on a phone.** The "Manage vaults" and "New note" buttons wrapped 14px icons in nothing but `p-1.5`, giving them roughly 26x26px of tappable area right next to the vault dropdown — close enough that a thumb aiming for "New note" would land on the dropdown instead. Those two buttons, plus the vault selector, the search box, and the create-note row beside them, now all clear the 44px touch-target floor the rest of the app uses. The search box also gained enough right padding to clear its own clear-search button, which was already 44px wide and had been sitting on top of whatever you typed.
- **[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.
diff --git a/data.reference/digital-twin/meta.json b/data.reference/digital-twin/meta.json
index cae6e08dba..8b32d94dcc 100644
--- a/data.reference/digital-twin/meta.json
+++ b/data.reference/digital-twin/meta.json
@@ -20,6 +20,7 @@
],
"deletedDocuments": [],
"testHistory": [],
+ "deletedPersonas": [],
"enrichment": {
"completedCategories": [],
"lastSession": null,
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index 55ecb4c8f3..bcd7352af5 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -215,6 +215,17 @@ export const personaSchema = z.object({
updatedAt: z.string().datetime()
});
+// Tombstone for a deleted persona (#3533). Keyed on `id`, unlike the document
+// tombstone above: a persona id is minted ONCE by the machine that created the
+// persona and then travels with the record through peer sync (mergeMeta unions
+// personas by id), so every peer agrees on it. `id` is a plain non-empty string
+// rather than a guid so a tombstone for a legacy/hand-edited persona id still
+// normalizes instead of failing the whole meta parse.
+export const deletedPersonaSchema = z.object({
+ id: z.string().min(1),
+ deletedAt: z.string().min(1)
+});
+
export const createPersonaInputSchema = z.object({
name: z.string().min(1).max(100),
description: z.string().max(500).optional(),
@@ -310,6 +321,7 @@ export const digitalTwinMetaSchema = z.object({
enrichment: enrichmentProgressSchema.default({ completedCategories: [], lastSession: null }),
settings: digitalTwinSettingsSchema.default({ autoInjectToCoS: true, maxContextTokens: 4000, includePrivacyContext: false }),
personas: z.array(personaSchema).default([]),
+ deletedPersonas: z.array(deletedPersonaSchema).default([]),
traits: traitsSchema.optional(),
confidence: confidenceSchema.optional()
});
diff --git a/server/services/digital-twin-meta.js b/server/services/digital-twin-meta.js
index 8298f59b20..dd3950ad99 100644
--- a/server/services/digital-twin-meta.js
+++ b/server/services/digital-twin-meta.js
@@ -37,6 +37,9 @@ export const DEFAULT_META = {
adversarialTestHistory: [],
multiTurnTestHistory: [],
personas: [],
+ // Tombstones for personas the user deleted (#3533) — the persona union is
+ // add-only, so a peer that still has the persona would otherwise re-add it.
+ deletedPersonas: [],
enrichment: { completedCategories: [], lastSession: null },
settings: { autoInjectToCoS: true, maxContextTokens: 4000, includePrivacyContext: false }
};
diff --git a/server/services/digital-twin-personas.js b/server/services/digital-twin-personas.js
index a6c23c3be2..780577e3a1 100644
--- a/server/services/digital-twin-personas.js
+++ b/server/services/digital-twin-personas.js
@@ -14,6 +14,7 @@
import { generateId, now } from './digital-twin-helpers.js';
import { loadMeta, saveMeta } from './digital-twin-meta.js';
+import { recordTombstone } from '../lib/tombstones.js';
export async function getPersonas() {
const meta = await loadMeta();
@@ -77,6 +78,16 @@ export async function deletePersona(id) {
const meta = await loadMeta();
const before = (meta.personas || []).length;
meta.personas = (meta.personas || []).filter(p => p.id !== id);
+ const deleted = before !== meta.personas.length;
+
+ // Tombstone the id so peer sync — which unions personas add-only — can't
+ // resurrect it from a machine that still has the persona (#3533). The
+ // tombstone also propagates the delete to those machines. Only recorded when
+ // something was actually removed: a delete for an unknown id is a no-op, and
+ // writing a tombstone for it would just consume the capped list.
+ if (deleted) {
+ meta.deletedPersonas = recordTombstone(meta.deletedPersonas, id, { keyField: 'id' });
+ }
// Clearing the active persona when it's the one being deleted keeps the
// settings pointer from dangling at a non-existent id.
@@ -85,7 +96,7 @@ export async function deletePersona(id) {
}
await saveMeta(meta);
- return { deleted: before !== meta.personas.length };
+ return { deleted };
}
/**
diff --git a/server/services/digital-twin-personas.tombstone.test.js b/server/services/digital-twin-personas.tombstone.test.js
new file mode 100644
index 0000000000..e4c6e05752
--- /dev/null
+++ b/server/services/digital-twin-personas.tombstone.test.js
@@ -0,0 +1,118 @@
+/**
+ * End-to-end cover for the deleted-persona tombstone (#3533): a persona 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 rather than merely being
+ * defended against locally.
+ *
+ * Exercises the real disk path (meta.json) with PATHS pointed at a temp dir, so
+ * the service write, the merge, and the 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';
+
+// `digital-twin-sync.js` and `digital-twin-helpers.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 meta cache in beforeEach.
+const tempRoot = createTempDataRoot('portos-dt-persona-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 { createPersona, updatePersona, deletePersona, setActivePersona } = await import('./digital-twin-personas.js');
+const { loadMeta, saveMeta, cache } = await import('./digital-twin-meta.js');
+const { applyDigitalTwinRemote, getDigitalTwinSnapshot } = await import('./digital-twin-sync.js');
+
+const newPersona = () => createPersona({ name: 'Work', instructions: 'Stay concise and professional.' });
+
+/** The snapshot a peer that still holds the persona would ship. */
+const peerSnapshotWith = (persona) => ({ meta: { personas: [persona], deletedPersonas: [] } });
+
+beforeEach(async () => {
+ rmSync(twinDir, { recursive: true, force: true });
+ cache.meta.data = null;
+ cache.meta.timestamp = 0;
+ await saveMeta({ version: '1.0.0', documents: [], personas: [], deletedPersonas: [] });
+});
+
+afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));
+
+describe('digital twin persona tombstones (#3533)', () => {
+ it('records a tombstone on delete and keeps the persona deleted through a peer sync', async () => {
+ const persona = await newPersona();
+ const peer = peerSnapshotWith(persona);
+
+ expect(await deletePersona(persona.id)).toEqual({ deleted: true });
+ const afterDelete = await loadMeta();
+ expect(afterDelete.personas).toEqual([]);
+ expect(afterDelete.deletedPersonas.map((t) => t.id)).toEqual([persona.id]);
+
+ // The peer still has the persona and ships it back — the pre-#3533 bug.
+ await applyDigitalTwinRemote(peer);
+ expect((await loadMeta()).personas).toEqual([]);
+
+ // …and it stays deleted on every subsequent cycle, not just the first.
+ await applyDigitalTwinRemote(peer);
+ expect((await loadMeta()).personas).toEqual([]);
+ });
+
+ it('ships tombstones in the snapshot so peers can see the delete', async () => {
+ const persona = await newPersona();
+ await deletePersona(persona.id);
+ const { data } = await getDigitalTwinSnapshot();
+ expect(data.meta.deletedPersonas.map((t) => t.id)).toEqual([persona.id]);
+ expect(data.meta.personas).toEqual([]);
+ });
+
+ it("propagates a peer's delete by removing the local persona", async () => {
+ const persona = await newPersona();
+ await setActivePersona(persona.id);
+
+ const { applied } = await applyDigitalTwinRemote({
+ meta: { personas: [], deletedPersonas: [{ id: persona.id, deletedAt: new Date(Date.now() + 60_000).toISOString() }] },
+ });
+
+ expect(applied).toBe(true);
+ const meta = await loadMeta();
+ expect(meta.personas).toEqual([]);
+ expect(meta.deletedPersonas.map((t) => t.id)).toEqual([persona.id]);
+ // The reaped persona was the active one — the pointer must not dangle.
+ expect(meta.settings.activePersonaId).toBeNull();
+ });
+
+ it('keeps a persona edited here after another machine deleted it, and drops the stale tombstone', async () => {
+ const persona = await newPersona();
+ const edited = await updatePersona(persona.id, { instructions: 'Stay concise, professional, and warm.' });
+
+ // 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({ meta: { personas: [], deletedPersonas: [{ id: persona.id, deletedAt }] } });
+
+ const meta = await loadMeta();
+ expect(meta.personas.map((p) => p.id)).toEqual([persona.id]);
+ expect(meta.deletedPersonas).toEqual([]);
+ });
+
+ it('leaves an unrelated persona the peer has alone', async () => {
+ const persona = await newPersona();
+ await deletePersona(persona.id);
+
+ const peerOnly = { id: '11111111-2222-4333-8444-555555555555', name: 'Casual', instructions: 'Loosen up.', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() };
+ await applyDigitalTwinRemote({ meta: { personas: [peerOnly], deletedPersonas: [] } });
+
+ expect((await loadMeta()).personas.map((p) => p.id)).toEqual([peerOnly.id]);
+ });
+
+ it('does not tombstone an id that was never a persona here', async () => {
+ expect(await deletePersona('11111111-2222-4333-8444-666666666666')).toEqual({ deleted: false });
+ expect((await loadMeta()).deletedPersonas).toEqual([]);
+ });
+});
diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.js
index bab70afa11..e5ebc1490e 100644
--- a/server/services/digital-twin-sync.js
+++ b/server/services/digital-twin-sync.js
@@ -42,6 +42,10 @@
* simply drops the unknown `deletedDocuments` key (Zod strips 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.
+ *
+ * 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.
*/
import crypto from 'crypto';
@@ -452,12 +456,62 @@ export function mergeDocumentsWithTombstones(local, remote) {
return { documents, deletedDocuments };
}
+// The persona tombstone list on meta.json, keyed on the persona `id` (see
+// deletedPersonaSchema). Unlike a document id, a persona id is minted once by
+// the machine that created the persona and then travels with the record, so it
+// means the same thing on every peer.
+const PERSONA_TOMBSTONE_OPTS = { keyField: 'id' };
+
+/**
+ * The instant a persona was last asserted to EXIST — its creation stamp, or a
+ * later edit. Mirrors the document rule: a delete only wins over a persona older
+ * than the delete, so an edit made after another machine deleted the persona is
+ * the user's latest word and is not silently destroyed.
+ */
+function personaLiveStamp(persona) {
+ return newerStamp(persona?.updatedAt, persona?.createdAt);
+}
+
+/**
+ * Merge the persona list against both sides' delete tombstones (#3533).
+ *
+ * Personas are the same add-only-union shape documents were before #3530: the
+ * machine that still had the record simply re-added it, so a deleted persona
+ * came back on the next cycle, forever. The tombstone lists union in BOTH
+ * directions and any persona a surviving tombstone covers is dropped, so a
+ * delete performed on either machine converges. A persona lives entirely inside
+ * meta.json, so there is no on-disk companion to reap — unlike documents, the
+ * merge alone completes the delete.
+ *
+ * The union takes the more recently edited copy (LWW on `updatedAt`) rather than
+ * always keeping the local one. Persona ids are stable across peers and every
+ * persona carries a mandatory `updatedAt` (see personaSchema), so LWW is
+ * well-defined here — and it is what keeps supersession honest: a persona edited
+ * on one machine after another deleted it must carry that newer stamp to every
+ * peer, or a third machine holding a stale copy would still reap it against the
+ * older tombstone and the two would never converge.
+ *
+ * Returns the surviving personas plus the merged tombstone list.
+ */
+export function mergePersonasWithTombstones(local, remote) {
+ const { merged: tombstonesUnion } = mergeTombstones(local?.deletedPersonas, remote?.deletedPersonas, PERSONA_TOMBSTONE_OPTS);
+ const { merged: unioned } = unionByKey(local?.personas, remote?.personas, 'id', 'updatedAt');
+ const personas = unioned.filter((p) => !isTombstoned(tombstonesUnion, p.id, personaLiveStamp(p), 'id'));
+
+ // Prune against the same live stamp the filter used, or a persona kept alive
+ // by an edit would leave its tombstone behind to retry on every cycle.
+ const survivorStamps = personas.map((p) => ({ id: p.id, createdAt: personaLiveStamp(p) }));
+ const deletedPersonas = pruneTombstones(tombstonesUnion, survivorStamps, { ...PERSONA_TOMBSTONE_OPTS, timestampField: 'createdAt' });
+ return { personas, deletedPersonas };
+}
+
/**
* Merge digital-twin meta.json: documents union by filename (ADD-ONLY — a local
* doc entry is never replaced) minus anything either side has tombstoned in
* `deletedDocuments`, 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.
+ * id (LWW) minus anything tombstoned in `deletedPersonas`, 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 };
@@ -485,8 +539,16 @@ export function mergeMeta(local, remote) {
if (u.changed) { merged[key] = sortRunsNewestFirst(u.merged); changed = true; }
}
- const personas = unionByKey(local.personas, remote.personas, 'id');
- if (personas.changed) { merged.personas = personas.merged; changed = true; }
+ const { personas, deletedPersonas } = mergePersonasWithTombstones(local, remote);
+ const localPersonas = Array.isArray(local.personas) ? local.personas : [];
+ // The union preserves the local record objects it kept, so identity
+ // comparison is enough to tell whether anything was added, replaced, or reaped.
+ if (personas.length !== localPersonas.length || personas.some((p, i) => p !== localPersonas[i])) {
+ merged.personas = personas; changed = true;
+ }
+ if (!tombstonesEqual(deletedPersonas, normalizeTombstones(local.deletedPersonas, 'id'), 'id')) {
+ merged.deletedPersonas = deletedPersonas; changed = true;
+ }
if (isPlainObject(remote.enrichment)) {
const e = mergeEnrichment(local.enrichment, remote.enrichment);
@@ -505,6 +567,19 @@ export function mergeMeta(local, remote) {
if (c.changed) { merged.confidence = c.merged; changed = true; }
}
+ // A persona another machine deleted is reaped above, which can leave
+ // `settings.activePersonaId` pointing at an id that is no longer in the list
+ // (deletePersona clears it for a LOCAL delete; this is the remote half).
+ // Cleared rather than left dangling so the embodied twin falls back to the
+ // base twin instead of silently resolving to nothing (#3533).
+ const settings = isPlainObject(merged.settings) ? merged.settings : local.settings;
+ const activePersonaId = isPlainObject(settings) ? settings.activePersonaId : null;
+ const survivingPersonas = merged.personas ?? localPersonas;
+ if (activePersonaId && !survivingPersonas.some((p) => p?.id === activePersonaId)) {
+ merged.settings = { ...settings, activePersonaId: null };
+ changed = true;
+ }
+
return { merged, changed };
}