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
fix(brain): stop fan-out of memory updates and embeddings on single brain writes
Adam Eivy25ad9ded7d03
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6388a04d6b..50d0731997 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -36,6 +36,7 @@## Fixed+- **Brain → memory bridge no longer fans out across every record on a single write.** Adding one inbox item used to trigger ~12 memory updates and 12+ embedding rebuilds for unrelated projects (visible as a block of `🧠🔗 Updated brain→memory` lines after a single classification). Root cause: `saveJsonStore` emits `${type}:changed` with the whole `{ records }` blob on every write, and `brainMemoryBridge.handleEntityChanged` iterated every record on each event. The journals path was already migrated to per-entry events for exactly this reason; the sibling entity types (people, projects, ideas, admin, memories) were never updated. `server/services/brainStorage.js` now also emits per-record `${type}:upserted` (with `{ id, record }`) on `create`/`update` and `${type}:deleted` on `remove`; `server/services/brainMemoryBridge.js` listens to those instead of `:changed`, so a single classify-and-file now produces a single memory write + embedding. The store-wide `:changed` event still fires for any UI listeners that genuinely want the full set.- **Writers Room — "Add folder" form no longer clips its Cancel button.** The new-folder inline form previously laid out as `[input flex-1] [Add] [Cancel]` inside the 260px library aside, which left no room for the Cancel button — it overflowed off the right edge and was clipped by the panel's overflow boundary. Restructured to stack: the input takes the full width, then `[Add (flex-1)] [Cancel]` sits on a second row inside a `bg-port-card` boxed group matching the new-work form's existing layout.- **FLUX.2 stepwise previews now actually render.** The callback's `vae.decode(latents)` was silently failing every step with `IndexError: tuple index out of range` because `Flux2KleinPipeline` hands the callback latents in transformer-packed shape `(B, num_patches, C·P²)` (e.g. `(1, 2304, 128)` for 1024×576) but the VAE expects unpacked `(B, C, H, W)`. New `_unpack_flux2_latents()` does the patch unpack (2×2 patches × 8× VAE downsample) before the decode call. `make_stepwise_callback()` now takes `height`/`width` and short-circuits the unpack if a future pipeline version hands us an already-4-D tensor.- **FLUX.2 install detection now checks functional health, not just file existence.** Previously `resolveFlux2Python()` returned the venv binary path as long as the file existed — but a venv whose install was killed mid-pip leaves the python binary behind with an empty site-packages, so the status endpoint reported `venvInstalled: true`, the install banner cleared, and rendering crashed with `Exit code 1` in 100ms when `flux2_macos.py` failed to `import diffusers`. New helper `isFlux2VenvHealthy()` (cached) probes `from diffusers import Flux2KleinPipeline` once. `/setup/flux2-status` and `/setup/flux2-install`'s early-return both use it, so a half-broken venv now reports as not-installed and the user can retry the install from the UI without manual cleanup.diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.jsindex fcf6d26551..3afabdd462 100644--- a/server/services/brainMemoryBridge.js+++ b/server/services/brainMemoryBridge.js@@ -301,28 +301,39 @@ export async function syncAllBrainData({ dryRun = false } = {}) {}// ─── Event Handlers ─────────────────────────────────────────────────────────-// Entity stores emit "{type}:changed" with the full store data object { records: { id: {...} } }-// JSONL stores emit "{type}:added" with a single record--async function handleEntityChanged(brainType, storeData) {- if (!storeData?.records) return;- const map = await loadBridgeMap();- for (const [id, record] of Object.entries(storeData.records)) {- if (record.archived) {- // Archive the mapped CoS memory if one exists- const key = bridgeKey(brainType, id);- const memoryId = map[key];- if (memoryId) {- memory.updateMemory(memoryId, { status: 'archived' }).catch(err => {- console.error(`❌ Brain bridge archive failed for ${brainType}/${id}: ${err.message}`);- });- }- continue;+// Entity stores emit "{type}:upserted" / "{type}:deleted" with the single+// affected record. (An earlier version listened to the store-wide+// "{type}:changed" event and re-synced every record on each write — which+// triggered O(N) memory updates and embedding rebuilds for every brain item+// added. The journals path was fixed first; this is the same fix for the+// JSON entity stores.)+// JSONL stores still emit "{type}:added" with a single record.++async function handleEntityUpserted(brainType, { id, record }) {+ if (!id || !record) return;+ if (record.archived) {+ const map = await loadBridgeMap();+ const memoryId = map[bridgeKey(brainType, id)];+ if (memoryId) {+ memory.updateMemory(memoryId, { status: 'archived' }).catch(err => {+ console.error(`❌ Brain bridge archive failed for ${brainType}/${id}: ${err.message}`);+ });}- syncBrainRecord(brainType, { id, ...record }).catch(err => {- console.error(`❌ Brain bridge sync failed for ${brainType}/${id}: ${err.message}`);- });+ return;}+ syncBrainRecord(brainType, record).catch(err => {+ console.error(`❌ Brain bridge sync failed for ${brainType}/${id}: ${err.message}`);+ });+}++async function handleEntityDeleted(brainType, { id }) {+ if (!id) return;+ const map = await loadBridgeMap();+ const memoryId = map[bridgeKey(brainType, id)];+ if (!memoryId) return;+ memory.updateMemory(memoryId, { status: 'archived' }).catch(err => {+ console.error(`❌ Brain bridge delete-archive failed for ${brainType}/${id}: ${err.message}`);+ });}function handleJsonlAdded(brainType, record) {@@ -340,9 +351,11 @@ function handleJsonlAdded(brainType, record) {* are automatically mirrored to the CoS memory system.*/export function initBridge() {- // Entity store changes+ // Entity store changes — listen to per-record events so a single create/update+ // doesn't fan out to re-sync every existing record (and rebuild every embedding).for (const type of ['people', 'projects', 'ideas', 'admin', 'memories']) {- brainEvents.on(`${type}:changed`, (data) => handleEntityChanged(type, data));+ brainEvents.on(`${type}:upserted`, (payload) => handleEntityUpserted(type, payload));+ brainEvents.on(`${type}:deleted`, (payload) => handleEntityDeleted(type, payload));}// JSONL appends (digests, reviews)diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex 34d453de63..f265f948b6 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -197,6 +197,7 @@ export async function create(type, recordData) {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}`));@@ -225,6 +226,7 @@ export async function update(type, id, updates) {data.records[id] = record;await saveJsonStore(type, data);+ 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}`));@@ -243,9 +245,11 @@ export async function remove(type, id) {}const originInstanceId = data.records[id]?.originInstanceId ?? 'unknown';+ const deletedRecord = { id, ...data.records[id] };const deleteRecord = { updatedAt: now() };delete data.records[id];await saveJsonStore(type, data);+ brainEvents.emit(`${type}:deleted`, { id, record: deletedRecord });await brainSyncLog.appendChange('delete', type, id, deleteRecord, originInstanceId).catch(err => console.error(`⚠️ Sync log append failed for delete ${type}/${id}: ${err.message}`));