Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): harden brain split against partial/corrupt state

[._.]/ Adam Eivyab680ebb6eb1
diff --git a/scripts/migrations/200-split-brain-stores-to-per-record.js b/scripts/migrations/200-split-brain-stores-to-per-record.js
index 55cda0d897..08ccdccb0d 100644
--- a/scripts/migrations/200-split-brain-stores-to-per-record.js
+++ b/scripts/migrations/200-split-brain-stores-to-per-record.js
@@ -95,12 +95,29 @@ const perTypeSplits = BRAIN_ENTITY_TYPES.map((type) => makeSplitMigration({
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));
+ const failures = [];
+ // Sequential (not Promise.all) so the per-type log lines stay ordered. Each
+ // type's store is INDEPENDENT — a corrupt/unreadable legacy file for one type
+ // must NOT abort the splits for the others. brainStorage reads only the
+ // per-record dirs, so an un-split later type would load as empty even though
+ // its legacy file is intact on disk; aborting mid-loop on the first bad file
+ // would therefore hide every alphabetically-later store until manual repair.
+ // So run every type, collect per-type outcomes, and only THEN re-throw an
+ // aggregate — which keeps the migration PENDING (unapplied) for a retry while
+ // the healthy types that already split become gate-1 no-ops next boot.
+ for (let i = 0; i < perTypeSplits.length; i++) {
+ try {
+ perType.push(await perTypeSplits[i](ctx));
+ } catch (err) {
+ failures.push(BRAIN_ENTITY_TYPES[i]);
+ console.error(`❌ migration 200 (brain/${BRAIN_ENTITY_TYPES[i]}): ${err.message}`);
+ }
+ }
+ if (failures.length > 0) {
+ throw new Error(
+ `migration 200: ${failures.length} brain store(s) failed to split (${failures.join(', ')}) — ` +
+ `repair the unreadable legacy file(s) and reboot to retry; the healthy stores were split.`,
+ );
}
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.js
index 1ab219f638..ca50a9444c 100644
--- a/scripts/migrations/200-split-brain-stores-to-per-record.test.js
+++ b/scripts/migrations/200-split-brain-stores-to-per-record.test.js
@@ -154,6 +154,31 @@ describe('migration 200 — split brain stores to per-record', () => {
expect(existsSync(backupPath('people'))).toBe(false);
});
+ it('splits healthy stores even when an earlier type is unreadable, then throws an aggregate', async () => {
+ // `people` is first in the type order and unparseable; `admin` is later and valid.
+ writeFileSync(legacyPath('people'), 'not json{');
+ writeJson(legacyPath('admin'), { records: { 'a1': rec({ name: 'ok' }) } });
+
+ await expect(migration.up({ rootDir })).rejects.toThrow(/failed to split.*people/);
+
+ // The later healthy store was still split despite the earlier failure.
+ expect(readJson(recordPath('admin', 'a1')).name).toBe('ok');
+ // The failed store is left intact for repair (not split, not renamed).
+ expect(existsSync(legacyPath('people'))).toBe(true);
+ expect(existsSync(typeIndexPath('people'))).toBe(false);
+ });
+
+ it('treats a malformed records container as unreadable (throws, stays pending, keeps legacy)', async () => {
+ // Valid JSON, but `records` is an array rather than an object map — corruption.
+ writeJson(legacyPath('ideas'), { records: [1, 2, 3] });
+
+ await expect(migration.up({ rootDir })).rejects.toThrow(/failed to split.*ideas/);
+
+ // Legacy left intact, index not stamped — so the migration re-runs next boot.
+ expect(existsSync(legacyPath('ideas'))).toBe(true);
+ expect(existsSync(typeIndexPath('ideas'))).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' }) } });
diff --git a/scripts/migrations/_lib.js b/scripts/migrations/_lib.js
index aecdaf085e..5f5e35064e 100644
--- a/scripts/migrations/_lib.js
+++ b/scripts/migrations/_lib.js
@@ -84,8 +84,17 @@ const splitReadJsonTolerant = async (path) => {
try { return JSON.parse(raw); } catch { return { __unreadable: true }; }
};
-const splitWriteJson = (path, value) =>
- writeFile(path, JSON.stringify(value, null, 2) + '\n');
+// Atomic write (temp + rename) so a crash mid-write can't leave a truncated
+// `<id>/index.json`. Without it, a retry's `splitExistingRecordIds` scan would
+// see the partial file, trust it as already-split, skip re-splitting from the
+// authoritative legacy value, then stamp + rename the legacy store — and the
+// truncated record would forever load as null. rename() is atomic within one
+// filesystem, and tmp sits in the same dir as its target, so the swap is safe.
+const splitWriteJson = async (path, value) => {
+ const tmp = `${path}.tmp-${process.pid}`;
+ await writeFile(tmp, JSON.stringify(value, null, 2) + '\n');
+ await rename(tmp, path);
+};
// 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
@@ -205,8 +214,20 @@ export function makeSplitMigration({
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));
+ // Distinguish "records key absent" (a legitimately empty store → 0 records)
+ // from "records present but NOT an object map" (corruption). Silently
+ // emptying the latter would stamp v1, rename the legacy file to backup, and
+ // mark the migration applied while the real data sits stranded and unread in
+ // the backup — so honor `onUnreadable` for a malformed container exactly as
+ // for unparseable JSON.
+ if (container != null && !(typeof container === 'object' && !Array.isArray(container))) {
+ if (onUnreadable === 'throw') {
+ throw new Error(`${migrationLabel}: ${sourcePath} has a malformed "${recordsKey}" container (expected an object map) — repair or remove it, then reboot to retry the split`);
+ }
+ console.warn(`⚠️ ${migrationLabel}: ${sourcePath} has a malformed "${recordsKey}" container — skipping. Resolve manually before next boot.`);
+ return { ok: false, reason: 'unreadable' };
+ }
+ pairs = Object.entries(container ?? {}).filter(([key]) => !RESERVED_MAP_KEYS.has(key));
} else {
const records = Array.isArray(doc[recordsKey]) ? doc[recordsKey] : [];
pairs = records.map((record) => [record?.id, record]);
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 980a69d696..2fc8ceb0da 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -450,15 +450,18 @@ export async function updateMany(type, updates) {
await store.saveOneNow(id, next);
return next;
});
- if (record) applied.push({ id, record });
- }
- if (applied.length === 0) return [];
-
- for (const { id, record } of applied) {
+ if (!record) continue;
+ // Emit + append the sync-log entry as EACH record lands, not once after the
+ // whole batch. Per-record files mean there is no all-or-nothing batch to
+ // preserve, so if a later id's write throws, the records already persisted
+ // must still have federated — a batch-tail loop would skip them entirely and
+ // leave earlier successes local-only.
+ applied.push({ 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}`));
}
+ if (applied.length === 0) return [];
console.log(`🧠 Updated ${applied.length} ${type} records in one batch`);
return applied.map(({ id, record }) => ({ id, ...record }));
}