Skip to content

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

perf(brain): coalesce journal re-embedding per day instead of per save

[._.]/ Adam Eivy7433b72a0bbb
diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.js
index ce1d947a82..4ddb8fe255 100644
--- a/server/services/brainMemoryBridge.js
+++ b/server/services/brainMemoryBridge.js
@@ -429,6 +429,21 @@ const pendingResync = new Map(); // bridgeKey → { type, id, hardDelete } (dedu
let resyncTimer = null;
let resyncFlushing = false; // single-flight guard so two flushes can't overlap
+// Journals re-embed on a much longer window than the other brain types, per
+// day. The daily-log editor autosaves while the user types, so 'journals:upserted'
+// now fires every couple of seconds for the SAME day — where it used to fire
+// once per explicit Save. Re-embedding per event would mean an embedding call
+// per typing pause, and — once the day's entry outgrows the embedding char
+// budget — a full LLM summarization per event too (see generateMemoryEmbedding's
+// over-budget branch), which is exactly the kind of unannounced provider traffic
+// the AI policy rules out. Coalescing per day collapses a whole writing session
+// into one re-embed after the user settles; resyncBrainRecord re-reads the
+// canonical entry at flush time, so the trailing flush always embeds the newest
+// content — and embedding once the sentence is finished beats embedding it
+// half-typed 100 times.
+const JOURNAL_RESYNC_DEBOUNCE_MS = 30_000;
+const journalResyncTimers = new Map(); // journal id (the ISO date) → timer
+
/**
* Archive the memory entry mapped to a brain record (if any). Used when the
* canonical record is gone (tombstoned), archived, or otherwise should no
@@ -619,11 +634,17 @@ export function initBridge() {
// embedding calls per dictation segment and saturate the embedding
// backend.) appendJournal/setJournalContent fire 'journals:upserted' with
// the single affected entry; deleteJournal fires 'journals:deleted'.
- brainEvents.on('journals:upserted', ({ entry }) => handleJournalUpserted(entry));
+ // Debounced per day because the editor autosaves — see queueJournalResync.
+ brainEvents.on('journals:upserted', ({ entry }) => {
+ if (entry?.id) queueJournalResync(entry.id);
+ });
// handleJournalDeleted is async and awaits loadBridgeMap(); wrap the call
// in a .catch so a rejection becomes a logged error instead of an
// unhandled-rejection warning (or a process crash under strict modes).
brainEvents.on('journals:deleted', ({ entry }) => {
+ // Drop any debounced re-embed for the day first — the hard-delete below
+ // prunes the mapped memory, and a later flush would only re-read a tombstone.
+ if (entry?.id) cancelPendingJournalResync(entry.id);
handleJournalDeleted(entry).catch((err) => {
console.error(`❌ Brain bridge delete sync failed for journals/${entry?.id}: ${err.message}`);
});
@@ -640,11 +661,31 @@ export function initBridge() {
console.log('🧠🔗 Brain→Memory bridge initialized');
}
-function handleJournalUpserted(entry) {
- if (!entry?.id) return;
- syncBrainRecord('journals', entry).catch((err) => {
- console.error(`❌ Brain bridge sync failed for journals/${entry.id}: ${err.message}`);
- });
+/**
+ * Coalesce repeated saves of one day into a single re-embed, then hand off to
+ * the shared queueResync path (dedup + sequential drain + canonical re-read).
+ * Trailing-edge per day: each save pushes the flush out, so a writing session
+ * costs one re-embed once the user stops. See JOURNAL_RESYNC_DEBOUNCE_MS.
+ */
+function queueJournalResync(id) {
+ clearTimeout(journalResyncTimers.get(id));
+ const timer = setTimeout(() => {
+ journalResyncTimers.delete(id);
+ queueResync([{ type: 'journals', id }]);
+ }, JOURNAL_RESYNC_DEBOUNCE_MS);
+ // Don't hold the event loop open for a pending journal re-embed.
+ if (typeof timer.unref === 'function') timer.unref();
+ journalResyncTimers.set(id, timer);
+}
+
+/**
+ * Drop a day's pending re-embed. Called when the day is deleted: the delete
+ * path prunes the mapped memory immediately, so letting the debounce fire
+ * afterwards would just re-read a tombstone. Also exported for tests.
+ */
+export function cancelPendingJournalResync(id) {
+ clearTimeout(journalResyncTimers.get(id));
+ journalResyncTimers.delete(id);
}
async function handleJournalDeleted(entry) {
diff --git a/server/services/brainMemoryBridge.test.js b/server/services/brainMemoryBridge.test.js
index b2dbf720fa..b55a4e6686 100644
--- a/server/services/brainMemoryBridge.test.js
+++ b/server/services/brainMemoryBridge.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// The bridge memoizes its parsed bridge-map in a module-level variable
// (loadBridgeMap caches), so each test resets the module registry and
@@ -51,9 +51,16 @@ async function loadBridge() {
return import('./brainMemoryBridge.js');
}
-beforeEach(() => {
+beforeEach(async () => {
vi.clearAllMocks();
bridgeFileContents = null;
+ // The mocked brainEvents emitter is created by the vi.mock factory, which
+ // outlives vi.resetModules() — so each test's initBridge() stacks another
+ // set of listeners on the SAME emitter, and one emit fans out to every
+ // previous test's handlers. Existing tests only assert "not called" so they
+ // never noticed; any call-count assertion does. Reset to one listener per test.
+ const { brainEvents } = await import('./brainStorage.js');
+ brainEvents.removeAllListeners();
});
describe('brainMemoryBridge — resyncBrainRecord (issue #1080)', () => {
@@ -360,6 +367,78 @@ describe('brainMemoryBridge — entity :upserted/:deleted route through queueRes
});
});
+// The daily-log editor autosaves, so 'journals:upserted' now fires every couple
+// of seconds for the same day. Embedding per event would mean an embedding call
+// per typing pause — and a full LLM summarization per event once the entry
+// outgrows the embedding char budget.
+describe('brainMemoryBridge — journal re-embed debounce (daily-log autosave)', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ const emitSave = async (brainEvents, date, content) => {
+ getJournal.mockResolvedValue({ id: date, date, content });
+ brainEvents.emit('journals:upserted', { entry: { id: date, date, content } });
+ };
+
+ it('coalesces a writing session into one re-embed of the latest content', async () => {
+ const bridge = await loadBridge();
+ const { brainEvents } = await import('./brainStorage.js');
+ bridge.initBridge();
+
+ // 20 autosaves of the same day, 1.5s apart — a normal typing run.
+ for (let i = 0; i < 20; i += 1) {
+ await emitSave(brainEvents, '2026-06-09', `draft ${i}`);
+ await vi.advanceTimersByTimeAsync(1500);
+ }
+ expect(generateMemoryEmbedding).not.toHaveBeenCalled();
+
+ // Settle past the debounce, then drain.
+ await vi.advanceTimersByTimeAsync(31_000);
+ await bridge.flushPendingResync();
+
+ expect(generateMemoryEmbedding).toHaveBeenCalledTimes(1);
+ // Re-read canonical at flush, so it embeds the newest text, not the first.
+ // (createMemory takes the payload plus the embedding vector.)
+ expect(createMemory).toHaveBeenCalledWith(
+ expect.objectContaining({ content: expect.stringContaining('draft 19') }),
+ expect.anything(),
+ );
+ });
+
+ it('re-embeds each day separately rather than collapsing across days', async () => {
+ const bridge = await loadBridge();
+ const { brainEvents } = await import('./brainStorage.js');
+ bridge.initBridge();
+
+ await emitSave(brainEvents, '2026-06-09', 'day one');
+ await emitSave(brainEvents, '2026-06-10', 'day two');
+ await vi.advanceTimersByTimeAsync(31_000);
+ await bridge.flushPendingResync();
+
+ expect(generateMemoryEmbedding).toHaveBeenCalledTimes(2);
+ });
+
+ it('drops a pending re-embed when the day is deleted', async () => {
+ const bridge = await loadBridge();
+ const { brainEvents } = await import('./brainStorage.js');
+ bridge.initBridge();
+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('journals', '2026-06-09')]: 'mem-day' });
+
+ await emitSave(brainEvents, '2026-06-09', 'about to be deleted');
+ brainEvents.emit('journals:deleted', { date: '2026-06-09', entry: { id: '2026-06-09' } });
+ // handleJournalDeleted is async; flush microtasks (setImmediate is faked here).
+ await vi.advanceTimersByTimeAsync(0);
+
+ // The pending flush must not resurrect work against a tombstoned day.
+ getJournal.mockResolvedValue(null);
+ await vi.advanceTimersByTimeAsync(31_000);
+ await bridge.flushPendingResync();
+
+ expect(deleteMemory).toHaveBeenCalledWith('mem-day', true);
+ expect(generateMemoryEmbedding).not.toHaveBeenCalled();
+ });
+});
+
describe('brainMemoryBridge — syncAllBrainData refresh mode (issue #1080 recovery)', () => {
it('skips already-mapped records by default but re-embeds them with refresh:true', async () => {
const bridge = await loadBridge();