Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.8.0 fix(test): local lanes green — cli SIGTERM seam, GBRAIN_HOME isolation, 13 e2e repairs (#4171)

Garry Tandc716ea797db
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 00c6ce2029..a508d708c3 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.7.0",
+ "version": "0.46.8.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": { "name": "Garry Tan", "url": "https://github.com/garrytan" },
"homepage": "https://github.com/garrytan/gbrain",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index d5cb0911e6..af3b0f8311 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.7.0",
+ "version": "0.46.8.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": { "name": "Garry Tan", "url": "https://github.com/garrytan" },
"homepage": "https://github.com/garrytan/gbrain",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index d839a46803..d15731911f 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.7.0 -->
+<!-- gbrain-runbook-stamp: 0.46.8.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4da1a215cd..64cbcabdfa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,65 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.8.0] - 2026-08-15
+
+**The full local test suite is trustworthy again.** `bun run test` and
+`bun run test:e2e` now pass on developer machines the same way they pass in
+CI — the two failure classes that made local runs lie are fixed at the root.
+
+### Fixed
+
+- **Test runs no longer die mid-suite with phantom "externally killed" shards.**
+ The CLI installed its shutdown signal handler at module load, so any test
+ that imported the CLI armed a process-wide SIGTERM handler inside the test
+ runner; one test's synthetic signal emission then killed the entire shard.
+ The handler now installs only in real CLI entrypoints (compiled binary,
+ spawned CLIs), never in importers — pinned by spawn-based regression tests.
+- **Unit tests are isolated from your real brain.** A new test preload points
+ `GBRAIN_HOME` at per-run scratch, so config-honoring code paths no longer
+ change behavior with whatever your live `~/.gbrain/config.json` says (27
+ cycle/dream tests flipped red whenever another workspace rewrote it), and
+ tests can no longer clobber real config, audit logs, or lock files. The
+ unit/slow wrappers also strip an ambient `GBRAIN_HOME` at their boundary,
+ matching the existing `DATABASE_URL` discipline.
+- **One canonical `GBRAIN_HOME` convention.** Preferences and the migration
+ ledger now resolve through the same path convention as engine config
+ (`GBRAIN_HOME` is a parent directory; `.gbrain` is appended) instead of a
+ divergent local rule that split one logical home across two roots. Installs
+ that run with `GBRAIN_HOME` set get a one-time, atomic, rollback-safe
+ copy-forward of their existing preferences and migration history — an
+ explicit `minion_mode: off` opt-out survives the upgrade, and completed
+ migrations are never silently re-run. Read-only homes degrade to reading
+ the legacy file in place.
+- **13 end-to-end test files repaired** after drifting from behavior that
+ changed in earlier releases (transport-scoped local-only ops, soft-delete
+ semantics, pack-manifest extractable types, halfvec embedding columns,
+ multi-asset compiled builds, environment leakage into hermetic fixtures,
+ a clock-skew-sensitive staleness assertion, and a driver array-binding
+ quirk). All were test-side fixes — no product behavior had regressed.
+- **`gbrain doctor` announces its filesystem-only fallback.** When the DB
+ connect (or the DB-backed check run) fails, doctor now says so on stderr
+ instead of silently degrading — with connection errors scrubbed through
+ the credential redactor (URL userinfo, libpq `password=` forms including
+ quoted values, hostnames/IPs) so pasted output doesn't leak credentials
+ into issues and CI logs.
+- **The e2e runner no longer false-kills its known-slow file.** `run-e2e.sh`'s
+ per-file wedge timeout (the hard-timeout backstop against wedged files, 180s) is
+ now overridable per file; the full ingest-skill e2e gets 420s — its runtime
+ grows with every migration master adds, and the flat cap had started killing
+ legitimately-passing runs on quiet machines.
+
+### Added
+
+- Regression pins for the new harness contracts: importing the CLI installs
+ no termination/cleanup signal handlers; the test-home preload sets-when-unset and respects
+ pre-set values; `_resetForTests` fully detaches listeners; free-text
+ credential redaction (`redactUrlsInText`).
+
+To take advantage of v0.46.8.0: `gbrain self-upgrade`, then `gbrain doctor`
+— no schema migration, no config changes. If you run tests locally,
+`bun run test` and `DATABASE_URL=<test-db> bun run test:e2e` should both
+exit 0 on a clean checkout; if they don't, the failure is real.
## [0.46.7.0] - 2026-08-15
**gbrain is now a proper Codex plugin — and a Claude Code plugin — from one repo.**
diff --git a/TODOS.md b/TODOS.md
index d37e6e9b01..559a64bc6e 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -6418,3 +6418,36 @@ covers DEAD logs; go-forward capture beyond Claude Code is deliberately absent.
are heavy machinery for a benign-cost race; the retriage help documents
the behavior. Context: outside-voice CX5 on the #4152 ship review.
Effort: M.
+
+## Local-lane green wave follow-ups (filed at build time)
+
+- [ ] **P2 — Gate `installSigchldHandler()` on `import.meta.main` too.** Same
+ class as the process-cleanup SIGTERM leak fixed in this wave (cli.ts:3-4):
+ a process-wide SIGCHLD reaper installs into any process that merely imports
+ cli.ts — in a bun test runner it could race Bun's own child reaping and
+ steal spawn exit statuses. No observed failure yet; move it inside the
+ import.meta.main seam with a soak run of the full suite before landing.
+ Effort: S.
+- [ ] **P2 — CI e2e lane runs only 8 of ~187 e2e files.** The other ~179 run
+ only via local `bun run test:e2e`, which is how 13 files rotted undetected
+ across v0.42–v0.46 waves (this wave's fix list). Options: a nightly
+ heavy-tests job running the full run-e2e.sh list against the compose
+ postgres, or fold the full lane into ci-local + a required weekly schedule.
+ Decide venue, then wire `scripts/e2e-test-map.ts` coverage accordingly.
+ Effort: M.
+- [ ] **P3 — run-unit-parallel external-kill reporting contradicts itself.**
+ A shard killed by an in-suite exit(143) prints `pass=N fail=0` +
+ `oom_rescue_failed=0real` in the final banner yet exits 1, and the
+ oom-rescue summary line says "real failures confirmed" with fail=0. Make
+ the banner name the killed shard + rescue outcome explicitly so the next
+ mystery kill is a 1-minute diagnosis instead of a bisect. Effort: S.
+- [ ] **P2 — skills.test.ts e2e leaks a git commit into the HOST repo.** During
+ the v0.46.8.0 ship gate, the e2e ingest-skill run created a real commit
+ ("ingest NovaMind board update transcript") with fixture pages
+ (companies/, people/, meetings/) at the WORKSPACE repo root — the test's
+ write-through/commit path resolved the host cwd instead of its tmp fixture
+ repo, despite run-e2e.sh's HOME isolation. Caught only because a soft reset
+ surfaced the staged files. Find the cwd-resolving path in the ingest skill
+ lane (likely repo-root fallback when the source local_path isn't threaded),
+ fix it to fail closed, and add a run-e2e.sh post-run guard that fails the
+ lane if `git status` at the host root gained tracked-file changes. Effort: M.
diff --git a/VERSION b/VERSION
index bb656dd72d..0a747c2fb5 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.7.0
\ No newline at end of file
+0.46.8.0
\ No newline at end of file
diff --git a/bunfig.toml b/bunfig.toml
index fe89248b6f..4450b9483b 100644
--- a/bunfig.toml
+++ b/bunfig.toml
@@ -27,4 +27,10 @@ timeout = 60_000
# 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"]
+#
+# gbrain-home-preload: point GBRAIN_HOME at per-run scratch so tests never
+# read (or clobber) the operator's real ~/.gbrain config/brain — the live
+# config.json changing mid-day flipped 27 config-honoring cycle/dream tests
+# red on dev boxes while CI stayed green. Respects a pre-set GBRAIN_HOME
+# (the e2e wrapper sets its own). See test/helpers/gbrain-home-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", "./test/helpers/gbrain-home-preload.ts"]
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 4846b504eb..1f0368a0fa 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -248,6 +248,25 @@ The quarantine has grown to dozens of files — treat it as debt: every addition
`bun test` runs all tests without a database. E2E tests skip gracefully when `DATABASE_URL` is not set.
+**GBRAIN_HOME isolation preload.** `test/helpers/gbrain-home-preload.ts` (bunfig
+`[test]` preload) points `GBRAIN_HOME` at a per-run scratch dir when it isn't
+already set, so unit tests never read — or clobber — the operator's real
+`~/.gbrain` config/brain. Without it, any config-honoring code path silently
+changes behavior with whatever the live `config.json` says (observed: 27
+cycle/autopilot/dream tests flipped red the moment a sibling workspace's run
+rewrote the real config, while the identical commit stayed green in CI). The
+canonical GBRAIN_HOME convention is `config.ts:configDir()`: GBRAIN_HOME is a
+PARENT dir and `.gbrain` is appended. Subprocess-spawning tests must set BOTH
+`HOME: tmp` and `GBRAIN_HOME: tmp` in the child env (HOME alone loses to the
+inherited preload value; in-process HOME mutation loses to Bun's cached
+`os.homedir()`). The e2e wrapper sets its own GBRAIN_HOME before bun starts,
+which this preload respects. Because the preload respects a pre-set value, the
+unit/slow wrappers (`run-unit-parallel.sh` / `run-unit-shard.sh` /
+`run-slow-tests.sh`) strip an ambient `GBRAIN_HOME` at their boundary — same
+discipline as the database-URL vars — so a dev shell configured for a real
+brain can't ride through. `GBRAIN_DEBUG_PRELOAD=1` prints the allocated
+scratch home for debugging.
+
**Database-URL run guard (#3485).** A `bun test` invocation REFUSES to start while
`DATABASE_URL` or `GBRAIN_DATABASE_URL` is ambient in the environment, because some
tests run destructive SQL against whatever those URLs point at (a bare `bun test`
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index f86896f51c..2582bea6fe 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -179,9 +179,12 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/backoff.ts` — Adaptive load-aware throttling: CPU/memory checks, exponential backoff, active hours multiplier.
- `src/core/retry.ts` — canonical retry primitive for transient connection errors. Exports `withRetry<T>(fn, opts)` execution wrapper + `BULK_RETRY_OPTS` constant (`{maxRetries:3, delayMs:1000, delayMaxMs:10000, jitter:'decorrelated'}`, tuned for Supabase Supavisor's 5-10s circuit-breaker recovery) + `BATCH_AUDIT_SITES` typed const (closed enum of every audit-emission site) + `resolveBulkRetryOpts(env)` (reads `GBRAIN_BULK_MAX_RETRIES`/`GBRAIN_BULK_RETRY_BASE_MS`/`GBRAIN_BULK_RETRY_MAX_MS` with `>=0` validation, throws on bad input with a paste-ready hint) + `abortableSleep(ms, signal?)` + `RetryAbortError` (tagged error for clean shutdown) + `computeNextDelay()` (pure-fn for 3 jitter modes: `'none'`, `'full'`, `'decorrelated'`). The execution wrapper is consumed by `postgres-engine.ts` + `pglite-engine.ts` batch primitives (`addLinksBatch` / `addTimelineEntriesBatch` / `upsertChunks`) so every caller inherits retry as part of the data-primitive's contract. CI guard `scripts/check-no-double-retry.sh` fails the build on `withRetry(...engine.batch...)` patterns (prevents 3×3=9 retry amplification); `scripts/check-batch-audit-site.sh` validates every string-literal `auditSite: '...'` against the closed `BATCH_AUDIT_SITES` enum. Decorrelated jitter (AWS-style: `uniform(base, prevDelay*3)` capped at `delayMaxMs`) — `'full'` jitter allowed near-zero retries that re-hit the recovering breaker. `WithRetryOpts` has an optional `reconnect?: () => Promise<void>` callback awaited in the catch branch AFTER `isRetryableConnError` classification but BEFORE the inter-attempt sleep — lets engine-level callers rebuild a dead pool/singleton between attempts. `PostgresEngine.batchRetry` injects `() => this.reconnect()` (the race-safe `_reconnecting` guard kicks in). Fail-loud: a reconnect throw PROPAGATES as the new error, replacing the symptomatic "No database connection". `onRetry` callbacks are awaited (sync arrows work identically; async callbacks correctly delay the sleep). Pinned by `test/core/retry.test.ts` (37 cases), `test/core/retry-stress.slow.test.ts` (5 cases, 100 batches × 30% blip rate, asserts zero row loss), `test/core/retry-reconnect.test.ts` (5 cases), `test/e2e/db-singleton-shared-recovery.test.ts` (3 DB-gated cases).
- `src/core/process-watchdog.ts` (#1633) — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+ (the reported incident). `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests. Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Reusable beyond sync (autopilot/cycle are follow-up adopters). Pinned by `test/process-watchdog.test.ts` (pure decision matrix + handle contract) + `test/process-watchdog.serial.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too); deadline resolved by `resolveSyncHardDeadline` in `sync.ts` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none).
+- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time leaked a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (bun test runners died mid-suite when a test emitted a synthetic SIGTERM; the runner misread rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone left the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`).
+- `src/core/preferences.ts` — preferences.json + the migration ledger (`migrations/completed.jsonl` append/read helpers; `appendCompletedMigration`, `loadCompletedMigrations`). Path resolution delegates to `config.ts:gbrainPath()`, so GBRAIN_HOME follows the ONE canonical convention: it is a PARENT dir and `.gbrain` is appended (`GBRAIN_HOME=/tmp/x` → `/tmp/x/.gbrain/migrations/...`). Its previous local resolver returned GBRAIN_HOME directly, splitting one logical home across two roots (config at `$GBRAIN_HOME/.gbrain/config.json`, ledger at `$GBRAIN_HOME/migrations/`) — while claiming in its own comment to match gbrainPath. `copyForwardLegacyFile` migrates the pre-unification layout once per file on first touch: atomic (temp + linkSync, EEXIST = concurrent winner), JSON-validated for prefs, chmod 0600, copy-not-move for binary rollback, once-per-process warning; a valid-but-uncopyable legacy file (read-only home) is READ IN PLACE so a transient failure can't drop a `minion_mode` opt-out or migration history. One-shot by design — mixed-version writers diverging post-snapshot is an accepted, documented limitation.
- `src/core/audit/batch-retry-audit.ts` — JSONL audit primitive for batch-retry events, built on `audit-writer.ts`. Schema: `{ts, site, batch_size, attempt, outcome: 'success' | 'exhausted', delay_ms, error_message_summary, error_code?}`. Privacy: NEVER logs slugs / page IDs / content (mirrors `shell-audit.ts`). `logBatchRetry` fires per successful retry recovery; `logBatchExhausted` fires when retries exhaust and rows are lost. `readRecentBatchRetryEvents(hours=24)` returns `{events, corrupted_lines, files_scanned, files_unreadable}` — corruption + permission errors surface to doctor, not silently swallowed. `pruneOldBatchRetryAuditFiles(daysToKeep=30)` deletes old files, called from `gbrain dream --phase purge`. File: `~/.gbrain/audit/batch-retry-YYYY-Www.jsonl` (honors `GBRAIN_AUDIT_DIR`). `summarizeError` routes error messages through the shared `redactConnectionInfo` helper from `src/core/audit/redact-connection-info.ts` BEFORE truncation so DSNs / hostnames / credentials / IPv4 octets can't leak into operator-shared JSONL dumps. Pinned by `test/audit/batch-retry-audit.test.ts` (12 cases) + `test/audit/batch-retry-redaction.test.ts` (3 privacy regressions).
- `src/core/audit/lock-renewal-audit.ts` — JSONL audit primitive for per-job lock-renewal faults. Sibling of `batch-retry-audit.ts`, built on `audit-writer.ts`. Four outcomes: `failure` (single renewLock throw, counter incremented), `success_after_failure` (recovery; emits the recovery count), `gave_up` (time-based deadline exceeded; abort fired), `executeJob_rejected` (the second unhandledRejection vector — the stored `executeJob(...).finally(...)` promise itself rejected, e.g. failJob threw during the same DB outage). Schema: `{ts, job_id, job_name, attempt?, outcome, error_message_summary?, error_code?}` plus additive v0.46 (#4145) telemetry fields (`cause?`, `lateness_ms?`, `overlap_skips?`, `load1?`, `cores?`, `via?`, `deadline_deferred?`) threaded via an optional trailing `ctx` param on the sink (compactCtx copies only DEFINED fields so absent telemetry stays absent from the JSONL). Privacy: NEVER logs `lock_token` or `job.data`; error summaries route through `redactConnectionInfo` BEFORE truncation. Defense-in-depth: every audit call inside the lock-renewal tick's catch block is wrapped in its own inner try/catch so a misbehaving audit-writer can't re-introduce the unhandledRejection bug class. `readRecentLockRenewalEvents(hours=24)` walks current + previous ISO week with corrupted-line tolerance. `pruneOldLockRenewalAuditFiles(daysToKeep=30)` is ready for future dream-cycle purge wiring. File: `~/.gbrain/audit/lock-renewal-YYYY-Www.jsonl`. Pinned by `test/audit/lock-renewal-audit.test.ts` (incl. ctx round-trip + pre-upgrade-line readback).
-- `src/core/audit/redact-connection-info.ts` — Shared pure helper. `redactConnectionInfo(text: string): string` strips Postgres connection info before any audit JSONL write: `postgres://`/`postgresql://` URLs, `host=foo`, `user=foo`, `password=foo`, `pwd=foo`, IPv4 octets — each match becomes `<REDACTED:kind>`. Negative-lookbehind/lookahead `[\w.@-]` on the IPv4 pattern defeats version-string false positives (`v3.1.4.0`, `[email protected]`) while still matching real IPs in PG errors (`(192.168.1.42)`). Order-sensitive pattern set: URL forms first so substrings inside URLs don't get double-redacted. Idempotent, pure (no I/O), hot-path-safe (regex compiled at module load). Wired into BOTH `lock-renewal-audit.ts` AND `batch-retry-audit.ts`. Known limitations: bare-quoted hostnames (`at "db.example.com"`) and usernames (`for user "postgres.foo"`) are NOT caught — the highest-value leak (the IP in those shapes) IS caught. Pinned by `test/audit/redact-connection-info.test.ts` (15 cases: all 5 patterns + Supabase fixture + ENOTFOUND fixture + version-string false-positive defense).
+- `src/core/audit/redact-connection-info.ts` — Shared pure helper. `redactConnectionInfo(text: string): string` strips Postgres connection info before any audit JSONL write: `postgres://`/`postgresql://` URLs, `host=foo`, `user=foo`, `password=foo`, `pwd=foo`, IPv4 octets — each match becomes `<REDACTED:kind>`. Negative-lookbehind/lookahead `[\w.@-]` on the IPv4 pattern defeats version-string false positives (`v3.1.4.0`, `[email protected]`) while still matching real IPs in PG errors (`(192.168.1.42)`). Order-sensitive pattern set: URL forms first so substrings inside URLs don't get double-redacted. Idempotent, pure (no I/O), hot-path-safe (regex compiled at module load). Wired into `lock-renewal-audit.ts`, `batch-retry-audit.ts`, and cli.ts's doctor DB-fallback stderr note (layered with `url-redact.ts:redactUrlsInText`). Known limitations: bare-quoted hostnames (`at "db.example.com"`) and usernames (`for user "postgres.foo"`) are NOT caught — the highest-value leak (the IP in those shapes) IS caught. Pinned by `test/audit/redact-connection-info.test.ts` (15 cases: all 5 patterns + Supabase fixture + ENOTFOUND fixture + version-string false-positive defense).
+- `src/core/url-redact.ts` — Postgres-URL + free-text credential redaction, sibling of `redact-connection-info.ts`. `redactPgUrl(url)` strips userinfo from a single postgres/postgresql URL, preserving scheme/host/port/db/query (non-URL input collapses to `<redacted-url>`). `redactUrlsInText(text)` sweeps free text (error messages, log lines) for credential shapes of any word-character scheme (the pattern is `\w+://`, so scheme names containing `+`/`-`/`.` are not matched — postgres shapes are the target): the userinfo match is greedy up to the LAST `@` in the token so a raw `@` inside a password can't leak its tail (over-redacts toward safety), and libpq keyword/value forms (`password=` / `sslpassword=`, including quoted values with spaces) are masked too; text without a credential shape passes through untouched. `redactDeep(value)` recursively redacts postgres URLs inside structured payloads about to be stringified. Consumers: the upgrade-errors + connection-events audit JSONL sites, doctor's `connection_routing` check output, and cli.ts's doctor DB-fallback stderr note (layered with `redactConnectionInfo`). CI guard: `scripts/check-pg-url-redaction.sh` fails the build when a new code path emits an unredacted postgres URL. Pinned by `test/url-redact.test.ts`.
- `src/core/minions/lock-renewal-tick.ts` — Pure extracted function from `MinionWorker.launchJob`'s setInterval body; the structural fix that closes the production unhandledRejection crash class, now carrying the #4145 verify-before-evict doctrine. Exports `runLockRenewalTick(deps, state) → Promise<TickResult>` + `resolveLockRenewalKnobs(env, lockDuration, intervalMs?) → LockRenewalKnobs` + `RenewalCallTimeoutError` + `LockRenewalTelemetryCtx`. Doctrine: a thrown/timed-out renewal is NOT evidence of loss — when the NEXT tick would land past the soft deadline (`lease - safetyMargin`, cadence-aware: `sinceLastSuccess + intervalMs >= deadline`), the tick runs ONE bounded fenced VERIFY renewal. Fenced-true → starved-but-ours, lease re-extended, counter reset (audit `success_after_failure` with `via: 'verify'`); fenced-false → CERTAIN loss → `lock_lost` (the only certain signal); verify unreachable → defer + reconnect-once (audit `failure` with `deadline_deferred: true`), aborting only past `hardEvictMs` — a LOCAL decision under uncertainty bounding blind external side effects during a total outage. Four env knobs, positive-int parsed with stderr-warn-once + default fallback, then RELATIONALLY validated (margin < lease/2, callTimeout ≤ cadence, hardEvict ≥ soft deadline — warn-once clamps): `GBRAIN_LOCK_RENEWAL_MAX_FAILURES` (default 3, audit-labeling only), `GBRAIN_LOCK_RENEWAL_CALL_TIMEOUT_MS` (default `min(lease/3, 15s)`), `GBRAIN_LOCK_RENEWAL_SAFETY_MARGIN_MS` (default `min(lease/6, 30s)`), `GBRAIN_LOCK_RENEWAL_HARD_EVICT_MS` (default `2×lease`, floored to the soft deadline; setting it TO the deadline approximates legacy abort-at-deadline). Telemetry: tick lateness (`now - lastTickFiredAt - intervalMs`, the primary local-starvation signal — interval callbacks COALESCE under a blocked loop so missed-tick counters can't measure starvation), `overlapSkips` (tickInFlight re-entrancy skips only), failure-cause classification via the named `RenewalCallTimeoutError` (`call-timeout` | `refused` | `fenced-lost`), optional `deps.loadSnapshot` (try/caught — telemetry must never throw into control flow) and `deps.onRenewalSuccess` (worker resets its event-loop-delay histogram). Elapsed-time arithmetic runs on the injected `deps.now`, which production binds to `performance.now()` (monotonic) — the local clock only schedules WHEN to verify, never WHETHER to evict. The race timeout also aborts the in-flight call via AbortSignal threaded to `renewLock` (best-effort — the fence is the correctness authority). The tick checks `state.cancelled()` at every await boundary (entry, post-resolve, post-throw, post-verify). Result is a tagged union: `should_abort` carries `{cause, latenessMs, sinceLastSuccessMs, overlapSkips, load1?, cores?}` and `lock_lost` carries `{cause: 'fenced-lost', via: 'renewal'|'verify'}`; the worker stashes the result as per-launch `abortMeta` so the grace-evict log (30s later) reports the classified cause. The in-tick verify is reconciled in-code with queue.ts's no-background-retry rationale: it is synchronous, cancelled()-guarded, and callTimeoutMs-bounded — both UPDATEs are same-token idempotent lease extensions, so a fenced row cannot gain two holders. Pinned by `test/worker-lock-renewal.test.ts` (hermetic state-machine suite incl. the fake-time #4145 incident replay, CDX-4 cadence-quantization pin, hard-backstop timelines, relational-clamp cases) + `test/e2e/worker-lock-renewal-starvation.test.ts` (real-PG foundations). `LockRenewalDeps.renewLock` carries an optional per-call `{signal}`; the timeout race aborts it so the losing UPDATE releases its slot (issue #6 abandoned-racer class).
- `src/core/minions/worker-exit-codes.ts` — single source of truth for reserved worker process exit codes, shared by the worker (sets them) and supervisor/CLI (classify them). Exports `WORKER_EXIT_RSS_WATCHDOG = 12`. The RSS watchdog drain must be self-identifying: a code-0 exit is indistinguishable from a healthy queue-drain, so the supervisor's `code===0 → clean_exit` classifier never counted it and a respawn loop stayed invisible. A distinct code makes the drain `likely_cause=rss_watchdog`. Code 12 is deliberately outside {0 clean, 1 runtime_error} and the 128+N signal range. Also reserves the `jobs run-child` codes: 13 usage/PGLite, 14 not-claimed/token-mismatch, 15 result-write-failed (result-file presence, not the exit code, classifies the normal path).
- `src/core/minions/rss-default.ts` — cgroup-aware auto-sized default for the worker RSS watchdog cap. `resolveDefaultMaxRssMb(opts?)` / `describeDefaultMaxRss(opts?)` (provenance for the startup log) / `readCgroupMemLimitBytes(readFile?)`. Replaces a flat 2048MB default at every spawn site (`jobs work`, `jobs supervisor`, autopilot, `MinionSupervisor`). Formula `clamp(round(0.5 × basisMB), 4096, 16384)` where `basis = min(cgroupLimit, totalmem)`. LOAD-BEARING NUANCE: plain `os.totalmem()` reports HOST RAM, so in a 4GB cgroup on a 126GB host it would pick 16GB, the watchdog would never fire, and the kernel OOM-killer would SIGKILL at 4GB. The cap MUST sit below the real ceiling so the graceful drain (distinct exit code, loud log) beats the kernel's silent kill; the 4096 floor applies only when it stays below the basis. Reads cgroup v2 `/sys/fs/cgroup/memory.max` (literal `max` = unlimited) then v1 `/sys/fs/cgroup/memory/memory.limit_in_bytes`. Explicit `--max-rss` (including `0` to disable) always wins. Pinned by `test/rss-default.test.ts`.
@@ -218,7 +221,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/source-config-sql.ts` + `src/core/sources-load.ts` — canonical recovery for historical non-object `sources.config` values. The application reader unwraps nested JSON strings and merges recoverable array fragments left-to-right; the shared SQL expression mirrors that policy atomically for both engines, source config updates, archive/restore, and the paste-ready `source_config_shape` doctor repair. `localFederatedSourceIds` reads config through the same parser so stdio/CLI federation cannot silently disagree with `sources list`. `sourceConfigHasRemoteUrl` uses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to `{}` rather than throwing. Pinned by `test/sources-load.test.ts`, `test/job-pull-policy.test.ts`, `test/list-all-sources.test.ts`, `test/local-federated-search-scope.test.ts`, `test/destructive-guard.test.ts`, and `test/doctor-source-config-shape.test.ts`.
- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'`, auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `src/commands/sync.ts:1497-1519` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (14 cases), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`).
- `src/core/migrate.ts` — schema-migration runner. Owns the `MIGRATIONS` array (source of truth for schema DDL). `Migration` interface carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; mirror in pglite-schema.ts + schema.sql + bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (#1941, opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (#2073, idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — NULL never matched a scoped `AND source_id = …` filter so scoped `code-callers`/`code-callees` returned 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (#4152, additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes). The dedup-index self-heal (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) is NOT version-gated: `runMigrations` invokes `repairTimelineDedupIndex` on every pass (including the no-pending early-return path) because a merge-renumbered migration can leave the version counter past the index change while the index stays the old shape. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice).
-- `src/cli.ts` — `dream` dispatch at lines 1063-1080 binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` to stderr before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved. Pinned by `test/cli-dream-engine-warn.test.ts` (2 subprocess cases against good + bad DATABASE_URL).
+- `src/cli.ts` — no-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`).
- `skills/conventions/brain-routing.md` — agent-facing convention skill documenting the canonical 6-tier source resolution chain (flag → env → dotfile → local_path → brain_default → seed_default) with paste-ready decision tables. Linked from CLAUDE.md's "Two organizational axes" section and from `gbrain sources current`'s hint output.
- `test/operations-trust-boundary.test.ts` + `scripts/check-operations-filter-bypass.sh` — operations trust-boundary contract coverage. Pure assertions over all 74 ops (every op has a scope annotation; every mutating op has a non-read scope; `localOnly: true` ops are excluded from `operations.filter(op => !op.localOnly)`; the seven historically-sensitive localOnly ops snapshot-pinned by name) plus targeted handler-invocation regressions for the two historically-broken HTTP-callable classes: `submit_job` with `name='shell'` + `ctx.remote=true` MUST reject (the HTTP MCP shell-job RCE class), and `search_by_image` with `image_path` + `ctx.remote=true` MUST reject (the P0 image-leak class). `file_upload` and `sync_brain` omitted from handler-invocation tests because they're `localOnly: true` (that path would test an impossible production scenario). The shell guard greps `src/` for any module importing the `operations` value outside the canonical filter site at `src/commands/serve-http.ts` (three import shapes: destructured, aliased, namespace), with an explicit 10-entry allow-list + a literal-string check that `serve-http.ts` still contains `operations.filter(op => !op.localOnly)`. Wired into `bun run verify`.
- `src/core/content-sanity.ts` — pure assessor for the content-sanity defense. `assessContent(content, opts): SanityVerdict` returns one of `ok | warn_oversize | hard_block_junk_pattern | soft_block_oversize` with `{reason, bytes, matched_pattern_name?}`. Six built-in junk patterns (Cloudflare challenge dumps, CAPTCHAs, 403 dumps, bare error-page titles) compiled at module load; operator literal substrings via `loadOperatorLiterals()` from `src/core/content-sanity-literals.ts`. `ContentSanityBlockError` tagged class is the typed throw shape every wrapper site (`gbrain import`, `put_page` MCP op, `gbrain sync`, `/ingest` webhook) catches via the existing exception flow. The bytes-parity contract pins `Buffer.byteLength(content, 'utf8')` against the embedder's actual byte count so a 499K-byte page can't be soft-blocked on assessment then overflow on embed. Knob resolution chain env > file (`~/.gbrain/config.json`) > DB > defaults. Four knobs: `content_sanity.bytes_warn` (50_000), `content_sanity.bytes_block` (500_000), `content_sanity.junk_patterns_enabled` (true), `content_sanity.disabled` (false; `GBRAIN_NO_SANITY=1` is the loud-stderr kill-switch). New `assessContentSanity(opts): SanityAssessment` returns the three-tier disposition (`shouldQuarantine` / `shouldFlag` + reason/detail) consumed by `importFromContent` and `gbrain quarantine scan`; adds the fuzzy prose-vs-markup ratio pass (markup chars / total above `max_markup_ratio`; code pages exempt; gated by `prose_check_enabled`) on top of the byte + junk-pattern passes. Three more knobs: `content_sanity.junk_disposition` (`quarantine` default | `reject`; no env override — a destructive flip belongs in explicit config), `content_sanity.max_markup_ratio` (0.85, env `GBRAIN_MAX_MARKUP_RATIO`, clamped `(0,1]`), `content_sanity.prose_check_enabled` (true). Pinned by `test/content-sanity.test.ts`. new `assessContentSanity(opts): SanityAssessment` returns the three-tier disposition (`shouldQuarantine` / `shouldFlag` + reason/detail) consumed by `importFromContent` and `gbrain quarantine scan`. Adds the fuzzy prose-vs-markup ratio pass (markup chars / total chars above `max_markup_ratio`, default 0.85; code pages exempt; gated by `prose_check_enabled`, default true) on top of the byte + junk-pattern passes. Three config knobs: `content_sanity.junk_disposition` (`quarantine` default | `reject`; no env override), `content_sanity.max_markup_ratio` (0.85, env `GBRAIN_MAX_MARKUP_RATIO`, clamped `(0,1]`), `content_sanity.prose_check_enabled` (true). Same env > file > DB > defaults resolution chain. Pinned by `test/content-sanity.test.ts`.
@@ -351,7 +354,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `scripts/build-pglite-snapshot.ts` — `bun run build:pglite-snapshot`: bakes a post-`initSchema()` PGLite data dir into `test/fixtures/pglite-snapshot.tar` + a version file (schema hash line, then `dims=`/`model=` lines recording the embedding shape it was baked with). Idempotent (hash short-circuit ~40ms when fresh; rebuilds stale) and concurrency-safe (atomic `mkdir` lock at `test/fixtures/.pglite-snapshot.lock` with staleness-verified takeover — a live lock is never stolen; tar written first, version file last, so a crash can't leave a fresh-looking torn fixture; waiter bounded by `GBRAIN_SNAPSHOT_LOCK_TIMEOUT_MS`, default 120000; an exhausted waiter facing a still-live lock proceeds unlocked as a last resort — the loader's hash/shape gate validates the version file, not the tar bytes). Called through the shared `ensure_pglite_snapshot` helper in `scripts/lib/test-env.sh` (also home of `detect_cpus` + `detect_available_mem_mb`; sourced by `run-unit-parallel.sh`, `test-shard.sh`, `run-slow-tests.sh`, `run-serial-tests.sh`, and `run-verify-parallel.sh` — default-on, opt out `GBRAIN_NO_SNAPSHOT=1`, no-op when a parent already exported the path, non-fatal on build failure with a one-line "active" echo so a silent cold-init fallback stays visible) and directly by `scripts/ci-local.sh`; every caller exports `GBRAIN_PGLITE_SNAPSHOT`. The loader side is `tryLoadSnapshot` + `computeSnapshotSchemaHash` (exported from `src/core/pglite-engine.ts`): the hash folds `PGLITE_SCHEMA_SQL`, every migration's `sql` + `sqlFor.pglite`, AND each migration `handler`'s function source (handler-only migrations are invisible to a sql-only hash); any hash or embedding-shape mismatch warns once and falls through to normal cold init — the snapshot is an optimization, never authoritative. The loader memoizes per process: the schema hash computes once (MIGRATIONS + PGLITE_SCHEMA_SQL are static for the process lifetime) and the version file + ~42MB tar are read once per (path, process) instead of once per engine construction (a full suite constructs 600+ engines); a terminally-unusable path (missing/stale/torn) memoizes as null and is never retried, the tar blob loads lazily only after the FIRST caller passes the shape gate, and the dims/model shape gate itself is deliberately NOT memoized (tests reconfigure the gateway mid-process — a mismatched engine must still fall back to cold init). Accepted limitation: a snapshot rewritten mid-process is not observed; the only writer runs before test fan-out. Test seams `__snapshotMemoStatsForTests`/`__resetSnapshotMemoForTests`. Pinned by `test/snapshot-shape-guard.test.ts`.
- `docker-compose.ci.yml` + `scripts/ci-local.sh` — Local CI gate. `bun run ci:local` spins up four `pgvector/pgvector:pg16` services (postgres-1..4) + `oven/bun:1` with named volumes (`gbrain-ci-pg-data-{1..4}`, `gbrain-ci-node-modules`, `gbrain-ci-bun-cache`), runs gitleaks on host, smoke-tests `scripts/run-e2e.sh` argv handling, runs guards + typecheck, then the Tier 1 default: 4-shard parallel unit + E2E (`xargs -P4`, one Postgres per shard; unit phase keeps `DATABASE_URL` unset). `--no-shard` falls back to the legacy unsharded sequential flow (debug aid); `--diff` runs the diff-aware selector unsharded. Also runs a `pgbouncer` service (`edoburu/pgbouncer`, `POOL_MODE: transaction`, `AUTH_TYPE: plain` — pg16 stores SCRAM verifiers, so the userlist must hold the plaintext password; `IGNORE_STARTUP_PARAMETERS` whitelists gbrain's `statement_timeout`/`idle_in_transaction_session_timeout` startup params the way the Supabase pooler does) fronting postgres-1 on host port `GBRAIN_CI_PGBOUNCER_PORT` (default 6543); every E2E invocation exports `GBRAIN_PGBOUNCER_URL` (pooled; dedicated `gbrain_pgbouncer` database so it never races the `gbrain_test` TRUNCATE fixtures) + `GBRAIN_PGBOUNCER_DIRECT_URL`, consumed by `test/e2e/pgbouncer-teardown.test.ts` — the transaction-mode teardown bug class (#1972/#2015/#2084) reproduced in the local gate instead of only in production. `--no-pull` skips upstream pulls; `--clean` nukes named volumes. Postgres host port defaults to 5434; override with `GBRAIN_CI_PG_PORT=NNNN`. Stronger gate than PR CI's 2-file Tier 1 set.
- `scripts/select-e2e.ts` + `scripts/e2e-test-map.ts` — Diff-aware E2E test selector. Reads three git sources (committed `origin/master...HEAD`, working-tree `HEAD`, and `git ls-files --others --exclude-standard` for untracked NOT-gitignored files), classifies as EMPTY / DOC_ONLY / SRC. Fail-closed: EMPTY → all files; DOC_ONLY (every path matches the README/CLAUDE/AGENTS/CHANGELOG/TODOS allowlist) → empty stdout; SRC → escape-hatch paths (schema, package.json, skills/) trigger all, else the hand-tuned `E2E_TEST_MAP` glob narrows, and an unmapped src/ change still emits ALL files (never silently nothing). Pure-function exports `selectTests`, `classify`, `matchGlob`. `bun run ci:select-e2e` prints the current selection on stdout. `test/select-e2e.test.ts` covers all 4 branches plus 3 regression guards (skills/, untracked files, unmapped src/) — 24 cases.
-- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL per #3485, so this lane must carry it). This wrapper is the database-URL opt-in boundary (#3485): it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (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), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable.
+- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL per #3485, so this lane must carry it). This wrapper is the database-URL opt-in boundary (#3485): it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (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), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (`skills.test.ts` gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare `bun` (no outer cap) is the fallback when neither timeout binary is installed.
- `scripts/llms-config.ts` + `scripts/build-llms.ts` — Generator for `llms.txt` (llmstxt.org-spec web index) + `llms-full.txt` (inlined single-fetch bundle). Curated config drives both. Run `bun run build:llms` after adding a new doc. `LLMS_REPO_BASE` env lets forks regenerate with their own URL base. `FULL_SIZE_BUDGET` (600KB) caps the inline bundle; generator WARNs if exceeded. Committed output has no runtime consumer; committed for GitHub browsing and fork-safe fetching.
- `AGENTS.md` — Local-clone entry point for non-Claude agents (Codex, Cursor, OpenClaw, Aider). Mirrors `CLAUDE.md` intent via relative links. Claude Code keeps using `CLAUDE.md`.
- `docs/UPGRADING_DOWNSTREAM_AGENTS.md` — Patches for downstream agent skill forks to apply when upgrading. Each release appends a new section; includes diffs for brain-ops, meeting-ingestion, signal-detector, enrich.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index c646013e46..886a020b25 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.7.0",
+ "version": "0.46.8.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 1ec5091188..b8c7ff76e8 100644
--- a/package.json
+++ b/package.json
@@ -165,7 +165,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.7.0",
+ "version": "0.46.8.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin/README.md b/plugin/README.md
index c287c5c895..d1aa9a9b8c 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.7.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.8.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/run-slow-tests.sh b/scripts/run-slow-tests.sh
index 67ac5f1cfc..fd1753d987 100755
--- a/scripts/run-slow-tests.sh
+++ b/scripts/run-slow-tests.sh
@@ -9,6 +9,11 @@ set -euo pipefail
# 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
+# An ambient GBRAIN_HOME (a dev shell configured for a real brain) must not
+# reach unit tests either: the gbrain-home-preload respects a pre-set value
+# (the e2e wrapper needs that), so strip it at this boundary and let the
+# preload allocate per-run scratch instead.
+unset GBRAIN_HOME
cd "$(dirname "$0")/.."
. scripts/lib/test-env.sh
diff --git a/scripts/run-unit-parallel.sh b/scripts/run-unit-parallel.sh
index e77cce1d4a..3958ddcea5 100755
--- a/scripts/run-unit-parallel.sh
+++ b/scripts/run-unit-parallel.sh
@@ -48,6 +48,11 @@ set -uo pipefail
# 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
+# An ambient GBRAIN_HOME (a dev shell configured for a real brain) must not
+# reach unit tests either: the gbrain-home-preload respects a pre-set value
+# (the e2e wrapper needs that), so strip it at this boundary and let the
+# preload allocate per-run scratch instead.
+unset GBRAIN_HOME
cd "$(dirname "$0")/.."
diff --git a/scripts/run-unit-shard.sh b/scripts/run-unit-shard.sh
index 7c6fb97bc2..51c33c7144 100755
--- a/scripts/run-unit-shard.sh
+++ b/scripts/run-unit-shard.sh
@@ -18,6 +18,11 @@ set -euo pipefail
# 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
+# An ambient GBRAIN_HOME (a dev shell configured for a real brain) must not
+# reach unit tests either: the gbrain-home-preload respects a pre-set value
+# (the e2e wrapper needs that), so strip it at this boundary and let the
+# preload allocate per-run scratch instead.
+unset GBRAIN_HOME
cd "$(dirname "$0")/.."
diff --git a/src/cli.ts b/src/cli.ts
index 450b039244..ff2cb8326d 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -2,12 +2,7 @@
import { installSigchldHandler } from './core/zombie-reap.ts';
installSigchldHandler();
-// v0.41.6.0 D5: cleanup registry + signal handlers for SIGTERM/SIGHUP/SIGPIPE/
-// uncaughtException. NOT SIGINT (the existing AbortController path at :254
-// owns SIGINT). Installed at module load so locks acquired during boot
-// (e.g. during connectEngine's schema-probe path) are covered too.
import { installSignalHandlers as installCleanupSignalHandlers } from './core/process-cleanup.ts';
-installCleanupSignalHandlers();
import { readFileSync, existsSync, unlinkSync, fstatSync } from 'fs';
import { spawn } from 'child_process';
@@ -1993,8 +1988,18 @@ async function handleCliOnly(command: string, args: string[]) {
try {
eng = await connectEngine();
await runDoctor(eng, args);
- } catch {
- // DB unavailable — still run filesystem checks
+ } catch (e) {
+ // DB unavailable OR the DB-backed run threw — still run filesystem
+ // checks. Say so on stderr: a silent fallback looks identical to a
+ // healthy DB-backed run (minus the DB checks), which has misread as
+ // "doctor is broken". Scrub the message through BOTH redactors —
+ // connection-info (hosts/IPs/users/quoted libpq passwords) and the
+ // URL-userinfo sweep — because doctor output is exactly what users
+ // paste into issues and CI logs.
+ const { redactUrlsInText } = await import('./core/url-redact.ts');
+ const { redactConnectionInfo } = await import('./core/audit/redact-connection-info.ts');
+ const safeMsg = redactConnectionInfo(redactUrlsInText(e instanceof Error ? e.message : String(e)));
+ console.error(`[doctor] DB-backed doctor run failed (${safeMsg}) — falling back to filesystem-only checks`);
await runDoctor(null, args, getDbUrlSource());
} finally {
if (eng) await finishCliTeardown({ engine: eng });
@@ -3311,6 +3316,15 @@ Run gbrain <command> --help for command-specific help.
// process alive. A fatal error still exits 1 for every command, daemons
// included (matches the prior unconditional process.exit(1) on rejection).
if (import.meta.main) {
+ // v0.41.6.0 D5: cleanup registry + signal handlers for SIGTERM/SIGHUP/SIGPIPE/
+ // uncaughtException. NOT SIGINT (the existing AbortController path owns SIGINT).
+ // Installed before main() so locks acquired during boot (e.g. connectEngine's
+ // schema-probe path) are covered. Gated on import.meta.main — nothing at module
+ // scope acquires locks, and installing at module load leaked a process-wide
+ // SIGTERM→exit(143) handler into any process that merely IMPORTS this module
+ // (bun test runners died mid-suite when a test emitted a synthetic SIGTERM).
+ // Spawned/compiled CLI processes are entrypoints, so they still install.
+ installCleanupSignalHandlers();
main().then(
() => {
if (shouldForceExitAfterMain()) flushThenExit(currentExitCode());
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index b0777335b8..ae847b8d76 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -568,8 +568,9 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
// brain. Two exit paths must both close the engine:
// - autopilot's own shutdown() below (owns SIGINT + internal stops like
// max_crashes / cycle-failure-cap), and
- // - process-cleanup's SIGTERM handler (installed at cli.ts module load;
- // it runs the cleanup registry with a 3s deadline and then exits) —
+ // - process-cleanup's SIGTERM handler (installed inside cli.ts's
+ // import.meta.main seam before main() dispatches; it runs the cleanup
+ // registry with a 3s deadline and then exits) —
// which is why closeEngine is ALSO registered there.
// closeEngine aborts the in-flight inline cycle (runCycle checks the
// signal between phases and threads it into phase sub-work), gives it a
diff --git a/src/core/bootstrap/render.ts b/src/core/bootstrap/render.ts
index af3b141788..abd53465c4 100644
--- a/src/core/bootstrap/render.ts
+++ b/src/core/bootstrap/render.ts
@@ -287,9 +287,30 @@ export function renderWorkspace(workspaceDir: string, opts: RenderOptions = {}):
// Phase 2 — write, never clobbering without force [plan: render never
// clobbers]. Backups for a forced overwrite land under one per-run
- // timestamp dir.
+ // timestamp dir. The stamp has MILLISECOND granularity, so two forced
+ // renders of the same workspace within the same millisecond (a fast CI
+ // runner re-rendering back-to-back) would collide on the exclusive `wx`
+ // backup write with EEXIST. Claim the stamp dir ATOMICALLY (non-recursive
+ // mkdir; EEXIST → bump a numeric suffix) lazily on the first backup, so
+ // every render call owns a distinct backup dir.
const result: RenderResult = { written: [], skipped: [], backups: [] };
- const backupStamp = new Date().toISOString().replace(/[:.]/g, '-');
+ let backupStamp: string | null = null;
+ const claimBackupStamp = (): string => {
+ if (backupStamp) return backupStamp;
+ const root = join(workspaceDir, '.gbrain-bootstrap-backups');
+ mkdirSync(root, { recursive: true });
+ const base = new Date().toISOString().replace(/[:.]/g, '-');
+ for (let n = 0; ; n++) {
+ const candidate = n === 0 ? base : `${base}-${n}`;
+ try {
+ mkdirSync(join(root, candidate)); // non-recursive: EEXIST = taken
+ backupStamp = candidate;
+ return candidate;
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
+ }
+ }
+ };
for (const { dest, content } of rendered) {
if (!isBootstrapRenderDest(dest)) {
@@ -304,10 +325,11 @@ export function renderWorkspace(workspaceDir: string, opts: RenderOptions = {}):
result.skipped.push(dest);
continue;
}
- const backupAbs = join(workspaceDir, '.gbrain-bootstrap-backups', backupStamp, dest);
+ const stamp = claimBackupStamp();
+ const backupAbs = join(workspaceDir, '.gbrain-bootstrap-backups', stamp, dest);
mkdirSync(dirname(backupAbs), { recursive: true });
writeFileSync(backupAbs, readFileSync(abs), { flag: 'wx' });
- result.backups.push(join('.gbrain-bootstrap-backups', backupStamp, dest));
+ result.backups.push(join('.gbrain-bootstrap-backups', stamp, dest));
}
mkdirSync(dirname(abs), { recursive: true });
const tmp = `${abs}.tmp-${process.pid}`;
diff --git a/src/core/preferences.ts b/src/core/preferences.ts
index 3d6b251253..65f96c6bb3 100644
--- a/src/core/preferences.ts
+++ b/src/core/preferences.ts
@@ -8,41 +8,26 @@
* Also houses ~/.gbrain/migrations/completed.jsonl append helper.
*/
-import { readFileSync, writeFileSync, renameSync, chmodSync, mkdtempSync, rmSync, existsSync, mkdirSync, appendFileSync } from 'fs';
-import { join } from 'path';
-import { homedir } from 'os';
-
-function home(): string {
- // `os.homedir()` in Bun caches its initial value and ignores later
- // `process.env.HOME` mutations, which breaks test isolation and any
- // workflow that needs to run against a specific $HOME (CI, scripted installs).
- // Prefer the env var; fall back to the cached OS value. Matches the existing
- // `src/commands/upgrade.ts` pattern.
- //
- // NOTE: prefsDir() and migrationsDir() route through gbrainPath() (which
- // honors GBRAIN_HOME), so this fallback is only used by code paths that
- // want $HOME directly (none in this file as of v0.30.3).
- return process.env.HOME || homedir();
-}
+import { readFileSync, writeFileSync, renameSync, chmodSync, mkdtempSync, rmSync, existsSync, mkdirSync, appendFileSync, copyFileSync, linkSync } from 'fs';
+import { join, dirname } from 'path';
+import { gbrainPath } from './config.ts';
/**
- * GBRAIN_HOME-aware override for the .gbrain directory. When the env var
- * is set, this returns it directly (so the directory is GBRAIN_HOME itself,
- * matching the convention `src/core/config.ts:gbrainPath` enforces).
- * When unset, falls back to `<home>/.gbrain` so legacy callers and the
- * doctor's filesystem-only checks keep working.
+ * GBRAIN_HOME-aware resolution of the .gbrain directory — delegates to
+ * `src/core/config.ts:gbrainPath()` so preferences + the migration ledger
+ * follow the SAME convention as config resolution: GBRAIN_HOME is a PARENT
+ * dir and '.gbrain' is always appended (`GBRAIN_HOME=/tmp/x` →
+ * `/tmp/x/.gbrain`). The previous local implementation returned GBRAIN_HOME
+ * directly — while its own doc comment claimed to match gbrainPath — so
+ * with GBRAIN_HOME set, config lived at `$GBRAIN_HOME/.gbrain/config.json`
+ * but the migration ledger at `$GBRAIN_HOME/migrations/completed.jsonl`,
+ * splitting one logical home across two roots.
*
- * Without this, `~/.gbrain/migrations/completed.jsonl` is the only path
- * doctor reads on filesystem checks — the test isolation contract that
- * `gbrainPath()` provides for everywhere else doesn't extend here.
+ * When unset, gbrainPath falls back to `<home>/.gbrain` so legacy callers
+ * and doctor's filesystem-only checks keep working.
*/
function gbrainDir(): string {
- const override = process.env.GBRAIN_HOME;
- if (override) {
- const trimmed = override.trim();
- if (trimmed) return trimmed;
- }
- return join(home(), '.gbrain');
+ return gbrainPath();
}
export type MinionMode = 'always' | 'pain_triggered' | 'off';
@@ -88,6 +73,83 @@ function prefsPath(): string { return join(prefsDir(), 'preferences.json'); }
function migrationsDir(): string { return join(gbrainDir(), 'migrations'); }
function completedJsonlPath(): string { return join(migrationsDir(), 'completed.jsonl'); }
+/**
+ * One-time copy-forward from the pre-unification layout. Before gbrainDir()
+ * delegated to gbrainPath(), an install running with GBRAIN_HOME set kept
+ * these files at $GBRAIN_HOME/<relPath> directly (no '.gbrain' segment).
+ * Losing them on upgrade would silently re-run completed migrations and —
+ * worse — drop an explicit `minion_mode: off` opt-out back to the default.
+ * COPY (not move) so a binary rollback still finds the legacy file. Only
+ * fires when GBRAIN_HOME is set, the new path is absent, and the legacy
+ * file exists. Returns the path the caller should READ: the canonical path
+ * normally; the legacy path in place when a valid legacy file exists but
+ * could not be copied (read-only home, ENOSPC) — so a transient failure
+ * never drops an opt-out; an unparseable legacy prefs file is treated as
+ * missing rather than poisoning the canonical path.
+ *
+ * Known limitation (accepted): the copy is one-shot. During a mixed-version
+ * window (old binary still writing the legacy path after a new binary
+ * snapshot), post-snapshot legacy writes are not merged — the canonical
+ * path wins from then on. The exposed population (GBRAIN_HOME production
+ * installs × concurrent mixed-version writers) is tiny, and a merge engine
+ * here would cost more risk than the window it closes.
+ */
+/** One warning per (process, legacy path) — a persistently unmigratable file
+ * would otherwise spam every command until the operator intervenes. */
+const migrateWarned = new Set<string>();
+
+function copyForwardLegacyFile(
+ newPath: string,
+ relPath: string,
+ opts?: { validateJson?: boolean },
+): string {
+ const override = process.env.GBRAIN_HOME?.trim();
+ if (!override || existsSync(newPath)) return newPath;
+ const legacyPath = join(override, relPath);
+ if (legacyPath === newPath || !existsSync(legacyPath)) return newPath;
+ let tmpDir: string | null = null;
+ try {
+ // A foreign/corrupted legacy preferences.json must not poison the
+ // canonical path forever (loadPreferences JSON.parse throws and callers
+ // like autopilot boot unguarded); treat unparseable as missing. The
+ // ledger needs no validation — its reader skips malformed lines.
+ if (opts?.validateJson) {
+ JSON.parse(readFileSync(legacyPath, 'utf-8'));
+ }
+ mkdirSync(dirname(newPath), { recursive: true });
+ // Atomic install, matching savePreferences' discipline: copy into a
+ // sibling temp dir, then LINK into place. linkSync fails EEXIST if a
+ // concurrent process migrated (or appended) first — never truncates a
+ // reader's view mid-copy, never clobbers a concurrent append.
+ tmpDir = mkdtempSync(join(dirname(newPath), '.migrate-tmp-'));
+ const tmpFile = join(tmpDir, 'file');
+ copyFileSync(legacyPath, tmpFile);
+ try { chmodSync(tmpFile, 0o600); } catch { /* best-effort on exotic FS */ }
+ try {
+ linkSync(tmpFile, newPath);
+ console.error(`[preferences] migrated ${relPath} from legacy $GBRAIN_HOME layout (${legacyPath} → ${newPath}); legacy copy kept for rollback`);
+ } catch (linkErr) {
+ if ((linkErr as NodeJS.ErrnoException).code !== 'EEXIST') throw linkErr;
+ // Another process won the migration race — its copy stands.
+ }
+ return newPath;
+ } catch (err) {
+ // Copy failed (read-only $GBRAIN_HOME, ENOSPC, foreign JSON). Never
+ // silent, but warn once per process — and for a VALID-but-uncopyable
+ // legacy file, hand the caller the legacy path to READ IN PLACE so a
+ // transient failure can't silently drop an opt-out or migration
+ // history (the pre-change code read this path with no write needed).
+ const code = (err as NodeJS.ErrnoException).code ?? (err instanceof SyntaxError ? 'invalid-json' : 'error');
+ if (!migrateWarned.has(legacyPath)) {
+ migrateWarned.add(legacyPath);
+ console.error(`[preferences] found legacy ${relPath} at ${legacyPath} but could not migrate it (${code}); ${err instanceof SyntaxError ? 'treating as missing' : 'reading it in place'}`);
+ }
+ return err instanceof SyntaxError ? newPath : legacyPath;
+ } finally {
+ if (tmpDir) { try { rmSync(tmpDir, { recursive: true, force: true }); } catch { /* best-effort */ } }
+ }
+}
+
/** Validate that a value is a recognized minion mode. Throws with the allowed list. */
export function validateMinionMode(value: unknown): asserts value is MinionMode {
if (typeof value !== 'string' || !VALID_MODES.includes(value as MinionMode)) {
@@ -102,7 +164,7 @@ export function validateMinionMode(value: unknown): asserts value is MinionMode
* Malformed JSON throws; caller can catch if they want graceful fallback.
*/
export function loadPreferences(): Preferences {
- const path = prefsPath();
+ const path = copyForwardLegacyFile(prefsPath(), 'preferences.json', { validateJson: true });
if (!existsSync(path)) return {};
const raw = readFileSync(path, 'utf-8');
const parsed = JSON.parse(raw) as Preferences;
@@ -116,6 +178,10 @@ export function loadPreferences(): Preferences {
export function savePreferences(prefs: Preferences): void {
if (prefs.minion_mode !== undefined) validateMinionMode(prefs.minion_mode);
+ // No-op when the new path already exists; otherwise ensures a fresh save
+ // doesn't shadow un-migrated legacy prefs (the save below would win, but
+ // the migration log line should still fire once for observability).
+ copyForwardLegacyFile(prefsPath(), 'preferences.json', { validateJson: true });
const dir = prefsDir();
mkdirSync(dir, { recursive: true });
@@ -142,6 +208,13 @@ export function savePreferences(prefs: Preferences): void {
*/
export function appendCompletedMigration(entry: CompletedMigrationEntry): void {
if (!entry.version) throw new Error('appendCompletedMigration: version required');
+ // Copy-forward BEFORE any append: a partial/retry append that skipped the
+ // guard below would otherwise create a fresh ledger at the new path and
+ // permanently shadow the un-migrated legacy history. Appends target the
+ // SAME path reads resolve to — when copy-forward degraded to
+ // read-legacy-in-place (linkless FS), appending to the canonical path
+ // would split the ledger and hide the legacy history from readers.
+ const ledgerPath = copyForwardLegacyFile(completedJsonlPath(), join('migrations', 'completed.jsonl'));
if (entry.status !== 'complete' && entry.status !== 'partial' && entry.status !== 'retry') {
throw new Error(`appendCompletedMigration: status must be 'complete', 'partial', or 'retry', got "${entry.status}"`);
}
@@ -161,14 +234,16 @@ export function appendCompletedMigration(entry: CompletedMigrationEntry): void {
ts: new Date().toISOString(),
...entry,
};
- const dir = migrationsDir();
- mkdirSync(dir, { recursive: true });
- appendFileSync(completedJsonlPath(), JSON.stringify(full) + '\n');
+ mkdirSync(dirname(ledgerPath), { recursive: true });
+ // The top-of-function copy-forward is load-bearing for partial/retry
+ // appends (the 'complete' idempotency guard also routes through
+ // loadCompletedMigrations, but that guard is status-gated).
+ appendFileSync(ledgerPath, JSON.stringify(full) + '\n');
}
/** Read the completed.jsonl file, skipping malformed lines with a warning to stderr. */
export function loadCompletedMigrations(): CompletedMigrationEntry[] {
- const path = completedJsonlPath();
+ const path = copyForwardLegacyFile(completedJsonlPath(), join('migrations', 'completed.jsonl'));
if (!existsSync(path)) return [];
const raw = readFileSync(path, 'utf-8');
const out: CompletedMigrationEntry[] = [];
diff --git a/src/core/process-cleanup.ts b/src/core/process-cleanup.ts
index 81e0de9e75..dc78d133d7 100644
--- a/src/core/process-cleanup.ts
+++ b/src/core/process-cleanup.ts
@@ -17,7 +17,7 @@
*
* - Signal scope: SIGTERM, SIGHUP, SIGPIPE, uncaughtException,
* unhandledRejection. **NOT SIGINT** — gbrain has an existing
- * SIGINT-via-AbortController path at cli.ts:254 that propagates
+ * SIGINT-via-AbortController path in cli.ts that propagates
* abort to in-flight operations (clean cancel). Installing cleanup
* on SIGINT here would preempt that flow. Lock release on user
* cancel belongs in the AbortController path, not in a parallel
@@ -52,6 +52,16 @@ interface CleanupEntry {
const registry = new Map<symbol, CleanupEntry>();
let installed = false;
let cleanupInFlight = false;
+/** Refs to every listener attached by installSignalHandlers, keyed by
+ * target+event, so _resetForTests can DETACH them — without this, a test
+ * that installs and "resets" leaves a live SIGTERM→exit(143) listener on
+ * the shared bun test runner, and any later synthetic
+ * `process.emit('SIGTERM')` kills the entire suite. */
+const installedListeners: Array<{
+ target: NodeJS.Process | NodeJS.WriteStream;
+ event: string;
+ fn: (...args: never[]) => void;
+}> = [];
/**
* Register a cleanup callback. Returns a deregister handle (idempotent
@@ -122,10 +132,13 @@ async function runCleanupPass(): Promise<void> {
/**
* Install signal handlers + the EPIPE-on-stdout handler. Idempotent
- * (second call is NO-OP). MUST be called once at CLI module load AFTER
- * any existing signal handlers (so we don't preempt the SIGINT
- * AbortController at cli.ts:254 — we don't listen to SIGINT here, but
- * documenting the install order keeps future maintainers aware).
+ * (second call is NO-OP). MUST be called once from the CLI ENTRYPOINT —
+ * inside cli.ts's `import.meta.main` seam, before main() dispatches —
+ * and NOT at module load: a module-load install leaks a process-wide
+ * SIGTERM→exit(143) handler into any process that merely imports cli.ts
+ * (a bun test runner died mid-suite when a test emitted a synthetic
+ * SIGTERM). The SIGINT AbortController path in cli.ts stays untouched —
+ * we don't listen to SIGINT here.
*/
export function installSignalHandlers(): void {
if (installed) return;
@@ -142,19 +155,28 @@ export function installSignalHandlers(): void {
});
};
- process.on('SIGTERM', () => handleSignal('SIGTERM'));
- process.on('SIGHUP', () => handleSignal('SIGHUP'));
+ const attach = (
+ target: NodeJS.Process | NodeJS.WriteStream,
+ event: string,
+ fn: (...args: never[]) => void,
+ ): void => {
+ (target as NodeJS.Process).on(event as 'exit', fn as () => void);
+ installedListeners.push({ target, event, fn });
+ };
+
+ attach(process, 'SIGTERM', () => handleSignal('SIGTERM'));
+ attach(process, 'SIGHUP', () => handleSignal('SIGHUP'));
// SIGPIPE in Node is rarely raised directly (Node ignores it by default
// and surfaces an EPIPE write error on the stream instead). Listen anyway
// for environments where it does fire.
- process.on('SIGPIPE', () => handleSignal('SIGPIPE'));
+ attach(process, 'SIGPIPE', () => handleSignal('SIGPIPE'));
- process.on('uncaughtException', (err) => {
+ attach(process, 'uncaughtException', (err: unknown) => {
try { process.stderr.write(`[uncaughtException] ${err instanceof Error ? err.stack ?? err.message : err}\n`); }
catch { /* stderr might be broken */ }
void runCleanupPass().finally(() => process.exit(1));
});
- process.on('unhandledRejection', (reason) => {
+ attach(process, 'unhandledRejection', (reason: unknown) => {
try { process.stderr.write(`[unhandledRejection] ${reason instanceof Error ? reason.stack ?? reason.message : reason}\n`); }
catch { /* stderr might be broken */ }
void runCleanupPass().finally(() => process.exit(1));
@@ -162,14 +184,14 @@ export function installSignalHandlers(): void {
// EPIPE on stdout — the canonical `gbrain sync | head -N` case. Route
// through the cleanup pass so locks release BEFORE we exit.
- process.stdout.on('error', (err: NodeJS.ErrnoException) => {
+ attach(process.stdout, 'error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EPIPE') {
void triggerCleanupAndExit(0);
}
});
// Same for stderr — less common but possible (e.g. `2>&1 | head` after
// stderr was rerouted to stdout).
- process.stderr.on('error', (err: NodeJS.ErrnoException) => {
+ attach(process.stderr, 'error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EPIPE') {
// No stderr means no useful logs on the way out; still cleanup.
void triggerCleanupAndExit(0);
@@ -185,6 +207,14 @@ export function installSignalHandlers(): void {
*/
export function _resetForTests(): void {
registry.clear();
+ // Detach every listener installSignalHandlers attached — clearing flags
+ // alone leaves a live SIGTERM→exit(143) listener on the shared test-runner
+ // process, which a later synthetic `process.emit('SIGTERM')` would trigger,
+ // killing the whole suite.
+ for (const { target, event, fn } of installedListeners) {
+ (target as NodeJS.Process).off(event as 'exit', fn as () => void);
+ }
+ installedListeners.length = 0;
installed = false;
cleanupInFlight = false;
}
diff --git a/src/core/url-redact.ts b/src/core/url-redact.ts
index 7508fbbb64..e010dad54a 100644
--- a/src/core/url-redact.ts
+++ b/src/core/url-redact.ts
@@ -35,6 +35,34 @@ export function redactPgUrl(url: unknown): string {
return `${scheme}${userPart}${hostPart}${query ?? ''}`;
}
+/**
+ * Redact credential-bearing URLs of ANY scheme embedded in free text (error
+ * messages, log lines). Greedy userinfo match — `scheme://<anything>@` up to
+ * the last `@` in the same token — so a raw `@` INSIDE a password can't leak
+ * its tail (`p@ssw@rd` redacts whole, at the cost of over-redacting a
+ * hostname that legitimately follows a second `@`, which is the safe
+ * direction for a log line). Text without a `scheme://...@` shape passes
+ * through untouched.
+ *
+ * Examples (scheme genericized so this docstring itself never carries a
+ * credential-shaped span — the tests pin the real postgres shapes):
+ * redactUrlsInText('connect failed: demo://user:pw@db:5432/x timeout')
+ * → 'connect failed: demo://***@db:5432/x timeout'
+ * redactUrlsInText('demo://user:p@ssw@[email protected]/x')
+ * → 'demo://***@db.example.com/x'
+ */
+export function redactUrlsInText(text: string): string {
+ return (
+ text
+ .replace(/(\w+:\/\/)\S+@/g, '$1***@')
+ // libpq keyword/value form: `password=hunter2 host=db ...` — postgres.js
+ // echoes malformed connection strings verbatim in its error messages.
+ // Quoted values may contain spaces (`password='hunter two'`), so match
+ // quoted forms before the bare-token form.
+ .replace(/\b(password|sslpassword)\s*=\s*('[^']*'|"[^"]*"|\S+)/gi, '$1=***')
+ );
+}
+
/**
* Recursively redact any postgresql:// or postgres:// URLs found inside an
* arbitrary value (string, object, array). Useful when the caller is about
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index f5a63b173f..e370a5ffba 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.46.7.0 -->
+<!-- gbrain-template-stamp: 0.46.8.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/bootstrap-render.test.ts b/test/bootstrap-render.test.ts
index 386cabf0a6..ec8989d803 100644
--- a/test/bootstrap-render.test.ts
+++ b/test/bootstrap-render.test.ts
@@ -110,6 +110,25 @@ describe('renderWorkspace — happy path', () => {
expect(third.manifest.source_id).toBe('explicit-id');
});
+ test('rapid forced re-renders never collide on the backup stamp (same-millisecond EEXIST)', () => {
+ // Regression pin (CI 2026-08-16, shard 7): the backup stamp has
+ // MILLISECOND granularity, so two forced renders inside the same ms
+ // collided on the exclusive `wx` backup write with EEXIST. The stamp
+ // dir is now claimed atomically per render call (numeric suffix on
+ // collision). Ten back-to-back renders reliably land several in one
+ // millisecond on any modern machine.
+ const ws = answeredWs();
+ renderWorkspace(ws);
+ const stamps = new Set<string>();
+ for (let i = 0; i < 10; i++) {
+ const res = renderWorkspace(ws, { force: true });
+ expect(res.backups.length).toBeGreaterThan(0);
+ for (const b of res.backups) stamps.add(b.split('/')[1]);
+ }
+ // Every forced render owned a distinct backup dir.
+ expect(stamps.size).toBe(10);
+ });
+
test('re-render with force preserves the manifest created_at (first render wins)', () => {
const ws = answeredWs();
renderWorkspace(ws);
diff --git a/test/cli-import-no-signal-handlers.test.ts b/test/cli-import-no-signal-handlers.test.ts
new file mode 100644
index 0000000000..9370c4e16a
--- /dev/null
+++ b/test/cli-import-no-signal-handlers.test.ts
@@ -0,0 +1,79 @@
+/**
+ * Regression pins for the local-lane green wave's two harness contracts.
+ *
+ * 1. Importing src/cli.ts as a MODULE must not install process-cleanup's
+ * SIGTERM/SIGHUP→exit handlers. The install lives inside the
+ * `import.meta.main` seam; at module load it leaked a process-wide
+ * SIGTERM→exit(143) handler into any importer — in a bun test runner,
+ * one test's synthetic `process.emit('SIGTERM')` then killed the whole
+ * shard, which the parallel runner misread as an external kill. The
+ * one test that used to die on this (run-child-entry) now shields
+ * itself by stripping foreign listeners, so THIS pin is the only
+ * thing that fails if the install moves back to module scope.
+ *
+ * 2. test/helpers/gbrain-home-preload.ts sets GBRAIN_HOME to per-run
+ * scratch when unset and respects a pre-set value. Every unit test's
+ * isolation from the operator's real ~/.gbrain depends on it.
+ *
+ * Both pins spawn a fresh bun process: the contracts are about
+ * process-start module-load behavior, which can't be observed in-process.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { spawnSync } from 'child_process';
+import { join } from 'path';
+
+const REPO = join(import.meta.dir, '..');
+
+function runBunEval(script: string, env: Record<string, string | undefined>): string {
+ const res = spawnSync('bun', ['-e', script], {
+ encoding: 'utf-8',
+ timeout: 60_000,
+ cwd: REPO,
+ env: { ...process.env, ...env } as NodeJS.ProcessEnv,
+ });
+ return (res.stdout ?? '').trim();
+}
+
+describe('cli.ts module-import signal-handler contract', () => {
+ test('importing cli.ts does NOT install SIGTERM/SIGHUP handlers (import.meta.main seam)', () => {
+ const script = [
+ `await import(${JSON.stringify(join(REPO, 'src', 'cli.ts'))});`,
+ // Give any microtask-deferred module init a tick before counting.
+ `await new Promise((r) => setTimeout(r, 50));`,
+ `console.log(JSON.stringify({ sigterm: process.listenerCount('SIGTERM'), sighup: process.listenerCount('SIGHUP') }));`,
+ ].join('\n');
+ const out = runBunEval(script, {});
+ const lines = out.split('\n').filter((l) => l.trim().startsWith('{'));
+ const counts = JSON.parse(lines[lines.length - 1]) as { sigterm: number; sighup: number };
+ // zombie-reap's SIGCHLD handler is expected at module scope (tracked as a
+ // TODOS follow-up); SIGTERM/SIGHUP from process-cleanup must NOT be.
+ expect(counts.sigterm).toBe(0);
+ expect(counts.sighup).toBe(0);
+ });
+});
+
+describe('gbrain-home-preload contract', () => {
+ const PRELOAD = join(REPO, 'test', 'helpers', 'gbrain-home-preload.ts');
+
+ test('sets GBRAIN_HOME to per-run scratch when unset', () => {
+ const script = [
+ `await import(${JSON.stringify(PRELOAD)});`,
+ `console.log(JSON.stringify({ home: process.env.GBRAIN_HOME ?? null }));`,
+ ].join('\n');
+ const out = runBunEval(script, { GBRAIN_HOME: undefined });
+ const parsed = JSON.parse(out.split('\n').pop()!) as { home: string | null };
+ expect(parsed.home).not.toBeNull();
+ expect(parsed.home!).toContain('gbrain-test-home-');
+ });
+
+ test('respects a pre-set GBRAIN_HOME (the e2e wrapper sets its own)', () => {
+ const script = [
+ `await import(${JSON.stringify(PRELOAD)});`,
+ `console.log(JSON.stringify({ home: process.env.GBRAIN_HOME ?? null }));`,
+ ].join('\n');
+ const out = runBunEval(script, { GBRAIN_HOME: '/tmp/gbrain-preload-preset-pin' });
+ const parsed = JSON.parse(out.split('\n').pop()!) as { home: string | null };
+ expect(parsed.home).toBe('/tmp/gbrain-preload-preset-pin');
+ });
+});
diff --git a/test/core/cycle.serial.test.ts b/test/core/cycle.serial.test.ts
index 335866fe42..56a542fbc7 100644
--- a/test/core/cycle.serial.test.ts
+++ b/test/core/cycle.serial.test.ts
@@ -307,7 +307,13 @@ describe('runCycle — cycle_already_running skip', () => {
// ─── Engine null path ─────────────────────────────────────────────
describe('runCycle — engine = null (filesystem-only mode)', () => {
- const lockFile = require('path').join(require('os').homedir(), '.gbrain', 'cycle.lock');
+ // Resolve the lock path the way production does (gbrainPath honors
+ // GBRAIN_HOME — which the test preload points at per-run scratch). The
+ // old homedir()-based literal wrote lock files into the operator's REAL
+ // ~/.gbrain and stopped matching the code's path once tests were
+ // home-isolated.
+ const { gbrainPath } = require('../../src/core/config.ts') as typeof import('../../src/core/config.ts');
+ const lockFile = gbrainPath('cycle.lock');
afterEach(() => {
if (existsSync(lockFile)) { try { unlinkSync(lockFile); } catch { /* */ } }
diff --git a/test/db-lock-fencing.test.ts b/test/db-lock-fencing.test.ts
index 0edf7bf9e8..42c034e74f 100644
--- a/test/db-lock-fencing.test.ts
+++ b/test/db-lock-fencing.test.ts
@@ -102,13 +102,22 @@ describe('startCycleLockRefresher (Tier-1 #1 + D5.11)', () => {
const stop = startCycleLockRefresher(fakeLock(async () => false), controller, 'test-lock', 15);
try {
// Poll instead of a fixed sleep: under full-suite shard load, timer
- // ticks can be starved well past the nominal interval.
+ // ticks can be starved well past the nominal interval. Poll on the
+ // REASON, not just `aborted`: one loaded-CI run (2026-08-16, shard 9)
+ // observed `aborted === true` with `reason === undefined` at the first
+ // post-abort read — unreproduced locally/in-container across 50+ runs,
+ // so treat reason visibility as part of the awaited condition and keep
+ // the assertion diagnostic when it genuinely never arrives.
const deadline = Date.now() + 5_000;
- while (!controller.signal.aborted && Date.now() < deadline) {
+ while (!(controller.signal.reason instanceof LockStolenError) && Date.now() < deadline) {
await new Promise(r => setTimeout(r, 25));
}
expect(controller.signal.aborted).toBe(true);
- expect(controller.signal.reason).toBeInstanceOf(LockStolenError);
+ if (!(controller.signal.reason instanceof LockStolenError)) {
+ throw new Error(
+ `expected LockStolenError abort reason within 5s; aborted=${controller.signal.aborted} reason=${String(controller.signal.reason)}`,
+ );
+ }
} finally {
stop();
}
diff --git a/test/doctor-minions-check.test.ts b/test/doctor-minions-check.test.ts
index daa32a2518..92c2099ee1 100644
--- a/test/doctor-minions-check.test.ts
+++ b/test/doctor-minions-check.test.ts
@@ -27,7 +27,10 @@ let origHome: string | undefined;
function run(args: string[]): { exitCode: number; stdout: string; stderr: string } {
// Strip DATABASE_URL so doctor runs filesystem-only for these tests.
// Half-migrated checks run in the filesystem section; no DB needed.
- const env = { ...process.env, HOME: tmp } as Record<string, string | undefined>;
+ // Both HOME and GBRAIN_HOME must point at the fixture dir: config/path
+ // resolution prefers GBRAIN_HOME (which the test preload sets to its own
+ // scratch), so HOME alone leaves the child reading the wrong .gbrain.
+ const env = { ...process.env, HOME: tmp, GBRAIN_HOME: tmp } as Record<string, string | undefined>;
delete env.DATABASE_URL;
delete env.GBRAIN_DATABASE_URL;
// Cross-file poisoning guard: sibling test files in the same bun process
@@ -250,4 +253,37 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
expect(result.stdout).toContain('MINIONS HALF-INSTALLED');
expect(result.stdout).toContain('gbrain apply-migrations --yes');
});
+
+ test('DB-connect failure announces the filesystem-only fallback on stderr, credentials redacted', () => {
+ // The fallback used to be silent — indistinguishable from a healthy
+ // DB-backed run minus the DB checks. Pin the stderr note AND that a
+ // credential-bearing connect error never leaks the password (doctor
+ // output is what users paste into issues and CI logs).
+ const gbrainDir = join(tmp, '.gbrain');
+ mkdirSync(gbrainDir, { recursive: true });
+ // Assembled at runtime so the source never contains a scannable
+ // credential-URL span (the value is synthetic).
+ const fakeUrl = ['postgresql:/', '/alice:sekrit-hunter2', '@127.0.0.1:1/refused'].join('');
+ writeFileSync(
+ join(gbrainDir, 'config.json'),
+ JSON.stringify({ engine: 'postgres', database_url: fakeUrl }) + '\n',
+ );
+
+ // The shared run() helper discards stderr on exit 0; this pin needs it
+ // regardless of exit code, so spawn directly.
+ const env = { ...process.env, HOME: tmp, GBRAIN_HOME: tmp } as Record<string, string | undefined>;
+ delete env.DATABASE_URL;
+ delete env.GBRAIN_DATABASE_URL;
+ const { spawnSync } = require('child_process') as typeof import('child_process');
+ const res = spawnSync('bun', ['run', CLI, 'doctor', '--json'], {
+ env: env as NodeJS.ProcessEnv,
+ encoding: 'utf-8',
+ timeout: 60_000,
+ });
+ expect(res.stderr).toContain('[doctor] DB-backed doctor run failed');
+ expect(res.stderr).toContain('filesystem-only checks');
+ expect(res.stderr).not.toContain('sekrit-hunter2');
+ // stdout stays parseable JSON for --json consumers.
+ expect(() => JSON.parse(res.stdout.trim())).not.toThrow();
+ }, 60_000);
});
diff --git a/test/e2e/bootstrap-harness-lifecycle.serial.test.ts b/test/e2e/bootstrap-harness-lifecycle.serial.test.ts
index 0c2d71d705..bbaa8b8436 100644
--- a/test/e2e/bootstrap-harness-lifecycle.serial.test.ts
+++ b/test/e2e/bootstrap-harness-lifecycle.serial.test.ts
@@ -70,20 +70,17 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {
// remapped HOME (it reads the password database), so HOME alone does NOT
// sandbox user-scope writes — that leak is exactly why claudeUserSettingsPath
// honors CLAUDE_CONFIG_DIR/HOME explicitly now.
- //
- // DATABASE_URL/GBRAIN_DATABASE_URL must be scrubbed for the IN-PROCESS
- // runBootstrap lane too (the beforeAll already scrubs them for its
- // subprocesses): since v0.31.3 (9c60b3a06, #801) an env DATABASE_URL
- // deliberately overrides the file-backed PGLite engine in loadConfig().
- // Under the DATABASE_URL-bearing e2e wrapper, a leaked URL retargets the
- // mint at the shared Postgres test DB — no PGLite single-writer lock, so
- // the mint-refusal contract under a live serve never fires and the
- // fresh-minted token fails the bearer smoke against the PGLite serve.
const envFor = () => ({
GBRAIN_HOME: parent,
HOME: sandboxHome,
CLAUDE_CONFIG_DIR: join(sandboxHome, '.claude'),
CODEX_HOME: codexHome,
+ // The e2e lane exports DATABASE_URL; the IN-PROCESS runBootstrap calls
+ // (unlike the spawned children scrubbed in beforeAll) would otherwise
+ // resolve it via loadConfig's env>file precedence and mint tokens
+ // against Postgres while the live serve is PGLite-backed — turning the
+ // expected refusal into an invalid_token rollback. withEnv treats
+ // undefined as delete-with-restore.
DATABASE_URL: undefined,
GBRAIN_DATABASE_URL: undefined,
});
diff --git a/test/e2e/bootstrap-keyed-postgres.serial.test.ts b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
index 25ad541445..86c3346136 100644
--- a/test/e2e/bootstrap-keyed-postgres.serial.test.ts
+++ b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
@@ -321,12 +321,21 @@ describe.skipIf(!DATABASE_URL)('Postgres bootstrap verify (real Postgres)', () =
const magic = res.checks.find((c) => c.id === 'magic_moment');
expect(magic?.ok).toBe(true);
- // Probe cleanup [G13] must hold on the Postgres DDL path too.
+ // Probe cleanup [G13] must hold on the Postgres DDL path too. Verify
+ // cleans up through the real delete_page op, which is a SOFT delete
+ // (deleted_at stamp) — so assert no ACTIVE probe rows remain, and pin
+ // that the probes went through the soft-delete path rather than never
+ // being cleaned at all.
const probePages = await engine.executeRaw<{ n: number }>(
- `SELECT COUNT(*)::int AS n FROM pages WHERE source_id = $1 AND slug IN ($2, $3)`,
+ `SELECT COUNT(*)::int AS n FROM pages WHERE source_id = $1 AND slug IN ($2, $3) AND deleted_at IS NULL`,
['workspace', VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG],
);
expect(probePages[0].n).toBe(0);
+ const probeTombstones = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM pages WHERE source_id = $1 AND slug IN ($2, $3) AND deleted_at IS NOT NULL`,
+ ['workspace', VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG],
+ );
+ expect(probeTombstones[0].n).toBe(2);
const probeFacts = await engine.executeRaw<{ n: number }>(
`SELECT COUNT(*)::int AS n FROM facts WHERE source_id = $1 AND source_markdown_slug = $2`,
['workspace', VERIFY_PROBE_SLUG],
diff --git a/test/e2e/doctor-progress.test.ts b/test/e2e/doctor-progress.test.ts
index 39d943c729..b7448d1723 100644
--- a/test/e2e/doctor-progress.test.ts
+++ b/test/e2e/doctor-progress.test.ts
@@ -39,11 +39,30 @@ describeE2E('gbrain doctor --progress-json (E2E)', () => {
});
test('stderr has JSONL progress events, stdout stays clean', () => {
- const res = spawnSync('bun', [CLI, '--progress-json', 'doctor', '--json'], {
- encoding: 'utf-8',
- env: { ...process.env, NO_COLOR: '1' },
- timeout: DOCTOR_PROGRESS_TIMEOUT_MS,
- });
+ // A transient DB-connect failure sends the CLI down its filesystem-only
+ // doctor fallback (announced on stderr by cli.ts, but it still emits
+ // zero progress events with a healthy-looking stdout). Detect that via
+ // the 'connection' check in the --json payload and retry once before
+ // asserting, so a one-off connect blip doesn't fail the lane.
+ const runOnce = () =>
+ spawnSync('bun', [CLI, '--progress-json', 'doctor', '--json'], {
+ encoding: 'utf-8',
+ env: { ...process.env, NO_COLOR: '1' },
+ timeout: DOCTOR_PROGRESS_TIMEOUT_MS,
+ });
+ const connectionOk = (stdout: string): boolean => {
+ try {
+ const payload = JSON.parse(stdout);
+ const checks = (payload.checks ?? []) as Array<{ name?: string; status?: string }>;
+ const conn = checks.find((c) => c.name === 'connection');
+ return conn?.status === 'ok';
+ } catch {
+ return false;
+ }
+ };
+ let res = runOnce();
+ if (!connectionOk(res.stdout)) res = runOnce();
+ expect(connectionOk(res.stdout)).toBe(true);
// Even if some checks warn, doctor runs to completion. Failures would
// exit non-zero, which is OK — we're testing progress wiring.
diff --git a/test/e2e/helpers.ts b/test/e2e/helpers.ts
index 1203d2bbc4..59051092ba 100644
--- a/test/e2e/helpers.ts
+++ b/test/e2e/helpers.ts
@@ -110,6 +110,26 @@ export async function setupDB(): Promise<PostgresEngine> {
ON CONFLICT (key) DO NOTHING
`);
+ // Reset leaked brain identity: `sources` is not in ALL_TABLES (the default
+ // row must survive), but rows/columns written by earlier files or runs
+ // persist. writeSyncAnchor's ownership guard (#3735) keys on
+ // sources.default.local_path — a stale value from another test makes every
+ // legacy-path performSync classify as first_sync forever. 42P01-tolerant
+ // like the TRUNCATE loop above.
+ try {
+ await conn.unsafe(`DELETE FROM sources WHERE id <> 'default'`);
+ // Only the sync-identity columns: local_path feeds writeSyncAnchor's
+ // ownership guard (#3735) and last_commit/last_sync_at feed first_sync
+ // classification. chunker_version is deliberately left alone — NULLing
+ // it flips extraction-staleness semantics for unrelated suites.
+ await conn.unsafe(
+ `UPDATE sources SET local_path = NULL, last_commit = NULL, last_sync_at = NULL WHERE id = 'default'`,
+ );
+ } catch (e: unknown) {
+ const code = (e as { code?: string })?.code;
+ if (code !== '42P01' && code !== '42703') throw e; // missing table/column on older schemas
+ }
+
engine = new PostgresEngine();
await engine.connect({ database_url: DATABASE_URL });
// Apply MIGRATIONS via the engine path. db.initSchema above only runs the
diff --git a/test/e2e/ingestion-roundtrip.test.ts b/test/e2e/ingestion-roundtrip.test.ts
index a0fae218cf..099fa28ea7 100644
--- a/test/e2e/ingestion-roundtrip.test.ts
+++ b/test/e2e/ingestion-roundtrip.test.ts
@@ -171,8 +171,10 @@ describe('ingestion roundtrip — inbox-folder → daemon → ingest_capture →
expect(fetched?.compiled_truth).toContain('full e2e flow');
// File was archived after ingestion (the inbox-folder source's
- // post-emit archive step).
- expect(fs.existsSync(captured)).toBe(false);
+ // post-emit archive step). The archive (mkdir+rename) runs ASYNC
+ // relative to the dispatch that satisfied the waits above — emit is
+ // fire-and-forget — so poll rather than asserting immediately.
+ await waitFor(() => !fs.existsSync(captured));
const archiveDate = new Date().toISOString().slice(0, 10);
expect(fs.existsSync(path.join(inboxDir, '.archived', archiveDate, 'roundtrip.md'))).toBe(true);
diff --git a/test/e2e/migration-flow.test.ts b/test/e2e/migration-flow.test.ts
index bfacb7ba14..3a2af693ad 100644
--- a/test/e2e/migration-flow.test.ts
+++ b/test/e2e/migration-flow.test.ts
@@ -62,12 +62,13 @@ if (!SKIP) {
function freshTempHome(label: string) {
const dir = mkdtempSync(join(tmpdir(), `gbrain-e2e-migration-${label}-`));
- // preferences.ts's gbrainDir() returns `$HOME/.gbrain` when GBRAIN_HOME
- // is unset. Test fixtures write to `$dir/.gbrain/...`, so set HOME only
- // and clear any inherited GBRAIN_HOME (which would route prefs to $dir
- // directly, no .gbrain suffix).
+ // preferences.ts's gbrainDir() delegates to gbrainPath(): GBRAIN_HOME is a
+ // PARENT dir with '.gbrain' appended, so GBRAIN_HOME=$dir routes prefs +
+ // the migration ledger to `$dir/.gbrain/...`, matching the fixture layout.
+ // (HOME alone doesn't isolate in-process reads — the unset-GBRAIN_HOME
+ // fallback uses Bun's cached homedir(), frozen at the e2e wrapper's HOME.)
process.env.HOME = dir;
- delete process.env.GBRAIN_HOME;
+ process.env.GBRAIN_HOME = dir;
// Seed config so Phase A's `gbrain init --migrate-only` has a target.
mkdirSync(join(dir, '.gbrain'), { recursive: true });
writeFileSync(
@@ -87,6 +88,8 @@ function freshTempHome(label: string) {
function restoreHomePath() {
if (origHome === undefined) delete process.env.HOME;
else process.env.HOME = origHome;
+ if (origGbrainHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = origGbrainHome;
if (origPath === undefined) delete process.env.PATH;
else process.env.PATH = `${fakeBinDir}:${origPath ?? ''}`;
}
diff --git a/test/e2e/pglite-cli-exit.serial.test.ts b/test/e2e/pglite-cli-exit.serial.test.ts
index 93607de670..08ea42b7c5 100644
--- a/test/e2e/pglite-cli-exit.serial.test.ts
+++ b/test/e2e/pglite-cli-exit.serial.test.ts
@@ -96,14 +96,16 @@ beforeAll(() => {
delete runEnv.OPENAI_API_KEY;
delete runEnv.ANTHROPIC_API_KEY;
delete runEnv.GOOGLE_API_KEY;
- // Strip DB-URL env vars: since v0.31.3 (9c60b3a06, #801) an env
- // DATABASE_URL deliberately overrides a file-backed PGLite engine
- // selection in loadConfig(). This whole file is a hermetic-PGLite
- // suite; when run under the DATABASE_URL-bearing e2e wrapper, an
- // inherited URL would silently retarget every subprocess (including
- // the torn-WAL fixture below) at the shared Postgres test DB.
+ // This file is PGLite-only, but the e2e lane deliberately exports
+ // DATABASE_URL (scripts/run-e2e.sh). An inherited env URL overrides the
+ // fixture's `engine: 'pglite'` config (env > file precedence), silently
+ // rerouting every spawned CLI to the healthy shared Postgres — the
+ // corrupt-WAL case then exits 0 against the wrong engine. Strip all
+ // DB-routing vars so the spawned CLIs honor the PGLite fixture homes.
delete runEnv.DATABASE_URL;
delete runEnv.GBRAIN_DATABASE_URL;
+ delete runEnv.GBRAIN_PGBOUNCER_URL;
+ delete runEnv.GBRAIN_PGBOUNCER_DIRECT_URL;
// NOTE: init grew strict flag validation (#2201); `--repo`/`--yes` were
// never real init flags (previously silently ignored). The repo is wired
diff --git a/test/e2e/type-unification-full-flow.test.ts b/test/e2e/type-unification-full-flow.test.ts
index 0bc3181c27..ac604fa383 100644
--- a/test/e2e/type-unification-full-flow.test.ts
+++ b/test/e2e/type-unification-full-flow.test.ts
@@ -21,6 +21,7 @@ import { resetPgliteState } from '../helpers/reset-pglite.ts';
import { runUnifyTypes } from '../../src/core/schema-pack/unify-types-handler.ts';
import { runAllOnboardChecks } from '../../src/core/onboard/checks.ts';
import { _resetPackCacheForTests } from '../../src/core/schema-pack/registry.ts';
+import { withEnv, emptyHome } from '../helpers/with-env.ts';
let engine: PGLiteEngine;
@@ -142,8 +143,14 @@ describe('v0.42 type-unification E2E (IRON RULE)', () => {
const preDistinct = parseInt(preTypes[0].cnt, 10);
expect(preDistinct).toBeGreaterThanOrEqual(20);
- // Onboard surfaces pack_upgrade_available
- const checks = await runAllOnboardChecks(engine);
+ // Onboard surfaces pack_upgrade_available. checkPackUpgradeAvailable
+ // honors tier-6 file-plane config (v0.42.66.0, #3396), so hide the dev
+ // machine's real ~/.gbrain/config.json schema_pack for this assertion —
+ // otherwise the check reports 'ok' locally while 'warn' in CI.
+ const checks = await withEnv(
+ { GBRAIN_HOME: emptyHome(), GBRAIN_SCHEMA_PACK: undefined },
+ () => runAllOnboardChecks(engine),
+ );
const packUpgrade = checks.find(c => c.check.name === 'pack_upgrade_available');
expect(packUpgrade?.check.status).toBe('warn');
expect(packUpgrade?.remediations[0]?.job).toBe('unify-types');
diff --git a/test/helpers/gbrain-home-preload.ts b/test/helpers/gbrain-home-preload.ts
new file mode 100644
index 0000000000..b63a56303c
--- /dev/null
+++ b/test/helpers/gbrain-home-preload.ts
@@ -0,0 +1,41 @@
+/**
+ * Pre-test setup: point GBRAIN_HOME at a per-run scratch directory so unit
+ * tests never resolve the operator's real `~/.gbrain`.
+ *
+ * Why this exists: config resolution (`configPath()`/`gbrainPath()` and every
+ * loadConfig tier-6 file-plane read) falls back to the real home when
+ * GBRAIN_HOME is unset. Any test that exercises a config-honoring code path
+ * without its own `withEnv({ GBRAIN_HOME: ... })` silently changes behavior
+ * with whatever the operator's live `~/.gbrain/config.json` happens to say —
+ * schema_pack, engine, model routing, feature toggles. Concretely observed:
+ * 27 cycle/autopilot/dream tests flipped red on a dev box the moment a
+ * sibling workspace's run rewrote the real config.json mid-day, while the
+ * identical commit stayed green in CI (which has no ~/.gbrain at all). The
+ * reverse leak is worse — tests have historically CLOBBERED the operator's
+ * real config (`config.json.clobbered-*` remnants).
+ *
+ * Fix: same pattern as audit-dir-preload (#2823) and sync-failures-preload —
+ * set the env once, globally, before any test file loads, to a fresh mkdtemp
+ * dir unique to THIS process. Each shard is its own bun process, so shards
+ * don't collide; the OS reaps tmp.
+ *
+ * Only sets the var if it isn't already set: the e2e wrapper
+ * (scripts/run-e2e.sh) exports its own isolated GBRAIN_HOME before bun
+ * starts, and tests that manage GBRAIN_HOME via withEnv save/restore around
+ * this default like any other env var. An operator who deliberately exports
+ * GBRAIN_HOME keeps their override.
+ *
+ * Imported by `bunfig.toml` via
+ * `preload = [..., "./test/helpers/gbrain-home-preload.ts"]`.
+ */
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+if (!process.env.GBRAIN_HOME) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-test-home-'));
+ process.env.GBRAIN_HOME = dir;
+ if (process.env.GBRAIN_DEBUG_PRELOAD === '1') {
+ console.error(`[gbrain-home-preload] GBRAIN_HOME=${dir}`);
+ }
+}
diff --git a/test/init-migrate-only.test.ts b/test/init-migrate-only.test.ts
index a3732e5f19..c3df2c47a5 100644
--- a/test/init-migrate-only.test.ts
+++ b/test/init-migrate-only.test.ts
@@ -26,7 +26,10 @@ function run(args: string[]): { exitCode: number; stdout: string; stderr: string
// "no config" error-path tests need loadConfig() to return null, which it
// won't if any env var fallback is set (src/core/config.ts:30). Tests
// that seed their own config use freshHomeWithConfig() below.
- const env = { ...process.env, HOME: tmp } as Record<string, string | undefined>;
+ // Both HOME and GBRAIN_HOME must point at the fixture dir: config/path
+ // resolution prefers GBRAIN_HOME (which the test preload sets to its own
+ // scratch), so HOME alone leaves the child reading the wrong .gbrain.
+ const env = { ...process.env, HOME: tmp, GBRAIN_HOME: tmp } as Record<string, string | undefined>;
delete env.DATABASE_URL;
delete env.GBRAIN_DATABASE_URL;
try {
diff --git a/test/migration-resume.test.ts b/test/migration-resume.test.ts
index 6aa0486ffb..f016e55ff1 100644
--- a/test/migration-resume.test.ts
+++ b/test/migration-resume.test.ts
@@ -22,11 +22,12 @@ const originalGbrainHome = process.env.GBRAIN_HOME;
beforeEach(() => {
tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-migration-resume-'));
- // preferences.ts's gbrainDir() returns `$HOME/.gbrain` when GBRAIN_HOME
- // is unset. Set HOME only; clear any inherited GBRAIN_HOME so the test
- // body matches the migrations dir at `$tmpHome/.gbrain/migrations/`.
+ // preferences.ts's gbrainDir() delegates to gbrainPath(): GBRAIN_HOME is
+ // a PARENT dir with '.gbrain' appended, so GBRAIN_HOME=$tmpHome routes the
+ // ledger to `$tmpHome/.gbrain/migrations/`, matching the fixture layout.
+ // (HOME alone doesn't isolate — the fallback uses Bun's cached homedir().)
process.env.HOME = tmpHome;
- delete process.env.GBRAIN_HOME;
+ process.env.GBRAIN_HOME = tmpHome;
});
afterEach(() => {
diff --git a/test/preferences.test.ts b/test/preferences.test.ts
index 0b725e6553..ba3ed4a28d 100644
--- a/test/preferences.test.ts
+++ b/test/preferences.test.ts
@@ -21,12 +21,14 @@ beforeEach(() => {
origHome = process.env.HOME;
origGbrainHome = process.env.GBRAIN_HOME;
tmp = mkdtempSync(join(tmpdir(), 'gbrain-prefs-test-'));
- // preferences.ts's gbrainDir() returns `$HOME/.gbrain` when GBRAIN_HOME
- // is unset. Test fixtures write to `$tmp/.gbrain/...`, so set HOME only
- // and clear GBRAIN_HOME — setting GBRAIN_HOME would route prefs to $tmp
- // directly (no .gbrain suffix), which doesn't match the fixture layout.
+ // preferences.ts's gbrainDir() delegates to config.ts's gbrainPath():
+ // GBRAIN_HOME is a PARENT dir and '.gbrain' is appended, so
+ // GBRAIN_HOME=$tmp routes prefs + the migration ledger to
+ // `$tmp/.gbrain/...`, matching the fixture layout. (HOME alone doesn't
+ // isolate: the unset-GBRAIN_HOME fallback uses os.homedir(), which Bun
+ // caches at first call and ignores in-process HOME mutation.)
process.env.HOME = tmp;
- delete process.env.GBRAIN_HOME;
+ process.env.GBRAIN_HOME = tmp;
});
afterEach(() => {
@@ -211,3 +213,51 @@ describe('loadCompletedMigrations', () => {
expect(entries[1].version).toBe('0.11.0');
});
});
+
+describe('legacy $GBRAIN_HOME-direct layout copy-forward', () => {
+ // Before gbrainDir() delegated to gbrainPath(), a GBRAIN_HOME install kept
+ // prefs at $GBRAIN_HOME/preferences.json and the ledger at
+ // $GBRAIN_HOME/migrations/completed.jsonl (no '.gbrain' segment). The shim
+ // copies them forward on first read so an upgrade can't silently re-run
+ // completed migrations or drop an explicit minion_mode opt-out.
+
+ test('legacy ledger is copied forward and read under the new convention', () => {
+ mkdirSync(join(tmp, 'migrations'), { recursive: true });
+ writeFileSync(
+ join(tmp, 'migrations', 'completed.jsonl'),
+ JSON.stringify({ version: '0.11.0', status: 'complete' }) + '\n',
+ );
+ const entries = loadCompletedMigrations();
+ expect(entries.some((e) => e.version === '0.11.0' && e.status === 'complete')).toBe(true);
+ // Copied to the new path; legacy file retained for binary rollback.
+ expect(existsSync(join(tmp, '.gbrain', 'migrations', 'completed.jsonl'))).toBe(true);
+ expect(existsSync(join(tmp, 'migrations', 'completed.jsonl'))).toBe(true);
+ });
+
+ test('legacy preferences.json is copied forward — minion_mode opt-out survives the upgrade', () => {
+ writeFileSync(join(tmp, 'preferences.json'), JSON.stringify({ minion_mode: 'off' }) + '\n');
+ const prefs = loadPreferences();
+ expect(prefs.minion_mode).toBe('off');
+ expect(existsSync(join(tmp, '.gbrain', 'preferences.json'))).toBe(true);
+ expect(existsSync(join(tmp, 'preferences.json'))).toBe(true);
+ });
+
+ test('an existing new-path file wins — legacy is never copied over it', () => {
+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });
+ writeFileSync(join(tmp, '.gbrain', 'preferences.json'), JSON.stringify({ minion_mode: 'always' }) + '\n');
+ writeFileSync(join(tmp, 'preferences.json'), JSON.stringify({ minion_mode: 'off' }) + '\n');
+ expect(loadPreferences().minion_mode).toBe('always');
+ });
+
+ test('a partial append does not shadow un-migrated legacy history', () => {
+ mkdirSync(join(tmp, 'migrations'), { recursive: true });
+ writeFileSync(
+ join(tmp, 'migrations', 'completed.jsonl'),
+ JSON.stringify({ version: '0.10.0', status: 'complete' }) + '\n',
+ );
+ appendCompletedMigration({ version: '0.11.0', status: 'partial' });
+ const entries = loadCompletedMigrations();
+ expect(entries.some((e) => e.version === '0.10.0' && e.status === 'complete')).toBe(true);
+ expect(entries.some((e) => e.version === '0.11.0' && e.status === 'partial')).toBe(true);
+ });
+});
diff --git a/test/process-cleanup.test.ts b/test/process-cleanup.test.ts
index 834ebfefa9..030e7e097f 100644
--- a/test/process-cleanup.test.ts
+++ b/test/process-cleanup.test.ts
@@ -198,4 +198,31 @@ describe('installSignalHandlers', () => {
expect(process.listenerCount('SIGHUP')).toBe(before.sighup + 1);
expect(process.listenerCount('SIGPIPE')).toBe(before.sigpipe + 1);
});
+
+ test('_resetForTests DETACHES every listener installSignalHandlers attached', () => {
+ // Regression pin for the suite-wide-kill class: a flags-only reset left
+ // a live SIGTERM→exit(143) listener on the shared bun test runner, so a
+ // later synthetic process.emit('SIGTERM') from any test killed the whole
+ // suite. Counts must return to the pre-install BASELINE, not baseline+1.
+ _resetForTests();
+ const before = {
+ sigterm: process.listenerCount('SIGTERM'),
+ sighup: process.listenerCount('SIGHUP'),
+ sigpipe: process.listenerCount('SIGPIPE'),
+ uncaught: process.listenerCount('uncaughtException'),
+ rejection: process.listenerCount('unhandledRejection'),
+ stdoutErr: process.stdout.listenerCount('error'),
+ stderrErr: process.stderr.listenerCount('error'),
+ };
+ installSignalHandlers();
+ expect(process.listenerCount('SIGTERM')).toBe(before.sigterm + 1);
+ _resetForTests();
+ expect(process.listenerCount('SIGTERM')).toBe(before.sigterm);
+ expect(process.listenerCount('SIGHUP')).toBe(before.sighup);
+ expect(process.listenerCount('SIGPIPE')).toBe(before.sigpipe);
+ expect(process.listenerCount('uncaughtException')).toBe(before.uncaught);
+ expect(process.listenerCount('unhandledRejection')).toBe(before.rejection);
+ expect(process.stdout.listenerCount('error')).toBe(before.stdoutErr);
+ expect(process.stderr.listenerCount('error')).toBe(before.stderrErr);
+ });
});
diff --git a/test/skillpack-check.test.ts b/test/skillpack-check.test.ts
index a41d782f91..685c3b200f 100644
--- a/test/skillpack-check.test.ts
+++ b/test/skillpack-check.test.ts
@@ -26,7 +26,10 @@ let tmp: string;
let origHome: string | undefined;
function run(args: string[]): { exitCode: number; stdout: string; stderr: string } {
- const env = { ...process.env, HOME: tmp } as Record<string, string | undefined>;
+ // Both HOME and GBRAIN_HOME must point at the fixture dir: config/path
+ // resolution prefers GBRAIN_HOME (which the test preload sets to its own
+ // scratch), so HOME alone leaves the child reading the wrong .gbrain.
+ const env = { ...process.env, HOME: tmp, GBRAIN_HOME: tmp } as Record<string, string | undefined>;
delete env.DATABASE_URL;
delete env.GBRAIN_DATABASE_URL;
try {
diff --git a/test/url-redact.test.ts b/test/url-redact.test.ts
index da5fe485bb..b74de533da 100644
--- a/test/url-redact.test.ts
+++ b/test/url-redact.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'bun:test';
-import { redactPgUrl, redactDeep } from '../src/core/url-redact.ts';
+import { redactPgUrl, redactDeep, redactUrlsInText } from '../src/core/url-redact.ts';
describe('redactPgUrl', () => {
test('strips userinfo from postgresql:// URL', () => {
@@ -76,3 +76,48 @@ describe('redactDeep', () => {
expect(out.config.secondary.url).toBe('postgres://***@h2/d');
});
});
+
+describe('redactUrlsInText', () => {
+ // Fixture credential URLs are ASSEMBLED at runtime (scheme + userinfo +
+ // host concatenated) so the source text never contains a span the
+ // pre-push credential scanner would flag — the values are synthetic, but
+ // the assembled runtime shape is exactly what the redactor must catch.
+ const cred = (scheme: string, userinfo: string, rest: string) => `${scheme}://${userinfo}@${rest}`;
+
+ test('redacts a credential-bearing URL embedded in an error message', () => {
+ expect(redactUrlsInText(`connect failed: ${cred('postgresql', 'alice:sekrit', 'db.example.com:5432/x')} timeout`))
+ .toBe('connect failed: postgresql://***@db.example.com:5432/x timeout');
+ });
+
+ test('a raw @ inside the password cannot leak its tail (greedy match)', () => {
+ expect(redactUrlsInText(cred('postgresql', 'alice:p@ssw@rd', 'db.example.com:5432/x')))
+ .toBe('postgresql://***@db.example.com:5432/x');
+ });
+
+ test('redacts non-postgres schemes too', () => {
+ expect(redactUrlsInText(`fetch ${cred('https', 'token:gxp_notreal', 'example.com/o/r')} failed`))
+ .toBe('fetch https://***@example.com/o/r failed');
+ });
+
+ test('passes through text without userinfo URLs', () => {
+ expect(redactUrlsInText('connect ECONNREFUSED 127.0.0.1:5432')).toBe('connect ECONNREFUSED 127.0.0.1:5432');
+ expect(redactUrlsInText('postgresql://host:5432/db has no userinfo')).toBe('postgresql://host:5432/db has no userinfo');
+ });
+
+ test('redacts multiple URLs in one message', () => {
+ expect(redactUrlsInText(`a ${cred('postgres', 'u:p', 'h1/d')} b ${cred('postgres', 'u2:p2', 'h2/d')}`))
+ .toBe('a postgres://***@h1/d b postgres://***@h2/d');
+ });
+});
+
+describe('redactUrlsInText — libpq keyword/value form', () => {
+ test('password=... in a libpq-style connection error is scrubbed', () => {
+ expect(redactUrlsInText('invalid connection string: password=hunter2 user=alice host=db'))
+ .toBe('invalid connection string: password=*** user=alice host=db');
+ });
+
+ test('case-insensitive and sslpassword too', () => {
+ expect(redactUrlsInText('PASSWORD=abc sslpassword=def host=h'))
+ .toBe('PASSWORD=*** sslpassword=*** host=h');
+ });
+});