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 Digital Twin documents so a peer sync can't resurrect them (#3530)
[._.]/ Adam Eivyaeb41453241c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex facc7634e0..9a0e591b83 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -138,3 +138,5 @@- **[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.diff --git a/data.reference/digital-twin/meta.json b/data.reference/digital-twin/meta.jsonindex dd8ff8c436..cae6e08dba 100644--- a/data.reference/digital-twin/meta.json+++ b/data.reference/digital-twin/meta.json@@ -18,6 +18,7 @@"priority": 100}],+ "deletedDocuments": [],"testHistory": [],"enrichment": {"completedCategories": [],diff --git a/server/lib/README.md b/server/lib/README.mdindex 238f9f8a4f..cfa9f4a9d4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -317,6 +317,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath. Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `agentImportCycles.test.js` (acyclicity) and `sprites/animationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). || `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. || `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |+| `tombstones.js` | Generic timestamped tombstones (`{ <keyField>, deletedAt }`) that let an otherwise add-only peer merge represent a DELETE, so a record removed on one machine is not resurrected by a peer that still has it (#3530). `normalizeTombstones` / `recordTombstone` / `clearTombstone` / `tombstoneTimestamp` maintain the list; `mergeTombstones` unions it in both directions (newest deletion per key wins) so a delete propagates rather than only defending locally; `isTombstoned(list, key, createdAt)` suppresses a record unless its own creation stamp is strictly NEWER than the deletion; `pruneTombstones(list, records)` drops tombstones a re-created record has superseded (otherwise a stale peer copy keeps reaping it); `supersedingTimestamp(deletedAt)` stamps a re-create that lands in the same millisecond (or behind a skewed peer clock). Comparison goes through `lwwTimestamp.js`, so polarity matches every other sync merge. Key on a field that means the same thing on every machine — locally-minted ids usually do not. `DEFAULT_TOMBSTONE_LIMIT` (200) caps growth. || `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. || `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. || `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. |diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.jsindex 1c57399cec..7ed4d35a6b 100644--- a/server/lib/digitalTwinValidation.js+++ b/server/lib/digitalTwinValidation.js@@ -60,7 +60,22 @@ export const documentMetaSchema = z.object({version: z.string().optional(),enabled: z.boolean().default(true),priority: z.number().int().min(0).default(0),- weight: z.number().int().min(1).max(10).default(5)+ 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()+});++// Tombstone for a deleted Digital Twin document (#3530). Keyed on `filename`,+// NOT the document id: ids are minted per-install (`generateId`), so the same+// logical document can carry a different id on each machine — filename is the+// only identifier every peer agrees on (it is also what `mergeMeta` unions+// documents by, and what the `.md` file on disk is named).+export const deletedDocumentSchema = z.object({+ filename: z.string().min(1),+ deletedAt: z.string().min(1)});// Test history entry schema. personaId/personaName are present only when the@@ -285,6 +300,7 @@ export const confidenceSchema = z.object({export const digitalTwinMetaSchema = z.object({version: z.string().default('1.0.0'),documents: z.array(documentMetaSchema).default([]),+ deletedDocuments: z.array(deletedDocumentSchema).default([]),testHistory: z.array(testHistoryEntrySchema).default([]),valuesTestHistory: z.array(valuesTestHistoryEntrySchema).default([]),adversarialTestHistory: z.array(adversarialTestHistoryEntrySchema).default([]),diff --git a/server/lib/index.js b/server/lib/index.jsindex 02ad2f8ad4..38ba201e81 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -287,6 +287,7 @@ export * from './staleWhileRevalidate.js';export * from './staticImportGraph.js';export * from './streamBackpressure.js';export * from './sseUtils.js';+export * from './tombstones.js';export * from './uploadLimits.js';export * from './uuid.js';export * from './versionUtils.js';diff --git a/server/lib/tombstones.js b/server/lib/tombstones.jsnew file mode 100644index 0000000000..d8d9606192--- /dev/null+++ b/server/lib/tombstones.js@@ -0,0 +1,164 @@+/**+ * Generic TOMBSTONE helpers for add-only cross-machine merges.+ *+ * Most PortOS peer merges are union/add-only: a record present on either side+ * survives. That is the right default for edits (no data is ever lost), but it+ * makes DELETES unrepresentable — the peer that still holds the record simply+ * re-adds it on the next sync and the user's delete is undone forever.+ *+ * A tombstone is the missing signal: `{ <keyField>: string, deletedAt: ISO }`,+ * meaning "this key was deliberately removed at this instant". Merges union the+ * tombstone list in BOTH directions (so a delete on machine A also removes the+ * record on machine B) and suppress any record the tombstone covers.+ *+ * The re-create case is what makes tombstones subtle: a record deleted at T1 and+ * then legitimately re-created at T2 must NOT stay suppressed forever. That is+ * why tombstones are timestamped rather than a bare key list — a record whose+ * own creation stamp is STRICTLY NEWER than the tombstone supersedes it, and+ * `pruneTombstones` then drops the tombstone so it can't resurface from a peer+ * that has not seen the re-create yet. `supersedingTimestamp` keeps that+ * ordering honest when the re-create lands in the same millisecond as the+ * delete (or when a peer's clock ran ahead).+ *+ * Timestamp comparison goes through `lwwTimestamp.js` so the polarity matches+ * every other sync merge (parse to epoch ms; unparseable loses; ties break to+ * the incumbent) rather than a lexicographic string compare.+ *+ * Choose the key field carefully: it must mean the same thing on every machine.+ * Locally-minted record ids usually do NOT (the same logical record can carry a+ * different id per install), which is why the Digital Twin documents tombstone+ * on `filename`.+ */++import { isPlainObject } from './objects.js';+import { parseTsMs, compareNewerWins } from './lwwTimestamp.js';++// Tombstones live inside a record that syncs in full on every cycle, so the list+// is capped. Oldest deletions fall off first; a delete that old has long since+// reached every peer (or the peer has been offline longer than the tombstone+// retention, in which case a resurrection is the lesser evil vs. unbounded meta).+export const DEFAULT_TOMBSTONE_LIMIT = 200;++function sortTombstones(list, keyField) {+ return [...list].sort((a, b) => {+ const am = parseTsMs(a.deletedAt) ?? 0;+ const bm = parseTsMs(b.deletedAt) ?? 0;+ if (am !== bm) return bm - am; // newest first+ const ak = a[keyField];+ const bk = b[keyField];+ return ak < bk ? -1 : ak > bk ? 1 : 0; // stable across peers+ });+}++/**+ * Coerce arbitrary (peer-supplied, possibly legacy) input into a clean, sorted,+ * de-duplicated tombstone list. Entries without a non-empty string key or+ * without a parseable `deletedAt` are dropped — an undatable tombstone can never+ * win a supersession comparison anyway, so keeping it would only grow the list.+ * Duplicate keys collapse to the NEWEST deletion.+ */+export function normalizeTombstones(value, keyField = 'key') {+ if (!Array.isArray(value)) return [];+ const byKey = new Map();+ for (const raw of value) {+ if (!isPlainObject(raw)) continue;+ const key = raw[keyField];+ if (typeof key !== 'string' || key === '') continue;+ if (parseTsMs(raw.deletedAt) === null) continue;+ const existing = byKey.get(key);+ if (!existing || compareNewerWins(raw.deletedAt, existing.deletedAt)) {+ byKey.set(key, { [keyField]: key, deletedAt: raw.deletedAt });+ }+ }+ return sortTombstones([...byKey.values()], keyField);+}++/** The deletion stamp recorded for `key`, or null when it is not tombstoned. */+export function tombstoneTimestamp(list, key, keyField = 'key') {+ if (!Array.isArray(list)) return null;+ let newest = null;+ for (const raw of list) {+ if (!isPlainObject(raw) || raw[keyField] !== key) continue;+ if (parseTsMs(raw.deletedAt) === null) continue;+ if (newest === null || compareNewerWins(raw.deletedAt, newest)) newest = raw.deletedAt;+ }+ return newest;+}++/**+ * True when `key` is tombstoned AND the record's own `createdAt` does not+ * supersede the deletion. A record with no (or an unparseable) creation stamp+ * never supersedes — records that predate the tombstone convention are exactly+ * the ones a delete was meant to remove.+ */+export function isTombstoned(list, key, createdAt, keyField = 'key') {+ const deletedAt = tombstoneTimestamp(list, key, keyField);+ if (deletedAt === null) return false;+ return !compareNewerWins(createdAt, deletedAt);+}++/** Record (or refresh) a tombstone for `key`. Returns a new normalized list. */+export function recordTombstone(list, key, { keyField = 'key', deletedAt, limit = DEFAULT_TOMBSTONE_LIMIT } = {}) {+ 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);+}++/** Drop the tombstone for `key` (the record came back). Returns a new list. */+export function clearTombstone(list, key, keyField = 'key') {+ return normalizeTombstones(list, keyField).filter((t) => t[keyField] !== key);+}++/** Structural equality for two normalized tombstone lists (order-sensitive). */+export function tombstonesEqual(a, b, keyField = 'key') {+ if (a.length !== b.length) return false;+ return a.every((t, i) => t[keyField] === b[i][keyField] && t.deletedAt === b[i].deletedAt);+}++/**+ * Union two tombstone lists (newest deletion per key wins) so a delete performed+ * on either machine reaches the other. `changed` is structural, so a merge that+ * only reorders or truncates still reports honestly.+ */+export function mergeTombstones(localArr, remoteArr, { keyField = 'key', limit = DEFAULT_TOMBSTONE_LIMIT } = {}) {+ const local = normalizeTombstones(localArr, keyField);+ const map = new Map(local.map((t) => [t[keyField], t]));+ for (const rt of normalizeTombstones(remoteArr, keyField)) {+ const lt = map.get(rt[keyField]);+ if (!lt || compareNewerWins(rt.deletedAt, lt.deletedAt)) map.set(rt[keyField], rt);+ }+ const merged = sortTombstones([...map.values()], keyField).slice(0, limit);+ return { merged, changed: !tombstonesEqual(merged, local, keyField) };+}++/**+ * Drop tombstones that a surviving record has superseded (its creation stamp is+ * strictly newer than the deletion). Without this the tombstone would keep+ * bouncing back from a peer that has not seen the re-create yet, and the+ * re-created record would be reaped on every subsequent cycle.+ */+export function pruneTombstones(list, records, { keyField = 'key', recordKeyField = keyField, timestampField = 'createdAt' } = {}) {+ const live = new Map();+ for (const record of Array.isArray(records) ? records : []) {+ if (!isPlainObject(record)) continue;+ const key = record[recordKeyField];+ if (typeof key !== 'string' || key === '') continue;+ const stamp = record[timestampField];+ if (!live.has(key) || compareNewerWins(stamp, live.get(key))) live.set(key, stamp);+ }+ return normalizeTombstones(list, keyField)+ .filter((t) => !compareNewerWins(live.get(t[keyField]), t.deletedAt));+}++/**+ * A creation stamp guaranteed to supersede `priorDeletedAt`. Normally just+ * `now`; when the re-create lands in the same millisecond as the delete (or the+ * deleting peer's clock ran ahead) it steps one millisecond past the tombstone+ * so the re-created record is not suppressed on the next merge.+ */+export function supersedingTimestamp(priorDeletedAt, now = new Date().toISOString()) {+ const priorMs = parseTsMs(priorDeletedAt);+ const nowMs = parseTsMs(now);+ if (priorMs === null || nowMs === null || nowMs > priorMs) return now;+ return new Date(priorMs + 1).toISOString();+}diff --git a/server/lib/tombstones.test.js b/server/lib/tombstones.test.jsnew file mode 100644index 0000000000..e8fb26787e--- /dev/null+++ b/server/lib/tombstones.test.js@@ -0,0 +1,199 @@+import { describe, it, expect } from 'vitest';+import {+ DEFAULT_TOMBSTONE_LIMIT,+ normalizeTombstones,+ tombstoneTimestamp,+ isTombstoned,+ recordTombstone,+ clearTombstone,+ tombstonesEqual,+ mergeTombstones,+ pruneTombstones,+ supersedingTimestamp,+} from './tombstones.js';++const OPTS = { keyField: 'filename' };+const tomb = (filename, deletedAt) => ({ filename, deletedAt });++describe('normalizeTombstones', () => {+ it('returns [] for non-arrays', () => {+ expect(normalizeTombstones(null, 'filename')).toEqual([]);+ expect(normalizeTombstones({ filename: 'a.md' }, 'filename')).toEqual([]);+ });++ it('drops entries with no key or an unparseable deletedAt', () => {+ const list = normalizeTombstones([+ tomb('a.md', '2026-01-02T00:00:00.000Z'),+ tomb('', '2026-01-02T00:00:00.000Z'),+ tomb('b.md', 'not-a-date'),+ tomb('c.md', undefined),+ 'garbage',+ null,+ ], 'filename');+ expect(list.map(t => t.filename)).toEqual(['a.md']);+ });++ it('collapses duplicate keys to the newest deletion', () => {+ const list = normalizeTombstones([+ tomb('a.md', '2026-01-01T00:00:00.000Z'),+ tomb('a.md', '2026-03-01T00:00:00.000Z'),+ tomb('a.md', '2026-02-01T00:00:00.000Z'),+ ], 'filename');+ expect(list).toEqual([tomb('a.md', '2026-03-01T00:00:00.000Z')]);+ });++ it('sorts newest-first with a key tiebreak so both peers land on the same order', () => {+ const a = [tomb('b.md', '2026-01-01T00:00:00.000Z'), tomb('a.md', '2026-01-01T00:00:00.000Z'), tomb('z.md', '2026-05-01T00:00:00.000Z')];+ const b = [tomb('z.md', '2026-05-01T00:00:00.000Z'), tomb('a.md', '2026-01-01T00:00:00.000Z'), tomb('b.md', '2026-01-01T00:00:00.000Z')];+ expect(normalizeTombstones(a, 'filename')).toEqual(normalizeTombstones(b, 'filename'));+ expect(normalizeTombstones(a, 'filename').map(t => t.filename)).toEqual(['z.md', 'a.md', 'b.md']);+ });++ it('strips extra fields down to the key + deletedAt', () => {+ expect(normalizeTombstones([{ filename: 'a.md', deletedAt: '2026-01-01T00:00:00.000Z', junk: 1 }], 'filename'))+ .toEqual([tomb('a.md', '2026-01-01T00:00:00.000Z')]);+ });+});++describe('tombstoneTimestamp / isTombstoned', () => {+ const list = [tomb('a.md', '2026-02-01T00:00:00.000Z')];++ it('reports null for an untombstoned key', () => {+ expect(tombstoneTimestamp(list, 'b.md', 'filename')).toBeNull();+ expect(isTombstoned(list, 'b.md', undefined, 'filename')).toBe(false);+ });++ it('suppresses a record with no creation stamp (pre-tombstone records)', () => {+ expect(isTombstoned(list, 'a.md', undefined, 'filename')).toBe(true);+ expect(isTombstoned(list, 'a.md', 'garbage', 'filename')).toBe(true);+ });++ it('suppresses a record created before the delete, but not one created after', () => {+ expect(isTombstoned(list, 'a.md', '2026-01-01T00:00:00.000Z', 'filename')).toBe(true);+ expect(isTombstoned(list, 'a.md', '2026-02-01T00:00:00.000Z', 'filename')).toBe(true); // tie loses+ expect(isTombstoned(list, 'a.md', '2026-03-01T00:00:00.000Z', 'filename')).toBe(false);+ });+});++describe('recordTombstone / clearTombstone', () => {+ it('adds a tombstone and refreshes an existing one', () => {+ const first = recordTombstone([], 'a.md', { ...OPTS, deletedAt: '2026-01-01T00:00:00.000Z' });+ expect(first).toEqual([tomb('a.md', '2026-01-01T00:00:00.000Z')]);+ const second = recordTombstone(first, 'a.md', { ...OPTS, deletedAt: '2026-04-01T00:00:00.000Z' });+ expect(second).toEqual([tomb('a.md', '2026-04-01T00:00:00.000Z')]);+ });++ it('stamps now when no (or an invalid) deletedAt is supplied', () => {+ const before = Date.now();+ const [t] = recordTombstone([], 'a.md', { ...OPTS, deletedAt: 'nope' });+ expect(Date.parse(t.deletedAt)).toBeGreaterThanOrEqual(before);+ });++ it('caps the list at the limit, dropping the oldest deletions', () => {+ const many = Array.from({ length: 5 }, (_, i) => tomb(`f${i}.md`, `2026-01-0${i + 1}T00:00:00.000Z`));+ const capped = recordTombstone(many, 'new.md', { ...OPTS, deletedAt: '2026-06-01T00:00:00.000Z', limit: 3 });+ expect(capped.map(t => t.filename)).toEqual(['new.md', 'f4.md', 'f3.md']);+ });++ it('defaults the cap to DEFAULT_TOMBSTONE_LIMIT', () => {+ const many = Array.from({ length: DEFAULT_TOMBSTONE_LIMIT + 10 }, (_, i) =>+ tomb(`f${String(i).padStart(4, '0')}.md`, new Date(Date.UTC(2026, 0, 1) + i * 1000).toISOString()));+ expect(recordTombstone(many, 'new.md', OPTS)).toHaveLength(DEFAULT_TOMBSTONE_LIMIT);+ });++ 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')]);+ expect(clearTombstone(undefined, 'a.md', 'filename')).toEqual([]);+ });+});++describe('mergeTombstones', () => {+ it('unions both directions so a delete on either machine survives', () => {+ const { merged, changed } = mergeTombstones(+ [tomb('a.md', '2026-01-01T00:00:00.000Z')],+ [tomb('b.md', '2026-02-01T00:00:00.000Z')],+ OPTS+ );+ expect(merged.map(t => t.filename)).toEqual(['b.md', 'a.md']);+ expect(changed).toBe(true);+ });++ it('keeps the newest deletion on a key collision', () => {+ const { merged } = mergeTombstones(+ [tomb('a.md', '2026-01-01T00:00:00.000Z')],+ [tomb('a.md', '2026-05-01T00:00:00.000Z')],+ OPTS+ );+ expect(merged).toEqual([tomb('a.md', '2026-05-01T00:00:00.000Z')]);+ });++ it('reports no change when the remote adds nothing (older peer sends no key)', () => {+ const local = [tomb('a.md', '2026-01-01T00:00:00.000Z')];+ expect(mergeTombstones(local, undefined, OPTS)).toEqual({ merged: local, changed: false });+ expect(mergeTombstones(local, [tomb('a.md', '2026-01-01T00:00:00.000Z')], OPTS).changed).toBe(false);+ });++ it('converges: merging in either direction yields the same list', () => {+ const a = [tomb('a.md', '2026-01-01T00:00:00.000Z'), tomb('c.md', '2026-03-01T00:00:00.000Z')];+ const b = [tomb('b.md', '2026-02-01T00:00:00.000Z'), tomb('c.md', '2026-01-01T00:00:00.000Z')];+ expect(mergeTombstones(a, b, OPTS).merged).toEqual(mergeTombstones(b, a, OPTS).merged);+ });+});++describe('pruneTombstones', () => {+ const list = [tomb('a.md', '2026-02-01T00:00:00.000Z')];++ it('drops a tombstone superseded by a re-created record', () => {+ const records = [{ filename: 'a.md', createdAt: '2026-03-01T00:00:00.000Z' }];+ expect(pruneTombstones(list, records, { ...OPTS, timestampField: 'createdAt' })).toEqual([]);+ });++ it('keeps a tombstone when the surviving record predates the delete', () => {+ const records = [{ filename: 'a.md', createdAt: '2026-01-01T00:00:00.000Z' }];+ expect(pruneTombstones(list, records, { ...OPTS, timestampField: 'createdAt' })).toEqual(list);+ });++ it('keeps a tombstone with no matching record', () => {+ expect(pruneTombstones(list, [{ filename: 'z.md', createdAt: '2027-01-01T00:00:00.000Z' }], OPTS)).toEqual(list);+ expect(pruneTombstones(list, null, OPTS)).toEqual(list);+ });++ it('uses the newest matching record when several share a key', () => {+ const records = [+ { filename: 'a.md', createdAt: '2026-01-01T00:00:00.000Z' },+ { filename: 'a.md', createdAt: '2026-06-01T00:00:00.000Z' },+ ];+ expect(pruneTombstones(list, records, OPTS)).toEqual([]);+ });+});++describe('supersedingTimestamp', () => {+ it('returns now when there is no prior deletion', () => {+ expect(supersedingTimestamp(null, '2026-01-01T00:00:00.000Z')).toBe('2026-01-01T00:00:00.000Z');+ });++ it('returns now when it is already past the deletion', () => {+ expect(supersedingTimestamp('2026-01-01T00:00:00.000Z', '2026-02-01T00:00:00.000Z')).toBe('2026-02-01T00:00:00.000Z');+ });++ it('steps past a same-millisecond delete so the re-create is not suppressed', () => {+ const stamp = supersedingTimestamp('2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z');+ expect(stamp).toBe('2026-01-01T00:00:00.001Z');+ expect(isTombstoned([tomb('a.md', '2026-01-01T00:00:00.000Z')], 'a.md', stamp, 'filename')).toBe(false);+ });++ it('steps past a peer clock that ran ahead of ours', () => {+ const stamp = supersedingTimestamp('2027-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z');+ expect(stamp).toBe('2027-01-01T00:00:00.001Z');+ });+});++describe('tombstonesEqual', () => {+ it('compares key + deletedAt positionally', () => {+ const a = [tomb('a.md', '2026-01-01T00:00:00.000Z')];+ expect(tombstonesEqual(a, [tomb('a.md', '2026-01-01T00:00:00.000Z')], 'filename')).toBe(true);+ expect(tombstonesEqual(a, [tomb('a.md', '2026-01-02T00:00:00.000Z')], 'filename')).toBe(false);+ expect(tombstonesEqual(a, [], 'filename')).toBe(false);+ });+});diff --git a/server/services/digital-twin-documents.js b/server/services/digital-twin-documents.jsindex 01e9b44510..40c26d2c06 100644--- a/server/services/digital-twin-documents.js+++ b/server/services/digital-twin-documents.js@@ -4,6 +4,7 @@ import { join } from 'path';import { DIGITAL_TWIN_DIR, generateId, ensureSoulDir } from './digital-twin-helpers.js';import { loadMeta, saveMeta } from './digital-twin-meta.js';import { extractVersion } from './digital-twin-meta.js';+import { recordTombstone, clearTombstone, tombstoneTimestamp, supersedingTimestamp } from '../lib/tombstones.js';export async function getDocuments() {const meta = await loadMeta();@@ -50,6 +51,12 @@ export async function createDocument(data) {// Write the fileawait writeFile(filePath, data.content);+ // Re-creating a filename that was previously deleted must clear its tombstone+ // and stamp a creation time that STRICTLY supersedes the deletion — otherwise+ // a peer that still holds the old tombstone would reap the new document on the+ // next sync (#3530).+ const deletedAt = tombstoneTimestamp(meta.deletedDocuments, data.filename, 'filename');+// Add to metaconst docMeta = {id: generateId(),@@ -59,11 +66,13 @@ export async function createDocument(data) {version: extractVersion(data.content),enabled: data.enabled !== false,priority: data.priority || 50,- weight: data.weight || 5+ weight: data.weight || 5,+ createdAt: supersedingTimestamp(deletedAt)};meta.documents.push(docMeta);meta.documents.sort((a, b) => a.priority - b.priority);+ meta.deletedDocuments = clearTombstone(meta.deletedDocuments, data.filename, 'filename');await saveMeta(meta);console.log(`🧬 Created soul document: ${data.filename}`);@@ -115,8 +124,11 @@ export async function deleteDocument(id) {await unlink(filePath);}- // Remove from meta+ // Remove from meta and tombstone the filename so peer sync — which unions+ // documents add-only — can't resurrect it from a machine that still has the+ // file (#3530). The tombstone also propagates the delete to those peers.meta.documents.splice(docIndex, 1);+ meta.deletedDocuments = recordTombstone(meta.deletedDocuments, docMeta.filename, { keyField: 'filename' });await saveMeta(meta);console.log(`🧬 Deleted soul document: ${docMeta.filename}`);diff --git a/server/services/digital-twin-documents.tombstone.test.js b/server/services/digital-twin-documents.tombstone.test.jsnew file mode 100644index 0000000000..c7f825b1e0--- /dev/null+++ b/server/services/digital-twin-documents.tombstone.test.js@@ -0,0 +1,131 @@+/**+ * End-to-end cover for the deleted-document tombstone (#3530): a document 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 a document re-created+ * after a delete must not be permanently suppressed.+ *+ * Exercises the real disk paths (meta.json + the .md files) with PATHS pointed+ * at a temp dir, so the merge, the file reap, and the add-only write all run.+ */++import { describe, it, expect, beforeEach, afterAll } from 'vitest';+import { existsSync, 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-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 { createDocument, deleteDocument } = await import('./digital-twin-documents.js');+const { loadMeta, saveMeta, cache } = await import('./digital-twin-meta.js');+const { applyDigitalTwinRemote, getDigitalTwinSnapshot } = await import('./digital-twin-sync.js');++const FILENAME = 'CUSTOM_ROUTINE.md';+const CONTENT = '# Custom Routine\n\nExample content.\n';+const docPath = join(twinDir, FILENAME);++const newDoc = () => createDocument({ filename: FILENAME, title: 'Custom Routine', category: 'lifestyle', content: CONTENT });++/** The snapshot a peer that still holds the document would ship. */+const peerSnapshotWithDoc = (meta) => ({+ meta: { ...meta, deletedDocuments: [] },+ documents: { [FILENAME]: CONTENT },+});++beforeEach(async () => {+ rmSync(twinDir, { recursive: true, force: true });+ cache.meta.data = null;+ cache.meta.timestamp = 0;+ await saveMeta({ version: '1.0.0', documents: [], deletedDocuments: [] });+});++afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));++describe('digital twin document tombstones (#3530)', () => {+ it('records a tombstone on delete and keeps the document deleted through a peer sync', async () => {+ const created = await newDoc();+ const peer = peerSnapshotWithDoc(await loadMeta());+ expect(existsSync(docPath)).toBe(true);++ expect(await deleteDocument(created.id)).toBe(true);+ const afterDelete = await loadMeta();+ expect(afterDelete.documents.map((d) => d.filename)).not.toContain(FILENAME);+ expect(afterDelete.deletedDocuments.map((t) => t.filename)).toEqual([FILENAME]);+ expect(existsSync(docPath)).toBe(false);++ // The peer still has the document and ships it back — the pre-#3530 bug.+ await applyDigitalTwinRemote(peer);++ const afterSync = await loadMeta();+ expect(afterSync.documents.map((d) => d.filename)).not.toContain(FILENAME);+ expect(existsSync(docPath)).toBe(false);+ // …and it stays deleted on every subsequent cycle, not just the first.+ await applyDigitalTwinRemote(peer);+ expect((await loadMeta()).documents.map((d) => d.filename)).not.toContain(FILENAME);+ expect(existsSync(docPath)).toBe(false);+ });++ it('ships tombstones in the snapshot so peers can see the delete', async () => {+ const created = await newDoc();+ await deleteDocument(created.id);+ const { data } = await getDigitalTwinSnapshot();+ expect(data.meta.deletedDocuments.map((t) => t.filename)).toEqual([FILENAME]);+ expect(Object.keys(data.documents)).not.toContain(FILENAME);+ });++ it('propagates a peer\'s delete: removes the local metadata entry AND the .md file', async () => {+ await newDoc();+ expect(existsSync(docPath)).toBe(true);++ // The peer deleted it after our copy was created.+ const { applied } = await applyDigitalTwinRemote({+ meta: { documents: [], deletedDocuments: [{ filename: FILENAME, deletedAt: new Date(Date.now() + 60_000).toISOString() }] },+ documents: {},+ });++ expect(applied).toBe(true);+ const meta = await loadMeta();+ expect(meta.documents.map((d) => d.filename)).not.toContain(FILENAME);+ expect(meta.deletedDocuments.map((t) => t.filename)).toEqual([FILENAME]);+ expect(existsSync(docPath)).toBe(false);+ });++ it('does not suppress a document re-created after the delete, and drops the stale tombstone', async () => {+ const created = await newDoc();+ await deleteDocument(created.id);+ const staleTombstone = (await loadMeta()).deletedDocuments;+ expect(staleTombstone).toHaveLength(1);++ const recreated = await newDoc();+ expect(recreated.createdAt > staleTombstone[0].deletedAt).toBe(true);+ expect((await loadMeta()).deletedDocuments).toEqual([]);++ // A peer that has not seen the re-create still ships the old tombstone.+ await applyDigitalTwinRemote({ meta: { documents: [], deletedDocuments: staleTombstone }, documents: {} });++ const meta = await loadMeta();+ expect(meta.documents.map((d) => d.filename)).toContain(FILENAME);+ expect(meta.deletedDocuments).toEqual([]);+ expect(existsSync(docPath)).toBe(true);+ });++ 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: [] },+ documents: { [FILENAME]: CONTENT },+ });+ expect((await loadMeta()).documents.map((d) => d.filename)).toContain(FILENAME);+ expect(existsSync(docPath)).toBe(true);+ });+});diff --git a/server/services/digital-twin-helpers.js b/server/services/digital-twin-helpers.jsindex ef60122996..d240f976e5 100644--- a/server/services/digital-twin-helpers.js+++ b/server/services/digital-twin-helpers.js@@ -2,6 +2,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';import { existsSync } from 'fs';import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { clearTombstone, tombstoneTimestamp, supersedingTimestamp } from '../lib/tombstones.js';export const DIGITAL_TWIN_DIR = PATHS.digitalTwin;@@ -86,11 +87,17 @@ export function resolveTestPersona(personas, personaId) {/*** Ensure a document entry exists in meta.documents. If absent, push it.* Mutates meta in place; caller must saveMeta() after.+ *+ * Re-registering a filename the user had deleted clears its `deletedDocuments`+ * tombstone and stamps a superseding `createdAt`, so peer sync treats the+ * regenerated document as new rather than reaping it against the old tombstone+ * (#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)) {- meta.documents.push({ id: generateId(), filename, title, category, enabled, priority });- }+ 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 });+ meta.deletedDocuments = clearTombstone(meta.deletedDocuments, filename, 'filename');}export async function ensureSoulDir() {diff --git a/server/services/digital-twin-meta.js b/server/services/digital-twin-meta.jsindex 7c7b255add..8298f59b20 100644--- a/server/services/digital-twin-meta.js+++ b/server/services/digital-twin-meta.js@@ -29,6 +29,9 @@ export { cache };export const DEFAULT_META = {version: '1.0.0',documents: [],+ // Tombstones for documents the user deleted (#3530) — peer sync is otherwise+ // add-only and would resurrect them from a machine that still has the file.+ deletedDocuments: [],testHistory: [],valuesTestHistory: [],adversarialTestHistory: [],@@ -62,7 +65,9 @@ export async function loadMeta() {}async function buildInitialMeta() {- const meta = { ...DEFAULT_META };+ // Deep clone — a shallow spread would share DEFAULT_META's arrays, so the+ // `documents.push` below would mutate the module-level default in place.+ const meta = structuredClone(DEFAULT_META);const files = await readdir(DIGITAL_TWIN_DIR).catch(() => []);const mdFiles = files.filter(f => f.endsWith('.md'));diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.jsindex 79cf226a81..ad8201b1a9 100644--- a/server/services/digital-twin-sync.js+++ b/server/services/digital-twin-sync.js@@ -21,7 +21,8 @@* personality-trait confidence (max per dimension —* see mergeConfidence)* - *.md documents — content shipped by filename, ADD-ONLY on the- * receiver (a local doc is never overwritten)+ * receiver (a local doc is never overwritten) MINUS+ * anything either side tombstoned (see below)* - 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)@@ -31,14 +32,25 @@* sends the four legacy keys can't blank out taste/documents/autobiography. The* snapshot is additive and ignore-if-unknown, so it needs no schemaVersions gate* (digitalTwin stays unversioned — see SNAPSHOT_CATEGORY_SCHEMA_KEYS).+ *+ * DELETES are the one thing pure union semantics can't express, so documents+ * carry tombstones (#3530): `meta.deletedDocuments` is a `{ filename, deletedAt }`+ * 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+ * resurrecting its own copy, and the upgraded peer defends locally — degraded,+ * but never corrupting, so still no schemaVersions bump. See lib/tombstones.js.*/import crypto from 'crypto';import { join, basename } from 'path';-import { readdir, readFile } from 'fs/promises';+import { readdir, readFile, unlink } from 'fs/promises';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';const DIR = PATHS.digitalTwin;const IDENTITY_FILE = join(DIR, 'identity.json');@@ -367,11 +379,40 @@ function sortRunsNewestFirst(runs) {});}+// The tombstone list on meta.json, keyed on document filename (see+// deletedDocumentSchema — document ids are minted per-install, so they can't key+// a cross-machine merge).+const DOC_TOMBSTONE_OPTS = { keyField: 'filename' };++/**+ * 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.+ *+ * 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.+ *+ * 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 { 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' });+ return { documents, deletedDocuments };+}+/*** Merge digital-twin meta.json: documents union by filename (ADD-ONLY — a local- * doc entry is never replaced), 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.+ * 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.*/export function mergeMeta(local, remote) {if (!isPlainObject(remote)) return { merged: local, changed: false };@@ -380,8 +421,16 @@ export function mergeMeta(local, remote) {let changed = false;const merged = { ...local };- const docs = unionByKey(local.documents, remote.documents, 'filename');- if (docs.changed) { merged.documents = docs.merged; changed = true; }+ const { documents, deletedDocuments } = mergeDocumentsWithTombstones(local, remote);+ const localDocs = Array.isArray(local.documents) ? local.documents : [];+ // unionByKey preserves the local record objects, so identity comparison is+ // enough to tell whether anything was added, replaced, or reaped.+ if (documents.length !== localDocs.length || documents.some((d, i) => d !== localDocs[i])) {+ merged.documents = documents; changed = true;+ }+ if (!tombstonesEqual(deletedDocuments, normalizeTombstones(local.deletedDocuments, 'filename'), 'filename')) {+ merged.deletedDocuments = deletedDocuments; changed = true;+ }// Test-history entries identify a run by `runId` (see digitalTwinValidation.js)// — they carry no `id`. Unioning them on 'id' collapsed every history to a@@ -536,16 +585,64 @@ async function applyMerge(path, remote, mergeFn, { dir } = {}) {return 1;}+/**+ * The set of document filenames a delete tombstone currently suppresses (#3530).+ *+ * Read straight off META_FILE rather than through `loadMeta()`: loadMeta's+ * missing-file path REBUILDS meta from a disk scan and saves it, which is+ * exactly the side effect the meta-before-documents ordering below exists to+ * avoid. applyMeta has already written the merged tombstones, so the file is+ * current.+ *+ * A filename that survived the merge as a live document entry is never+ * suppressed — that is the re-created-after-delete case, where the document's+ * `createdAt` superseded the tombstone.+ */+async function readSuppressedDocuments() {+ const meta = await readJSONFile(META_FILE, null);+ if (!isPlainObject(meta)) return new Set();+ const live = new Set(+ (Array.isArray(meta.documents) ? meta.documents : [])+ .filter(isPlainObject)+ .map((d) => d.filename)+ );+ return new Set(+ normalizeTombstones(meta.deletedDocuments, 'filename')+ .map((t) => t.filename)+ .filter((name) => !live.has(name))+ );+}++// Remove local .md files for documents that are tombstoned. This is what makes a+// delete PROPAGATE: mergeMeta drops the metadata entry on the receiving peer,+// and this removes the file the entry pointed at. Without it the receiver would+// keep serving the file and re-ship it in its own snapshot forever (#3530).+async function reapTombstonedDocuments(suppressed) {+ let count = 0;+ for (const rawName of suppressed) {+ const name = safeMdName(rawName);+ if (!name) continue;+ const filePath = join(DIR, name);+ if (!existsSync(filePath)) continue;+ await unlink(filePath);+ console.log(`🧬 Digital twin sync: removed deleted document ${name}`);+ count++;+ }+ return count;+}+// Documents are written ADD-ONLY: a local .md is never overwritten by a peer's// copy (we have no per-document timestamp to order edits). New documents the-// receiver is missing are written verbatim. The meta.json merge separately-// brings over each document's metadata entry so the UI lists them.-async function applyDocuments(documents) {+// receiver is missing are written verbatim — unless the filename is tombstoned,+// in which case the user deleted it and the peer is simply behind. The meta.json+// merge separately brings over each document's metadata entry so the UI lists them.+async function applyDocuments(documents, suppressed) {if (!isPlainObject(documents)) return 0;let count = 0;for (const [rawName, content] of Object.entries(documents)) {const name = safeMdName(rawName);if (!name || typeof content !== 'string') continue;+ if (suppressed.has(name)) continue;const filePath = join(DIR, name);if (existsSync(filePath)) continue;await ensureDir(DIR);@@ -618,7 +715,12 @@ export async function applyDigitalTwinRemote(remoteData) {// sender's real document metadata (title/category/priority/weight). Merging// meta first preserves the sender's entries; the files are written after.count += await applyMeta(remoteData.meta);- count += await applyDocuments(remoteData.documents);+ // Delete tombstones (#3530) gate both directions of the document apply: reap+ // local files a peer's delete covers, and skip re-writing anything this+ // machine deleted. Read AFTER applyMeta so the merged tombstone list is on disk.+ const suppressed = await readSuppressedDocuments();+ count += await reapTombstonedDocuments(suppressed);+ count += await applyDocuments(remoteData.documents, suppressed);if (isPlainObject(remoteData.autobiography)) {// stories only — config (prompt schedule) is intentionally machine-local.diff --git a/server/services/digital-twin-sync.test.js b/server/services/digital-twin-sync.test.jsindex 3def54f03c..eecb49b4b2 100644--- a/server/services/digital-twin-sync.test.js+++ b/server/services/digital-twin-sync.test.js@@ -340,6 +340,70 @@ describe('mergeMeta', () => {expect(changed).toBe(false);});+ // #3530: documents unioned add-only with no deletion tracking, so a peer that+ // still held a document the user deleted re-inserted its metadata entry (and+ // applyDocuments re-wrote the .md file) on every subsequent sync.+ describe('deleted-document tombstones (#3530)', () => {+ const DELETED_AT = '2026-02-01T00:00:00.000Z';+ const tomb = (filename, deletedAt = DELETED_AT) => ({ filename, deletedAt });+ const doc = (filename, extra = {}) => ({ id: `id-${filename}`, filename, weight: 5, ...extra });++ it('does not resurrect a document the local machine deleted', () => {+ const local = { documents: [doc('SOUL.md')], deletedDocuments: [tomb('CUSTOM_ROUTINE.md')] };+ const remote = { documents: [doc('SOUL.md'), doc('CUSTOM_ROUTINE.md', { createdAt: '2026-01-01T00:00:00.000Z' })] };+ const { merged, changed } = mergeMeta(local, remote);+ expect(merged.documents.map((d) => d.filename)).toEqual(['SOUL.md']);+ expect(changed).toBe(false);+ });++ it('suppresses a resurrected document that carries no creation stamp (legacy entry)', () => {+ const local = { documents: [], deletedDocuments: [tomb('CUSTOM_ROUTINE.md')] };+ const { merged, changed } = mergeMeta(local, { documents: [doc('CUSTOM_ROUTINE.md')] });+ expect(merged.documents ?? []).toEqual([]);+ expect(changed).toBe(false);+ });++ it('propagates a peer\'s delete: drops the local entry and adopts the tombstone', () => {+ const local = { documents: [doc('CUSTOM_ROUTINE.md', { createdAt: '2026-01-01T00:00:00.000Z' })], deletedDocuments: [] };+ const remote = { documents: [], deletedDocuments: [tomb('CUSTOM_ROUTINE.md')] };+ const { merged, changed } = mergeMeta(local, remote);+ expect(merged.documents).toEqual([]);+ expect(merged.deletedDocuments).toEqual([tomb('CUSTOM_ROUTINE.md')]);+ expect(changed).toBe(true);+ });++ it('does NOT suppress a document re-created after the delete, and prunes the stale tombstone', () => {+ const recreated = doc('CUSTOM_ROUTINE.md', { createdAt: '2026-03-01T00:00:00.000Z' });+ // The peer still holds the tombstone from the earlier delete.+ const local = { documents: [recreated], deletedDocuments: [] };+ const remote = { documents: [], deletedDocuments: [tomb('CUSTOM_ROUTINE.md')] };+ const { merged, changed } = mergeMeta(local, remote);+ expect(merged.documents ?? local.documents).toEqual([recreated]);+ expect(merged.deletedDocuments ?? []).toEqual([]);+ expect(changed).toBe(false);+ // …and the peer receiving the re-created doc accepts it, dropping its own tombstone.+ const onPeer = mergeMeta(remote, local);+ expect(onPeer.merged.documents).toEqual([recreated]);+ expect(onPeer.merged.deletedDocuments).toEqual([]);+ expect(onPeer.changed).toBe(true);+ });++ it('keeps the newer of two competing deletes and converges in both directions', () => {+ const a = { documents: [], deletedDocuments: [tomb('A.md', '2026-01-01T00:00:00.000Z')] };+ const b = { documents: [], deletedDocuments: [tomb('A.md', '2026-05-01T00:00:00.000Z'), tomb('B.md')] };+ expect(mergeMeta(a, b).merged.deletedDocuments)+ .toEqual(mergeMeta(b, a).merged.deletedDocuments ?? b.deletedDocuments);+ expect(mergeMeta(a, b).merged.deletedDocuments).toEqual([tomb('A.md', '2026-05-01T00:00:00.000Z'), tomb('B.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')] });+ expect(merged.deletedDocuments ?? local.deletedDocuments).toEqual([tomb('GONE.md')]);+ expect(changed).toBe(false);+ });+ });+it('leaves histories the peer did not send untouched (key-presence guarded)', () => {const local = { testHistory: [run('L1', '2026-01-01T00:00:00.000Z'), run('L2', '2026-01-02T00:00:00.000Z')] };const { merged, changed } = mergeMeta(local, { documents: [] });