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([issue-1077]): brain anti-entropy reconcile + correct compaction floor + scoped-checksum status
Adam Eivy5217deb16845
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 32ac80a751..fa3ff64e61 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -29,3 +29,4 @@## 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.+- **[issue-1077] Federated Brain now re-converges instead of silently diverging** — Brain sync between machines was delta-only: each peer pulled change-log entries since its last position. That alone wasn't enough to guarantee two machines ended up identical — if a peer was offline (or had sync off) while the change log was trimmed to bound its growth, any records whose entries had already been trimmed were lost to that peer *forever*, with no way to catch up. Two machines could quietly drift apart (in one real case, one machine was missing 21 links/projects/ideas the other had) while the UI still showed everything as fine. Three fixes: (1) Brain now does a periodic full reconcile — after the normal delta pull, the two machines compare a checksum of their entire Brain and, only if it differs, exchange a full snapshot and merge it (newest edit wins, deletes respected), so a machine that missed trimmed entries re-converges automatically; (2) the change log is now trimmed only below what every machine has actually pulled *from you* (not how far you've pulled from *them*), so entries a peer still needs are never dropped; (3) the peer card no longer mislabels a category "behind" when both machines are actually in sync (it was comparing a per-peer-scoped checksum against a whole-instance one — e.g. "Media Collections: behind" when both sides were empty). Brain has no per-record push pipeline, so the reconcile is a simple whole-Brain snapshot, applied idempotently; older peers that don't expose the new reconcile endpoints keep working on delta sync alone.diff --git a/server/routes/brain.js b/server/routes/brain.jsindex 45ed5e00c6..fbbdf57382 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -44,6 +44,7 @@ import { getBrainGraphData } from '../services/brainGraph.js';import { syncAllBrainData } from '../services/brainMemoryBridge.js';import * as brainSyncLog from '../services/brainSyncLog.js';import * as brainSync from '../services/brainSync.js';+import * as brainReconcile from '../services/brainReconcile.js';import * as journal from '../services/brainJournal.js';import { loadSlashdoCommand } from '../services/subAgentSpawner.js';import * as cos from '../services/cos.js';@@ -991,6 +992,28 @@ router.post('/sync', asyncHandler(async (req, res) => {res.json(result);}));+/**+ * GET /api/brain/reconcile/checksum+ * Anti-entropy checksum over ALL brain records (incl. tombstones) — #1077.+ * A peer fetches this after draining the delta log; on a mismatch it pulls the+ * full snapshot below. Lightweight (one hash) so it's cheap to poll each cycle.+ */+router.get('/reconcile/checksum', asyncHandler(async (req, res) => {+ const checksum = await brainReconcile.getBrainChecksum();+ res.json({ checksum });+}));++/**+ * GET /api/brain/reconcile/snapshot+ * Full brain snapshot (raw record map incl. tombstones + checksum) for a peer+ * to LWW-merge. Brain has no per-record push pipeline, so this is unscoped —+ * the receiver applies it idempotently via applyRemoteRecord.+ */+router.get('/reconcile/snapshot', asyncHandler(async (req, res) => {+ const snapshot = await brainReconcile.getBrainSnapshot();+ res.json(snapshot);+}));+// =============================================================================// DAILY LOG// =============================================================================diff --git a/server/routes/brain.test.js b/server/routes/brain.test.jsindex f20deec783..0fa5bd4244 100644--- a/server/routes/brain.test.js+++ b/server/routes/brain.test.js@@ -90,6 +90,13 @@ vi.mock('../services/brainSync.js', () => ({applyRemoteChanges: vi.fn()}));+// Mock the brain anti-entropy reconcile service (#1077)+vi.mock('../services/brainReconcile.js', () => ({+ getBrainChecksum: vi.fn(),+ getBrainSnapshot: vi.fn(),+ applyBrainSnapshot: vi.fn()+}));+// Mock the brain journal servicevi.mock('../services/brainJournal.js', () => ({listJournals: vi.fn(),@@ -119,6 +126,7 @@ import * as brainService from '../services/brain.js';import { getBrainGraphData } from '../services/brainGraph.js';import { syncAllBrainData } from '../services/brainMemoryBridge.js';import { getChangesSince } from '../services/brainSyncLog.js';+import { getBrainChecksum, getBrainSnapshot } from '../services/brainReconcile.js';import { applyRemoteChanges } from '../services/brainSync.js';import * as journal from '../services/brainJournal.js';@@ -1019,6 +1027,25 @@ describe('Brain Routes', () => {});});+ describe('GET /api/brain/reconcile/checksum (#1077)', () => {+ it('returns the whole-brain reconcile checksum', async () => {+ getBrainChecksum.mockResolvedValue('abc123');+ const response = await request(app).get('/api/brain/reconcile/checksum');+ expect(response.status).toBe(200);+ expect(response.body).toEqual({ checksum: 'abc123' });+ });+ });++ describe('GET /api/brain/reconcile/snapshot (#1077)', () => {+ it('returns the raw record map + checksum', async () => {+ const snap = { records: { links: { x: { id: 'x', updatedAt: '2026-01-01T00:00:00.000Z' } } }, checksum: 'abc123' };+ getBrainSnapshot.mockResolvedValue(snap);+ const response = await request(app).get('/api/brain/reconcile/snapshot');+ expect(response.status).toBe(200);+ expect(response.body).toEqual(snap);+ });+ });+describe('POST /api/brain/sync', () => {it('should apply remote changes and return stats', async () => {const mockResult = { inserted: 2, updated: 1, deleted: 0, skipped: 1 };diff --git a/server/services/brainReconcile.js b/server/services/brainReconcile.jsnew file mode 100644index 0000000000..99e4fa3eb4--- /dev/null+++ b/server/services/brainReconcile.js@@ -0,0 +1,134 @@+/**+ * Brain Anti-Entropy Reconcile+ *+ * Brain peer-sync is delta-log-based (see brainSyncLog.js): a peer pulls change+ * entries since its cursor. That alone is NOT eventually-consistent — once a+ * record's create/update entry is compacted out of the log, a peer that never+ * pulled it (was offline, had a stale cursor, or had sync disabled during the+ * window) can never learn that record's state again. The two installs then+ * diverge silently and forever (issue #1077).+ *+ * This module adds the missing anti-entropy layer, mirroring the snapshot+ * reconcile that the `dataSync` snapshot categories already have:+ *+ * - `getBrainChecksum()` — a deterministic hash over EVERY record across all+ * brain stores, INCLUDING tombstones (their LWW `updatedAt` clock is part+ * of the converged state). Two installs with identical brain state produce+ * identical checksums regardless of key/insertion order.+ * - `getBrainSnapshot()` — the raw `{ type: { id: record } }` map (live records+ * + tombstones) plus that checksum, for a peer to LWW-merge.+ * - `applyBrainSnapshot(snapshot)` — LWW-merges each record through+ * `brainStorage.applyRemoteRecord`, so the apply is idempotent and obeys the+ * same tombstone/echo guards as delta sync. Returns per-op counts.+ *+ * Brain has NO per-record push pipeline (unlike universe/pipeline/media), so+ * there is nothing to scope out per peer — the snapshot is always the full set,+ * applied idempotently. That keeps this layer simple and forward/backward+ * compatible: an older peer that never calls these endpoints just keeps using+ * delta sync; a newer peer reconciles on top.+ */++import { createHash } from 'crypto';+import * as brainStorage from './brainStorage.js';+import * as brainSyncLog from './brainSyncLog.js';++const { BRAIN_ENTITY_TYPES } = brainStorage;++/**+ * Build the canonical `{ type: { id: record } }` map across all brain stores,+ * including tombstones. Types and ids are emitted in sorted order so the+ * serialization (and thus the checksum) is independent of object key order.+ */+async function buildRawMap() {+ const map = {};+ for (const type of [...BRAIN_ENTITY_TYPES].sort()) {+ const records = await brainStorage.getRawRecords(type);+ const sorted = {};+ for (const id of Object.keys(records).sort()) {+ sorted[id] = records[id];+ }+ map[type] = sorted;+ }+ return map;+}++/**+ * Deterministic md5 over the canonical brain record map. Matches `dataSync`'s+ * `computeChecksum` (md5 of a JSON string) so the two reconcile layers behave+ * the same. Stable across installs because `buildRawMap` sorts types + ids.+ */+function computeChecksum(rawMap) {+ return createHash('md5').update(JSON.stringify(rawMap)).digest('hex');+}++/**+ * Current brain reconcile checksum. Lightweight relative to the snapshot — a+ * peer fetches this first and only pulls the full snapshot on a mismatch.+ */+export async function getBrainChecksum() {+ return computeChecksum(await buildRawMap());+}++/**+ * Full brain snapshot: the canonical raw map + its checksum. The receiver+ * LWW-merges it; the checksum lets it cache + skip an unchanged peer next cycle.+ */+export async function getBrainSnapshot() {+ const records = await buildRawMap();+ return { records, checksum: computeChecksum(records) };+}++/**+ * LWW-merge a peer's brain snapshot into local state.+ *+ * Each record is applied through `brainStorage.applyRemoteRecord`, which is+ * idempotent and enforces the tombstone/LWW guards (a stale create can't+ * resurrect a newer delete; an equal/older `updatedAt` is skipped). A tombstone+ * record (`_deleted === true`) is applied as a delete so the deletion+ * propagates; everything else is an upsert. Unknown types are ignored+ * (forward-compat with a peer that adds a new store).+ *+ * Applied changes are relayed to OUR sync log so they propagate onward to other+ * peers and our delta cursor stays meaningful — mirroring `brainSync`'s relay,+ * and gated the same way (only APPLIED ops relay, so an echo can't amplify).+ *+ * @returns {Promise<{inserted:number, updated:number, deleted:number, skipped:number}>}+ */+export async function applyBrainSnapshot(snapshot) {+ let inserted = 0, updated = 0, deleted = 0, skipped = 0;+ const relayBatch = [];++ const records = snapshot?.records;+ if (!records || typeof records !== 'object') {+ return { inserted, updated, deleted, skipped };+ }++ for (const type of Object.keys(records)) {+ if (!BRAIN_ENTITY_TYPES.includes(type)) continue;+ const byId = records[type];+ if (!byId || typeof byId !== 'object') continue;++ for (const [id, record] of Object.entries(byId)) {+ if (!record || !record.updatedAt) { skipped++; continue; }+ const op = record._deleted === true ? 'delete' : 'update';+ // For a delete, hand applyRemoteRecord the wire-shape tombstone fields+ // (it rebuilds the marker); for an upsert, pass the record through.+ const applyRecord = op === 'delete'+ ? { updatedAt: record.updatedAt, originInstanceId: record.originInstanceId }+ : record;+ const result = await brainStorage.applyRemoteRecord(type, id, applyRecord, op);+ if (!result.applied) { skipped++; continue; }+ if (op === 'delete') deleted++;+ else updated++;+ relayBatch.push({ op, type, id, record: applyRecord, originInstanceId: record.originInstanceId });+ }+ }++ if (relayBatch.length > 0) {+ await brainSyncLog.appendChanges(relayBatch)+ .catch(err => console.error(`⚠️ Brain reconcile relay append failed (${relayBatch.length} entries): ${err.message}`));+ }++ console.log(`🔄 Brain reconcile applied: ${updated} upserted, ${deleted} deleted, ${skipped} skipped`);+ return { inserted, updated, deleted, skipped };+}diff --git a/server/services/brainReconcile.test.js b/server/services/brainReconcile.test.jsnew file mode 100644index 0000000000..af8db5f854--- /dev/null+++ b/server/services/brainReconcile.test.js@@ -0,0 +1,128 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// brainStorage is the data layer; mock it so the reconcile logic is tested in+// isolation (matching the inline-copy / mock style used across sync tests).+vi.mock('./brainStorage.js', () => ({+ BRAIN_ENTITY_TYPES: ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets'],+ getRawRecords: vi.fn(),+ applyRemoteRecord: vi.fn(),+}));+vi.mock('./brainSyncLog.js', () => ({+ appendChanges: vi.fn().mockResolvedValue([]),+}));++import * as brainStorage from './brainStorage.js';+import * as brainSyncLog from './brainSyncLog.js';+import { getBrainChecksum, getBrainSnapshot, applyBrainSnapshot } from './brainReconcile.js';++// Default: every store empty unless a test overrides a specific type.+function emptyStores(overrides = {}) {+ brainStorage.getRawRecords.mockImplementation(async (type) => overrides[type] ?? {});+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe('brainReconcile checksum', () => {+ it('is deterministic regardless of record/type key order', async () => {+ emptyStores({+ links: {+ b: { id: 'b', updatedAt: '2026-01-02T00:00:00.000Z', title: 'B' },+ a: { id: 'a', updatedAt: '2026-01-01T00:00:00.000Z', title: 'A' },+ },+ });+ const c1 = await getBrainChecksum();++ // Same data, opposite insertion order → identical checksum.+ emptyStores({+ links: {+ a: { id: 'a', updatedAt: '2026-01-01T00:00:00.000Z', title: 'A' },+ b: { id: 'b', updatedAt: '2026-01-02T00:00:00.000Z', title: 'B' },+ },+ });+ const c2 = await getBrainChecksum();++ expect(c1).toBe(c2);+ });++ it('changes when a record changes', async () => {+ emptyStores({ links: { a: { id: 'a', updatedAt: '2026-01-01T00:00:00.000Z', title: 'A' } } });+ const before = await getBrainChecksum();+ emptyStores({ links: { a: { id: 'a', updatedAt: '2026-01-03T00:00:00.000Z', title: 'A2' } } });+ const after = await getBrainChecksum();+ expect(before).not.toBe(after);+ });++ it('includes tombstones in the checksum (a delete changes converged state)', async () => {+ emptyStores({ links: { a: { id: 'a', updatedAt: '2026-01-01T00:00:00.000Z', title: 'A' } } });+ const live = await getBrainChecksum();+ emptyStores({ links: { a: { _deleted: true, updatedAt: '2026-01-05T00:00:00.000Z', deletedAt: '2026-01-05T00:00:00.000Z', originInstanceId: 'x' } } });+ const tomb = await getBrainChecksum();+ expect(live).not.toBe(tomb);+ });+});++describe('brainReconcile snapshot', () => {+ it('returns the raw record map + matching checksum', async () => {+ emptyStores({ projects: { p1: { id: 'p1', updatedAt: '2026-01-01T00:00:00.000Z', name: 'P' } } });+ const snap = await getBrainSnapshot();+ expect(snap.records.projects.p1.name).toBe('P');+ expect(snap.checksum).toBe(await getBrainChecksum());+ });+});++describe('applyBrainSnapshot', () => {+ it('upserts live records and tombstones deletes via applyRemoteRecord (LWW)', async () => {+ brainStorage.applyRemoteRecord.mockResolvedValue({ applied: true });+ const snapshot = {+ records: {+ links: {+ live1: { id: 'live1', updatedAt: '2026-01-02T00:00:00.000Z', title: 'L' },+ dead1: { _deleted: true, updatedAt: '2026-01-03T00:00:00.000Z', originInstanceId: 'peer' },+ },+ },+ };+ const res = await applyBrainSnapshot(snapshot);++ expect(brainStorage.applyRemoteRecord).toHaveBeenCalledWith(+ 'links', 'live1', snapshot.records.links.live1, 'update');+ expect(brainStorage.applyRemoteRecord).toHaveBeenCalledWith(+ 'links', 'dead1', { updatedAt: '2026-01-03T00:00:00.000Z', originInstanceId: 'peer' }, 'delete');+ expect(res).toEqual({ inserted: 0, updated: 1, deleted: 1, skipped: 0 });+ });++ it('relays ONLY applied changes to the sync log (no echo amplification)', async () => {+ // First record applies, second is rejected (local_newer) — only the first relays.+ brainStorage.applyRemoteRecord+ .mockResolvedValueOnce({ applied: true })+ .mockResolvedValueOnce({ applied: false, reason: 'local_newer' });+ await applyBrainSnapshot({+ records: { links: {+ x: { id: 'x', updatedAt: '2026-01-02T00:00:00.000Z', title: 'X' },+ y: { id: 'y', updatedAt: '2026-01-01T00:00:00.000Z', title: 'Y' },+ } },+ });+ expect(brainSyncLog.appendChanges).toHaveBeenCalledTimes(1);+ const relayed = brainSyncLog.appendChanges.mock.calls[0][0];+ expect(relayed.map(r => r.id)).toEqual(['x']);+ });++ it('skips records missing updatedAt (no LWW clock) and unknown types', async () => {+ brainStorage.applyRemoteRecord.mockResolvedValue({ applied: true });+ const res = await applyBrainSnapshot({+ records: {+ links: { noClock: { id: 'noClock', title: 'no ts' } },+ bogusType: { z: { id: 'z', updatedAt: '2026-01-02T00:00:00.000Z' } },+ },+ });+ expect(brainStorage.applyRemoteRecord).not.toHaveBeenCalled();+ expect(res.skipped).toBe(1); // only the known-type no-clock record counts as skipped+ });++ it('tolerates a missing/!object records payload', async () => {+ const res = await applyBrainSnapshot({});+ expect(res).toEqual({ inserted: 0, updated: 0, deleted: 0, skipped: 0 });+ expect(brainStorage.applyRemoteRecord).not.toHaveBeenCalled();+ });+});diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex fe6de6fec6..e055e9ff12 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -211,6 +211,19 @@ export async function getAll(type) {.map(([id, record]) => ({ id, ...record }));}+/**+ * Get the RAW records map for a store, INCLUDING tombstones, keyed by id.+ *+ * Unlike `getAll` (which strips tombstones for user-facing reads), the sync+ * reconcile path needs tombstones too: they carry the LWW `updatedAt` clock a+ * peer must see to keep a delete from resurrecting. Returns a shallow copy of+ * the `{ id: record }` map so callers can't mutate the cache.+ */+export async function getRawRecords(type) {+ const data = await loadJsonStore(type);+ return { ...data.records };+}+/*** Get a record by ID*/diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsindex 497c87b7e1..d8fca2d508 100644--- a/server/services/brainStorage.test.js+++ b/server/services/brainStorage.test.js@@ -59,6 +59,21 @@ describe('brainStorage tombstones', () => {expect(second).toBe(false); // already tombstoned → no-op, no extra sync entry});+ it('getRawRecords surfaces tombstones that getAll hides (sync reconcile path #1077)', async () => {+ const created = await brainStorage.create('ideas', { title: 'RawIdea', oneLiner: 'x' });+ await brainStorage.remove('ideas', created.id);++ // getAll strips the tombstone…+ const visible = await brainStorage.getAll('ideas');+ expect(visible.find((r) => r.id === created.id)).toBeUndefined();++ // …but getRawRecords keeps it (with its LWW clock) for snapshot reconcile.+ const raw = await brainStorage.getRawRecords('ideas');+ expect(raw[created.id]).toBeDefined();+ expect(raw[created.id]._deleted).toBe(true);+ expect(raw[created.id].updatedAt).toBeTruthy();+ });+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'diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex a2bd796ad5..a3651c43f4 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -16,6 +16,7 @@ import { peerBaseUrl } from '../lib/peerUrl.js';import { peerAuthHeaders } from '../lib/peerHttpClient.js';import * as brainSync from './brainSync.js';import * as brainSyncLog from './brainSyncLog.js';+import * as brainReconcile from './brainReconcile.js';import * as memorySync from './memorySync.js';import * as catalogSync from './catalogSync.js';import * as dataSync from './dataSync.js';@@ -121,12 +122,20 @@ async function syncImageFromPeer(peer, avatarPath) {export async function getSyncStatus({ includeChecksums = false, forPeer = null } = {}) {const isPostgres = getBackendName() === 'postgres';const snapshotCategories = includeChecksums ? dataSync.getSupportedCategories() : [];+ // Scope the served checksums to the REQUESTING peer (#1077 Bug 3). The peer's+ // cursor caches the `forPeer`-scoped checksum it pulled (source excludes+ // records it pushes per-record), so a self-view UNscoped (global) checksum+ // here would never match the cursor for any per-record-subscribable category+ // (universe/pipeline/mediaCollections) — making them read "behind" forever,+ // even when both sides are empty. An absent `forPeer` (self-view, older peer)+ // keeps the unscoped global checksum (forPeerId: undefined).+ const forPeerId = isNonEmptyStr(forPeer) ? forPeer : undefined;const [brainSeq, memorySeq, catalogSeqs, cursors, ...checksumResults] = await Promise.all([Promise.resolve(brainSyncLog.getCurrentSeq()),isPostgres ? memorySync.getMaxSequence() : Promise.resolve(null),isPostgres ? catalogSync.getMaxSequences().catch(() => null) : Promise.resolve(null),loadCursors(),- ...snapshotCategories.map(cat => dataSync.getChecksum(cat).catch(() => null))+ ...snapshotCategories.map(cat => dataSync.getChecksum(cat, { forPeerId }).catch(() => null))]);const local = { brainSeq, memorySeq, catalogSeqs };if (includeChecksums) {@@ -168,7 +177,46 @@ async function syncBrainFromPeer(peer, cursor) {hasMore = data.hasMore;}- return { brainSeq, totalApplied };+ // --- Anti-entropy reconcile (#1077) ---+ // Delta sync alone diverges once log entries are compacted away. After+ // draining the log, compare a whole-brain checksum with the peer; on a+ // mismatch, pull the full snapshot and LWW-merge it (idempotent). This is the+ // ONLY path that re-converges a peer that missed compacted entries. Scoped to+ // brain (no per-record push pipeline), so the snapshot is always the full set.+ //+ // Cheap-path skips, in order:+ // 1. peer too old to expose /reconcile/checksum → null → delta-only (legacy),+ // leaving the cached checksum untouched.+ // 2. peer checksum === our cached checksum for this peer → nothing changed+ // on their side since we last reconciled → skip (the init value already+ // holds it; no work).+ // 3. peer checksum === our CURRENT local checksum → already converged → just+ // cache the peer checksum so step 2 short-circuits next cycle.+ // Returns `brainChecksum` so the caller caches the converged value on the+ // cursor (cache key is the peer checksum we reconciled against).+ let brainChecksum = cursor.brainChecksum ?? null;+ const remote = await fetchPeer(peer, '/api/brain/reconcile/checksum');+ const remoteChecksum = isNonEmptyStr(remote?.checksum) ? remote.checksum : null;+ if (remoteChecksum && remoteChecksum !== cursor.brainChecksum) {+ const localChecksum = await brainReconcile.getBrainChecksum().catch(() => null);+ if (remoteChecksum === localChecksum) {+ // Already converged — record the peer checksum so we skip next cycle.+ brainChecksum = remoteChecksum;+ } else {+ const snapshot = await fetchPeer(peer, '/api/brain/reconcile/snapshot');+ if (snapshot?.records) {+ const result = await brainReconcile.applyBrainSnapshot(snapshot);+ totalApplied += result.inserted + result.updated + result.deleted;+ // Cache the peer's served checksum so an unchanged peer short-circuits+ // at step 2 next cycle. (Our post-merge local checksum may differ from+ // the peer's if WE hold records THEY lack — that asymmetry is fine; the+ // peer reconciles those from us on its own cycle.)+ brainChecksum = isNonEmptyStr(snapshot.checksum) ? snapshot.checksum : remoteChecksum;+ }+ }+ }++ return { brainSeq, totalApplied, brainChecksum };}/**@@ -692,7 +740,16 @@ export async function syncWithPeer(peer) {// --- Single consolidated cursor write ---await withCursors(async (cursors) => {if (!cursors[peerId]) cursors[peerId] = {};- if (categories.brain) cursors[peerId].brainSeq = brainResult.brainSeq;+ if (categories.brain) {+ cursors[peerId].brainSeq = brainResult.brainSeq;+ // Cache the reconcile checksum we converged against so an unchanged peer+ // short-circuits the snapshot fetch next cycle (#1077). Only overwrite+ // when we actually resolved one — a failed/legacy probe (null) leaves+ // the prior value so we don't lose the skip-optimization on a blip.+ if (isNonEmptyStr(brainResult.brainChecksum)) {+ cursors[peerId].brainChecksum = brainResult.brainChecksum;+ }+ }if (memoryResult.memorySeq !== (cursor.memorySeq ?? '0')) cursors[peerId].memorySeq = memoryResult.memorySeq;// Persist the per-kind catalog cursor only when the drain wasn't blocked// by a schema gap — a blocked cycle leaves the prior cursor so we re-try@@ -772,19 +829,27 @@ export async function syncAllPeers() {console.log(`🔄 Sync cycle complete: ${cycleChanges} change${cycleChanges === 1 ? '' : 's'} applied across ${online.length} peer${online.length === 1 ? '' : 's'}`);}- // Compact sync log below the minimum peer cursor to bound log growth- // Include all enabled peers with brain sync (not just online) so offline peers don't lose unsynced entries- const cursors = await loadCursors();- const brainEnabledIds = new Set(- peers- .filter(p => p.enabled && p.instanceId && getEffectiveCategories(p).brain)- .map(p => p.instanceId)- );- const seqs = Object.entries(cursors)- .filter(([id]) => brainEnabledIds.has(id))- .map(([, c]) => c.brainSeq ?? 0);- if (seqs.length > 0) {- const minSeq = Math.min(...seqs);+ // Compact the sync log below the point every brain-enabled peer has already+ // consumed FROM US (#1077 Bug 1). The floor MUST be each peer's cursor into+ // OUR log — `peer.remoteSyncSeqs.cursorForYou.brainSeq`, learned during the+ // probe — NOT `cursors[peerId].brainSeq` (our OUTBOUND pull cursor into them).+ // Flooring on the outbound cursor drops entries a peer hasn't pulled yet, so+ // that peer can never learn those records once they're gone (the exact+ // divergence this issue fixes). Include all ENABLED brain peers (not just+ // online) so an offline peer's unconsumed entries are never dropped.+ //+ // A brain-enabled peer that hasn't reported its cursor into us (older peer,+ // never probed with `forPeer`, or never synced) contributes a floor of 0 —+ // we keep everything for it rather than assume it caught up. compactLog still+ // runs (vs. the old skip-when-empty) so a 0 floor is an explicit "keep all",+ // and the anti-entropy reconcile (Part 1) re-converges anyone genuinely behind.+ const brainPeers = peers.filter(p => p.enabled && p.instanceId && getEffectiveCategories(p).brain);+ if (brainPeers.length > 0) {+ const consumedSeqs = brainPeers.map(p => {+ const consumed = p.remoteSyncSeqs?.cursorForYou?.brainSeq;+ return typeof consumed === 'number' && Number.isFinite(consumed) && consumed >= 0 ? consumed : 0;+ });+ const minSeq = Math.min(...consumedSeqs);await brainSyncLog.compactLog(minSeq);}}diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 94aefdfefb..48f97d4227 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -22,6 +22,11 @@ vi.mock('./brainSyncLog.js', () => ({vi.mock('./brainSync.js', () => ({applyRemoteChanges: vi.fn()}));+vi.mock('./brainReconcile.js', () => ({+ getBrainChecksum: vi.fn().mockResolvedValue('local-cksum'),+ getBrainSnapshot: vi.fn(),+ applyBrainSnapshot: vi.fn().mockResolvedValue({ inserted: 0, updated: 0, deleted: 0, skipped: 0 }),+}));vi.mock('./memorySync.js', () => ({applyRemoteChanges: vi.fn(),getMaxSequence: vi.fn().mockResolvedValue('0')@@ -47,6 +52,7 @@ vi.mock('./memoryBackend.js', () => ({}));vi.mock('./dataSync.js', () => ({getSnapshot: vi.fn().mockResolvedValue({ data: {}, checksum: 'abc' }),+ getChecksum: vi.fn().mockResolvedValue({ checksum: 'abc' }),applyRemote: vi.fn().mockResolvedValue({ applied: false, count: 0 }),getSupportedCategories: vi.fn(() => ['goals', 'character', 'digitalTwin', 'meatspace'])}));@@ -85,7 +91,8 @@ import { applyRemoteChanges as applyBrainChanges } from './brainSync.js';import { applyRemoteChanges as applyMemoryChanges } from './memorySync.js';import { applyRemoteChanges as applyCatalogChanges } from './catalogSync.js';import { instanceEvents } from './instanceEvents.js';-import { getCurrentSeq } from './brainSyncLog.js';+import { getCurrentSeq, compactLog } from './brainSyncLog.js';+import { getBrainChecksum, applyBrainSnapshot } from './brainReconcile.js';import { getMaxSequence } from './memorySync.js';import { syncWithPeer, syncAllPeers, getSyncStatus, initSyncOrchestrator, stopSyncOrchestrator } from './syncOrchestrator.js';@@ -127,25 +134,14 @@ describe('syncOrchestrator', () => {});it('fetches brain and memory changes from peer', async () => {- // Brain sync: single batch, no more- mockFetch- .mockResolvedValueOnce({- ok: true,- json: async () => ({- changes: [{ seq: 1, op: 'create', type: 'people', id: 'p1', record: {} }],- maxSeq: 1,- hasMore: false- })- })- // Memory sync: single batch- .mockResolvedValueOnce({- ok: true,- json: async () => ({- memories: [{ id: 'm1', content: 'test' }],- maxSequence: '5',- hasMore: false- })- });+ // URL-routed (resilient to the #1077 reconcile checksum fetch between+ // brain and memory). Brain + memory each return a single batch.+ mockFetch.mockImplementation(async (url) => {+ if (url.includes('/api/brain/reconcile/checksum')) return { ok: true, json: async () => ({ checksum: 'local-cksum' }) };+ if (url.includes('/api/brain/sync')) return { ok: true, json: async () => ({ changes: [{ seq: 1, op: 'create', type: 'people', id: 'p1', record: {} }], maxSeq: 1, hasMore: false }) };+ if (url.includes('/api/memory/sync')) return { ok: true, json: async () => ({ memories: [{ id: 'm1', content: 'test' }], maxSequence: '5', hasMore: false }) };+ return { ok: true, json: async () => ({}) };+ });applyBrainChanges.mockResolvedValue({ inserted: 1, updated: 0, deleted: 0, skipped: 0 });applyMemoryChanges.mockResolvedValue({ inserted: 1, updated: 0 });@@ -154,7 +150,8 @@ describe('syncOrchestrator', () => {expect(result.brain.totalApplied).toBe(1);expect(result.memory.totalApplied).toBe(1);- expect(mockFetch).toHaveBeenCalledTimes(2);+ // brain delta + reconcile checksum + memory = 3 fetches+ expect(mockFetch).toHaveBeenCalledTimes(3);});it('handles pagination loop with hasMore=true', async () => {@@ -210,21 +207,14 @@ describe('syncOrchestrator', () => {};readJSONFile.mockResolvedValue(cursorData);- // Brain: no changes- mockFetch- .mockResolvedValueOnce({- ok: true,- json: async () => ({ changes: [], maxSeq: 0, hasMore: false })- })- // Memory: returns data from seq 0 (after cursor reset)- .mockResolvedValueOnce({- ok: true,- json: async () => ({- memories: [{ id: 'm1', content: 'new' }],- maxSequence: '2',- hasMore: false- })- });+ // URL-routed so the test is resilient to the order/number of fetches+ // (the anti-entropy reconcile adds a /reconcile/checksum fetch — #1077).+ mockFetch.mockImplementation(async (url) => {+ if (url.includes('/api/brain/sync')) return { ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) };+ if (url.includes('/api/brain/reconcile/checksum')) return { ok: true, json: async () => ({ checksum: 'local-cksum' }) };+ if (url.includes('/api/memory/sync')) return { ok: true, json: async () => ({ memories: [{ id: 'm1', content: 'new' }], maxSequence: '2', hasMore: false }) };+ return { ok: true, json: async () => ({}) };+ });applyMemoryChanges.mockResolvedValue({ inserted: 1, updated: 0 });@@ -248,27 +238,20 @@ describe('syncOrchestrator', () => {};readJSONFile.mockResolvedValue(cursorData);- // Brain: returns data from seq 0 (after cursor reset)- mockFetch- .mockResolvedValueOnce({- ok: true,- json: async () => ({- changes: [{ seq: 1, op: 'create', type: 'people', id: 'p1', record: {} }],- maxSeq: 1,- hasMore: false- })- })- // Memory: no changes- .mockResolvedValueOnce({- ok: true,- json: async () => ({ memories: [], maxSequence: '10', hasMore: false })- });+ // URL-routed (resilient to the reconcile fetch added in #1077). Brain+ // returns data from seq 0 (after cursor reset); memory + reconcile quiet.+ mockFetch.mockImplementation(async (url) => {+ if (url.includes('/api/brain/sync')) return { ok: true, json: async () => ({ changes: [{ seq: 1, op: 'create', type: 'people', id: 'p1', record: {} }], maxSeq: 1, hasMore: false }) };+ if (url.includes('/api/brain/reconcile/checksum')) return { ok: true, json: async () => ({ checksum: 'local-cksum' }) };+ if (url.includes('/api/memory/sync')) return { ok: true, json: async () => ({ memories: [], maxSequence: '10', hasMore: false }) };+ return { ok: true, json: async () => ({}) };+ });applyBrainChanges.mockResolvedValue({ inserted: 1, updated: 0, deleted: 0, skipped: 0 });const result = await syncWithPeer(peerWithReset);- const brainCall = mockFetch.mock.calls.find(c => c[0].includes('/api/brain/sync'));+ const brainCall = mockFetch.mock.calls.find(c => c[0].includes('/api/brain/sync') && !c[0].includes('reconcile'));expect(brainCall[0]).toContain('since=0');expect(result.brain.totalApplied).toBe(1);});@@ -599,6 +582,34 @@ describe('syncOrchestrator', () => {const status = await getSyncStatus({});expect(status).not.toHaveProperty('cursorForYou');});++ // Regression (#1077, Bug 3): the served local.checksums must be SCOPED to the+ // requesting peer (forPeerId === forPeer) so they match the scoped checksum+ // the peer's cursor cached during sync. Computing them unscoped (global) made+ // every per-record-subscribable category (universe/pipeline/mediaCollections)+ // read "behind" forever — including the both-empty case.+ it('computes local.checksums scoped to the requesting peer (forPeerId === forPeer)', async () => {+ const dataSync = await import('./dataSync.js');+ dataSync.getSupportedCategories.mockReturnValue(['mediaCollections']);+ dataSync.getChecksum.mockResolvedValue({ checksum: 'scoped-xyz' });+ readJSONFile.mockImplementation(async () => ({ 'peer-A': { brainSeq: 88 } }));++ const status = await getSyncStatus({ includeChecksums: true, forPeer: 'peer-A' });++ expect(dataSync.getChecksum).toHaveBeenCalledWith('mediaCollections', { forPeerId: 'peer-A' });+ expect(status.local.checksums.mediaCollections).toBe('scoped-xyz');+ });++ it('computes UNscoped local.checksums when no forPeer is supplied (self-view)', async () => {+ const dataSync = await import('./dataSync.js');+ dataSync.getSupportedCategories.mockReturnValue(['mediaCollections']);+ dataSync.getChecksum.mockResolvedValue({ checksum: 'global-abc' });+ readJSONFile.mockImplementation(async () => ({}));++ await getSyncStatus({ includeChecksums: true });++ expect(dataSync.getChecksum).toHaveBeenCalledWith('mediaCollections', { forPeerId: undefined });+ });});describe('sync:progress events', () => {@@ -659,6 +670,72 @@ describe('syncOrchestrator', () => {});});+ // #1077 Part 1: anti-entropy reconcile. After draining the delta log, brain+ // sync compares a whole-brain checksum with the peer and pulls+merges the+ // snapshot on a mismatch — the only path that re-converges a peer that missed+ // compacted entries.+ describe('brain anti-entropy reconcile (#1077)', () => {+ // Brain delta drain is always empty here; we exercise the reconcile leg.+ const routeFetch = (handlers) => mockFetch.mockImplementation(async (url) => {+ if (url.includes('/api/brain/sync')) return { ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) };+ if (url.includes('/api/brain/reconcile/checksum')) return { ok: true, json: async () => handlers.checksum };+ if (url.includes('/api/brain/reconcile/snapshot')) return { ok: true, json: async () => handlers.snapshot };+ if (url.includes('/api/memory/sync')) return { ok: true, json: async () => ({ memories: [], maxSequence: '0', hasMore: false }) };+ return { ok: true, json: async () => ({}) };+ });++ it('pulls + merges the snapshot when peer checksum differs from local', async () => {+ getBrainChecksum.mockResolvedValue('local-AAA');+ applyBrainSnapshot.mockResolvedValue({ inserted: 0, updated: 3, deleted: 1, skipped: 0 });+ routeFetch({+ checksum: { checksum: 'peer-BBB' },+ snapshot: { records: { links: { x: { id: 'x', updatedAt: '2026-02-02T00:00:00.000Z' } } }, checksum: 'peer-BBB' },+ });++ const result = await syncWithPeer(mockPeer);++ expect(applyBrainSnapshot).toHaveBeenCalledTimes(1);+ // delta(0) + reconcile merge(3 upd + 1 del) = 4+ expect(result.brain.totalApplied).toBe(4);+ });++ it('SKIPS the snapshot fetch when peer checksum equals our local checksum', async () => {+ getBrainChecksum.mockResolvedValue('same-CCC');+ routeFetch({ checksum: { checksum: 'same-CCC' }, snapshot: { records: {} } });++ await syncWithPeer(mockPeer);++ expect(applyBrainSnapshot).not.toHaveBeenCalled();+ const snapshotFetches = mockFetch.mock.calls.filter(c => c[0].includes('/api/brain/reconcile/snapshot'));+ expect(snapshotFetches).toHaveLength(0);+ });++ it('SKIPS reconcile entirely when peer checksum matches the cached cursor checksum', async () => {+ readJSONFile.mockImplementation(async () => ({ [mockPeer.instanceId]: { brainSeq: 0, brainChecksum: 'cached-DDD' } }));+ routeFetch({ checksum: { checksum: 'cached-DDD' }, snapshot: { records: {} } });++ await syncWithPeer(mockPeer);++ // Cached match → never even computes local checksum or fetches snapshot.+ expect(getBrainChecksum).not.toHaveBeenCalled();+ expect(applyBrainSnapshot).not.toHaveBeenCalled();+ });++ it('falls back to delta-only when peer is too old to expose /reconcile/checksum', async () => {+ mockFetch.mockImplementation(async (url) => {+ if (url.includes('/api/brain/sync')) return { ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) };+ if (url.includes('/api/brain/reconcile/checksum')) return { ok: false, status: 404, json: async () => ({}) };+ if (url.includes('/api/memory/sync')) return { ok: true, json: async () => ({ memories: [], maxSequence: '0', hasMore: false }) };+ return { ok: true, json: async () => ({}) };+ });++ const result = await syncWithPeer(mockPeer);++ expect(applyBrainSnapshot).not.toHaveBeenCalled();+ expect(result.brain.totalApplied).toBe(0);+ });+ });+describe('syncAllPeers', () => {it('iterates online peers with instanceId', async () => {const onlinePeer = { ...mockPeer };@@ -668,16 +745,64 @@ describe('syncOrchestrator', () => {getPeers.mockResolvedValue([onlinePeer, offlinePeer, disabledPeer, noIdPeer]);- // For the single qualifying peer: brain + memory fetch- mockFetch- .mockResolvedValueOnce({ ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) })- .mockResolvedValueOnce({ ok: true, json: async () => ({ memories: [], maxSequence: '0', hasMore: false }) });+ // For the single qualifying peer: brain delta + reconcile checksum (#1077)+ // + memory fetch. URL-routed so it doesn't depend on call order.+ mockFetch.mockImplementation(async (url) => {+ if (url.includes('/api/brain/reconcile/checksum')) return { ok: true, json: async () => ({ checksum: 'local-cksum' }) };+ if (url.includes('/api/brain/sync')) return { ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) };+ if (url.includes('/api/memory/sync')) return { ok: true, json: async () => ({ memories: [], maxSequence: '0', hasMore: false }) };+ return { ok: true, json: async () => ({}) };+ });++ await syncAllPeers();++ // Only 1 peer qualifies (online + enabled + has instanceId): brain delta ++ // reconcile checksum + memory. Match by URL so unrelated fetches don't skew.+ const brainSyncCalls = mockFetch.mock.calls.filter(c => c[0].includes('/api/brain/sync'));+ const reconcileCalls = mockFetch.mock.calls.filter(c => c[0].includes('/api/brain/reconcile/checksum'));+ const memoryCalls = mockFetch.mock.calls.filter(c => c[0].includes('/api/memory/sync'));+ expect(brainSyncCalls).toHaveLength(1);+ expect(reconcileCalls).toHaveLength(1);+ expect(memoryCalls).toHaveLength(1);+ });+ });++ // #1077 Bug 1: compaction must floor on how much each brain-enabled peer has+ // pulled FROM us (peer.remoteSyncSeqs.cursorForYou.brainSeq), NOT our outbound+ // pull cursor into them (cursors[peerId].brainSeq). Flooring on the wrong+ // cursor drops log entries a peer hasn't consumed → that peer can never learn+ // those records (the divergence this issue fixes).+ describe('brain log compaction floor (#1077)', () => {+ beforeEach(() => {+ getCurrentSeq.mockReturnValue(200);+ // No changes to pull, so each peer's sync is a no-op drain.+ mockFetch.mockResolvedValue({ ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) });+ });++ it('floors on the MIN of peers consumption of our log (cursorForYou.brainSeq)', async () => {+ const peerA = { ...mockPeer, instanceId: 'A', remoteSyncSeqs: { cursorForYou: { brainSeq: 150 } } };+ const peerB = { ...mockPeer, name: 'B', instanceId: 'B', remoteSyncSeqs: { cursorForYou: { brainSeq: 90 } } };+ getPeers.mockResolvedValue([peerA, peerB]);+ // Our OUTBOUND pull cursors are high — the old (buggy) floor would use these.+ readJSONFile.mockImplementation(async () => ({ A: { brainSeq: 199 }, B: { brainSeq: 199 } }));++ await syncAllPeers();++ // Floor = min(150, 90) = 90 — NOT min(199,199), and NOT our pull cursors.+ expect(compactLog).toHaveBeenCalledWith(90);+ });++ it('floors at 0 when a brain-enabled peer has not reported its cursor into us', async () => {+ const reported = { ...mockPeer, instanceId: 'A', remoteSyncSeqs: { cursorForYou: { brainSeq: 150 } } };+ // peer B is brain-enabled but never told us how far it pulled — must NOT+ // assume it caught up. Floor drops to 0 so we keep everything for it.+ const unreported = { ...mockPeer, name: 'B', instanceId: 'B', remoteSyncSeqs: null };+ getPeers.mockResolvedValue([reported, unreported]);+ readJSONFile.mockImplementation(async () => ({}));await syncAllPeers();- // Only 1 peer qualifies (online + enabled + has instanceId)- // fetchPeer should be called for brain + memory- expect(mockFetch).toHaveBeenCalledTimes(2);+ expect(compactLog).toHaveBeenCalledWith(0);});});