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

fix([brain]): federate Daily Log and Inbox across peers

Adam Eivyd3e139d25698
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fa3ff64e61..4e8d3acb5d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,7 @@
## Fixed
+- **Brain Daily Log and Inbox now sync across federated machines** — your Daily Log entries and Inbox items were never federating to your other PortOS peers, even with Brain sync turned on. Both stores lived outside the brain sync pipeline — the Daily Log in a separate journal store and the Inbox as an append-only log — so neither was ever recorded in the change log that peers pull from. They are now first-class brain records that ride the same delta-sync + last-writer-wins + tombstone machinery as the rest of Brain (people, projects, ideas, links, …): edits propagate, deletes propagate as tombstones (so a delete on one machine can't be resurrected by another), and the anti-entropy reconcile self-heals a peer that was offline. Daily Log entries are keyed by date so the same day edited on two machines converges into one entry instead of forking. A migration converts each install's existing Inbox log to the new format (keeping a `.migrated` backup) and brings existing journal entries into the sync contract — no action needed.
- **Updating across a major dependency bump no longer breaks the UI** — when an update changed a workspace's `package.json` (e.g. the React 18 → 19 bump), the updater ran an in-place `npm install` over the old `node_modules`. Because the client/server lockfiles are per-install and gitignored, that could leave a half-upgraded, duplicated dependency tree (a stray `react@18` lingering beside `react@19`) — the build succeeded but the app threw "Invalid hook call" at runtime and rendered a blank page. The updater now detects which workspaces' `package.json` the pull actually changed and does a clean reinstall (wiping `node_modules` and the stale gitignored lockfile) for only those, resolving the tree from scratch; unchanged workspaces keep their fast incremental install. Both `update.sh` and `update.ps1` (Windows) got the fix, and the same guard now covers the manual `git pull` + `npm start` path — startup remembers each workspace's `package.json` hash and clean-reinstalls when it changes.
- **De-watermarked images now label correctly in the gallery lightbox** — after removing the visible Gemini / Nano-Banana ✦ sparkle, the resulting variant was meant to read "Watermark removed from …" in the lightbox lineage row and group as "Watermark removed". But the `watermarkRemoved` flag the server stamps on the variant was dropped during image normalization, so through the real gallery path (Image Gen, History, Collections) the variant fell through to the generic "Cleaned from …" label instead. The flag now survives normalization, so the honest lineage label and variant grouping fire as intended.
- **Database page works on Windows** — the Database page's Start/Fix/Status actions invoke the `db.sh` manager through bash; on Windows the script's native path (`H:\…\db.sh`) was passed with backslashes, which bash collapsed into a bogus path (exit 127, "No such file or directory"), so the page reported the Docker database as stopped even while it was running. The path is now normalized to forward slashes, which Git Bash accepts on Windows. A second Windows-only failure in the per-backend export path (spawning `mkdir -p`, which isn't a real executable on Windows) was also fixed by using Node's filesystem API instead. Mac/Linux behavior is unchanged.
diff --git a/data.reference/brain/inbox.json b/data.reference/brain/inbox.json
new file mode 100644
index 0000000000..79802cb55a
--- /dev/null
+++ b/data.reference/brain/inbox.json
@@ -0,0 +1,3 @@
+{
+ "records": {}
+}
diff --git a/data.reference/brain/inbox_log.jsonl b/data.reference/brain/inbox_log.jsonl
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/scripts/migrations/081-brain-daily-log-inbox-sync.js b/scripts/migrations/081-brain-daily-log-inbox-sync.js
new file mode 100644
index 0000000000..b9bbafbf37
--- /dev/null
+++ b/scripts/migrations/081-brain-daily-log-inbox-sync.js
@@ -0,0 +1,196 @@
+/**
+ * Migration 081 — bring the Daily Log (journals) and Inbox into brain peer-sync.
+ *
+ * Both stores were previously OUTSIDE the brain entity-store contract, so neither
+ * ever entered the sync log — they silently never federated across peers:
+ * - The Daily Log lived in journals.json with the right `{ records: { date: e } }`
+ * SHAPE, but its entries were written by a separate brainJournal store that
+ * never called brainSyncLog.appendChange, and `journals` wasn't in
+ * BRAIN_ENTITY_TYPES, so even a received entry would be dropped on apply.
+ * - The Inbox lived in inbox_log.jsonl, an append-only JSONL with no id-keyed
+ * map, no updatedAt LWW clock, and no tombstones.
+ *
+ * brainStorage now lists `journals` and `inbox` in BRAIN_ENTITY_TYPES as ordinary
+ * `{ records: { id: record } }` stores. This migration reshapes the on-disk data
+ * to match that contract so existing entries sync going forward:
+ *
+ * 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.
+ * 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
+ * meaningful). The old .jsonl is renamed aside (.migrated) as a recovery
+ * copy rather than deleted.
+ *
+ * Idempotent: re-running finds the inner `id` already stripped and the sync
+ * fields already present, and skips a missing/renamed inbox_log.jsonl. The wire
+ * format is the standard entity-store record, so no schemaVersion bump is needed
+ * — but a peer still on pre-081 code simply won't have `journals`/`inbox` in its
+ * BRAIN_ENTITY_TYPES and will skip those records on apply (forward-compatible).
+ *
+ * Runs in the boot-time migration runner, BEFORE the service layer is wired up,
+ * so it reads the instance id straight from data/instances.json and rewrites the
+ * JSON files directly.
+ */
+
+import { readFile, writeFile, rename } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+
+const UNKNOWN_INSTANCE = 'unknown';
+
+// Read this install's instance id without importing the service layer (which the
+// boot-time runner can't load yet). Falls back to the 'unknown' sentinel that
+// brainStorage itself uses when identity is unavailable.
+async function readInstanceId(rootDir) {
+ const file = join(rootDir, 'data', 'instances.json');
+ if (!existsSync(file)) return UNKNOWN_INSTANCE;
+ const raw = await readFile(file, 'utf-8').catch(() => null);
+ if (raw == null) return UNKNOWN_INSTANCE;
+ try {
+ return JSON.parse(raw)?.self?.instanceId || UNKNOWN_INSTANCE;
+ } catch {
+ return UNKNOWN_INSTANCE;
+ }
+}
+
+// Stamp the entity-store sync fields a record is missing, WITHOUT overwriting
+// values it already has. `seedTime` seeds createdAt/updatedAt when absent (for
+// inbox we pass capturedAt so the LWW clock reflects real capture order; for
+// 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 }) {
+ // eslint-disable-next-line no-unused-vars
+ const { id: _innerId, ...rest } = record;
+ return {
+ ...rest,
+ originInstanceId: rest.originInstanceId || instanceId,
+ createdAt: rest.createdAt || seedTime || nowIso,
+ updatedAt: rest.updatedAt || seedTime || rest.createdAt || nowIso,
+ };
+}
+
+/**
+ * Pure transform over parsed inputs, exported for unit tests.
+ * - journalsStore: parsed journals.json (or null if absent).
+ * - inboxRows: array of parsed inbox_log.jsonl rows (empty if absent).
+ * Returns { journalsStore, inboxStore, journalsChanged, inboxCount }.
+ */
+export function computeDailyLogInboxMigration(journalsStore, inboxRows, { instanceId, nowIso }) {
+ // 1. Journals: normalize each entry in place (strip inner id, stamp sync fields).
+ let journalsChanged = false;
+ let outJournals = null;
+ if (journalsStore && typeof journalsStore === 'object') {
+ const records = journalsStore.records && typeof journalsStore.records === 'object'
+ ? journalsStore.records
+ : {};
+ const nextRecords = {};
+ for (const [date, entry] of Object.entries(records)) {
+ if (!entry || typeof entry !== 'object') continue;
+ 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.
+ const normalized = normalizeRecord(entry, {
+ instanceId,
+ seedTime: entry.updatedAt || entry.createdAt || nowIso,
+ nowIso,
+ });
+ nextRecords[date] = normalized;
+ if (JSON.stringify(normalized) !== before) journalsChanged = true;
+ }
+ outJournals = { ...journalsStore, records: nextRecords };
+ }
+
+ // 2. Inbox: re-key JSONL rows by id into a records map.
+ const inboxRecords = {};
+ let inboxCount = 0;
+ for (const row of inboxRows) {
+ if (!row || typeof row !== 'object' || !row.id) continue;
+ inboxRecords[row.id] = normalizeRecord(row, {
+ instanceId,
+ seedTime: row.capturedAt || nowIso,
+ nowIso,
+ });
+ inboxCount++;
+ }
+ const inboxStore = { records: inboxRecords };
+
+ return { journalsStore: outJournals, inboxStore, journalsChanged, inboxCount };
+}
+
+function parseJsonl(content) {
+ const rows = [];
+ for (const line of content.trim().split('\n')) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ try {
+ rows.push(JSON.parse(trimmed));
+ } catch {
+ // Skip a corrupt/half-written line rather than aborting the migration.
+ }
+ }
+ return rows;
+}
+
+export async function up({ rootDir }) {
+ const brainDir = join(rootDir, 'data', 'brain');
+ const journalsPath = join(brainDir, 'journals.json');
+ const legacyInboxPath = join(brainDir, 'inbox_log.jsonl');
+ const inboxPath = join(brainDir, 'inbox.json');
+
+ const instanceId = await readInstanceId(rootDir);
+ const nowIso = new Date().toISOString();
+
+ // Load journals.json if present.
+ let journalsStore = null;
+ if (existsSync(journalsPath)) {
+ const raw = await readFile(journalsPath, 'utf-8').catch(() => null);
+ if (raw != null) {
+ try { journalsStore = JSON.parse(raw); } catch { journalsStore = 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 = [];
+ const hasLegacyInbox = existsSync(legacyInboxPath);
+ if (hasLegacyInbox) {
+ const raw = await readFile(legacyInboxPath, 'utf-8').catch(() => null);
+ if (raw != null) inboxRows = parseJsonl(raw);
+ }
+
+ const { journalsStore: outJournals, inboxStore, journalsChanged, inboxCount } =
+ computeDailyLogInboxMigration(journalsStore, inboxRows, { instanceId, nowIso });
+
+ if (outJournals && journalsChanged) {
+ await writeFile(journalsPath, JSON.stringify(outJournals, null, 2));
+ }
+
+ // Only write inbox.json + retire the legacy file when there was a legacy file
+ // to convert. If inbox.json already exists and no .jsonl remains, this is a
+ // re-run — leave the authoritative inbox.json untouched.
+ if (hasLegacyInbox) {
+ // Merge into an existing inbox.json if a partial prior run left one, so we
+ // never drop records already converted. New rows win only when absent.
+ let existing = {};
+ if (existsSync(inboxPath)) {
+ const raw = await readFile(inboxPath, 'utf-8').catch(() => null);
+ if (raw != null) {
+ try { existing = JSON.parse(raw)?.records || {}; } catch { existing = {}; }
+ }
+ }
+ const merged = { records: { ...inboxStore.records, ...existing } };
+ await writeFile(inboxPath, JSON.stringify(merged, null, 2));
+ // Rename the legacy JSONL aside as a recovery copy (idempotent: gone next run).
+ await rename(legacyInboxPath, `${legacyInboxPath}.migrated`);
+ }
+
+ console.log(
+ `🧠 daily-log/inbox-sync: journals ${journalsChanged ? 'normalized' : 'already current'}, ` +
+ `inbox ${hasLegacyInbox ? `migrated ${inboxCount} entr${inboxCount === 1 ? 'y' : 'ies'} → inbox.json` : 'already current'}`
+ );
+}
+
+export default { up };
diff --git a/scripts/migrations/081-brain-daily-log-inbox-sync.test.js b/scripts/migrations/081-brain-daily-log-inbox-sync.test.js
new file mode 100644
index 0000000000..f08e6c82ae
--- /dev/null
+++ b/scripts/migrations/081-brain-daily-log-inbox-sync.test.js
@@ -0,0 +1,148 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration, { computeDailyLogInboxMigration } from './081-brain-daily-log-inbox-sync.js';
+
+let rootDir;
+let brainDir;
+
+beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-081-'));
+ brainDir = join(rootDir, 'data', 'brain');
+ mkdirSync(brainDir, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+});
+
+const writeJson = (name, obj) => writeFileSync(join(brainDir, name), JSON.stringify(obj, null, 2));
+const writeJsonl = (name, rows) =>
+ writeFileSync(join(brainDir, name), rows.map((r) => JSON.stringify(r)).join('\n') + '\n');
+const readJson = (name) => JSON.parse(readFileSync(join(brainDir, name), 'utf-8'));
+const writeInstanceId = (id) => {
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ writeFileSync(join(rootDir, 'data', 'instances.json'), JSON.stringify({ self: { instanceId: id } }));
+};
+
+describe('computeDailyLogInboxMigration (pure)', () => {
+ const opts = { instanceId: 'inst-1', nowIso: '2026-06-09T00:00:00.000Z' };
+
+ it('strips the inner id from journal entries and stamps missing sync fields', () => {
+ const journals = {
+ records: {
+ '2026-04-18': { id: 'uuid-1', date: '2026-04-18', content: 'hi', segments: [] },
+ },
+ };
+ const { journalsStore, journalsChanged } = computeDailyLogInboxMigration(journals, [], opts);
+ const entry = journalsStore.records['2026-04-18'];
+ expect(entry).not.toHaveProperty('id');
+ expect(entry.originInstanceId).toBe('inst-1');
+ expect(entry.createdAt).toBe('2026-06-09T00:00:00.000Z');
+ expect(entry.updatedAt).toBe('2026-06-09T00:00:00.000Z');
+ expect(journalsChanged).toBe(true);
+ });
+
+ it('preserves existing journal sync clocks (no LWW bump on already-stamped days)', () => {
+ const journals = {
+ records: {
+ '2026-04-18': {
+ date: '2026-04-18', content: 'hi', segments: [],
+ originInstanceId: 'other', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-02-02T00:00:00.000Z',
+ },
+ },
+ };
+ const { journalsStore, journalsChanged } = computeDailyLogInboxMigration(journals, [], opts);
+ const entry = journalsStore.records['2026-04-18'];
+ expect(entry.originInstanceId).toBe('other');
+ expect(entry.updatedAt).toBe('2026-02-02T00:00:00.000Z');
+ // Already in shape (no inner id, all fields present) → no rewrite.
+ expect(journalsChanged).toBe(false);
+ });
+
+ it('re-keys inbox JSONL rows by id, drops inner id, seeds clocks from capturedAt', () => {
+ const rows = [
+ { id: 'a', capturedText: 'x', status: 'done', capturedAt: '2026-03-01T00:00:00.000Z' },
+ { id: 'b', capturedText: 'y', status: 'needs_review', capturedAt: '2026-03-02T00:00:00.000Z' },
+ ];
+ const { inboxStore, inboxCount } = computeDailyLogInboxMigration(null, rows, opts);
+ expect(inboxCount).toBe(2);
+ expect(Object.keys(inboxStore.records)).toEqual(['a', 'b']);
+ expect(inboxStore.records.a).not.toHaveProperty('id');
+ expect(inboxStore.records.a.originInstanceId).toBe('inst-1');
+ expect(inboxStore.records.a.createdAt).toBe('2026-03-01T00:00:00.000Z');
+ expect(inboxStore.records.a.updatedAt).toBe('2026-03-01T00:00:00.000Z');
+ });
+
+ it('skips inbox rows without an id', () => {
+ const { inboxStore, inboxCount } = computeDailyLogInboxMigration(null, [{ capturedText: 'no id' }], opts);
+ expect(inboxCount).toBe(0);
+ expect(inboxStore.records).toEqual({});
+ });
+
+ it('handles a null journals store (fresh install)', () => {
+ const { journalsStore, journalsChanged } = computeDailyLogInboxMigration(null, [], opts);
+ expect(journalsStore).toBeNull();
+ expect(journalsChanged).toBe(false);
+ });
+});
+
+describe('migration 081 up()', () => {
+ it('converts inbox_log.jsonl → inbox.json and renames the legacy file aside', async () => {
+ writeInstanceId('inst-x');
+ writeJsonl('inbox_log.jsonl', [
+ { id: 'a', capturedText: 'x', status: 'done', capturedAt: '2026-03-01T00:00:00.000Z' },
+ ]);
+
+ await migration.up({ rootDir });
+
+ expect(existsSync(join(brainDir, 'inbox.json'))).toBe(true);
+ expect(existsSync(join(brainDir, 'inbox_log.jsonl'))).toBe(false);
+ expect(existsSync(join(brainDir, 'inbox_log.jsonl.migrated'))).toBe(true);
+ const inbox = readJson('inbox.json');
+ expect(inbox.records.a.originInstanceId).toBe('inst-x');
+ expect(inbox.records.a).not.toHaveProperty('id');
+ });
+
+ it('normalizes journals.json in place', async () => {
+ writeInstanceId('inst-x');
+ writeJson('journals.json', {
+ records: { '2026-04-18': { id: 'uuid-1', date: '2026-04-18', content: 'hi', segments: [] } },
+ });
+
+ await migration.up({ rootDir });
+
+ const journals = readJson('journals.json');
+ expect(journals.records['2026-04-18']).not.toHaveProperty('id');
+ expect(journals.records['2026-04-18'].originInstanceId).toBe('inst-x');
+ });
+
+ it('is idempotent — a second run finds nothing to do and does not lose data', async () => {
+ writeInstanceId('inst-x');
+ writeJsonl('inbox_log.jsonl', [
+ { id: 'a', capturedText: 'x', status: 'done', capturedAt: '2026-03-01T00:00:00.000Z' },
+ ]);
+ writeJson('journals.json', {
+ records: { '2026-04-18': { id: 'uuid-1', date: '2026-04-18', content: 'hi', segments: [] } },
+ });
+
+ await migration.up({ rootDir });
+ const inboxAfter1 = readJson('inbox.json');
+ const journalsAfter1 = readJson('journals.json');
+
+ // Second run: no legacy jsonl remains, journals already in shape.
+ await migration.up({ rootDir });
+ expect(readJson('inbox.json')).toEqual(inboxAfter1);
+ expect(readJson('journals.json')).toEqual(journalsAfter1);
+ });
+
+ it('falls back to the unknown sentinel when instances.json is absent', async () => {
+ writeJsonl('inbox_log.jsonl', [
+ { id: 'a', capturedText: 'x', status: 'done', capturedAt: '2026-03-01T00:00:00.000Z' },
+ ]);
+ await migration.up({ rootDir });
+ expect(readJson('inbox.json').records.a.originInstanceId).toBe('unknown');
+ });
+});
diff --git a/server/services/brainJournal.js b/server/services/brainJournal.js
index c549c81145..ab8e74c044 100644
--- a/server/services/brainJournal.js
+++ b/server/services/brainJournal.js
@@ -11,19 +11,27 @@
* Storage files:
* data/brain/journals.json — { records: { 'YYYY-MM-DD': entry } }
* data/brain/journal-settings.json — { obsidianVaultId, obsidianFolder, autoSync }
+ *
+ * The journals.json store is OWNED by brainStorage (type `journals`, see
+ * BRAIN_ENTITY_TYPES): writes go through brainStorage.upsertWithId so every
+ * Daily Log edit lands in the brain sync log and federates to peers via the same
+ * delta-log + LWW + tombstone pipeline as every other brain entity. This module
+ * keeps the Daily-Log-specific concerns on top: date-keyed identity, segment
+ * append semantics, the Obsidian mirror, and the bridge events the memory
+ * vectorizer listens for. We must NOT write journals.json directly here anymore
+ * — that would bypass the sync log and silently diverge peers again.
*/
import { writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
-import { v4 as uuidv4 } from '../lib/uuid.js';
import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
+import * as brainStorage from './brainStorage.js';
import { brainEvents, now } from './brainStorage.js';
import * as obsidian from './obsidian.js';
import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';
-const JOURNALS_FILE = join(PATHS.brain, 'journals.json');
const SETTINGS_FILE = join(PATHS.brain, 'journal-settings.json');
const DEFAULT_SETTINGS = {
@@ -49,22 +57,45 @@ export async function updateSettings(partial) {
// ─── Store ─────────────────────────────────────────────────────────────────
-// Serialize every load→mutate→save of journals.json so a fire-and-forget
+// Serialize every read→mutate→write of a journal entry so a fire-and-forget
// Obsidian path-persist can't interleave with an appendJournal() and clobber
// newer segments. PortOS is single-user, but dictation bursts schedule
// overlapping async tasks (appendJournal → fire-and-forget syncToObsidian →
-// persistObsidianPath) that all want to rewrite the same file. This mutex
+// persistObsidianLocation) that all want to rewrite the same entry. This mutex
// guarantees at most one read-modify-write runs at a time.
+//
+// Entry storage is delegated to brainStorage (type `journals`): getById reads
+// the live record, upsertWithId(date, …) persists it AND appends to the brain
+// sync log so the edit federates. We never touch journals.json directly here.
const storeMutex = createMutex();
-async function loadStore() {
- await ensureDir(PATHS.brain);
- return readJSONFile(JOURNALS_FILE, { records: {} });
-}
+// 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) => {
+ // eslint-disable-next-line no-unused-vars
+ const { id: _id, ...rest } = entry;
+ return brainStorage.upsertWithId('journals', date, rest, { emitEvent: false });
+};
-async function saveStore(store) {
- await ensureDir(PATHS.brain);
- await writeFile(JOURNALS_FILE, JSON.stringify(store, null, 2));
+// 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 records = {};
+ for (const entry of await brainStorage.getAll('journals')) {
+ records[entry.date || entry.id] = entry;
+ }
+ return records;
}
// Accept YYYY-MM-DD only, and require a real calendar day so we can't create
@@ -106,8 +137,9 @@ function toJournalSummary(entry) {
}
export async function listJournals({ limit = 50, offset = 0, includeContent = false } = {}) {
- const store = await loadStore();
- const records = Object.values(store.records || {});
+ // getAll strips tombstones, so deleted days don't show in the sidebar even
+ // before the tombstone is GC'd.
+ const records = await brainStorage.getAll('journals');
records.sort((a, b) => (b.date || '').localeCompare(a.date || ''));
const total = records.length;
const page = records.slice(offset, offset + limit);
@@ -119,58 +151,52 @@ export async function listJournals({ limit = 50, offset = 0, includeContent = fa
export async function getJournal(date) {
if (!isIsoDate(date)) return null;
- const store = await loadStore();
- return store.records?.[date] || null;
+ return getEntry(date);
}
// ─── Writes ────────────────────────────────────────────────────────────────
-function ensureEntry(store, date) {
- if (!store.records) store.records = {};
- if (store.records[date]) return store.records[date];
- const entry = {
- id: uuidv4(),
+// Build a fresh entry skeleton for a date that has no record yet. createdAt/
+// updatedAt/originInstanceId are stamped by brainStorage.upsertWithId on write —
+// 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) {
+ return {
date,
content: '',
segments: [],
- createdAt: now(),
- updatedAt: now(),
obsidianPath: null,
obsidianVaultId: null,
};
- store.records[date] = entry;
- return entry;
}
// 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 persistObsidianPath() — callers must not assume
+// obsidianPath itself via persistObsidianLocation() — callers must not assume
// this async work mutates the `entry` they passed in or that a later
-// saveStore() in their flow will pick up the path.
+// putEntry() in their flow will pick up the path.
function scheduleObsidianSync(entry) {
syncToObsidian(entry).catch((err) => console.error(`📓 Obsidian sync failed: ${err.message}`));
}
export async function setJournalContent(date, content) {
if (!isIsoDate(date)) throw new Error(`invalid date: ${date}`);
- const { entry, records } = await storeMutex(async () => {
- const store = await loadStore();
- const entryLocal = ensureEntry(store, date);
+ const entry = await storeMutex(async () => {
+ const existing = await getEntry(date);
const clean = content || '';
- entryLocal.content = clean;
- // Full replace invalidates the old segment history: the user rewrote the
- // whole day, so segment metadata (counts, per-line sources, timestamps)
- // would otherwise drift from what's actually stored in `content`. Collapse
- // to a single 'edit' segment that represents the rewrite.
- entryLocal.segments = clean
- ? [{ text: clean, at: now(), source: 'edit' }]
- : [];
- entryLocal.updatedAt = now();
- await saveStore(store);
- return { entry: entryLocal, records: store.records };
+ const next = {
+ ...(existing || newEntry(date)),
+ content: clean,
+ // Full replace invalidates the old segment history: the user rewrote the
+ // whole day, so segment metadata (counts, per-line sources, timestamps)
+ // would otherwise drift from what's actually stored in `content`. Collapse
+ // to a single 'edit' segment that represents the rewrite.
+ segments: clean ? [{ text: clean, at: now(), source: 'edit' }] : [],
+ };
+ return putEntry(date, next);
});
scheduleObsidianSync(entry);
- brainEvents.emit('journals:changed', { records });
+ brainEvents.emit('journals:changed', { records: await rawRecords() });
// Per-entry event so downstream syncers (memory bridge) can update the
// single affected day without iterating the whole store.
brainEvents.emit('journals:upserted', { entry });
@@ -194,20 +220,22 @@ export async function appendJournal(date, text, { source = 'text' } = {}) {
if (!clean) return null;
const segmentSource = normalizeSource(source);
- const { entry, segment, records } = await storeMutex(async () => {
- const store = await loadStore();
- const entryLocal = ensureEntry(store, date);
+ const { entry, segment } = await storeMutex(async () => {
+ const existing = await getEntry(date);
+ const base = existing || newEntry(date);
const segmentLocal = { text: clean, at: now(), source: segmentSource };
- entryLocal.segments.push(segmentLocal);
- entryLocal.content = entryLocal.content
- ? `${entryLocal.content.trimEnd()}\n\n${clean}`
- : clean;
- entryLocal.updatedAt = now();
- await saveStore(store);
- return { entry: entryLocal, segment: segmentLocal, records: store.records };
+ const next = {
+ ...base,
+ segments: [...(Array.isArray(base.segments) ? base.segments : []), segmentLocal],
+ content: base.content
+ ? `${base.content.trimEnd()}\n\n${clean}`
+ : clean,
+ };
+ const saved = await putEntry(date, next);
+ return { entry: saved, segment: segmentLocal };
});
scheduleObsidianSync(entry);
- brainEvents.emit('journals:changed', { records });
+ brainEvents.emit('journals:changed', { records: await rawRecords() });
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
@@ -218,20 +246,19 @@ export async function appendJournal(date, text, { source = 'text' } = {}) {
export async function deleteJournal(date) {
if (!isIsoDate(date)) return false;
- const result = await storeMutex(async () => {
- const store = await loadStore();
- if (!store.records?.[date]) return null;
- const entryLocal = store.records[date];
- delete store.records[date];
- await saveStore(store);
- return { entry: entryLocal, records: store.records };
+ const entry = await storeMutex(async () => {
+ const existing = await getEntry(date);
+ if (!existing) return null;
+ // Tombstones in place (via brainStorage.remove) so the delete federates and
+ // a stale create echoed from a peer can't resurrect the day.
+ await brainStorage.remove('journals', date);
+ return existing;
});
- if (!result) return false;
- const { entry, records } = result;
+ if (!entry) return false;
if (entry.obsidianPath) {
await removeFromObsidian(entry).catch((err) => console.error(`📓 Obsidian delete failed: ${err.message}`));
}
- brainEvents.emit('journals:changed', { records });
+ 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
// the bridge which record vanished.
@@ -303,16 +330,17 @@ export async function syncToObsidian(entry, { force = false } = {}) {
// 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.
+// 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.
async function persistObsidianLocation(date, notePath, vaultId) {
return storeMutex(async () => {
- const store = await loadStore();
- const entry = store.records?.[date];
+ const entry = await getEntry(date);
if (!entry) return;
if (entry.obsidianPath !== notePath || entry.obsidianVaultId !== vaultId) {
- entry.obsidianPath = notePath;
- entry.obsidianVaultId = vaultId;
- await saveStore(store);
+ await putEntry(date, { ...entry, obsidianPath: notePath, obsidianVaultId: vaultId });
}
});
}
diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.js
index 8f1e5719d8..1943f8aec8 100644
--- a/server/services/brainJournal.test.js
+++ b/server/services/brainJournal.test.js
@@ -32,9 +32,39 @@ vi.mock('./obsidian.js', () => ({
deleteNote: vi.fn(),
}));
+// brainJournal now delegates entry storage to brainStorage's `journals` entity
+// store. Back it with an in-memory date→record map so the journal logic (segment
+// append, content replace, tombstone-on-delete, slim summaries) is exercised for
+// real while staying isolated from disk. Mirrors brainStorage semantics:
+// getById/getAll strip tombstones and re-attach the map key as `id`;
+// upsertWithId stores the record verbatim and stamps createdAt/updatedAt.
+const { journalRecords } = vi.hoisted(() => ({ journalRecords: new Map() }));
vi.mock('./brainStorage.js', () => ({
brainEvents: { emit: vi.fn() },
now: () => '2026-04-17T12:00:00.000Z',
+ getById: vi.fn(async (_type, id) => {
+ const rec = journalRecords.get(id);
+ return rec && !rec._deleted ? { id, ...rec } : null;
+ }),
+ getAll: vi.fn(async () =>
+ [...journalRecords.entries()]
+ .filter(([, rec]) => !rec._deleted)
+ .map(([id, rec]) => ({ id, ...rec }))),
+ upsertWithId: vi.fn(async (_type, id, record) => {
+ const existing = journalRecords.get(id);
+ const stored = {
+ ...record,
+ createdAt: existing?.createdAt ?? '2026-04-17T12:00:00.000Z',
+ updatedAt: '2026-04-17T12:00:00.000Z',
+ };
+ journalRecords.set(id, stored);
+ return { id, ...stored };
+ }),
+ remove: vi.fn(async (_type, id) => {
+ if (!journalRecords.has(id)) return false;
+ journalRecords.set(id, { _deleted: true, updatedAt: '2026-04-17T12:00:00.000Z' });
+ return true;
+ }),
}));
import * as journal from './brainJournal.js';
@@ -52,6 +82,7 @@ describe('brainJournal', () => {
// path silently creates sibling dirs, orphaning our mocked path.)
rmSync(TEMP_ROOT, { recursive: true, force: true });
mkdirSync(TEMP_ROOT, { recursive: true });
+ journalRecords.clear();
vi.clearAllMocks();
});
diff --git a/server/services/brainReconcile.test.js b/server/services/brainReconcile.test.js
index 37e4daf5bd..cb59589730 100644
--- a/server/services/brainReconcile.test.js
+++ b/server/services/brainReconcile.test.js
@@ -3,7 +3,7 @@ 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'],
+ BRAIN_ENTITY_TYPES: ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets', 'journals', 'inbox'],
getRawRecords: vi.fn(),
applyRemoteRecord: vi.fn(),
}));
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 9a5fbd8e17..3dac6f4daf 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -2,8 +2,8 @@
* Brain Storage Service
*
* Handles file-based persistence for the Brain feature.
- * - JSON for entity stores (people, projects, ideas, admin)
- * - JSONL for append-heavy logs (inbox_log, digests, reviews)
+ * - JSON for entity stores (people, projects, ideas, admin, …, journals, inbox)
+ * - JSONL for append-only generated logs (digests, reviews)
* - In-memory caching with TTL for performance
*/
@@ -23,11 +23,20 @@ const DATA_DIR = PATHS.brain;
// The JSON entity stores that participate in peer sync (have records with IDs).
// Canonical list — sync, tombstone GC, and origin backfill all derive from it
-// so adding an 8th type can't silently drop out of one of those paths. (The
+// so adding a type can't silently drop out of one of those paths. (The
// boot-time migration keeps its own copy by necessity — migrations run before
// the service layer is wired up — see scripts/migrations/080-*.js.)
+//
+// `journals` (the Daily Log) and `inbox` were added in migration 081: both were
+// previously stored OUTSIDE this contract (journals in a separate brainJournal
+// store, inbox as an append-only JSONL) and so never entered the sync log —
+// they silently never federated. They are now `{ records: { id: record } }`
+// stores exactly like the others (journals keyed by date, inbox by uuid), so
+// the delta log, anti-entropy reconcile, tombstone GC, and originInstanceId
+// backfill all cover them with no per-type branching.
export const BRAIN_ENTITY_TYPES = Object.freeze([
'people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets',
+ 'journals', 'inbox',
]);
// A tombstone is a deleted-record marker kept IN PLACE in `data.records[id]`
@@ -59,7 +68,6 @@ export const BRAIN_TOMBSTONE_GRACE_MS = 30 * 24 * 60 * 60 * 1000;
// File paths
const FILES = {
meta: join(DATA_DIR, 'meta.json'),
- inboxLog: join(DATA_DIR, 'inbox_log.jsonl'),
people: join(DATA_DIR, 'people.json'),
projects: join(DATA_DIR, 'projects.json'),
ideas: join(DATA_DIR, 'ideas.json'),
@@ -67,6 +75,12 @@ const FILES = {
memories: join(DATA_DIR, 'memories.json'),
links: join(DATA_DIR, 'links.json'),
buckets: join(DATA_DIR, 'buckets.json'),
+ // journals (Daily Log) and inbox are now id-keyed entity stores (see
+ // BRAIN_ENTITY_TYPES) so they ride the peer-sync pipeline. journals.json keeps
+ // its filename + { records: { 'YYYY-MM-DD': entry } } shape; inbox migrated
+ // from the old inbox_log.jsonl to inbox.json (migration 081).
+ journals: join(DATA_DIR, 'journals.json'),
+ inbox: join(DATA_DIR, 'inbox.json'),
digests: join(DATA_DIR, 'digests.jsonl'),
reviews: join(DATA_DIR, 'reviews.jsonl')
};
@@ -84,7 +98,8 @@ const caches = {
memories: { data: null, timestamp: 0 },
links: { data: null, timestamp: 0 },
buckets: { data: null, timestamp: 0 },
- inboxLog: { data: null, timestamp: 0 },
+ journals: { data: null, timestamp: 0 },
+ inbox: { data: null, timestamp: 0 },
digests: { data: null, timestamp: 0 },
reviews: { data: null, timestamp: 0 }
};
@@ -291,6 +306,46 @@ export async function update(type, id, updates) {
return { id, ...record };
}
+/**
+ * Upsert a record under a CALLER-PROVIDED id (full replace, create-if-missing).
+ *
+ * `create()` mints a uuid, which is wrong for stores whose identity is a natural
+ * key — the Daily Log keys entries by calendar date so the same day converges
+ * across peers instead of forking into per-machine uuids. This primitive lets
+ * such a store own its id while still riding the exact entity-store contract:
+ * it preserves `originInstanceId`/`createdAt` from an existing live record,
+ * stamps a fresh `updatedAt` (the LWW clock), appends a create/update entry to
+ * the sync log, and emits `${type}:upserted` unless the caller suppresses it.
+ *
+ * `recordData` is stored verbatim except for the three managed fields — callers
+ * pass the FULL desired record (this does not merge unknown fields the way
+ * `update()` does). `emitEvent:false` lets a caller (e.g. brainJournal) emit its
+ * own richer, bridge-shaped event instead of the generic one.
+ */
+export async function upsertWithId(type, id, recordData, { emitEvent = true } = {}) {
+ const data = await loadJsonStore(type);
+ const existing = data.records[id];
+ const live = existing && !isTombstone(existing) ? existing : null;
+ const timestamp = now();
+ const originInstanceId = live?.originInstanceId ?? await getInstanceId();
+
+ const record = {
+ ...recordData,
+ originInstanceId,
+ createdAt: live?.createdAt ?? timestamp,
+ updatedAt: timestamp
+ };
+
+ data.records[id] = record;
+ await saveJsonStore(type, data);
+ if (emitEvent) brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });
+ await brainSyncLog.appendChange(live ? 'update' : 'create', type, id, record, originInstanceId)
+ .catch(err => console.error(`⚠️ Sync log append failed for upsert ${type}/${id}: ${err.message}`));
+
+ console.log(`🧠 Upserted ${type} record: ${id}`);
+ return { id, ...record };
+}
+
/**
* Apply many record updates to one store in a single load-modify-save.
*
@@ -377,7 +432,7 @@ export async function query(type, filters = {}) {
}
// =============================================================================
-// JSONL APPEND LOGS (inbox_log, digests, reviews)
+// JSONL APPEND LOGS (digests, reviews)
// =============================================================================
/**
@@ -420,40 +475,28 @@ async function appendJsonl(type, record) {
brainEvents.emit(`${type}:added`, record);
}
-/**
- * Rewrite entire JSONL file (for updates/deletes)
- */
-async function rewriteJsonl(type, records) {
- await ensureBrainDir();
- const content = records.map(r => JSON.stringify(r)).join('\n') + (records.length > 0 ? '\n' : '');
- await writeFile(FILES[type], content);
-
- caches[type].data = records;
- caches[type].timestamp = Date.now();
-
- brainEvents.emit(`${type}:changed`, records);
-}
-
// =============================================================================
// INBOX LOG OPERATIONS
// =============================================================================
+// The inbox is now an id-keyed entity store (see BRAIN_ENTITY_TYPES) so it
+// federates through the same delta-log + LWW + tombstone pipeline as every other
+// brain type. These wrappers keep the historical getInboxLog/createInboxLog/…
+// API (capturedAt sort, status counts) on top of the generic entity primitives.
+
/**
- * Get all inbox log entries
+ * Get all inbox log entries (newest-first by capturedAt), optional status filter.
*/
export async function getInboxLog(options = {}) {
const { status, limit = 50, offset = 0 } = options;
- let records = await loadJsonlStore('inboxLog');
+ let records = await getAll('inbox');
- // Sort by capturedAt descending (newest first)
records = records.sort((a, b) => new Date(b.capturedAt) - new Date(a.capturedAt));
- // Filter by status if provided
if (status) {
records = records.filter(r => r.status === status);
}
- // Apply pagination
return records.slice(offset, offset + limit);
}
@@ -461,66 +504,36 @@ export async function getInboxLog(options = {}) {
* Get inbox log entry by ID
*/
export async function getInboxLogById(id) {
- const records = await loadJsonlStore('inboxLog');
- return records.find(r => r.id === id) || null;
+ return getById('inbox', id);
}
/**
- * Create inbox log entry
+ * Create inbox log entry. `capturedAt` is the user-facing capture time (kept
+ * distinct from the sync `createdAt`/`updatedAt` clocks stamped by create()).
*/
export async function createInboxLog(entry) {
- const record = {
- id: generateId(),
- ...entry,
- capturedAt: entry.capturedAt || now()
- };
-
- await appendJsonl('inboxLog', record);
- console.log(`🧠 Created inbox log: ${record.id}`);
- return record;
+ return create('inbox', { ...entry, capturedAt: entry.capturedAt || now() });
}
/**
- * Update inbox log entry
+ * Update inbox log entry (partial merge — returns null if absent/tombstoned).
*/
export async function updateInboxLog(id, updates) {
- const records = await loadJsonlStore('inboxLog');
- const index = records.findIndex(r => r.id === id);
-
- if (index === -1) {
- return null;
- }
-
- records[index] = { ...records[index], ...updates };
- await rewriteJsonl('inboxLog', records);
-
- console.log(`🧠 Updated inbox log: ${id}`);
- return records[index];
+ return update('inbox', id, updates);
}
/**
- * Delete inbox log entry
+ * Delete inbox log entry (tombstones in place for sync convergence).
*/
export async function deleteInboxLog(id) {
- const records = await loadJsonlStore('inboxLog');
- const index = records.findIndex(r => r.id === id);
-
- if (index === -1) {
- return false;
- }
-
- records.splice(index, 1);
- await rewriteJsonl('inboxLog', records);
-
- console.log(`🧠 Deleted inbox log: ${id}`);
- return true;
+ return remove('inbox', id);
}
/**
* Get inbox log count by status
*/
export async function getInboxLogCounts() {
- const records = await loadJsonlStore('inboxLog');
+ const records = await getAll('inbox');
const counts = {
total: records.length,
diff --git a/server/services/brainSync.test.js b/server/services/brainSync.test.js
index 4fca8519e6..6a94de39fc 100644
--- a/server/services/brainSync.test.js
+++ b/server/services/brainSync.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('./brainStorage.js', () => ({
applyRemoteRecord: vi.fn(),
- BRAIN_ENTITY_TYPES: ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets'],
+ BRAIN_ENTITY_TYPES: ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets', 'journals', 'inbox'],
}));
vi.mock('./brainSyncLog.js', () => ({
diff --git a/server/services/brainTombstoneGc.test.js b/server/services/brainTombstoneGc.test.js
index fd61bc3caf..7505206f25 100644
--- a/server/services/brainTombstoneGc.test.js
+++ b/server/services/brainTombstoneGc.test.js
@@ -1,12 +1,12 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets'];
+const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets', 'journals', 'inbox'];
const pruneTombstones = vi.fn();
vi.mock('./brainStorage.js', () => ({
pruneTombstones: (...args) => pruneTombstones(...args),
BRAIN_TOMBSTONE_GRACE_MS: 30 * 24 * 60 * 60 * 1000,
- BRAIN_ENTITY_TYPES: ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets'],
+ BRAIN_ENTITY_TYPES: ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets', 'journals', 'inbox'],
}));
import { sweepBrainTombstones } from './brainTombstoneGc.js';