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: stop federated brain-sync resurrection/amplification loop
Adam Eivy69b0b52d52e3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bc3aea8153..84ebbd0552 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -15,3 +15,7 @@- **[issue-1050] More reliable database exports** — manual database exports now pick a PostgreSQL dump tool that matches the database being exported, so an export no longer fails on machines with several Postgres versions installed.- **[issue-909] CyberCity theme colors** — internal refactor of how the 3D city picks up your theme accent, replacing a fragile shared-state mechanism with a cleaner one; no change to how the city looks.- **[issue-1064] Smoother CyberCity theme switching** — changing your theme now recolors the 3D city in place instead of rebuilding the whole scene, so the switch is seamless with no rebuild flash or blank frame.++## Fixed++- **Federated brain sync no longer loops forever** — on installs with two or more federated machines, deleting a Brain item (a person, project, idea, link, etc.) could quietly resurrect it: a peer would echo back the old "create," the item would reappear, the delete would re-run, and the two halves would ping-pong between machines indefinitely — flooding the logs with constant sync activity and ballooning the sync counters into the tens of thousands. Brain deletes now leave a durable "tombstone" so a stale create from a peer is rejected instead of reviving the record, matching how the creative catalog already handles deletes. A one-time cleanup neutralizes any already-resurrected items and compacts the runaway sync log (one install collapsed from 74,000 log entries to 7) without disturbing peer sync positions, and old tombstones are swept automatically after a grace period. If you disabled federation sync to stop the churn, it's safe to re-enable once every machine is updated.diff --git a/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.js b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.jsnew file mode 100644index 0000000000..2e3960a5f3--- /dev/null+++ b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.js@@ -0,0 +1,149 @@+/**+ * Migration 080 — brain tombstone backfill + sync-log cleanup.+ *+ * Fixes the federated brain-sync resurrection/amplification loop. Brain entity+ * deletes used to be HARD deletes with no tombstone, so a stale `create`+ * echoed from a peer found `existing === undefined`, skipped the last-writer-+ * wins guard, and RESURRECTED the record; the newer `delete` re-killed it; both+ * ops relayed to every peer forever. Installs that ran the looping code carry:+ * - "ghost" records: live entries that actually have a NEWER matching delete+ * in the sync log (the resurrected half of a ping-pong pair).+ * - a bloated `sync_log.jsonl`: tens of thousands of churn entries, with the+ * monotonic seq counter far above the surviving line count.+ *+ * This migration (idempotent, safe across independently-upgrading peers):+ * 1. Builds, from the sync log, the newest `delete` updatedAt per (type, id).+ * 2. For each entity store, converts any live record that has a newer matching+ * delete into a tombstone (neutralizes ghosts in place). The new tombstone+ * code then rejects future stale creates.+ * 3. COMPACTS the sync log to the last entry per (type, id) — WITHOUT+ * renumbering. Max seq is preserved so peer `brainSeq` cursors stay valid+ * (resetting to 0 would strand every peer cursor and break convergence).+ *+ * Runs in the boot-time migration runner, which fires BEFORE initSyncLog() — so+ * rewriting sync_log.jsonl here is safe (currentSeq hasn't been read yet).+ *+ * Wire format is unchanged (deletes still ship `{ updatedAt }`), so no+ * schemaVersion bump and older peers are unaffected.+ */++import { readFile, writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';++const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets'];++function parseLog(content) {+ const entries = [];+ for (const line of content.trim().split('\n')) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ try {+ entries.push(JSON.parse(trimmed));+ } catch {+ // Skip a corrupt/half-written line rather than aborting the whole migration.+ }+ }+ return entries;+}++/**+ * Core transform, exported for unit tests. Pure over its inputs:+ * - logEntries: array of parsed sync-log entries (in seq order).+ * - stores: { [type]: { records: { [id]: record } } } loaded entity stores.+ * Returns { stores, compactedLines, ghostsTombstoned } with mutated stores and+ * the compacted JSONL line array (seq numbers preserved).+ */+export function computeBrainCleanup(logEntries, stores, { nowIso }) {+ // Newest delete updatedAt per (type/id), for ghost detection.+ const newestDelete = new Map();+ for (const e of logEntries) {+ if (e?.op !== 'delete' || !e.type || !e.id || !e.record?.updatedAt) continue;+ const key = `${e.type}/${e.id}`;+ const prev = newestDelete.get(key);+ if (!prev || e.record.updatedAt > prev.updatedAt) {+ newestDelete.set(key, { updatedAt: e.record.updatedAt, originInstanceId: e.originInstanceId });+ }+ }++ // 1. Tombstone any live record that has a newer matching delete (the ghost).+ let ghostsTombstoned = 0;+ for (const type of ENTITY_TYPES) {+ const store = stores[type];+ if (!store?.records) continue;+ for (const [id, record] of Object.entries(store.records)) {+ if (record?._deleted) continue; // already a tombstone+ const del = newestDelete.get(`${type}/${id}`);+ if (del && record?.updatedAt != null && del.updatedAt > record.updatedAt) {+ store.records[id] = {+ _deleted: true,+ updatedAt: del.updatedAt,+ originInstanceId: record.originInstanceId ?? del.originInstanceId ?? 'unknown',+ deletedAt: nowIso,+ };+ ghostsTombstoned++;+ }+ }+ }++ // 2. Compact the log to the terminal entry per (type, id), preserving seq.+ // Keep insertion order by seq so the file stays monotonic for peers.+ const terminal = new Map(); // key -> entry (last wins)+ for (const e of logEntries) {+ if (e?.seq == null || !e.type || !e.id) continue;+ terminal.set(`${e.type}/${e.id}`, e);+ }+ const compactedLines = [...terminal.values()]+ .sort((a, b) => a.seq - b.seq)+ .map((e) => JSON.stringify(e));++ return { stores, compactedLines, ghostsTombstoned };+}++export async function up({ rootDir }) {+ const brainDir = join(rootDir, 'data', 'brain');+ const logPath = join(brainDir, 'sync_log.jsonl');++ if (!existsSync(logPath)) {+ console.log('🧹 brain-cleanup: no sync log present, nothing to do');+ return;+ }++ const logContent = await readFile(logPath, 'utf-8');+ const logEntries = parseLog(logContent);++ // Load the entity stores that exist on disk.+ const stores = {};+ for (const type of ENTITY_TYPES) {+ const file = join(brainDir, `${type}.json`);+ if (!existsSync(file)) continue;+ const raw = await readFile(file, 'utf-8').catch(() => null);+ if (raw == null) continue;+ try {+ const parsed = JSON.parse(raw);+ stores[type] = parsed && typeof parsed === 'object' && parsed.records ? parsed : { records: {} };+ } catch {+ // Skip an unparseable store rather than abort — the migration is idempotent.+ }+ }++ const nowIso = new Date().toISOString();+ const { compactedLines, ghostsTombstoned } = computeBrainCleanup(logEntries, stores, { nowIso });++ // Persist tombstoned stores (only those we loaded; only when changed is fine+ // to skip — rewriting an unchanged store is harmless and keeps the code simple).+ for (const type of ENTITY_TYPES) {+ if (!stores[type]) continue;+ await writeFile(join(brainDir, `${type}.json`), JSON.stringify(stores[type], null, 2));+ }++ // Rewrite the compacted log. Preserve trailing newline convention.+ const newContent = compactedLines.length > 0 ? compactedLines.join('\n') + '\n' : '';+ await writeFile(logPath, newContent);++ console.log(+ `🧹 brain-cleanup: tombstoned ${ghostsTombstoned} ghost record(s), compacted sync log ${logEntries.length} → ${compactedLines.length} entries`+ );+}++export default { up };diff --git a/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.js b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.jsnew file mode 100644index 0000000000..393c5ee2cf--- /dev/null+++ b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.js@@ -0,0 +1,120 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration, { computeBrainCleanup } from './080-brain-tombstone-and-synclog-cleanup.js';++let rootDir;+let brainDir;++beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-080-'));+ brainDir = join(rootDir, 'data', 'brain');+ mkdirSync(brainDir, { recursive: true });+});++afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+});++function writeLog(entries) {+ writeFileSync(join(brainDir, 'sync_log.jsonl'), entries.map((e) => JSON.stringify(e)).join('\n') + '\n');+}+function writeStore(type, records) {+ writeFileSync(join(brainDir, `${type}.json`), JSON.stringify({ records }, null, 2));+}+function readStore(type) {+ return JSON.parse(readFileSync(join(brainDir, `${type}.json`), 'utf-8'));+}+function readLogLines() {+ const p = join(brainDir, 'sync_log.jsonl');+ if (!existsSync(p)) return [];+ return readFileSync(p, 'utf-8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l));+}++describe('migration 080 — brain tombstone + sync-log cleanup', () => {+ it('no-ops when there is no sync log', async () => {+ await expect(migration.up({ rootDir })).resolves.not.toThrow();+ });++ it('converts a ghost (live record with a newer matching delete) into a tombstone', async () => {+ // The links record is live, but the log shows it was deleted AFTER its create.+ writeStore('links', {+ 'ghost-1': { url: 'https://x', updatedAt: '2026-01-01T00:00:00.000Z', originInstanceId: 'peer-a' },+ });+ writeLog([+ { seq: 1, op: 'create', type: 'links', id: 'ghost-1', record: { url: 'https://x', updatedAt: '2026-01-01T00:00:00.000Z' }, originInstanceId: 'peer-a' },+ { seq: 2, op: 'delete', type: 'links', id: 'ghost-1', record: { updatedAt: '2026-01-02T00:00:00.000Z' }, originInstanceId: 'peer-a' },+ ]);++ await migration.up({ rootDir });++ const rec = readStore('links').records['ghost-1'];+ expect(rec._deleted).toBe(true);+ expect(rec.updatedAt).toBe('2026-01-02T00:00:00.000Z');+ });++ it('leaves a live record whose delete is OLDER than the record (legit re-create) alone', async () => {+ writeStore('people', {+ 'p1': { name: 'Alice', updatedAt: '2026-02-01T00:00:00.000Z', originInstanceId: 'peer-a' },+ });+ writeLog([+ { seq: 1, op: 'delete', type: 'people', id: 'p1', record: { updatedAt: '2026-01-01T00:00:00.000Z' } },+ { seq: 2, op: 'create', type: 'people', id: 'p1', record: { name: 'Alice', updatedAt: '2026-02-01T00:00:00.000Z' } },+ ]);++ await migration.up({ rootDir });++ expect(readStore('people').records['p1']).toMatchObject({ name: 'Alice', updatedAt: '2026-02-01T00:00:00.000Z' });+ expect(readStore('people').records['p1']._deleted).toBeUndefined();+ });++ it('compacts the sync log to one terminal entry per (type,id) and preserves max seq', async () => {+ writeLog([+ { seq: 1, op: 'create', type: 'links', id: 'a', record: { updatedAt: '2026-01-01T00:00:00.000Z' } },+ { seq: 2, op: 'delete', type: 'links', id: 'a', record: { updatedAt: '2026-01-02T00:00:00.000Z' } },+ { seq: 3, op: 'create', type: 'links', id: 'a', record: { updatedAt: '2026-01-03T00:00:00.000Z' } },+ { seq: 4, op: 'create', type: 'people', id: 'b', record: { updatedAt: '2026-01-01T00:00:00.000Z' } },+ { seq: 5, op: 'delete', type: 'people', id: 'b', record: { updatedAt: '2026-01-05T00:00:00.000Z' } },+ ]);++ await migration.up({ rootDir });++ const lines = readLogLines();+ expect(lines).toHaveLength(2); // one terminal per (links/a) and (people/b)+ const maxSeq = Math.max(...lines.map((l) => l.seq));+ expect(maxSeq).toBe(5); // peer cursors stay valid — NOT renumbered to 0+ // Terminal entries are the last per key+ expect(lines.find((l) => l.id === 'a').seq).toBe(3);+ expect(lines.find((l) => l.id === 'b').seq).toBe(5);+ });++ it('is idempotent — a second run is a no-op', async () => {+ writeStore('links', {+ 'ghost-1': { url: 'https://x', updatedAt: '2026-01-01T00:00:00.000Z', originInstanceId: 'peer-a' },+ });+ writeLog([+ { seq: 1, op: 'create', type: 'links', id: 'ghost-1', record: { url: 'https://x', updatedAt: '2026-01-01T00:00:00.000Z' } },+ { seq: 2, op: 'delete', type: 'links', id: 'ghost-1', record: { updatedAt: '2026-01-02T00:00:00.000Z' } },+ ]);++ await migration.up({ rootDir });+ const storeAfter1 = readStore('links');+ const logAfter1 = readLogLines();++ await migration.up({ rootDir });+ expect(readStore('links')).toEqual(storeAfter1);+ expect(readLogLines()).toEqual(logAfter1);+ });++ it('computeBrainCleanup preserves the global max seq as a terminal entry', () => {+ const log = [+ { seq: 10, op: 'create', type: 'links', id: 'a', record: { updatedAt: '2026-01-01T00:00:00.000Z' } },+ { seq: 99, op: 'delete', type: 'links', id: 'a', record: { updatedAt: '2026-01-02T00:00:00.000Z' } },+ ];+ const { compactedLines } = computeBrainCleanup(log, {}, { nowIso: '2026-06-08T00:00:00.000Z' });+ const seqs = compactedLines.map((l) => JSON.parse(l).seq);+ expect(Math.max(...seqs)).toBe(99);+ });+});diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex daff93a4e1..a531b57de5 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -21,6 +21,32 @@ const withRemoteLock = createMutex();const DATA_DIR = PATHS.brain;+// A tombstone is a deleted-record marker kept IN PLACE in `data.records[id]`+// (rather than removing the key) so the last-writer-wins guard in+// applyRemoteRecord can reject a stale `create` echoed back from a peer.+// Without it, a hard delete leaves `existing === undefined`, the LWW guard is+// skipped, and the record resurrects — then the newer delete re-kills it, and+// both ops relay to every peer forever (the federated brain-sync loop).+// Shape: { _deleted: true, updatedAt, originInstanceId, deletedAt }. The+// `updatedAt` is the LWW clock; `deletedAt` is the GC clock.+const isTombstone = (rec) => !!(rec && rec._deleted);++// Build the in-place tombstone marker. `updatedAt` is the LWW clock (must be the+// delete's timestamp); `deletedAt` is the GC clock — equal at birth, kept+// separate so the GC sweep reads its own field.+const makeTombstone = (updatedAt, originInstanceId) => ({+ _deleted: true,+ updatedAt,+ originInstanceId: originInstanceId ?? 'unknown',+ deletedAt: updatedAt,+});++// GC grace period: how long a tombstone is retained before it can be hard-+// pruned. Must comfortably exceed the longest realistic peer-offline window so+// a peer that reconnects still sees the delete (not a since-vanished id that it+// would re-create). 30 days matches the sharing-side tombstone grace buffer.+export const BRAIN_TOMBSTONE_GRACE_MS = 30 * 24 * 60 * 60 * 1000;+// File pathsconst FILES = {meta: join(DATA_DIR, 'meta.json'),@@ -169,7 +195,11 @@ async function saveJsonStore(type, data) {*/export async function getAll(type) {const data = await loadJsonStore(type);- return Object.entries(data.records).map(([id, record]) => ({ id, ...record }));+ // Tombstones (deleted markers) are excluded from all read paths — they exist+ // only to anchor the LWW sync guard, never as user-visible records.+ return Object.entries(data.records)+ .filter(([, record]) => !isTombstone(record))+ .map(([id, record]) => ({ id, ...record }));}/**@@ -178,7 +208,7 @@ export async function getAll(type) {export async function getById(type, id) {const data = await loadJsonStore(type);const record = data.records[id];- return record ? { id, ...record } : null;+ return record && !isTombstone(record) ? { id, ...record } : null;}/**@@ -213,7 +243,8 @@ export async function create(type, recordData) {export async function update(type, id, updates) {const data = await loadJsonStore(type);- if (!data.records[id]) {+ // A tombstoned record is gone — treat it as not-found rather than reviving it.+ if (!data.records[id] || isTombstone(data.records[id])) {return null;}@@ -252,7 +283,7 @@ export async function updateMany(type, updates) {const applied = [];for (const { id, ...fields } of updates) {const existing = data.records[id];- if (!existing) continue;+ if (!existing || isTombstone(existing)) continue;const record = {...existing,...fields,@@ -282,17 +313,25 @@ export async function updateMany(type, updates) {export async function remove(type, id) {const data = await loadJsonStore(type);- if (!data.records[id]) {+ const existing = data.records[id];+ // Already gone (absent) or already tombstoned — nothing to delete, and+ // re-tombstoning would mint a redundant sync-log entry that relays needlessly.+ if (!existing || isTombstone(existing)) {return false;}- const originInstanceId = data.records[id]?.originInstanceId ?? 'unknown';- const deletedRecord = { id, ...data.records[id] };- const deleteRecord = { updatedAt: now() };- delete data.records[id];+ const originInstanceId = existing.originInstanceId ?? 'unknown';+ const deletedRecord = { id, ...existing };+ const ts = now();+ // Retain a tombstone in place (not a hard delete) so a stale `create` echoed+ // from a peer is rejected by the LWW guard in applyRemoteRecord.+ data.records[id] = makeTombstone(ts, originInstanceId);await saveJsonStore(type, data);brainEvents.emit(`${type}:deleted`, { id, record: deletedRecord });- await brainSyncLog.appendChange('delete', type, id, deleteRecord, originInstanceId)+ // Wire format unchanged: the sync-log delete entry still carries only+ // { updatedAt } so an older peer (no tombstone support) applies it as a+ // plain hard delete exactly as before.+ await brainSyncLog.appendChange('delete', type, id, { updatedAt: ts }, originInstanceId).catch(err => console.error(`⚠️ Sync log append failed for delete ${type}/${id}: ${err.message}`));console.log(`🧠 Deleted ${type} record: ${id}`);@@ -634,18 +673,30 @@ export async function applyRemoteRecord(type, id, record, op) {const data = await loadJsonStore(type);if (op === 'delete') {- if (!data.records[id]) return { applied: false, reason: 'not_found' };// Require updatedAt on delete operations for last-writer-wins conflict resolutionif (!record?.updatedAt) {return { applied: false, reason: 'missing_timestamp' };}- // LWW: only delete if local record isn't newer than the remote delete (>= for consistency with update path)- if (data.records[id].updatedAt >= record.updatedAt) {+ const existing = data.records[id];+ // LWW: skip if our copy (live record OR existing tombstone) is at least as+ // new as the incoming delete. The tombstone-vs-tombstone case makes a+ // repeated delete idempotent → not relayed → the echo loop converges.+ if (existing && existing.updatedAt >= record.updatedAt) {return { applied: false, reason: 'local_newer' };}- delete data.records[id];+ // Tombstone in place even when no local record exists. A delete that+ // arrives before we ever saw a create still leaves a marker, so a later+ // stale create for that id is rejected instead of resurrecting.+ data.records[id] = makeTombstone(+ record.updatedAt,+ record.originInstanceId ?? existing?.originInstanceId+ );} else {const existing = data.records[id];+ // Guard now also fires when `existing` is a tombstone — a stale create+ // (older updatedAt than the recorded delete) is rejected, breaking the+ // resurrection loop. A genuinely newer create (later updatedAt than the+ // tombstone) still wins and legitimately revives the record.if (existing && existing.updatedAt >= record.updatedAt) {return { applied: false, reason: 'local_newer' };}@@ -661,6 +712,34 @@ export async function applyRemoteRecord(type, id, record, op) {});}+/**+ * Hard-prune tombstones older than `cutoffMs` (a Date.now()-style epoch ms).+ * Called by the brain tombstone GC sweep on the orchestrator's interval.+ * Load-modify-save per store; writes only when something was pruned.+ * Returns the number of tombstones removed.+ */+export async function pruneTombstones(type, cutoffMs) {+ return withRemoteLock(async () => {+ const data = await loadJsonStore(type);+ let pruned = 0;+ for (const [id, record] of Object.entries(data.records)) {+ if (!isTombstone(record)) continue;+ const deletedAt = Date.parse(record.deletedAt ?? record.updatedAt ?? '');+ if (Number.isFinite(deletedAt) && deletedAt < cutoffMs) {+ delete data.records[id];+ pruned++;+ }+ }+ if (pruned > 0) {+ await ensureBrainDir();+ await writeFile(FILES[type], JSON.stringify(data, null, 2));+ caches[type].data = data;+ caches[type].timestamp = Date.now();+ }+ return pruned;+ });+}+/*** Backfill originInstanceId on records missing it (run once at startup)*/@@ -674,6 +753,8 @@ export async function backfillOriginInstanceId() {let changed = false;for (const [, record] of Object.entries(data.records)) {+ // Tombstones always carry originInstanceId; skip them.+ if (isTombstone(record)) continue;if (!record.originInstanceId) {record.originInstanceId = instanceId;changed = true;diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsnew file mode 100644index 0000000000..07c953be8c--- /dev/null+++ b/server/services/brainStorage.test.js@@ -0,0 +1,150 @@+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++// Allocate the temp dir lazily on first PATHS read — brainStorage's module+// graph (brainSyncLog) reads PATHS.brain at import time, before any top-level+// test assignment would run, so the dataRoot getter must self-initialize.+// `var` + a function declaration are both hoisted (no TDZ), so they're safe to+// reference from the hoisted vi.mock factory / import side-effects.+var tempRoot; // eslint-disable-line no-var+function getTempRoot() {+ if (!tempRoot) tempRoot = mkdtempSync(join(tmpdir(), 'brainstorage-test-'));+ return tempRoot;+}++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makePathsProxy(actual, {+ dataRoot: () => getTempRoot(),+ extraOverrides: (dataRoot) => ({ brain: join(dataRoot, 'brain') }),+ });+});++// getInstanceId is used by create()/backfill; stub to a stable id.+vi.mock('./instances.js', () => ({+ getInstanceId: () => Promise.resolve('local-instance'),+}));++import * as brainStorage from './brainStorage.js';++afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });++// Each test uses a fresh entity type slice by resetting caches; use distinct+// ids to avoid cross-test bleed within the shared temp store files.+beforeEach(() => {+ brainStorage.invalidateAllCaches();+});++const ISO = (s) => new Date(s).toISOString();++describe('brainStorage tombstones', () => {+ it('remove() writes a tombstone instead of hard-deleting, and hides it from reads', async () => {+ const created = await brainStorage.create('people', { name: 'Alice' });+ expect(await brainStorage.getById('people', created.id)).toMatchObject({ name: 'Alice' });++ const ok = await brainStorage.remove('people', created.id);+ expect(ok).toBe(true);++ // Hidden from reads+ expect(await brainStorage.getById('people', created.id)).toBeNull();+ const all = await brainStorage.getAll('people');+ expect(all.find((r) => r.id === created.id)).toBeUndefined();++ // But the tombstone is physically present in the store (not hard-deleted)+ brainStorage.invalidateAllCaches();+ const second = await brainStorage.remove('people', created.id);+ expect(second).toBe(false); // already tombstoned → no-op, no extra sync entry+ });++ it('applyRemoteRecord delete tombstones an unknown id (delete-before-create)', async () => {+ const res = await brainStorage.applyRemoteRecord(+ 'projects', 'ghost-1', { updatedAt: ISO('2026-01-02') }, 'delete'+ );+ expect(res.applied).toBe(true);++ // A stale create (older updatedAt) must be rejected by the tombstone guard+ const stale = await brainStorage.applyRemoteRecord(+ 'projects', 'ghost-1', { name: 'X', updatedAt: ISO('2026-01-01') }, 'create'+ );+ expect(stale.applied).toBe(false);+ expect(stale.reason).toBe('local_newer');+ expect(await brainStorage.getById('projects', 'ghost-1')).toBeNull();+ });++ it('rejects a stale create against an existing tombstone (the loop-breaker)', async () => {+ const created = await brainStorage.create('ideas', { title: 'T' });+ // Local delete at a known time+ await brainStorage.remove('ideas', created.id);+ const tombstoneTime = (await rawRecord('ideas', created.id)).updatedAt;++ // Peer echoes the original create with an OLDER updatedAt → must be rejected+ const echo = await brainStorage.applyRemoteRecord(+ 'ideas', created.id, { title: 'T', updatedAt: ISO('2000-01-01') }, 'create'+ );+ expect(echo.applied).toBe(false);+ expect(echo.reason).toBe('local_newer');+ // Still a tombstone, unchanged+ const rec = await rawRecord('ideas', created.id);+ expect(rec._deleted).toBe(true);+ expect(rec.updatedAt).toBe(tombstoneTime);+ });++ it('allows a genuinely newer create to resurrect a tombstone', async () => {+ await brainStorage.applyRemoteRecord(+ 'admin', 'r1', { updatedAt: ISO('2026-01-01') }, 'delete'+ );+ const revive = await brainStorage.applyRemoteRecord(+ 'admin', 'r1', { task: 'revived', updatedAt: ISO('2026-02-01') }, 'create'+ );+ expect(revive.applied).toBe(true);+ expect(await brainStorage.getById('admin', 'r1')).toMatchObject({ task: 'revived' });+ });++ it('delete is idempotent: re-applying the same delete is rejected (no relay)', async () => {+ const first = await brainStorage.applyRemoteRecord(+ 'links', 'l1', { updatedAt: ISO('2026-01-01') }, 'delete'+ );+ expect(first.applied).toBe(true);+ const again = await brainStorage.applyRemoteRecord(+ 'links', 'l1', { updatedAt: ISO('2026-01-01') }, 'delete'+ );+ expect(again.applied).toBe(false);+ expect(again.reason).toBe('local_newer');+ });++ it('update() treats a tombstone as not-found', async () => {+ const created = await brainStorage.create('buckets', { label: 'B' });+ await brainStorage.remove('buckets', created.id);+ const updated = await brainStorage.update('buckets', created.id, { label: 'B2' });+ expect(updated).toBeNull();+ });++ it('pruneTombstones removes only tombstones older than the cutoff', async () => {+ // Old tombstone+ await brainStorage.applyRemoteRecord('memories', 'old', { updatedAt: ISO('2020-01-01') }, 'delete');+ // Fresh tombstone (now)+ const freshCreated = await brainStorage.create('memories', { content: 'keep' });+ await brainStorage.remove('memories', freshCreated.id);+ // A live record that must survive+ const live = await brainStorage.create('memories', { content: 'alive' });++ const cutoff = Date.parse(ISO('2021-01-01'));+ const pruned = await brainStorage.pruneTombstones('memories', cutoff);+ expect(pruned).toBe(1); // only the 2020 tombstone++ expect(await rawRecord('memories', 'old')).toBeUndefined();+ expect((await rawRecord('memories', freshCreated.id))._deleted).toBe(true);+ expect(await brainStorage.getById('memories', live.id)).toMatchObject({ content: 'alive' });+ });+});++// Read the raw stored record (including tombstones) by bypassing the read filter.+async function rawRecord(type, id) {+ const { readFile } = await import('fs/promises');+ const file = join(getTempRoot(), 'brain', `${type}.json`);+ const data = JSON.parse(await readFile(file, 'utf-8'));+ return data.records[id];+}diff --git a/server/services/brainSync.js b/server/services/brainSync.jsindex 778fd5e821..db6767c820 100644--- a/server/services/brainSync.js+++ b/server/services/brainSync.js@@ -26,17 +26,28 @@ export async function applyRemoteChanges(changes) {const relayBatch = [];for (const change of changes) {- const { op, type, id, record, originInstanceId } = change;+ let { op, type, id, record, originInstanceId } = change;if (!ENTITY_TYPES.includes(type)) {skipped++;continue;}+ // Forward-compat: a future peer might ship a tombstone record as a+ // create/update (`record._deleted === true`). Route it through the delete+ // path with the wire-shape delete record so we tombstone it locally rather+ // than writing a resurrectable live record. Older peers never do this.+ if ((op === 'create' || op === 'update') && record?._deleted === true) {+ op = 'delete';+ record = { updatedAt: record.updatedAt, originInstanceId: record.originInstanceId ?? originInstanceId };+ }+if (op === 'delete') {const result = await brainStorage.applyRemoteRecord(type, id, record, 'delete');if (result.applied) {deleted++;+ // Relay only APPLIED changes — a rejected (local_newer) op is NOT+ // re-appended, which is what stops the cross-peer echo amplification.relayBatch.push({ op, type, id, record, originInstanceId });} else {skipped++;diff --git a/server/services/brainSync.test.js b/server/services/brainSync.test.jsindex 0e64af0f9d..e036da25ca 100644--- a/server/services/brainSync.test.js+++ b/server/services/brainSync.test.js@@ -111,6 +111,30 @@ describe('brainSync', () => {expect(appendChanges).not.toHaveBeenCalled();});+ it('routes a forward-compat create carrying a tombstone (_deleted) through the delete path', async () => {+ applyRemoteRecord.mockResolvedValue({ applied: true });++ const result = await applyRemoteChanges([+ {+ op: 'create',+ type: 'people',+ id: 'p9',+ record: { _deleted: true, updatedAt: '2026-03-01T00:00:00.000Z', originInstanceId: 'peer-2' },+ originInstanceId: 'peer-2',+ },+ ]);++ // Applied as a DELETE with the wire-shape delete record (no _deleted leaks+ // into a live store write).+ expect(applyRemoteRecord).toHaveBeenCalledWith(+ 'people', 'p9',+ { updatedAt: '2026-03-01T00:00:00.000Z', originInstanceId: 'peer-2' },+ 'delete'+ );+ expect(result.deleted).toBe(1);+ expect(result.inserted).toBe(0);+ });+it('handles mixed operations correctly', async () => {applyRemoteRecord.mockResolvedValueOnce({ applied: true }) // create peoplediff --git a/server/services/brainTombstoneGc.js b/server/services/brainTombstoneGc.jsnew file mode 100644index 0000000000..50bdde0c16--- /dev/null+++ b/server/services/brainTombstoneGc.js@@ -0,0 +1,36 @@+/**+ * Brain Tombstone GC+ *+ * Brain entity deletes leave a tombstone in place (see brainStorage.remove /+ * applyRemoteRecord) so the LWW sync guard can reject a stale `create` echoed+ * from a peer. Tombstones can't live forever, so this sweep hard-prunes any+ * older than a grace period.+ *+ * Grace-period (not cursor-watermark) pruning is sufficient under the+ * single-user trust model: by the time the grace window elapses, every healthy+ * peer has long since received and applied the delete (the sync log is+ * compacted below the minimum peer cursor), so there is no live `create` left+ * in circulation to resurrect the id. A peer offline longer than the grace+ * window is effectively a fresh re-sync — an acceptable trade-off.+ *+ * Mirrors the sharing-side tombstoneGc.js pattern; runs on the sync+ * orchestrator's existing 60s interval.+ */++import * as brainStorage from './brainStorage.js';++const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets'];++/**+ * Prune brain tombstones older than the grace period.+ * @param {{ now?: number, graceMs?: number }} [opts]+ * @returns {Promise<{ pruned: number }>}+ */+export async function sweepBrainTombstones({ now = Date.now(), graceMs = brainStorage.BRAIN_TOMBSTONE_GRACE_MS } = {}) {+ const cutoff = now - graceMs;+ let pruned = 0;+ for (const type of ENTITY_TYPES) {+ pruned += await brainStorage.pruneTombstones(type, cutoff);+ }+ return { pruned };+}diff --git a/server/services/brainTombstoneGc.test.js b/server/services/brainTombstoneGc.test.jsnew file mode 100644index 0000000000..94ce03c0c0--- /dev/null+++ b/server/services/brainTombstoneGc.test.js@@ -0,0 +1,37 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const pruneTombstones = vi.fn();+vi.mock('./brainStorage.js', () => ({+ pruneTombstones: (...args) => pruneTombstones(...args),+ BRAIN_TOMBSTONE_GRACE_MS: 30 * 24 * 60 * 60 * 1000,+}));++import { sweepBrainTombstones } from './brainTombstoneGc.js';++const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets'];++describe('brainTombstoneGc', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('prunes every entity type with a cutoff = now - grace and sums the counts', async () => {+ pruneTombstones.mockResolvedValue(2);+ const now = 1_000_000_000_000;+ const graceMs = 1000;++ const result = await sweepBrainTombstones({ now, graceMs });++ expect(result.pruned).toBe(2 * ENTITY_TYPES.length);+ expect(pruneTombstones).toHaveBeenCalledTimes(ENTITY_TYPES.length);+ for (const type of ENTITY_TYPES) {+ expect(pruneTombstones).toHaveBeenCalledWith(type, now - graceMs);+ }+ });++ it('returns pruned:0 when nothing is old enough', async () => {+ pruneTombstones.mockResolvedValue(0);+ const result = await sweepBrainTombstones({ now: 1_000_000_000_000, graceMs: 1000 });+ expect(result.pruned).toBe(0);+ });+});diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 4528cd1f62..b116cfba5b 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -766,6 +766,11 @@ export function initSyncOrchestrator() {runTombstoneSweep().catch(err => {console.error(`❌ Tombstone sweep tick failed: ${err.message}`);});+ // Brain entity tombstones ride the same tick — same once-a-minute cadence,+ // same rejection (a rejected dynamic import would otherwise crash the tick).+ runBrainTombstoneSweep().catch(err => {+ console.error(`❌ Brain tombstone sweep tick failed: ${err.message}`);+ });}, SYNC_INTERVAL_MS);console.log(`🔄 Sync orchestrator started (${SYNC_INTERVAL_MS / 1000}s interval)`);@@ -799,6 +804,23 @@ async function runTombstoneSweep() {}}+/**+ * Run a single brain-tombstone GC sweep, fire-and-forget. Dynamic import keeps+ * brainTombstoneGc (→ brainStorage) off the orchestrator's module-load path,+ * matching runTombstoneSweep above. Logs a one-line summary only when something+ * was actually pruned — quiet on no-op cycles.+ */+async function runBrainTombstoneSweep() {+ const { sweepBrainTombstones } = await import('./brainTombstoneGc.js');+ const result = await sweepBrainTombstones().catch((err) => {+ console.error(`❌ Brain tombstone sweep failed: ${err.message}`);+ return null;+ });+ if (result && result.pruned > 0) {+ console.log(`🪦 Brain tombstone GC: pruned ${result.pruned} tombstone${result.pruned === 1 ? '' : 's'}`);+ }+}+/*** Stop the sync orchestrator*/