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: guard withTransaction client writes against the real portos DB under the test runner
[._.]/ Adam Eivy7064233392a7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex be2b9603d9..5a025bc4eb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,7 +6,9 @@- **Generate an author headshot from the persona's description + style** — The Authors editor's headshot field gains a **Generate** button alongside Upload and Choose from gallery: it folds the author's **physical description** (the subject) and **headshot style** (the art direction) into one portrait prompt and renders through the existing image-gen system, dropping the result straight into the headshot slot. The button stays disabled until at least one of those fields is filled. While a render is in flight the thumbnail shows the live diffusion preview and step percentage (async local/codex backends), and the Upload / gallery / URL controls lock so a manual choice can't be clobbered when the render lands; the synchronous external SD-API backend lands the image directly. Switching authors mid-render cancels the in-flight tracking so a completed (or still-pending) render can't write the wrong persona's headshot. (`client/src/pages/Authors.jsx`)-- **Author personas — manage reusable authors and pick one for a series** — Create gains an **Authors** page (`/authors`, reachable from the sidebar and ⌘K) for managing reusable author personas: each carries a **name**, **writing style**, **bio**, a **physical description** and a **headshot style** (the prompt inputs for generating a book-cover author headshot), plus an optional **headshot image** you can **upload** (a photo from your device), **choose from your image gallery** (the same searchable picker the image-gen page uses), or paste a URL into — with a live thumbnail preview and one-click clear. The Series Pipeline's author field — previously a free-text byline on both the create form and the series bible — is now an **author picker** that lists your personas: selecting one stores the persona link (`authorId`) **and** the denormalized byline string on the series, so covers and title screens still render the right name. Picking "— No author —" clears it; a legacy free-text byline with no linked persona is shown as a hint until you link one. Authors are stored in PostgreSQL (`authors` table, `db-primary`); they're local-only for now (a federated peer renders a synced series' byline from the string it carries) — cross-machine sync of the personas themselves is tracked as a follow-up. (`server/services/authors/`, `server/routes/authors.js`, `server/scripts/init-db.sql`, `server/lib/db.js`, `server/services/pipeline/series.js`, `client/src/pages/Authors.jsx`, `client/src/components/pipeline/AuthorPicker.jsx`, `client/src/services/apiAuthors.js`, `client/src/components/Layout.jsx`, `server/lib/navManifest.js`)+- **Author personas — manage reusable authors and pick one for a series** — Create gains an **Authors** page (`/authors`, reachable from the sidebar and ⌘K) for managing reusable author personas: each carries a **name**, **writing style**, **bio**, a **physical description** and a **headshot style** (the prompt inputs for generating a book-cover author headshot), plus an optional **headshot image** you can **upload** (a photo from your device), **choose from your image gallery** (the same searchable picker the image-gen page uses), or paste a URL into — with a live thumbnail preview and one-click clear. The Series Pipeline's author field — previously a free-text byline on both the create form and the series bible — is now an **author picker** that lists your personas: selecting one stores the persona link (`authorId`) **and** the denormalized byline string on the series, so covers and title screens still render the right name. Picking "— No author —" clears it; a legacy free-text byline with no linked persona is shown as a hint until you link one. Authors are stored in PostgreSQL (`authors` table, `db-primary`) and **federate across your machines** (see the next entry). (`server/services/authors/`, `server/routes/authors.js`, `server/scripts/init-db.sql`, `server/lib/db.js`, `server/services/pipeline/series.js`, `client/src/pages/Authors.jsx`, `client/src/components/pipeline/AuthorPicker.jsx`, `client/src/services/apiAuthors.js`, `client/src/components/Layout.jsx`, `server/lib/navManifest.js`)++- **Author personas sync across federated peers** — Authors are now a first-class cross-machine sync category. Turn on **Authors** under a peer's sync settings (Instances page) and your personas — name, writing style, bio, physical description, headshot direction, and the **headshot image** itself when it's a gallery image — replicate to that peer: creating an author auto-subscribes it to every authors-enabled peer, each edit pushes the LWW-merged record, and a delete propagates as a tombstone (then garbage-collects once every subscribed peer has acked it). Built on the same per-record peer-push pipeline as media collections (not the 60s snapshot loop), with full version-gating — a peer on an older PortOS that predates author sync is detected and the authors category pauses for it (every other category keeps flowing) until it upgrades. A merge conflict (both machines edited the same author) is archived to the Conflicts tab. Gallery-picked headshots transfer their bytes; uploaded-from-device headshots sync the record but not yet the bytes (tracked as a follow-up). (`server/services/authors/{logic,db,file,index}.js`, `server/lib/syncWire.js`, `server/lib/schemaVersions.js`, `server/lib/conflictJournal.js`, `server/lib/peerSyncValidation.js`, `server/services/sharing/peerSync.js`, `server/services/sharing/tombstoneGc.js`, `server/services/instances.js`, `server/routes/instances.js`, `client/src/pages/Instances.jsx`)- **LoRA dataset grid: collapse captions, click-to-preview, and full-height thumbnails** — The dataset workbench image grid (`/media/training/:id`) gets three usability fixes. A **Hide captions / Show captions** toggle collapses every card's caption editor and action row at once, so you can scan the whole dataset as a clean thumbnail wall. Clicking any thumbnail now opens a **full-size preview lightbox** (← / → to step through the ready images, Esc to close) — the same affordance the media galleries already have. And thumbnails render at their **natural aspect ratio** (fixed column width, full relative height) instead of a fixed square crop, so portrait and landscape training images are no longer sliced off at the top and bottom. (`client/src/components/loraTraining/DatasetImageGrid.jsx`)@@ -52,6 +54,8 @@## Fixed+- **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`)- **LoRA training stops oversubscribing unified memory — frees resident models, spills the latent cache to disk, and refuses to start when memory is too tight** — On a 128 GB Apple-Silicon box a single mflux FLUX.2 run pushed the machine to ~122 GB used + ~21 GB swap, and that swap-thrash coincided with the GPU watchdog reboots above. Three changes keep a run inside the unified-memory pool. (1) **Pre-train reclaim** — before spawning the trainer, PortOS unloads every model resident in Ollama and LM Studio (best-effort; failures are ignored) so their memory returns to the pool instead of stacking under the run. Only **loopback-local** backends are touched — a remote `OLLAMA_URL`/`LM_STUDIO_URL` (a LAN peer in a federated setup) is left alone, since evicting it would free no local memory. (2) **Latent cache always spills to disk** — the mflux `low_ram` flag is now on at every memory tier; keeping the encoded dataset cache in RAM bought nothing but the swap pressure, and disk-backing it costs only I/O, no training quality. (3) **Headroom gate** — the quantize/`low_ram` tier is now derived from the *post-unload available* memory (measured via `vm_stat` on macOS, free + inactive + speculative + purgeable) rather than raw RAM, so a busy box auto-tightens to a smaller base; and a run refuses to start with a clear error when under ~24 GB is free, rather than crashing the box mid-run. (`server/services/loraTraining/memoryPrep.js`, `server/services/loraTraining/runtimes.js`, `server/services/loraTraining/index.js`)diff --git a/scripts/cleanup-test-data.js b/scripts/cleanup-test-data.jsindex 6ff04f2828..fd19ba0d43 100644--- a/scripts/cleanup-test-data.js+++ b/scripts/cleanup-test-data.js@@ -46,6 +46,18 @@ import { listUniverses, deleteUniverse } from '../server/services/universeBuildeimport { listSeries, deleteSeries } from '../server/services/pipeline/series.js';import { listIssues, deleteIssue } from '../server/services/pipeline/issues.js';+// Real records are ALWAYS minted with randomUUID() — universes get a bare UUID,+// series an `ser-<uuid>`, issues an `iss-<uuid>` (server/services/pipeline/{series,+// issues}.js, universeBuilder.js). So any record whose id is NOT that shape+// (e.g. `ok-1`, `ser-1`, `ser-uuid-2`, `iss-live`, `iss-dup`) is unambiguously a+// hard-coded test fixture the app could never have created — a far more reliable+// signal than the name roster, and it catches generic-named fixtures the roster+// intentionally omits. We delete on EITHER signal: impossible-id OR test-name.+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const isUniverseFixtureId = (id) => !UUID_RE.test(id || '');+const isSeriesFixtureId = (id) => !(/^ser-/.test(id || '') && UUID_RE.test((id || '').slice(4)));+const isIssueFixtureId = (id) => !(/^iss-/.test(id || '') && UUID_RE.test((id || '').slice(4)));+// Roster of names known to come from test fixtures. Conservative default:// only unmistakable test names. Generic single-word names that could// plausibly be a real user's universe/series (e.g. 'A', 'B', 'Live',@@ -66,6 +78,7 @@ const TEST_FIXTURE_UNIVERSE_NAMES = new Set([const TEST_FIXTURE_SERIES_NAMES = new Set(['Commit S',+ 'Committed S','Linkless S','Locked S','Same Title',@@ -73,6 +86,14 @@ const TEST_FIXTURE_SERIES_NAMES = new Set(['Old tombstone','New tombstone','Edited Locally',+ // Added 2026-06-14 after auditing the live DB: more unambiguous test names+ // (the matching fixtures all carry `ser-<uuid>` ids so the id-shape check+ // alone wouldn't catch them). All sourced from series.test.js / importer.test.js.+ 'A Series',+ 'Born Committed',+ 'Real Work',+ 'Moving Series',+ 'S1',]);function parseArgs(argv) {@@ -94,33 +115,56 @@ async function main() {console.log('⚠️ Run `pm2 stop portos-server` first, then `pm2 start portos-server` to propagate\n');}+ // A record is a fixture target on EITHER signal: an impossible (non-minted)+ // id shape OR a name in the test roster. The id-shape check is the stronger+ // signal — the running app cannot mint `ser-1`/`ok-1`/`iss-live`.+ const universeReason = (u) =>+ isUniverseFixtureId(u.id) ? 'non-uuid id'+ : TEST_FIXTURE_UNIVERSE_NAMES.has((u.name || '').trim()) ? 'test name' : null;+ const seriesReason = (s) =>+ isSeriesFixtureId(s.id) ? 'non-uuid id'+ : TEST_FIXTURE_SERIES_NAMES.has((s.name || '').trim()) ? 'test name' : null;+// Universes (skip already-tombstoned ones so a re-run is a no-op).const universes = await listUniverses({ includeDeleted: false });- const universeTargets = universes.filter(u =>- TEST_FIXTURE_UNIVERSE_NAMES.has((u.name || '').trim())- );+ const universeTargets = universes+ .map(u => ({ rec: u, reason: universeReason(u) }))+ .filter(t => t.reason);console.log(`🗑️ Universes to delete: ${universeTargets.length}`);- for (const u of universeTargets) {- console.log(` - ${u.id.slice(0, 8)} "${u.name}" (updated ${u.updatedAt})`);+ for (const { rec: u, reason } of universeTargets) {+ console.log(` - ${u.id.slice(0, 8)} "${u.name}" (${reason}, updated ${u.updatedAt})`);}// Series + their child issues. Resolve children up front so the dry-run// output also reports the cascade — running with --apply matches.const series = await listSeries({ includeDeleted: false });- const seriesTargets = series.filter(s =>- TEST_FIXTURE_SERIES_NAMES.has((s.name || '').trim())- );+ const seriesTargets = series+ .map(s => ({ rec: s, reason: seriesReason(s) }))+ .filter(t => t.reason);+ const seriesTargetIds = new Set(seriesTargets.map(t => t.rec.id));// Map series.id → array of live child issues for that series.const childIssuesBySeries = new Map();- for (const s of seriesTargets) {+ for (const { rec: s } of seriesTargets) {const children = await listIssues({ seriesId: s.id, includeDeleted: false }).catch(() => []);childIssuesBySeries.set(s.id, children);}const totalChildIssues = [...childIssuesBySeries.values()].reduce((n, arr) => n + arr.length, 0);console.log(`\n🗑️ Series to delete: ${seriesTargets.length} (cascading ${totalChildIssues} child issue${totalChildIssues === 1 ? '' : 's'})`);- for (const s of seriesTargets) {+ for (const { rec: s, reason } of seriesTargets) {const children = childIssuesBySeries.get(s.id) || [];- console.log(` - ${s.id.slice(0, 12)} "${s.name}" (updated ${s.updatedAt}, ${children.length} child issue${children.length === 1 ? '' : 's'})`);+ console.log(` - ${s.id.slice(0, 12)} "${s.name}" (${reason}, updated ${s.updatedAt}, ${children.length} child issue${children.length === 1 ? '' : 's'})`);+ }++ // Orphan fixture issues: a non-uuid-id issue whose parent series is NOT itself+ // a target (so it won't be reached by the cascade above). These are direct+ // test-fixture inserts (`iss-live`, `iss-dup`, …) that would otherwise survive.+ const allIssues = await listIssues({ includeDeleted: false }).catch(() => []);+ const orphanIssueTargets = allIssues.filter(+ i => isIssueFixtureId(i.id) && !seriesTargetIds.has(i.seriesId),+ );+ console.log(`\n🗑️ Orphan fixture issues (non-uuid id, parent not targeted): ${orphanIssueTargets.length}`);+ for (const i of orphanIssueTargets) {+ console.log(` - ${i.id} (series ${i.seriesId}, #${i.number})`);}if (!apply) {@@ -132,7 +176,7 @@ async function main() {// pointers, but the tombstone on the universe doesn't cascade to series;// series with this universeId orphan-but-live, which is fine).console.log('\n🗑️ Applying universe tombstones...');- for (const u of universeTargets) {+ for (const { rec: u } of universeTargets) {await deleteUniverse(u.id).catch(err =>console.error(` ⚠️ failed to delete universe ${u.id.slice(0, 8)}: ${err.message}`),);@@ -142,7 +186,7 @@ async function main() {// an orphan child wouldn't surface in the dry-run either — children must// go via this script's pass, not the parent's GC). Then tombstone the series.console.log('🗑️ Applying issue + series tombstones...');- for (const s of seriesTargets) {+ for (const { rec: s } of seriesTargets) {const children = childIssuesBySeries.get(s.id) || [];for (const i of children) {await deleteIssue(i.id).catch(err =>@@ -153,7 +197,13 @@ async function main() {console.error(` ⚠️ failed to delete series ${s.id.slice(0, 12)}: ${err.message}`),);}- console.log(`\n✅ Tombstoned ${universeTargets.length} universe(s) + ${seriesTargets.length} series + ${totalChildIssues} issue(s).`);+ // Orphan fixture issues whose parent series wasn't itself a target.+ for (const i of orphanIssueTargets) {+ await deleteIssue(i.id).catch(err =>+ console.error(` ⚠️ failed to delete orphan issue ${i.id}: ${err.message}`),+ );+ }+ console.log(`\n✅ Tombstoned ${universeTargets.length} universe(s) + ${seriesTargets.length} series + ${totalChildIssues + orphanIssueTargets.length} issue(s).`);console.log('🔄 Now restart the PM2 server to propagate the tombstones to peers:');console.log(' pm2 restart portos-server');console.log(' (peer:online will re-fire every per-record sub and the new tombstone');diff --git a/server/lib/db.guards.test.js b/server/lib/db.guards.test.jsindex fe373882ae..81bc8c94f9 100644--- a/server/lib/db.guards.test.js+++ b/server/lib/db.guards.test.js@@ -18,13 +18,19 @@* even if a suite reaches it without gating on checkHealth* first. (DELETE-only guarding let test INSERTs leak* fixtures into the real `portos` DB on 2026-06-14.)+ * - withTransaction() — the SAME backstop on the raw pg client it hands the+ * callback. client.query() bypasses query() entirely, so+ * every store mutation that writes inside a transaction+ * (updateAuthor, deleteAuthor, mergeAuthorsFromSync,+ * universe runs, catalog, writers-room) wrote to the real+ * `portos` DB unguarded under VITEST until this was added.*/import { describe, it, expect, afterEach } from 'vitest';import { readdirSync, openSync, readSync, closeSync, existsSync } from 'node:fs';import { dirname, join, sep } from 'node:path';import { fileURLToPath } from 'node:url';-import { isTestDatabase, isTestRunner, checkHealth, query } from './db.js';+import { isTestDatabase, isTestRunner, checkHealth, query, assertWriteAllowed } from './db.js';import { DB_TEST_INCLUDE } from '../vitest.config.db.js';// NODE_ENV is 'test' throughout (vitest default); we vary PGDATABASE / TEST_DB_OK.@@ -195,6 +201,52 @@ describe('query row-write backstop', () => {});});+// The shared backstop used by BOTH query() and the withTransaction client. The+// transaction path is the one that actually leaked: nearly every store mutation+// (updateAuthor, deleteAuthor, mergeAuthorsFromSync, universe runs, catalog,+// writers-room) runs its INSERT/UPDATE/DELETE through `client.query()` inside a+// transaction, which talks to the raw pg client — NOT this module's query(). We+// can't open a real transaction in CI (no DB), so we test the guard the proxy+// wraps directly: assertWriteAllowed sees the exact SQL the proxy forwards it.+describe('assertWriteAllowed (shared query + transaction-client backstop)', () => {+ it('throws on a row write against a non-test DB under the runner', () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ expect(() => assertWriteAllowed("INSERT INTO authors (id) VALUES ('x')")).toThrow(+ /Refusing to mutate/i,+ );+ expect(() => assertWriteAllowed('DELETE FROM universes')).toThrow(/Refusing to mutate/i);+ expect(() => assertWriteAllowed("UPDATE pipeline_series SET name = 'x'")).toThrow(+ /Refusing to mutate/i,+ );+ });++ it('allows transaction control statements (BEGIN/COMMIT/ROLLBACK) and reads', () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ // These are exactly the statements withTransaction runs around the callback,+ // plus the SELECT … FOR UPDATE reads the store mutations issue first.+ expect(() => assertWriteAllowed('BEGIN')).not.toThrow();+ expect(() => assertWriteAllowed('COMMIT')).not.toThrow();+ expect(() => assertWriteAllowed('ROLLBACK')).not.toThrow();+ expect(() => assertWriteAllowed('SELECT data FROM authors WHERE id = $1 FOR UPDATE')).not.toThrow();+ });++ it('allows row writes against a designated test DB', () => {+ setEnv('PGDATABASE', 'portos_test');+ setEnv('TEST_DB_OK', undefined);+ expect(() => assertWriteAllowed("INSERT INTO authors (id) VALUES ('x')")).not.toThrow();+ });++ it('tolerates a non-string arg (a config object with no .text reaches it as undefined)', () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ // The transaction proxy passes config?.text; a parameterless control call+ // can surface undefined here — it must not throw on a non-string.+ expect(() => assertWriteAllowed(undefined)).not.toThrow();+ });+});+// Drift guard: a DB-backed suite skips on a non-test DB (correct), so if a new// one is left out of vitest.config.db.js it would simply NEVER run — silently// losing coverage with a green board. This asserts every real DB-backed suitediff --git a/server/lib/db.js b/server/lib/db.jsindex 82ff94702b..c605e5d1f3 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -88,18 +88,22 @@ const ROW_WRITE_SQL =/^\s*(?:--[^\n]*\n|\/\*[\s\S]*?\*\/|\s)*(INSERT\s+INTO|UPDATE\s|DELETE\s+FROM|TRUNCATE)\b/i;/**- * Execute a query against the connection pool.- * @param {string} text - SQL query text with $1, $2, etc. placeholders- * @param {Array} params - Parameter values- * @returns {Promise<pg.QueryResult>}+ * Hard backstop: under the test runner, refuse to MUTATE a non-test database.+ * Throws (fail loudly) on any row write (INSERT/UPDATE/DELETE/TRUNCATE) instead+ * of silently writing — or stranding — real data. Reads (SELECT) and schema DDL+ * are left alone so health/version probes and ensureSchema() still work.+ *+ * Shared by BOTH the pool `query()` wrapper and the per-transaction client in+ * `withTransaction()`. The transaction path is critical: nearly every store+ * mutation (updateAuthor, deleteAuthor, mergeAuthorsFromSync, universe runs,+ * catalog, writers-room) runs its writes through `client.query()` inside a+ * transaction — which talks to the raw pg client, NOT this module's `query()`.+ * Guarding only `query()` left that path wide open: a suite under VITEST that+ * reached any transaction write path wrote straight into the real `portos` DB.+ *+ * @param {string} text - SQL query text*/-export async function query(text, params) {- // Hard backstop: under the test runner, refuse to MUTATE a non-test database- // even if a suite somehow reaches query() without gating on checkHealth()- // first (a new test author calls query('INSERT …') directly, or a backend- // selector mis-chose Postgres because NODE_ENV wasn't 'test'). Throwing fails- // loudly instead of silently writing — or stranding — real data. Reads- // (SELECT) are left alone so health/version probes still work.+export function assertWriteAllowed(text) {if (isTestRunner() &&!isTestDatabase() &&@@ -111,6 +115,40 @@ export async function query(text, params) {`Point PGDATABASE at a *_test database (e.g. portos_test), gate the suite on requireDb(), or set TEST_DB_OK=1. Query: ${text.slice(0, 80)}`,);}+}++// Proxy handler that runs a pg client's row writes through assertWriteAllowed.+// Defined once at module scope (not per-transaction): the `get` trap receives+// the client as `target`, so a single shared handler guards every client+// withTransaction() wraps — no per-call handler/closure allocation. A Proxy+// (rather than an object-spread copy) is required because pg's client methods+// live on the prototype, which a spread would not carry.+const GUARDED_CLIENT_HANDLER = {+ get(target, prop, receiver) {+ if (prop === 'query') {+ return (config, ...rest) => {+ const sql = typeof config === 'string' ? config : config?.text;+ assertWriteAllowed(sql);+ return target.query(config, ...rest);+ };+ }+ const value = Reflect.get(target, prop, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ },+};++/**+ * Execute a query against the connection pool.+ * @param {string} text - SQL query text with $1, $2, etc. placeholders+ * @param {Array} params - Parameter values+ * @returns {Promise<pg.QueryResult>}+ */+export async function query(text, params) {+ // Hard backstop: refuse to mutate a non-test DB under the runner even if a+ // suite reaches query() without gating on checkHealth() first (a new test+ // author calls query('INSERT …') directly, or a backend selector mis-chose+ // Postgres because NODE_ENV wasn't 'test').+ assertWriteAllowed(text);return pool.query(text, params);}@@ -140,10 +178,18 @@ export async function getServerMajorVersion() {*/export async function withTransaction(fn) {const client = await pool.connect();+ // Guard the client's row writes with the same backstop as query(). The raw+ // pg client bypasses query() entirely, so without this wrapper a test-runner+ // process pointed at the real `portos` DB writes through every store's+ // transaction path unguarded (see assertWriteAllowed). BEGIN/COMMIT/ROLLBACK+ // below call the raw client directly (they are not row writes). pg's+ // client.query accepts either a SQL string or a { text, values } config —+ // GUARDED_CLIENT_HANDLER reads the SQL out of both.+ const guardedClient = new Proxy(client, GUARDED_CLIENT_HANDLER);await client.query('BEGIN');let result;try {- result = await fn(client);+ result = await fn(guardedClient);await client.query('COMMIT');} catch (err) {await client.query('ROLLBACK');