Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(test): refuse to start a test run while a database URL is ambient (#3485)
Garry Tan296222eff054
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex 9d467f5134..ab98fb62a1 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -61,10 +61,15 @@ jobs:- name: Run JSONB double-encode parity tests on real Postgresenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test+ # #3485 preload guard: this job intentionally tests against a DB.+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'# --timeout also raises bun's 5s default hook budget (beforeAll/afterAll# do NOT inherit a test's third-arg timeout; verified on bun 1.3.x).# Every runner script in scripts/ passes it; bare invocations must too.- run: bun test --timeout=60000 test/e2e/op-checkpoint-jsonb-parity.test.ts test/e2e/jsonb-roundtrip.test.ts+ # phantom-redirect rides this job: its Postgres arm is the other+ # engine-parity backstop and no other CI lane carries DATABASE_URL to it+ # (the unit wrappers strip the URL per #3485).+ run: bun test --timeout=60000 test/e2e/op-checkpoint-jsonb-parity.test.ts test/e2e/jsonb-roundtrip.test.ts test/phantom-redirect-engine-parity.test.tstier1:name: Tier 1 (Mechanical)@@ -94,6 +99,8 @@ jobs:run: bun test --timeout=60000 test/e2e/mechanical.test.ts test/e2e/mcp.test.tsenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test+ # #3485 preload guard: this job intentionally tests against a DB.+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'tier2:name: Tier 2 (LLM Skills)@@ -161,6 +168,8 @@ jobs:run: bun test --timeout=60000 test/e2e/skills.test.ts test/e2e/zeroentropy-live.test.tsenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test+ # #3485 preload guard: this job intentionally tests against a DB.+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}# v0.33.3.0: ZE live API tests skip gracefully when this is unset,diff --git a/.github/workflows/heavy-tests.yml b/.github/workflows/heavy-tests.ymlindex 1844103b45..404716ae3f 100644--- a/.github/workflows/heavy-tests.yml+++ b/.github/workflows/heavy-tests.yml@@ -64,6 +64,8 @@ jobs:- name: Run heavy testsenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test+ # #3485 preload guard: this job intentionally tests against a DB.+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'run: bun run test:heavy# Agent-bootstrap offline Docker e2e [A7] — placeholder registration.diff --git a/bunfig.toml b/bunfig.tomlindex 1efda81feb..fe89248b6f 100644--- a/bunfig.toml+++ b/bunfig.toml@@ -23,4 +23,8 @@ timeout = 60_000# were appending rows into the operator's real ~/.gbrain/sync-failures.jsonl,# which `gbrain doctor` reads and warns on. See# test/helpers/sync-failures-preload.ts.-preload = ["./test/helpers/legacy-embedding-preload.ts", "./test/helpers/audit-dir-preload.ts", "./test/helpers/sync-failures-preload.ts"]+# #3485: database-url-guard-preload runs FIRST — it refuses to start the run+# while DATABASE_URL/GBRAIN_DATABASE_URL is ambient without the explicit+# GBRAIN_TEST_ALLOW_DATABASE_URL=1 opt-in that the e2e wrappers set at their+# own subprocess boundary. See test/helpers/database-url-guard-preload.ts.+preload = ["./test/helpers/database-url-guard-preload.ts", "./test/helpers/legacy-embedding-preload.ts", "./test/helpers/audit-dir-preload.ts", "./test/helpers/sync-failures-preload.ts"]diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.shindex d83aef43fa..915851fdfe 100755--- a/scripts/run-e2e.sh+++ b/scripts/run-e2e.sh@@ -36,6 +36,16 @@ set -euo pipefailcd "$(dirname "$0")/.."+# #3485: this wrapper IS the e2e boundary — opt in to running with a database+# URL present. The bunfig test preload (database-url-guard-preload.ts) refuses+# bare `bun test` runs while DATABASE_URL/GBRAIN_DATABASE_URL is ambient; the+# per-file name floor (test/helpers/db-guard.ts) still applies after this.+export GBRAIN_TEST_ALLOW_DATABASE_URL=1+# The e2e suite runs on DATABASE_URL only; an ambient GBRAIN_DATABASE_URL+# would pass the opt-in yet reach CLI-subprocess paths with no name floor —+# drop it here so only the floored variable crosses the boundary.+unset GBRAIN_DATABASE_URL+# --- HOME isolation: snapshot real user config before switching ---# Tolerate unset HOME (minimal containers, exotic CI shells) without tripping set -u.REAL_HOME="${HOME:-/tmp}"@@ -83,6 +93,10 @@ mkdir -p "$E2E_TMP_HOME/.gbrain"for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GBRAIN_)[A-Za-z0-9_]*' | sort -u); docase "$_e2e_var" inGBRAIN_HOME) ;; # required for HOME isolation (set above) — keep+ GBRAIN_TEST_ALLOW_DATABASE_URL) ;; # #3485 preload opt-in (set above) — keep+ GBRAIN_E2E_ALLOW_DB) ;; # #3485 name-floor opt-in — the guard's own error+ # message tells operators to set it; stripping it+ # here would make that escape hatch a dead end*) unset "$_e2e_var" || true ;;esacdone@@ -99,7 +113,10 @@ fiif [ "$#" -gt 0 ]; thenfiles=("$@")else- files=(test/e2e/*.test.ts)+ # phantom-redirect lives in test/ (its PGLite arm runs in the unit suite) but+ # its Postgres arm is only reachable through a DATABASE_URL-bearing lane —+ # the unit wrappers strip the URL (#3485), so this lane must carry it.+ files=(test/e2e/*.test.ts test/phantom-redirect-engine-parity.test.ts)fi# SHARD env (e.g. SHARD=1/4) keeps every M-th file starting at index N (1-indexed).diff --git a/scripts/run-slow-tests.sh b/scripts/run-slow-tests.shindex f37ee6cccf..c47ce8cc90 100755--- a/scripts/run-slow-tests.sh+++ b/scripts/run-slow-tests.sh@@ -4,6 +4,11 @@# CI runs both; bun run ci:local skips slow tests via run-unit-shard.sh.set -euo pipefail++# #3485: unit/slow tests need no database — strip ambient DB URLs at this+# wrapper boundary so the bunfig preload guard passes and nothing can reach a+# real brain. The e2e wrapper (run-e2e.sh) is the only lane that keeps them.+unset DATABASE_URL GBRAIN_DATABASE_URLcd "$(dirname "$0")/.."slow_files=()diff --git a/scripts/run-unit-parallel.sh b/scripts/run-unit-parallel.shindex ff4fd68676..502d311f76 100755--- a/scripts/run-unit-parallel.sh+++ b/scripts/run-unit-parallel.sh@@ -44,6 +44,11 @@set -uo pipefail+# #3485: unit tests need no database — strip ambient DB URLs at this wrapper+# boundary so the bunfig preload guard passes and nothing can reach a real+# brain. The e2e wrapper (run-e2e.sh) is the only lane that keeps them.+unset DATABASE_URL GBRAIN_DATABASE_URL+cd "$(dirname "$0")/.."# ──────────────────────────────────────────────────────────────────────────diff --git a/scripts/run-unit-shard.sh b/scripts/run-unit-shard.shindex 67a8d8863d..7c6fb97bc2 100755--- a/scripts/run-unit-shard.sh+++ b/scripts/run-unit-shard.sh@@ -14,6 +14,11 @@set -euo pipefail+# #3485: unit/slow tests need no database — strip ambient DB URLs at this+# wrapper boundary so the bunfig preload guard passes and nothing can reach a+# real brain. The e2e wrapper (run-e2e.sh) is the only lane that keeps them.+unset DATABASE_URL GBRAIN_DATABASE_URL+cd "$(dirname "$0")/.."# --max-concurrency=N is forwarded to `bun test`. v0.26.4: invoked bydiff --git a/test/database-url-guard-preload.test.ts b/test/database-url-guard-preload.test.tsnew file mode 100644index 0000000000..f2e0d363c9--- /dev/null+++ b/test/database-url-guard-preload.test.ts@@ -0,0 +1,103 @@+/**+ * #3485 invocation-level guard: a bare `bun test` must refuse to start while+ * DATABASE_URL or GBRAIN_DATABASE_URL is ambient, unless the invoker opted in+ * with GBRAIN_TEST_ALLOW_DATABASE_URL=1 (the e2e wrappers do, at their own+ * subprocess boundary).+ *+ * Each case spawns a real `bun test` child on a trivial probe fixture with a+ * controlled environment, so what's asserted is the actual preload behavior,+ * not a re-implementation of it. The child inherits this repo's bunfig.toml+ * (cwd = repo root), which registers the guard preload first.+ */+import { describe, test, expect } from 'bun:test';+import { resolve } from 'path';++const REPO_ROOT = resolve(import.meta.dir, '..');+const PROBE = 'test/fixtures/preload-guard/guard-probe.test.ts';+const GUARD_MARKER = 'TEST-RUN GUARD: refusing to start';++/** Base child env: inherit, then strip every var the guard reads. */+function baseEnv(): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(process.env)) {+ if (v === undefined) continue;+ if (k === 'DATABASE_URL' || k === 'GBRAIN_DATABASE_URL' || k === 'GBRAIN_TEST_ALLOW_DATABASE_URL') continue;+ env[k] = v;+ }+ return env;+}++function runProbe(extra: Record<string, string>): { exitCode: number; stderr: string } {+ const proc = Bun.spawnSync(['bun', 'test', '--timeout=15000', PROBE], {+ cwd: REPO_ROOT,+ env: { ...baseEnv(), ...extra },+ stdout: 'pipe',+ stderr: 'pipe',+ // A hung child would otherwise block the sync call past bun's own+ // per-test timeout (which cannot preempt a native sync call).+ timeout: 20_000,+ killSignal: 'SIGKILL',+ });+ return { exitCode: proc.exitCode ?? -1, stderr: proc.stderr.toString() };+}++describe('database-url-guard-preload (#3485)', () => {+ test('refuses when DATABASE_URL is set', () => {+ const r = runProbe({ DATABASE_URL: 'postgresql://localhost:5434/gbrain' });+ expect(r.exitCode).not.toBe(0);+ expect(r.stderr).toContain(GUARD_MARKER);+ expect(r.stderr).toContain('DATABASE_URL');+ }, 30_000);++ test('refuses when GBRAIN_DATABASE_URL is set', () => {+ const r = runProbe({ GBRAIN_DATABASE_URL: 'postgresql://localhost:5434/gbrain' });+ expect(r.exitCode).not.toBe(0);+ expect(r.stderr).toContain(GUARD_MARKER);+ expect(r.stderr).toContain('GBRAIN_DATABASE_URL');+ }, 30_000);++ test('refuses and names both when both are set', () => {+ const r = runProbe({+ DATABASE_URL: 'postgresql://localhost:5434/gbrain',+ GBRAIN_DATABASE_URL: 'postgresql://localhost:5434/gbrain',+ });+ expect(r.exitCode).not.toBe(0);+ expect(r.stderr).toContain(GUARD_MARKER);+ expect(r.stderr).toContain('DATABASE_URL and GBRAIN_DATABASE_URL are set');+ }, 30_000);++ test('allows with GBRAIN_TEST_ALLOW_DATABASE_URL=1', () => {+ const r = runProbe({+ DATABASE_URL: 'postgresql://localhost:5434/gbrain',+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1',+ });+ expect(r.stderr).not.toContain(GUARD_MARKER);+ expect(r.exitCode).toBe(0);+ }, 30_000);++ test('runs clean with no database URL ambient', () => {+ const r = runProbe({});+ expect(r.stderr).not.toContain(GUARD_MARKER);+ expect(r.exitCode).toBe(0);+ }, 30_000);++ test('refuses truthy-but-wrong override values (strict === "1")', () => {+ // A future loosening to Boolean(process.env...) must fail this test:+ // only the exact string '1' opts in.+ const r = runProbe({+ DATABASE_URL: 'postgresql://localhost:5434/gbrain',+ GBRAIN_TEST_ALLOW_DATABASE_URL: 'true',+ });+ expect(r.exitCode).not.toBe(0);+ expect(r.stderr).toContain(GUARD_MARKER);+ }, 30_000);++ test('treats empty-string values as unset (v !== "" branch)', () => {+ // `export DATABASE_URL=` (empty) is a plausible dev state after a manual+ // unset attempt; the guard deliberately does not refuse on it — an empty+ // string cannot name a database to destroy.+ const r = runProbe({ DATABASE_URL: '', GBRAIN_DATABASE_URL: '' });+ expect(r.stderr).not.toContain(GUARD_MARKER);+ expect(r.exitCode).toBe(0);+ }, 30_000);+});diff --git a/test/fixtures/preload-guard/guard-probe.test.ts b/test/fixtures/preload-guard/guard-probe.test.tsnew file mode 100644index 0000000000..f92bd7d3b1--- /dev/null+++ b/test/fixtures/preload-guard/guard-probe.test.ts@@ -0,0 +1,13 @@+/**+ * Probe fixture for test/database-url-guard-preload.test.ts.+ *+ * Deliberately trivial: the parent test spawns `bun test` on this file with+ * controlled env and asserts on the RUN's exit code — the preload guard fires+ * (or doesn't) before this file executes. If the guard refuses, this test+ * never runs; if the guard allows, this passes and the run exits 0.+ */+import { test, expect } from 'bun:test';++test('probe: run started, preload guard allowed it', () => {+ expect(true).toBe(true);+});diff --git a/test/helpers/database-url-guard-preload.ts b/test/helpers/database-url-guard-preload.tsnew file mode 100644index 0000000000..1582af3963--- /dev/null+++ b/test/helpers/database-url-guard-preload.ts@@ -0,0 +1,59 @@+/**+ * Invocation-level guard: refuse to start a test run while a database URL is+ * ambient in the environment, unless the invoker explicitly opted in.+ *+ * Why this exists (#3485): `gbrain init` writes DATABASE_URL into+ * ~/.gbrain/.env pointing at the developer's real brain. Several test files+ * connect to whatever DATABASE_URL names and run TRUNCATE/DELETE/DROP — a+ * bare `bun test` with that env sourced has destroyed a real brain before.+ * The per-file name floor (test/helpers/db-guard.ts) is the second layer;+ * this preload is the first: no test file loads at all while an unexpected+ * database URL is present.+ *+ * Both DATABASE_URL and GBRAIN_DATABASE_URL are checked — the runtime honors+ * both (src/core/config.ts), so guarding only one leaves a live path.+ *+ * HARD-FAIL, never silently unset: silently clearing the var would turn+ * DATABASE_URL-gated e2e tests into green skips, hiding the exact class of+ * bug (#2339) those tests exist to catch. The e2e wrappers (scripts/+ * run-e2e.sh, the e2e/heavy workflows) set GBRAIN_TEST_ALLOW_DATABASE_URL=1+ * at their own subprocess boundary; nothing sets it globally.+ *+ * Registered FIRST in bunfig.toml's [test].preload so it runs before any+ * other preload does work.+ */++const ALLOW = process.env.GBRAIN_TEST_ALLOW_DATABASE_URL === '1';++if (!ALLOW) {+ const offending = (['DATABASE_URL', 'GBRAIN_DATABASE_URL'] as const).filter(+ (name) => {+ const v = process.env[name];+ return v !== undefined && v !== '';+ },+ );+ if (offending.length > 0) {+ console.error(+ [+ `TEST-RUN GUARD: refusing to start — ${offending.join(' and ')} ${offending.length === 1 ? 'is' : 'are'} set.`,+ ``,+ `Some tests run destructive SQL (TRUNCATE/DELETE/DROP) against whatever`,+ `these URLs point at. A bare \`bun test\` with a real brain's URL in the`,+ `environment has wiped that brain before (#3485).`,+ ``,+ `Pick one:`,+ ` - unset the variable${offending.length > 1 ? 's' : ''} and re-run (unit tests need no database).`,+ ` If it keeps coming back, check for a .env file in this directory or a`,+ ` sourced ~/.gbrain/.env — bun auto-loads cwd .env into the test run.`,+ ` - run the e2e suite through its wrapper: \`bun run test:e2e\``,+ ` (the wrapper opts in at its own boundary), or`,+ ` - if you really mean to run tests against this database, opt in`,+ ` ONE-SHOT: \`GBRAIN_TEST_ALLOW_DATABASE_URL=1 bun test ...\` — avoid a`,+ ` shell-profile export, which would permanently disarm this guard. The`,+ ` per-file guard (test/helpers/db-guard.ts) still requires a test-shaped`,+ ` database name after that.`,+ ].join('\n'),+ );+ process.exit(1);+ }+}