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
address review (claude): harden tombstone guard + migration seq preservation
Adam Eivy96a9ede4597c
diff --git a/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.js b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.jsindex cdfe5f349d..f395a08bf4 100644--- a/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.js+++ b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.js@@ -92,11 +92,21 @@ export function computeBrainCleanup(logEntries, stores, { nowIso }) {// 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)+ let maxSeqEntry = null; // the single highest-seq entry, type/id or notfor (const e of logEntries) {- if (e?.seq == null || !e.type || !e.id) continue;+ if (e?.seq == null) continue;+ if (!maxSeqEntry || e.seq > maxSeqEntry.seq) maxSeqEntry = e;+ if (!e.type || !e.id) continue;terminal.set(`${e.type}/${e.id}`, e);}- const compactedLines = [...terminal.values()]+ const kept = [...terminal.values()];+ // Guarantee the max seq survives even if the highest-seq entry lacks type/id+ // (every real appendChange sets both today, but the peer-cursor-validity+ // invariant must not depend on that). Append it only if not already kept.+ if (maxSeqEntry && !kept.some((e) => e.seq === maxSeqEntry.seq)) {+ kept.push(maxSeqEntry);+ }+ const compactedLines = kept.sort((a, b) => a.seq - b.seq).map((e) => JSON.stringify(e));@@ -124,7 +134,12 @@ export async function up({ rootDir }) {if (raw == null) continue;try {const parsed = JSON.parse(raw);- stores[type] = parsed && typeof parsed === 'object' && parsed.records ? parsed : { records: {} };+ // Preserve any other top-level keys the store may carry — only normalize+ // the `records` map. (Brain stores hold only `records` today, but dropping+ // unknown keys would be a latent data-loss path if the shape ever grows.)+ stores[type] = parsed && typeof parsed === 'object'+ ? { ...parsed, records: parsed.records ?? {} }+ : { records: {} };} catch {// Skip an unparseable store rather than abort — the migration is idempotent.}diff --git a/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.js b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.jsindex 393c5ee2cf..c57ed5fbc8 100644--- a/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.js+++ b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.js@@ -117,4 +117,14 @@ describe('migration 080 — brain tombstone + sync-log cleanup', () => {const seqs = compactedLines.map((l) => JSON.parse(l).seq);expect(Math.max(...seqs)).toBe(99);});++ it('preserves max seq even when the highest-seq entry lacks type/id', () => {+ const log = [+ { seq: 10, op: 'create', type: 'links', id: 'a', record: { updatedAt: '2026-01-01T00:00:00.000Z' } },+ { seq: 200 }, // a malformed/typeless high-seq entry — must still anchor the cursor+ ];+ 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(200);+ });});diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex 2e6206c9f3..fe6de6fec6 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -701,6 +701,13 @@ export async function applyRemoteRecord(type, id, record, op) {record.originInstanceId ?? existing?.originInstanceId);} else {+ // A create/update with no updatedAt has no LWW clock — `existing.updatedAt+ // >= undefined` is always false, which would let it silently overwrite a+ // tombstone and resurrect a deleted record. Reject it (mirrors the delete+ // path) so the loop-breaker can't be defeated by a timestamp-less create.+ if (!record?.updatedAt) {+ return { applied: false, reason: 'missing_timestamp' };+ }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@@ -709,7 +716,12 @@ export async function applyRemoteRecord(type, id, record, op) {if (existing && existing.updatedAt >= record.updatedAt) {return { applied: false, reason: 'local_newer' };}- data.records[id] = { ...record };+ // Defense-in-depth: a create carrying `_deleted` (a future peer, or a+ // direct caller bypassing brainSync's reroute) must persist as a proper+ // tombstone, never as a malformed live record missing `deletedAt`.+ data.records[id] = record._deleted+ ? makeTombstone(record.updatedAt, record.originInstanceId ?? existing?.originInstanceId)+ : { ...record };}await ensureBrainDir();diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsindex 07c953be8c..497c87b7e1 100644--- a/server/services/brainStorage.test.js+++ b/server/services/brainStorage.test.js@@ -92,6 +92,27 @@ describe('brainStorage tombstones', () => {expect(rec.updatedAt).toBe(tombstoneTime);});+ it('rejects a create with no updatedAt (cannot defeat the tombstone guard)', async () => {+ await brainStorage.applyRemoteRecord('people', 'no-ts', { updatedAt: ISO('2026-01-01') }, 'delete');+ const res = await brainStorage.applyRemoteRecord('people', 'no-ts', { name: 'X' }, 'create');+ expect(res.applied).toBe(false);+ expect(res.reason).toBe('missing_timestamp');+ expect(await brainStorage.getById('people', 'no-ts')).toBeNull();+ });++ it('persists a _deleted create as a proper tombstone (defense-in-depth)', async () => {+ const res = await brainStorage.applyRemoteRecord(+ 'projects', 'fwd-1',+ { _deleted: true, updatedAt: ISO('2026-04-01'), originInstanceId: 'peer-z' },+ 'create'+ );+ expect(res.applied).toBe(true);+ const rec = await rawRecord('projects', 'fwd-1');+ expect(rec._deleted).toBe(true);+ expect(rec.deletedAt).toBe(ISO('2026-04-01')); // not a malformed live record+ expect(await brainStorage.getById('projects', 'fwd-1')).toBeNull();+ });+it('allows a genuinely newer create to resurrect a tombstone', async () => {await brainStorage.applyRemoteRecord('admin', 'r1', { updatedAt: ISO('2026-01-01') }, 'delete'