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

feat: improve daily log autosave performance and obsidian sync serialization

[._.]/ Adam Eivy604e0d650257
diff --git a/PLAN.md b/PLAN.md
index 72a309b336..d6c476695d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -26,7 +26,7 @@ embedding budget) was fixed in that PR by debouncing the journal re-embed
(`queueJournalResync` in `server/services/brainMemoryBridge.js`). These are the
rest — each is a perf/cleanup item, none is a correctness bug:
-- [ ] Delete the dead `journals:changed` event. `server/services/brainJournal.js`
+- [x] Delete the dead `journals:changed` event. `server/services/brainJournal.js`
emits it at lines ~259/298/335/356 as `{ records: await rawRecords() }`, and
`rawRecords()` (line ~142) rebuilds the entire date→entry map (two full object
copies of every journal day) — awaited inline before the save returns, so it
@@ -36,13 +36,13 @@ rest — each is a perf/cleanup item, none is a correctness bug:
(`brainStorage.js`) with no cross-install surface, so removal is compat-safe.
`server/services/brainJournal.test.js:141` asserts the emit and must be updated.
Skipped in the autosave PR as pre-existing dead-code cleanup outside its scope.
-- [ ] Cache the Obsidian sidecar. `loadObsidianLocations()`
+- [x] Cache the Obsidian sidecar. `loadObsidianLocations()`
(`server/services/brainJournal.js:85`) is `ensureDir` + `readJSONFile` with no
cache, called from `getEntry`, `putEntry`, and `rawRecords` — ~3 uncached file
reads + 3 `mkdir` syscalls per save, now once per autosave. Mirror the
write-through cache `brainStorage` already uses (`CACHE_TTL_MS = 2000`). Fixing
the item above removes one of the three call sites for free.
-- [ ] Serialize `scheduleObsidianSync` per date (`server/services/brainJournal.js:238`).
+- [x] Serialize `scheduleObsidianSync` per date (`server/services/brainJournal.js:238`).
It rewrites the day's full markdown note fire-and-forget on every save, and its
own comment notes Obsidian lives on iCloud where "writes can stall for hundreds
of ms" — so at autosave cadence, overlapping writes to one file are possible and
diff --git a/server/services/brainJournal.js b/server/services/brainJournal.js
index efc2fafd45..2d76552780 100644
--- a/server/services/brainJournal.js
+++ b/server/services/brainJournal.js
@@ -81,9 +81,24 @@ const storeMutex = createMutex();
// ── Local Obsidian-location sidecar (NOT synced) ─────────────────────────────
// Read/write the machine-local map of where each day was mirrored. Kept out of
// the synced journal record (see OBSIDIAN_LOCATIONS_FILE rationale above).
+let obsidianLocationsCache = null;
+let obsidianLocationsCacheTime = 0;
+const OBSIDIAN_LOCATIONS_CACHE_TTL_MS = 2000;
+
+export function _clearObsidianLocationsCacheForTest() {
+ obsidianLocationsCache = null;
+ obsidianLocationsCacheTime = 0;
+}
+
async function loadObsidianLocations() {
+ const nowMs = Date.now();
+ if (obsidianLocationsCache && (nowMs - obsidianLocationsCacheTime) < OBSIDIAN_LOCATIONS_CACHE_TTL_MS) {
+ return obsidianLocationsCache;
+ }
await ensureDir(PATHS.brain);
- return readJSONFile(OBSIDIAN_LOCATIONS_FILE, {});
+ obsidianLocationsCache = await readJSONFile(OBSIDIAN_LOCATIONS_FILE, {});
+ obsidianLocationsCacheTime = Date.now();
+ return obsidianLocationsCache;
}
async function getObsidianLocation(date) {
@@ -94,12 +109,14 @@ async function getObsidianLocation(date) {
// Serialized via storeMutex by callers; persists the location for one date (or
// drops it when both fields are null, e.g. after a delete).
async function saveObsidianLocation(date, { obsidianPath, obsidianVaultId }) {
- const map = await loadObsidianLocations();
+ const map = { ...(await loadObsidianLocations()) };
if (obsidianPath == null && obsidianVaultId == null) {
delete map[date];
} else {
map[date] = { obsidianPath: obsidianPath ?? null, obsidianVaultId: obsidianVaultId ?? null };
}
+ obsidianLocationsCache = map;
+ obsidianLocationsCacheTime = Date.now();
await atomicWrite(OBSIDIAN_LOCATIONS_FILE, map);
}
@@ -135,22 +152,6 @@ async function putEntry(date, entry) {
return { ...saved, obsidianPath: loc.obsidianPath, obsidianVaultId: loc.obsidianVaultId };
}
-// Store-wide "the daily log changed" signal, carrying the ONE day that moved.
-//
-// This used to ship the full date→entry map, rebuilt by reading and JSON-parsing
-// every `data/brain/journals/<date>/index.json` on disk (issue #3510). Since the
-// per-record split (#725) there is no whole-store cache to absorb that, so every
-// autosave/dictation segment against today re-read the user's entire history to
-// build a payload nobody consumed — the write paths already emit
-// `journals:upserted` / `journals:appended` / `journals:deleted` with the single
-// affected entry, and those are what the memory bridge listens on.
-//
-// Payload is now a delta: `{ date, entry }`, with `entry: null` for a delete. A
-// listener that wants more than the changed day should read it back through
-// `listJournals()` / `getJournal(date)` rather than have every writer pay for a
-// full-store materialization on the off chance someone is subscribed.
-const emitChanged = (date, entry) => brainEvents.emit('journals:changed', { date, entry });
-
// Accept YYYY-MM-DD only, and require a real calendar day so we can't create
// store keys like '2026-02-30' that don't sort meaningfully or round-trip.
export const isIsoDate = (date) => {
@@ -231,13 +232,26 @@ function newEntry(date) {
};
}
-// Fire-and-forget: Obsidian lives on iCloud and writes can stall for hundreds
-// of ms; callers shouldn't wait on it. The sync path persists any discovered
-// obsidianPath itself via persistObsidianLocation() — callers must not assume
-// this async work mutates the `entry` they passed in or that a later
+// Fire-and-forget, serialized per date: Obsidian lives on iCloud where writes
+// can stall for hundreds of ms. Callers shouldn't wait on it, but serializing per
+// date prevents out-of-order writes during rapid autosaves. The sync path persists
+// any discovered obsidianPath itself via persistObsidianLocation() — callers must
+// not assume this async work mutates the `entry` they passed in or that a later
// putEntry() in their flow will pick up the path.
+const pendingObsidianSyncs = new Map();
+
function scheduleObsidianSync(entry) {
- syncToObsidian(entry).catch((err) => console.error(`📓 Obsidian sync failed: ${err.message}`));
+ const date = entry.date;
+ const previous = pendingObsidianSyncs.get(date) || Promise.resolve();
+ const next = previous
+ .then(() => syncToObsidian(entry))
+ .catch((err) => console.error(`📓 Obsidian sync failed: ${err.message}`))
+ .finally(() => {
+ if (pendingObsidianSyncs.get(date) === next) {
+ pendingObsidianSyncs.delete(date);
+ }
+ });
+ pendingObsidianSyncs.set(date, next);
}
export async function setJournalContent(date, content) {
@@ -257,7 +271,6 @@ export async function setJournalContent(date, content) {
return putEntry(date, next);
});
scheduleObsidianSync(entry);
- emitChanged(date, entry);
// Per-entry event so downstream syncers (memory bridge) can update the
// single affected day without iterating the whole store.
brainEvents.emit('journals:upserted', { entry });
@@ -296,7 +309,6 @@ export async function appendJournal(date, text, { source = 'text' } = {}) {
return { entry: saved, segment: segmentLocal };
});
scheduleObsidianSync(entry);
- emitChanged(date, entry);
brainEvents.emit('journals:appended', { entry, segment });
// Per-entry event so the memory bridge re-embeds only this day, not all
// of them. (Keep journals:appended separate — it carries the single new
@@ -333,7 +345,6 @@ export async function upsertAutoSection(date, body, markers) {
});
if (!entry) return null;
scheduleObsidianSync(entry);
- emitChanged(date, entry);
brainEvents.emit('journals:upserted', { entry });
return entry;
}
@@ -354,12 +365,8 @@ export async function deleteJournal(date) {
}
// Drop the local mirror-location record for this day (sidecar is not synced).
await saveObsidianLocation(date, { obsidianPath: null, obsidianVaultId: null });
- // `entry: null` — the day is gone; the journals:deleted event below carries
- // the record that was removed for consumers that need its contents.
- emitChanged(date, null);
// Explicit deletion signal so memory bridges / integrations can archive
- // the corresponding vector entry — the changed event alone doesn't tell
- // the bridge which record vanished.
+ // the corresponding vector entry.
brainEvents.emit('journals:deleted', { date, entry });
return true;
}
diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.js
index 065c36bf5f..b09f378abd 100644
--- a/server/services/brainJournal.test.js
+++ b/server/services/brainJournal.test.js
@@ -88,6 +88,7 @@ describe('brainJournal', () => {
rmSync(TEMP_ROOT, { recursive: true, force: true });
mkdirSync(TEMP_ROOT, { recursive: true });
journalRecords.clear();
+ journal._clearObsidianLocationsCacheForTest();
vi.clearAllMocks();
});
@@ -143,10 +144,9 @@ describe('brainJournal', () => {
expect(second.segments).toHaveLength(2);
});
- it('emits journals:changed, journals:appended, and journals:upserted', async () => {
+ it('emits journals:appended and journals:upserted', async () => {
await journal.appendJournal('2026-04-17', 'hello');
const eventNames = brainEvents.emit.mock.calls.map((c) => c[0]);
- expect(eventNames).toContain('journals:changed');
expect(eventNames).toContain('journals:appended');
// journals:upserted is the per-entry event the memory bridge listens
// on — must fire for every append so a single day's embedding gets
@@ -154,16 +154,12 @@ describe('brainJournal', () => {
expect(eventNames).toContain('journals:upserted');
});
- // Issue #3510: journals:changed used to carry the full date→entry map,
- // rebuilt by reading every historical day off disk on every autosave /
- // dictation segment. It now carries just the day that moved.
- it('emits journals:changed as a { date, entry } delta, not a full map', async () => {
+ it('emits journals:upserted with the updated entry delta', async () => {
await journal.appendJournal('2026-04-16', 'yesterday');
await journal.appendJournal('2026-04-17', 'today');
- const payload = lastEmit('journals:changed');
- expect(payload.date).toBe('2026-04-17');
+ const payload = lastEmit('journals:upserted');
+ expect(payload.entry.date).toBe('2026-04-17');
expect(payload.entry.content).toBe('today');
- expect(payload).not.toHaveProperty('records');
});
it('does not read every historical entry when appending to one day', async () => {
@@ -204,29 +200,25 @@ describe('brainJournal', () => {
expect(cleared.segments).toEqual([]);
});
- it('emits a { date, entry } delta without re-reading the store (#3510)', async () => {
+ it('emits journals:upserted without re-reading the store (#3510)', async () => {
await journal.appendJournal('2026-04-16', 'yesterday');
getAll.mockClear();
await journal.setJournalContent('2026-04-17', 'brand new');
expect(getAll).not.toHaveBeenCalled();
- expect(lastEmit('journals:changed')).toMatchObject({
- date: '2026-04-17',
+ expect(lastEmit('journals:upserted')).toMatchObject({
entry: { content: 'brand new' },
});
});
});
describe('deleteJournal', () => {
- // `entry: null` marks the day as gone; the journals:deleted event that
- // follows carries the removed record for consumers that need its contents.
- it('emits journals:changed with a null entry and no full-store read (#3510)', async () => {
+ it('emits journals:deleted without full-store read (#3510)', async () => {
await journal.appendJournal('2026-04-16', 'yesterday');
await journal.appendJournal('2026-04-17', 'today');
getAll.mockClear();
expect(await journal.deleteJournal('2026-04-17')).toBe(true);
expect(getAll).not.toHaveBeenCalled();
- expect(lastEmit('journals:changed')).toEqual({ date: '2026-04-17', entry: null });
expect(lastEmit('journals:deleted').entry.content).toBe('today');
});
});
@@ -319,5 +311,27 @@ describe('brainJournal', () => {
const revived = records.find((r) => r.date === '2026-04-17');
expect(revived).toBeUndefined();
});
+
+ it('serializes obsidian syncs per date in strict sequential order', async () => {
+ const callOrder = [];
+ obsidian.upsertNote.mockImplementation(async (vaultId, path, content) => {
+ const match = content.match(/content-(\d+)/);
+ const num = match ? match[1] : '0';
+ callOrder.push(`start-${num}`);
+ await new Promise((r) => setTimeout(r, 10));
+ callOrder.push(`end-${num}`);
+ return path;
+ });
+
+ await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: true });
+
+ await journal.setJournalContent('2026-04-17', 'content-1');
+ await journal.setJournalContent('2026-04-17', 'content-2');
+
+ // Wait for background queue to flush
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(callOrder).toEqual(['start-1', 'end-1', 'start-2', 'end-2']);
+ });
});
});