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
perf: batch brain bridge map persistence (#5214)
[._.]/ Adam Eivy64fea47f17e2
diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.jsindex 7131692273..9049148c06 100644--- a/server/services/brainMemoryBridge.js+++ b/server/services/brainMemoryBridge.js@@ -228,7 +228,7 @@ export function brainRecordToMemory(brainType, record) {* Upsert a single brain record into the memory system.* Creates a new memory or updates the existing one based on the bridge map.*/-export async function syncBrainRecord(brainType, record) {+export async function syncBrainRecord(brainType, record, { deferMapSave = false, onMapChanged } = {}) {const memoryData = brainRecordToMemory(brainType, record);if (!memoryData) return null;@@ -261,7 +261,8 @@ export async function syncBrainRecord(brainType, record) {// Create new memoryconst created = await memory.createMemory(memoryData, embedding);map[key] = created.id;- await saveBridgeMap();+ onMapChanged?.();+ if (!deferMapSave) await saveBridgeMap();console.log(`🧠🔗 Created brain→memory: ${brainType}/${record.id} → ${created.id}`);return created.id;}@@ -294,6 +295,13 @@ const makeEmbeddedChecker = (map, missingMemIds) => (key) => {export async function syncAllBrainData({ dryRun = false, refresh = false, onlyMissing = false } = {}) {const map = await loadBridgeMap();const stats = { synced: 0, skipped: 0, errors: 0, archived: 0 };+ let bridgeMapChanged = false;+ const deferredMapSave = {+ deferMapSave: true,+ onMapChanged: () => { bridgeMapChanged = true; },+ };++ try {// `onlyMissing` is the cheap, targeted backfill: embed only records that lack// an embedding (unmapped, or mapped to a memory whose vector is NULL because@@ -325,7 +333,7 @@ export async function syncAllBrainData({ dryRun = false, refresh = false, onlyMistats.synced++;continue;}- const memoryId = await syncBrainRecord(type, record).catch(err => {+ const memoryId = await syncBrainRecord(type, record, deferredMapSave).catch(err => {console.error(`❌ Failed to sync ${type}/${record.id}: ${err.message}`);stats.errors++;return null;@@ -357,7 +365,7 @@ export async function syncAllBrainData({ dryRun = false, refresh = false, onlyMistats.synced += 1;continue;}- const memoryId = await syncBrainRecord('journals', record).catch((err) => {+ const memoryId = await syncBrainRecord('journals', record, deferredMapSave).catch((err) => {console.error(`❌ Failed to sync journals/${record.date}: ${err.message}`);stats.errors += 1;return null;@@ -382,7 +390,7 @@ export async function syncAllBrainData({ dryRun = false, refresh = false, onlyMistats.synced++;continue;}- const memoryId = await syncBrainRecord(type, record).catch(err => {+ const memoryId = await syncBrainRecord(type, record, deferredMapSave).catch(err => {console.error(`❌ Failed to sync ${type}/${record.id}: ${err.message}`);stats.errors++;return null;@@ -422,7 +430,15 @@ export async function syncAllBrainData({ dryRun = false, refresh = false, onlyMi}}- return stats;+ return stats;+ } finally {+ if (bridgeMapChanged) {+ await saveBridgeMap().catch((err) => {+ console.error(`❌ Failed to save brain bridge map after bulk sync: ${err.message}`);+ stats.errors++;+ });+ }+ }}/**diff --git a/server/services/brainMemoryBridge.test.js b/server/services/brainMemoryBridge.test.jsindex 85642c13f9..eda3624f92 100644--- a/server/services/brainMemoryBridge.test.js+++ b/server/services/brainMemoryBridge.test.js@@ -21,6 +21,11 @@ const getDigests = vi.fn(async () => []);const getReviews = vi.fn(async () => []);const listJournals = vi.fn(async () => ({ records: [] }));const getJournal = vi.fn();+const atomicWrite = vi.fn(async (filePath, data) => {+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);+ const { writeFile } = await import('fs/promises');+ return writeFile(filePath, payload);+});vi.mock('fs', () => ({ existsSync: vi.fn(() => bridgeFileContents !== null) }));vi.mock('fs/promises', () => ({@@ -30,14 +35,9 @@ vi.mock('fs/promises', () => ({vi.mock('../lib/fileUtils.js', () => ({PATHS: { brain: '/tmp/test-brain' },ensureDir: vi.fn(async () => {}),- // atomicWrite replaced the raw writeFile(JSON.stringify) bridge-map site (#1837);- // route it through the mocked fs/promises.writeFile so it updates- // bridgeFileContents and a reloaded bridge sees the persisted map.- atomicWrite: vi.fn(async (filePath, data) => {- const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);- const { writeFile } = await import('fs/promises');- return writeFile(filePath, payload);- }),+ // Route atomic writes through the mocked fs/promises.writeFile so a reloaded+ // bridge sees the persisted map.+ atomicWrite,}));vi.mock('./memoryBackend.js', () => ({createMemory, updateMemory, updateMemoryEmbedding, deleteMemory, getMemoryIdsMissingEmbedding,@@ -444,6 +444,53 @@ describe('brainMemoryBridge — journal re-embed debounce (daily-log autosave)',});describe('brainMemoryBridge — syncAllBrainData refresh mode (issue #1080 recovery)', () => {+ it('persists all newly created mappings once after a bulk sync', async () => {+ const bridge = await loadBridge();+ getAll.mockImplementation(async (type) => (type === 'people'+ ? [{ id: 'p1', name: 'Alice' }, { id: 'p2', name: 'Bob' }]+ : []));++ const stats = await bridge.syncAllBrainData();++ expect(stats.synced).toBe(2);+ expect(atomicWrite).toHaveBeenCalledTimes(1);+ expect(JSON.parse(bridgeFileContents)).toMatchObject({+ [bridge.bridgeKey('people', 'p1')]: expect.any(String),+ [bridge.bridgeKey('people', 'p2')]: expect.any(String),+ });+ });++ it('persists a replacement for a stale falsy mapping', async () => {+ const bridge = await loadBridge();+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('people', 'p1')]: null });+ getAll.mockImplementation(async (type) => (type === 'people'+ ? [{ id: 'p1', name: 'Alice' }]+ : []));++ await bridge.syncAllBrainData();++ expect(atomicWrite).toHaveBeenCalledTimes(1);+ expect(JSON.parse(bridgeFileContents)).toMatchObject({+ [bridge.bridgeKey('people', 'p1')]: expect.any(String),+ });+ });++ it('persists created mappings when a later bulk read fails', async () => {+ const bridge = await loadBridge();+ getAll.mockImplementation(async (type) => {+ if (type === 'people') return [{ id: 'p1', name: 'Alice' }];+ if (type === 'projects') throw new Error('store unavailable');+ return [];+ });++ await expect(bridge.syncAllBrainData()).rejects.toThrow('store unavailable');++ expect(atomicWrite).toHaveBeenCalledTimes(1);+ expect(JSON.parse(bridgeFileContents)).toMatchObject({+ [bridge.bridgeKey('people', 'p1')]: expect.any(String),+ });+ });+it('skips already-mapped records by default but re-embeds them with refresh:true', async () => {const bridge = await loadBridge();getAll.mockImplementation(async (type) => (type === 'people' ? [{ id: 'p1', name: 'Alice' }] : []));