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

address review (codex): defer inbox recovery past initSyncLog + keep Obsidian location machine-local

Adam Eivya81575ddb6df
diff --git a/scripts/migrations/081-brain-daily-log-inbox-sync.js b/scripts/migrations/081-brain-daily-log-inbox-sync.js
index 7e9245fd89..31604a4d97 100644
--- a/scripts/migrations/081-brain-daily-log-inbox-sync.js
+++ b/scripts/migrations/081-brain-daily-log-inbox-sync.js
@@ -16,8 +16,11 @@
*
* 1. journals.json — STRIP the inner `id` field from each entry (the map key is
* the record id now, and an inner `id` would clobber the date key that
- * getById re-attaches), then stamp the sync fields (originInstanceId +
- * createdAt/updatedAt fallbacks) any entry is missing.
+ * getById re-attaches), STRIP the machine-local `obsidianPath`/
+ * `obsidianVaultId` into a non-synced sidecar (journal-obsidian-locations.json
+ * — federating them would poison the reconcile checksum across peers with
+ * different vaults and break local mirror cleanup), then stamp the sync
+ * fields (originInstanceId + createdAt/updatedAt fallbacks) any entry is missing.
* 2. inbox_log.jsonl → inbox.json — re-key each JSONL row by its `id` into a
* records map, drop the now-redundant inner `id`, and stamp the same sync
* fields (createdAt/updatedAt seeded from capturedAt so the LWW clock is
@@ -69,8 +72,11 @@ async function readInstanceId(rootDir) {
// journals we pass the existing updatedAt/createdAt or now()). Returns a new
// object with the inner `id` removed (the map key is the id).
function normalizeRecord(record, { instanceId, seedTime, nowIso }) {
+ // Strip the inner `id` (map key is the id) AND the machine-local Obsidian
+ // fields (extracted to the sidecar by the caller; they must never federate).
+ // The Obsidian keys are no-ops on inbox records, which never carry them.
// eslint-disable-next-line no-unused-vars
- const { id: _innerId, ...rest } = record;
+ const { id: _innerId, obsidianPath: _op, obsidianVaultId: _ov, ...rest } = record;
const normalized = {
...rest,
createdAt: rest.createdAt || seedTime || nowIso,
@@ -95,14 +101,21 @@ function normalizeRecord(record, { instanceId, seedTime, nowIso }) {
* - journalsStore: parsed journals.json (or null if absent).
* - inboxRows: array of parsed inbox_log.jsonl rows (empty if absent).
* - bridgeMap: parsed memory-bridge-map.json (or null if absent).
- * Returns { journalsStore, inboxStore, bridgeMap, bridgeRemapped, journalsChanged, inboxCount }.
+ * - obsidianLocations: parsed journal-obsidian-locations.json (or null if absent).
+ * Returns { journalsStore, inboxStore, bridgeMap, bridgeRemapped, obsidianLocations,
+ * obsidianExtracted, journalsChanged, inboxCount }.
*/
-export function computeDailyLogInboxMigration(journalsStore, inboxRows, { instanceId, nowIso, bridgeMap = null } = {}) {
- // 1. Journals: normalize each entry in place (strip inner id, stamp sync fields).
- // Capture oldUuid→date so step 3 can re-key the memory bridge.
+export function computeDailyLogInboxMigration(journalsStore, inboxRows, { instanceId, nowIso, bridgeMap = null, obsidianLocations = null } = {}) {
+ // 1. Journals: normalize each entry (strip inner id + machine-local Obsidian
+ // fields, stamp sync fields). Capture oldUuid→date so step 3 can re-key the
+ // memory bridge, and extract Obsidian location into the local sidecar so it
+ // stops federating (it would poison the reconcile checksum across peers with
+ // different vaults — see brainJournal.OBSIDIAN_LOCATIONS_FILE).
let journalsChanged = false;
let outJournals = null;
const uuidToDate = new Map();
+ const outLocations = { ...(obsidianLocations && typeof obsidianLocations === 'object' ? obsidianLocations : {}) };
+ let obsidianExtracted = 0;
if (journalsStore && typeof journalsStore === 'object') {
const records = journalsStore.records && typeof journalsStore.records === 'object'
? journalsStore.records
@@ -111,6 +124,16 @@ export function computeDailyLogInboxMigration(journalsStore, inboxRows, { instan
for (const [date, entry] of Object.entries(records)) {
if (!entry || typeof entry !== 'object') continue;
if (entry.id) uuidToDate.set(entry.id, date);
+ // Move Obsidian location to the sidecar (only when the record carries one
+ // and the sidecar doesn't already have an entry for this day — don't
+ // overwrite a newer local sidecar on re-run).
+ if ((entry.obsidianPath != null || entry.obsidianVaultId != null) && !(date in outLocations)) {
+ outLocations[date] = {
+ obsidianPath: entry.obsidianPath ?? null,
+ obsidianVaultId: entry.obsidianVaultId ?? null,
+ };
+ obsidianExtracted++;
+ }
const before = JSON.stringify(entry);
// Seed from the entry's own updatedAt/createdAt so we don't bump the LWW
// clock of days that already have one.
@@ -158,7 +181,16 @@ export function computeDailyLogInboxMigration(journalsStore, inboxRows, { instan
}
}
- return { journalsStore: outJournals, inboxStore, bridgeMap: outBridge, bridgeRemapped, journalsChanged, inboxCount };
+ // Only surface the sidecar when something was extracted (or one was passed in),
+ // so a fresh install with no Obsidian usage doesn't get an empty file written.
+ const outObsidian = (obsidianExtracted > 0 || obsidianLocations) ? outLocations : null;
+
+ return {
+ journalsStore: outJournals, inboxStore,
+ bridgeMap: outBridge, bridgeRemapped,
+ obsidianLocations: outObsidian, obsidianExtracted,
+ journalsChanged, inboxCount,
+ };
}
function parseJsonl(content) {
@@ -181,6 +213,7 @@ export async function up({ rootDir }) {
const legacyInboxPath = join(brainDir, 'inbox_log.jsonl');
const inboxPath = join(brainDir, 'inbox.json');
const bridgeMapPath = join(brainDir, 'memory-bridge-map.json');
+ const obsidianLocationsPath = join(brainDir, 'journal-obsidian-locations.json');
const instanceId = await readInstanceId(rootDir);
const nowIso = new Date().toISOString();
@@ -203,6 +236,16 @@ export async function up({ rootDir }) {
}
}
+ // Load the local Obsidian-locations sidecar if a prior run already created one
+ // (so we merge into it rather than clobber a newer local value).
+ let obsidianLocations = null;
+ if (existsSync(obsidianLocationsPath)) {
+ const raw = await readFile(obsidianLocationsPath, 'utf-8').catch(() => null);
+ if (raw != null) {
+ try { obsidianLocations = JSON.parse(raw); } catch { obsidianLocations = null; }
+ }
+ }
+
// Load legacy inbox JSONL if present AND we haven't already produced inbox.json
// (idempotency: once migrated, the .jsonl is renamed aside so this is skipped).
let inboxRows = [];
@@ -212,13 +255,21 @@ export async function up({ rootDir }) {
if (raw != null) inboxRows = parseJsonl(raw);
}
- const { journalsStore: outJournals, inboxStore, bridgeMap: outBridge, bridgeRemapped, journalsChanged, inboxCount } =
- computeDailyLogInboxMigration(journalsStore, inboxRows, { instanceId, nowIso, bridgeMap });
+ const {
+ journalsStore: outJournals, inboxStore,
+ bridgeMap: outBridge, bridgeRemapped,
+ obsidianLocations: outObsidian, obsidianExtracted,
+ journalsChanged, inboxCount,
+ } = computeDailyLogInboxMigration(journalsStore, inboxRows, { instanceId, nowIso, bridgeMap, obsidianLocations });
if (outJournals && journalsChanged) {
await writeFile(journalsPath, JSON.stringify(outJournals, null, 2));
}
+ if (outObsidian && obsidianExtracted > 0) {
+ await writeFile(obsidianLocationsPath, JSON.stringify(outObsidian, null, 2));
+ }
+
if (outBridge && bridgeRemapped > 0) {
await writeFile(bridgeMapPath, JSON.stringify(outBridge, null, 2));
}
@@ -245,6 +296,7 @@ export async function up({ rootDir }) {
console.log(
`🧠 daily-log/inbox-sync: journals ${journalsChanged ? 'normalized' : 'already current'}, ` +
`inbox ${hasLegacyInbox ? `migrated ${inboxCount} entr${inboxCount === 1 ? 'y' : 'ies'} → inbox.json` : 'already current'}` +
+ `${obsidianExtracted > 0 ? `, moved ${obsidianExtracted} Obsidian location${obsidianExtracted === 1 ? '' : 's'} to local sidecar` : ''}` +
`${bridgeRemapped > 0 ? `, re-keyed ${bridgeRemapped} journal memory-bridge entr${bridgeRemapped === 1 ? 'y' : 'ies'}` : ''}`
);
}
diff --git a/scripts/migrations/081-brain-daily-log-inbox-sync.test.js b/scripts/migrations/081-brain-daily-log-inbox-sync.test.js
index 48d02efcc2..161dbe8a01 100644
--- a/scripts/migrations/081-brain-daily-log-inbox-sync.test.js
+++ b/scripts/migrations/081-brain-daily-log-inbox-sync.test.js
@@ -88,6 +88,37 @@ describe('computeDailyLogInboxMigration (pure)', () => {
expect(journalsChanged).toBe(false);
});
+ it('extracts machine-local Obsidian fields off the synced record into the sidecar', () => {
+ const journals = {
+ records: {
+ '2026-04-18': {
+ id: 'uuid-1', date: '2026-04-18', content: 'hi', segments: [],
+ obsidianPath: 'Daily Log/2026-04-18.md', obsidianVaultId: 'vault-A',
+ },
+ },
+ };
+ const { journalsStore, obsidianLocations, obsidianExtracted } =
+ computeDailyLogInboxMigration(journals, [], { ...opts, obsidianLocations: {} });
+ const entry = journalsStore.records['2026-04-18'];
+ expect(entry).not.toHaveProperty('obsidianPath');
+ expect(entry).not.toHaveProperty('obsidianVaultId');
+ expect(obsidianExtracted).toBe(1);
+ expect(obsidianLocations['2026-04-18']).toEqual({
+ obsidianPath: 'Daily Log/2026-04-18.md', obsidianVaultId: 'vault-A',
+ });
+ });
+
+ it('does not overwrite a newer sidecar entry on re-run (idempotent extraction)', () => {
+ const journals = {
+ records: { '2026-04-18': { date: '2026-04-18', content: 'hi', segments: [], obsidianPath: 'old.md', obsidianVaultId: 'v1' } },
+ };
+ const existing = { '2026-04-18': { obsidianPath: 'new.md', obsidianVaultId: 'v2' } };
+ const { obsidianLocations, obsidianExtracted } =
+ computeDailyLogInboxMigration(journals, [], { ...opts, obsidianLocations: existing });
+ expect(obsidianExtracted).toBe(0);
+ expect(obsidianLocations['2026-04-18']).toEqual({ obsidianPath: 'new.md', obsidianVaultId: 'v2' });
+ });
+
it('re-keys journal memory-bridge entries from uuid to date, leaving others alone', () => {
const journals = { records: { '2026-04-18': { id: 'uuid-1', date: '2026-04-18', content: 'hi', segments: [] } } };
const bridgeMap = {
@@ -164,6 +195,29 @@ describe('migration 081 up()', () => {
expect(readJson('journals.json')).toEqual(journalsAfter1);
});
+ it('writes the Obsidian-locations sidecar and strips those fields from journals.json', async () => {
+ writeInstanceId('inst-x');
+ writeJson('journals.json', {
+ records: {
+ '2026-04-18': {
+ id: 'uuid-1', date: '2026-04-18', content: 'hi', segments: [],
+ obsidianPath: 'Daily Log/2026-04-18.md', obsidianVaultId: 'vault-A',
+ },
+ },
+ });
+
+ await migration.up({ rootDir });
+
+ const journals = readJson('journals.json');
+ expect(journals.records['2026-04-18']).not.toHaveProperty('obsidianPath');
+ expect(journals.records['2026-04-18']).not.toHaveProperty('obsidianVaultId');
+ expect(existsSync(join(brainDir, 'journal-obsidian-locations.json'))).toBe(true);
+ const sidecar = readJson('journal-obsidian-locations.json');
+ expect(sidecar['2026-04-18']).toEqual({
+ obsidianPath: 'Daily Log/2026-04-18.md', obsidianVaultId: 'vault-A',
+ });
+ });
+
it('re-keys the on-disk memory-bridge map for journal entries', async () => {
writeInstanceId('inst-x');
writeJson('journals.json', {
diff --git a/server/index.js b/server/index.js
index bc550f7dd8..421642695b 100644
--- a/server/index.js
+++ b/server/index.js
@@ -539,8 +539,11 @@ try {
console.error(`❌ agentActionExecutor init failed: ${err instanceof Error ? err.message : String(err)}`);
}
-// Recover any inbox entries stuck in 'classifying' from a previous crash/restart
-recoverStuckClassifications().catch(err => console.error(`❌ Brain recovery failed: ${err.message}`));
+// Inbox recovery is deferred until after initSyncLog() (see the ensureSelf chain
+// below) — it mutates inbox entries, which are now synced brain records, so its
+// updateInboxLog() calls append to sync_log.jsonl and MUST run after the log's
+// currentSeq is loaded, or they'd write low/duplicate sequence numbers and
+// corrupt peer cursors.
recoverStuckAnalyses().catch(err => console.error(`❌ Writers Room recovery failed: ${err.message}`));
recoverStuckAutoRuns().catch(err => console.error(`❌ Pipeline auto-run recovery failed: ${err.message}`));
// Initialize brain scheduler for daily digests and weekly reviews
@@ -706,6 +709,13 @@ app.use(errorMiddleware);
// race conditions where brain mutations arrive before the sync log is ready
ensureSelf()
.then(() => initSyncLog())
+ .then(() => {
+ // Recover inbox entries stuck in 'classifying' from a previous crash. Runs
+ // AFTER initSyncLog() because updateInboxLog() now appends to the brain sync
+ // log — running it before currentSeq is loaded would mint colliding seqs and
+ // corrupt peer cursors. Fire-and-forget; failures are logged.
+ recoverStuckClassifications().catch(err => console.error(`❌ Brain recovery failed: ${err.message}`));
+ })
.then(() => initMediaJobQueue())
.then(() => {
// Universe Builder needs the media job queue running before it can listen
diff --git a/server/services/brainJournal.js b/server/services/brainJournal.js
index ab8e74c044..0715bcd358 100644
--- a/server/services/brainJournal.js
+++ b/server/services/brainJournal.js
@@ -34,6 +34,16 @@ import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';
const SETTINGS_FILE = join(PATHS.brain, 'journal-settings.json');
+// Where each day's note was ACTUALLY mirrored, kept in a LOCAL sidecar that is
+// deliberately NOT a synced brain store. Obsidian vault ids and note paths are
+// machine-local: a peer's vault id is meaningless here, and federating it would
+// (1) make removeFromObsidian refuse to unlink this machine's own mirror when a
+// peer's id is stamped on the record, and (2) poison the brain reconcile
+// checksum so two machines with the same day but different vaults never
+// converge (endless reconcile churn — the #1077 amplification class). Shape:
+// { [date]: { obsidianPath, obsidianVaultId } }.
+const OBSIDIAN_LOCATIONS_FILE = join(PATHS.brain, 'journal-obsidian-locations.json');
+
const DEFAULT_SETTINGS = {
obsidianVaultId: null,
obsidianFolder: 'Daily Log',
@@ -69,31 +79,73 @@ export async function updateSettings(partial) {
// sync log so the edit federates. We never touch journals.json directly here.
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).
+async function loadObsidianLocations() {
+ await ensureDir(PATHS.brain);
+ return readJSONFile(OBSIDIAN_LOCATIONS_FILE, {});
+}
+
+async function getObsidianLocation(date) {
+ const map = await loadObsidianLocations();
+ return map[date] || { obsidianPath: null, obsidianVaultId: null };
+}
+
+// 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();
+ if (obsidianPath == null && obsidianVaultId == null) {
+ delete map[date];
+ } else {
+ map[date] = { obsidianPath: obsidianPath ?? null, obsidianVaultId: obsidianVaultId ?? null };
+ }
+ await writeFile(OBSIDIAN_LOCATIONS_FILE, JSON.stringify(map, null, 2));
+}
+
+// ── Synced journal entry store ───────────────────────────────────────────────
+
// Daily Log entries are keyed by calendar date in the entity store, so the
// record id IS the date — that's what lets two peers editing the same day
// converge (LWW on one record) instead of forking into per-machine uuids.
-const getEntry = (date) => brainStorage.getById('journals', date);
-
-// Persist a fully-formed entry under its date key. The inner `id` is stripped
-// before storage: the map key IS the id (matching every other entity store and
-// the 081 migration), and getById re-attaches it. Keeping an inner `id` would be
-// redundant and would pollute the synced record / reconcile checksum.
-// `emitEvent:false` because this module emits its own richer bridge-shaped events
-// (journals:upserted with the segment, journals:appended, etc.) right after, and
-// we don't want the generic brainStorage `journals:upserted` to double-fire.
-const putEntry = (date, entry) => {
+// Reads merge the local Obsidian location back onto the entry so callers
+// (summaries, UI, delete) still see obsidianPath/obsidianVaultId, even though
+// those fields live in the non-synced sidecar.
+async function getEntry(date) {
+ const entry = await brainStorage.getById('journals', date);
+ if (!entry) return null;
+ const loc = await getObsidianLocation(date);
+ return { ...entry, obsidianPath: loc.obsidianPath, obsidianVaultId: loc.obsidianVaultId };
+}
+
+// Persist a fully-formed entry under its date key. The inner `id` AND the
+// machine-local Obsidian fields are stripped before storage: the map key IS the
+// id (so an inner `id` would be redundant and pollute the synced record /
+// reconcile checksum), and obsidianPath/obsidianVaultId must never federate
+// (they live in the local sidecar — see OBSIDIAN_LOCATIONS_FILE). `emitEvent:false`
+// because this module emits its own richer bridge-shaped events (journals:upserted
+// with the segment, journals:appended, etc.) right after, and we don't want the
+// generic brainStorage `journals:upserted` to double-fire.
+async function putEntry(date, entry) {
// eslint-disable-next-line no-unused-vars
- const { id: _id, ...rest } = entry;
- return brainStorage.upsertWithId('journals', date, rest, { emitEvent: false });
-};
+ const { id: _id, obsidianPath: _op, obsidianVaultId: _ov, ...rest } = entry;
+ const saved = await brainStorage.upsertWithId('journals', date, rest, { emitEvent: false });
+ // Re-attach the local location so the returned entry shape is unchanged for callers.
+ const loc = await getObsidianLocation(date);
+ return { ...saved, obsidianPath: loc.obsidianPath, obsidianVaultId: loc.obsidianVaultId };
+}
// The legacy journals:changed event carried the full date→entry map. Rebuild it
// from the store (tombstones stripped) so existing consumers keep working. The
// brainStorage 2s cache absorbs dictation bursts so this isn't a hot re-read.
async function rawRecords() {
+ const locations = await loadObsidianLocations();
const records = {};
for (const entry of await brainStorage.getAll('journals')) {
- records[entry.date || entry.id] = entry;
+ const date = entry.date || entry.id;
+ const loc = locations[date] || { obsidianPath: null, obsidianVaultId: null };
+ records[date] = { ...entry, obsidianPath: loc.obsidianPath, obsidianVaultId: loc.obsidianVaultId };
}
return records;
}
@@ -143,8 +195,16 @@ export async function listJournals({ limit = 50, offset = 0, includeContent = fa
records.sort((a, b) => (b.date || '').localeCompare(a.date || ''));
const total = records.length;
const page = records.slice(offset, offset + limit);
+ // Hydrate just the page with each day's local Obsidian location (the
+ // obsidianPath/obsidianVaultId fields live in the non-synced sidecar, not the
+ // synced record) so summaries still report the mirror status.
+ const locations = await loadObsidianLocations();
+ const hydrated = page.map((entry) => {
+ const loc = locations[entry.date || entry.id] || { obsidianPath: null, obsidianVaultId: null };
+ return { ...entry, obsidianPath: loc.obsidianPath, obsidianVaultId: loc.obsidianVaultId };
+ });
return {
- records: includeContent ? page : page.map(toJournalSummary),
+ records: includeContent ? hydrated : hydrated.map(toJournalSummary),
total,
};
}
@@ -161,12 +221,12 @@ export async function getJournal(date) {
// we only seed the Daily-Log-specific fields. `id` is the date (the entity-store
// key) so it converges across peers; upsertWithId returns it as `id` too.
function newEntry(date) {
+ // Obsidian location is tracked in the local sidecar, never on the synced
+ // record, so it's intentionally absent here (putEntry strips it regardless).
return {
date,
content: '',
segments: [],
- obsidianPath: null,
- obsidianVaultId: null,
};
}
@@ -258,6 +318,8 @@ export async function deleteJournal(date) {
if (entry.obsidianPath) {
await removeFromObsidian(entry).catch((err) => console.error(`📓 Obsidian delete failed: ${err.message}`));
}
+ // Drop the local mirror-location record for this day (sidecar is not synced).
+ await saveObsidianLocation(date, { obsidianPath: null, obsidianVaultId: null });
brainEvents.emit('journals:changed', { records: await rawRecords() });
// Explicit deletion signal so memory bridges / integrations can archive
// the corresponding vector entry — the changed event alone doesn't tell
@@ -328,19 +390,16 @@ export async function syncToObsidian(entry, { force = false } = {}) {
return notePath;
}
-// Record the note location (path + vault) on the store entry whenever it
-// changes. Serialized via storeMutex so a fire-and-forget Obsidian persist
-// can't clobber concurrent appendJournal writes. Goes through putEntry like
-// every other write, so the path stamp federates too — harmless: obsidianVaultId
-// is machine-local and removeFromObsidian refuses to unlink when a peer's vault
-// id doesn't match the locally-configured one. The `!==` guard keeps this from
-// minting a redundant sync-log entry on every Obsidian sync of an unchanged day.
+// Record the note location (path + vault) in the LOCAL sidecar whenever it
+// changes — NOT on the synced journal record (these fields are machine-local;
+// see OBSIDIAN_LOCATIONS_FILE). Serialized via storeMutex so a fire-and-forget
+// Obsidian persist can't clobber concurrent appendJournal writes. The `!==`
+// guard skips a redundant sidecar write on every sync of an unchanged day.
async function persistObsidianLocation(date, notePath, vaultId) {
return storeMutex(async () => {
- const entry = await getEntry(date);
- if (!entry) return;
- if (entry.obsidianPath !== notePath || entry.obsidianVaultId !== vaultId) {
- await putEntry(date, { ...entry, obsidianPath: notePath, obsidianVaultId: vaultId });
+ const loc = await getObsidianLocation(date);
+ if (loc.obsidianPath !== notePath || loc.obsidianVaultId !== vaultId) {
+ await saveObsidianLocation(date, { obsidianPath: notePath, obsidianVaultId: vaultId });
}
});
}