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
split brain entity stores to per-record collectionStore layout (#725)
[._.]/ Adam Eivydc2dbc076e06
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8620c417f1..64664236d6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -50,6 +50,8 @@## Internal+- **[issue-725] Brain entity stores split to per-record `collectionStore` layout.** Every Brain store (people, projects, ideas, admin, memories, links, buckets, journals, inbox, songs) moved off its monolithic `data/brain/<type>.json` file — where every create/update/delete rewrote the whole file and every read parsed all records behind a 2s cache and one global write mutex — onto the per-record `collectionStore` shape (`data/brain/<type>/<id>/index.json`), read through to disk with per-id write queues so writes to different records no longer serialize. This is proactive scale headroom: PortOS is distributed and a user's federated peers accumulate Brain data on their own schedule, so stores are prepared for size before any one install hits the whole-file-rewrite cliff. Federation is untouched — Brain federates strictly per-record through the storage API seams, so the on-disk container shape is orthogonal to the wire format (no schema-version bump, no wire-category change), and in-place tombstones are preserved through the split so no last-writer-wins delete marker is lost. Migration 200 splits existing installs (legacy files renamed to `.bak-200`, never deleted; idempotent and recovery-safe), and the shared split skeleton (`makeSplitMigration`) gained a `map` mode for the object-keyed `{ records: { <id>: rec } }` shape alongside the existing array mode. Every exported `brainStorage` function keeps its signature and behavior, so all runtime consumers and the whole reconcile/anti-entropy path are unchanged. (`server/services/brainStorage.js`, `scripts/migrations/200-split-brain-stores-to-per-record.js`, `scripts/migrations/_lib.js`)+- **[issue-2775] De-flaked the MidiVisualization "Space toggles playback" test.** The MIDI-visualization component tests asserted on the transport button's *optimistic* `playing` state and raced the synth player's async lifecycle (`play()`'s `await ctx.resume()` microtask hop and the immediate `totalSec <= 0 → onEnded` reset), so `findByLabelText('Pause playback')` failed intermittently in CI and passed on re-run. `useMidiPlayer` is now mocked in the component test with a synchronous state-flip stub, so the three chrome-wiring assertions (playing → label, click/Space → toggle, collapse → teardown) are deterministic and no longer depend on audio timing. The hook's real async behavior stays covered directly in `useMidiPlayer.test.jsx` and the player lib in `midiPlayback.test.js`, so no coverage is lost. (`client/src/components/songs/MidiVisualization.test.jsx`)- **[issue-2706] Stage-seeding migrations now guard their own `data.reference` assets.** Migrations 189 (model-personality), 094 (object-attachment checks), and 182 (CWQE quality) each seed stage prompts on upgrade but shipped without a colocated test, so a rename or removal of a reference template would have surfaced only at runtime as "Stage not found" on a fresh install. Each now has a `.test.js` asserting it seeds when absent, no-ops on re-run, never clobbers a customized template or hand-tuned config entry, and — the point — that every `data.reference/prompts/stages/*.md` template it names and its `stage-config.json` entry actually ship. The guard is anchored to the migration's own stage list (now exposed on the object the seed helper returns), so adding a stage without shipping its template fails the suite instead of leaving it green against a stale hand-copied list. The three suites collapse to one `runSeedStageMigrationTests({ migration, stages, prefix })` call apiece via a new shared helper — the seed-family analogue of `_testHelpers.js`'s `runPromptMigrationTests`. (`scripts/migrations/_seedStageTestHelpers.js`)diff --git a/scripts/migrations/200-split-brain-stores-to-per-record.js b/scripts/migrations/200-split-brain-stores-to-per-record.jsnew file mode 100644index 0000000000..55cda0d897--- /dev/null+++ b/scripts/migrations/200-split-brain-stores-to-per-record.js@@ -0,0 +1,107 @@+/**+ * Split each monolithic brain entity store `data/brain/<type>.json` into+ * per-record files under `data/brain/<type>/<id>/index.json`, with a type-level+ * `data/brain/<type>/index.json` stamping `schemaVersion: 1`.+ *+ * Why (issue #725):+ * Every brain entity store was a single `{ records: { <id>: record } }` file+ * that `brainStorage.js` rewrote whole on every create/update/delete and+ * parsed whole on every read (behind a 2s TTL cache + one global write mutex).+ * That's fine at a dozen records but does not scale — and PortOS is+ * distributed: other installs (and a user's federated peers) accumulate brain+ * data on their own schedule, and we don't know how large those stores are.+ * The per-record `collectionStore` layout reads/writes one record at a time+ * and lets writes to different records proceed in parallel. See+ * `server/lib/collectionStore.js`.+ *+ * What changes on disk (per type):+ *+ * before: after:+ * data/brain/ data/brain/+ * └── people.json ├── people/+ * { records: { │ ├── index.json (schemaVersion: 1)+ * "<id>": { … } } } │ ├── <id>/+ * │ │ └── index.json (the record)+ * │ └── …+ * └── people.json.bak-200 (renamed, not deleted)+ *+ * The legacy file is RENAMED to `<type>.json.bak-200`, never deleted — recovery+ * path stays open. A later migration (or manual cleanup) can remove the backups+ * once validated.+ *+ * Federation is UNAFFECTED. Brain federates strictly per-record through the+ * `brainStorage` API seams (`getRawRecords` / `appendChange` / `applyRemoteRecord`),+ * never by shipping a whole-store file — so the on-disk container shape is+ * orthogonal to the wire format and this split needs no `schemaVersions.js` bump+ * or wire-category change (brain is intentionally ungated there).+ *+ * TOMBSTONES are preserved. Brain keeps deleted records in place as+ * `{ _deleted: true, updatedAt, originInstanceId, deletedAt }` markers so the+ * last-writer-wins guard in `applyRemoteRecord` can reject a stale `create`+ * echoed back from a peer. The `map`-shape split writes every map value verbatim+ * (tombstones included), so no delete is silently resurrected by the upgrade.+ *+ * Idempotency: gate 1 (type index already at v1) makes a re-run after full+ * success a no-op; the per-record existing-id check finishes a partial run+ * without clobbering fresher post-crash state; a fresh install with no legacy+ * file stamps the type index so the boot verifier doesn't flag it missing.+ *+ * Records carry no record-shape `schemaVersion` — only the type-level layout+ * version (1, this migration's stamp) applies. Brain stores hold no cross-record+ * type-level state (no `runs[]` analog), so `config` is `{}`.+ */++import { makeSplitMigration } from './_lib.js';++// FROZEN snapshot of the brain entity types as of migration 200. The live list+// is `BRAIN_ENTITY_TYPES` in server/services/brainStorage.js, but a migration is+// a point-in-time record — it must NOT track later additions to that list (a+// type added after this migration gets its own later split), so it keeps its own+// copy exactly as migrations 080/081 do.+const BRAIN_ENTITY_TYPES = [+ 'people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets',+ 'journals', 'inbox', 'songs',+];++// The type-level storage-layout version this migration stamps. Mirrors+// BRAIN_STORE_SCHEMA_VERSION in brainStorage.js.+const BRAIN_STORE_SCHEMA_VERSION = 1;++// Record ids are UUIDs for every type EXCEPT `journals`, which keys entries by+// calendar date (`YYYY-MM-DD`) so the same day converges across peers. Both+// shapes match the collectionStore default id allowlist — keep them in lockstep+// so a record whose id the store would accept gets split, and one it would+// reject (and silently drop from `listIds`) is left in the backup for manual+// recovery rather than written to a directory the store can never load.+const BRAIN_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;++// One split per brain entity type. `makeSplitMigration` joins its `typeDirName`+// and `legacyFilename` under `data/`, so the nested `brain/<type>` paths target+// `data/brain/<type>/` and `data/brain/<type>.json` respectively.+const perTypeSplits = BRAIN_ENTITY_TYPES.map((type) => makeSplitMigration({+ migrationLabel: `migration 200 (brain/${type})`,+ typeDirName: `brain/${type}`,+ legacyFilename: `brain/${type}.json`,+ backupSuffix: '.bak-200',+ typeSchemaVersion: BRAIN_STORE_SCHEMA_VERSION,+ typeLabel: type,+ recordsKey: 'records',+ recordsShape: 'map',+ idPattern: BRAIN_ID_PATTERN,+ recordNoun: `brain ${type} record`,+ onUnreadable: 'throw', // keep pending so a repaired file re-splits next boot+}).up);++export default {+ up: async (ctx) => {+ const perType = [];+ // Sequential (not Promise.all) so the per-type log lines stay ordered and a+ // failure surfaces against the type that caused it. Each type's split is+ // independent — `onUnreadable: 'throw'` on one leaves the others' work in+ // place and keeps THIS migration pending for a retry.+ for (const up of perTypeSplits) {+ perType.push(await up(ctx));+ }+ return { ok: true, perType };+ },+};diff --git a/scripts/migrations/200-split-brain-stores-to-per-record.test.js b/scripts/migrations/200-split-brain-stores-to-per-record.test.jsnew file mode 100644index 0000000000..1ab219f638--- /dev/null+++ b/scripts/migrations/200-split-brain-stores-to-per-record.test.js@@ -0,0 +1,168 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './200-split-brain-stores-to-per-record.js';++const writeJson = (p, v) => writeFileSync(p, JSON.stringify(v, null, 2) + '\n');+const readJson = (p) => JSON.parse(readFileSync(p, 'utf-8'));++// A live brain record (no `id` field — the map KEY is the id).+const rec = (overrides = {}) => ({+ originInstanceId: 'inst-A',+ createdAt: '2026-07-01T00:00:00.000Z',+ updatedAt: '2026-07-01T00:00:00.000Z',+ ...overrides,+});++// An in-place tombstone (what brainStorage.remove writes).+const tombstone = (ts = '2026-07-02T00:00:00.000Z') => ({+ _deleted: true,+ updatedAt: ts,+ originInstanceId: 'inst-A',+ deletedAt: ts,+});++describe('migration 200 — split brain stores to per-record', () => {+ let rootDir;+ let dataDir;+ let brainDir;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-200-'));+ dataDir = join(rootDir, 'data');+ brainDir = join(dataDir, 'brain');+ mkdirSync(brainDir, { recursive: true });+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ const typeDir = (type) => join(brainDir, type);+ const typeIndexPath = (type) => join(typeDir(type), 'index.json');+ const recordPath = (type, id) => join(typeDir(type), id, 'index.json');+ const legacyPath = (type) => join(brainDir, `${type}.json`);+ const backupPath = (type) => join(brainDir, `${type}.json.bak-200`);++ it('fresh install (no legacy files) stamps every type index at v1', async () => {+ const result = await migration.up({ rootDir });+ expect(result.ok).toBe(true);+ // All 10 brain entity types get an index.json stamped at v1.+ for (const type of ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets', 'journals', 'inbox', 'songs']) {+ expect(existsSync(typeIndexPath(type))).toBe(true);+ const idx = readJson(typeIndexPath(type));+ expect(idx.schemaVersion).toBe(1);+ expect(idx.type).toBe(type);+ expect(idx.config).toEqual({});+ }+ });++ it('splits a map-shaped store into per-record files and backs up the legacy file', async () => {+ writeJson(legacyPath('people'), {+ records: {+ 'aaaaaaaa-1111': rec({ name: 'Alice' }),+ 'bbbbbbbb-2222': rec({ name: 'Bob' }),+ },+ });++ await migration.up({ rootDir });++ // Records land at data/brain/people/<id>/index.json, id derived from the KEY.+ expect(readJson(recordPath('people', 'aaaaaaaa-1111')).name).toBe('Alice');+ expect(readJson(recordPath('people', 'bbbbbbbb-2222')).name).toBe('Bob');+ // The record value carries no `id` field (id is the directory name).+ expect(readJson(recordPath('people', 'aaaaaaaa-1111')).id).toBeUndefined();+ // Type index stamped.+ expect(readJson(typeIndexPath('people')).schemaVersion).toBe(1);+ // Legacy renamed, not deleted.+ expect(existsSync(legacyPath('people'))).toBe(false);+ expect(existsSync(backupPath('people'))).toBe(true);+ expect(Object.keys(readJson(backupPath('people')).records)).toHaveLength(2);+ });++ it('PRESERVES in-place tombstones through the split (LWW markers survive)', async () => {+ writeJson(legacyPath('links'), {+ records: {+ 'live-0001': rec({ url: 'https://example.com' }),+ 'dead-0002': tombstone('2026-07-05T00:00:00.000Z'),+ },+ });++ await migration.up({ rootDir });++ const live = readJson(recordPath('links', 'live-0001'));+ expect(live.url).toBe('https://example.com');+ const dead = readJson(recordPath('links', 'dead-0002'));+ expect(dead._deleted).toBe(true);+ expect(dead.updatedAt).toBe('2026-07-05T00:00:00.000Z');+ expect(dead.deletedAt).toBe('2026-07-05T00:00:00.000Z');+ });++ it('keys journals by calendar date and splits them like any other type', async () => {+ writeJson(legacyPath('journals'), {+ records: {+ '2026-07-18': rec({ note: 'wrote code' }),+ '2026-07-19': rec({ note: 'shipped it' }),+ },+ });++ await migration.up({ rootDir });++ expect(readJson(recordPath('journals', '2026-07-18')).note).toBe('wrote code');+ expect(readJson(recordPath('journals', '2026-07-19')).note).toBe('shipped it');+ expect(readJson(typeIndexPath('journals')).schemaVersion).toBe(1);+ });++ it('is idempotent — a second run is a no-op and leaves the backup untouched', async () => {+ writeJson(legacyPath('ideas'), { records: { 'idea-0001': rec({ title: 'X' }) } });++ await migration.up({ rootDir });+ const backupBefore = readFileSync(backupPath('ideas'), 'utf-8');++ const second = await migration.up({ rootDir });+ expect(second.ok).toBe(true);+ // Backup unchanged; record still present.+ expect(readFileSync(backupPath('ideas'), 'utf-8')).toBe(backupBefore);+ expect(readJson(recordPath('ideas', 'idea-0001')).title).toBe('X');+ });++ it('skips reserved map keys (__proto__ / constructor / prototype), leaving them in the backup', async () => {+ // Build the map WITHOUT __proto__ as a literal object key (that would set the+ // prototype), then attach reserved keys as own enumerable properties the way+ // JSON.parse would surface them.+ const records = { 'real-0001': rec({ name: 'ok' }) };+ Object.defineProperty(records, '__proto__', { value: rec({ name: 'evil' }), enumerable: true, configurable: true });+ records.constructor = rec({ name: 'ctor' });+ writeJson(legacyPath('admin'), { records });++ await migration.up({ rootDir });++ expect(existsSync(recordPath('admin', 'real-0001'))).toBe(true);+ expect(existsSync(recordPath('admin', '__proto__'))).toBe(false);+ expect(existsSync(recordPath('admin', 'constructor'))).toBe(false);+ });++ it('splits each type independently — one type with data does not affect the empty ones', async () => {+ writeJson(legacyPath('songs'), { records: { 'song-0001': rec({ title: 'Wonderwall' }) } });++ await migration.up({ rootDir });++ expect(readJson(recordPath('songs', 'song-0001')).title).toBe('Wonderwall');+ // A type with no legacy file still gets its index stamped (fresh-install path).+ expect(readJson(typeIndexPath('people')).schemaVersion).toBe(1);+ expect(existsSync(backupPath('people'))).toBe(false);+ });++ it('recovers from a .bak-200 backup when the split half-completed', async () => {+ // Simulate: legacy already renamed to backup, but records not yet split.+ writeJson(backupPath('projects'), { records: { 'proj-0001': rec({ name: 'PortOS' }) } });++ await migration.up({ rootDir });++ expect(readJson(recordPath('projects', 'proj-0001')).name).toBe('PortOS');+ expect(readJson(typeIndexPath('projects')).schemaVersion).toBe(1);+ // Backup left in place (recovery path never re-renames).+ expect(existsSync(backupPath('projects'))).toBe(true);+ });+});diff --git a/scripts/migrations/_lib.js b/scripts/migrations/_lib.jsindex d539056174..aecdaf085e 100644--- a/scripts/migrations/_lib.js+++ b/scripts/migrations/_lib.js@@ -46,6 +46,17 @@ import { createHash } from 'crypto';// - `buildConfig(doc)` — 034 moves the legacy cross-record `runs[]` into// `config.runs`; the others stamp `config: {}`.// - `idPattern` / `invalidWarn` / `recordNoun` — per-kind id shape + log copy.+// - `recordsShape: 'array' | 'map'` — the legacy container shape. 034/035/036/+// 059 store `{ [recordsKey]: [ {id, …}, … ] }` (an ARRAY; id comes from+// `record.id`) — the default `'array'`. Brain entity stores (migration 200)+// store `{ [recordsKey]: { <id>: record } }` (an object MAP; id is the KEY,+// the record value carries no id field). `'map'` iterates `Object.entries`,+// derives the id from the key, and — because the value is written verbatim —+// PRESERVES in-place tombstones (`{ _deleted: true, updatedAt, … }`) so a+// split can't drop the last-writer-wins markers federation depends on. Map+// mode also skips the reserved keys `__proto__` / `constructor` / `prototype`+// (a legacy JSON map can carry them as own keys; the collectionStore id+// allowlist would accept them, so guard here) — left in the backup.const splitFileExists = (path) => stat(path).then(() => true, (err) => {if (err.code === 'ENOENT') return false;@@ -76,6 +87,12 @@ const splitReadJsonTolerant = async (path) => {const splitWriteJson = (path, value) =>writeFile(path, JSON.stringify(value, null, 2) + '\n');+// Reserved keys a legacy `map`-shape doc can carry as own properties (JSON.parse+// surfaces a literal `"__proto__"` key as an own property). They pass a typical+// `idPattern`, so a map split must drop them explicitly rather than write a+// `__proto__/index.json` record dir — left in the backup for manual recovery.+const RESERVED_MAP_KEYS = new Set(['__proto__', 'constructor', 'prototype']);+// Scan the type dir for records already split in a prior partial run. Uses// `withFileTypes` so stray non-directory entries (user `.bak` files, editor// swap files) are skipped without statting INTO them — `stat('foo.bak/index.json')`@@ -110,6 +127,9 @@ async function splitExistingRecordIds(typeDir) {* - `extraValid(record)`— extra per-record validity gate beyond id (059's name check)* - `dedupe` — claim ids as written so later duplicates skip (059); default false* - `onUnreadable` — `'return'` (default) or `'throw'`+ * - `recordsShape` — `'array'` (default; id from `record.id`) or `'map'`+ * (legacy `{ [recordsKey]: { <id>: record } }`; id is the+ * object key, tombstones preserved, reserved keys skipped)*/export function makeSplitMigration({migrationLabel,@@ -125,6 +145,7 @@ export function makeSplitMigration({extraValid = null,dedupe = false,onUnreadable = 'return',+ recordsShape = 'array',}) {const up = async ({ rootDir }) => {const dataDir = join(rootDir, 'data');@@ -175,20 +196,34 @@ export function makeSplitMigration({return { ok: false, reason: 'unreadable' };}- const records = Array.isArray(doc[recordsKey]) ? doc[recordsKey] : [];+ // Normalize both container shapes into `[id, record]` pairs so the split+ // loop below is shape-agnostic. Array: id from `record.id` (034/035/036/059).+ // Map: id from the object KEY, value written verbatim (migration 200 — brain+ // `{ records: { <id>: record } }`, tombstones and all). Both feed the same+ // downstream object/id/idPattern validation, so a null/non-string id or a+ // non-object record is rejected there, not here.+ let pairs;+ if (recordsShape === 'map') {+ const container = doc[recordsKey];+ const map = (container && typeof container === 'object' && !Array.isArray(container)) ? container : {};+ pairs = Object.entries(map).filter(([key]) => !RESERVED_MAP_KEYS.has(key));+ } else {+ const records = Array.isArray(doc[recordsKey]) ? doc[recordsKey] : [];+ pairs = records.map((record) => [record?.id, record]);+ }const existingIds = await splitExistingRecordIds(typeDir);await mkdir(typeDir, { recursive: true });let written = 0;let skipped = 0;let invalid = 0;- for (const record of records) {+ for (const [rawId, record] of pairs) {if (!record || typeof record !== 'object') {invalid += 1;console.warn(`⚠️ ${migrationLabel}: skipping non-object ${recordNoun} record (left in backup for manual recovery)`);continue;}- const id = typeof record.id === 'string' ? record.id : null;+ const id = typeof rawId === 'string' ? rawId : null;if (!id || !idPattern.test(id)) {invalid += 1;console.warn(`⚠️ ${migrationLabel}: skipping ${recordNoun} with invalid id "${id}" (left in backup for manual recovery)`);diff --git a/server/index.js b/server/index.jsindex d51406afaa..8a9203485d 100644--- a/server/index.js+++ b/server/index.js@@ -161,7 +161,7 @@ import { initSharing } from './services/sharing/index.js';import askRoutes from './routes/ask.js';import { ensureSelf, startPolling } from './services/instances.js';import { initSyncLog } from './services/brainSyncLog.js';-import { backfillOriginInstanceId } from './services/brainStorage.js';+import { backfillOriginInstanceId, brainCollectionStores } from './services/brainStorage.js';import { initSyncOrchestrator } from './services/syncOrchestrator.js';import { initSocket } from './services/socket.js';import { errorMiddleware, setupProcessErrorHandlers, asyncHandler, ServerError } from './lib/errorHandler.js';@@ -283,7 +283,7 @@ await runMigrations({ rootDir: resolveInstallRoot(join(__dirname, '..')) }).catc// but DO NOT crash the server. PortOS is single-user (CLAUDE.md "Security// Model"); a hard exit on startup is worse than a noisy log the user can act// on. Returns per-store statuses for downstream telemetry; we discard them.-await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore, liOutcomesStore(), commissionStore()]).catch(err => {+await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore, liOutcomesStore(), commissionStore(), ...brainCollectionStores()]).catch(err => {console.error(`❌ Collection version check failed at startup: ${err?.stack ?? err}`);});diff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.jsindex d1539382db..ebfd68c511 100644--- a/server/lib/collectionStore.js+++ b/server/lib/collectionStore.js@@ -92,6 +92,14 @@ import { createFileWriteQueue, createRecordWriteQueue } from './fileWriteQueue.jconst isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);+// Reserved names that must never become a record-directory id. They pass the+// default (and any typical) `idPattern` — a legacy JSON map can carry them as+// own keys — but naming a record `__proto__`/`constructor`/`prototype` invites+// prototype-pollution confusion and a weird on-disk dir. Rejecting them in+// `isValidId` (below) makes the store the single owner of "what id may I hold,"+// so consumers don't each re-guard the triple.+const RESERVED_IDS = new Set(['__proto__', 'constructor', 'prototype']);+/*** The type-index `config` slot — cross-record state owned by the collection as* a whole. See the header doc block for the convention. All keys are optional;@@ -163,7 +171,7 @@ export function createCollectionStore({// uses readdir as the source of truth whenever the collection dir exists.const knownIds = new Set();- const isValidId = (id) => typeof id === 'string' && idPattern.test(id);+ const isValidId = (id) => typeof id === 'string' && idPattern.test(id) && !RESERVED_IDS.has(id);// Per-record write queue. Tail-chained per `id` so two writes against the// same record serialize while writes against different records proceed in@@ -414,6 +422,7 @@ export function createCollectionStore({dir,type,schemaVersion,+ isValidId,typeIndexPath,recordDir,recordPath,diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex b466a7e79b..980a69d696 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -2,9 +2,34 @@* Brain Storage Service** Handles file-based persistence for the Brain feature.- * - JSON for entity stores (people, projects, ideas, admin, …, journals, inbox)+ * - Per-record `collectionStore` dirs for entity stores (people, projects,+ * ideas, admin, …, journals, inbox, songs) — `data/brain/<type>/<id>/index.json`+ * - JSON for the single `meta.json` settings doc* - JSONL for append-only generated logs (digests, reviews)- * - In-memory caching with TTL for performance+ *+ * Storage layout (issue #725): each entity store is a `collectionStore` — one+ * file per record, read through to disk with no whole-store in-memory cache. A+ * write touches one record's file and per-id write queues let writes to+ * DIFFERENT records proceed in parallel (the scalability win over the old+ * monolithic `data/brain/<type>.json` + 2s-TTL cache + single global mutex).+ * Migration 200 splits the legacy monolithic files into this shape.+ *+ * The old single global write mutex is replaced by the store's per-id+ * `queueRecordWrite(id, fn)`: two writes to the SAME (type, id) serialize —+ * local create/update AND remote peer applies AND tombstone GC all queue on the+ * same per-id tail, so a peer sync landing mid-way through a local write can't+ * read a stale snapshot and drop the other write (the CLAUDE.md-sanctioned+ * "serialize two write paths that mutate the same record" case). Writes to+ * different records no longer serialize against each other. brainJournal layers+ * its own storeMutex ON TOP for the read→mutate→write of a single journal entry;+ * that only ever nests storeMutex → this per-id queue (one direction), so no+ * deadlock.+ *+ * FEDERATION is unaffected by the layout. Brain federates strictly per-record+ * through this module's API seams (`getRawRecords` / `applyRemoteRecord`) plus+ * the `brainSyncLog` delta log — never by shipping a whole-store file — so the+ * on-disk container shape is orthogonal to the wire format (no `schemaVersions.js`+ * gate; brain is intentionally ungated there).*/import { readFile, appendFile } from 'fs/promises';@@ -13,51 +38,67 @@ import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import EventEmitter from 'events';import { atomicWrite, ensureDir, readJSONFile, safeJSONParse, safeDate, PATHS } from '../lib/fileUtils.js';-import { createMutex } from '../lib/asyncMutex.js';import { getInstanceId } from './instances.js';import * as brainSyncLog from './brainSyncLog.js';--// ONE mutex serializes EVERY write to a brain entity store — local mutations-// (create/update/remove/upsertWithId/updateMany) AND remote peer applies-// (applyRemoteRecord) AND tombstone GC. They all do whole-file read-modify-write-// on the same data/brain/<type>.json, so a peer sync landing mid-way through a-// local journal append / inbox capture (or vice-versa) would otherwise read a-// stale snapshot and drop the other write. This is the CLAUDE.md-sanctioned-// "serialize two write paths that mutate the same record" case (sync orchestrator-// vs request handler are two in-process writers, not competing humans) — NOT a-// concurrency defense against multiple users. brainJournal layers its own-// storeMutex ON TOP for the read→mutate→write of a single journal entry; that-// only ever nests storeMutex → this lock (one direction), so no deadlock.-const withStoreWriteLock = createMutex();+import { createCollectionStore } from '../lib/collectionStore.js';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 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.)+// The entity stores that participate in peer sync (records with IDs).+// Canonical list — sync, tombstone GC, origin backfill, and the per-type+// collectionStore construction below all derive from it so adding a type can't+// silently drop out of one of those paths. (Boot-time migrations keep their own+// frozen copy by necessity — migrations run before the service layer is wired+// up — see scripts/migrations/080-*.js and 200-*.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.+// `journals` (the Daily Log) and `inbox` were added in migration 081; both are+// `{ 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', 'songs',]);-// A tombstone is a deleted-record marker kept IN PLACE in `data.records[id]`-// (rather than removing the key) so the last-writer-wins guard in-// applyRemoteRecord can reject a stale `create` echoed back from a peer.-// Without it, a hard delete leaves `existing === undefined`, the LWW guard is-// skipped, and the record resurrects — then the newer delete re-kills it, and-// both ops relay to every peer forever (the federated brain-sync loop).-// Shape: { _deleted: true, updatedAt, originInstanceId, deletedAt }. The-// `updatedAt` is the LWW clock; `deletedAt` is the GC clock.+// The type-level storage-layout version. Bumped by a migration that changes the+// on-disk layout; distinct from any per-record field-shape version (brain+// records carry none). Migration 200 stamps this on every brain type index.+export const BRAIN_STORE_SCHEMA_VERSION = 1;++// One collectionStore per entity type, rooted at data/brain/<type>/. No+// `sanitizeRecord` — brain records (and their in-place tombstones) are stored+// and loaded verbatim, exactly as the old monolithic map did.+const brainStores = Object.freeze(Object.fromEntries(+ BRAIN_ENTITY_TYPES.map((type) => [type, createCollectionStore({+ dir: join(DATA_DIR, type),+ type,+ schemaVersion: BRAIN_STORE_SCHEMA_VERSION,+ })]),+));++function storeFor(type) {+ const store = brainStores[type];+ if (!store) throw new Error(`brainStorage: unknown entity type "${type}"`);+ return store;+}++/**+ * The per-type collectionStores, for the boot-time schema-version verifier in+ * server/index.js (`verifyCollectionVersions`).+ */+export function brainCollectionStores() {+ return BRAIN_ENTITY_TYPES.map((type) => brainStores[type]);+}++// A tombstone is a deleted-record marker kept IN PLACE as the record's stored+// value (its `{id}/index.json`) — rather than removing the record dir — so the+// last-writer-wins guard in applyRemoteRecord can reject a stale `create`+// echoed back from a peer. Without it, a hard delete leaves `existing ===+// undefined`, the LWW guard is skipped, and the record resurrects — then the+// newer delete re-kills it, and both ops relay to every peer forever (the+// federated brain-sync loop). Shape:+// { _deleted: true, updatedAt, originInstanceId, deletedAt }. The `updatedAt`+// is the LWW clock; `deletedAt` is the GC clock.const isTombstone = (rec) => !!(rec && rec._deleted);// Build the in-place tombstone marker. `updatedAt` is the LWW clock (must be the@@ -76,48 +117,23 @@ const makeTombstone = (updatedAt, originInstanceId) => ({// would re-create). 30 days matches the sharing-side tombstone grace buffer.export const BRAIN_TOMBSTONE_GRACE_MS = 30 * 24 * 60 * 60 * 1000;-// File paths+// Non-collection files: the single settings doc and the append-only JSONL logs.const FILES = {meta: join(DATA_DIR, 'meta.json'),- people: join(DATA_DIR, 'people.json'),- projects: join(DATA_DIR, 'projects.json'),- ideas: join(DATA_DIR, 'ideas.json'),- admin: join(DATA_DIR, 'admin.json'),- 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'),- // SongBook repertoire records (guitar tabs / chord sheets / sheet music).- // Attachment BYTES live machine-local under data/brain/songbook/ (see- // routes/brainSongbook.js); only the metadata rides in the synced record.- songs: join(DATA_DIR, 'songs.json'),digests: join(DATA_DIR, 'digests.jsonl'),- reviews: join(DATA_DIR, 'reviews.jsonl')+ reviews: join(DATA_DIR, 'reviews.jsonl'),};// Event emitter for brain data changesexport const brainEvents = new EventEmitter();-// In-memory caches+// In-memory caches — only for the non-collection files. Entity stores read+// through to disk (per issue #725: no whole-store cache to go stale when a+// per-record write bypasses it).const caches = {meta: { data: null, timestamp: 0 },- people: { data: null, timestamp: 0 },- projects: { data: null, timestamp: 0 },- ideas: { data: null, timestamp: 0 },- admin: { data: null, timestamp: 0 },- memories: { data: null, timestamp: 0 },- links: { data: null, timestamp: 0 },- buckets: { data: null, timestamp: 0 },- journals: { data: null, timestamp: 0 },- inbox: { data: null, timestamp: 0 },- songs: { data: null, timestamp: 0 },digests: { data: null, timestamp: 0 },- reviews: { data: null, timestamp: 0 }+ reviews: { data: null, timestamp: 0 },};const CACHE_TTL_MS = 2000;@@ -199,45 +215,32 @@ export async function updateMeta(updates) {}// =============================================================================-// JSON ENTITY STORES (people, projects, ideas, admin)+// ENTITY STORES (per-record collectionStore, read-through)// =============================================================================/**- * Load a JSON entity store- */-async function loadJsonStore(type) {- const cache = caches[type];- if (cache.data && (Date.now() - cache.timestamp) < CACHE_TTL_MS) {- return cache.data;- }-- await ensureBrainDir();- const filePath = FILES[type];-- cache.data = await readJSONFile(filePath, { records: {} });- cache.timestamp = Date.now();- return cache.data;-}--/**- * Save a JSON entity store+ * Assemble the raw `{ id: record }` map for a type from its per-record files,+ * INCLUDING tombstones. Read-through: one `loadOne` per id, in parallel. This+ * is the seam the reconcile/anti-entropy path and getAll/getRawRecords build on+ * — identical return shape to the old monolithic `loadJsonStore(type).records`.*/-async function saveJsonStore(type, data) {- await ensureBrainDir();- await atomicWrite(FILES[type], data);- caches[type].data = data;- caches[type].timestamp = Date.now();- brainEvents.emit(`${type}:changed`, data);+async function loadRawMap(type) {+ const store = storeFor(type);+ const ids = await store.listIds();+ const entries = await Promise.all(ids.map(async (id) => {+ const record = await store.loadOne(id);+ return record ? [id, record] : null;+ }));+ return Object.fromEntries(entries.filter(Boolean));}/**- * Get all records from a JSON store+ * Get all records from a store (tombstones excluded — they exist only to anchor+ * the LWW sync guard, never as user-visible records).*/export async function getAll(type) {- const data = await loadJsonStore(type);- // Tombstones (deleted markers) are excluded from all read paths — they exist- // only to anchor the LWW sync guard, never as user-visible records.- return Object.entries(data.records)+ const map = await loadRawMap(type);+ return Object.entries(map).filter(([, record]) => !isTombstone(record)).map(([id, record]) => ({ id, ...record }));}@@ -247,22 +250,20 @@ export async function getAll(type) {** Unlike `getAll` (which strips tombstones for user-facing reads), the sync* reconcile path needs tombstones too: they carry the LWW `updatedAt` clock a- * peer must see to keep a delete from resurrecting. Returns a shallow copy of- * the `{ id: record }` map — the map itself is safe to mutate, but the record- * objects are shared with the cache by reference, so callers must treat them as- * read-only (the reconcile path only serializes them, never mutates).+ * peer must see to keep a delete from resurrecting. Returns a fresh `{ id:+ * record }` map — safe to mutate the map, but the record objects are the parsed+ * on-disk values, so callers treat them as read-only (the reconcile path only+ * serializes them, never mutates).*/export async function getRawRecords(type) {- const data = await loadJsonStore(type);- return { ...data.records };+ return loadRawMap(type);}/*** Get a record by ID*/export async function getById(type, id) {- const data = await loadJsonStore(type);- const record = data.records[id];+ const record = await storeFor(type).loadOne(id);return record && !isTombstone(record) ? { id, ...record } : null;}@@ -270,55 +271,53 @@ export async function getById(type, id) {* Create a new record*/export async function create(type, recordData) {- // getInstanceId() before the lock — it's an independent read, and acquiring- // the lock first would needlessly serialize identity reads behind every write.+ const store = storeFor(type);const originInstanceId = await getInstanceId();- return withStoreWriteLock(async () => {- const data = await loadJsonStore(type);- const id = generateId();- const timestamp = now();+ const id = generateId();+ const timestamp = now();- const record = {- ...recordData,- originInstanceId,- createdAt: timestamp,- updatedAt: timestamp- };+ const record = {+ ...recordData,+ originInstanceId,+ createdAt: timestamp,+ updatedAt: timestamp+ };- data.records[id] = record;- await saveJsonStore(type, data);- brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });- await brainSyncLog.appendChange('create', type, id, record, originInstanceId)- .catch(err => console.error(`⚠️ Sync log append failed for create ${type}/${id}: ${err.message}`));+ // Fresh uuid → no read-modify-write; saveOne queues per-id internally.+ await store.saveOne(id, record);+ brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });+ await brainSyncLog.appendChange('create', type, id, record, originInstanceId)+ .catch(err => console.error(`⚠️ Sync log append failed for create ${type}/${id}: ${err.message}`));- console.log(`🧠 Created ${type} record: ${id}`);- return { id, ...record };- });+ console.log(`🧠 Created ${type} record: ${id}`);+ return { id, ...record };}/*** Update a record*/export async function update(type, id, updates) {- return withStoreWriteLock(async () => {- const data = await loadJsonStore(type);-+ const store = storeFor(type);+ // A malformed id can't name a valid per-record dir — treat as not-found+ // rather than letting the store's write-queue assertion throw on it.+ if (!store.isValidId(id)) return null;+ return store.queueRecordWrite(id, async () => {+ const existing = await store.loadOne(id);// A tombstoned record is gone — treat it as not-found rather than reviving it.- if (!data.records[id] || isTombstone(data.records[id])) {+ if (!existing || isTombstone(existing)) {return null;}const record = {- ...data.records[id],+ ...existing,...updates,// Preserve immutable fields — originInstanceId tracks the creating instance- originInstanceId: data.records[id].originInstanceId,- createdAt: data.records[id].createdAt,+ originInstanceId: existing.originInstanceId,+ createdAt: existing.createdAt,updatedAt: now()};- data.records[id] = record;- await saveJsonStore(type, data);+ await store.saveOneNow(id, record);brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });await brainSyncLog.appendChange('update', type, id, record, record.originInstanceId).catch(err => console.error(`⚠️ Sync log append failed for update ${type}/${id}: ${err.message}`));@@ -332,42 +331,42 @@ export async function update(type, id, updates) {* Locked read-modify-write update.** `update(type, id, partial)` merges a partial the CALLER computed — usually- * from a record snapshot read OUTSIDE the store write lock. When the partial+ * from a record snapshot read OUTSIDE the store write queue. When the partial* is derived from the current record (append to / filter an array field like* `attachments`), a concurrent writer landing between the snapshot read and* the update silently gets clobbered (and the clobber wins LWW federation).*- * `updateWith` closes that window: INSIDE withStoreWriteLock it re-reads the+ * `updateWith` closes that window: INSIDE the per-id write queue it re-reads the* fresh record, calls `fn({ id, ...record })` → a partial-updates object (or* null/undefined to abort without writing), then merges/persists with exactly* `update()`'s semantics — immutable originInstanceId/createdAt, fresh- * updatedAt stamp, cache write-through, `${type}:upserted` event, and a sync- * log append. Returns the updated `{ id, ...record }`, or null when the record- * is missing/tombstoned or fn aborted.+ * updatedAt stamp, `${type}:upserted` event, and a sync log append. Returns the+ * updated `{ id, ...record }`, or null when the record is missing/tombstoned or+ * fn aborted.*/export async function updateWith(type, id, fn) {- return withStoreWriteLock(async () => {- const data = await loadJsonStore(type);-+ const store = storeFor(type);+ if (!store.isValidId(id)) return null;+ return store.queueRecordWrite(id, async () => {+ const existing = await store.loadOne(id);// A tombstoned record is gone — treat it as not-found rather than reviving it.- if (!data.records[id] || isTombstone(data.records[id])) {+ if (!existing || isTombstone(existing)) {return null;}- const updates = await fn({ id, ...data.records[id] });+ const updates = await fn({ id, ...existing });if (!updates) return null;const record = {- ...data.records[id],+ ...existing,...updates,// Preserve immutable fields — originInstanceId tracks the creating instance- originInstanceId: data.records[id].originInstanceId,- createdAt: data.records[id].createdAt,+ originInstanceId: existing.originInstanceId,+ createdAt: existing.createdAt,updatedAt: now()};- data.records[id] = record;- await saveJsonStore(type, data);+ await store.saveOneNow(id, record);brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });await brainSyncLog.appendChange('update', type, id, record, record.originInstanceId).catch(err => console.error(`⚠️ Sync log append failed for update ${type}/${id}: ${err.message}`));@@ -394,12 +393,12 @@ export async function updateWith(type, id, fn) {* own richer, bridge-shaped event instead of the generic one.*/export async function upsertWithId(type, id, recordData, { emitEvent = true } = {}) {- // Resolve our instance id outside the lock (independent read); the existing- // record's origin is preferred inside the lock when one is present.+ const store = storeFor(type);+ // Resolve our instance id outside the queue (independent read); the existing+ // record's origin is preferred inside the queue when one is present.const fallbackOrigin = await getInstanceId();- return withStoreWriteLock(async () => {- const data = await loadJsonStore(type);- const existing = data.records[id];+ return store.queueRecordWrite(id, async () => {+ const existing = await store.loadOne(id);const live = existing && !isTombstone(existing) ? existing : null;const timestamp = now();const originInstanceId = live?.originInstanceId ?? fallbackOrigin;@@ -411,8 +410,7 @@ export async function upsertWithId(type, id, recordData, { emitEvent = true } =updatedAt: timestamp};- data.records[id] = record;- await saveJsonStore(type, data);+ await store.saveOneNow(id, record);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}`));@@ -423,24 +421,25 @@ export async function upsertWithId(type, id, recordData, { emitEvent = true } =}/**- * Apply many record updates to one store in a single load-modify-save.+ * Apply many record updates to one store.*- * A batch like a chip reorder must NOT fan out into N concurrent single-record- * `update()` calls: `update()` is a read-modify-save over the whole shared JSON- * file, so concurrent calls on a cold cache read overlapping baselines and the- * last save wins — silently dropping the other records' changes. Collapsing the- * batch into one load-modify-save (one file write) makes the whole reorder- * atomic. `updates` is an array of { id, ...fields }; unknown ids are skipped.- * Returns the updated records.+ * With the old monolithic file, a batch (e.g. a chip reorder) had to be one+ * atomic load-modify-save or N concurrent single-record `update()` calls would+ * read overlapping baselines of the shared file and last-save-wins. Per-record+ * files remove that race entirely — writes to different ids no longer share a+ * file — so this now serializes each record on its own per-id queue and merges+ * against the freshest persisted record. `updates` is an array of { id,+ * ...fields }; unknown/tombstoned ids are skipped. Returns the updated records.*/export async function updateMany(type, updates) {- return withStoreWriteLock(async () => {- const data = await loadJsonStore(type);- const applied = [];- for (const { id, ...fields } of updates) {- const existing = data.records[id];- if (!existing || isTombstone(existing)) continue;- const record = {+ const store = storeFor(type);+ const applied = [];+ for (const { id, ...fields } of updates) {+ if (!store.isValidId(id)) continue;+ const record = await store.queueRecordWrite(id, async () => {+ const existing = await store.loadOne(id);+ if (!existing || isTombstone(existing)) return null;+ const next = {...existing,...fields,// Preserve immutable fields, exactly as update() does.@@ -448,30 +447,30 @@ export async function updateMany(type, updates) {createdAt: existing.createdAt,updatedAt: now()};- data.records[id] = record;- applied.push({ id, record });- }- if (applied.length === 0) return [];+ await store.saveOneNow(id, next);+ return next;+ });+ if (record) applied.push({ id, record });+ }+ if (applied.length === 0) return [];- await saveJsonStore(type, data);- for (const { id, record } of applied) {- brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });- await brainSyncLog.appendChange('update', type, id, record, record.originInstanceId)- .catch(err => console.error(`⚠️ Sync log append failed for update ${type}/${id}: ${err.message}`));- }- console.log(`🧠 Updated ${applied.length} ${type} records in one batch`);- return applied.map(({ id, record }) => ({ id, ...record }));- });+ for (const { id, record } of applied) {+ brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });+ await brainSyncLog.appendChange('update', type, id, record, record.originInstanceId)+ .catch(err => console.error(`⚠️ Sync log append failed for update ${type}/${id}: ${err.message}`));+ }+ console.log(`🧠 Updated ${applied.length} ${type} records in one batch`);+ return applied.map(({ id, record }) => ({ id, ...record }));}/*** Delete a record*/export async function remove(type, id) {- return withStoreWriteLock(async () => {- const data = await loadJsonStore(type);-- const existing = data.records[id];+ const store = storeFor(type);+ if (!store.isValidId(id)) return false;+ return store.queueRecordWrite(id, async () => {+ const existing = await store.loadOne(id);// Already gone (absent) or already tombstoned — nothing to delete, and// re-tombstoning would mint a redundant sync-log entry that relays needlessly.if (!existing || isTombstone(existing)) {@@ -481,10 +480,10 @@ export async function remove(type, id) {const originInstanceId = existing.originInstanceId ?? 'unknown';const deletedRecord = { id, ...existing };const ts = now();- // Retain a tombstone in place (not a hard delete) so a stale `create` echoed- // from a peer is rejected by the LWW guard in applyRemoteRecord.- data.records[id] = makeTombstone(ts, originInstanceId);- await saveJsonStore(type, data);+ // Retain a tombstone in place (save it as the record's value, not a hard+ // delete of the record dir) so a stale `create` echoed from a peer is+ // rejected by the LWW guard in applyRemoteRecord.+ await store.saveOneNow(id, makeTombstone(ts, originInstanceId));brainEvents.emit(`${type}:deleted`, { id, record: deletedRecord });// Wire format unchanged: the sync-log delete entry still carries only// { updatedAt } so an older peer (no tombstone support) applies it as a@@ -559,7 +558,7 @@ async function appendJsonl(type, record) {// INBOX LOG OPERATIONS// =============================================================================-// The inbox is now an id-keyed entity store (see BRAIN_ENTITY_TYPES) so it+// The inbox is 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.@@ -587,10 +586,10 @@ export async function getInboxLogById(id) {return getById('inbox', id);}-// The inbox's concurrent same-file write paths (a capture's create immediately+// The inbox's concurrent same-record write paths (a capture's create immediately// followed by a background-classification update on the same entry, plus the-// boot recovery sweep) are serialized by create/update/remove's own-// withStoreWriteLock — no separate inbox lock is needed.+// boot recovery sweep) are serialized by create/update/remove's own per-id write+// queue — no separate inbox lock is needed./*** Create inbox log entry. `capturedAt` is the user-facing capture time (kept@@ -796,8 +795,8 @@ export const getLinks = (filters) => filters ? query('links', filters) : getAll(export const getLinkById = (id) => getById('links', id);export const createLink = (data) => create('links', data);export const updateLink = (id, data) => update('links', id, data);-// Batch reorder: one atomic load-modify-save so a multi-chip drag can't-// lose-update the shared links store the way N concurrent updateLink calls can.+// Batch reorder: per-id write queues so a multi-chip drag merges each link+// against its freshest persisted record.export const reorderLinks = (updates) => updateMany('links', updates);export const deleteLink = (id) => remove('links', id);@@ -821,26 +820,27 @@ export const deleteBucket = (id) => remove('buckets', id);// =============================================================================/**- * Apply a remote record to a JSON store (last-writer-wins by updatedAt)+ * Apply a remote record to a store (last-writer-wins by updatedAt)*/export async function applyRemoteRecord(type, id, record, op) {- // Reject prototype-polluting ids before they reach `data.records[id]`. JSON- // serialization drops a `__proto__` key so there's no live data corruption,- // but accepting it would return `applied:true` and append a phantom relay- // entry that can never converge (the reconcile snapshot path guards this too;- // centralizing it here covers BOTH the delta-sync and snapshot callers).- if (id === '__proto__' || id === 'constructor' || id === 'prototype') {+ const store = storeFor(type);+ // Reject a malformed id (can't name a valid per-record dir) or a+ // prototype-polluting name — the store's `isValidId` owns both the format+ // allowlist AND the reserved-key denylist (`__proto__`/`constructor`/+ // `prototype`), so a bad id returns `invalid_id` here instead of throwing on+ // the write-queue assertion or appending a phantom relay entry that can never+ // converge (this covers BOTH the delta-sync and reconcile-snapshot callers).+ if (!store.isValidId(id)) {return { applied: false, reason: 'invalid_id' };}- return withStoreWriteLock(async () => {- const data = await loadJsonStore(type);+ return store.queueRecordWrite(id, async () => {+ const existing = await store.loadOne(id);if (op === 'delete') {// Require updatedAt on delete operations for last-writer-wins conflict resolutionif (!record?.updatedAt) {return { applied: false, reason: 'missing_timestamp' };}- const existing = data.records[id];// LWW: skip if our copy (live record OR existing tombstone) is at least as// new as the incoming delete. The tombstone-vs-tombstone case makes a// repeated delete idempotent → not relayed → the echo loop converges.@@ -850,10 +850,10 @@ export async function applyRemoteRecord(type, id, record, op) {// Tombstone in place even when no local record exists. A delete that// arrives before we ever saw a create still leaves a marker, so a later// stale create for that id is rejected instead of resurrecting.- data.records[id] = makeTombstone(+ await store.saveOneNow(id, makeTombstone(record.updatedAt,record.originInstanceId ?? existing?.originInstanceId- );+ ));} else {// A create/update with no updatedAt has no LWW clock — `existing.updatedAt// >= undefined` is always false, which would let it silently overwrite a@@ -862,9 +862,8 @@ export async function applyRemoteRecord(type, id, record, op) {if (!record?.updatedAt) {return { applied: false, reason: 'missing_timestamp' };}- const existing = data.records[id];- // Guard now also fires when `existing` is a tombstone — a stale create- // (older updatedAt than the recorded delete) is rejected, breaking the+ // Guard also fires when `existing` is a tombstone — a stale create (older+ // updatedAt than the recorded delete) is rejected, breaking the// resurrection loop. A genuinely newer create (later updatedAt than the// tombstone) still wins and legitimately revives the record.if (existing && existing.updatedAt >= record.updatedAt) {@@ -873,16 +872,11 @@ export async function applyRemoteRecord(type, id, record, op) {// Defense-in-depth: a create carrying `_deleted` (a future peer, or a// direct caller bypassing brainSync's reroute) must persist as a proper// tombstone, never as a malformed live record missing `deletedAt`.- data.records[id] = record._deleted+ await store.saveOneNow(id, record._deleted? makeTombstone(record.updatedAt, record.originInstanceId ?? existing?.originInstanceId)- : { ...record };+ : { ...record });}- await ensureBrainDir();- await atomicWrite(FILES[type], data);- caches[type].data = data;- caches[type].timestamp = Date.now();-return { applied: true };});}@@ -890,29 +884,27 @@ export async function applyRemoteRecord(type, id, record, op) {/*** Hard-prune tombstones older than `cutoffMs` (a Date.now()-style epoch ms).* Called by the brain tombstone GC sweep on the orchestrator's interval.- * Load-modify-save per store; writes only when something was pruned.- * Returns the number of tombstones removed.+ * Per-id re-check inside the write queue so a tombstone a concurrent apply just+ * refreshed isn't pruned on a stale read. Returns the number of tombstones+ * removed.*/export async function pruneTombstones(type, cutoffMs) {- return withStoreWriteLock(async () => {- const data = await loadJsonStore(type);- let pruned = 0;- for (const [id, record] of Object.entries(data.records)) {- if (!isTombstone(record)) continue;- const deletedAt = Date.parse(record.deletedAt ?? record.updatedAt ?? '');- if (Number.isFinite(deletedAt) && deletedAt < cutoffMs) {- delete data.records[id];- pruned++;- }- }- if (pruned > 0) {- await ensureBrainDir();- await atomicWrite(FILES[type], data);- caches[type].data = data;- caches[type].timestamp = Date.now();+ const store = storeFor(type);+ const ids = await store.listIds();+ // Different ids are independent files — prune them in parallel (each still+ // serialized on its own per-id queue so the stale-read recheck holds). The+ // count is order-independent.+ const results = await Promise.all(ids.map((id) => store.queueRecordWrite(id, async () => {+ const record = await store.loadOne(id);+ if (!isTombstone(record)) return false;+ const deletedAt = Date.parse(record.deletedAt ?? record.updatedAt ?? '');+ if (Number.isFinite(deletedAt) && deletedAt < cutoffMs) {+ await store.deleteOneNow(id);+ return true;}- return pruned;- });+ return false;+ })));+ return results.filter(Boolean).length;}/**@@ -920,30 +912,24 @@ export async function pruneTombstones(type, cutoffMs) {*/export async function backfillOriginInstanceId() {const instanceId = await getInstanceId();- let totalBackfilled = 0;-- for (const type of BRAIN_ENTITY_TYPES) {- const data = await loadJsonStore(type);- let changed = false;-- for (const [, record] of Object.entries(data.records)) {- // Tombstones always carry originInstanceId; skip them.- if (isTombstone(record)) continue;- if (!record.originInstanceId) {- record.originInstanceId = instanceId;- changed = true;- totalBackfilled++;- }- }-- if (changed) {- await ensureBrainDir();- await atomicWrite(FILES[type], data);- caches[type].data = data;- caches[type].timestamp = Date.now();- }- }+ // Every record across all types is an independent file — backfill them in+ // parallel (per-id writes still serialize on their own queue). This runs at+ // startup and gates sync start, so the parallelism directly shortens boot.+ const perType = await Promise.all(BRAIN_ENTITY_TYPES.map(async (type) => {+ const store = storeFor(type);+ const ids = await store.listIds();+ const changes = await Promise.all(ids.map((id) => store.queueRecordWrite(id, async () => {+ const record = await store.loadOne(id);+ // Tombstones always carry originInstanceId; skip them and absent records.+ if (!record || isTombstone(record) || record.originInstanceId) return false;+ await store.saveOneNow(id, { ...record, originInstanceId: instanceId });+ return true;+ })));+ return changes.filter(Boolean).length;+ }));++ const totalBackfilled = perType.reduce((sum, n) => sum + n, 0);if (totalBackfilled > 0) {console.log(`🧠 Backfilled originInstanceId on ${totalBackfilled} records`);}@@ -954,7 +940,8 @@ export async function backfillOriginInstanceId() {// =============================================================================/**- * Invalidate all caches+ * Invalidate the non-collection caches (meta + JSONL logs). Entity stores read+ * through to disk, so there is no entity cache to clear.*/export function invalidateAllCaches() {for (const key of Object.keys(caches)) {diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsindex 46e2d43624..67e87015e6 100644--- a/server/services/brainStorage.test.js+++ b/server/services/brainStorage.test.js@@ -322,10 +322,10 @@ describe('songs entity enrollment (SongBook)', () => {});});-// Read the raw stored record (including tombstones) by bypassing the read filter.+// Read the raw stored record (including tombstones) by bypassing the read+// filter. getRawRecords returns the per-record map with tombstones, so this is+// layout-agnostic (works against the collectionStore per-record files).async function rawRecord(type, id) {- const { readFile } = await import('fs/promises');- const file = join(getTempRoot(), 'brain', `${type}.json`);- const data = JSON.parse(await readFile(file, 'utf-8'));- return data.records[id];+ const map = await brainStorage.getRawRecords(type);+ return map[id];}