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
throttle bulk brain-record creates through the debounced resync queue
[._.]/ Adam Eivyef783c13b6c9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9433132300..b3006cbe48 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -56,6 +56,8 @@## Fixed+- **Bulk brain-record creates no longer fire a thundering herd of embedding calls** — The Brain→Memory bridge (which mirrors every brain record into the pgvector memory table so agents can semantically search them) handled each `{type}:upserted` event inline with a fire-and-forget `syncBrainRecord` — fine for human-paced single edits, but a **bulk producer** like the new ChatGPT import (creating ~1,400 conversations back-to-back) fired that many `:upserted` events in a tight loop, launching ~1,400 **concurrent** embedding HTTP calls + Postgres writes. That saturated the embedding backend (most calls time out and the embedding is swallowed to `null`, so the records persist **silently unsearchable**) and exhausted the PG pool. The peer-sync `sync:applied` path already solved this with a debounced (250 ms) + sequential + deduped `queueResync` drain; the direct entity events now route through that same machinery. Because `queueResync` re-reads each record's **canonical** stored state (`resyncBrainRecord`), the archived/deleted/tombstoned branches are handled uniformly and a now-stale event payload still converges correctly. (`server/services/brainMemoryBridge.js`)+- **Test runner can no longer write to the real `portos` database through a transaction (the last guard hole)** — The `query()` row-write backstop added in the previous incident fix guarded only PortOS's own pool wrapper, but **`withTransaction()` hands its callback a raw `pg` client whose `client.query()` bypasses `query()` entirely** — and nearly every store mutation (`updateAuthor`/`deleteAuthor`/`mergeAuthorsFromSync`, universe runs, catalog, writers-room, story-builder, creative-director) issues its `INSERT`/`UPDATE`/`DELETE` *inside* a transaction. So a suite running under VITEST against the real `portos` DB (a CoS-agent worktree with `NODE_ENV` unset, or any non-DB suite that reaches a transaction write path) still wrote straight into production, unguarded — the DB-backed `*.db.test.js` suites skipped correctly via `checkHealth()`, but the transaction door was wide open. Fix: the shared backstop is factored into `assertWriteAllowed()` and `withTransaction()` now wraps its client in a `Proxy` that runs every `client.query()` through it (the SQL is read from both the string and `{ text }` call forms; `BEGIN`/`COMMIT`/`ROLLBACK` and `SELECT … FOR UPDATE` pass through). Verified: a transaction `INSERT` against `portos` under VITEST now throws `Refusing to mutate` and leaves no row, while all 14 DB-backed suites (109 tests) still pass against `portos_test`. (`server/lib/db.js`, `server/lib/db.guards.test.js`)- **Test runner can no longer write fixtures into — or wipe — the real `portos` database when `NODE_ENV` isn't `test`** — A CoS agent running the server test suite in its worktree wrote test fixtures (`Test Work` writers-room works, `Issue 1`/`Old B` pipeline issues, `X`/`B` universes, `u-1`/`u-B` universe-runs, `stb-*` story-builder sessions) straight into the shared production Postgres, and the DB suites' `DELETE FROM …` cleanup **hard-deleted the user's real universes, series, and writers-room work**. Root cause: the test-runner safety gate in `server/lib/db.js` keyed only on `NODE_ENV==='test'`. The agent's wrapper left `NODE_ENV` unset/`development`, so `checkHealth()` did **not** report disconnected, the DB-backed `*.db.test.js` suites ran against the real DB instead of skipping, and the `query()` backstop only blocked `DELETE`/`TRUNCATE` — letting `INSERT`s leak while cleanup `DELETE`s threw and stranded them. Fixes: a new `isTestRunner()` detects the runner via `NODE_ENV==='test'` **or** `process.env.VITEST` (set in every vitest worker), so a misconfigured `NODE_ENV` can't disarm the gate; `checkHealth()` and the `query()` backstop both use it; and the backstop now refuses **all** row writes (`INSERT`/`UPDATE`/`DELETE`/`TRUNCATE`), not just deletions, against a non-test database under the runner. Verified: with `NODE_ENV=development`, `writersRoom/db.test.js` + `seriesStore/db.test.js` now skip against the prod DB and write nothing; the full main suite (11,251 tests) leaves the prod DB byte-identical; `npm run test:db` (99 tests on `portos_test`) still passes. (`server/lib/db.js`, `server/lib/db.guards.test.js`)diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.jsindex aeb09d9ef0..fde167cc3d 100644--- a/server/services/brainMemoryBridge.js+++ b/server/services/brainMemoryBridge.js@@ -459,40 +459,10 @@ export function queueResync(records) {// ─── Event Handlers ─────────────────────────────────────────────────────────// 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.)+// affected record. Both are routed through the debounced+sequential+// queueResync path (not handled inline) — see initBridge for why.// 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}`);- });- }- 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) {if (!record?.id) return;syncBrainRecord(brainType, record).catch(err => {@@ -508,11 +478,22 @@ function handleJsonlAdded(brainType, record) {* are automatically mirrored to the CoS memory system.*/export function initBridge() {- // 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).+ // Entity store changes — route through the debounced + sequential queueResync+ // path rather than embedding inline per event. A single create/update already+ // emits one per-record event (not a store-wide fan-out), but a BULK producer —+ // e.g. the ChatGPT import creating ~1,400 conversations back-to-back — fires+ // that many `:upserted` events in a tight loop. Handling each inline would+ // launch ~1,400 concurrent embedding calls + Postgres writes, saturating the+ // embedding backend (most time out → records persist with a NULL embedding,+ // silently unsearchable) and exhausting the PG pool. queueResync coalesces the+ // burst (250ms debounce + dedup) and drains it sequentially — the same+ // protection the peer-sync `sync:applied` path already relies on. It also+ // re-reads each record's CANONICAL state (resyncBrainRecord), so the archived/+ // deleted/tombstoned branches are handled there uniformly and an event whose+ // payload is already stale by flush time still converges correctly.for (const type of ['people', 'projects', 'ideas', 'admin', 'memories']) {- brainEvents.on(`${type}:upserted`, (payload) => handleEntityUpserted(type, payload));- brainEvents.on(`${type}:deleted`, (payload) => handleEntityDeleted(type, payload));+ brainEvents.on(`${type}:upserted`, ({ id }) => queueResync([{ type, id }]));+ brainEvents.on(`${type}:deleted`, ({ id }) => queueResync([{ type, id }]));}// JSONL appends (digests, reviews)diff --git a/server/services/brainMemoryBridge.test.js b/server/services/brainMemoryBridge.test.jsindex 6f4269a7f9..77355287c9 100644--- a/server/services/brainMemoryBridge.test.js+++ b/server/services/brainMemoryBridge.test.js@@ -207,6 +207,60 @@ describe('brainMemoryBridge — queueResync debounce + dedup', () => {});});+describe('brainMemoryBridge — entity :upserted/:deleted route through queueResync (bulk-create throttle)', () => {+ it('does NOT embed synchronously on a single :upserted — it enqueues for the debounced flush', async () => {+ const bridge = await loadBridge();+ const { brainEvents } = await import('./brainStorage.js');+ bridge.initBridge();+ getById.mockResolvedValue({ id: 'm1', title: 'note', content: 'hi' });++ brainEvents.emit('memories:upserted', { id: 'm1', record: { id: 'm1', title: 'note' } });+ // Before the flush nothing has been embedded — the burst is only queued.+ expect(getById).not.toHaveBeenCalled();+ expect(createMemory).not.toHaveBeenCalled();++ await bridge.flushPendingResync();+ // After the flush it re-reads canonical state and embeds exactly once.+ expect(getById).toHaveBeenCalledWith('memories', 'm1');+ expect(createMemory).toHaveBeenCalledTimes(1);+ });++ it('coalesces a tight burst of N :upserted events into N sequential resyncs (one per distinct id)', async () => {+ const bridge = await loadBridge();+ const { brainEvents } = await import('./brainStorage.js');+ bridge.initBridge();+ getById.mockImplementation(async (_type, id) => ({ id, title: id, content: id }));++ // Simulate the ChatGPT import creating many conversations back-to-back.+ for (let i = 0; i < 50; i++) {+ brainEvents.emit('memories:upserted', { id: `c${i}`, record: { id: `c${i}` } });+ }+ // A repeat touch of an already-queued id collapses (dedup).+ brainEvents.emit('memories:upserted', { id: 'c0', record: { id: 'c0' } });++ await bridge.flushPendingResync();++ // 50 distinct ids → 50 reads, NOT 51 — and they ran through the sequential+ // queue, not 51 concurrent fire-and-forget embeds.+ expect(getById).toHaveBeenCalledTimes(50);+ expect(createMemory).toHaveBeenCalledTimes(50);+ });++ it('routes :deleted through the resync path, archiving the mapped memory', async () => {+ const bridge = await loadBridge();+ const { brainEvents } = await import('./brainStorage.js');+ bridge.initBridge();+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('people', 'p9')]: 'mem-del' });+ getById.mockResolvedValue(null); // deleted/tombstoned → getById returns null++ brainEvents.emit('people:deleted', { id: 'p9' });+ await bridge.flushPendingResync();++ expect(updateMemory).toHaveBeenCalledWith('mem-del', { status: 'archived' });+ expect(createMemory).not.toHaveBeenCalled();+ });+});+describe('brainMemoryBridge — syncAllBrainData refresh mode (issue #1080 recovery)', () => {it('skips already-mapped records by default but re-embeds them with refresh:true', async () => {const bridge = await loadBridge();