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: let a re-create or edit after a delete supersede the document tombstone across peers (#3530)
[._.]/ Adam Eivyc466129760d6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9a0e591b83..621a5634f9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -139,4 +139,4 @@- **[issue-3510] Typing in your Daily Log no longer re-reads every day you have ever written.** Each daily-log entry is its own file on disk, and every save, autosave, and dictated segment against today was rebuilding a full date-to-entry map of your entire journal history — opening and parsing every past day, merging each one's local Obsidian mirror location back onto it — purely to fill in the payload of a store-wide "the journal changed" event. Nothing consumed that map: the write paths already announce the single affected day, and that is what the memory vectorizer listens on. The event now carries just the day that moved, so an append costs the one entry it touched instead of the whole archive, and a long dictation session no longer re-reads years of entries once per sentence. A delete reports the day with an explicitly empty entry, which is distinct from a day that simply was not part of the change.- **[issue-3516] Applying an AI-suggested goal hierarchy no longer reports success when it failed.** The routine that writes the suggestion back — creating the new north-star goal, creating the sub-goals under it, then re-parenting everything else — already gave up and reported failure the moment any of those steps was rejected by the server, but both views that call it threw that answer away and showed "Goal hierarchy applied" regardless. So a run that created nothing at all still looked like it had worked, and the list you were staring at kept showing the old arrangement. Both the list and the tree view now say so when the apply fails, and both refresh the goals afterwards either way, because a failure can still have created part of the hierarchy before aborting and leaving that half-written state off screen was the actual complaint. The apply routine swallows each server error on purpose so it can report one clean yes-or-no, so it now also asks those calls to stay quiet — otherwise the failure would have surfaced as two error toasts stacked on top of each other.-- **[issue-3530] Deleting a Digital Twin document no longer leaves it to be resurrected by your other machines.** Peer sync merged the identity documents add-only: whichever machine still had the file put its metadata entry back into `meta.json` and re-wrote the `.md` on disk, so a document you deleted came back on the next sync cycle, every cycle, forever. A delete now records a tombstone on the document's filename, and those tombstones union in both directions — so the machine that still holds the document drops its entry and removes the file, instead of the deleting machine merely defending itself while the peer keeps re-sending. Filename is the key rather than the document id because ids are minted per install and the same document can carry a different one on each machine. Deleting is not permanent in the way a naive tombstone would make it: a document created after the delete records a creation stamp that supersedes the tombstone, which is then dropped, so re-creating a document you removed — by hand or by an enrichment session regenerating its target — works and survives a peer that has not seen the re-create yet. 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.+- **[issue-3530] Deleting a Digital Twin document no longer leaves it to be resurrected by your other machines.** Peer sync merged the identity documents add-only: whichever machine still had the file put its metadata entry back into `meta.json` and re-wrote the `.md` on disk, so a document you deleted came back on the next sync cycle, every cycle, forever. A delete now records a tombstone on the document's filename, and those tombstones union in both directions — so the machine that still holds the document drops its entry and removes the file, instead of the deleting machine merely defending itself while the peer keeps re-sending. Filename is the key rather than the document id because ids are minted per install and the same document can carry a different one on each machine. Deleting is not permanent in the way a naive tombstone would make it: a document created — or edited — after the delete records a stamp that supersedes the tombstone, which is then dropped, so re-creating a document you removed (by hand, or by an enrichment session regenerating its target) works and survives a peer that has not seen the re-create yet, and an edit you made on one machine is not silently destroyed by a delete another machine performed before that edit. Those two stamps are the one part of a document's entry that is not add-only — each machine takes the newer of its own and its peer's — so a machine holding a stale copy cannot keep a third machine's older delete alive against a document that has since come back. 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.diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.jsindex 7ed4d35a6b..55ecb4c8f3 100644--- a/server/lib/digitalTwinValidation.js+++ b/server/lib/digitalTwinValidation.js@@ -61,11 +61,13 @@ export const documentMetaSchema = z.object({enabled: z.boolean().default(true),priority: z.number().int().min(0).default(0),weight: z.number().int().min(1).max(10).default(5),- // When this document was (re-)created. Optional because documents predating- // #3530 — and any rebuilt by digital-twin-meta's disk scan — carry no stamp.- // It exists so a re-created document can supersede an older `deletedDocuments`- // tombstone during peer sync instead of being suppressed forever.- createdAt: z.string().optional()+ // When this document was (re-)created, and when it was last edited. Both are+ // optional because documents predating #3530 — and any rebuilt by+ // digital-twin-meta's disk scan — carry no stamp. They exist so a document+ // re-created (or edited) after a delete supersedes the older+ // `deletedDocuments` tombstone during peer sync instead of being reaped.+ createdAt: z.string().optional(),+ updatedAt: z.string().optional()});// Tombstone for a deleted Digital Twin document (#3530). Keyed on `filename`,diff --git a/server/lib/tombstones.js b/server/lib/tombstones.jsindex d8d9606192..2c3d95ce5d 100644--- a/server/lib/tombstones.js+++ b/server/lib/tombstones.js@@ -97,8 +97,13 @@ export function isTombstoned(list, key, createdAt, keyField = 'key') {return !compareNewerWins(createdAt, deletedAt);}-/** Record (or refresh) a tombstone for `key`. Returns a new normalized list. */+/**+ * Record (or refresh) a tombstone for `key`. Returns a new normalized list.+ * An empty/non-string key is ignored rather than written — a keyless tombstone+ * matches nothing and would only fail the caller's schema on the next read.+ */export function recordTombstone(list, key, { keyField = 'key', deletedAt, limit = DEFAULT_TOMBSTONE_LIMIT } = {}) {+ if (typeof key !== 'string' || key === '') return normalizeTombstones(list, keyField);const stamp = parseTsMs(deletedAt) === null ? new Date().toISOString() : deletedAt;const kept = normalizeTombstones(list, keyField).filter((t) => t[keyField] !== key);return sortTombstones([...kept, { [keyField]: key, deletedAt: stamp }], keyField).slice(0, limit);@@ -111,6 +116,7 @@ export function clearTombstone(list, key, keyField = 'key') {/** Structural equality for two normalized tombstone lists (order-sensitive). */export function tombstonesEqual(a, b, keyField = 'key') {+ if (!Array.isArray(a) || !Array.isArray(b)) return false;if (a.length !== b.length) return false;return a.every((t, i) => t[keyField] === b[i][keyField] && t.deletedAt === b[i].deletedAt);}diff --git a/server/lib/tombstones.test.js b/server/lib/tombstones.test.jsindex e8fb26787e..c0913019ee 100644--- a/server/lib/tombstones.test.js+++ b/server/lib/tombstones.test.js@@ -101,6 +101,12 @@ describe('recordTombstone / clearTombstone', () => {expect(recordTombstone(many, 'new.md', OPTS)).toHaveLength(DEFAULT_TOMBSTONE_LIMIT);});+ it('ignores an empty/non-string key rather than writing a tombstone nothing can match', () => {+ const list = [tomb('a.md', '2026-01-01T00:00:00.000Z')];+ expect(recordTombstone(list, '', OPTS)).toEqual(list);+ expect(recordTombstone(list, undefined, OPTS)).toEqual(list);+ });+it('clears a tombstone by key and leaves the rest normalized', () => {const list = [tomb('a.md', '2026-01-01T00:00:00.000Z'), tomb('b.md', '2026-01-02T00:00:00.000Z')];expect(clearTombstone(list, 'a.md', 'filename')).toEqual([tomb('b.md', '2026-01-02T00:00:00.000Z')]);@@ -196,4 +202,9 @@ describe('tombstonesEqual', () => {expect(tombstonesEqual(a, [tomb('a.md', '2026-01-02T00:00:00.000Z')], 'filename')).toBe(false);expect(tombstonesEqual(a, [], 'filename')).toBe(false);});++ it('returns false rather than throwing on a non-array side', () => {+ expect(tombstonesEqual(undefined, [], 'filename')).toBe(false);+ expect(tombstonesEqual([], null, 'filename')).toBe(false);+ });});diff --git a/server/services/digital-twin-documents.js b/server/services/digital-twin-documents.jsindex 40c26d2c06..ead5e15436 100644--- a/server/services/digital-twin-documents.js+++ b/server/services/digital-twin-documents.js@@ -103,6 +103,11 @@ export async function updateDocument(id, updates) {}if (updates.weight !== undefined) docMeta.weight = updates.weight;+ // Stamp the edit so a delete performed on ANOTHER machine before this edit+ // reached it can't reap the document and destroy the edit with it: the sync+ // merge keeps whichever of create/edit/delete happened last (#3530).+ docMeta.updatedAt = new Date().toISOString();+meta.documents[docIndex] = docMeta;await saveMeta(meta);diff --git a/server/services/digital-twin-documents.tombstone.test.js b/server/services/digital-twin-documents.tombstone.test.jsindex c7f825b1e0..48adbfc896 100644--- a/server/services/digital-twin-documents.tombstone.test.js+++ b/server/services/digital-twin-documents.tombstone.test.js@@ -27,7 +27,8 @@ vi.mock('../lib/fileUtils.js', async () => {});});-const { createDocument, deleteDocument } = await import('./digital-twin-documents.js');+const { createDocument, updateDocument, deleteDocument } = await import('./digital-twin-documents.js');+const { ensureDocumentInMeta } = await import('./digital-twin-helpers.js');const { loadMeta, saveMeta, cache } = await import('./digital-twin-meta.js');const { applyDigitalTwinRemote, getDigitalTwinSnapshot } = await import('./digital-twin-sync.js');@@ -120,6 +121,33 @@ describe('digital twin document tombstones (#3530)', () => {expect(existsSync(docPath)).toBe(true);});+ it('keeps a document edited here after another machine deleted it', async () => {+ const created = await newDoc();+ await updateDocument(created.id, { content: `${CONTENT}\nEdited.\n` });+ const edited = (await loadMeta()).documents.find((d) => d.filename === FILENAME);+ 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({ meta: { documents: [], deletedDocuments: [{ filename: FILENAME, deletedAt }] }, documents: {} });++ const meta = await loadMeta();+ expect(meta.documents.map((d) => d.filename)).toContain(FILENAME);+ expect(meta.deletedDocuments).toEqual([]);+ expect(existsSync(docPath)).toBe(true);+ });++ it('re-registering an enrichment target clears a tombstone the peer merged in', async () => {+ const meta = await loadMeta();+ meta.documents.push({ id: 'x', filename: 'MEMORIES.md', title: 'Memories', category: 'enrichment', enabled: true, priority: 30 });+ meta.deletedDocuments = [{ filename: 'MEMORIES.md', deletedAt: new Date().toISOString() }];+ await saveMeta(meta);++ ensureDocumentInMeta(meta, 'MEMORIES.md', 'Memories', 'enrichment');+ expect(meta.deletedDocuments).toEqual([]);+ expect(meta.documents.find((d) => d.filename === 'MEMORIES.md').createdAt).toBeTruthy();+ });+it('still accepts a document the peer has that was never deleted here', async () => {await applyDigitalTwinRemote({meta: { documents: [{ id: 'peer-1', filename: FILENAME, title: 'Custom Routine', category: 'lifestyle' }], deletedDocuments: [] },diff --git a/server/services/digital-twin-helpers.js b/server/services/digital-twin-helpers.jsindex d240f976e5..ffcd965ed5 100644--- a/server/services/digital-twin-helpers.js+++ b/server/services/digital-twin-helpers.js@@ -94,9 +94,15 @@ export function resolveTestPersona(personas, personaId) {* (#3530) — enrichment regenerates its target docs on every session.*/export function ensureDocumentInMeta(meta, filename, title, category, { enabled = true, priority = 30 } = {}) {- if (meta.documents.find(d => d.filename === filename)) return;- const createdAt = supersedingTimestamp(tombstoneTimestamp(meta.deletedDocuments, filename, 'filename'));- meta.documents.push({ id: generateId(), filename, title, category, enabled, priority, createdAt });+ const deletedAt = tombstoneTimestamp(meta.deletedDocuments, filename, 'filename');+ const existing = meta.documents.find(d => d.filename === filename);+ if (existing && deletedAt === null) return;+ // An entry that already exists but is still covered by a tombstone would be+ // reaped on the next sync even though the caller just wrote the file — so+ // refresh its stamp and drop the tombstone rather than returning early.+ const createdAt = supersedingTimestamp(deletedAt);+ if (existing) existing.createdAt = createdAt;+ else meta.documents.push({ id: generateId(), filename, title, category, enabled, priority, createdAt });meta.deletedDocuments = clearTombstone(meta.deletedDocuments, filename, 'filename');}diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.jsindex ad8201b1a9..bab70afa11 100644--- a/server/services/digital-twin-sync.js+++ b/server/services/digital-twin-sync.js@@ -51,6 +51,7 @@ import { existsSync } from 'fs';import { atomicWrite, readJSONFile, ensureDir, PATHS } from '../lib/fileUtils.js';import { canonicalStringify, isPlainObject } from '../lib/objects.js';import { normalizeTombstones, mergeTombstones, isTombstoned, pruneTombstones, tombstonesEqual } from '../lib/tombstones.js';+import { compareNewerWins } from '../lib/lwwTimestamp.js';const DIR = PATHS.digitalTwin;const IDENTITY_FILE = join(DIR, 'identity.json');@@ -384,26 +385,70 @@ function sortRunsNewestFirst(runs) {// a cross-machine merge).const DOC_TOMBSTONE_OPTS = { keyField: 'filename' };+/** The newer of two timestamp strings; either may be absent/unparseable. */+function newerStamp(candidate, incumbent) {+ return compareNewerWins(candidate, incumbent) ? candidate : incumbent;+}++/**+ * The instant a document was last asserted to EXIST — its creation stamp, or a+ * later edit. A delete only wins over a document older than the delete: an edit+ * made after another machine deleted the document is the user's latest word on+ * the subject, and reaping it would silently destroy that edit.+ */+function documentLiveStamp(doc) {+ return newerStamp(doc?.updatedAt, doc?.createdAt);+}+/*** Merge the document list against both sides' delete tombstones (#3530).*- * The document union is still ADD-ONLY — a local entry is never replaced — but- * the tombstone lists union in BOTH directions first, and any document a- * surviving tombstone covers is then dropped. That makes a delete performed on- * either machine converge: the deleting side stops resurrecting the entry, and- * the side that still has the document removes it.+ * The document union is still ADD-ONLY — a local entry's title/priority/weight+ * is never replaced — but the tombstone lists union in BOTH directions first,+ * and any document a surviving tombstone covers is then dropped. That makes a+ * delete performed on either machine converge: the deleting side stops+ * resurrecting the entry, and the side that still has the document removes it.*- * A document whose own `createdAt` is strictly newer than the tombstone- * supersedes it (re-create after delete), and the now-obsolete tombstone is- * pruned so it can't bounce back from a peer that hasn't seen the re-create.+ * A document whose own live stamp is strictly newer than the tombstone+ * supersedes it (re-created, or edited after the delete), and the now-obsolete+ * tombstone is pruned so it can't bounce back from a peer that hasn't seen that+ * yet. The two stamps themselves are the one part of a document entry that is+ * NOT add-only: each takes the newer of the two sides, so the knowledge that a+ * document was re-created (or edited) propagates to every peer. Without that, a+ * machine holding a stale entry would keep an older stamp and a third peer's+ * still-live tombstone would reap the document there.** Returns the surviving documents plus the merged tombstone list.*/export function mergeDocumentsWithTombstones(local, remote) {const { merged: tombstonesUnion } = mergeTombstones(local?.deletedDocuments, remote?.deletedDocuments, DOC_TOMBSTONE_OPTS);++ const remoteStamps = new Map();+ for (const doc of Array.isArray(remote?.documents) ? remote.documents : []) {+ if (!isPlainObject(doc) || typeof doc.filename !== 'string') continue;+ const prev = remoteStamps.get(doc.filename);+ remoteStamps.set(doc.filename, {+ createdAt: newerStamp(doc.createdAt, prev?.createdAt),+ updatedAt: newerStamp(doc.updatedAt, prev?.updatedAt),+ });+ }+const { merged: unioned } = unionByKey(local?.documents, remote?.documents, 'filename');- const documents = unioned.filter((doc) => !isTombstoned(tombstonesUnion, doc.filename, doc.createdAt, 'filename'));- const deletedDocuments = pruneTombstones(tombstonesUnion, documents, { ...DOC_TOMBSTONE_OPTS, timestampField: 'createdAt' });+ const documents = unioned+ .map((doc) => {+ const peer = remoteStamps.get(doc.filename);+ if (!peer) return doc;+ const createdAt = newerStamp(peer.createdAt, doc.createdAt);+ const updatedAt = newerStamp(peer.updatedAt, doc.updatedAt);+ if (createdAt === doc.createdAt && updatedAt === doc.updatedAt) return doc;+ return { ...doc, ...(createdAt ? { createdAt } : {}), ...(updatedAt ? { updatedAt } : {}) };+ })+ .filter((doc) => !isTombstoned(tombstonesUnion, doc.filename, documentLiveStamp(doc), 'filename'));++ // Prune against the same live stamp the filter used, or a document kept alive+ // by an edit would leave its tombstone behind to retry on every cycle.+ const survivorStamps = documents.map((doc) => ({ filename: doc.filename, createdAt: documentLiveStamp(doc) }));+ const deletedDocuments = pruneTombstones(tombstonesUnion, survivorStamps, { ...DOC_TOMBSTONE_OPTS, timestampField: 'createdAt' });return { documents, deletedDocuments };}@@ -624,7 +669,13 @@ async function reapTombstonedDocuments(suppressed) {if (!name) continue;const filePath = join(DIR, name);if (!existsSync(filePath)) continue;- await unlink(filePath);+ // A file we can't remove (permissions, or it vanished between the check and+ // the call) must not abort the rest of the sync — report and move on.+ const removed = await unlink(filePath).then(() => true, (err) => {+ console.error(`❌ Digital twin sync: could not remove deleted document ${name}: ${err.message}`);+ return false;+ });+ if (!removed) continue;console.log(`🧬 Digital twin sync: removed deleted document ${name}`);count++;}diff --git a/server/services/digital-twin-sync.test.js b/server/services/digital-twin-sync.test.jsindex eecb49b4b2..a2bf583061 100644--- a/server/services/digital-twin-sync.test.js+++ b/server/services/digital-twin-sync.test.js@@ -396,6 +396,37 @@ describe('mergeMeta', () => {expect(mergeMeta(a, b).merged.deletedDocuments).toEqual([tomb('A.md', '2026-05-01T00:00:00.000Z'), tomb('B.md')]);});+ it('adopts the peer\'s newer creation stamp so a third peer\'s tombstone can\'t reap the re-created doc', () => {+ // This machine has the ORIGINAL entry; the peer re-created the document+ // after a delete. Without propagating the newer stamp, the stale local+ // entry would later be reaped by a third peer still holding the tombstone.+ const local = { documents: [doc('CUSTOM_ROUTINE.md', { createdAt: '2026-01-01T00:00:00.000Z', weight: 9 })] };+ const remote = { documents: [doc('CUSTOM_ROUTINE.md', { createdAt: '2026-03-01T00:00:00.000Z', weight: 1 })] };+ const { merged, changed } = mergeMeta(local, remote);+ expect(changed).toBe(true);+ expect(merged.documents[0].createdAt).toBe('2026-03-01T00:00:00.000Z');+ expect(merged.documents[0].weight).toBe(9); // the rest of the entry stays add-only++ // …and that refreshed entry now survives the stale tombstone.+ const third = { documents: [], deletedDocuments: [tomb('CUSTOM_ROUTINE.md')] };+ expect(mergeMeta(merged, third).merged.documents).toEqual(merged.documents);+ });++ it('does not reap a document edited after another machine deleted it', () => {+ const edited = doc('CUSTOM_ROUTINE.md', { createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-03-01T00:00:00.000Z' });+ const { merged } = mergeMeta({ documents: [edited] }, { documents: [], deletedDocuments: [tomb('CUSTOM_ROUTINE.md')] });+ expect(merged.documents ?? [edited]).toEqual([edited]);+ // …and the superseded tombstone is pruned rather than retried every cycle.+ expect(merged.deletedDocuments ?? []).toEqual([]);+ });++ it('still reaps a document whose last edit predates the delete', () => {+ const stale = doc('CUSTOM_ROUTINE.md', { createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-15T00:00:00.000Z' });+ const { merged } = mergeMeta({ documents: [stale] }, { documents: [], deletedDocuments: [tomb('CUSTOM_ROUTINE.md')] });+ expect(merged.documents).toEqual([]);+ expect(merged.deletedDocuments).toEqual([tomb('CUSTOM_ROUTINE.md')]);+ });+it('leaves local tombstones untouched when an older peer sends none (key-presence guarded)', () => {const local = { documents: [doc('SOUL.md')], deletedDocuments: [tomb('GONE.md')] };const { merged, changed } = mergeMeta(local, { documents: [doc('SOUL.md')] });