Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Postgres connections to non-local hosts use TLS unless the URL opts out
garrytanc2506e4e631b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 821c6f24a1..3f21c1c360 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,23 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Postgres connections to a database that isn't on your machine now use TLS unless the URL opts out.** Before this release gbrain's Postgres driver connected in plaintext whenever the database URL had no `sslmode`, so the password and every page crossed the network unencrypted, even to a hosted database that supports TLS. Now every connection pool requires TLS (`sslmode=require`) for any host other than `localhost`, `127.0.0.0/8`, `::1` or a Unix socket; private addresses and Docker service names count as remote. An sslmode in the URL is always honored, so `?sslmode=disable` keeps a plaintext connection on a network you trust. A server that has no TLS no longer connects silently: it fails with `postgres_tls_required`, which says to turn TLS on at the server or add `sslmode=disable`. `sslmode=require` encrypts but does not verify the server certificate; `sslmode=verify-full`, with the provider's CA in `NODE_EXTRA_CA_CERTS`, verifies it too. A new doctor check, `postgres_tls`, warns when a brain on a remote host is connected without TLS. PGLite has no network connection and is unchanged.++**If you self-host Postgres without TLS on another machine:** after upgrading, gbrain refuses to connect with `postgres_tls_required`. Either enable TLS on the server (`ssl = on` with a certificate), or add `?sslmode=disable` (or `&sslmode=disable`) to your database URL in `~/.gbrain/config.json` or `GBRAIN_DATABASE_URL`/`DATABASE_URL`.++### Itemized changes++- `src/core/pg-tls.ts` (new): `resolvePgTls` / `withPgTls`, the one TLS resolver every `postgres()` call site in `src/` uses (the module pool in `db.ts`, worker instance pools in `postgres-engine.ts`, the read and direct pools in `connection-manager.ts`, the graduation target probe and the schema-lock diagnostic connection). An `ssl` option, `sslmode` / `ssl` / `sslrootcert=system` in the URL, or the driver's `PGSSL` variable is explicit and left alone; a loopback host or socket keeps the driver default; anything else gets `ssl: 'require'`. After a failed default-required connect, `tlsRequiredDefaultError` sends the protocol's SSLRequest to the server and turns a "no" into `postgres_tls_required` (DNS, refused and timeout failures are not probed).+- `src/core/error-registry.ts`: new code `postgres_tls_required` (host_only, actor user; fix asks the user, reads `gbrain engine status --probe --json`, verifies with `gbrain doctor --only postgres_tls --json`). `docs/guides/error-codes.md` regenerated.+- `src/core/pg-access-classify.ts`: new reason `tls_required_default` (manual tier in `gbrain db-repair`, which never removes TLS on its own; fatal for persistence reads).+- `src/commands/doctor/checks/postgres-tls.ts` (new): `postgres_tls` (ops) reads the session's `pg_stat_ssl` row; warns for a non-loopback host without TLS, notes when `require` does not verify the certificate, says when a pooler hop may be the unencrypted link, emits nothing on PGLite.+- `src/core/behavior-change-notice.ts`: one row (`postgres_tls_default`) disclosing the new default and the opt-out.+- `gbrain init` prints the Supabase URL format with `?sslmode=require`; `docs/ENGINES.md#tls-for-postgres-connections` documents the modes, `verify-full` with Supabase's CA, and the opt-out; the personal-brain tutorial and the other documented Postgres URLs carry `?sslmode=require`.+- `scripts/ci-local.sh`, `scripts/run-e2e.sh`: the Docker CI gate reaches its untrusted-by-name service hosts (`postgres-N`, `pgbouncer`) with an explicit `sslmode=disable`, and the derived PgBouncer E2E URL keeps the base URL's query.+- Tests: `test/pg-tls.test.ts` (loopback, remote, explicit modes, opt-out, a guard that every `postgres()` pool in `src/` goes through `withPgTls`), `test/pg-tls-default-refusal.test.ts` (a fake server without TLS on a non-loopback interface gets the coded error; `sslmode=disable` and a TLS-capable server do not), `test/doctor-postgres-tls.test.ts`, `test/e2e/pg-tls-postgres.test.ts` (real servers: a TLS server through a non-loopback address connects with `pg_stat_ssl.ssl = true` on both pool kinds; an `ssl=off` server refuses, then connects with `sslmode=disable` and doctor warns).+## [0.60.626.0] - 2026-11-09**`gbrain sources record-origin --remote` now locks down the existing checkout too, and on a managed brain it can no longer report success while a reclone still clones with git-lfs on.** On a managed brain the record took only the source row lock, so a reclone that had already read the source, or held its worktree locks, could clone with git-lfs downloads and hooks on after the command said the source was recorded. The record now takes the worktree locks and rows a reclone takes (refusing the id `source_busy` while one runs), and the reclone reads the record under its own locks. `--remote --apply` now also turns git-lfs downloads and hooks off in the existing checkout's `.git/config`, because a reclone only happens when a checkout is lost or replaced, and until then doctor read green while the checkout still fetched git-lfs objects and ran hooks. The git-lfs check now reads a committed `.gitattributes` under a directory whose name holds a tab (it was cut at the tab and skipped), ignores commented-out `filter=lfs` lines, says "declares a git-lfs filter" when a rule only declares one, and records a clone of an empty repository instead of telling the operator to restore an intact checkout. A failed write is reported for its own id instead of ending the run without saying which ids were recorded.diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex e4a25c8d82..8726a805f2 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -183,6 +183,46 @@ analyzes the tables. If a refresh is skipped (a lock, or a role that does notown the tables), run `ANALYZE content_chunks(model, modality, page_id, body_generation)` and`ANALYZE pages` as the table owner.+### TLS for Postgres connections++Every Postgres connection gbrain opens to a host that is **not on this+machine** requires TLS unless the database URL says otherwise. On this+machine means `localhost`, `127.0.0.0/8`, `::1` or a Unix socket path;+everything else needs TLS, including private addresses (`10.x`,+`192.168.x`) and Docker service names such as `postgres-1`, because gbrain+cannot tell a trusted network from an untrusted one by its name.+(`src/core/pg-tls.ts` is the one resolver every connection pool uses.)++| URL says | What gbrain does |+|---|---|+| no `sslmode`, host on this machine | plaintext, as before |+| no `sslmode`, any other host | `sslmode=require` |+| `?sslmode=require` | encrypts the connection; does **not** verify the server certificate |+| `?sslmode=verify-full` | encrypts and verifies the certificate and host name against the CA store |+| `?sslmode=disable` | plaintext; the one opt-out, for a network you trust |++An sslmode (or `ssl=`, or `sslrootcert=system`) in the URL is always+honored and never weakened, and so is the driver's own `PGSSL` variable.++`require` stops anyone on the network from reading the traffic, but it would+not notice an attacker who sits in the middle and presents their own+certificate. For that, use `verify-full`. It checks the server certificate+against Node's CA store, so a provider with its own CA needs that CA added:+Supabase publishes it under **Project Settings → Database → SSL+Configuration → Download certificate**. Put the file on the brain host and set+`NODE_EXTRA_CA_CERTS=/path/to/prod-ca-2021.crt` in the environment gbrain+runs in (for the installed service, `~/.gbrain/env`), then use+`?sslmode=verify-full`. A `sslrootcert=<file>` parameter is not read by the+driver; use `NODE_EXTRA_CA_CERTS` instead.++A server that does not accept TLS fails the connection with+[`postgres_tls_required`](guides/error-codes.md#postgres_tls_required),+which names both choices: turn TLS on at the server, or add+`sslmode=disable` to the URL. Nothing falls back to plaintext on its own.+`gbrain doctor --only postgres_tls` reports whether the current session is+encrypted (`pg_stat_ssl`) and warns for a non-local brain that is not. PGLite+opens no network connection, so none of this applies to it.+### Vector index sizingThe chunk HNSW index stores each vector beside its graph links, so at 1,024@@ -963,6 +1003,7 @@ names — reasons may be added, never renamed or removed). All 16:| `schema_missing` | 42P01/42703 — pending migrations (`gbrain apply-migrations --yes`; excluded from the db-repair marker on the MCP mid-operation path, where it usually means code skew) || `pgvector_missing` | the vector extension is absent — auto tier creates it || `storage_corrupt` | XX001/XX002, or an XX000 such as `unexpected chunk number … for toast value` or `tuple concurrently deleted` — stored data is damaged; db-repair stops at manual and names the first step, `gbrain repair orphan-children` (preview, includes the torn-TOAST probe; [orphan children](guides/repair.md#orphan-children)) |+| `tls_required_default` | `postgres_tls_required`: gbrain's TLS default met a non-local server without TLS — db-repair stops at manual; turn TLS on at the server or add `sslmode=disable` ([TLS](#tls-for-postgres-connections)) || `unknown` | unclassified — redacted error + `gbrain doctor` |The classifier lives in `src/core/pg-access-classify.ts`; remediation copy hasdiff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex 70f176a0d3..6ed3b905e7 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -6,6 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/integrations-memorable.ts` — `memorable_relay_health` (OPS category), the doctor surface for the optional third-party relay. Engine-free (file-plane reads only), pushed unconditionally so it survives `--fast`/`--scope`. Rung ladder: gate off → quiet ok; enabled WITHOUT the gbrain disclosure stamp → FAIL naming the exact fix (the `memorable enable` out-of-band state); CLI-side consent absent → warn; no runnable binary → FAIL; last relay run failed → warn with the CLAMPED cause (the shared `clampRelayCause`; child text never lands in a doctor message verbatim) — EXCEPT the documented openclaw `no_decisive_steps` rejection, which becomes an ok-with-note (`expected_openclaw_rejection`, name-only capture refused until argument capture lands) held as a DEFERRED note that surfaces only after the codex rung below passes: on a mixed openclaw+codex host the rejection is the persistent last-relay state, and an early return would paint the check green while a trust-stale codex hook sits silently dead; receipts written but the child never reported → warn; codex hooks wired but no codex-harness receipt in the recent receipt window (tail-200 read) → warn (`codex_hooks_never_fired` — codex hooks fail silently on a stale trust entry); healthy → ok with structured details (`out_of_band_settable: true` always rides — the enable flag can be flipped by the external CLI, which is exactly why the gate also demands the stamp). Pinned by `test/doctor-memorable.test.ts`.- `src/commands/doctor/checks/routing-federation.ts` — `checkOauthClientScopeHealth` (`oauth_client_scope_health`, re-exported by the doctor.ts façade) has three warn arms: (a) dangling federated read grants, (b) orphaned empty `<name>-workspace` sources, (c) privileged self-registered clients — active `oauth_clients` rows whose scope word-matches `DCR_PRIVILEGED_SCOPES` — the DERIVED complement `ALLOWED_SCOPES_LIST \ DCR_REGISTRABLE_SCOPES` (exported; bound as a `$1` regex parameter, never interpolated) — and the `(read/write)` / `--scopes read,write` copy is built from `DCR_REGISTRABLE_SCOPES`; pinned by the set-equality + per-scope loop in `test/doctor-oauth-client-scope-health.test.ts`; rows with `grant_revision = 0` and no `oauth_grant_audit` row with `action = 'register'` (every operator path writes one; the anonymous DCR insert does not). Arm (c) is advisory (the signature also matches operator clients that predate the grant audit log) and carries the `gbrain auth rescope-client <client_id> --scopes read,write` / `gbrain auth revoke-client <client_id>` remedy; when the audit table or `grant_revision` column is absent it fails OPEN and the ok message states the self-registered-client audit was skipped (unknown). Pinned by `test/doctor-oauth-client-scope-health.test.ts`.+- `src/commands/doctor/checks/postgres-tls.ts` — `postgres_tls` (OPS, after `rls`): the session's own `pg_stat_ssl` row on a Postgres brain. Warns (fix asks the user; verify `gbrain doctor --only postgres_tls`) for a non-loopback host without TLS, saying whether the URL opted out (`sslmode=disable`) or a pooler hop reads unencrypted; ok when encrypted, noting that `require` does not verify the certificate; ok on a loopback host; nothing on PGLite or when `pg_stat_ssl` is unreadable. `postgresTlsCheck(url, session)` is the pure half (`test/doctor-postgres-tls.test.ts`).- `src/commands/doctor/checks/embedding-identity.ts` — `embedding_identity_unqualified` (#6113, BRAIN, right after `embedding_env_override`): warns when the DB `config` row `embedding_model` has no provider prefix (managed fact extraction reads only that row and `config set` refuses it). The fix is the read-only `gbrain migrate embeddings --to <provider:model> --dry-run`, filled from `loadConfig()`'s provider-qualified `embedding_model`, or `<PROVIDER_MODEL>` plus an `inputs` entry when none is configured; `details.target_differs` flags a configured model with another name (applying it switches models). Applying re-embeds active facts (paid, user's call). The free relabel is parked (TODOS). Test: `test/doctor-embedding-identity-unqualified.test.ts`.- `src/commands/doctor/checks/embedding-state.ts` — `embedding_state` (#6696 B3, BRAIN, `tier: 'ops'`, `opsPglite: 'not_applicable'`, after `embeddings`): `readEmbeddingState` in `ops` mode on the ops tier, `full` otherwise. Warns only on chunks of pages soft-deleted past the 72 h purge window (`deleted_page_chunks_overdue`, fix `pages purge-deleted`) and, on a keyed brain, live pages with body text but no chunks (`chunkless_pages_healable`, fix `embed --stale`); the pending backlog stays `embeddings`' warning and quarantined pages `quarantined_pages`'. keyword_only, deleted chunks inside the window and a keyless brain are `infoCheck`; ops without a covering index warns with `details.health: 'unknown'` (`embedding_state_unknown`). Test: `test/doctor-embedding-state.test.ts`.- `src/commands/doctor/checks/knowledge-health.ts` — `facts_extraction_health` reads the last 24 h of `facts:absorb` rows in `ingest_log` (written by `src/core/facts/absorb-log.ts`) per source and reason (`split_part(summary, ':', 1)`) and warns when a failure reason reaches `facts.absorb_warn_threshold` (default 10) in a source. Two reasons are not failures and never count: `write_pending_accepted` (the absorb log read the facts write's receipt back from the journal and it is still queued, running or recovering after the job's publish wait) and `write_deferred_unadmitted` (`writer_lock_unavailable` before admission, no receipt; the job retries). Deferrals warn on their own when, in a source, more than 10 or one over an hour old have no later completed `facts-absorb` job for the same page; that warning's fix is the read-only `gbrain sources writer status --source <id> --json`. The failure count is history: the message gives the incidents in the rolling 24 h window and when the newest ages out, and `details.facts_absorb` (`incidents_24h`, `ages_out_at`, `jobs_still_dead`, `dead_jobs`) adds the current state, the `facts-absorb` jobs dead or failed in the last 24 h with no later completed job for the same page (source and slug); they never change the status, and when no other fix applies the newest one gets the paid `gbrain jobs retry <id>` fix (`retry_job` over MCP, asks first). Tests: `test/doctor-facts-absorb-contention-6778.test.ts`, `test/facts-absorb-publish-wait-6778.test.ts`, `test/doctor-facts-absorb-history-6761.test.ts`.diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex eb1e400d51..f3993a35b7 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -20,6 +20,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and reads the token's source, operation and takes-holder grant through `resolveTokenGrant` (`src/core/grants/legacy-token.ts`, shared with the legacy HTTP transport so the two transports cannot drift; a legacy-shape row converts to the grant columns on that read; `[]` takes-holders preserved as explicit deny-all, NULL → the `/mcp` dispatch site's fail-closed `['world']`). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`). `authorize()` only calls `grants.begin()` and redirects to `/admin/?oauth_request=<id>#oauth-consent`; codes are minted solely in `OAuthGrants.decide()` behind the admin cookie session and session-bound CSRF. `registerClient` (the unauthenticated DCR store method) computes the `grant_types` default (`authorization_code`) BEFORE the scope block, then calls `dcrScopeViolation` once and throws `InvalidClientMetadataError` (HTTP 400) on a privileged request — rejected, never silently dropped — before the unknown-scope filter runs; a registration that omits `scope` registers an empty scope (no default scope) and its consent request carries `scopes: []`. `allowClientCredentialsDcr` (`--enable-dcr-insecure`) yields anonymous READ-ONLY machine clients; that gate is evaluated BEFORE `dcrScopeViolation`, so a `client_credentials` request without the flag gets 'not permitted via dynamic client registration' rather than the misleading 'limited to `read`' ceiling message (pinned in `test/oauth-dcr-scope-ceiling.test.ts`). Downstream is already bounded: `OAuthGrants.begin()` snapshots the intersected grant, `exchangeCode` and `verifyAccessToken` re-intersect with the client's current scope. Operator paths (`registerClientManual`, CLI, admin API) do not use this store method and accept every canonical scope. Pinned in-process by `test/oauth-consent-security.test.ts` (live SDK `/register` with a foreign `redirect_uri`), against the real server by `test/e2e/serve-http-consent.test.ts`, and for the ceiling by `test/oauth-dcr-scope-ceiling.test.ts` + `test/oauth-authorize-scope-default.test.ts` (DCR client: `/authorize` `read write admin` -> code `['read','write']`, `admin` alone -> `[]`).+- `src/core/pg-tls.ts` — the one TLS resolver every `postgres()` pool in `src/` builds its options through (`withPgTls(url, opts)`; `test/pg-tls.test.ts` fails a call site that skips it). An explicit `ssl` option, URL `sslmode` / `ssl` / `sslrootcert=system`, or the driver's `PGSSL` wins unchanged; a loopback host (`localhost`, 127.0.0.0/8, ::1, a Unix socket) keeps the driver default; any other host, private and Docker service names included, gets `ssl: 'require'`. `sslmode=disable` in the URL is the opt-out. `tlsRequiredDefaultError` runs after a failed default-required connect (module pool, instance pool, direct pool): it sends the SSLRequest and turns a server's "no" into `postgres_tls_required` (classifier reason `tls_required_default`); DNS, refused and timeout failures are not probed. Docs: `docs/ENGINES.md#tls-for-postgres-connections`.+- `src/core/remote-body.ts` — linear protected-body sanitizer over the existing Facts parser/renderer. Processes every protected fence, retains only world Facts, removes all Takes and drops malformed protected sections. Chunk creation sanitizes full bodies before splitting. Page/history responses apply it whenever trust is not explicitly local, independently of page-visibility opt-outs and holder grants. Fences are located by `protectedRegions` (`src/core/fence-scan.ts`), shared with the strip functions, `preserveProtectedTakes` and the write projection: every marker token counts as in the lexical scan, and a region readers see runs past end markers quoted in code to the end readers pair with it, so the boundary never hides less than the lexical scan. Readers skip markers in inline code and trusted closed code blocks. Pinned by `test/fence-marker-code-context.test.ts`.- `src/core/scope.ts` — OAuth scope hierarchy + allowlist (the 6 scope strings, `hasScope`, `assertAllowedScopes`, `filterAllowedScopes`, `parseScopeString`, `normalizeScopesInput`) AND the anonymous-registration policy: `DCR_REGISTRABLE_SCOPES` (`read`, `write`) and `dcrScopeViolation(requested, grantTypes)` — returns `null` when the requested scopes fit the Dynamic Client Registration ceiling, otherwise the `invalid_client_metadata` message naming the offending scopes and the operator remedy (`gbrain auth register-client` / admin API / `gbrain auth rescope-client <client_id> --scopes ...`). `agent` keeps its own "operator-approved grant with explicit delegation bindings" wording; when `grantTypes` includes `client_credentials` (only reachable under `--enable-dcr-insecure`) the ceiling is `read` alone; unknown scope strings are ignored here (the unknown-filter drops them). `scopesSupportedForDiscovery({ enableDcr })` is the `scopes_supported` list for OAuth discovery (consumed by `serve-http.ts`'s `authRouterOptions`): the DCR-registrable subset (`read write`, canonical order) while DCR is enabled — so a client that copies discovery into its registration passes `dcrScopeViolation` — and every scope except `agent` otherwise; it never narrows an operator-registered client, because a client that omits `scope` at `/authorize` receives its full registered set via `grantScopes` (`oauth-grants.ts`) and an explicit request is intersected with the registration. The DCR constants and the helper sit BELOW `ALLOWED_SCOPES_LIST`, and no comment line pairs that identifier with `[`, because `scripts/check-admin-scope-drift.sh` extracts the allowlist block with an awk match on exactly that pair. Pinned by `test/scope.test.ts` + `test/oauth-dcr-scope-ceiling.test.ts` + the discovery test in `test/e2e/serve-http-consent.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 917a8556ba..e2ad50fa9d 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3590,6 +3590,14 @@ More: [docs/ENGINES.md#serve-deep-health](../../docs/ENGINES.md#serve-deep-healtMore: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### postgres_tls_required++<a id="postgres_tls_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| TLS was required by default for a non-local Postgres host, and the server does not accept TLS connections, so gbrain did not connect. | gbrain connects with sslmode=require to any Postgres host that is not on this machine (localhost, 127.0.0.0/8, ::1 or a Unix socket) unless the database URL names an sslmode, so the password and page contents never cross a network in plaintext without an explicit choice. Brains whose URL had no sslmode connected in plaintext before this default. | Turn TLS on at the database server and keep the default (sslmode=require encrypts; sslmode=verify-full with the server CA also verifies the certificate). To keep connecting without TLS on a network you trust, add sslmode=disable to the database URL. Run: gbrain engine status --probe --json | user | `gbrain doctor --only postgres_tls --json` | 1 | no |+### preparation_stalled<a id="preparation_stalled"></a>diff --git a/docs/guides/pooler-misroute-audit.md b/docs/guides/pooler-misroute-audit.mdindex 2ab18b9290..ad476f902a 100644--- a/docs/guides/pooler-misroute-audit.md+++ b/docs/guides/pooler-misroute-audit.md@@ -38,7 +38,7 @@ from the gbrain repository at this version or later, then:```bashbun audit-pooler-misroute.ts \- --url 'postgresql://postgres:<password>@db.<project>.supabase.co:5432/postgres' \+ --url 'postgresql://postgres:<password>@db.<project>.supabase.co:5432/postgres?sslmode=require' \--since 2026-10-01T00:00:00Z --until 2026-10-12T18:00:00Z --json > audit.json```diff --git a/docs/guides/servers-today.md b/docs/guides/servers-today.mdindex 6422e16e1a..d4950a3bb5 100644--- a/docs/guides/servers-today.md+++ b/docs/guides/servers-today.md@@ -8,7 +8,7 @@ is the planned way to run many brains in one process.## Pick the brain's shape-- **No-root (database-only).** `gbrain init --db-only --url postgresql://<user>:<password>@<host>:5432/<database>`+- **No-root (database-only).** `gbrain init --db-only --url 'postgresql://<user>:<password>@<host>:5432/<database>?sslmode=require'`keeps the brain in the database with no content directory or checkout.Any host can publish its writes, so a replaced container never strandsthem. Take markdown out with `gbrain export`.diff --git a/docs/tutorials/personal-brain.md b/docs/tutorials/personal-brain.mdindex bb97d227ea..ba052dd7d2 100644--- a/docs/tutorials/personal-brain.md+++ b/docs/tutorials/personal-brain.md@@ -157,13 +157,15 @@ In the Supabase dashboard, click **Connect** in the top navigation bar, then **CYou want the **Transaction pooler** string. Format looks like:```-postgresql://postgres.YOUR-PROJECT:[email protected]:6543/postgres+postgresql://postgres.YOUR-PROJECT:[email protected]:6543/postgres?sslmode=require```+Keep the `?sslmode=require` on the end. It makes the connection encrypted, which gbrain requires for any database that isn't on your own machine (it adds it for you if you leave it off). It does not check the server's certificate, though. To check it too, download Supabase's CA certificate (**Project Settings → Database → SSL Configuration**), set `NODE_EXTRA_CA_CERTS` to its path in `~/.gbrain/env`, and use `?sslmode=verify-full` instead ([details](../ENGINES.md#tls-for-postgres-connections)).+Configure it via:```bash-gbrain config set database_url "postgresql://postgres.YOUR-PROJECT:[email protected]:6543/postgres"+gbrain config set database_url "postgresql://postgres.YOUR-PROJECT:[email protected]:6543/postgres?sslmode=require"```This writes `~/.gbrain/config.json` (file-plane routed) and infers@@ -179,7 +181,7 @@ Two ways to fix it. The free one first:**Free: point GBrain's direct connection at the Session pooler.** The session pooler is the same Supavisor host on port 5432, and it's IPv4. Copy the **Session pooler** string from the same **Connect → Connection String** panel and set it as the direct-connection override:```bash-export GBRAIN_DIRECT_DATABASE_URL="postgresql://postgres.YOUR-PROJECT:[email protected]:5432/postgres"+export GBRAIN_DIRECT_DATABASE_URL="postgresql://postgres.YOUR-PROJECT:[email protected]:5432/postgres?sslmode=require"```Now both pools — reads on the transaction pooler (6543), DDL and locks on the session pooler (5432) — run over IPv4 at zero extra cost.diff --git a/llms-full.txt b/llms-full.txtindex b8356e3356..22bae2898c 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5708,6 +5708,46 @@ analyzes the tables. If a refresh is skipped (a lock, or a role that does notown the tables), run `ANALYZE content_chunks(model, modality, page_id, body_generation)` and`ANALYZE pages` as the table owner.+### TLS for Postgres connections++Every Postgres connection gbrain opens to a host that is **not on this+machine** requires TLS unless the database URL says otherwise. On this+machine means `localhost`, `127.0.0.0/8`, `::1` or a Unix socket path;+everything else needs TLS, including private addresses (`10.x`,+`192.168.x`) and Docker service names such as `postgres-1`, because gbrain+cannot tell a trusted network from an untrusted one by its name.+(`src/core/pg-tls.ts` is the one resolver every connection pool uses.)++| URL says | What gbrain does |+|---|---|+| no `sslmode`, host on this machine | plaintext, as before |+| no `sslmode`, any other host | `sslmode=require` |+| `?sslmode=require` | encrypts the connection; does **not** verify the server certificate |+| `?sslmode=verify-full` | encrypts and verifies the certificate and host name against the CA store |+| `?sslmode=disable` | plaintext; the one opt-out, for a network you trust |++An sslmode (or `ssl=`, or `sslrootcert=system`) in the URL is always+honored and never weakened, and so is the driver's own `PGSSL` variable.++`require` stops anyone on the network from reading the traffic, but it would+not notice an attacker who sits in the middle and presents their own+certificate. For that, use `verify-full`. It checks the server certificate+against Node's CA store, so a provider with its own CA needs that CA added:+Supabase publishes it under **Project Settings → Database → SSL+Configuration → Download certificate**. Put the file on the brain host and set+`NODE_EXTRA_CA_CERTS=/path/to/prod-ca-2021.crt` in the environment gbrain+runs in (for the installed service, `~/.gbrain/env`), then use+`?sslmode=verify-full`. A `sslrootcert=<file>` parameter is not read by the+driver; use `NODE_EXTRA_CA_CERTS` instead.++A server that does not accept TLS fails the connection with+[`postgres_tls_required`](guides/error-codes.md#postgres_tls_required),+which names both choices: turn TLS on at the server, or add+`sslmode=disable` to the URL. Nothing falls back to plaintext on its own.+`gbrain doctor --only postgres_tls` reports whether the current session is+encrypted (`pg_stat_ssl`) and warns for a non-local brain that is not. PGLite+opens no network connection, so none of this applies to it.+### Vector index sizingThe chunk HNSW index stores each vector beside its graph links, so at 1,024@@ -6488,6 +6528,7 @@ names — reasons may be added, never renamed or removed). All 16:| `schema_missing` | 42P01/42703 — pending migrations (`gbrain apply-migrations --yes`; excluded from the db-repair marker on the MCP mid-operation path, where it usually means code skew) || `pgvector_missing` | the vector extension is absent — auto tier creates it || `storage_corrupt` | XX001/XX002, or an XX000 such as `unexpected chunk number … for toast value` or `tuple concurrently deleted` — stored data is damaged; db-repair stops at manual and names the first step, `gbrain repair orphan-children` (preview, includes the torn-TOAST probe; [orphan children](guides/repair.md#orphan-children)) |+| `tls_required_default` | `postgres_tls_required`: gbrain's TLS default met a non-local server without TLS — db-repair stops at manual; turn TLS on at the server or add `sslmode=disable` ([TLS](#tls-for-postgres-connections)) || `unknown` | unclassified — redacted error + `gbrain doctor` |The classifier lives in `src/core/pg-access-classify.ts`; remediation copy hasdiff --git a/scripts/ci-local.sh b/scripts/ci-local.shindex e7a0cb36fa..1b6a9bb423 100755--- a/scripts/ci-local.sh+++ b/scripts/ci-local.sh@@ -166,12 +166,12 @@ env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun run test:slowecho "[runner] unit (unsharded, DATABASE_URL unset)"env -u DATABASE_URL bash scripts/run-unit-shard.shecho "[runner] PgBouncer admin database (gbrain_ci_admin_test on postgres-1)"-bun scripts/lib/ensure-e2e-database.ts postgresql://postgres:postgres@postgres-1:5432/gbrain_test gbrain_ci_admin_test \+bun scripts/lib/ensure-e2e-database.ts postgresql://postgres:postgres@postgres-1:5432/gbrain_test?sslmode=disable gbrain_ci_admin_test \|| { echo "[runner] ERROR: could not create gbrain_ci_admin_test; E2E not started" >&2; exit 1; }echo "[runner] e2e (unsharded)"-DATABASE_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_test \-GBRAIN_PGBOUNCER_URL=postgresql://postgres:postgres@pgbouncer:5432/gbrain_pgbouncer_test \-GBRAIN_PGBOUNCER_DIRECT_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_ci_admin_test \+DATABASE_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_test?sslmode=disable \+GBRAIN_PGBOUNCER_URL=postgresql://postgres:postgres@pgbouncer:5432/gbrain_pgbouncer_test?sslmode=disable \+GBRAIN_PGBOUNCER_DIRECT_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_ci_admin_test?sslmode=disable \GBRAIN_PGBOUNCER_E2E_DB=gbrain_test \GBRAIN_CI_REQUIRE_PGBOUNCER=1 \GBRAIN_TEST_DB=1 \@@ -203,7 +203,7 @@ export GBRAIN_TEST_TIMEOUT_MULTIPLIER=\${GBRAIN_TEST_TIMEOUT_MULTIPLIER:-6}# database (shard 1 uses postgres-1/gbrain_test), created once before any# shard starts.echo \"[runner] PgBouncer admin database (gbrain_ci_admin_test on postgres-1)\"-bun scripts/lib/ensure-e2e-database.ts postgresql://postgres:postgres@postgres-1:5432/gbrain_test gbrain_ci_admin_test \\+bun scripts/lib/ensure-e2e-database.ts postgresql://postgres:postgres@postgres-1:5432/gbrain_test?sslmode=disable gbrain_ci_admin_test \\|| { echo \"[runner] ERROR: could not create gbrain_ci_admin_test; shards not started\" >&2; exit 1; }mkdir -p /tmp/shard-logsecho \"[runner] Tier 1: 4-shard parallel unit + E2E (xargs -P4)\"@@ -223,9 +223,9 @@ printf '%s\\n' 1 2 3 4 | xargs -P4 -I{} sh -c '# Backend-matrix PgBouncer pass: the one pooler fronts postgres-1, so each# shard gets its own pooled database there (run-e2e.sh creates it).SHARD=\${shard}/4 \\- DATABASE_URL=postgresql://postgres:postgres@postgres-\${shard}:5432/gbrain_test \\- GBRAIN_PGBOUNCER_URL=postgresql://postgres:postgres@pgbouncer:5432/gbrain_pgbouncer_test \\- GBRAIN_PGBOUNCER_DIRECT_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_ci_admin_test \\+ DATABASE_URL=postgresql://postgres:postgres@postgres-\${shard}:5432/gbrain_test?sslmode=disable \\+ GBRAIN_PGBOUNCER_URL=postgresql://postgres:postgres@pgbouncer:5432/gbrain_pgbouncer_test?sslmode=disable \\+ GBRAIN_PGBOUNCER_DIRECT_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_ci_admin_test?sslmode=disable \\GBRAIN_PGBOUNCER_E2E_DB=gbrain_pooled_\${shard}_test \\GBRAIN_CI_REQUIRE_PGBOUNCER=1 \\GBRAIN_TEST_DB=1 \\diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsvindex 24734842f9..a696f94843 100644--- a/scripts/core-world-reads-baseline.tsv+++ b/scripts/core-world-reads-baseline.tsv@@ -807,6 +807,7 @@ src/core/persistence/worktree-refresh.ts process_env 7 W6: settings plane out ofsrc/core/persistence/write-wait.ts load_config 2 W6: settings plane out of the coresrc/core/persistence/write-wait.ts process_env 3 W6: settings plane out of the coresrc/core/pg-access-classify.ts process_env 1 W6: settings plane out of the core+src/core/pg-tls.ts process_env 1 postgres.js reads PGHOST, PGPORT and PGSSL from the process itself, so the TLS default reads the same values to judge the host it will dialsrc/core/pg-type-cache.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/pg-type-cache.ts module_collection 2 W6: per-engine state, or mark as a constant tablesrc/core/pg-type-cache.ts process_env 1 W6: settings plane out of the corediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 71d0966adc..7f9faf8f86 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -21,7 +21,7 @@ src/core/import-file.ts 2088 ratchet +2 #7880: importFromContent's holdNoncanonisrc/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 249 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import; +1 GBRA-156: whois import (ops/whois.ts; spread shares the chunks line); +1 GST-359 D: qmMemoryOperations import (ops/qm-memory.ts; spread shares the memory line); re-summed at the train R merge with v0.60.574.0: 246 + 1; re-summed at the memory train #8481 merge with v0.60.576.0 (248 measured); +1 Wakeshift PR 1: wakeshiftOperations import (ops/wakeshift.ts; its spread shares the jobs line)src/core/pglite-engine.ts 3103 ratchet +9 #7191: findPages/countPagesBy delegates and imports (SQL in engine-sql/page-lookup.ts); +4 GBRA-283 B1 (#8455): initSchema seeds an engine opened from settings with settings.embedding and refuses a mismatch, and its open skips the snapshot fast path (logic in embedded-engine.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3097 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move)-src/core/postgres-engine.ts 3178 ratchet +9 #7191: findPages/countPagesBy scoped-read delegates and imports (SQL in engine-sql/page-lookup.ts); +6 GBRA-283 B1 (#8455): an engine opened from settings routes its direct URL and statement-description cache from its settings, and initSchema seeds settings.embedding and refuses a mismatch (logic in embedded-engine.ts; engine methods cannot move); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move); +2 wave-b PR 4 merged with #7218 (both sides added imports); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3155 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move); +7 GBRA-283 B1 review: the instance pool passes settings connection fields explicitly, initSchema reads the embedding identity again under the schema lock, and reconnect ends the superseded manager (engine methods cannot move); re-summed at the train R merge with v0.60.574.0: 3170 + 4; +4 #6318: withScopedReadTransaction runs a bounded preparation's read under its deadline (read-deadline.ts; reserved-connection envelope runDeadlineRead in postgres-engine/bounded-statement.ts) and adds statement_timeout to the transaction settings (engine methods cannot move): re-summed at the 0.60.583.0 merge: 3174 + 4+src/core/postgres-engine.ts 3180 ratchet +9 #7191: findPages/countPagesBy scoped-read delegates and imports (SQL in engine-sql/page-lookup.ts); +6 GBRA-283 B1 (#8455): an engine opened from settings routes its direct URL and statement-description cache from its settings, and initSchema seeds settings.embedding and refuses a mismatch (logic in embedded-engine.ts; engine methods cannot move); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move); +2 wave-b PR 4 merged with #7218 (both sides added imports); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3155 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move); +7 GBRA-283 B1 review: the instance pool passes settings connection fields explicitly, initSchema reads the embedding identity again under the schema lock, and reconnect ends the superseded manager (engine methods cannot move); re-summed at the train R merge with v0.60.574.0: 3170 + 4; +4 #6318: withScopedReadTransaction runs a bounded preparation's read under its deadline (read-deadline.ts; reserved-connection envelope runDeadlineRead in postgres-engine/bounded-statement.ts) and adds statement_timeout to the transaction settings (engine methods cannot move): re-summed at the 0.60.583.0 merge: 3174 + 4; +2 TLS default: the pg-tls import and the instance pool builds its options through withPgTls and turns a no-TLS refusal into postgres_tls_required (logic in pg-tls.ts; engine methods cannot move): 3178 + 2src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.tssrc/core/types.ts 2357 ratchet +2 #8664 agent label: WriteAttributionView.agent_label (+ its doc line; the header, record and read live in persistence/attribution.ts and ops/attribution.ts) +3 train R: #7491 SearchOpts identifier-probe field and #7175 keywordPhrase option (interface fields); +2 GBRA-154 #7175: SearchOpts.keywordPhrase (opt-in phrase factor); +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured); +2 GBRA-95 G7a follow-up: Page.withheld_source_path field; +2 #7600: SearchResult.quoted (interface field; logic in search/transcript-quote.ts); +1 #8377: ChronicleTimelineRow.trust_tier (interface field; chronicle reads quote rows by tier); re-summed at the train R merge with v0.60.574.0: 2354 + 1src/core/minions/queue.ts 2547 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured); +3 GBRA-133: the stall sweep deletes a drain-lease holder record whose lease lock is gone or expired@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1692 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1)+src/core/behavior-change-notice.ts 1693 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move): 1692 + 1diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.shindex 86bd3ddd6c..53e5441f30 100755--- a/scripts/run-e2e.sh+++ b/scripts/run-e2e.sh@@ -289,7 +289,11 @@ if [ -z "$PGBOUNCER_E2E_URL" ] && [ -n "$PGBOUNCER_E2E_DB" ]; thenecho "ERROR: GBRAIN_PGBOUNCER_E2E_DB needs GBRAIN_PGBOUNCER_URL (the pooler to reach it through)." >&2exit 2fi- PGBOUNCER_E2E_URL="${GBRAIN_PGBOUNCER_URL%/*}/${PGBOUNCER_E2E_DB}?prepare=false"+ # Keep the pooler URL's own query (ci-local's explicit sslmode=disable) on the derived URL.+ _pgb_base="${GBRAIN_PGBOUNCER_URL%%\?*}"+ _pgb_query=""+ case "$GBRAIN_PGBOUNCER_URL" in *\?*) _pgb_query="${GBRAIN_PGBOUNCER_URL#*\?}&" ;; esac+ PGBOUNCER_E2E_URL="${_pgb_base%/*}/${PGBOUNCER_E2E_DB}?${_pgb_query}prepare=false"fipooled_db_ready=0if [ -n "$PGBOUNCER_E2E_URL" ]; thendiff --git a/src/commands/db-repair.ts b/src/commands/db-repair.tsindex 324b9043f3..664b4c8c6f 100644--- a/src/commands/db-repair.ts+++ b/src/commands/db-repair.ts@@ -347,6 +347,7 @@ function tierOf(reason: PgAccessReason): 'auto' | 'rewrite' | 'manual' {case 'no_url':case 'env_shadowed':case 'storage_corrupt':+ case 'tls_required_default':case 'unknown':return 'manual';default: {@@ -811,6 +812,7 @@ async function applyLadder(case 'no_url':case 'env_shadowed':case 'storage_corrupt':+ case 'tls_required_default':case 'unknown':return manualStop();diff --git a/src/commands/doctor/checks/postgres-tls.ts b/src/commands/doctor/checks/postgres-tls.tsnew file mode 100644index 0000000000..f371abb24c--- /dev/null+++ b/src/commands/doctor/checks/postgres-tls.ts@@ -0,0 +1,76 @@+/**+ * postgres_tls: is this Postgres brain's connection encrypted? A brain on a+ * non-loopback host connected without TLS (the session's own pg_stat_ssl row)+ * is a warning that names the fix; an encrypted one is ok, with a note when+ * sslmode=require encrypts without verifying the server certificate. PGLite+ * opens no network connection and emits nothing. The TLS default itself is+ * src/core/pg-tls.ts.+ *+ * Behind a pooler (PgBouncer, Supavisor) pg_stat_ssl describes the pooler's+ * link to the database, not this client's link to the pooler; the message+ * says so when the URL asked for TLS but the session reads unencrypted.+ */++import { loadConfig } from '../../../core/config.ts';+import type { Action } from '../../../core/agent-output.ts';+import { pgConnectHosts, isLoopbackPgHost, resolvePgTls } from '../../../core/pg-tls.ts';+import { doctorVerify } from '../check-fix.ts';+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';++export interface SessionTls { ssl: boolean; version: string | null }++const TLS_FIX: Action = {+ ask_user: true,+ argv: ['gbrain', 'engine', 'status', '--probe', '--json'],+ consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Read-only: shows where the database URL comes from (an environment variable or the config file), which is where the sslmode setting goes.',+ user_message: 'This brain talks to a database server that is not on this machine without encryption, so the password and page contents cross the network in plaintext. Turn TLS on at the server and use sslmode=require (or sslmode=verify-full with the server CA, which also verifies the certificate) in the database URL; keep sslmode=disable only on a network you trust.',+ verify: doctorVerify('postgres_tls'),+ docs: 'docs/guides/error-codes.md#postgres_tls_required',+};++/** Pure: the finding for a connected Postgres brain, from its URL and its session's pg_stat_ssl row (null when unreadable). */+export function postgresTlsCheck(url: string, session: SessionTls | null, env: Record<string, string | undefined> = process.env): Check | null {+ const hosts = pgConnectHosts(url, {}, env);+ if (hosts.length > 0 && hosts.every(isLoopbackPgHost)) {+ return { name: 'postgres_tls', status: 'ok', message: 'The Postgres host is on this machine; TLS is not required.' };+ }+ if (!session) return null;+ const tls = resolvePgTls(url, {}, env);+ if (session.ssl) {+ const unverified = tls.mode === 'require' || tls.mode === 'prefer' || tls.mode === 'allow';+ return {+ name: 'postgres_tls', status: 'ok',+ message: `The connection to the non-local Postgres host is encrypted (${session.version ?? 'TLS'}).${unverified ? ' sslmode=' + tls.mode + ' does not verify the server certificate; sslmode=verify-full with the server CA also verifies it.' : ''}`,+ details: { ssl: true, version: session.version, sslmode: tls.mode },+ };+ }+ const optedOut = tls.mode === 'disable';+ return {+ name: 'postgres_tls', status: 'warn',+ message: optedOut+ ? 'Connected to a non-local Postgres host without TLS (sslmode=disable in the database URL): the password and page contents cross the network in plaintext. Turn TLS on at the server and use sslmode=require or sslmode=verify-full.'+ : `The non-local Postgres server reports this session as unencrypted although the URL asks for sslmode=${tls.mode}. Behind a pooler, this is the pooler's own link to the database; make sure that link is encrypted too.`,+ details: { ssl: false, sslmode: tls.mode },+ fix: TLS_FIX,+ };+}++async function runPostgresTls(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ if (engine.kind !== 'postgres') return checks;+ const url = loadConfig()?.database_url;+ if (!url) return checks;+ let session: SessionTls | null = null;+ try {+ const rows = await engine.executeRaw<{ ssl: boolean; version: string | null }>('SELECT ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid()');+ if (rows[0]) session = { ssl: rows[0].ssl === true, version: rows[0].version ?? null };+ } catch { /* pg_stat_ssl unreadable: no finding */ }+ const check = postgresTlsCheck(url, session);+ if (check) checks.push({ name: 'postgres_tls', status: check.status, message: check.message, ...(check.details ? { details: check.details } : {}), ...(check.fix ? { fix: check.fix } : {}) });+ return checks;+}++export const postgresTlsEntry: DoctorEntry = { name: 'postgres_tls', emits: ['postgres_tls'], run: runPostgresTls };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 87a3dfce38..76f66b7dbf 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -42,6 +42,7 @@ import {} from './checks/db-connection.ts';import { ipcSocketPathEntry } from './checks/local-ipc.ts';import { functionSearchPathEntry } from './checks/function-search-path.ts';+import { postgresTlsEntry } from './checks/postgres-tls.ts';import {pgvectorEntry,rlsEntry,@@ -224,6 +225,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [folderAccessEntry,sharedAgentAccessEntry,rlsEntry,+ postgresTlsEntry,functionSearchPathEntry,schemaVersionEntry,rlsEventTriggerEntry,diff --git a/src/commands/init.ts b/src/commands/init.tsindex 17c0437880..4e7e93d37f 100644--- a/src/commands/init.ts+++ b/src/commands/init.ts@@ -1694,7 +1694,7 @@ async function supabaseWizard(): Promise<string> {}console.log('\nEnter your Supabase/Postgres connection URL:');- console.log(' Format: postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres'); /* allow-pg-url-literal */+ console.log(' Format: postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres?sslmode=require'); /* allow-pg-url-literal */console.log(' Find it: Supabase Dashboard > Connect (top bar) > Connection String > Transaction pooler\n');const url = (await promptLineStderr('Connection URL: ')) ?? '';diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 9368f567d1..42d85af29b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1494,6 +1494,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.622.0', id: 'purge_cancels_deferred_write_gst1602', text: 'With `persistence.refresh_barrier` on, `gbrain forget <id> --purge` no longer refuses `purge_blocked_pending_recovery` while a write deferred behind a refresh holds the claim in its staged body: the deferred write was never claimed, so the purge cancels it with `purged_content`, as it does a queued one, and removes the content at once instead of up to 15 minutes later.' },{ since: '0.60.623.0', id: 'owner_reads_private_gst2059', text: 'A brain can now name its owner: `gbrain access owner set <member>` (config `access.owner_member`, an enabled member). Every remote credential or stdio server bound to that member reads the whole brain, `visibility: private` pages, privacy-alias pages (`access: private`, ...), derived and pinned-question pages included, through `get_page`, `search`, `query`, `recall` and the other page reads in the sources its grant reads, and `recall` returns its private facts. `readable_by` and folder rules still bind it, and it is not relaxed when it speaks for a shared-room audience. A page the owner\'s credential creates in `default` through `put_page` is not kept to the owner (no `readable_by: [member:<id>]`). Other members, unbound and public callers are unchanged. `_meta.access.relaxation` reads `owner` for such a call, and `gbrain access check --token <name>` reports it. `gbrain repair private-labels` (named runs only) previews the `access: private` labels stamped on ordinary pages with counts per category, keeps real restrictions, and clears the rest in reviewed batches (`--apply --expect <hash>`), recording each change so `--class restore` can put it back. The bulk-ingestion page template no longer writes an `access:` line; what each designation means is in docs/guides/access-designations.md.' },{ since: '0.60.626.0', id: 'record_origin_checkout_lockdown_8888', text: '`gbrain sources record-origin <id>... --remote --apply` now also turns git-lfs downloads and hooks off in each recorded source\'s existing checkout (its `.git/config`: `lfs.fetchexclude=*`, `core.hooksPath=/dev/null`, `lfs.locksverify=false`), not only on later reclones, in the repository\'s shared config, and refuses `write_failed` naming the key when a worktree-scoped or included setting still overrides one; a source already recorded as remote gets the lock-down on the next `--remote --apply` when its checkout lacks it, even when its files now use git-lfs, and a key that holds several values in that config is replaced by the one clone-time value. On a managed brain it takes the same worktree locks a reclone takes, refusing the id `source_busy` while a reclone, refresh or write holds them, and a reclone reads the record under its own locks. A write that fails is reported for its own id (`write_failed`) instead of ending the run. The git-lfs check reads a committed `.gitattributes` under a directory whose name holds a tab, ignores commented-out `filter=lfs` lines, says when a committed rule only declares an LFS filter, records a clone of an empty repository instead of refusing it, and names the cause of an `lfs_unknown` refusal.' },+ { since: 'TBD', id: 'postgres_tls_default', text: 'Postgres connections to a host that is not on this machine now require TLS (sslmode=require) unless the database URL names an sslmode; localhost, 127.0.0.0/8, ::1 and Unix sockets are unchanged. A private address or a Docker service name counts as not on this machine. A database server without TLS now fails to connect with `postgres_tls_required` instead of connecting in plaintext: turn TLS on at the server, or add `sslmode=disable` to the database URL to keep the old plaintext connection on a network you trust. `sslmode=require` encrypts but does not verify the server certificate; `sslmode=verify-full` (with the provider CA in `NODE_EXTRA_CA_CERTS`) verifies it too. `gbrain doctor --only postgres_tls` shows whether this brain\'s connection is encrypted.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.tsindex efcb865e6f..ff313c2a7c 100644--- a/src/core/connection-manager.ts+++ b/src/core/connection-manager.ts@@ -38,6 +38,7 @@import postgres from '#postgres'import { traceSqlOptions } from './sql-trace.ts';+import { tlsRequiredDefaultError, withPgTls } from './pg-tls.ts';import { gbrainApplicationName, readPoolPipelineOptions, transactionPipelineOptions, resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, resolveUrlConnectTimeout, resolveSharedTypes, resolveArrayTypes, endPoolBounded, poolHealthOptions, type PoolHealthHooks } from './db.ts';import { redactPgUrl } from './url-redact.ts';import { logConnectionEvent } from './connection-audit.ts';@@ -274,7 +275,7 @@ export class ConnectionManager {if (Object.keys(timeouts).length > 0) opts.connection = timeouts;const prepare = resolvePrepare(this.opts.url);if (typeof prepare === 'boolean') opts.prepare = prepare;- this._readPool = postgres(this.opts.url, traceSqlOptions(opts, 'read'));+ this._readPool = postgres(this.opts.url, traceSqlOptions(withPgTls(this.opts.url, opts), 'read'));logConnectionEvent({ pool: 'read', op: 'init' });return this._readPool;}@@ -436,8 +437,10 @@ export class ConnectionManager {};const t0 = Date.now();let pool: Sql | null = null;+ let directOpts: Record<string, unknown> = opts;try {- pool = postgres(this._directUrl, traceSqlOptions(this.opts.settingsConnection ? { ...opts, ...settingsConnectionOptions(this._directUrl) } : opts, 'direct'));+ directOpts = this.opts.settingsConnection ? { ...opts, ...settingsConnectionOptions(this._directUrl) } : opts;+ pool = postgres(this._directUrl, traceSqlOptions(withPgTls(this._directUrl, directOpts), 'direct'));// Probe to validate connectivity early.await pool`SELECT 1`;logConnectionEvent({@@ -457,7 +460,7 @@ export class ConnectionManager {duration_ms: Date.now() - t0,error: { message: err instanceof Error ? err.message : String(err) },});- throw err;+ throw (this._directUrl ? await tlsRequiredDefaultError(this._directUrl, err, directOpts) : null) ?? err;}}diff --git a/src/core/db.ts b/src/core/db.tsindex cb2fd3b189..e430095fbc 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -1,6 +1,7 @@import postgres from '#postgres'import { claimOwner, isOneShotCommand } from './persistence/claim-phase.ts';import { traceSqlOptions } from './sql-trace.ts';+import { tlsRequiredDefaultError, withPgTls } from './pg-tls.ts';import { beginReadWrite } from './postgres-engine/read-write-transactions.ts';import { warnPoolerPrepareOffOnce } from './pooler-notice.ts';import { GBrainError, type EngineConfig } from './types.ts';@@ -545,7 +546,7 @@ export async function connect(config: EngineConfig, hooks: PoolHealthHooks = {})opts.prepare = prepare;if (!prepare) warnPoolerPrepareOffOnce(url);}- sql = postgres(url, traceSqlOptions(opts, 'module'));+ sql = postgres(url, traceSqlOptions(withPgTls(url, opts), 'module'));// GBRA-156: a one-shot command's startup reads its retired-marker state beside its persistence row, which opened the// pool's second connection on the critical path (about three round trips behind a pooler); it opens beside the first.@@ -559,6 +560,8 @@ export async function connect(config: EngineConfig, hooks: PoolHealthHooks = {})} catch (e: unknown) {sql = null;connectedUrl = null;+ const tlsRefusal = await tlsRequiredDefaultError(url, e);+ if (tlsRefusal) throw tlsRefusal;const msg = e instanceof Error ? e.message : String(e);throw new GBrainError('Cannot connect to database',diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 7f676f4c6a..1195f74e2f 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -434,6 +434,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['grant_new_ops_available','reranker_health','rls',+ // The session's TLS state on a non-loopback Postgres host (doctor/checks/postgres-tls.ts).+ 'postgres_tls',// #7632: every gbrain function that pins a search_path ends it with pg_temp.'function_search_path','rls_event_trigger',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex af6d21fed8..95ed62601a 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -581,6 +581,7 @@ export const CODES = {publish_scan_unreadable: { class: 'host_only', summary: "An automatic publish could not read its local commits in full to scan them for secrets (a missing or corrupt object, git output the scan does not recognise, or the 300 s budget); no secret was reported and nothing was pushed.", docs: 'docs/guides/shared-checkout-git.md#publish_scan_unreadable', actor: 'user' },push_unconfirmed: { class: 'retryable', summary: "The commit is durable locally but no push destination confirmed it.", docs: 'docs/guides/shared-checkout-git.md#outcomes', exit: 4 },schema_lock_blocked: { class: 'retryable', summary: "A schema step (the schema.sql replay in init/upgrade, or one migration) waited its lock_timeout for a table lock another session holds and stopped instead of hanging.", why: "Every ALTER TABLE in the replay takes an ACCESS EXCLUSIVE lock even as a no-op, so one open transaction in another client (idle in transaction, a stuck job) blocked gbrain init and upgrade forever with no output. The wait is now bounded (GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS, default 60) and the refusal names the blocking sessions by pid, application and state, sampled while the wait was active; query text is never shown. The cancelled step changed nothing.", docs: 'docs/ENGINES.md#schema-lock-blocked', suggestion: 'Let the named session finish or, with the user\'s agreement, end it on the database host with SELECT pg_terminate_backend(<pid>), then rerun the same gbrain command; init retries a few times on its own with a short backoff.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the database, the pooler and the schema version so the rerun is judged against the current state.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },+ postgres_tls_required: { class: 'host_only', actor: 'user', retryable: false, summary: "TLS was required by default for a non-local Postgres host, and the server does not accept TLS connections, so gbrain did not connect.", why: "gbrain connects with sslmode=require to any Postgres host that is not on this machine (localhost, 127.0.0.0/8, ::1 or a Unix socket) unless the database URL names an sslmode, so the password and page contents never cross a network in plaintext without an explicit choice. Brains whose URL had no sslmode connected in plaintext before this default.", suggestion: 'Turn TLS on at the database server and keep the default (sslmode=require encrypts; sslmode=verify-full with the server CA also verifies the certificate). To keep connecting without TLS on a network you trust, add sslmode=disable to the database URL.', fix: { ask_user: true, argv: ['gbrain', 'engine', 'status', '--probe', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows where the database URL comes from (an environment variable or the config file), which is where the sslmode setting goes.', user_message: 'Your database server does not accept TLS, and gbrain now requires it for a server that is not on this machine. Either turn TLS on at the server (then nothing else changes), or, if this network is trusted, add sslmode=disable to the database URL to keep the old plaintext connection. sslmode=require and sslmode=verify-full are the secure choices.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'postgres_tls', '--json'] } } },pg_connection_recovery_failed: { class: 'retryable', summary: "A Postgres connection the driver retired after an incident (stuck, desynced, or closed under running statements) could not reconnect; statements waiting for it failed with the connect error.", why: "The database or pooler refused or dropped the new connection (unreachable host, exhausted connection slots, rotated credentials). The next statement retries the connect, and the connection stays marked until one succeeds, so a repeating line means the pool is not recovering on its own.", docs: 'docs/ENGINES.md#pg-connection-recovery-failed', suggestion: 'Check the database and pooler from the serve host (gbrain doctor --only pool_reap_health --json); a serve that keeps logging this line needs the database reachable again, then a restart if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--only', 'pool_reap_health', '--json'], consent: [], actor: 'agent', why: 'Read-only: counts the recent stuck, desync and recovery events serve recorded.', requires_exclusive: false } },pg_connection_stuck: { class: 'retryable', summary: "A pooled Postgres statement ran past its in-flight budget (the pool's statement_timeout plus grace, or the longer statement_timeout its operation declared) with nothing coming back from the server (reason=idle) or while bytes kept arriving (reason=age), so the driver retired that connection; the statement and everything queued behind it failed with CONNECTION_STUCK.", why: "Nothing arriving for that long usually means the connection is wedged: a pipeline the server and client no longer agree on, a transaction-mode pooler that swallowed a CancelRequest and left the backend in ClientRead, or a dead peer. It is not proof: behind a transaction-mode pooler the startup statement_timeout never applies (SHOW statement_timeout reads 0), so a legitimately slow statement can reach the budget too. reason=age is a statement that kept streaming rows or notices past its budget (#6543); an operation that needs longer declares it with SET LOCAL statement_timeout (0 for no limit), which the driver tracks per statement. Before #6383 such a connection held its queue forever while /health answered 200. The pool reconnects on its own; the warn line names the pool, the age, the queue depth and the statement by keyword and table.", docs: 'docs/ENGINES.md#pg-connection-stuck', suggestion: 'Retry the failed call. If the line repeats, run gbrain doctor --json and report the warn lines with the operations that preceded them; GBRAIN_PG_STUCK_GRACE_MS raises the grace, and off disables the watchdog.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports pool pressure, the pooler mode and the recent persistence hold lines beside this warning.', requires_exclusive: false } },pg_pool_stalled: { class: 'retryable', summary: "The Postgres pool of a resident gbrain process has had connections checked out or statements waiting for one across two 30 s ticks without completing a single statement.", why: "One slow statement is one quiet tick; two in a row with nothing settled means every checked-out connection is waiting on the server at once, which is what a wedged pool or an unreachable database looks like from inside the process. With the in-flight watchdog on, the stall ends within statement_timeout plus grace and a pg_pool_recovered line follows; with it off this line is the only trace.", docs: 'docs/ENGINES.md#pg-pool-stalled', suggestion: 'Wait one more tick for pg_pool_recovered or pg_connection_stuck; if the line keeps repeating, check the database and pooler (gbrain doctor --json) and restart the process if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: checks the database and pooler from a fresh process beside the stalled one.', requires_exclusive: false } },diff --git a/src/core/persistence/graduation-target.ts b/src/core/persistence/graduation-target.tsindex ceb9b18490..2db76774f8 100644--- a/src/core/persistence/graduation-target.ts+++ b/src/core/persistence/graduation-target.ts@@ -15,6 +15,7 @@* automatic session-pooler fallback for this operation.*/import postgres from '#postgres';+import { withPgTls } from '../pg-tls.ts';import { createHash, randomInt } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import { PostgresEngine } from '../postgres-engine.ts';@@ -89,7 +90,7 @@ function classifyConnectError(error: unknown): { reachable: boolean; auth: boole}function probeClient(url: string, timeoutSeconds: number) {- return postgres(url, { max: 1, prepare: false, connect_timeout: timeoutSeconds, idle_timeout: 1, onnotice: () => {} });+ return postgres(url, withPgTls(url, { max: 1, prepare: false, connect_timeout: timeoutSeconds, idle_timeout: 1, onnotice: () => {} }));}function versionAtLeast(version: string | null, min: string): boolean {diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 47c067bd3d..cf9e5271c0 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -225,7 +225,7 @@ export function assertPersistenceAccepting(engine: BrainEngine): void {}/** DX-A3: pending heads that need intervention, not more waiting. */export const BLOCKED_WRITE_REASONS = ['recovery_required', 'owner_unavailable', 'unexpected_file_bytes', 'unexpected_staging_bytes'] as const;-const FATAL_READ_REASONS: readonly PgAccessReason[] = ['auth_failed', 'permission_denied', 'tenant_not_found', 'db_missing', 'schema_missing', 'storage_corrupt'];+const FATAL_READ_REASONS: readonly PgAccessReason[] = ['auth_failed', 'permission_denied', 'tenant_not_found', 'db_missing', 'schema_missing', 'storage_corrupt', 'tls_required_default'];/** CEO-A7: the first poll waits this long (at most half the wait) for an in-process handoff, or not at all when this process already settled the request; later polls back off from 50 to 250 ms. */export const WRITE_POLL_START_MS = 200;export type WriteWait =diff --git a/src/core/pg-access-classify.ts b/src/core/pg-access-classify.tsindex 03a1628ad2..ee8c6d3065 100644--- a/src/core/pg-access-classify.ts+++ b/src/core/pg-access-classify.ts@@ -45,6 +45,7 @@ import {isSupabasePoolerUrl,} from './supabase-pooler-url.ts';import { extractProjectRef } from './supabase-admin.ts';+import { CODES } from './error-registry.ts';/*** APPEND-ONLY. Consumers switch exhaustively with a `never` sentinel@@ -68,6 +69,7 @@ export type PgAccessReason =| 'schema_missing' // 42P01 / 42703 missing relation or column| 'pgvector_missing' // vector extension absent| 'storage_corrupt' // XX000/XX001/XX002: torn TOAST value, catalog/tuple damage (#5216, #4738)+ | 'tls_required_default' // postgres_tls_required: gbrain's TLS default met a non-local server without TLS| 'unknown';export type PgAccessFix =@@ -163,7 +165,8 @@ interface ReasonRow {/** Code-prefix matches (e.g. every 08xxx connection SQLSTATE). */codePrefixes?: string[];patterns?: RegExp[];- remediation: string;+ /** Left out only on a row for a gbrain-coded error: its advice is that code's error-registry suggestion. */+ remediation?: string;/** E10: the same advice without Supabase specifics, used when the configured URL is not a Supabase host. */plainRemediation?: string;fix?: PgAccessFix;@@ -179,6 +182,11 @@ interface ReasonRow {* second person, never preachy.*/const REASON_ROWS: ReadonlyArray<ReasonRow> = [+ {+ reason: 'tls_required_default',+ transient: false,+ codes: ['postgres_tls_required'],+ },{reason: 'storage_corrupt',transient: false,@@ -406,7 +414,8 @@ export function classifyPgAccessError(err: unknown, ctx?: PgAccessContext): PgActransient: row.transient,sqlstate: looksLikeSqlstate(code),message,- remediation: ctx?.url && !looksLikeSupabase(ctx.url) && row.plainRemediation ? row.plainRemediation : row.remediation,+ remediation: ctx?.url && !looksLikeSupabase(ctx.url) && row.plainRemediation ? row.plainRemediation+ : row.remediation ?? (CODES as Record<string, { suggestion?: string }>)[code ?? '']?.suggestion ?? UNKNOWN_REMEDIATION,fix: contextualFix(row.reason, ctx?.url) ?? row.fix,supabase: supabaseHints(ctx?.url, row.reason),brainId: ctx?.brainId,diff --git a/src/core/pg-tls.ts b/src/core/pg-tls.tsnew file mode 100644index 0000000000..2dcb55cdbf--- /dev/null+++ b/src/core/pg-tls.ts@@ -0,0 +1,150 @@+/**+ * TLS for every postgres() pool gbrain opens (one resolver, every call site).+ *+ * The vendored postgres.js defaults to `ssl: false`, so a URL without an+ * sslmode connected in plaintext even to a database across the internet. Each+ * call site now builds its options through `withPgTls(url, opts)`:+ *+ * 1. An explicit setting wins and is never changed: an `ssl` option the call+ * site passes, `sslmode` / `ssl` / `sslrootcert=system` in the URL, or+ * the driver's own PGSSL environment variable (which it reads itself).+ * 2. Otherwise a host on this machine keeps the driver default (no TLS):+ * localhost, 127.0.0.0/8, ::1 (and ::ffff:127.x) or a Unix socket path.+ * 3. Otherwise TLS is required (`ssl: 'require'`). That includes private+ * addresses and Docker service names: gbrain cannot tell a trusted network+ * from an untrusted one by name, so they opt out like any other host.+ *+ * The one opt-out is `sslmode=disable` in the URL. `require` encrypts the+ * connection but does not verify the server certificate (postgres.js sets+ * rejectUnauthorized=false for it); `sslmode=verify-full` with the server's CA+ * also verifies it. PGLite opens no network connection, so none of this+ * applies to it.+ *+ * When a default-required connection fails, `tlsRequiredDefaultError` asks+ * the server directly (the protocol's 8-byte SSLRequest) whether it speaks+ * TLS; a plain "no" becomes the coded `postgres_tls_required` error instead+ * of the driver's unreadable TLS handshake failure.+ */++import { connect as netConnect, isIP } from 'node:net';+import type { OperationError } from './ops/contract.ts';++export type PgTlsSource = 'option' | 'url' | 'env' | 'loopback' | 'default';++export interface PgTlsResolution {+ source: PgTlsSource;+ /** The mode in effect as text: the URL's sslmode, 'require' for the default, 'driver-default' on loopback. */+ mode: string;+}++type Env = Record<string, string | undefined>;++/** PGHOST, PGPORT and PGSSL, read the way the driver reads them, so the default matches the host it dials. */+const processEnv = (): Env => process.env;++export function isLoopbackPgHost(host: string): boolean {+ const h = host.trim().toLowerCase().replace(/^\[(.*)\]$/, '$1');+ if (!h) return false;+ if (h.startsWith('/')) return true;+ if (h === 'localhost') return true;+ if (isIP(h) === 4) return h.startsWith('127.');+ if (isIP(h) === 6) {+ if (h === '::1' || /^(0{1,4}:){7}0{0,3}1$/.test(h)) return true;+ const mapped = h.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);+ return !!mapped && mapped[1].startsWith('127.');+ }+ return false;+}++function stripPort(entry: string): string {+ const e = entry.trim();+ if (e.startsWith('[')) return e.slice(1, e.indexOf(']') > 0 ? e.indexOf(']') : undefined);+ return (e.match(/:/g) ?? []).length === 1 ? e.slice(0, e.indexOf(':')) : e;+}++/** The hosts the driver will dial, read the way postgres.js reads them (options, URL host list, PGHOST, localhost). */+export function pgConnectHosts(url: string, opts: Record<string, unknown> = {}, env: Env = processEnv()): string[] {+ if (typeof opts.path === 'string' && opts.path) return [opts.path];+ const optHost = typeof opts.hostname === 'string' ? opts.hostname : typeof opts.host === 'string' ? opts.host : '';+ let urlHost = '';+ const afterScheme = url.indexOf('://') >= 0 ? url.slice(url.indexOf('://') + 3) : '';+ const authority = afterScheme.split(/[?/]/)[0] ?? '';+ try { urlHost = decodeURIComponent(authority.slice(authority.lastIndexOf('@') + 1)); } catch { urlHost = authority.slice(authority.lastIndexOf('@') + 1); }+ const raw = optHost || urlHost || env.PGHOST || 'localhost';+ if (raw.startsWith('/')) return [raw];+ return raw.split(',').map(stripPort).filter(Boolean);+}++function urlParams(url: string): URLSearchParams {+ const q = url.indexOf('?');+ return new URLSearchParams(q >= 0 ? url.slice(q + 1).split('#')[0] : '');+}++export function resolvePgTls(url: string, opts: Record<string, unknown> = {}, env: Env = processEnv()): PgTlsResolution {+ if ('ssl' in opts && opts.ssl !== undefined) return { source: 'option', mode: typeof opts.ssl === 'string' ? opts.ssl : String(opts.ssl === false ? 'disable' : 'custom') };+ const params = urlParams(url);+ const explicit = params.get('sslmode') ?? params.get('ssl') ?? (params.get('sslrootcert') === 'system' ? 'verify-full' : null);+ if (explicit !== null) return { source: 'url', mode: explicit === 'false' ? 'disable' : explicit };+ if (env.PGSSL) return { source: 'env', mode: env.PGSSL };+ const hosts = pgConnectHosts(url, opts, env);+ if (hosts.length > 0 && hosts.every(isLoopbackPgHost)) return { source: 'loopback', mode: 'driver-default' };+ return { source: 'default', mode: 'require' };+}++/** The options to hand postgres(): unchanged unless the TLS default applies, then with `ssl: 'require'`. */+export function withPgTls<T extends Record<string, unknown>>(url: string, opts: T, env: Env = processEnv()): T {+ return resolvePgTls(url, opts, env).source === 'default' ? { ...opts, ssl: 'require' } : opts;+}++/** Ask a Postgres server whether it accepts TLS: 'S' yes, 'N' no, null when it could not be asked. */+export function probeServerTls(host: string, port: number, timeoutMs = 3000): Promise<'S' | 'N' | null> {+ return new Promise(resolve => {+ let settled = false;+ const finish = (v: 'S' | 'N' | null) => { if (settled) return; settled = true; clearTimeout(timer); socket.destroy(); resolve(v); };+ const socket = netConnect({ host, port });+ const timer = setTimeout(() => finish(null), timeoutMs);+ socket.once('connect', () => socket.write(Buffer.from([0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f])));+ socket.once('data', d => finish(d[0] === 0x53 ? 'S' : d[0] === 0x4e ? 'N' : null));+ socket.once('error', () => finish(null));+ socket.once('close', () => finish(null));+ });+}++/** Failures that happen before or after the TLS handshake (DNS, refused, timeout, a server SQLSTATE): no probe. */+const NOT_A_TLS_REFUSAL: ReadonlySet<string> = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ETIMEDOUT', 'CONNECT_TIMEOUT', 'ENETUNREACH', 'EHOSTUNREACH']);++function firstHostPort(url: string, opts: Record<string, unknown>, env: Env): { host: string; port: number } | null {+ const host = pgConnectHosts(url, opts, env)[0];+ if (!host || host.startsWith('/')) return null;+ if (typeof opts.port === 'number') return { host, port: opts.port };+ const authority = (url.slice(url.indexOf('://') + 3).split(/[?/]/)[0] ?? '').split('@').pop() ?? '';+ const first = authority.split(',')[0] ?? '';+ const port = first.startsWith('[') ? first.slice(first.indexOf(']') + 2) : first.includes(':') ? first.slice(first.lastIndexOf(':') + 1) : '';+ return { host, port: Number(port) || Number(env.PGPORT) || 5432 };+}++/** The coded refusal; its text, why and fix live once, in the error registry entry. */+export async function postgresTlsRequiredError(): Promise<OperationError> {+ const [{ opError }, { CODES }] = await Promise.all([import('./ops/contract.ts'), import('./error-registry.ts')]);+ const entry = CODES.postgres_tls_required;+ return opError('postgres_tls_required', entry.summary, entry.suggestion, { why: entry.why, fix: { ...entry.fix, docs: 'docs/guides/error-codes.md#postgres_tls_required' } });+}++/**+ * After a connect failure: the coded error when the TLS default applied and the+ * server answers the SSLRequest with "no"; null otherwise (the original error stands).+ */+export async function tlsRequiredDefaultError(+ url: string,+ error: unknown,+ opts: Record<string, unknown> = {},+ probe: (host: string, port: number) => Promise<'S' | 'N' | null> = probeServerTls,+ env: Env = processEnv(),+): Promise<OperationError | null> {+ if (resolvePgTls(url, opts, env).source !== 'default') return null;+ const code = String((error as { code?: unknown } | null)?.code ?? '');+ if (NOT_A_TLS_REFUSAL.has(code) || /^[0-9A-Z]{5}$/.test(code)) return null;+ const target = firstHostPort(url, opts, env);+ if (!target) return null;+ return (await probe(target.host, target.port)) === 'N' ? await postgresTlsRequiredError() : null;+}diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 9c9d976bd4..86a0c9fb98 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -21,6 +21,7 @@ import postgres from '#postgres'import { reservedTransactions, type ReservedTransactions } from './postgres-engine/reserved-transactions.ts';import { holdSearchConnection } from './search/connection-budget.ts';import { traceSqlOptions } from './sql-trace.ts';+import { tlsRequiredDefaultError, withPgTls } from './pg-tls.ts';import { hasPostgresCancellationCapability, postgresCancellationUnavailable, reserveWithCancellation } from './postgres-engine/cancellation.ts';import { runBoundedStatement, runDeadlineRead } from './postgres-engine/bounded-statement.ts';import { needsJitOff, runJitOffStatement } from './postgres-engine/jit-off-statement.ts';@@ -468,8 +469,9 @@ export class PostgresEngine implements BrainEngine {if (typeof prepare === 'boolean') {opts.prepare = prepare;}- this._sql = postgres(url, traceSqlOptions(embedded ? { ...opts, ...settingsConnectionOptions(url) } : opts, 'instance'));- await db.checkPoolAndLoadSharedTypes(this._sql, url, { persisted: !embedded });+ const instanceOpts = embedded ? { ...opts, ...settingsConnectionOptions(url) } : opts;+ this._sql = postgres(url, traceSqlOptions(withPgTls(url, instanceOpts), 'instance'));+ await db.checkPoolAndLoadSharedTypes(this._sql, url, { persisted: !embedded }).catch(async (e: unknown) => { throw (await tlsRequiredDefaultError(url, e, instanceOpts)) ?? e; });await db.setSessionDefaults(this._sql);this._connectionStyle = 'instance';diff --git a/src/core/postgres-engine/schema-lock-timeout.ts b/src/core/postgres-engine/schema-lock-timeout.tsindex 31365d2cc5..fe853772dd 100644--- a/src/core/postgres-engine/schema-lock-timeout.ts+++ b/src/core/postgres-engine/schema-lock-timeout.ts@@ -18,6 +18,7 @@* is never read: the message carries identifiers only.*/import postgres from '#postgres';+import { withPgTls } from '../pg-tls.ts';import { opError, type OperationError } from '../ops/contract.ts';import { isLockTimeoutError } from '../retry-matcher.ts';@@ -100,7 +101,7 @@ export function schemaLockBlockedError(input: { step: string; timeoutMs: number;export function schemaDiagnosticConnection(url: string | undefined): SchemaLockTimeoutOpts['diagnostic'] {if (!url) return undefined;return async () => {- const sql = postgres(url, { max: 1, connect_timeout: 10, prepare: false, onnotice: () => {}, connection: { application_name: 'gbrain-schema-lock-diagnostic' } });+ const sql = postgres(url, withPgTls(url, { max: 1, connect_timeout: 10, prepare: false, onnotice: () => {}, connection: { application_name: 'gbrain-schema-lock-diagnostic' } }));return { unsafe: (query: string, params?: unknown[]) => sql.unsafe(query, params as never), end: () => sql.end({ timeout: 5 }) };};}diff --git a/test/doctor-postgres-tls.test.ts b/test/doctor-postgres-tls.test.tsnew file mode 100644index 0000000000..ae79000bd2--- /dev/null+++ b/test/doctor-postgres-tls.test.ts@@ -0,0 +1,64 @@+/**+ * postgres_tls doctor finding (src/commands/doctor/checks/postgres-tls.ts): a+ * Postgres brain on a non-loopback host connected without TLS warns and names+ * the fix. The live pg_stat_ssl read is covered by test/e2e/pg-tls-postgres.test.ts;+ * PGLite has no network connection, so the entry emits nothing there.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { postgresTlsCheck, postgresTlsEntry } from '../src/commands/doctor/checks/postgres-tls.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => { if (engine) await engine.disconnect(); }, 60_000);++const REMOTE = 'postgres://u:[email protected]:5432/brain';++describe('postgres_tls doctor check', () => {+ test('a non-loopback brain connected without TLS warns and names the fix', () => {+ const c = postgresTlsCheck(REMOTE + '?sslmode=disable', { ssl: false, version: null }, {})!;+ expect(c.status).toBe('warn');+ expect(c.message).toContain('without TLS');+ expect(c.message).toContain('sslmode=require');+ expect((c.fix as { ask_user?: boolean } | undefined)?.ask_user).toBe(true);+ expect(c.fix?.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'postgres_tls', '--json']);+ expect(categorizeCheck('postgres_tls')).toBe('ops');+ });++ test('a session the server reports unencrypted warns even when the URL asked for TLS (a pooler hop)', () => {+ const c = postgresTlsCheck(REMOTE, { ssl: false, version: null }, {})!;+ expect(c.status).toBe('warn');+ expect(c.message).toContain('pooler');+ });++ test('an encrypted non-loopback session is ok and says require does not verify the certificate', () => {+ const c = postgresTlsCheck(REMOTE, { ssl: true, version: 'TLSv1.3' }, {})!;+ expect(c.status).toBe('ok');+ expect(c.message).toContain('TLSv1.3');+ expect(c.message).toContain('verify-full');+ const verified = postgresTlsCheck(REMOTE + '?sslmode=verify-full', { ssl: true, version: 'TLSv1.3' }, {})!;+ expect(verified.message).not.toContain('does not verify');+ });++ test('a loopback host is ok without TLS', () => {+ expect(postgresTlsCheck('postgres://[email protected]:5432/brain', { ssl: false, version: null }, {})!.status).toBe('ok');+ });++ test('an unreadable pg_stat_ssl on a remote host emits nothing', () => {+ expect(postgresTlsCheck(REMOTE, null, {})).toBeNull();+ });++ test('the entry is registered and emits nothing on PGLite', async () => {+ expect(DOCTOR_CHECK_REGISTRY).toContain(postgresTlsEntry);+ expect(await postgresTlsEntry.run({ engine } as never)).toEqual([]);+ });+});diff --git a/test/e2e/pg-tls-postgres.test.ts b/test/e2e/pg-tls-postgres.test.tsnew file mode 100644index 0000000000..e4153e6f14--- /dev/null+++ b/test/e2e/pg-tls-postgres.test.ts@@ -0,0 +1,89 @@+/**+ * Postgres arm of the TLS default (src/core/pg-tls.ts), against real servers.+ *+ * - DATABASE_URL (the CI lane: a loopback server without TLS) still connects+ * in plaintext, and the doctor finding reads ok.+ * - GBRAIN_TEST_PG_TLS_REMOTE_URL: a TLS-enabled server reached through a+ * non-loopback address, with no sslmode in the URL. Both pool kinds connect+ * encrypted (pg_stat_ssl.ssl = true).+ * - GBRAIN_TEST_PG_PLAIN_REMOTE_URL: a server with ssl=off reached through a+ * non-loopback address, no sslmode. connect() refuses with+ * postgres_tls_required; the same URL plus sslmode=disable connects and the+ * doctor finding warns.+ *+ * The two remote URLs need a container reached through its bridge address, so+ * they are opt-in (they skip when unset); see the PR for the docker commands.+ */++import { describe, test, expect } from 'bun:test';+import * as db from '../../src/core/db.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { postgresTlsCheck } from '../../src/commands/doctor/checks/postgres-tls.ts';++const LOCAL = process.env.DATABASE_URL;+const TLS_REMOTE = process.env.GBRAIN_TEST_PG_TLS_REMOTE_URL;+const PLAIN_REMOTE = process.env.GBRAIN_TEST_PG_PLAIN_REMOTE_URL;+const SESSION_SSL = 'SELECT ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid()';++async function moduleSessionTls(url: string): Promise<{ ssl: boolean; version: string | null }> {+ await db.connect({ database_url: url } as never);+ try {+ const [row] = await db.getConnection().unsafe(SESSION_SSL);+ return { ssl: row.ssl === true, version: row.version ?? null };+ } finally { await db.disconnect(); }+}++function withParam(url: string, param: string): string {+ return url + (url.includes('?') ? '&' : '?') + param;+}++describe.skipIf(!LOCAL)('loopback Postgres without TLS', () => {+ test('still connects in plaintext, and doctor reads ok', async () => {+ const session = await moduleSessionTls(LOCAL!);+ if (/@(localhost|127\.|\[::1\])/.test(LOCAL!)) {+ expect(postgresTlsCheck(LOCAL!, session)!.status).toBe('ok');+ }+ }, 60_000);+});++describe.skipIf(!TLS_REMOTE)('non-loopback Postgres with TLS, no sslmode in the URL', () => {+ test('the module pool connects encrypted', async () => {+ const session = await moduleSessionTls(TLS_REMOTE!);+ expect(session.ssl).toBe(true);+ expect(postgresTlsCheck(TLS_REMOTE!, session)!.status).toBe('ok');+ }, 60_000);++ test('a worker instance pool connects encrypted', async () => {+ const engine = new PostgresEngine();+ await engine.connect({ database_url: TLS_REMOTE!, poolSize: 2 } as never);+ try {+ const [row] = await engine.executeRaw<{ ssl: boolean }>(SESSION_SSL);+ expect(row.ssl).toBe(true);+ } finally { await engine.disconnect(); }+ }, 60_000);+});++describe.skipIf(!PLAIN_REMOTE)('non-loopback Postgres with ssl=off', () => {+ test('connect() refuses with postgres_tls_required instead of falling back to plaintext', async () => {+ let error: unknown;+ try { await db.connect({ database_url: PLAIN_REMOTE! } as never); } catch (e) { error = e; } finally { await db.disconnect(); }+ expect((error as { canonicalCode?: string } | undefined)?.canonicalCode).toBe('postgres_tls_required');+ expect(String((error as Error).message)).toContain('TLS was required by default for a non-local Postgres host');+ }, 60_000);++ test('a worker instance pool refuses the same way', async () => {+ const engine = new PostgresEngine();+ let error: unknown;+ try { await engine.connect({ database_url: PLAIN_REMOTE!, poolSize: 2 } as never); } catch (e) { error = e; } finally { await engine.disconnect().catch(() => {}); }+ expect((error as { canonicalCode?: string } | undefined)?.canonicalCode).toBe('postgres_tls_required');+ }, 60_000);++ test('sslmode=disable opts out: it connects in plaintext and doctor warns', async () => {+ const url = withParam(PLAIN_REMOTE!, 'sslmode=disable');+ const session = await moduleSessionTls(url);+ expect(session.ssl).toBe(false);+ const check = postgresTlsCheck(url, session)!;+ expect(check.status).toBe('warn');+ expect(check.message).toContain('sslmode=disable');+ }, 60_000);+});diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 51e19e3824..4797e07eaf 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -393,6 +393,10 @@"category": "ops","name": "rls"},+ {+ "category": "ops",+ "name": "postgres_tls"+ },{"category": "ops","name": "function_search_path"diff --git a/test/pg-tls-default-refusal.test.ts b/test/pg-tls-default-refusal.test.tsnew file mode 100644index 0000000000..b3e7442435--- /dev/null+++ b/test/pg-tls-default-refusal.test.ts@@ -0,0 +1,73 @@+/**+ * The TLS default's refusal: a non-local Postgres server that answers the+ * SSLRequest with "no" fails `connect()` with the coded `postgres_tls_required`+ * error (naming the sslmode=disable opt-out and the secure modes) instead of the+ * driver's TLS handshake reset. A fake server on this machine's non-loopback+ * interface stands in for the remote host.+ */++import { describe, test, expect, afterAll } from 'bun:test';+import { createServer, type Server, type AddressInfo } from 'node:net';+import { networkInterfaces } from 'node:os';+import * as db from '../src/core/db.ts';+import { toAgentError, cliRenderContext } from '../src/core/agent-output.ts';+import { classifyPgAccessError } from '../src/core/pg-access-classify.ts';+import { CODES } from '../src/core/error-registry.ts';++const ip = Object.values(networkInterfaces()).flat().find(i => i && i.family === 'IPv4' && !i.internal)?.address;+const servers: Server[] = [];++async function fakeServer(answer: 'N' | 'S'): Promise<number> {+ const srv = createServer(s => {+ s.on('error', () => {});+ s.once('data', () => { s.write(answer); s.once('data', () => s.destroy()); });+ });+ servers.push(srv);+ await new Promise<void>(r => srv.listen(0, '0.0.0.0', () => r()));+ return (srv.address() as AddressInfo).port;+}++async function connectError(url: string): Promise<unknown> {+ try { await db.connect({ database_url: url } as never); } catch (e) { return e; } finally { await db.disconnect(); }+ throw new Error('connect unexpectedly succeeded');+}++afterAll(() => { for (const s of servers) s.close(); });++describe.skipIf(!ip)('postgres_tls_required', () => {+ test('a non-local server without TLS fails with the coded error naming the opt-out and the secure modes', async () => {+ const port = await fakeServer('N');+ const e = await connectError(`postgres://u:p@${ip}:${port}/db?connect_timeout=3`);+ expect((e as { canonicalCode?: string }).canonicalCode).toBe('postgres_tls_required');+ const env = toAgentError(e, { transport: 'cli', command: 'doctor', render: cliRenderContext() });+ expect(env.code).toBe('postgres_tls_required');+ expect(env.message).toContain('TLS was required by default for a non-local Postgres host');+ expect(env.suggestion).toContain('sslmode=disable');+ expect(env.suggestion).toContain('sslmode=require');+ expect(env.suggestion).toContain('sslmode=verify-full');+ expect(env.why).toBeTruthy();+ expect(env.fix?.next).toBe('ask_user');+ expect(env.fix?.argv).toEqual(['gbrain', 'engine', 'status', '--probe', '--json']);+ expect(env.fix?.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'postgres_tls', '--json']);+ expect(classifyPgAccessError(e).reason).toBe('tls_required_default');+ }, 30_000);++ test('sslmode=disable in the URL opts out: no TLS is attempted, so the refusal never fires', async () => {+ const port = await fakeServer('N');+ const e = await connectError(`postgres://u:p@${ip}:${port}/db?connect_timeout=3&sslmode=disable`);+ expect((e as { canonicalCode?: string }).canonicalCode).toBeUndefined();+ expect(String((e as Error).message)).toContain('Cannot connect to database');+ }, 30_000);++ test('a server that does accept TLS but fails later keeps the original error', async () => {+ const port = await fakeServer('S');+ const e = await connectError(`postgres://u:p@${ip}:${port}/db?connect_timeout=3`);+ expect((e as { canonicalCode?: string }).canonicalCode).toBeUndefined();+ }, 30_000);+});++test('the registry explains postgres_tls_required', () => {+ const entry = (CODES as Record<string, { summary: string; suggestion?: string }>).postgres_tls_required;+ expect(entry).toBeDefined();+ expect(entry.suggestion).toContain('sslmode=disable');+});diff --git a/test/pg-tls.test.ts b/test/pg-tls.test.tsnew file mode 100644index 0000000000..fdb1f54c79--- /dev/null+++ b/test/pg-tls.test.ts@@ -0,0 +1,146 @@+/**+ * Postgres TLS default (src/core/pg-tls.ts): every postgres() pool requires+ * TLS for a host that is not on this machine unless the URL, the call site or+ * the driver's PGSSL variable names a mode. PGLite has no network connection,+ * so nothing here applies to it.+ */++import { describe, test, expect } from 'bun:test';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import postgres from '#postgres';+import { isLoopbackPgHost, pgConnectHosts, resolvePgTls, withPgTls } from '../src/core/pg-tls.ts';++const NO_ENV = {};++function driverSsl(url: string, opts: Record<string, unknown> = {}, env: Record<string, string | undefined> = NO_ENV): unknown {+ const sql = postgres(url, withPgTls(url, opts, env));+ return (sql as unknown as { options: { ssl: unknown } }).options.ssl;+}++describe('isLoopbackPgHost', () => {+ test.each([+ 'localhost', 'LOCALHOST', '127.0.0.1', '127.1.2.3', '::1', '[::1]', '0:0:0:0:0:0:0:1', '::ffff:127.0.0.1',+ '/var/run/postgresql', '/tmp/.s.PGSQL.5432',+ ])('%s is loopback', host => {+ expect(isLoopbackPgHost(host)).toBe(true);+ });++ test.each([+ 'db.example.com', '10.0.0.5', '192.168.1.20', '172.17.0.2', 'postgres-1', 'pgbouncer', 'localhost.example.com',+ '128.0.0.1', '::2', 'fe80::1', '', 'localhost-db',+ ])('%s is not loopback', host => {+ expect(isLoopbackPgHost(host)).toBe(false);+ });+});++describe('pgConnectHosts', () => {+ test('reads the URL host, a multi-host list, an IPv6 literal and the driver fallbacks', () => {+ expect(pgConnectHosts('postgres://u:[email protected]:5432/x', {}, NO_ENV)).toEqual(['db.example.com']);+ expect(pgConnectHosts('postgres://u:p@localhost:5432,db.example.com:5433/x', {}, NO_ENV)).toEqual(['localhost', 'db.example.com']);+ expect(pgConnectHosts('postgres://u:p@[::1]:5432/x', {}, NO_ENV)).toEqual(['::1']);+ expect(pgConnectHosts('postgres:///x', {}, NO_ENV)).toEqual(['localhost']);+ expect(pgConnectHosts('postgres:///x', {}, { PGHOST: '/var/run/postgresql' })).toEqual(['/var/run/postgresql']);+ expect(pgConnectHosts('postgres://[email protected]/x', { host: '127.0.0.1' }, NO_ENV)).toEqual(['127.0.0.1']);+ expect(pgConnectHosts('postgres://[email protected]/x', { path: '/tmp/.s.PGSQL.5432' }, NO_ENV)).toEqual(['/tmp/.s.PGSQL.5432']);+ });+});++describe('resolvePgTls', () => {+ test('a loopback host keeps the driver default (no TLS required)', () => {+ for (const url of ['postgres://u:p@localhost:5432/x', 'postgres://u:[email protected]:5432/x', 'postgres://u:p@[::1]:5432/x', 'postgresql://u@localhost/x']) {+ expect(resolvePgTls(url, {}, NO_ENV).source).toBe('loopback');+ expect(driverSsl(url)).toBe(false);+ }+ });++ test('a Unix socket keeps the driver default', () => {+ expect(resolvePgTls('postgres:///x', { path: '/tmp/.s.PGSQL.5432' }, NO_ENV).source).toBe('loopback');+ expect(resolvePgTls('postgres:///x', {}, { PGHOST: '/var/run/postgresql' }).source).toBe('loopback');+ });++ test('any other host requires TLS by default: a public name, a private IP, a Docker service name', () => {+ for (const url of [+ 'postgres://u:[email protected]:5432/x',+ 'postgresql://postgres.ref:[email protected]:6543/postgres',+ 'postgres://u:[email protected]:5432/x',+ 'postgres://u:p@postgres-1:5432/x',+ 'postgres://u:p@localhost:5432,db.example.com:5432/x',+ ]) {+ const r = resolvePgTls(url, {}, NO_ENV);+ expect(r.source).toBe('default');+ expect(r.mode).toBe('require');+ expect(driverSsl(url)).toBe('require');+ }+ });++ test('sslmode in the URL is honored, including the disable opt-out', () => {+ const base = 'postgres://u:[email protected]:5432/x';+ expect(resolvePgTls(base + '?sslmode=disable', {}, NO_ENV)).toMatchObject({ source: 'url', mode: 'disable' });+ expect(driverSsl(base + '?sslmode=disable')).toBe(false);+ expect(driverSsl(base + '?sslmode=require')).toBe('require');+ expect(driverSsl(base + '?sslmode=verify-full')).toBe('verify-full');+ expect(driverSsl(base + '?sslmode=prefer')).toBe('prefer');+ expect(driverSsl(base + '?prepare=false&sslmode=disable')).toBe(false);+ });++ test('the ssl parameter and sslrootcert=system count as explicit', () => {+ const base = 'postgres://u:[email protected]:5432/x';+ expect(resolvePgTls(base + '?ssl=false', {}, NO_ENV).source).toBe('url');+ expect(driverSsl(base + '?ssl=false')).toBe(false);+ expect(resolvePgTls(base + '?sslrootcert=system', {}, NO_ENV).source).toBe('url');+ expect(driverSsl(base + '?sslrootcert=system')).toBe('verify-full');+ });++ test('an explicit mode on a loopback URL is never weakened', () => {+ expect(driverSsl('postgres://u:p@localhost:5432/x?sslmode=verify-full')).toBe('verify-full');+ });++ test('a call site ssl option wins and is passed through unchanged', () => {+ const tlsObject = { rejectUnauthorized: true, ca: 'PEM' };+ expect(resolvePgTls('postgres://[email protected]/x', { ssl: tlsObject }, NO_ENV).source).toBe('option');+ expect(withPgTls('postgres://[email protected]/x', { ssl: tlsObject }, NO_ENV).ssl).toBe(tlsObject);+ });++ test('the driver PGSSL variable is an explicit setting the resolver leaves alone', () => {+ const r = resolvePgTls('postgres://[email protected]/x', {}, { PGSSL: 'verify-full' });+ expect(r.source).toBe('env');+ expect('ssl' in withPgTls('postgres://[email protected]/x', {}, { PGSSL: 'verify-full' })).toBe(false);+ });++ test('withPgTls never mutates the options it is given', () => {+ const opts = { max: 1 };+ const out = withPgTls('postgres://[email protected]/x', opts, NO_ENV);+ expect(out as Record<string, unknown>).toEqual({ max: 1, ssl: 'require' });+ expect(opts).toEqual({ max: 1 });+ });+});++describe('every postgres() pool in src/ goes through withPgTls', () => {+ function walk(dir: string, out: string[] = []): string[] {+ for (const name of readdirSync(dir)) {+ const p = join(dir, name);+ if (statSync(p).isDirectory()) walk(p, out);+ else if (p.endsWith('.ts')) out.push(p);+ }+ return out;+ }++ test('no call site builds a pool with bare options', () => {+ const root = join(import.meta.dir, '..', 'src');+ const offenders: string[] = [];+ let sites = 0;+ for (const file of walk(root)) {+ const text = readFileSync(file, 'utf8');+ if (!/^import postgres from '#postgres'/m.test(text)) continue;+ for (const [i, line] of text.split('\n').entries()) {+ const t = line.trimStart();+ if (t.startsWith('*') || t.startsWith('//') || !/(?:=|return|\(|,)\s*postgres\(/.test(line)) continue;+ sites++;+ if (!line.includes('withPgTls(')) offenders.push(file.slice(root.length + 1) + ':' + (i + 1));+ }+ }+ expect(offenders).toEqual([]);+ expect(sites).toBeGreaterThanOrEqual(6);+ });+});