Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.50.5.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins (#5130)
Garry Tan668b9bac3027
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 6a07607723..6f6604af3e 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.50.4.0",+ "version": "0.50.5.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 70f658ee0e..ad6edd6b07 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.50.4.0",+ "version": "0.50.5.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.github/workflows/heavy-tests.yml b/.github/workflows/heavy-tests.ymlindex a67e1797f6..9ada902528 100644--- a/.github/workflows/heavy-tests.yml+++ b/.github/workflows/heavy-tests.yml@@ -470,7 +470,7 @@ jobs:# keyless and paid runs each pay the 2-4 min compile.- name: Build gbrain (compile once for both door runs)run: |- bun build --compile --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts+ bun build --compile --no-compile-autoload-bunfig --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.tsecho "GBRAIN_COMPILED_BIN=$RUNNER_TEMP/gbrain-door-bin" >> "$GITHUB_ENV"# SECRETLESS provisioning: the npm registry verifies the per-platform@@ -681,7 +681,7 @@ jobs:- name: Build gbrain (compile once for the doors)run: |- bun build --compile --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts+ bun build --compile --no-compile-autoload-bunfig --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.tsecho "GBRAIN_COMPILED_BIN=$RUNNER_TEMP/gbrain-door-bin" >> "$GITHUB_ENV"- name: Install codex + claude (pinned npm versions, refuse on drift)@@ -784,7 +784,7 @@ jobs:# Compile gbrain ONCE for both bun test invocations below.- name: Build gbrain (compile once for both door runs)run: |- bun build --compile --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts+ bun build --compile --no-compile-autoload-bunfig --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.tsecho "GBRAIN_COMPILED_BIN=$RUNNER_TEMP/gbrain-door-bin" >> "$GITHUB_ENV"# SECRETLESS provisioning, pack-verify-install: `npm pack` DOWNLOADS@@ -995,7 +995,7 @@ jobs:- run: bun install --frozen-lockfile- name: Build gbrainrun: |- bun build --compile --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts+ bun build --compile --no-compile-autoload-bunfig --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.tsecho "GBRAIN_COMPILED_BIN=$RUNNER_TEMP/gbrain-door-bin" >> "$GITHUB_ENV"- name: Install opencode@latest (unpinned — the whole point)timeout-minutes: 10diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 6c8863121e..ea10b5587e 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -113,7 +113,7 @@ jobs:# release runner is a flakier duplicate gate — it blocked the first# release on ambient-env tests (run 30698650484). The build job's gate# is the artifact itself: compile, then smoke-test the binary.- - run: bun build --compile --target=${{ matrix.target }} --outfile bin/${{ matrix.artifact }} src/cli.ts+ - run: bun build --compile --no-compile-autoload-bunfig --target=${{ matrix.target }} --outfile bin/${{ matrix.artifact }} src/cli.ts- name: Smoke-test the compiled binaryrun: |chmod +x bin/${{ matrix.artifact }}diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 11df19d80a..5354e0f44c 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.50.4.0 -->+<!-- gbrain-runbook-stamp: 0.50.5.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6923626d7..e811ace2e3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,34 @@All notable changes to GBrain will be documented in this file.+## [0.50.5.0] - 2026-09-16++**Security hardening pass across the remote OAuth surface, transcript ingest, and environment handling.** This wave closes the critical- and high-severity items from privately reported advisories. Fresh installs and existing brains are on the same footing after upgrade; where an operator kept a security-relevant setting in a project directory's `.env`, gbrain now says so and names the fix. Thanks to the reporters credited below.++### Fixed+- **Self-registered OAuth clients are held to `read`/`write`.** With `--enable-dcr`, a self-registered client that requests a privileged scope (`admin`, `sources_admin`, `users_admin`, `agent`) is now rejected at registration with HTTP 400 `invalid_client_metadata` and told to use the operator path instead; machine clients registered under `--enable-dcr-insecure` are read-only. Every self-registered authorization-code connection still stops at the admin dashboard for the owner's approval before a token is issued, and a single client can no longer hold more than a small number of consent requests awaiting a decision. The consent gate is pinned end to end against a real `gbrain serve --http --enable-dcr` process. Widen a client afterward with `gbrain auth rescope-client <client_id> --scopes …`, or pre-register it with `gbrain auth register-client` / the admin API. A `client_credentials` registration without `--enable-dcr-insecure` is told the grant is not available, rather than being quoted a read-only ceiling. While self-registration is enabled, OAuth discovery advertises exactly the scopes a self-registering client may request, so a connector that copies `scopes_supported` into its registration succeeds; operator-registered clients keep their full grant. Reported by @amansk, @rohanprichard, @DanielSiva and @benmiller-SC.+- **Remote `sources_remove` is confined to the caller's granted sources**, matching `sources_list` / `sources_status`; an out-of-scope id answers `not_found`. The local CLI is unchanged; the confinement is one shared helper for `sources_remove` and `sources_status`.+- **`gbrain doctor` flags privileged self-registered clients.** `oauth_client_scope_health` warns about active OAuth clients that hold a scope beyond the self-registration ceiling without an operator grant record, and prints the exact `rescope-client` / `revoke-client` fix; if the grant audit schema is absent it says so instead of guessing. The privileged set is derived from the scope registry, so a future scope is audited automatically.+- **Transcript ingest redacts credentials by wire format, not just vendor prefix.** The shared secret scanner now detects JWTs, cloud and API key shapes, `Bearer` headers, connection strings carrying inline passwords, and high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignments, and redacts them from message bodies, speaker labels, titles and session metadata before anything is written by `gbrain transcripts ingest`. Preview with `--dry-run`. The scanner is linear on long lines — a minified or bundled line of hundreds of KB (a JSON blob of credential-less database URLs, thousands of `Bearer` headers) scans in milliseconds instead of seconds, so a pasted bundle cannot stall transcript ingest, `gbrain sources push`, or compiled-context scanning; connection-string detection no longer mistakes a credential-less URL followed by an email address for a password, finding previews redact every secret on the line, and a token that is also a connection-string password is redacted as the full credential span. Connection-string passwords pasted with unescaped `/`, braces, angle brackets, pipes, carets, backticks or backslashes are redacted, an all-caps `BEARER` header is recognized, and every detector does constant work per occurrence: JWT, high-entropy-assignment and PEM-block matching are bounded (a PEM body over 16 KB falls back to the header-only match), and corpus redaction rebuilds the text from the claimed spans in a single pass — a 1 MB transcript with thousands of distinct secrets redacts in about the time it takes to scan, and it redacts exactly the spans the scanner reports so the redacted corpus and the push-gate findings can no longer disagree. Overlapping detector matches redact the union of what every pattern matched, so a credential whose neighbouring text happens to look like a vendor identifier is never partially exposed in the page or the finding preview. A bearer token or pasted assignment value is also redacted where the same value recurs bare or embedded anywhere else in the session — across messages, speaker labels, titles and metadata, in either order — bounded (first 64 distinct values per session, values up to 512 characters, streaming so memory stays flat) so hostile page content cannot make redaction slow or memory-hungry. The private-key scanner stays linear on very large single-line inputs. Re-run `gbrain transcripts ingest` to re-render already-imported sessions. Reported by @Jack82-ai.+- **Raw session metadata follows its page's soft delete.** `get_raw_data` no longer returns rows for a soft-deleted page, and the compiled-context sensitivity scan reports a JWT or bearer token once instead of twice. A repeat transcript import no longer rewrites unchanged session metadata on every run.+- **Security-relevant environment variables are ignored from a project directory's `.env`.** A fixed set of `GBRAIN_*` variables — the ones that load code, name programs to run, relocate `~/.gbrain`, or widen a security posture — are no longer honored when a `.env` file in the current working directory assigns them; gbrain prints one stderr line naming the variable and where to put it instead. The check runs in compiled binaries and in every gbrain process (hooks, `serve`, `mcp`, workers). `~/.gbrain/.env` is loaded before the guardrails loader so it is a working home for `GBRAIN_GUARDRAILS_MODULE` (see Changed for the accepted spec shapes). The quarantine parses `.env` files with the same line grammar Bun uses (a bare carriage return terminates a line; a BOM or U+2028 cannot hide an assignment), also covers the loader / git / node / proxy / AI-CLI variable families a checkout could plant for the programs gbrain spawns, and re-runs gbrain once with the sanitized environment so git, the agent CLI and workers inherit the clean view. Running gbrain from inside `~/.gbrain` no longer warns about its own `.env`; the shell-job opt-in also reaches `--job-isolation process` children as `--allow-shell-jobs`. The quarantine re-runs gbrain from an empty temporary directory so the dropped variables are absent (not empty) for every program gbrain spawns, ignores a planted re-run marker, protects the XDG config roots, TLS trust stores, OpenSSL configuration loaders, temp-directory and `HOME` roots, editor/pager and every provider-endpoint variable, and lets Ctrl-C reach the running command exactly once. `GBRAIN_DATABASE_URL` and `GBRAIN_OAUTH_RELAY_URL` join the protected set: a project's `.env` can no longer choose which brain gbrain writes to or which relay hands back tokens — export them from your shell or put them in `~/.gbrain/.env`. Guardrails fail closed at this boundary too: when a project `.env` assigns `GBRAIN_GUARDRAILS_MODULE` and a value was dropped, gbrain refuses to start rather than run without the configured firewall. The quarantine also covers the shell-startup and interpreter-home family (`BASH_ENV`, `SHELLOPTS`/`PS4`, `ZDOTDIR`, `PYTHONHOME`, `GCONV_PATH`, `BASH_FUNC_*`, …); running gbrain from inside its own config directory keeps its exemption only when the project `.env` assigns none of `GBRAIN_HOME`, `HOME`, `USERPROFILE`; and the sanitized re-run always exits with the child's status, forwards Ctrl-C only when no controlling terminal exists, hands the child your real `HOME` when a planted one was dropped, exits within a second when its wrapper is force-killed (supervisor restarts no longer leave an orphaned worker), and keeps relative runtime paths (`bun --preload ./x src/cli.ts`, `--env-file .env.ci`, …) working across the hop. Reported by @dberzan.+- **A project directory's `bunfig.toml` can no longer preload code into the compiled `gbrain` binary.** Every `bun build --compile` invocation (release workflow, `bun run build`, CI door builds, docs) now passes `--no-compile-autoload-bunfig`, and a CI guard keeps every build invocation flagged. Script-mode installs (`bun install -g`, `bun link`) run gbrain as an ordinary Bun script, which applies the current directory's `bunfig.toml` before gbrain starts; gbrain now prints a one-line warning when it finds a top-level `preload` there (see `SECURITY.md`).+- **Source removal over MCP keys on the caller's write authority.** A federated read grant no longer lets a `sources_admin` client hard-remove a sibling source; out-of-authority ids answer `not_found` as before, `sources_status` is unchanged, and the local CLI keeps full operator authority.+- **`gbrain delete <slug> --purge` no longer reports success while the page's markdown file is still on disk.** An already-soft-deleted page gets its file removal retried against the recorded path, and a removal failure stops with `storage_error` naming the file so you can fix it and re-run; the row stays soft-deleted until the file is gone.++### Added+- **`gbrain delete <slug> --purge`** removes a page — row, chunks, links, and raw session metadata — immediately with no recovery window. Local CLI only; agents connected over MCP get `permission_denied` for `purge` and keep the recoverable soft delete, and a purge response always reports its file write-through outcome plus the copies a purge cannot reach (brain-repo history, exports, derived rows) so a credential remediation never stops at the row. The soft-delete response points at it.+- **`gbrain jobs work --allow-shell-jobs`** — the shell-handler opt-in is now also a flag; the supervisor passes it to workers automatically so the cwd-`.env` quarantine cannot silently disable it.++### Changed+- **`GBRAIN_GUARDRAILS_MODULE` accepts only an absolute path or a `~/` path.** cwd-relative specs (`./x`, `../x`) and bare package names are refused because both resolve against whatever directory gbrain happens to run in (a package name loads the current directory's `node_modules/<name>/`); a refused spec is a fail-closed exit 1 with the fix in the message. This also applies to the published `gbrain/core/guardrails` library export.+- Connection strings with inline passwords now count as secrets for `gbrain sources push` / bootstrap verify and are dropped from compiled-context entries; declare a confirmed non-secret value safe with its fingerprint in `.gbrain-scan-allow`. The high-entropy assignment rule now requires a digit in the value, so identifier-shaped assignments in code stop being redacted.+- Startup banner and warning text plus `docs/mcp/DEPLOY.md`, `docs/mcp/CHATGPT.md`, `SECURITY.md` and `docs/guardrails.md` describe the registration ceiling, the owner-approval step, the widen path, and the cwd-`.env` trust boundary.++### To take advantage of v0.50.5.0+`gbrain upgrade`, then restart `gbrain serve --http` and run `gbrain doctor`. If it lists self-registered OAuth clients with a privileged scope you did not intend, run `gbrain auth rescope-client <client_id> --scopes read,write` or `gbrain auth revoke-client <client_id>`. Connectors that request `admin` at self-registration will now fail to register — pre-register them with `gbrain auth register-client <name> --scopes …` or let them self-register with `read write` and rescope later. If you kept `GBRAIN_GUARDRAILS_MODULE`, `GBRAIN_HOME`, a `GBRAIN_ALLOW_*` flag or another protected variable in a project's `.env`, move it to `~/.gbrain/.env` (or your service's EnvironmentFile / shell profile) — gbrain names the variable it ignored and where to put it. A hand-started worker that runs shell jobs should use `gbrain jobs work --allow-shell-jobs`. If `GBRAIN_GUARDRAILS_MODULE` is a package name or a relative path, change it to the module's absolute path (or a `~/` path) — gbrain exits 1 until you do. If you set `GBRAIN_DATABASE_URL` in a project's `.env` on purpose, export it from your shell or put it in `~/.gbrain/.env` instead. If you build the binary yourself, rebuild it with `bun run build` (**Say to your agent:** *"rebuild the gbrain binary"*) so it carries the new compile flag.++**Say to your agent:** *"archive my session transcripts"* / *"import my conversations"* — *"a secret leaked into a brain page — rotate it and purge the page"* (your agent rotates the credential, then runs `gbrain delete <slug> --purge` on the host) — *"run a brain health check"* (your agent runs `gbrain doctor` and follows any `oauth_client_scope_health` advice) — *"start my brain's MCP server with self-service client registration"* (your agent runs `gbrain serve --http --enable-dcr`; you approve each new connection in the admin UI).## [0.50.4.0] - 2026-09-16### For contributorsdiff --git a/CLAUDE.md b/CLAUDE.mdindex 7632ecb04e..4cc494cb3d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -522,7 +522,7 @@ ms, max waiters) for `--json`; a one-line summary prints to stderr.## Build-`bun build --compile --outfile bin/gbrain src/cli.ts`+`bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts`## Version locations (single source of truth: `VERSION` file)diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 7ae82f5a9a..b5a96d63c5 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -243,7 +243,7 @@ scanning" for details.## Building```bash-bun build --compile --outfile bin/gbrain src/cli.ts+bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts```## Adding a new operationdiff --git a/README.md b/README.mdindex cd52bf0262..0399ceeb5a 100644--- a/README.md+++ b/README.md@@ -305,10 +305,14 @@ How the open-loop engine decides who's waiting: [`docs/guides/open-loops.md`](doYour other agents' histories import in one command. `gbrain transcripts ingest`parses agent session logs (Claude Code, Codex, OpenClaw, Hermes, Grok Build) and extractedconsumer chat exports (ChatGPT / Claude.ai `conversations.json`) into readable-conversation pages with provenance back to the exact session file. Secrets are-scrubbed from message bodies, titles, speakers, and session metadata before-anything is written, embedding is off by default for bulk backfills, and-re-runs are free — unchanged sessions skip on content hash:+conversation pages with provenance back to the exact session file. Pattern-based redaction runs over message bodies, titles, speakers, and session+metadata before anything is written — vendor key prefixes, JWTs, cloud/API key+shapes, `Bearer` headers, connection-string credentials, and high-entropy+`KEY=`/`TOKEN=` assignments become `<REDACTED:…>` placeholders (preview with+`--dry-run`; no pattern set is complete, so if a secret still lands see+["If a secret reached the brain"](SECURITY.md#if-a-secret-reached-the-brain):+rotate it, then `gbrain delete <slug> --purge`). Embedding is off by default+for bulk backfills, and re-runs are free — unchanged sessions skip on content hash:```bashgbrain transcripts ingest # discover importable session logsdiff --git a/SECURITY.md b/SECURITY.mdindex 7b9269ce9f..25ec9c698d 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -59,6 +59,163 @@ enforced structurally by actionlint on every workflow change.trust-on-first-use on this path. For the strongest guarantee, install theattested release binary and run `gh attestation verify` as above.+## Environment variables and cwd `.env` files++gbrain is usually a globally installed CLI (or a compiled binary) that runs+with an arbitrary working directory — the repo you happen to be in, the+workspace an agent hook fires from. Bun auto-loads `.env`, `.env.local` and+the `.env.<NODE_ENV>[.local]` variants from that working directory into the+process environment before any gbrain code runs, for `bun run` and for+compiled binaries alike, and it expands `${VAR}` references inside those+files. A `.env` committed into a cloned repository is therefore **untrusted+input** — it was written by whoever authored the repo, not by you.+Compiled `gbrain` binaries are built with `--no-compile-autoload-bunfig`, so a+`bunfig.toml` in the working directory is inert — it cannot preload code into+the binary before gbrain starts (a CI guard keeps every build invocation+flagged). The development runtime `bun src/cli.ts` stays bun-native; a+contributor's own working directory is trusted. Script-mode installs+(`bun install -g github:garrytan/gbrain`, `git clone` + `bun link`) run+`src/cli.ts` as an ordinary Bun script, and Bun applies the current+directory's `bunfig.toml` before any gbrain code runs — gbrain prints a+one-line warning when it finds a top-level `preload` there, but it cannot+undo it. Only the compiled binary ignores a cwd `bunfig.toml`; run script-mode+gbrain from directories you control, or use the release binary in untrusted+checkouts.++**The trust boundary.** Security-relevant variables are honored from your+shell environment, from a service `EnvironmentFile`, and from+`~/.gbrain/.env` (the operator-owned secrets file). They are **never** honored+from a `.env` file in the current directory. At startup every gbrain process+checks the working directory's `.env` family and, for each protected variable+that one of those files *assigns* (whatever the value — an expanded+`${PWD}/…` looks like an ordinary absolute path by the time it reaches the+process), drops the variable and prints one line to stderr:++```+[env] Ignoring GBRAIN_PLUGIN_PATH because a .env file in the current directory assigns it — cwd .env files are untrusted for security settings. Export it from your shell or set it in ~/.gbrain/.env.+```++When a `.env` file in the current directory assigns any protected variable+(`GBRAIN_GUARDRAILS_MODULE` is the one exception — it refuses to run instead,+see below), gbrain drops it, prints one `[env] Ignoring …` line, and then re-runs itself+once from an empty temporary directory with the sanitized environment, switches+back to your directory, and exits with that run's status. The re-run's+environment simply lacks the dropped variables (they are never carried as empty+strings, which git and the dynamic loader would treat as set), so every program+gbrain spawns — git, the claude CLI, workers — inherits the clean view. The+internal variable `GBRAIN_CWD_ENV_QUARANTINED` marks the re-run — it is not a+setting, and gbrain honours it only when it provably started in the empty+directory the marker names. A signal-killed re-run maps to exit 128+signal;+the wrapper's exit status is always the re-run's (it relays the child and+nothing else), and the re-run dies with its wrapper: if the wrapper is+force-killed (SIGKILL cannot be forwarded), the re-run notices within about a+second, removes its neutral directory and exits, so a supervisor tracking the+wrapper's pid never leaves an orphaned worker behind. With a controlling terminal, Ctrl-C reaches the re-run directly+from that terminal and the wrapper does not forward it; with no controlling+terminal (a supervisor, cron, a detached harness) a SIGINT that reaches the+wrapper alone is forwarded once so the re-run is not orphaned; SIGTERM/SIGHUP+sent to the wrapper are always forwarded. When the dropped variable was a+planted `HOME`, the re-run receives your real home directory (derived from the+startup environment, never from the file) so git identity and `~/`-relative+paths keep working. gbrain processes that gbrain itself starts from+that directory (a supervised worker, a background push) repeat the step once+for their own subtree. This costs nothing when the working directory has no+`.env`, or when nothing protected is assigned there.++**Protected variables.** Two groups, one predicate+(`isCwdDotenvProtectedKey` in `src/core/env-trust.ts`):++- The security-relevant `GBRAIN_*` keys (`CWD_DOTENV_PROTECTED_KEYS`):+ code-loading `GBRAIN_GUARDRAILS_MODULE`, `GBRAIN_PLUGIN_PATH`; exec-target+ `GBRAIN_CLAUDE_CLI_BIN`, `GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG`,+ `GBRAIN_JOB_CHILD_CLI`, `GBRAIN_BIN_OVERRIDE`; root/registry redirect+ `GBRAIN_HOME`, `GBRAIN_MOUNTS_PATH`; the brain connection string+ `GBRAIN_DATABASE_URL` (a cwd `.env` would retarget every hook, query and+ write at a database it names — the `DATABASE_URL` value guard covers only+ the bare name) and the OAuth relay `GBRAIN_OAUTH_RELAY_URL`; posture-widening+ `GBRAIN_ALLOW_SHELL_JOBS`, `GBRAIN_ALLOW_PRIVATE_REMOTES`,+ `GBRAIN_ALLOW_UNVERIFIED_REMOTE`, `GBRAIN_GIT_ALLOW_FILE_TRANSPORT`,+ `GBRAIN_ALLOW_MASS_RECONCILE`, `GBRAIN_ALLOW_DEFAULT_WRITE`,+ `GBRAIN_NO_SANITY`, `GBRAIN_REMOTE_PRIVATE_PAGES`.+- The variable families through which a checkout could hijack the programs+ gbrain spawns rather than gbrain itself (`CWD_DOTENV_PROTECTED_PREFIXES`,+ `CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS`): the `LD_*`/`DYLD_*` dynamic-loader+ family, git configuration/hook/exec injection (`GIT_*`), Bun and npm runtime+ configuration (`BUN_*`, `NPM_CONFIG_*`/`npm_config_*`), Node preload and+ TLS knobs (`NODE_OPTIONS`, `NODE_PATH`, `NODE_EXTRA_CA_CERTS`,+ `NODE_TLS_REJECT_UNAUTHORIZED`), the `XDG_CONFIG_HOME`/`XDG_DATA_HOME`/+ `XDG_CACHE_HOME` and `GNUPGHOME` roots that git and other tools read as+ global configuration, the `SSL_CERT_FILE`/`SSL_CERT_DIR`/`CURL_CA_BUNDLE`/+ `REQUESTS_CA_BUNDLE` trust stores, the OpenSSL provider/engine loaders+ (`OPENSSL_CONF`, `OPENSSL_ENGINES`, `OPENSSL_MODULES` — a planted+ configuration loads a shared object into every OpenSSL-linked child such as+ git over https), the temp roots (`TMPDIR`, `TMP`, `TEMP`) that the sanitized+ re-run's neutral directory and every temp write resolve through, `HOME` and+ `USERPROFILE` (inert while exported, but where `HOME` is unset a planted+ value would relocate `~/.gitconfig`, `~/.ssh` and `~/.gbrain` into the+ checkout), the shell-startup and interpreter-home family the+ non-interactive shells gbrain's children start would read (`BASH_ENV`,+ `SHELLOPTS`/`PS4`, `BASHOPTS`, `PROMPT_COMMAND`, `ZDOTDIR`, `PYTHONHOME`,+ `PERLLIB`, `GCONV_PATH`, and exported functions under the `BASH_FUNC_*`+ prefix), `EDITOR`/`VISUAL`/`PAGER`, ssh askpass+ programs, interpreter preload for Python/Perl/Ruby helpers, HTTP(S)/ALL proxy+ variables in both spellings, and every AI-provider endpoint or credential+ variable gbrain's gateway reads from the environment (`CLAUDE_CONFIG_DIR`,+ `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, `OPENAI_BASE_URL`,+ `OPENROUTER_BASE_URL`, `LITELLM_BASE_URL`, `OLLAMA_BASE_URL`,+ `LMSTUDIO_BASE_URL`, `LLAMA_SERVER_BASE_URL`, `LLAMA_SERVER_RERANKER_BASE_URL`).+ The endpoint-redirect `GBRAIN_*` keys (`GBRAIN_REMOTE_MCP_URL`,+ `GBRAIN_REMOTE_ISSUER_URL`, `GBRAIN_DIRECT_DATABASE_URL`) and the re-run+ marker itself are in the first group. This is a denylist of known hijack+ families; it grows as new families are identified.++`GBRAIN_GUARDRAILS_MODULE` additionally accepts only an absolute path or a+`~/` path: cwd-relative specs and bare package names are refused (a package+name would resolve from the current directory's `node_modules`). It is also+the one key that fails closed at the cwd boundary: when a cwd `.env` assigns+it and a non-empty value was dropped, gbrain does not re-run without it — it+refuses to start (exit 1, `guardrails: GBRAIN_GUARDRAILS_MODULE is assigned by+a .env file in the current directory; refusing to run without the operator's+firewall …`), because Bun merges the file before gbrain starts and a value you+exported cannot be told apart from the file's. A benign repository never+assigns this gbrain-specific key; your own setting belongs in your shell or in+`~/.gbrain/.env`.++**Semantics worth knowing.**++- *Per process, then inherited.* Every gbrain process re-applies the check at+ startup; the one-time sanitized re-run above is what makes the result reach+ git, the agent CLI and workers. The supervisor passes the shell-job opt-in to+ workers — and workers to per-job child processes — as the+ `--allow-shell-jobs` flag so the quarantine cannot silently disable it.+- *Key presence, not value.* If a cwd `.env` assigns a protected key, a value+ you exported from the shell is dropped too while you stay in that directory —+ the warning tells you so. Move the setting to `~/.gbrain/.env` or run from+ another directory. A family member you exported (say `GIT_AUTHOR_NAME`) is+ untouched unless the cwd `.env` assigns that same name.+- *Everything else still loads.* Routing and tuning `GBRAIN_*` variables and+ every variable not listed above still load from a cwd `.env` as before.+ `DATABASE_URL` keeps its own, value-matching guard (see `docs/ENGINES.md`).+ `GBRAIN_DATABASE_URL` exported from your shell is always honored, but a+ `GBRAIN_DATABASE_URL` *assigned by a cwd `.env`* is dropped like any other+ protected key — a project directory never gets to choose which brain you+ write to. Move it to your shell or `~/.gbrain/.env`.+- *Your own config directory.* Running gbrain from inside `~/.gbrain` (or+ `$GBRAIN_HOME/.gbrain`) makes its `.env` the "cwd `.env`". That file is+ yours, so it is honored without a warning — unless a cwd `.env` assigns+ any key the config directory is derived from (`GBRAIN_HOME`, `HOME`,+ `USERPROFILE`); a planted home is never treated as your config directory.+- *Server deployments.* `GBRAIN_ADMIN_BOOTSTRAP_TOKEN`, `GBRAIN_HTTP_CORS_ORIGIN`+ and `GBRAIN_HTTP_TRUST_PROXY` are deliberately not on the list so documented+ container deployments that co-locate them keep working — launch+ `gbrain serve --http` from a directory you control.+- *Compiled binaries included.* The check and the sanitized re-run behave+ identically in `bun run src/cli.ts` and in the compiled `gbrain` binary.++If you kept one of the protected variables in a project's `.env` on purpose,+move it to `~/.gbrain/.env` (loaded before anything else, never overriding a+shell export) or export it from your shell profile.+## Remote MCP Security### Keep dynamic client registration disabled unless explicitly needed@@ -67,12 +224,25 @@ GBrain disables Dynamic Client Registration (DCR) by default. Keep thatdefault for internet-reachable deployments and pre-register trusted clientswith operator-approved scopes and source access. Enabling DCR lets networkcallers create OAuth client records, so use it only when the deployment's-trust model requires self-service registration and browser approval remains-part of the authorization flow.+trust model requires self-service registration. Self-registered clients still+need the owner's approval in the admin dashboard for every authorization-code+connection; DCR by itself never yields a token.++When DCR is on, a self-registered client passes three gates. At registration+it may request at most `read write`; a request for any privileged scope is+rejected with HTTP 400 `invalid_client_metadata` (never silently narrowed) and+the error text points at the operator path (`gbrain auth register-client`, the+admin API, or a later `gbrain auth rescope-client <client_id> --scopes ...`).+Every authorization-code connection then stops at the admin dashboard for the+owner's approval before a code is minted — approval never widens the+registered scope. Finally, codes and tokens are re-intersected with the+client's current registered scope on every request, so a rescope takes effect+immediately.Do not enable `--enable-dcr-insecure` on an untrusted network. That option isreserved for deployments that intentionally allow self-registered-machine-to-machine clients without browser approval.+machine-to-machine (`client_credentials`) clients, which are issued tokens+without owner approval; such clients are capped at **read-only** scope.### Recommended: `gbrain serve --http`@@ -139,17 +309,54 @@ unknown authentication methods are rejected consistently. Browser-basedclients can be configured entirely through the supported CLI flags; operatorsdo not need to edit OAuth database rows by hand.-### DCR consent default (v0.42.55+)+### DCR consent default and scope ceilingThe "disable `client_credentials`, only allow `authorization_code`" guidance-above is now the built-in default for the DCR path, not just advice for custom+above is the built-in default for the DCR path, not just advice for customwrappers. With `--enable-dcr` on, a self-registered client defaults to the-`authorization_code` (browser-approval) grant, and an explicit+`authorization_code` (owner-approval) grant, and an explicit`client_credentials` request is rejected with `invalid_client_metadata`.Operators who genuinely need the machine-to-machine grant on the registration-endpoint opt in with `--enable-dcr-insecure` (which implies `--enable-dcr`); a+endpoint opt in with `--enable-dcr-insecure` (which implies `--enable-dcr`);+those anonymous machine clients are limited to `read`. While DCR is enabled,+OAuth discovery advertises only the self-registration ceiling (`read write`)+as `scopes_supported`, so a client that registers with the advertised scopes+is accepted, and an explicit request above the ceiling is still refused. Astartup WARNING prints whenever DCR is enabled, and a second when the insecure-grant is allowed. Pre-registering clients via the CLI / admin API is unchanged.+grant is allowed. Pre-registering clients via the CLI / admin API is unchanged+and accepts every scope; discovery without DCR lists every scope such a client+may hold.++`gbrain doctor` (`oauth_client_scope_health`) warns about active clients that+hold a scope beyond the self-registration ceiling but carry no operator grant+record, with the exact `rescope-client` / `revoke-client` remedy. Remote+`sources_remove` callers may remove only their own write source (a federated+read grant naming a source does not make it removable); any other id answers+`not_found`, indistinguishable from a nonexistent source. `sources_status`+keeps the read-scope confinement it shares with `sources_list`, and the local+CLI keeps full operator authority.++### Owner approval for authorization-code connections++`/authorize` never issues an authorization code on its own. It records a+pending request and sends the browser to the admin dashboard, where the brain+owner signs in (bootstrap token or magic link), reviews the client name,+redirect URI and requested scopes, and approves or denies. Only an approval+mints a code; the code is bound to the client, redirect URI and S256 PKCE+challenge of the pending request and is delivered to the client's registered+redirect URI. A denial returns `error=access_denied`. This applies equally to+clients that self-registered through Dynamic Client Registration — with+`--enable-dcr`, self-registration lets a network caller create a client record+and a pending request, never a token. Revoked clients are refused at+`/authorize` before a pending request is created.++Pending requests expire after ten minutes and do not survive a server restart.+They are bounded twice: a server-wide ceiling on the in-memory store and a+per-client ceiling of ten requests awaiting a decision. Beyond either,+`/authorize` sends the client back to its registered redirect URI with+`error=too_many_requests` and no code until earlier requests are decided or+expire; a `429` status on `/authorize` comes only from the MCP SDK's built-in+per-IP limits, which remain in force on `/authorize`, `/register` and `/token`.### Token Management@@ -340,3 +547,41 @@ admin SSE feed at `/admin/events`. Operators on a personal laptop who wantraw payloads back can pass `gbrain serve --http --log-full-params` (loudstderr warning at startup). Multi-tenant deployments should leave iton the redacted default.++## If a secret reached the brain++Transcript ingest, captures and syncs redact credential-shaped strings before+anything is written: vendor key prefixes, JWTs, cloud/API key shapes, `Bearer`+headers, connection strings carrying inline passwords, PEM private keys, and+high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignments. No pattern set is+complete. If you find a live credential in a page:++1. **Rotate the credential first.** Anything readable by a connected agent+ should be treated as exposed.+2. **Remove the page immediately**, from the host machine:++ ```bash+ gbrain delete <slug> --purge+ ```++ `--purge` is honored only by the local CLI; remote/MCP callers keep the+ 72-hour soft delete. It removes the row and its chunks, links and raw session+ metadata with no recovery window, and it refuses to report success while+ the page's markdown file remains on disk: it retries the removal and, if the+ file still cannot be removed, stops with `storage_error` naming the path so+ you can fix permissions and re-run (the row stays soft-deleted until the+ file is gone). Verify with `gbrain get <slug>` (expects not found).+3. **Check the other copies.** The brain-repo git history, a synced working+ tree, an export directory or a compiled context file may still hold the+ value; rewrite/re-push or regenerate those as needed.+4. Add a value's fingerprint (printed with every `gbrain sources push` finding)+ to `<workspace>/.gbrain-scan-allow` ONLY for values you have confirmed are+ not credentials.++**Say to your agent:** *"a secret leaked into a brain page — rotate it and+purge the page"* (your agent rotates the credential, then runs+`gbrain delete <slug> --purge` on the host).++Behavior note: connection strings with inline passwords now block+`gbrain sources push` / bootstrap verify and are dropped from compiled-context+entries. The escape hatch is the same `.gbrain-scan-allow` fingerprint line.diff --git a/TODOS.md b/TODOS.mdindex 6d75c4afa0..4f672f2731 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,73 @@# TODOS++## Security fix wave follow-ups (filed 2026-09-15, follow-up from v0.50.5.0)++- [ ] **P2 — cwd-`.env` quarantine: decide the remaining `GBRAIN_*` variables.**+ **What:** `src/core/env-trust.ts` protects a fixed set of `GBRAIN_*` variables plus the loader / git / node / proxy / AI-CLI families. A few `GBRAIN_*` variables with plausible per-project uses (`GBRAIN_SKILLS_DIR`, `GBRAIN_RECIPES_DIR`, `GBRAIN_GITHUB_PAT` — `GBRAIN_DATABASE_URL` graduated to the protected list in v0.50.5.0) and the `serve --http` deployment trio (`GBRAIN_ADMIN_BOOTSTRAP_TOKEN`, `GBRAIN_HTTP_CORS_ORIGIN`, `GBRAIN_HTTP_TRUST_PROXY`) were deliberately left out because documented container/service deployments may co-locate them with the process cwd. **Why:** each is the same trust-boundary class; the cost is a behavior change for operators who rely on project-dir `.env` files. **Fix:** decide per variable, then add to the protected list with a "why" comment (the structural test pins the list; `_DIR` names need `SUSPICIOUS_NAME` in `test/env-trust-protected-keys.test.ts` widened). **Effort:** S. **Priority:** P2.+- [ ] **P2 — Align the #427 `DATABASE_URL` guard with the key-presence semantics of the security quarantine.**+ **What:** `effectiveEnvDatabaseUrl` still decides by comparing the runtime value against the literal right-hand sides parsed from the cwd `.env` files, while v0.50.5.0 moved the security quarantine to key-presence (Bun may transform values before they reach the process). **Why:** two guards with two semantics over one parser is a maintenance hazard, and the documented "an exported, different URL still wins" behavior is what keeps the value-match form alive. **Fix:** either resolve variable references during the re-parse the way Bun does, or move `DATABASE_URL` to key-presence with a doc note. **Effort:** S. **Priority:** P2.+- [ ] **P3 — Operator-configurable `redirect_uri` allow-list for dynamic client registration.**+ **What:** with `--enable-dcr`, a self-registered client may name any `https://` (or loopback / custom-scheme) redirect target; the owner sees it on the consent page but there is no server-side allow-list (e.g. loopback plus the browser-connector callback hosts). **Why:** suggested in a private report as a cheap way to narrow the phishing payoff even with consent in place. **Fix:** `oauth.dcr_redirect_allowlist` config key checked in `registerClient` before the insert; startup summary prints the effective list. **Effort:** S. **Priority:** P3.+- [ ] **P3 — RFC 7591 initial access tokens for `/register`.**+ **What:** registration is anonymous whenever DCR is on; an operator-minted, single-use registration token would let URL-only connectors register without opening `/register` to everyone. **Why:** suggested in a private report; would also let `--enable-dcr` stay off by default for more deployments. **Effort:** M. **Priority:** P3.+- [x] **P3 — `scopes_supported` still advertises `admin` / `sources_admin` / `users_admin` to self-registering clients.**+ **What:** OAuth metadata lists every scope the server knows except the operator-only `agent` scope (omitted from discovery since v0.50.2.0), but DCR clients are capped at `read write` (read-only for `client_credentials`), so a connector that copies `scopes_supported` into its request is rejected at `/register` or gets an empty grant at `/authorize`, and the consent page shows no badge for the dropped scope. **Fix:** either advertise the DCR-registrable subset when DCR is enabled, or have the consent page explain why a requested scope is absent. **Effort:** S. **Priority:** P3. **Completed v0.50.5.0:** discovery advertises the DCR-registrable set while DCR is enabled.+- [ ] **P3 — Source fence for operator-registered `sources_admin` clients on the remaining `sources_*` mutating ops.**+ **What:** v0.50.5.0 confines remote `sources_remove` to the caller's write source (`assertSourceInCallerWriteScope`); `sources_archive` and the other mutating source ops still act on any id a `sources_admin` token names. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Entropy-gated assignment redaction: a hex digest after `token:` still redacts.**+ **What:** the `high_entropy_assignment` rule now requires a digit in the value (so identifiers and paths survive) but a 40-hex git sha or content hash following a `token`/`secret` keyword still redacts in transcript pages. A hex-only exemption would re-open real hex API keys, so this is a documented trade-off pending a better signal. **Effort:** S. **Priority:** P3.+- [ ] **P2 — Next security wave: the remaining medium/low privately reported items.**+ **What:** four open reports remain after the v0.50.5.0 wave, covering admin-API key minting, private-visibility parity across every read surface, the documented untrusted-content controls, and an input-validation regex in skill-name handling; one further report is already closed on master by the v0.50.0.0 data-only frontmatter parser and only needs its advisory published. Specifics live in the maintainer's private plan file, not here, until the fixes ship. **Why:** the v0.50.5.0 wave closed the critical/high set only. **Effort:** M. **Priority:** P2.+- [ ] **P3 — Per-client pending-consent cap is per process.**+ **What:** `OAuthGrants.begin()` bounds awaiting-decision requests server-wide (1000) and per `client_id` (10) in the in-memory store, so a multi-process deployment multiplies both ceilings. **Fix:** persist the per-client count or add a short per-client cooldown shared through the database. **Effort:** M. **Priority:** P3.+- [ ] **P3 — `sources_add` over MCP can create a source the caller then cannot see or remove.**+ **What:** a remote `sources_admin` caller may add a source outside its own grant; with `sources_list` / `sources_status` / `sources_remove` all confined to the grant, the new source stays invisible to its creator until the operator rescopes the client (`gbrain auth rescope-client <id> --federated-read ...`). Consistent with the e2e "stays hidden until rescope" contract but surprising. **Fix:** auto-grant the creator read access, or name the rescope step in the op result hint. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Doctor `oauth_client_scope_health` arm (c) signature also matches pre-audit operator clients.**+ **What:** the "privileged self-registered client" WARN keys on `grant_revision = 0` + no `oauth_grant_audit` 'register' row, which operator clients created before the grant audit log also satisfy; the message is worded as advisory for that reason. **Fix:** a one-time backfill of `register` audit rows for existing operator-created clients would make the DCR signature exact. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Confirm the Postgres arm of the `getRawData` soft-delete parity describe on the first CI run.**+ **What:** `test/e2e/engine-parity.test.ts` gained a standalone describe whose PGLite arm ran in the implementation sandbox; the Postgres arm needs `DATABASE_URL` (no Docker there). **Effort:** XS. **Priority:** P3.+- [ ] **P3 — Unify the `bearer` floors between secret-scan (20 chars) and the PII family (10 chars).**+ **What:** `sensitivity-scan.ts` bridges the gap by fingerprint dedupe so short bearer tokens still surface as `pii:bearer`; making secret-scan the single owner would let the PII family drop `jwt` / `bearer` entirely. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Bulk purge for a leaked transcript session.**+ **What:** a long session lands as `-pN` part pages plus raw metadata; after a leak the operator hand-lists slugs for `gbrain delete <slug> --purge`. A `gbrain transcripts purge --session <file>` would purge every part + raw row of one session. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Widen `scripts/check-pg-url-redaction.sh` to every scheme `db_url_credentials` covers.**+ **What:** the guard greps `src/` for `postgres(ql)://…@` literals only; comments could still spell a mysql/mongodb/redis URL with userinfo. **Effort:** XS. **Priority:** P3.+- [ ] **P3 — `gbrain jobs submit shell --follow` (inline execution) reads the shell opt-in from env only.**+ **What:** `jobs work` gained `--allow-shell-jobs` because the cwd-`.env` quarantine can drop `GBRAIN_ALLOW_SHELL_JOBS`; the inline `--follow` path has no flag equivalent. **Effort:** XS. **Priority:** P3.+- [ ] **P3 — CLI-spawning tests fail on the runtime gate instead of skipping when the host Bun is below `MINIMUM_BUN_VERSION`.**+ **What:** `test/cli-flag-validation.test.ts` subprocess smokes and every `test/helpers/cli-spawn.ts` consumer spawn `bun` from PATH; on a 1.3.10 host they fail with "GBrain requires Bun 1.3.11 or newer". **Fix:** `test.skipIf(!bunSupported)` or spawn `process.execPath`. **Effort:** XS. **Priority:** P3.+- [ ] **P3 — `scripts/generate-flag-registry.ts` attributes `jobs work --allow-shell-jobs` to the `doctor` scan surface.**+ **What:** the `facadeExpansion` heuristic filed the new flag under `doctor`; verify that is the intended registry shape or teach the generator the `jobs work` surface. **Effort:** XS. **Priority:** P3.+- [ ] **P3 — Pass `env: process.env` explicitly at the remaining git exec sites.**+ **What:** the sanitized re-run already cleans the environment those `execFileSync('git', …)` calls in `src/commands/doctor/bootstrap-checks.ts` and `src/core/skill-fix-gates.ts` inherit; the hook path carries the explicit env as belt-and-braces and these two do not. **Effort:** XS. **Priority:** P3.+- [ ] **P3 — cwd-`.env` sanitized re-run when gbrain is started via `bun -e` or a wrapper with no re-runnable entry.**+ **What:** `cli-preflight.ts:selfArgv` returns null there and the process keeps the in-process-only quarantine (descendants may still see planted values). Only dev/wrapper invocations are affected. **Effort:** S. **Priority:** P3.+- [ ] **P3 — `DeleteThroughResult.skipped` union: add `already_soft_deleted`.**+ **What:** `delete_page purge` on a tombstoned row reports `write_through: { removed: false, skipped: 'already_soft_deleted' }` via an inline `as const` (the `subagent_sandbox` precedent); widening the closed union in `write-through.ts` is a one-liner. **Effort:** XS. **Priority:** P3.+- [ ] **P3 — Drop the dead `includeDeleted` at the transcript ingest raw probe.**+ **What:** `importFromContent` re-imports (and revives) a soft-deleted base page, so the all-skipped probe at `src/core/transcripts/ingest.ts` only ever runs against a live page; the flag is harmless but dead (pinned by the "probe never runs" test). **Effort:** XS. **Priority:** P3.+- [ ] **P2 — Allowlist-based environment for spawned tools instead of the cwd-`.env` denylist.**+ **What:** `src/core/env-trust.ts` protects a denylist of known hijack families (loader, git, node, proxies, XDG roots, trust stores, editors, provider endpoints); a denylist is reactive by nature (the XDG config-root vector was found only in review). A per-spawn-site allowlist for git, the claude CLI and workers, built from `env-trust.ts`, would make the boundary positive. **Effort:** M. **Priority:** P2.+- [ ] **P3 — gbrain self-spawn sites pass a pre-sanitized env + neutral cwd.**+ **What:** supervisor → worker, hook → detached push and worker → run-child inherit the hostile cwd, so each subtree pays its own sanitized re-run and warning once; `cli-preflight.ts` could export the hop env builder so descendants start clean. **Effort:** S. **Priority:** P3.+- [ ] **P3 — cwd `bunfig.toml` under the dev runtime (`preload`) is a sibling vector to cwd `.env` for `bun src/cli.ts`.**+ **What:** compiled binaries are unaffected; decide whether preflight should refuse or warn when a cwd bunfig names a preload. **Effort:** S. **Priority:** P3.+- [ ] **P2 — Script-mode installs still apply a project directory's `bunfig.toml` `preload` before gbrain starts.**+ **What:** the documented install (`bun install -g github:garrytan/gbrain`, `bun link`) runs `src/cli.ts` as a Bun script, and Bun applies the cwd `bunfig.toml` top-level `preload` before any gbrain code; only the compiled binary carries `--no-compile-autoload-bunfig`. Measured on Bun 1.3.13: only `bun --config=/dev/null <entry>` suppresses it — no env var, no `-c` spelling, no `--no-bunfig`. Shipped now: a one-line stderr warning from `cli-preflight.ts` when a foreign cwd declares a top-level `preload`. **Fix options:** (1) make the compiled release binary the documented user install; (2) `#!/usr/bin/env -S bun --config=/dev/null` once busybox-`env` platforms are ruled out (coreutils ≥ 8.30, macOS ≥ 10.15); (3) a thin launcher as the `bin` target that execs `bun --config=/dev/null <cli.ts>`; (4) an upstream Bun off switch. Pinned by the script-mode describe in `test/cli-cwd-dotenv-quarantine.test.ts`. **Effort:** S–M. **Priority:** P2.+- [ ] **P3 — `removeSource` (`src/core/sources-ops.ts`) lacks the CLI's `clientsReferencingSource` pre-check.**+ **What:** `gbrain sources remove` refuses with a structured list of referencing OAuth clients; the `sources_remove` op path lets a caller whose write source IS the target pass the authority gate and hit the raw `oauth_clients.source_id` FK RESTRICT (23503) instead. Also: the CLI does not clean the managed clone dir (`_keepStorage` unused) while the op does, and remote `sources_remove` is now effectively operator-only over HTTP (every client is bound and its own source is FK-blocked) — decide whether it should stay exposed. **Fix:** share one removal path between CLI and op (pre-check + clone cleanup). **Effort:** S. **Priority:** P3.+- [ ] **P3 — `test/pages-purge-artifact.test.ts` chmod variants skip where the caller has CAP_DAC_OVERRIDE.**+ **What:** on root / privileged runners `chmod 0555` does not block `unlink(2)`, so the two permission-denied variants skip by name; the directory-in-place variants keep the fail-closed purge path covered unconditionally. **Fix:** none needed unless CI reports the skips as coverage loss. **Effort:** XS. **Priority:** P3.+- [ ] **P3 — Provider API keys loaded from a project `.env` are deliberately not quarantined (design decision).**+ **What:** `OPENAI_API_KEY`, `OPENROUTER_API_KEY` and the other provider credentials a cwd `.env` may assign are the operator's own spend, not a redirection of gbrain's targets, so only the `*_BASE_URL` endpoint variables are on the protected list. Revisit if a concrete path is found where a planted key (rather than a planted endpoint) moves brain content somewhere the operator did not choose. **Effort:** S. **Priority:** P3.+- [x] **P3 — `sources_remove` confinement uses the read ladder; consider the write-authority rule for a destructive op.** **Completed: v0.50.5.0 (2026-09-16)** — `sources_remove` now keys on `assertSourceInCallerWriteScope` (`src/core/ops/context.ts`): an untrusted caller may remove only its own write source, a federated read grant confers no removal right, and out-of-authority ids answer `not_found`.+ **What (as filed):** remote `sources_remove` may name any id inside `sourceIds ?? [sourceId]` (federated read grant), while `delete_page` requires the caller's write source. A `sources_admin` token bound to `a` with `federated_read: [a, b]` can hard-remove `b`. Strict improvement over the pre-wave behavior; tightening to the write source would mirror `delete_page`. **Effort:** S. **Priority:** P3.+- [ ] **P2 — Per-client pending-consent cap can be used to lock a known client out of consent.**+ **What:** anyone holding a `client_id` + registered `redirect_uri` (both appear in `/authorize` URLs) can hold ten pending requests per ten-minute window, so the legitimate connector is redirected with `error=too_many_requests` until the owner decides them; the cap moved the targeted-denial cost from the global capacity to ten unauthenticated requests. **Fix:** separate unauthenticated admission limits from the legitimate client's approval capacity — count per `(client_id, remote address)` with the address threaded into `begin()`, evict the oldest undecided request for that client instead of refusing, add a bulk-deny in the admin UI, or exempt operator-registered clients. Flagged independently by the pre-landing adversarial pass. **Effort:** S. **Priority:** P2.+- [ ] **P3 — `delete_page --purge` sweep of slug-keyed derived rows without FKs.**+ **What:** the purge response names the residuals (git history, exports, compiled context, `take_proposals`/`open_loops`/`files` rows keyed by slug text); sweeping those tables would make the purge more complete. **Effort:** S. **Priority:** P3.+## Community fix wave follow-ups (filed 2026-09-09)- [ ] **P3 — new v0.49/v0.50 tests assume `os.tmpdir()` is already a realpath (macOS `/var` vs `/private/var`).**diff --git a/VERSION b/VERSIONindex 28a84426d3..afcb2e3c35 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.50.4.0+0.50.5.0\ No newline at end of filediff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 708697055f..c7355f9338 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -304,7 +304,10 @@ cwd-.env guard (gbrain never adopts a `DATABASE_URL` that Bun auto-loadedfrom the working directory's `.env` family: `.env`, `.env.local`, and the`.env.<NODE_ENV>` / `.env.<NODE_ENV>.local` variants for `development`,`production` and `test`; with the precedence note when both `GBRAIN_DATABASE_URL` and-`DATABASE_URL` are set), redacted URLs only, and — on Postgres — a+`DATABASE_URL` are set — this `DATABASE_URL` guard matches the file's VALUE; the+security-relevant `GBRAIN_*` variables get the stricter key-presence quarantine+described under "Environment variables and cwd `.env` files" in `SECURITY.md`),+redacted URLs only, and — on Postgres — azero-round-trip pooler block (Supabase pooler detection, prepared-statementresolution, pool sizes, direct/session-pooler derivability). `--brain <id>`resolves a mounted brain and reports the MOUNT's engine and URL source, neverdiff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 3c3866a402..df5e63754a 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -162,7 +162,7 @@ Every non-localOnly operation on the MCP surface: 122 tools across 23 areas. **S| `fetch` | Fetch the full text of one search result by its `id` (OpenAI deep-research contract: the search/fetch pair). | read | | || `get_chunks` | Get content chunks for a page | read | | || `get_page` | Read a page by slug (supports optional fuzzy matching). | read | yes | |-| `get_raw_data` | Retrieve raw data for a page | read | | |+| `get_raw_data` | Retrieve raw data for a page. | read | | || `get_versions` | Page version history | read | | || `list_pages` | List pages with optional filters. | read | yes | || `put_page` | Write or replace a page (markdown with frontmatter). | write | yes | |diff --git a/docs/UPGRADING_DOWNSTREAM_AGENTS.md b/docs/UPGRADING_DOWNSTREAM_AGENTS.mdindex 009891e125..a361988fe8 100644--- a/docs/UPGRADING_DOWNSTREAM_AGENTS.md+++ b/docs/UPGRADING_DOWNSTREAM_AGENTS.md@@ -355,8 +355,10 @@ do not opt in are unaffected.To adopt, follow `skills/migrations/v0.14.0.md`. The short version:-1. Set `GBRAIN_ALLOW_SHELL_JOBS=1` on the worker process, then `gbrain jobs work`- (Postgres). On PGLite, every crontab invocation uses `--follow` for inline+1. Start the worker with `gbrain jobs work --allow-shell-jobs` (equivalently,+ export `GBRAIN_ALLOW_SHELL_JOBS=1` on the worker process; a `.env` in the+ worker's directory cannot set it) (Postgres). On PGLite, every crontab+ invocation uses `--follow` for inlineexecution; no persistent worker.2. Classify each of your host's cron entries: LLM-requiring (keep on gateway) vsdeterministic (candidate for shell). Typical splits:diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex d00f48c5d7..ce0f375c91 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -10,7 +10,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/runtime-version.ts` — Bun 1.3.11 minimum enforced by the CLI entrypoint and guarded HTTP transport, with upgrade/restart guidance. Package engines and runtime checks share the same supported floor.- `src/core/data-frontmatter.ts` — shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema with existing scalar types, sanitizes parser errors, and keeps body text opaque. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures: `test/data-frontmatter.test.ts`, `test/frontmatter-security.test.ts`.-- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Bounded pending consent requests snapshot current operation and delegation policies. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions, and adds a read-only bootstrap scope hint to scope-less Bearer challenges without changing token authority; `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell.+- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions, and adds a read-only bootstrap scope hint to scope-less Bearer challenges without changing token authority; `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell.- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows. `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.- `src/core/guarded-http.ts` + `src/core/ssrf-validate.ts` — DNS answer classification, validated-address connections with original TLS/HTTP hostname and port, shared deadline/redirect policy, header-only probes, and bounded gzip/deflate/Brotli decoding. Ambient proxies fail closed with restart guidance. Consumers: URL reachability, remote images, and HTTP integration checks. Real TLS fixtures run on Bun 1.3.11 and 1.3.13.@@ -20,7 +20,10 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`): a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` additionally fences the RESOLVED slug when importFromContent's dedup pre-check redirects the write to a different page (same content_hash / `frontmatter.id`), since the disk write-through runs against that slug. That re-check applies whichever confinement the CALLER is under — OAuth binding and/or subagent allow-list/legacy namespace — via `slugOutsideCallerFence(ctx, slug)`, which composes `slugUnderBoundPrefixes` with the subagent fence's own match rule: the delegated `submit_agent` → subagent context carries `viaSubagent` + `allowedSlugPrefixes` while its `auth` carries current read scope without the parent's direct-write fence, so an auth-only check would let a slug-bound client holding `agent` scope reach an out-of-fence page simply by delegating the write. Denials never name the resolved slug (it would be a slug-enumeration oracle). Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page`'s inline disk write-through is the shared `writePageThrough` helper (`src/core/write-through.ts`), ATOMIC via temp-sibling + rename so a crash or concurrent `gbrain sync` can't read a half-written `.md`; same helper backs `gbrain brainstorm/lsd --save`. `put_page` acquires the root lock before publishing a revision, returns `storage_busy` with an explicit not-applied/not-queued result on acquisition contention, and reports post-persistence embedding outcomes separately. No durable queue or caller revision precondition is implied. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`). Two load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`.-- `src/core/ops/pages.ts` — the page-domain op module (`get_page`, `put_page`, `delete_page`/`restore_page`, `capture`, …; the source-scoping contract of the delete/restore trio is described under `src/core/destructive-guard.ts`). `get_page` resolution ladder: exact read in the caller's scope → alias hop → fuzzy. The alias hop scopes its lookup to the federated grant (`sourceIds[]`) > the scalar `sourceId` > (trusted unscoped only) every LIVE source — archived sources' alias rows count only when `include_deleted` asks for archived material — through `engine.resolveSlugWithAliasDetailed`, then reads the canonical page IN THE SOURCE THAT OWNS THE ALIAS ROW (`getPage(canonical, { sourceId: hit.source_id })`): a federated `getPage` prefers the anchor source, so an unrelated live page at the canonical slug in another granted source would otherwise shadow the alias owner's page. The redirect target composes with the same private-page gate as the exact read and reports `resolved_slug`. `capture`: an EXPLICIT type (the `type` param, else a frontmatter `type:` in the content — `explicitCaptureType` in `src/core/capture-content.ts`, BOM/CRLF tolerant, malformed YAML → none) is validated against the active pack when one resolves (`schema-pack/write-vocabulary.ts`) and IS the effective type for both the default slug and the merged frontmatter — approved as X, stored as X; no explicit type stamps `note` (never checked). Sits at its module-size ratchet ceiling (`scripts/module-size-limits.tsv`); the next growth peels a submodule. Pinned by `test/get-page-federated-scope.test.ts`, `test/capture-explicit-type.test.ts`, and the engine-parity suite (both engines pick the same owning row). The alias hop has no catch of its own: both engines return `null` for the pre-v104 missing-table case, so any other rejection (connection reset, timeout) propagates instead of degrading to `page_not_found`.+- `src/core/ops/pages.ts` — the page-domain op module (`get_page`, `put_page`, `delete_page`/`restore_page`, `capture`, …; the source-scoping contract of the delete/restore trio is described under `src/core/destructive-guard.ts`). `get_page` resolution ladder: exact read in the caller's scope → alias hop → fuzzy. The alias hop scopes its lookup to the federated grant (`sourceIds[]`) > the scalar `sourceId` > (trusted unscoped only) every LIVE source — archived sources' alias rows count only when `include_deleted` asks for archived material — through `engine.resolveSlugWithAliasDetailed`, then reads the canonical page IN THE SOURCE THAT OWNS THE ALIAS ROW (`getPage(canonical, { sourceId: hit.source_id })`): a federated `getPage` prefers the anchor source, so an unrelated live page at the canonical slug in another granted source would otherwise shadow the alias owner's page. The redirect target composes with the same private-page gate as the exact read and reports `resolved_slug`. `capture`: an EXPLICIT type (the `type` param, else a frontmatter `type:` in the content — `explicitCaptureType` in `src/core/capture-content.ts`, BOM/CRLF tolerant, malformed YAML → none) is validated against the active pack when one resolves (`schema-pack/write-vocabulary.ts`) and IS the effective type for both the default slug and the merged frontmatter — approved as X, stored as X; no explicit type stamps `note` (never checked). Sits at its module-size ratchet ceiling (`scripts/module-size-limits.tsv`); the next growth peels a submodule. Pinned by `test/get-page-federated-scope.test.ts`, `test/capture-explicit-type.test.ts`, and the engine-parity suite (both engines pick the same owning row). The alias hop has no catch of its own: both engines return `null` for the pre-v104 missing-table case, so any other rejection (connection reset, timeout) propagates instead of degrading to `page_not_found`. `delete_page`: `purge: true` (strict boolean) is honored ONLY when `ctx.remote === false` — any other caller gets `permission_denied` (the local-only-lane convention shared with `connectors_status`/`get_recent_transcripts`; a non-boolean `purge` is still `invalid_params`) and keeps the soft-delete path. Purge soft-deletes (write-through + audit shape), then calls `engine.deletePage(slug, sourceOpts)`. On an already-soft-deleted row it resolves the tombstone's recorded file (`resolvePageWriteTarget(..., { includeDeleted: true })`) and RETRIES the artifact removal before dropping the row; `write_through` reports the real outcome (`removed: true`, `removed: false, skipped: 'file_not_present'`, or a non-error skip), never a fabricated skip. `assertPurgeArtifactGone` fails BOTH purge paths closed when the unlink errored: `OperationError('storage_error')` naming the path, the row stays soft-deleted, and a re-run resumes on the tombstone path — a purge that leaves the file is not a purge (the next sync would re-import it); plain soft-delete stays best-effort (pinned by `test/pages-purge-artifact.test.ts`); `status: 'purged'` always carries `write_through` and a `residuals` hint (`PURGE_RESIDUALS`: brain-repo history, synced copies, exports, compiled context, slug-keyed derived rows may still hold the content — rotate first) — the already-soft-deleted branch reports `{ removed: false, skipped: 'already_soft_deleted' }` (single response shape); result `status: 'purged'`; dry-run action `purge_page`. The CLI flag `gbrain delete <slug> --purge` derives from the contract (no cli.ts special case). The soft-delete result's `recoverable_until` hint names the purge command.+- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).+- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`.+- `src/core/ops/raw-data.ts` — `put_raw_data` / `get_raw_data`. `get_raw_data` follows the page soft-delete (a tombstoned page reads as `[]`, `restore_page` brings the rows back; there is no remote `include_deleted` param — `get_page include_deleted: true` verifies the tombstone) and, per #4352, a `visibility: private` page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from `readPolicyOpts(ctx)`, never from MCP parameters.- `src/core/ops/admin.ts` — the admin/diagnostics domain module (`get_stats`, `get_health`, `get_brain_identity`, …). All three aggregate ops confine remote callers via the same ladder reads use: `ctx.remote === false` keeps the trusted brain-wide view; every other caller gets `sourceScopeOpts(ctx)` (federated array > scalar > the unmatchable `__all__` sentinel, which fail-closes to zeros) threaded into `engine.getStats(scope)`/`getHealth(scope)` — aggregates leak by subtraction, so they scope exactly like reads, and read-scope `get_brain_identity` is confined the same way. `get_health`'s `migrations {pending, partial, wedged, skipped_future}` block stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in `BrainEngine.getHealth` — growing the engine interface would force both engines to duplicate a file read).- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's result is empty and `hasUnsealedPagesInScope` finds markdown pages in scope below the safe-chunk index version (sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by `pages_chunker_version_idx` as an Index Cond — NOT the COALESCE `safeChunksFilter` form, which the partial btree cannot serve and which walked every markdown page on a sealed brain; pinned by `test/search-safe-index-probe.test.ts`; fail-open; ignores the call's `types`/`excludePrivate`), it appends the `safe_index_pending` degraded stage so the MCP empty-result block names the pending `gbrain reindex --markdown` instead of a clean miss; the withholding itself is unchanged.- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting `row_num` past the canonical page's current MAX(row_num) (all rows incl. expired — the partial `idx_facts_fence_key` only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.@@ -45,7 +48,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/search.ts:gbrain search stats` — `graph_signals` section (enabled/source/failures_count/failures_by_reason). JSON envelope adds a `graph_signals` sibling property; `_meta.metric_glossary` adds `graph_signals.enabled` + `graph_signals.failures_by_reason`. Human output prints the section after the existing block. Reads `search.graph_signals` config first, falls back to the mode default. Pinned by `test/search/search-stats-graph-signals.test.ts`. Both `gbrain search stats` and `gbrain search tune` also surface a `coverage` disclosure (JSON: `{cli_invocations: 'recorded_on_clean_exit', reason}`; human: a one-line caveat) sourced from `telemetryCoverage()`/`TELEMETRY_COVERAGE_CAVEAT` in `src/core/search/telemetry.ts`: a short-lived CLI call's buffer flushes during the bounded CLI teardown drain, so a CLEAN exit is recorded; hard kills, drains that exceed their bound, and anything buffered when an engine disconnects outside the CLI teardown path still drop — the disclosure is display-only and reads its truth from the telemetry module's single-source constants. Pinned by the coverage-disclosure tests in `test/commands-search.test.ts`.- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`).-- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` early-nulls the handle (so no NEW statement can reach it), then runs `drainBackgroundWorkBeforeDisconnect()` so statements ALREADY in flight settle against the still-open handle — PGLite's `close()` deadlocks permanently (close's promise AND the in-flight query's promise never settle) with a statement in flight; the ordering is load-bearing (drain above the null would let a new statement race the close). Teardown defense is layered and honestly scoped: the drain PREVENTS the known wedge; the in-loop close bound (`GBRAIN_PGLITE_CLOSE_TIMEOUT_MS`, default 5000ms, floor 1s, ceiling 2^31−1, read per call) covers ONLY a close that still yields to the event loop — armed BEFORE `close()` is called and deliberately ref'd, a timed-out close degrades to a once-per-process stderr warning naming both env knobs and teardown proceeds (an abandoned close's later rejection is swallowed; the WAL-repair path covers a zombie instance on next open); a close that WEDGES the loop (blocked or microtask-starved) can never be caught by any same-loop timer and is observable/killable only by the opt-in out-of-band watchdog — a diagnostic/incident instrument, not ambient production protection: `GBRAIN_PGLITE_CLOSE_WATCHDOG_MS` (unset/0 = off; a positive value clamps UP to `max(5000, registered-sink-count×2000 + close timeout + 2000)` with a warn so a units typo never SIGKILLs a healthy slow teardown) + `GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS` (default 30000) arm the shared `process-watchdog.ts` worker around a PGLite disconnect with a live handle (armed after the early-return, before the drain; disposed in a nested finally so a `releaseLock` throw can't leak it; SIGTERM at deadline, SIGKILL at deadline+grace; lock-only teardown and postgres pool teardown are out of scope). Pinned by `test/pglite-engine-disconnect.serial.test.ts` + `test/search-telemetry-disconnect-hang.serial.test.ts` + `test/pglite-disconnect-watchdog.serial.test.ts` (spawned fixture that genuinely starves the loop) + the structural pins in `test/fix-wave-structural.test.ts`. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `disconnect()` uses snapshot+early-null (snapshot `_db`/`_lock`, null instance fields BEFORE any `await` so a concurrent `connect()` can't see a partial mid-close state) wrapped in try/finally guaranteeing lock-release even if `db.close()` throws; KEEPS close-then-release order (release-then-close was rejected: it would widen the window where a sibling process connects to a still-closing brain); Pinned by `test/pglite-engine-disconnect.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.+- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` early-nulls the handle (so no NEW statement can reach it), then runs `drainBackgroundWorkBeforeDisconnect()` so statements ALREADY in flight settle against the still-open handle — PGLite's `close()` deadlocks permanently (close's promise AND the in-flight query's promise never settle) with a statement in flight; the ordering is load-bearing (drain above the null would let a new statement race the close). Teardown defense is layered and honestly scoped: the drain PREVENTS the known wedge; the in-loop close bound (`GBRAIN_PGLITE_CLOSE_TIMEOUT_MS`, default 5000ms, floor 1s, ceiling 2^31−1, read per call) covers ONLY a close that still yields to the event loop — armed BEFORE `close()` is called and deliberately ref'd, a timed-out close degrades to a once-per-process stderr warning naming both env knobs and teardown proceeds (an abandoned close's later rejection is swallowed; the WAL-repair path covers a zombie instance on next open); a close that WEDGES the loop (blocked or microtask-starved) can never be caught by any same-loop timer and is observable/killable only by the opt-in out-of-band watchdog — a diagnostic/incident instrument, not ambient production protection: `GBRAIN_PGLITE_CLOSE_WATCHDOG_MS` (unset/0 = off; a positive value clamps UP to `max(5000, registered-sink-count×2000 + close timeout + 2000)` with a warn so a units typo never SIGKILLs a healthy slow teardown) + `GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS` (default 30000) arm the shared `process-watchdog.ts` worker around a PGLite disconnect with a live handle (armed after the early-return, before the drain; disposed in a nested finally so a `releaseLock` throw can't leak it; SIGTERM at deadline, SIGKILL at deadline+grace; lock-only teardown and postgres pool teardown are out of scope). Pinned by `test/pglite-engine-disconnect.serial.test.ts` + `test/search-telemetry-disconnect-hang.serial.test.ts` + `test/pglite-disconnect-watchdog.serial.test.ts` (spawned fixture that genuinely starves the loop) + the structural pins in `test/fix-wave-structural.test.ts`. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `disconnect()` uses snapshot+early-null (snapshot `_db`/`_lock`, null instance fields BEFORE any `await` so a concurrent `connect()` can't see a partial mid-close state) wrapped in try/finally guaranteeing lock-release even if `db.close()` throws; KEEPS close-then-release order (release-then-close was rejected: it would widen the window where a sibling process connects to a still-closing brain); Pinned by `test/pglite-engine-disconnect.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass. `getRawData` pushes `p.deleted_at IS NULL` into its `where[]` unless `opts.includeDeleted` — parity twin of the Postgres `alive` fragment; see the postgres-engine.ts entry.- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).- `src/core/pglite-lock.ts` — advisory data-dir lock so two processes never open the same embedded PGLite (single-connection WASM Postgres) at once. Atomic `mkdir` of `.gbrain-lock/` + a `lock` file carrying `{pid, acquired_at, refreshed_at, command, argv, subcommand}`. A held lock HEARTBEATS its `refreshed_at` every 30s (`.unref()`ed timer; informational). A waiting acquirer reaps a holder ONLY on affirmative proof of death — ESRCH from kill-0, or a `ps`-/`proc`-read command line (Windows uses the shared CIM probe) proving a mismatch with structured recorded argv under AFFIRMATIVE same-namespace proof (on Linux the lock's recorded `pid_ns` must be readable and equal ours, a readable, matching `boot_id` is also required; legacy locks without structured argv or required namespace markers are never cmdline-reaped; unreadable cmdline and same-process PID also read as alive) — a LIVE holder is NEVER stolen, regardless of how stale its heartbeat is. Every reap serializes on an atomic claim dir (`tryReapLockDir`) and re-validates the victim's ownership token while the lock is still in place, so concurrent reapers can't delete each other's freshly installed locks; a crashed claimant's dir is broken after a 30s TTL / dead PID. A live `gbrain serve` holder is identified from the parsed `subcommand` and reported immediately with separate CLI-retry and MCP-tool choices; other live holders keep the bounded wait. `gbrain sync` normally never reaches this error under a live serve — the cli.ts preflight (`src/commands/sync-delegate.ts`) probes the lock file read-only and delegates the sync through the serve's IPC socket instead. The heartbeat runs on the JS event loop, which is blocked during long synchronous WASM imports/CHECKPOINTs, so a working `dream`/`embed` holder can look stale while alive; a steal-on-stale-heartbeat grace would let a second OS process open the same data dir and corrupt the catalog + pgvector extension (58P01 / `internal_load_library` / `type "vector" does not exist`), recoverable only by wipe+restore. A wedged-but-alive holder is never stolen: serve-tagged holders report immediately, while other holders time out with a message naming the PID. Each holder carries an ownership token (`<pid>:<acquired_at>`); the heartbeat and `releaseLock` verify the on-disk lock is STILL theirs before touching it. In-memory engines take no lock. There is deliberately NO same-process reentrancy or same-PID special case: a second `acquireLock` from the process that already holds the lock waits out the timeout like any other live holder (the classic cause is a command double-connecting a second engine on the same data dir; the fix is to reuse the connected engine at the dispatch layer, never to soften the lock). `LockHandle.reaped` marks an acquisition that reaped a prior holder's lock (dead-PID reap, PID-recycling reap, or corrupt-lock-file removal — the only reaps that exist); the WAL auto-repair gate refuses to run surgery on a reaped acquisition since a corrupt lock file cannot prove its holder is dead. A corrupt-lock reap ALSO writes a persisted marker (`<dataDir>.lock-reap.json`, read via exported `msSinceLastReap`) so the NEXT process's clean acquisition is still repair-quarantined for 10 minutes — the in-process flag alone would let the reaper's successor run surgery under a possibly-live writer; dead-PID reaps (affirmative ESRCH verdict; EPERM reads as ALIVE) deliberately skip the marker so dead-holder recovery stays one-failed-command-plus-one-re-run. Heartbeat refreshes write via tmp+rename (a torn in-place write could be read mid-flight by a polling acquirer and misclassify a HEALTHY live holder as a corrupt lock). Pinned by `test/pglite-lock.test.ts`. A corrupted store surfaces a `reinit-pglite` recovery hint via `classifyPgliteInitError`'s `corrupt` verdict in `pglite-engine.ts`. Exported `inspectLockHolder(dataDir): LockHolderInfo` is the READ-ONLY inspection seam for status surfaces (`gbrain engine status`, smoke-test): never reaps, never mkdirs, never blocks; a dead-PID holder reads as not-held, a live serve holder reads as `serve: true` so a probe can report `locked_by_serve` instead of hanging on the single-writer lock. `peekLock(dataDir)` is the pure read of the same lock — no `mkdir`, no acquisition side effect, never throws `LiveServeLockError` — so a third-party caller can tell "held by a live serve" apart from "available" without taking the lock itself; it reports not-held for a missing lock dir, a dead-PID holder, or an unreadable lock file, and is deliberately outside gbrain's own acquisition path, which is unchanged. Exported as `gbrain/pglite-lock`.- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (a port of the electric-sql/pglite pg_resetwal contribution, PR #994, Apache-2.0). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.@@ -65,7 +68,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/doctor/checks/default-source-path.ts` — the gathering wrapper on the doctor surface: reads the `default` sources row, page counts (live + file-backed), `sync.repo_path` resolution, and the leak-guard collision, then delegates the verdict to `assessDefaultSourcePath`. Only gathers the fallback-topology inputs when the pointer is actually null; returns null for the skip verdict.- `src/commands/doctor/checks/fts-reindex.ts` — `ftsReindexIncompleteCheck(engine)`: the `fts_reindex_incomplete` check. Reads the `fts.reindex_in_progress` config row that `reindex-search-vector` sets before its trigger-language flip and clears only after both backfills finish; null (nothing pushed) when absent, `fail` naming the language and the resume command (`GBRAIN_FTS_LANGUAGE=<lang> gbrain reindex-search-vector --yes`) when set, because un-backfilled rows are unreachable by keyword search under the new configuration. Registered in doctor.ts inside the `engine !== null` lazy-import guard (skipped on `--fast` / DB-down); category `brain`. Pinned by `test/doctor-fts-reindex-incomplete.test.ts`.- `src/commands/doctor/checks/home-worktree.ts` — the `home_dir_in_worktree` check: walks up from the gbrain home looking for an enclosing `.git` (dir or linked-worktree file), warning that a `git add` from the worktree root could stage the brain; stops at $HOME. Both anchors (`GBRAIN_HOME`, `$HOME`) are `path.resolve()`d before the containment test, so a trailing-slash `HOME=/home/user/` (a common shell/launchd spelling) cannot make a brain inside a worktree grade ok. `isValidGitMarker` structurally validates a candidate before it counts (a `.git/` dir must contain HEAD; a `.git` file must start with `gitdir:` — git itself rejects anything else), and invalid candidates CONTINUE the walk so a valid repo higher up still warns. Cheap (stat + read, no subprocess) — runs on every doctor invocation including `--fast`.-- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/postgres-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — a superset of PGLite's probe set: the shared column-only forward-reference cases (`files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`/`archived_at`/`archive_expires_at`, `timeline_entries.event_page_id`) plus Postgres-blob-only probes for state the PGLite blob doesn't carry (`dream_verdicts.expires_at` — see the forward-reference-bootstrap.ts entry); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-ownership.test.ts`. `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). Test seam `__resetFactsEmbeddingCastCacheForTest()` clears the per-engine cache. `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`.+- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/postgres-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — a superset of PGLite's probe set: the shared column-only forward-reference cases (`files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`/`archived_at`/`archive_expires_at`, `timeline_entries.event_page_id`) plus Postgres-blob-only probes for state the PGLite blob doesn't carry (`dream_verdicts.expires_at` — see the forward-reference-bootstrap.ts entry); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-ownership.test.ts`. `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). Test seam `__resetFactsEmbeddingCastCacheForTest()` clears the per-engine cache. `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`).- `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/core/postgres-engine/` + `src/core/pglite-engine/` — narrow-deps engine module directories, mirrored in lockstep (the engine-parity discipline applies to these dirs exactly as to the façades). Each holds `facts.ts`, `takes.ts`, `code-edges.ts`, and `salience.ts`: the corresponding BrainEngine method clusters implemented as free functions over a typed deps interface (e.g. `PgliteFactsDeps`) that the engine class satisfies, so each module depends only on the narrow slice it uses. `code-edges.ts` `getCalleesOf` takes an opt-in `bareFallback` (set ONLY by the `code_callees` op + `gbrain code-callees`, never by the code_flow/code_blast BFS): a zero-row exact miss for a delimiter-free input re-keys the same UNION on `content_chunks.symbol_name` (exact, indexed, never LIKE), so the documented "bare or qualified name" contract holds for namespace/class-qualified chunks (C#/Java/Ruby/Rust, TS class methods) whose edges are emitted bare. The façade methods delegate to them via static top-level imports (the engine-live no-runtime-dynamic-import rule applies) and keep the full public surface.- `src/core/postgres-engine/forward-reference-bootstrap.ts` — `applyPostgresForwardReferenceBootstrap(conn)`: the forward-reference bootstrap for the RAW `SCHEMA_SQL` replay path (probe + patch every column/table the embedded schema blob forward-references but older brains don't have yet — single probe round-trip, idempotent, fast no-op when nothing is missing). Peeled out of `PostgresEngine` so BOTH replay entrypoints run it before the blob: `PostgresEngine.initSchema()` AND the standalone module-singleton `db.ts:initSchema()` (replaying with no bootstrap would wedge an upgrade-boundary brain on `CREATE INDEX` over a column the replayed blob forward-references). Callers MUST hold the initSchema advisory lock (key 42) on `conn` so concurrent bootstraps can't race on a transaction pooler. Mirror of `PGLiteEngine#applyForwardReferenceBootstrap` in shape — keep in sync; covered by `test/schema-bootstrap-coverage.test.ts` (PGLite A2 static check + the Postgres-blob CREATE-INDEX class-closure gate, which parses `SCHEMA_SQL` and requires every migration-added blob-indexed column to have a probe here or an explicit exemption) + `test/e2e/postgres-bootstrap.test.ts` (Postgres side, live convergence cases). Probes are column-only (nullable `ADD COLUMN`, plus `SET DEFAULT` where hardening the upgrade window needs it — `dream_verdicts.expires_at`); the owning migration stays the source of truth for backfill/constraints/indexes: on the engine path it runs right after the bootstrap under the same advisory lock, while the standalone `db.ts:initSchema` path replays the blob WITHOUT running migrations — safe because the NULL-tolerant read predicates treat pre-backfill rows as valid until the next full engine init.@@ -306,7 +309,11 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/source-config-sql.ts` + `src/core/sources-load.ts` — canonical recovery for non-object `sources.config` values. The application reader unwraps nested JSON strings and merges recoverable array fragments left-to-right; the shared SQL expression mirrors that policy atomically for both engines, source config updates, archive/restore, and the paste-ready `source_config_shape` doctor repair. `localFederatedSourceIds` reads config through the same parser so stdio/CLI federation cannot silently disagree with `sources list`. `sourceConfigHasRemoteUrl` uses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to `{}` rather than throwing. Pinned by `test/sources-load.test.ts`, `test/job-pull-policy.test.ts`, `test/list-all-sources.test.ts`, `test/local-federated-search-scope.test.ts`, `test/destructive-guard.test.ts`, and `test/doctor-source-config-shape.test.ts`.- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `src/commands/sync.ts:1497-1519` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed), with `maybeWarnUnscopedDefaultWrite` as its warning-only projection; `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.- `src/core/migrate.ts` — schema-migration runner. Owns the `MIGRATIONS` array (source of truth for schema DDL). `Migration` interface carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; mirror in pglite-schema.ts + schema.sql + bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice).-- `src/cli.ts` — no-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`).+- `src/cli.ts` — no-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`). `main()` opens with `await runCliPreflight()` (core/cli-preflight.ts: cwd-.env quarantine -> `~/.gbrain/.env` -> guardrails loader) before `parseGlobalFlags`; the former inline #3688 guardrails block lives in the preflight module.+- `src/core/cli-preflight.ts` — `runCliPreflight()`, the first statement of `cli.ts:main()`. (0) Re-run detection: `GBRAIN_CWD_ENV_QUARANTINED` (`CWD_ENV_QUARANTINED_MARKER`) is parsed as JSON `{cwd, neutral, wrapperPid}` and honoured ONLY when the process's startup cwd realpath-equals `neutral` and `neutral` holds none of `CWD_DOTENV_FILES` (`wrapperPid` is informational — accepted only as a positive safe integer, otherwise ignored); on a verified hop it deletes the marker, `chdir(cwd)`s back, skips step 1 (the parent already warned), and arms `installWrapperWatchdog`: an `unref()`ed 1 s interval comparing `process.ppid` (live in Bun) with `wrapperPid` — a mismatch prints one `[env]` line, `rmdirSync`s the empty neutral dir the wrapper's `finally` never reached, and exits 137, so a supervisor that SIGKILLs the wrapper pid (`restartCurrentChild`, job-isolation children, hook pushes) takes the real re-run down within about a second instead of leaving an orphan; an unverified marker is ignored, never chdir'd on. (1) `parseCwdDotenv(cwd)` ONCE, shared by the cwd == config dir check and `quarantineCwdDotenv(process.env, cwd, { assignments })`. (1a) If the drop removed a NON-EMPTY `GBRAIN_GUARDRAILS_MODULE`, print `GUARDRAILS_ASSIGNED_BY_CWD_DOTENV` and exit 1 — fail-closed, never a re-run without the operator's firewall (the `~/.gbrain/.env` home is read after the quarantine and unaffected). (1b) Otherwise, whenever anything was dropped: `Bun.spawn([execPath, ...execArgv (dev runtime only; `resolveRuntimePaths` resolves a `./`/`../`-relative — or bare-and-existing — value of `--preload`/`-r`/`--require`/`--import`, `--config`/`-c`, `--env-file`, `--tsconfig-override`, both spellings, against the ORIGINAL cwd because the re-run starts in the empty neutral dir; everything else passes through verbatim, in order), entry/user args], { cwd: <fresh mkdtemp dir, realpath'd so `neutral` is absolute+canonical>, env: process.env minus undefined + marker, plus the operator's real `HOME` (`USERPROFILE` on win32, from `os.userInfo().homedir`, which Bun derives from the startup environ before the `.env` merge) when a planted one was dropped, stdio: inherit })` — the re-run's Bun never loads the hostile `.env`, so dropped keys are absent (never `''`, which git and the loader presence-check); signal handlers are installed BEFORE the spawn (no orphan window); `reexecSanitized` first removes every pre-existing SIGINT/SIGTERM/SIGHUP listener (cli.ts installs process-cleanup handlers before `main()`; the wrapper relays the child and nothing else), then forwards SIGINT only when `hasControllingTerminal()` is false (`/dev/tty` `O_NOCTTY` probe; isTTY flags on win32 — a terminal delivers Ctrl-C to both processes itself), always forwards SIGTERM/SIGHUP, removes the neutral dir, and exits with the child's code or 128+signal — never earlier. Termination is structural (a re-run's startup cwd has no `.env`); gbrain self-spawns starting in the hostile cwd hop once per subtree. (2) `loadGbrainEnvFile(configDir)`; (3) the #3688 guardrails loader (moved from cli.ts; fail-closed; passes `skipCwdCheck: collision`). cwd == config dir (`cwdIsOperatorConfigDir`, exported for tests): quarantine skipped only when no cwd `.env` assigns any of `GBRAIN_HOME`, `HOME`, `USERPROFILE` and `realpath(cwd) === realpath(configDir())`. Script mode (`isScriptRuntime()`: `process.execPath` is a bun runtime, not a compiled binary): `warnScriptModeBunfig` prints `SCRIPT_MODE_BUNFIG_WARNING` once when the STARTUP cwd's `bunfig.toml` declares a top-level `preload` and the cwd is not the checkout containing the running entry (Bun ran that preload before this code; the compiled binary is built with `--no-compile-autoload-bunfig`); never repeated on the re-run. Zero cost when nothing protected is assigned. Pinned by `test/cli-cwd-dotenv-quarantine.test.ts` (hostile git checkout with planted `core.fsmonitor` via `GIT_CONFIG_*` AND via `XDG_CONFIG_HOME`; `sh` presence probe for `GIT_SSL_NO_VERIFY`; four forged-marker shapes; depth-2 re-spawn; SIGTERM/SIGKILL; pty (`script`) tty-SIGINT ignore vs non-tty SIGINT forward; SIGHUP forward; execArgv preservation across the hop; chdir-back-when-original-cwd-vanished; relative-`TMPDIR` hop; guardrails fail-closed refusal + control; wrapper outlives SIGTERM until the child exits (exit = child's, neutral dir removed); planted-`HOME` drop → real home restored in both the cron and the exported-HOME shapes; forged-home config-dir exemption refused; script-mode bunfig warning (foreign cwd warns once, own checkout silent, `[test]`-section preload silent); cwd + relative-argv restoration; compiled binary from `GBRAIN_COMPILED_BIN ?? bin/gbrain`, including a cwd `bunfig.toml` `preload` staying inert).+- `src/core/env-trust.ts` — Trust boundary for environment variables Bun auto-loaded from the cwd `.env` family. `CWD_DOTENV_FILES` (the eight names Bun auto-loads across NODE_ENV values), `splitDotenvLines` (Bun's line grammar: `\n`, `\r\n` AND a bare `\r` terminate a line, leading BOM stripped — shared with gbrain-env-file.ts), `dotenvValuesForKey(key, dir)` (value set across all assignments; the #427 `DATABASE_URL` value-match guard in config.ts, which re-exports both), `cwdDotenvAssignsKey(key, dir | assignments)` (KEY-PRESENCE predicate; an empty assignment counts) and `parseCwdDotenv(dir)` → `DotenvAssignment[]` (one read the two preflight consumers share). The assignment RHS is matched as `([^\r\n]*)`, never `.*$`. Protection is one predicate, `isCwdDotenvProtectedKey(key)`: `CWD_DOTENV_PROTECTED_KEYS` (code-loading / exec-target / root- and endpoint-redirect incl. `GBRAIN_DATABASE_URL` (key-presence; the #427 config.ts VALUE guard is separate and covers only bare `DATABASE_URL`), `GBRAIN_DIRECT_DATABASE_URL`, `GBRAIN_REMOTE_MCP_URL`, `GBRAIN_REMOTE_ISSUER_URL`, `GBRAIN_OAUTH_RELAY_URL` / posture-widening `GBRAIN_*`, plus the re-run marker `GBRAIN_CWD_ENV_QUARANTINED`; one why-comment per key, plus the deliberate exclusions and deferrals) PLUS `CWD_DOTENV_PROTECTED_PREFIXES` (`LD_`, `DYLD_`, `GIT_`, `BUN_`, `NPM_CONFIG_`, `npm_config_`, `BASH_FUNC_`) and `CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS` (NODE_OPTIONS/NODE_PATH/CA/TLS, SSH_ASKPASS*, XDG_CONFIG/DATA/CACHE_HOME, GNUPGHOME, SSL_CERT_FILE/DIR, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE, OPENSSL_CONF/ENGINES/MODULES, TMPDIR/TMP/TEMP, HOME/USERPROFILE, the shell-startup / interpreter-home group BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH (sh/ksh `ENV` deliberately excluded: interactive-only and a routine project key), EDITOR/VISUAL/PAGER, PYTHON/PERL/RUBY preload, proxy vars both spellings, CLAUDE_CONFIG_DIR, ANTHROPIC_*/OPENAI/OPENROUTER/LITELLM/OLLAMA/LMSTUDIO/LLAMA_SERVER(_RERANKER)_BASE_URL) — the families a cwd .env could plant for the programs gbrain spawns; a denylist that grows as families are identified. `quarantineCwdDotenv(env = process.env, dir = process.cwd(), { warn, assignments })` iterates the keys the cwd .env files ASSIGN, deletes each protected one present in `env`, prints ONE stderr line (`formatQuarantineWarning`, composed from the exported `CWD_DOTENV_REMEDIATION` that guardrails.ts reuses) naming them sorted, returns them sorted. INVARIANTS: key presence, never value match; the parser accepts every line shape Bun's loader does; in-process only — children spawned without an explicit `env` see Bun's startup snapshot, which is why `cli-preflight.ts` re-runs gbrain from a neutral cwd whenever the list is non-empty; fs/path only, no config import. Pinned by `test/env-trust.test.ts`; the GBRAIN list is guarded against rot by the structural `test/env-trust-protected-keys.test.ts` (every `process.env.GBRAIN_*` / `Bun.env.GBRAIN_*` / `env.GBRAIN_*` read in src/ whose name matches `_BIN|_CLI|_MODULE|_PATH|_HOME|_URL` suffix or `GBRAIN_ALLOW_` prefix must be on the list or carry a `cwd-dotenv-ok: <why>` annotation).+- `src/core/guardrails.ts` — vendor-neutral content guardrail seams (`registerGuardrailProvider`, `classify`). `loadGuardrailProvidersFromEnv(env = process.env, opts?: { cwd, skipCwdCheck })` accepts ONLY an absolute path or a `~/` path for `GBRAIN_GUARDRAILS_MODULE`; cwd-relative specs (`./`, `../`, bare `.`) and bare package specifiers (`pkg`, `@scope/pkg`, `pkg/sub` — in the compiled binary Bun's module walk-up starts at the cwd, so a hostile checkout's `node_modules/<name>/` would load) throw `GuardrailLoadError` before any import, and when `env` is `process.env` (or `opts.cwd` is given) a spec that a cwd .env file assigns is refused via `cwdDotenvAssignsKey` (message composed from env-trust's `CWD_DOTENV_REMEDIATION`) unless `opts.skipCwdCheck` (preflight's cwd == config-dir case). node:path/url/os are static imports. Registration is counted by EVENTS against a pre-import baseline so import-time side-effect registration and same-id replacement are accepted (#3688 residual). Pinned by `test/guardrails.test.ts` + `test/guardrails-env-load.test.ts`.+- `src/core/config.ts` (cwd `.env` boundary) — the #427 cwd-.env parser (`CWD_DOTENV_FILES`, `dotenvValuesForKey`) lives in `env-trust.ts`; config.ts re-exports both (façade rule — `test/config-env-hijack.test.ts` keeps importing from config) and `effectiveEnvDatabaseUrl` / `envShadowDetected` keep VALUE-match semantics for `DATABASE_URL` (a deliberate export equal to the cwd value would have selected the same database anyway; the value guard never touches `GBRAIN_DATABASE_URL` — the key-presence quarantine in env-trust.ts drops that one when a cwd `.env` assigns it). `loadConfig()` calls `loadGbrainEnvFile(getConfigDir)` (`~/.gbrain/.env`, operator-owned, never overrides a shell export) — `cli-preflight.ts` loads the same file earlier so the guardrails loader sees it.- `skills/conventions/brain-routing.md` — agent-facing convention skill documenting the canonical 6-tier source resolution chain (flag → env → dotfile → local_path → brain_default → seed_default) with paste-ready decision tables. Linked from CLAUDE.md's "Two organizational axes" section and from `gbrain sources current`'s hint output.- `test/operations-trust-boundary.test.ts` + `scripts/check-operations-filter-bypass.sh` — operations trust-boundary contract coverage. Pure assertions over all 74 ops (every op has a scope annotation; every mutating op has a non-read scope; `localOnly: true` ops are excluded from `operations.filter(op => !op.localOnly)`; the seven sensitive localOnly ops snapshot-pinned by name) plus targeted handler-invocation guards for the HTTP-callable classes: `submit_job` with `name='shell'` + `ctx.remote=true` MUST reject (shell-job RCE); `search_by_image` with `image_path` + `ctx.remote=true` MUST reject (image leak); and the list-op read-leak class — `find_orphans`/`get_recent_salience`/`find_anomalies`/`find_experts` invoked with `ctx.remote=true` over a seeded `visibility: private` page MUST NOT return its slug/title, with a local positive control proving the assertions non-vacuous, count self-consistency assertions pinning the no-count-oracle posture (both orphan denominators shrink with hidden rows; `excluded` untouched; anomaly `count` mirrors the visible slug list), and a soft-delete re-probe pinning the includeDeleted fail-closed path. `file_upload` and `sync_brain` omitted from handler-invocation tests because they're `localOnly: true` (that path would test an impossible production scenario). The shell guard greps `src/` for any module importing the `operations` value outside the canonical filter site at `src/commands/serve-http.ts` (three import shapes: destructured, aliased, namespace), with an explicit 10-entry allow-list + a literal-string check that `serve-http.ts` still contains `operations.filter(op => !op.localOnly)`. Wired into `bun run verify`. Dynamic sibling: `test/remote-privacy-sweep.test.ts` (next entry) — same doctrine, corpus-seeded, catches leaks in ops neither curated list has heard of yet.- `test/remote-privacy-sweep.test.ts` — registry-driven, corpus-seeded leak detection across the ENTIRE dispatch surface (catches a new remote surface that forgets the world-only filter). Seeds a hermetic PGLite corpus carrying high-entropy PRIVATE sentinels (private page title/body, a private fact, a non-world take, fence-row content — never slugs, which are legitimately echoed in "Page not found" errors and would false-positive on correct behavior) plus WORLD markers as positive controls; enumerates every non-localOnly op from the registry; dispatches each one remote-shaped through `dispatchToolCall` (the exact layer both MCP transports share) in BOTH caller shapes — scalar source-scoped (like stdio) and federated with an auth-array read grant; and asserts no private sentinel appears anywhere in the serialized response envelope: structured fields, rendered text, error messages, and the `_meta.brain_hot_memory` channel alike. Fail-closed maintenance contract: `EXPECTED_OUTCOME`'s key set must be set-equal to the enumerated registry, so a NEW op FAILS the suite until classified (`data` = must prove corpus contact via a WORLD marker / `ok` / `error` — envelope still sentinel-checked / `denied` = publish-gated, must error naming its `mcp.*` gate; plus a `PARAM_FACTORY` entry if it can return corpus data — the failure message prints exactly what to add). A separate arm asserts every `localOnly` op is denied fail-closed over non-stdio transports; `KNOWN_EXPOSED` op-wide exemptions must stay empty absent written justification + review. Phase W covers mutating ops against fresh slugs (destructive ops last, corpus-intact re-checks between phases). Honest scope: covers the dispatch surface for transport-floor callers; does NOT cover the IPC context-pack handler (`src/mcp/context-pack-handler.ts` bypasses `dispatchToolCall`) or write-triggered restoration echoes — the write-side sweep is a filed TODO. Static siblings: `test/operations-trust-boundary.test.ts` (previous entry) + `scripts/check-operations-filter-bypass.sh`.@@ -322,11 +329,11 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/minions/embed-backfill-admission.ts` — Centralized, dependency-light embed-backfill admission contract shared by the public `MinionQueue.add` boundary, CLI, MCP operations, automatic submitters, sync cost reporting, and doctor remediation. `embedBackfillWorkerSurface` recognizes only explicit `postgres` as worker-backed; the declared engine-kind switch is compile-time exhaustive, while untyped/cast unknown runtime values still fail closed as `no_worker_surface`. `assertEmbedBackfillQueueAdmission` refuses before any database/config access unless the explicit PGLite inline-worker trust is present, validates payload source IDs through the canonical `source-id.ts` contract before rendering any remedy, and `embedBackfillManualDrainCommand(sourceId)` is the single injection-safe exact `gbrain embed --stale --source <id>` recovery command.- `src/core/embed-backfill-submit.ts` — Automatic per-source embed-backfill submitter with a true discriminated result union: `submitted` requires `jobId` plus an explicit spend-bypass payload, `cooldown` requires a reason plus a numeric remaining duration or explicit `null` for active work, `spend_capped` requires cap/spend payloads, and `no_worker_surface` requires the refused engine kind. It queries cooldown/spend state only after the shared admission classification accepts a worker-backed engine, preserving Postgres behavior while guaranteeing PGLite/unknown refusal before config, schema, or SQL access; callers handle every status exhaustively.- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`) on the `db_dead` unhealthy payload. `getHandler(name)` is the read-only registry accessor run-child uses.-- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, restarts on crash with exponential backoff, periodic health check. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in tini-as-PID-1 when tini is on `PATH` (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) does not permanently give up: the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment does not read a healthy supervisor as "not running". `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog: `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions. Queue-scoped singleton: the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (mixing in a config-derived DB identity would let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` cannot both run with conflicting `--max-rss`: the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`. `SupervisorOpts.jobIsolation` passes `--job-isolation process` to the spawned worker via a CONDITIONAL `buildWorkerArgs` push (inline argv stays byte-identical). `queryWedgeSignals`/`probeQueueState` thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion).+- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, restarts on crash with exponential backoff, periodic health check. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in tini-as-PID-1 when tini is on `PATH` (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) does not permanently give up: the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment does not read a healthy supervisor as "not running". `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog: `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions. Queue-scoped singleton: the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (mixing in a config-derived DB identity would let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` cannot both run with conflicting `--max-rss`: the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`. `SupervisorOpts.jobIsolation` passes `--job-isolation process` to the spawned worker via a CONDITIONAL `buildWorkerArgs` push (inline argv stays byte-identical). `queryWedgeSignals`/`probeQueueState` thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion). `buildWorkerArgs` also appends `--allow-shell-jobs` when `opts.allowShellJobs` (conditional push like `--job-isolation`, so existing argv stays byte-identical; pinned by `test/supervisor-build-worker-args.test.ts`). Rationale: the worker's startup cwd-.env quarantine drops `GBRAIN_ALLOW_SHELL_JOBS` whenever a .env in the worker's cwd assigns it, so the env copy in `runSuperviseLoop` alone could silently disable shell jobs; `jobs work` parses the flag and re-sets `process.env.GBRAIN_ALLOW_SHELL_JOBS='1'` after preflight (read sites in jobs.ts / handlers/shell.ts unchanged). `allowShellJobs` sets the env var on the child AND pushes `--allow-shell-jobs`.- `src/core/minions/detached-stderr.ts` — durable stderr sink + spawn helper for `gbrain jobs supervisor start --detach`. `openDetachedStderrSink()` opens an append-mode log in the audit dir (`${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/supervisor-stderr.log`, next to the JSONL lifecycle audit), falling back to the null device, then `'ignore'`; never throws (a sink failure must not block the supervisor start). The detached supervisor gets the fd as `stdio[2]` and its worker inherits it, so ONE durable descriptor covers both processes — not a per-call EPIPE swallow. Prevents the SIGPIPE failure of inheriting the INVOKER's stderr: a short-lived automation runner closing its capture pipe after the start payload would make the worker exit 141 on its next stderr write (and could take the supervisor down writing its own crash event), leaving active jobs and DB locks stale while producers keep enqueueing. Pinned by `test/detached-stderr.test.ts`.- `src/core/minions/child-worker-supervisor.ts` — shared spawn-and-respawn core reused by both `MinionSupervisor` (standalone `gbrain jobs supervisor` daemon) and `src/commands/autopilot.ts` (autopilot daemon), so the two consumers can't drift into parallel-loop bugs. Pure class: NO PID file, NO signal handlers, NO `process.exit`, NO health check. Lifecycle events fire via injected `onEvent: (ChildSupervisorEvent) => void`. Exit classifier: `code === 0` leaves `crashCount` UNCHANGED (preserves flap detection across mixed exit sequences); `code != 0` follows `runDuration > stableRunResetMs ? 1 : ++crashCount`. Clean-restart budget: sliding window of code=0 exits; when count exceeds `cleanRestartBudget` (default 10) inside `cleanRestartWindowMs` (default 60s), emits `health_warn { reason: 'clean_restart_budget_exceeded' }` and applies `cleanRestartBudgetBackoffMs` (default 1s). The exit classifier special-cases `WORKER_EXIT_RSS_WATCHDOG` — `likely_cause='rss_watchdog'`, and that exit does NOT bump `crashCount` (routes to its own breaker); a dedicated `_watchdogExitTimestamps` sliding window trips a loud `rss_watchdog_loop` health_warn naming the cap when N watchdog exits land inside the window, INDEPENDENT of the stable-run reset (which would otherwise hide a >5-min-run watchdog drain loop). Opts `watchdogLoopBudget` (3), `watchdogLoopWindowMs` (600000), `watchdogBackoffMs` (30000); `ChildSupervisorEvent` extended. Public read-only accessors `childAlive`, `inBackoff`, `crashCount`; `killChild(signal)` gates on liveness (`exitCode === null && signalCode === null`), NOT `.killed` — `.killed` flips true once a signal is *sent*, so a `!this._child.killed` guard would make a follow-up SIGKILL after an ignored SIGTERM a silent no-op. `restartCurrentChild(graceMs)` (wedge self-heal) captures the CURRENT child ref, SIGTERM→grace→SIGKILLs THAT ref (never the respawn — closes the timer-kills-fresh-worker race), and flags `_intentionalRestart` so the exit is `likelyCause='wedge_restart'`, leaves `crashCount` UNTOUCHED (never trips `max_crashes`; like `rss_watchdog`), and respawns immediately (`backoff ms:0 reason='wedge_restart'`). `awaitChildExit(timeoutMs)` short-circuits when `child.exitCode !== null || child.signalCode !== null` so fast-SIGTERM responders don't cause a 35s shutdown hang. Degraded-retry: the `run()` loop does not fire `onMaxCrashesExceeded` at the soft `maxCrashes`; it announces `health_warn { reason: 'crash_budget_degraded' }` once per episode and keeps respawning with capped backoff (the 60s cap makes it a paced retry, not a hot loop), re-arming after a stable-run reset drops the count. Permanent give-up fires only at `hardStopMaxCrashes` (default `maxCrashes × HARD_STOP_CRASH_MULTIPLIER` = 10×; `0` disables). Test hooks `_backoffFloorMs`, `_now`. `supervisor-audit.ts` carries `rss_watchdog` as a non-clean cause + its own `CrashSummary.by_cause` bucket, and `wedge_restart` to `CLEAN_EXIT_CAUSES` (a self-heal, not a crash; denylist preserved so future causes route to `legacy`). Pinned by `test/child-worker-supervisor.test.ts` (12 cases).- `src/core/minions/spawn-helpers.ts` — pure `detectTini()` + `buildSpawnInvocation()` consumed by both `supervisor.ts` and `autopilot.ts` (one implementation for both spawn sites; tini wrapping is testable without `mock.module()`, rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations. `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with tini prepended when present, or the bare invocation otherwise. Pinned by `test/spawn-helpers.test.ts` (5) and `test/supervisor-tini.test.ts` (4).-- `src/core/minions/job-isolation.ts` — per-job process-isolation protocol: atomic outcome-file codec (`writeChildOutcomeFile` tmp+rename, `decodeChildOutcomeFile` with a 32MiB cap that throws `UnrecoverableError` — oversize results die loudly on attempt 1, decode errors report byte counts never content), `encodeHandlerError`/`reconstructHandlerError` preserving the two `instanceof` classes executeJob branches on (UnrecoverableError, RateLeaseUnavailableError), the child argv/env contract (`CHILD_ENV`, `buildChildArgs`), `resolveChildCliInvocation` (env override → compiled binary → bun-dev fallback → null for fail-fast), and `killProcessGroup(pid, sig)` — children are spawned detached (own group) because SIGKILL on a tini pid alone orphans the handler grandchild, and Bun rejects negative pids in process.kill (oven-sh/bun#15791) so group signaling falls back to POSIX /bin/kill. Pinned by `test/job-isolation-protocol.test.ts` (incl. real-process grandchild-death).+- `src/core/minions/job-isolation.ts` — per-job process-isolation protocol: atomic outcome-file codec (`writeChildOutcomeFile` tmp+rename, `decodeChildOutcomeFile` with a 32MiB cap that throws `UnrecoverableError` — oversize results die loudly on attempt 1, decode errors report byte counts never content), `encodeHandlerError`/`reconstructHandlerError` preserving the two `instanceof` classes executeJob branches on (UnrecoverableError, RateLeaseUnavailableError), the child argv/env contract (`CHILD_ENV`, `buildChildArgs`), `resolveChildCliInvocation` (env override → compiled binary → bun-dev fallback → null for fail-fast), and `killProcessGroup(pid, sig)` — children are spawned detached (own group) because SIGKILL on a tini pid alone orphans the handler grandchild, and Bun rejects negative pids in process.kill (oven-sh/bun#15791) so group signaling falls back to POSIX /bin/kill. Pinned by `test/job-isolation-protocol.test.ts` (incl. real-process grandchild-death). `buildChildArgs(jobId, env = process.env)` appends `--allow-shell-jobs` when `env.GBRAIN_ALLOW_SHELL_JOBS === '1'` (child-job-runner passes its spawning env), because the per-job child re-runs the cwd-.env preflight in the worker's cwd and would otherwise lose the opt-in; `jobs run-child` re-asserts the env from that flag. Pinned by `test/job-isolation-allow-shell-jobs.test.ts`. `child-job-runner.ts` passes `opts.env ?? process.env` as the base env, so `GBRAIN_ALLOW_SHELL_JOBS === '1'` in it appends `--allow-shell-jobs` (any other value does not); pinned by the pass-through case in `test/child-job-runner.test.ts`.- `src/core/minions/child-job-runner.ts` — parent-side runner: `runJobInChild(opts)` spawns the child (detached + tini when available, stdio inherit for handler logs, per-job lifecycle log lines), maps per-job abort → group SIGTERM now + group SIGKILL at +25s (`CHILD_KILL_GRACE_MS`, inside the 30s force-evict backstop), gives worker-shutdown children the drain window to finish AND report (a non-reporting shutdown kill throws `ChildWorkerShutdownError` → released, no attempt burned), classifies pre-exec spawn failure as `ChildSpawnInfraError` (released, no attempt burned), and bounds child pools via env (`GBRAIN_POOL_SIZE` default 3, `GBRAIN_DIRECT_POOL_SIZE=1`). Pinned by `test/child-job-runner.test.ts` (real children) + `test/worker-job-isolation.test.ts` (full parent path on PGLite).- `src/core/minions/run-child.ts` — `runChildJobEntry(engine, opts, injectables)`: the `jobs run-child` core. Re-reads the job row and validates status+token (exit 14 on mismatch, handler never runs), builds the shared token-fenced context against the CHILD's engine, runs the handler, writes ONE atomic outcome file (handler failure = reported outcome = exit 0; only write-failure exits 15). Installs a SIGTERM→shutdownSignal-ONLY handler (inline signal-separation parity: ctx.signal stays live so cooperative handlers finish + report inside the drain window; the parent's group SIGKILL at drain end is the backstop) and a parent-liveness watchdog polling `process.kill(parentPid, 0)` (ppid checks are dead code under tini) that aborts BOTH signals on parent death with a hard exit after grace. No worker machinery (parent owns liveness). Pinned by `test/run-child-entry.test.ts`.- `src/core/minions/job-context.ts` — shared `buildJobContext(engine, queue, job, lockToken, signal, shutdownSignal)` (extracted verbatim from executeJob) so inline mode and the run-child child wire identical token-fenced DB callbacks.@@ -339,10 +346,10 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/minions/types.ts` — `MinionJobInput` + `MinionJobStatus` + handler context types. `MinionJobInput.max_stalled` is optional; omitted values let the schema DEFAULT (5) kick in, provided values are clamped to `[1, 100]`. `SubagentHandlerData.require_writes` requires at least one settled successful page write, not merely a clean model finish.- `src/core/minions/errors.ts` — dependency-free `UnrecoverableError`, re-exported through `types.ts` for compatibility. Delegated policy imports this leaf directly, avoiding initialization cycles through durable authority. Fresh-process import tests preserve the shared error identity and isolated-worker reconstruction.- `src/core/minions/protected-names.ts` — side-effect-free constant module exporting `PROTECTED_JOB_NAMES` + `isProtectedJobName()`. Kept pure so queue core can import without loading handler modules. `PROTECTED_JOB_NAMES` includes `synthesize`, `patterns`, `consolidate`. These phases internally submit `subagent` children with `allowProtectedSubmit=true` and can spend Anthropic credits. Only trusted local callers (CLI, autopilot, `doctor --remediate`) can submit them; MCP requests are rejected by `submit_job`'s protected-name guard.-- `src/core/minions/handlers/shell.ts` — `shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides + `inherit:`-resolved keys. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Requires `GBRAIN_ALLOW_SHELL_JOBS=1` on worker (gated by `registerBuiltinHandlers`). `ShellJobParams.inherit?: string[]` is a free-form list of snake_case config-key names; the worker resolves each via `loadConfig()` and injects the value under the derived env key (`database_url` → `GBRAIN_DATABASE_URL`; else uppercased). Names persist in `minion_jobs.data` (and the shell-audit JSONL); values never do. The canonical validator `validateShellJobParams` (sibling `shell-validate.ts`) runs PRE-ENQUEUE in both submit surfaces — `gbrain jobs submit shell` (jobs.ts:271) AND the `submit_job` op for `name='shell'` (operations.ts:2085); the handler-entry re-validation here is defense-in-depth (so validation can never run only AFTER `queue.add()` has persisted the row). The validator does NOT police which config keys the agent inherits — same-uid trust model treats the agent as a peer of the worker.+- `src/core/minions/handlers/shell.ts` — `shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides + `inherit:`-resolved keys. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Always registered (`registerBuiltinHandlers`) and self-gated: unless `GBRAIN_ALLOW_SHELL_JOBS === '1'` in the worker env — set by `gbrain jobs work --allow-shell-jobs` after the cwd-`.env` preflight, or exported from the operator's shell (a cwd `.env` cannot set it: `env-trust.ts`) — a claimed job throws `UnrecoverableError` naming `--allow-shell-jobs` (dead-letter, no retries). `ShellJobParams.inherit?: string[]` is a free-form list of snake_case config-key names; the worker resolves each via `loadConfig()` and injects the value under the derived env key (`database_url` → `GBRAIN_DATABASE_URL`; else uppercased). Names persist in `minion_jobs.data` (and the shell-audit JSONL); values never do. The canonical validator `validateShellJobParams` (sibling `shell-validate.ts`) runs PRE-ENQUEUE in both submit surfaces — `gbrain jobs submit shell` (jobs.ts:271) AND the `submit_job` op for `name='shell'` (operations.ts:2085); the handler-entry re-validation here is defense-in-depth (so validation can never run only AFTER `queue.add()` has persisted the row). The validator does NOT police which config keys the agent inherits — same-uid trust model treats the agent as a peer of the worker.- `src/core/minions/handlers/shell-inherit.ts` — three helpers. `INHERIT_NAME_RE` (`/^[a-z][a-z0-9_]*$/`) is the snake_case shape guard used by the validator; rejects `__proto__`, leading-underscore, uppercase, and path-traversal shapes so audit logs stay readable and prototype-pollution lookups can't smuggle through. `deriveEnvKey(name)` maps config-key → child-env-key (`name.toUpperCase()` with one override: `database_url` → `GBRAIN_DATABASE_URL` because plain `DATABASE_URL` is ambiguous). `resolveInheritValue(cfg, name)` is the value lookup; uses `Object.hasOwn` to defeat prototype-pollution lookups, returns undefined for missing / non-string / empty-string values. No closed enum — agent and worker share a uid, so refusing arbitrary config keys defends nothing in that trust model.- `src/core/minions/handlers/shell-validate.ts` — `validateShellJobParams(data, opts?)` shared pre-enqueue validator. Throws `UnrecoverableError` with paste-ready operator hints on every failure. Three rules: (1) cmd/argv/cwd/env shape, (2) inherit array shape + snake_case regex per element (prototype-pollution defense), (3) fail-fast on missing config value with `gbrain config set <key>` hint. Optional `redact_secrets?: boolean` for output-side scrubbing. Deliberately does NOT police WHICH secrets the agent passes — single-uid trust model. Test seam: `opts.config` drives the validator hermetically without mocking. Re-called at `shell.ts` handler entry for defense-in-depth (catches rows that bypassed the pre-enqueue validator).-- `src/core/minions/handlers/shell-redact.ts` — opt-in output-side scrubbing for shell-job stdout/stderr. Pure `redactSecretsInText(text, secrets)`: string-mode `replaceAll` so regex metacharacters in values stay literal. When the caller passes `redact_secrets: true` (or `--redact-secrets`), the handler builds a Map of inherit-name → resolved-value and post-processes both tails before throw/return so persisted `result.stdout_tail` / `result.stderr_tail` / `error_text` carry `<REDACTED:name>`. Only `inherit:`-resolved values are scrubbed; caller-supplied `env:` values pass through. Heuristic — defeats `echo "$GBRAIN_DATABASE_URL"`, not adversarial encode-then-print. Default `false`.+- `src/core/minions/handlers/shell-redact.ts` — opt-in output-side scrubbing for shell-job stdout/stderr. Pure `redactSecretsInText(text, secrets)` where `secrets` is any ordered iterable of `[name, value]` pairs (both production callers — the shell handler and `brain-repo-durability.ts`'s PAT scrub — pass a Map; an array is accepted so two values can share a pattern name): string-mode `replaceAll` so regex metacharacters in values stay literal, applied in iteration order — when one value is a substring of another the longer one must come first. When the caller passes `redact_secrets: true` (or `--redact-secrets`), the handler builds a Map of inherit-name → resolved-value and post-processes both tails before throw/return so persisted `result.stdout_tail` / `result.stderr_tail` / `error_text` carry `<REDACTED:name>`. Only `inherit:`-resolved values are scrubbed; caller-supplied `env:` values pass through. Heuristic — defeats `echo "$GBRAIN_DATABASE_URL"`, not adversarial encode-then-print. Default `false`.- `src/core/config.ts:ensureGitignore` — idempotent retroactive writer of `~/.gbrain/.gitignore` (single line `*`). Called from `saveConfig()` so every config-writing path lays it down, AND from `runPostUpgrade()` so existing users pick it up on `gbrain upgrade`. Never clobbers a user-customized `.gitignore` (checks file exists + content non-empty before writing). Scope: blocks casual `git add ~/.gbrain` from inside an enclosing worktree, but does NOT cover already-tracked files, screenshots, backups (Time Machine / iCloud / Dropbox), or `git add -f`. The doctor check `home_dir_in_worktree` surfaces what `.gitignore` can't.- `src/core/minions/handlers/shell-audit.ts` — per-submission JSONL audit trail at `~/.gbrain/audit/shell-jobs-YYYY-Www.jsonl` (ISO-week rotation; override via `GBRAIN_AUDIT_DIR`). Best-effort: `mkdirSync(recursive)` + `appendFileSync`; failures logged to stderr, submission not blocked. Logs cmd (first 80 chars) or argv (JSON array). Never logs env values.- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown'`). Single shared point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.@@ -378,7 +385,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/agent.ts` — `gbrain agent run|logs|register` dispatcher. `run` submits `subagent` (or N children + 1 aggregator) under `{allowProtectedSubmit: true}`; single-entry `--fanout-manifest` short-circuits; children get `on_child_fail: 'continue'` + `max_stalled: 3`; `--follow` is the default on TTY (streams logs + polls `waitForCompletion` in parallel; Ctrl-C detaches, does not cancel). `logs` delegates to `agent-logs.ts`; `register` lazy-imports `agent-register.ts`. Subcommand-aware help is answered BEFORE any engine or queue work and STOPS at the `--` terminator (`agent run -- --help` submits the LITERAL prompt); on a brainless machine (null engine) help still prints while real `run`/`logs` invocations refuse with an init hint.- `src/commands/agent-logs.ts` — `gbrain agent logs <job> [--follow] [--since]`. Merges JSONL heartbeat audit + `subagent_messages` into a chronological timeline. `parseSince` accepts ISO-8601 or relative (`5m`, `1h`, `2d`). Transcript tail renders only for terminal jobs.- `src/commands/agent-register.ts` — `gbrain agent register <name> --harness claude-code|codex|opencode|openclaw`: mints a scoped OAuth client + access token and prints the exact harness wiring in one step (CLI-only, never an MCP op). Composes existing parts — `registerScopedClient` (auth.ts), `exchangeClientCredentials`, the mcp-registration argv builders, `renderCodexHttpServerBlock`, `openclawThinClientBlock` — no new auth machinery. Order is load-bearing: cli.ts pre-connect guards (thin-client refusal + PGLite live-serve probe) → pure parse (exit 2) → preset resolve → source validation (existence + not-archived, engine lane `ANY($1::text[])`) → column pre-flight OUTSIDE any tx (25P02 forbids in-tx degrade) → ONE `engine.transaction` (name-scoped `pg_advisory_xact_lock` → duplicate-name pre-check → `ensureWorkspaceSource` create-or-reuse-only-when-truly-empty (refuses page-, fact-, or file-bearing and archived sources) → `registerScopedClient` with ttl + surface) → COMMIT → post-commit fail-open surface audit → token exchange on the OUTER engine (the tx sql is dead) → serve probe (`probeServeHealth` + the unconditional `SCOPES_MIN_SERVE_VERSION` floor line): a probe-PROVEN pre-scopes serve REFUSES registration (`serve_too_old`) unless `--allow-old-serve` — such a serve verifies scoped tokens as full access; an unreachable serve stays a warning, and the reissue lane warns instead of refusing (the secret is already rotated by that point) → render + print (human, or ONE JSON doc carrying `probe_note` + `serve_warning` from the probe; secrets redacted unless `--show-token`). Presets: `daily-driver` (write one source; federated reads = SNAPSHOT of non-archived sources at registration, EXCLUDING other agents' `*-workspace` scratch sources — a workspace named explicitly in `--federated-read` is still granted, and the print counts the exclusions) and `coding-agent` (write-isolated derived `<name>-workspace` DB-only source; requires `--federated-read`); both default the client to the `starter` surface — override with `--surface` at registration or widen per client via `gbrain auth rescope-client`. Always writes `token_ttl` (default 30 days — the server default is 1 hour and would kill a pasted config). `--url|--port` required (every block embeds the brain URL). A scope blocklist keeps operator-grade scopes on `auth register-client`. `--reissue <client-id>` rotates the secret under the same advisory lock and reprints the block (headed by the stored client_name); rotation is not revocation — outstanding tokens live until expiry. Failure after COMMIT prints the client_id + the exact revoke command (never a false "nothing was created"). openclaw renders the honest thin-client CLI block (no native remote-MCP client upstream yet). Pinned by `test/agent-register.test.ts`.-- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status` consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `case 'work'` resolves + fail-fast validates the child CLI invocation and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `case 'run-child'` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes.+- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status` consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `case 'work'` resolves + fail-fast validates the child CLI invocation and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `case 'run-child'` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check.- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and `maxCrashes: 5`. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (a stale lock from a crashed process does not block). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution).- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract. It is compile-time source text (no runtime filesystem dependency; static imports of pure core leaves are fine — the rule bans filesystem/dynamic loading) and is imported by the stdio SDK server, OAuth HTTP SDK server, and legacy raw HTTP initialize path so all transports return the same instructions without drift. The contract covers skill routing, untrusted-content posture, source scope, and the `put_page` whole-page replacement/read-before-write rule. Two append-only extensions compose on top of it, in a fixed order: `buildMcpInstructions({writeback?})` adds the opt-in ambient-writeback section (from `src/core/facts/writeback-instructions.ts`) when `memory.auto_writeback` is enabled — absent/off is BYTE-IDENTICAL to `GBRAIN_MCP_INSTRUCTIONS`, and three exact-equality transport pins depend on that; `resolveMcpInstructions(config, env?, { writeback? })` takes that composed base and appends the operator-set deployment identity LAST under a `Deployment identity:` banner (no transport can weaken the contract): `GBRAIN_MCP_INSTRUCTIONS` env wins when non-blank, else `mcp.instructions` from the FILE plane (`~/.gbrain/config.json`; `gbrain config set|unset mcp.instructions` route there via `FILE_PLANE_DOTTED_KEYS` in `src/commands/config.ts`); an empty or whitespace-only env value is UNSET, not an override, and blank identity + writeback off returns the byte-identical canonical contract. Every transport calls `resolveMcpInstructions` with its own writeback opts: stdio once at boot via the fail-closed resolver (restart-to-flip, the strict-params posture; read failure = OFF bundle, never a wrong visibility posture; a running `gbrain serve` also needs a restart to pick up a new identity); OAuth per request (write-scope-gated, and the section renders only when THIS token's actual visible set — surface filter + bound-client fence — can call `remember`; `extract_facts` advertised under the same predicates); legacy bearer per initialize (surface-clamped: a surface without `remember` gets no section). All three route availability through `ambientOptsFrom(wb, {remember, extractFacts})`. Pinned over a real SDK `StdioClientTransport` by `test/e2e/serve-stdio-roundtrip.test.ts`, over raw HTTP by `test/http-transport.test.ts`, the identity plane (incl. the three-way composition order) by `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`, and the enabled-state builder/parity matrix by `test/mcp-instructions-writeback.test.ts`.@@ -393,10 +400,12 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/mcp-usage.ts` — `readClientOpUsage(engine, {days})`: the ONE shared reader over `mcp_request_log`, consumed by `gbrain auth clients --usage`, the advisor `mcp-client-fit` collector, and `scripts/derive-starter-ops.ts`. Encodes the row-hygiene rules once (`normalizeLoggedOperation`): JSON-RPC method rows (`tools/list`, `initialize`, …) and `surface_change` audit rows drop; the legacy `tools/call:<name>` prefix strips to the op name, and the hygiene check re-runs on the stripped name (`tools/call:tools/list` is still not an op call). Only `status IN ('success','success_with_warnings')` rows count as usage — denied or erroring traffic cannot "use" its way into starter derivation or advisor fit findings. Windows on `created_at` (rides `idx_mcp_log_time_agent`); plain SQL through `engine.executeRaw`, both engines. Behavioral automation classification: `likely_automation` = >90% of calls are `context_pack`/`delta` boundary verbs (the hook lane is stdio and never logs, so there is no name convention to key on). Sees HTTP clients ONLY — stdio never writes the log. Pinned by test/mcp-usage.test.ts.- `docs/protocol/MCP_META_CHANNELS.md` — normative `_meta` conventions for MCP tool responses: one producer per top-level key, additive-forever within a key, producer isolation, and the registered-keys table (`brain_hot_memory`, `retrieval`, `warnings`). Anything the model must SEE rides a content block (mainstream harnesses don't feed `_meta` to the model); `_meta` serves structured consumers. Add a key by registering it in the table — one producer, additive-forever.- `src/mcp/rate-limit.ts` — Bounded-LRU token-bucket limiter. `buildDefaultLimiters()` returns the two-bucket pipeline: pre-auth IP (30/60s, fires BEFORE the DB lookup so brute-force load against `access_tokens` is capped) + post-auth token-id (60/60s). Tracks `lastTouchedMs` separately from `lastRefillMs` so an exhausted key can't be reset by hammering past the TTL. LRU cap bounds memory under attacker-controlled key growth. `refund(key)` returns one consumed token (capped at the limit) — the `request_tools` persist path refunds when a race-lost 0-row UPDATE (concurrent operator pin) means no write actually happened; dry-run previews never draw a token at all (the limiter meters actual writes only).-- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. Discovery omits operator-only `agent` scope while DCR still rejects explicit delegation. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS). Shutdown: `waitForHttpServerLifecycle` tracks accepted sockets weakly (`trackServerSockets`; Bun never emits socket `close`, so a strong set leaked one per request), severs the still-reachable ones right after `server.close()`, and bounds the close wait at `CLOSE_TIMEOUT_MS` (5s) — a collected keep-alive wrapper whose native handle keeps `close()` from returning gets one stderr line and shutdown proceeds instead of hanging.+- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. OAuth discovery's `scopes_supported` (RFC 8414 AS metadata and both RFC 9728 protected-resource documents, one value through the SDK router) comes from `scopesSupportedForDiscovery({ enableDcr })` in `src/core/scope.ts`: with `--enable-dcr` it is exactly the self-registration ceiling (`read write`), so a client that copies discovery into its `/register` request succeeds; without DCR it is every scope except operator-only `agent`. The DCR ceiling still rejects an explicit privileged request, and operator-registered clients are never narrowed by the advertisement. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and per-IP `express-rate-limit` buckets: the MCP SDK's defaults on `/authorize` (100 / 15 min), `/register` (20 / hour) and `/token` (50 / 15 min) because `authRouterOptions` passes no `rateLimit: false`, the custom `client_credentials` handler's `ccRateLimiter`, and the shared 10 / min `adminAuthRateLimiter` on `/admin/login`, `/admin/api/issue-magic-link`, `/admin/auth/:token` and the authenticated consent GET/POST. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS). Shutdown: `waitForHttpServerLifecycle` tracks accepted sockets weakly (`trackServerSockets`; Bun never emits socket `close`, so a strong set leaked one per request), severs the still-reachable ones right after `server.close()`, and bounds the close wait at `CLOSE_TIMEOUT_MS` (5s) — a collected keep-alive wrapper whose native handle keeps `close()` from returning gets one stderr line and shutdown proceeds instead of hanging. DCR startup copy: the SECURITY WARNING states self-registered clients are limited to read/write (read-only for `client_credentials` under `--enable-dcr-insecure`) and that every authorization_code connection needs owner approval in the admin UI; banner `DCR:` values are `enabled (consent; DCR max read write)` / `enabled (INSECURE: read-only M2M)` / `disabled`.+- `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/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Also exports `FILES_METADATA_MERGE_SQL`, the one `ON CONFLICT (storage_path)` merge fragment every files upsert (`src/commands/files.ts` x4, `src/core/ops/files.ts` `file_upload`) interpolates: it resets a non-object `files.metadata` to `{}` before the jsonb `||` merge, because `||` array-wraps a non-object left operand and would turn a legacy string-scalar row into `["{}", {...}]` that `gbrain repair-jsonb` can no longer see (pinned by `test/file-upload-fail-closed.test.ts`). Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases).-- `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 threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `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`).+- `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 threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `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/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`.- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).- `src/commands/serve-http-grants.ts` + `admin/src/components/ClientGrant.tsx` — typed admin grant request validation and shared profile/advanced permission editor. Register/rescope/TTL routes in `serve-http.ts` use canonical grant validation and audit; legacy response shapes remain available. New UI creation defaults to memory-writer and requires a preview, while edits carry the displayed revision and require a fresh preview after any field change or conflict. Detail/catalog endpoints expose non-secret grants and the shared harness registry. Operation authority snapshots, source sets, delegated tools/namespaces, spend, concurrency, and future TTL are independently reviewable; profile regrant is explicit. `admin/src/pages/Agents.tsx` downloads the private `HarnessCredentials` handoff and links current harness guides instead of maintaining native config snippets. Rebuild committed `admin/dist` and `src/admin-embedded.ts` after SPA edits.- `admin/` — React 19 + Vite + TypeScript admin SPA embedded in the binary via `admin/dist/` served by `serve-http.ts`. 7 screens: Login (bootstrap token → session cookie), Dashboard (metrics + SSE feed + token health), Agents (sortable table + sparklines + Register), Register (modal with scope checkboxes + grant type selector), Credentials reveal (Copy + Download JSON + one-time-only warning), Request Log (filterable paginated), Agent Detail drawer (Details / Activity / Config Export tabs + Revoke). Design tokens: `#0a0a0f` bg, Inter for UI, JetBrains Mono for data, 4-32px spacing scale, rounded pill badges. HTTP-only SameSite=Strict cookie auth. 65KB gzip. Build: `cd admin && bun install && bun run build`; output at `admin/dist/` is committed for self-contained binaries.@@ -415,7 +424,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `test/fixtures/whoknows-eval.jsonl` — 10-row synthetic placeholder demonstrating the eval-fixture schema (`{query, expected_top_3_slugs, notes?}` JSONL). End users replace with their own real queries; placeholder uses obviously-example slugs (`wiki/people/example-alice`). Drives `test/e2e/whoknows.test.ts` (seeds a matching synthetic brain, asserts the >=80% gate) and the `whoknows_health` doctor check.- `src/core/skillopt/` + `src/commands/skillopt.ts` + `skills/skill-optimizer/` — self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904). `gbrain skillopt <skill>` treats `SKILL.md` as trainable parameters of a frozen agent: validation-gated (median-of-3 + epsilon=0.05), budget-capped (preflight estimator), per-skill DB-locked (`tryAcquireDbLock('skillopt:<name>', 60min)`), atomic-versioned (history-intent-first 5-step commit), body-only mutations (frontmatter forbidden). Rollouts use `gateway.toolLoop` directly with no-op persistence callbacks (zero `subagent_messages` pollution) + a read-only tool allowlist derived from `BRAIN_TOOL_ALLOWLIST` minus `put_page`/`submit_job`/`file_upload`. Two reflect calls per step; rejected-edit buffer LRU-bounded to 100; bundled-skill gate; bootstrap workflow (sentinel + `--bootstrap-reviewed`); D_sel floor (>=5 with `--split` override); audit JSONL via `audit-writer.ts`. Added to `ALL_PHASES` after `patterns` (default OFF; opt-in via `gbrain config set cycle.skillopt.enabled true`); cycle phase wrapper at `src/core/skillopt/cycle-phase.ts` walks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added to `PROTECTED_JOB_NAMES`. Surface: dream-cycle phase wrapper; `--all` batch mode (`src/core/skillopt/batch.ts:runBatchAll`); `--target-models` fleet (`runFleet` parallel per-model receipts under `skillopt/fleet/<slug>/`); MCP op `run_skillopt` (admin scope + per-skill `skillopt.allowed_skills` allowlist, NOT localOnly, validates `skill_name` kebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minion `skillopt` handler + `--background` with `allowProtectedSubmit: true`; write-flavored optimization via `src/core/skillopt/write-capture.ts:buildWriteCaptureRegistry` (virtual `put_page`/`submit_job`/`file_upload` captured in-memory; `--write-capture` flag); held-out real-user test set via `src/core/skillopt/held-out.ts` (capture infra at `~/.gbrain/skillopt-captures/<skill>/<run>.jsonl`, `--held-out <path>` flag, `runHeldOutGate` candidate >= baseline). Hermetic via DI seams (`opts.chatFn` for optimizer + judge; `opts.toolLoopFn` for rollouts; no `mock.module`). `--bootstrap-from-skill` → `runBootstrapFromSkill` in `src/core/skillopt/bootstrap-benchmark.ts`: reads `SKILL.md` directly (no `routing-eval.jsonl`), makes ONE LLM call emitting a full starter benchmark (tasks + rule judges) as JSONL, parsed line-by-line with skip-bad-line salvage and a min-2-valid-checks-per-task drop; provider/transport errors PROPAGATE (not collapsed to `bootstrap_empty`). `--bootstrap-tasks N` (default 15, capped 50); `maxTokens` scales `min(8000, max(4000, N*220))`. The stderr REVIEW line prints the literal `gbrain skillopt <name> --bootstrap-reviewed --split 1:1:1` — load-bearing because the default `4:1:5` split makes a 15-task starter's `D_sel = floor(15/10) = 1`, below the `>=5` floor, so a 15-task benchmark needs `--split 1:1:1`. Both bootstrap generators share `assertBenchmarkAbsent` + `readSkillBodyOrThrow`; `--bootstrap-from-skill` is mutually exclusive with `--bootstrap-from-routing`/`--benchmark`/`--all`/`--target-models`/`--resume`. Generated rule judges are explicitly WEAK DRAFTS to be strengthened during the review gate. The held-out gate is wired: `--held-out <path>` is parsed and threaded through every caller (CLI main + `--background` `held_out_path` + batch/fleet `heldOutPath` + the `run_skillopt` `held_out_path` param), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate. `assertBundledMutationHeldOut` in bundled-skill-gate.ts: bundled + `--allow-mutate-bundled` requires a NON-EMPTY held-out (`MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE` = 5, derived so they can't desync) or hard-refuses (exit 2), for ALL callers (they funnel through `runSkillOpt`); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting). `receipt.baseline_sel_score` populated + a real final-test eval (`test_score` + `baseline_test_score`) scoring best + baseline on `split.test`; shared `scoreSkillOnTasks` primitive (validate-gate.ts) backs baseline/final-test/held-out scoring. `--no-mutate` writes proposed.md via `writeProposed` in version-store.ts. `maxRuntimeMin` ENFORCED (wall-clock deadline between steps → `skillopt_runtime_exceeded` → outcome aborted). Three eval-internal ablation opts on `SkillOptOpts` (NOT on CLI): `reflectMode` (`'both'`/`'failure-only'`), `disableValidationGate` (greedy-accept), `optimizerMode` (`'reflect'`/`'one-shot-rewrite'`), recorded in `RunReceipt` + audit `run_start` for replayability; `ROLLOUT_SUCCESS_THRESHOLD = 0.5` named constant for the partition; one-shot fence-strip is anchored (`^```...```$`) so an embedded code sample isn't truncated. Claude Haiku 4.5's dateless canonical id `claude-haiku-4-5` is in `src/core/anthropic-pricing.ts` (a `BudgetTracker`-capped run on Haiku would otherwise throw `no_pricing` on the FIRST `chat()` of every rollout); `runValidationGate` (validate-gate.ts) scans settled results for `isMustAbortError(error)` (from `worker-pool.ts`; `BUDGET_EXHAUSTED` is in `MUST_ABORT_ERROR_TAGS`) and re-throws so the caller aborts loudly instead of recording a hollow `selScore:0` — ordinary non-abort rollout errors still fail-open to `score:0` (judge-hiccup posture preserved), but a 100%-failed gate (every task errored — e.g. a logged-out `claude-cli` child — or every rollout carrying a `judge_error`) throws `skillopt_all_rollouts_failed` / `skillopt_all_judge_errors` (constants exported from validate-gate.ts) so a dead provider ends the run `errored` with the first provider message as `abort_detail` instead of a plausible `no_improvement` at 0.000; the orchestrator's zero-candidate step (reflect produced/parsed no edits) logs audit reason `no_edits_proposed[: <first reflect error>]` + one stderr line, distinct from the apply-rejected `no_edits_applied`, and does not touch the rejected buffer. `GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG=1` (empty config dir) logs the child out on every platform, macOS included — docs/comment make no keychain-survives claim (pinned by `test/skillopt/deadline-and-hermetic.test.ts`). Pinned by 152 tests across 18 files (foundation + adversarial + v2 surface + E2E PGLite serial), `test/skillopt/bootstrap-from-skill.test.ts` (20 cases), `test/skillopt/rollout.test.ts`, `test/skillopt/validate-gate-abort.test.ts` (7 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (held-out block/allow, bundled no-mutate, runtime deadline, receipt honesty, held-out disjointness, no-DB-pollution). Drives the Track B SkillOpt benchmark suite in the sibling `gbrain-evals` repo.- `src/core/brainstorm/{domain-bank,orchestrator,judges}.ts` + `src/commands/{brainstorm,lsd,eval-brainstorm}.ts` + `src/core/last-retrieved.ts` — bisociation-grounded idea generation pair: `gbrain brainstorm <question>` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd <question>` (Lateral Synaptic Drift — inverted judge rejecting ideas with resistance >4.5 "too obvious", stale-page bias via `pages.last_retrieved_at`, 2 close × 12 far, axiomatic inversions required, ephemeral by default). The "domain bank" is prefix-stratified sampling from the user's own brain (`SELECT DISTINCT substring(slug from '^[^/]+/[^/]+')` cached 1h-TTL in `config` per source) tiebroken by `JOIN page_links` connection_count, with corpus-sampling fallback when fewer prefixes than M exist. Distance normalized to [0,1] via `1 - clamp(cosine_distance, 0, 2) / 2`. `judges.ts` exports `runJudge(config, ideas)` + two configs (`BRAINSTORM_JUDGE_CONFIG` weighted originality/resistance/thesis_density/concrete_grounding/cognitive_load 0.25/0.20/0.20/0.20/0.15 vs `LSD_JUDGE_CONFIG` cognitive_load 0.50 + inversion rule). Calibration cold-start fallback: when `calibration_profiles.active_bias_tags` is empty, judge runs without anti-bias context AND stderr-warns. Op-layer write-back in `src/core/operations.ts` `search`/`query`/`get_page` handlers fires `bumpLastRetrievedAt(engine, pageIds)` (fire-and-forget, 5-min throttled via SQL clause, default-on with `search.track_retrieval` config escape hatch); internal callers (sync, migrations, dream cycle) bypass the op layer so the LSD stale signal stays clean. The fire-and-forget IIFE is tracked in a module-scoped `Set<Promise<unknown>>`; `awaitPendingLastRetrievedWrites(timeoutMs?: number): Promise<{outcome, pending}>` resolves once all tracked promises settle, bounded by a 5s `Promise.race` timeout that stderr-warns the pending count. `src/cli.ts` awaits the drain unconditionally for every op in the op-dispatch finally block BEFORE `engine.disconnect()`, then a fallback `process.exit(0)` fires ONLY when `outcome === 'timeout'` AND `shouldForceExitAfterMain(argv)` (excludes `serve` so daemons stay alive) — so the IIFE cannot race disconnect and leave PGLite's WASM keeping Bun's event loop alive. `pages.last_retrieved_at TIMESTAMPTZ NULL` has a full (NOT partial) B-tree index covering both NULL and range branches; full forward-reference bootstrap probe on both engines. Frontmatter `mode: lsd` makes the dream-cycle synthesize phase skip LSD output via `isLsdOutput()` in `src/core/cycle/transcript-discovery.ts` short-circuiting `isDreamOutput()`. `gbrain eval brainstorm <fixture.jsonl>` is a three-axis conjunctive gate (distance + usefulness + grounding — distance alone is gameable). `gbrain doctor` has a `brainstorm_health` check (migration applied, `search.track_retrieval` setting, calibration cold-start status). `judges.ts` computes the judge token budget via `computeJudgeMaxTokens(ideaCount, modelId)` (named constants `TOKEN_BUDGET_PER_IDEA`, `TOKEN_BUDGET_ENVELOPE`, `LEGACY_MIN_MAX_TOKENS`, `MAX_OUTPUT_TOKENS_CEIL`; `ANTHROPIC_OUTPUT_CAPS` map: Opus 4.7 32K, Sonnet 4.6 / Haiku 4.5 64K, legacy Claude 3.5 8K) so a large multi-call judge doesn't truncate mid-JSON; with no `modelOverride` the cap routes through the gateway's actual configured chat model via `getChatModel()`. `--save` for both commands persists through the canonical ingestion path: `persistSavedIdea(engine, {slug, content, provenanceVia})` calls `importFromContent({noEmbed:true, sourcePath})` (chunked + tagged + content_hash so search finds it, no embedding cost at save) THEN renders the saved row to disk via the shared `writePageThrough` helper (file rendered FROM the row so the two sinks can't diverge and `gbrain sync` doesn't churn it). `formatSaveOutcome(outcome, ctx)` returns an honest per-branch message (both-sinks, DB-only when no `sync.repo_path`/repo-not-a-dir, DB-saved-but-file-errored, total-failure → loud `save FAILED … NOT persisted` on stderr + nonzero exit) — `--save` never prints "Saved" when the DB write failed. `buildIdeaSlug(question, label, nonce?)` adds a random nonce suffix (injectable for tests) so two same-day runs sharing the first 60 slug chars don't clobber. `--json` callers stay DB-only. `buildBrainstormFrontmatterObject(result)` in orchestrator.ts returns the object form for `serializeMarkdown`. Pinned by `test/last-retrieved.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts` (IRON-RULE: real `bun src/cli.ts` subprocess against a hermetic PGLite tempdir asserts search/get/query exit 0 in <15s + daemon-survival), `test/fix-wave-structural.test.ts` (asserts the drain `await` is textually BEFORE `engine.disconnect`), `test/brainstorm/{distance,lsd-mode-skip,eval-brainstorm,judges-maxtokens,save}.test.ts`. Open Collider source: `github.com/CL-ML/open-collider`.-- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId)` is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained `file://` `source_uri`) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention (GIT-ROOT-relative when the scan root sits inside a git repo, so a subdirectory-scoped `local_path` binds the same form delete-reconcile keys on; scan-root-relative otherwise). The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision', warning?, error? }` so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.serial.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.serial.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.+- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained `file://` `source_uri`) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention (GIT-ROOT-relative when the scan root sits inside a git repo, so a subdirectory-scoped `local_path` binds the same form delete-reconcile keys on; scan-root-relative otherwise). The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering FROM the row means file and row cannot diverge. ATOMIC: writes to a unique temp sibling (`<file>.tmp.<pid>.<rand>`) + `renameSync`, cleaning up temp on any failure, so a crash or concurrent `gbrain sync`/autopilot walking the live git tree never reads a half-written `.md` (matches the `.tmp + rename` convention in import-checkpoint.ts / op-checkpoint.ts). After a successful rename, a row whose `source_path` is still NULL is immediately bound to `sourcePathToBind` (pages born via put/capture/reverse-write otherwise stay `source_path=NULL` forever because mtime-watermark incremental sync never rescans an untouched file); NULL-guarded so a scanner-recorded path is never rewritten, best-effort so a failed bind never fails the write. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision', warning?, error? }` so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.serial.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.serial.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error`, deleting a just-created row first so "created" is never answered for a page with no file backing.- `src/core/model-id.ts` — `splitProviderModelId(input: string | null | undefined): {provider: string | null, model: string}` shared parser for the pricing side. Splits on `:` first, then `/`. Defensive contract: null/undefined/empty/whitespace returns `{provider: null, model: ''}`. Five sites consume it (`src/core/anthropic-pricing.ts:estimateMaxCostUsd`, `src/core/budget/budget-tracker.ts:lookupPricing`, `src/core/eval-contradictions/cost-tracker.ts:pricingFor`, `src/core/minions/batch-projection.ts` at two call sites, `src/core/model-config.ts:isAnthropicProvider`) so the pricing + classification surface has no parallel re-implementations of `provider:model` splitting — slash-form ids (`anthropic/claude-sonnet-4-6`) classify correctly instead of falling through to "unknown model". Distinct from the gateway-side `parseModelId` in `src/core/ai/model-resolver.ts`, which throws on bare names because routing needs an explicit provider; this one returns `{provider: null, model: 'bare'}` because pricing lookups happen against bare model ids. Pinned by `test/model-id.test.ts`.- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first read; local engine or thin-client). Entity→text fallback: a bare positional is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read) the query retries as the SQL-level fact-text grep with a one-line stderr note — so keyless/casual usage (`gbrain recall coffee`) finds the fact either way. One gating predicate + one note formatter (`entityTextFallbackApplies`/`noteEntityTextFallback`) shared by the local path and the thin-client mirror so the two can't drift; explicit `--grep` callers keep exact semantics (their filter already ran, no fallback surprise). `--since` composes with the positional entity and with `--session-id` through `engine.listFactsSince({entitySlug, sessionId})` (one query, cutoff before LIMIT, event time unless `--since-last-run`), mirroring the `recall` op's composition in `src/core/ops/facts.ts`; pinned by `test/facts-recall-since-composition.test.ts`.- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest`; embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec.@@ -474,7 +483,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `scripts/check-getpage-scoped-write.mjs` — CI scanner for the unscoped-check/scoped-write source-isolation bug class: flags any non-test src file containing BOTH a `getPage(` call with no second argument (or the `X ? {sourceId} : undefined` any-source-when-unset ternary) AND a write-path call (`putPage(`/`importFromContent(`/`importFromFile(`). Fix pattern: `getPage(slug, { sourceId: x ?? 'default' })` (mirror the write's schema default); opt-out marker `gbrain-allow-unscoped-getpage: <reason>` for documented read-only first-match sites (span, preceding lines, or trailing same-line comment). Grandfathered allowlist is EMPTY. Comment/string-aware balanced-paren span walker (same skeleton as check-jsonb-params.mjs); argv-overridable roots; wired as `check:getpage-scope` in verify CHECKS + guards-manifest + `test/fixtures/guards/check-getpage-scoped-write.mjs/{bad,good}/` + `test/check-getpage-scoped-write.test.ts`.- `scripts/check-jsonb-params.mjs` — AST-lite CI guard for the POSITIONAL jsonb double-encode form the template grep above misses: an `executeRaw`/`executeRawDirect`/`.unsafe()` call whose balanced arg span binds `JSON.stringify(x)` into a bare `$N::jsonb` cast. Walks each call's balanced span respecting strings/templates/comments, handles generic-typed calls (`executeRaw<T>(`), and allows the sanctioned forms (`$N::text::jsonb`, `$N::text[]`, `executeRawJsonb`, `sql.json`, an inline `jsonb-guard-ok` comment). PGLite's native `db.query` is deliberately not scanned (it parses text→jsonb, so the bug can't occur there). Heuristic by design (whole-span correlation; can't see a `JSON.stringify` assigned to a variable before the call) — the real backstop is the DATABASE_URL-gated e2e parity tests. Scan roots overridable via argv for its self-test (`test/check-jsonb-params.test.ts`).- `scripts/check-source-id-projection.sh` — CI grep guard for the multi-source bug class. Greps `src/core/postgres-engine.ts` + `src/core/pglite-engine.ts` for `SELECT.*FROM pages` projections matching the `rowToPage` feeder shape (id + slug + type + title) and fails if `source_id` is missing. `Page.source_id` is required at the type level; a projection dropping the column produces `Page` rows with `source_id: undefined` while TypeScript's `: string` lies about it. Wired into `bun run verify`.-- `scripts/guards-manifest.tsv` + `scripts/guard-self-test.sh` — THE single registry of `scripts/check-*` CI guards (52 guards) and its self-test harness. Every guard is classified `scanner` (greps/parses repo sources — must eventually carry fixtures), `buildfresh`, or `repostate` (exempt-with-reason, not fixture-tested). `guard-self-test.sh` (`bun run check:guard-self-test`, wired into `bun run verify`) runs each `selftest=yes` scanner against known-bad (must exit non-zero) and known-good (must pass) fixture trees under `test/fixtures/guards/<guard>/{bad,good}/` via the `GBRAIN_GUARD_ROOT` env seam, and fails the build when a new `scripts/check-*` script is missing from the manifest — so a guard whose pattern rots into a permanently-green no-op fails CI instead of masquerading as coverage. The manifest registers and classifies guards but does not itself schedule them — `run-verify-parallel.sh`'s `CHECKS` array remains the execution list, and a registered guard is not automatically wired into verify. New guard = new manifest row (+ fixtures if scanner) + a `CHECKS` entry if it should gate pushes.+- `scripts/check-compile-autoload.sh` — CI scanner: every `bun build --compile` invocation (CLI one-liners carrying `--outfile`, or `['build', '--compile', …]` spawn arrays) in `package.json`, `CLAUDE.md`, `CONTRIBUTING.md`, `.github/`, `scripts/` and `docs/` must carry `--no-compile-autoload-bunfig`, because a compiled Bun binary otherwise auto-loads a cwd `bunfig.toml` and runs its `preload` before any gbrain code (before `cli-preflight.ts`). Prose that names the command without `--outfile` is ignored; `test/` compile helpers are out of scope (throwaway binaries run from temp dirs). Self-tested via `test/fixtures/guards/check-compile-autoload.sh/{bad,good}/`; wired as `check:compile-autoload` in verify CHECKS.+- `scripts/guards-manifest.tsv` + `scripts/guard-self-test.sh` — THE single registry of `scripts/check-*` CI guards (53 guards) and its self-test harness. Every guard is classified `scanner` (greps/parses repo sources — must eventually carry fixtures), `buildfresh`, or `repostate` (exempt-with-reason, not fixture-tested). `guard-self-test.sh` (`bun run check:guard-self-test`, wired into `bun run verify`) runs each `selftest=yes` scanner against known-bad (must exit non-zero) and known-good (must pass) fixture trees under `test/fixtures/guards/<guard>/{bad,good}/` via the `GBRAIN_GUARD_ROOT` env seam, and fails the build when a new `scripts/check-*` script is missing from the manifest — so a guard whose pattern rots into a permanently-green no-op fails CI instead of masquerading as coverage. The manifest registers and classifies guards but does not itself schedule them — `run-verify-parallel.sh`'s `CHECKS` array remains the execution list, and a registered guard is not automatically wired into verify. New guard = new manifest row (+ fixtures if scanner) + a `CHECKS` entry if it should gate pushes.- `scripts/merge-lcov.ts` + `scripts/coverage-diff-gate.ts` + `scripts/coverage-baseline-gate.ts` + `scripts/update-coverage-baseline.ts` + `scripts/render-coverage-summary.ts` + `scripts/coverage-gate-exemptions.txt` + `scripts/coverage-baseline.json` — the coverage measurement + gating cluster; the operating guide is docs/TESTING.md "Coverage lanes and gates". `merge-lcov.ts` walks artifact dirs for `lcov.info` + `lane-manifest.json`, sums DA hits per file:line, normalizes paths repo-relative, and emits a merged lcov + summary JSON (src-only totals/per-dir/per-file, the `lineHits` extension the diff gate consumes, and never-loaded src files as count + sorted list — deliberately never a percentage, since physical lines ≠ executable lines); `--manifest-expect` pins the lane set; SHA, duplicate identities, and actual per-lane LCOV counts are validated (`--sha` supports offline artifacts), and a missing/incomplete lane or a `shard` lane with `lcovCount != 1` (the xargs-batching tripwire) marks the summary `degraded: true` — still exit 0 (degraded is data, and both gates go report-only on it). `coverage-diff-gate.ts` gates added/changed gate-scoped lines (non-test, non-generated `src/**.ts`) at ≥80% covered plus zero changed-but-never-loaded files; report-only unless `COVERAGE_GATE_ENFORCE=1`; a `[coverage-exempt: reason]` commit trailer passes with a loud warning; `coverage-gate-exemptions.txt` rows (exact path or trailing-`/` prefix; SHRINK-ONLY — additions need a graduation review) are excluded from the gate but still reported (`[e2e-exempt]` / `[subprocess-undercount]`); exit contract: 0 = pass or report-only, 1 = fail while enforcing, 2 = infrastructure error (never conflated with a coverage verdict). `coverage-baseline-gate.ts` reads the baseline via `git show origin/master:scripts/coverage-baseline.json` (never the working tree, so a PR can't weaken its own bar) and compares corpus-matched sections only (`--corpus prCorpus|fullCorpus`), failing on >0.5pp global or >1.0pp per-dir drops; `provisional: true` in the baseline (the current state — both corpus sections unseeded) keeps it report-only regardless of enforcement; `update-coverage-baseline.ts` writes the working-tree baseline (per-file detail limited to the committed `watchlist`) and `--promote` flips `provisional: false`. `render-coverage-summary.ts` renders the summary JSON as markdown on stdout for `$GITHUB_STEP_SUMMARY`, including the behavioral-vs-structural counts from `scripts/structural-suites.tsv`. Wiring: 17 PR-corpus lanes in test.yml (10 matrix shards + four serial partitions + the three dedicated slow jobs) upload `coverage-*` artifacts and the advisory `coverage-report` job merges + renders + runs both gates report-only (deliberately absent from `test-status`/`cache-write` until graduation); schedule-only `coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report` in e2e.yml produce the self-contained nightly fullCorpus number (full e2e glob included) and the `coverage-full-merged` trend artifact. Collection is `COVERAGE_DIR`-opt-in in `test-shard.sh`/`run-serial-tests.sh`/`run-e2e.sh` — unique coverage dir per bun process (a reused dir overwrites `lcov.info`), lane manifest written only on a green run, `run-e2e.sh` requires an ABSOLUTE `COVERAGE_DIR` and honors `E2E_FILE_TIMEOUT_SECS` (both deliberately non-`GBRAIN_`-prefixed to survive the hermetic env scrub). Bun/JSC emits line records only (function coverage is informational) and no subprocess coverage, so `src/cli.ts` undercounts. Pinned by `test/scripts/merge-lcov.test.ts`, `test/scripts/coverage-diff-gate.test.ts`, `test/scripts/render-coverage-summary.test.ts`.- `scripts/check-module-size.sh` + `scripts/module-size-limits.tsv` — the module-size ratchet (`bun run check:module-size`, wired into `bun run verify`). The TSV commits a per-file `wc -l` ceiling (`path max_lines policy note`); four rules, all violations reported before a single exit 1: a file above its ceiling fails (raise a ceiling only as a conscious TSV edit); a ceiling more than 50 lines above the measured size fails (stale slack after a shrink — lower it so the ratchet holds); a TSV row whose path no longer exists fails (remove the row); an unlisted `src/**/*.ts` (excluding `*.generated.ts`/`*.test.ts`) above the 1500-line new-file cap fails (split it or add a row). Policy `region-exempt` (only `src/core/migrate.ts`) counts lines OUTSIDE the append-only `export const MIGRATIONS = [` … `];` region, so the migrations array grows freely while the surrounding runner logic stays ratcheted. Self-test seams: `GBRAIN_GUARD_ROOT`, `GBRAIN_MODULE_SIZE_SLACK`, `GBRAIN_MODULE_SIZE_NEWFILE_CAP`.- `scripts/classify-tests.ts` + `scripts/structural-suites.tsv` — suite-level behavioral-vs-structural test classification (the intent axis described in docs/TESTING.md "File taxonomy"). Content-based detectors — repo-anchored `readFileSync`/`Bun.file` readers, exec-scan grep windows over `src|scripts|docs`, and the `doctorSource()`/`doctorFileSource()` helpers — mark a suite STRUCTURAL when its assertions read repo source/doc text rather than executing product code; tmpdir-anchored reads don't count, and files with detectors but no attributable suite land in an `unknown` bucket emitted as comment rows (surfaced, never silently dropped). Modes: bare = rewrite the TSV; `--check` = byte-for-byte regenerate-and-diff freshness (wired as `bun run check:structural-manifest` in `bun run verify` via `scripts/check-structural-manifest.sh`); `--summary` = counts only. Fix misclassifications in the detector list, never by hand-editing the TSV. `render-coverage-summary.ts` consumes the TSV for the behavioral-vs-structural line in the CI coverage report.@@ -672,7 +682,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/bootstrap/atomic-write.ts` — the ONE atomic config-file writer for bootstrap host surfaces: symlink-target-resolving, mode-inheriting (`freshMode` for new files, `forceMode` for secret-bearing targets), random-suffix tmp + rename, tmp unlinked best-effort when write/chmod/rename throws (ENOSPC/EACCES never strand `.tmp-` litter), and the existsSync→realpathSync race falls back to fresh-path resolution instead of throwing raw ENOENT. hooks.ts (JSON), codex-toml.ts (TOML+EOL), and opencode-json.ts (JSONC) all swap through it; serialization and EOL policy stay caller-side.- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath; non-TTY requires `--yes`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/e2e/bootstrap-harness-lifecycle.serial.test.ts`.- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`.-- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure).+- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`.- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). `genuineUserTurnIndexes` separately records user-role turns containing real text blocks, because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.- `src/core/transcripts/grok.ts` — the Grok Build (grok CLI) transcript adapter: one session directory (`~/.grok/sessions/<url-encoded-cwd>/<uuid>/chat_history.jsonl`) = one session; `GROK_HOME` relocates the root. Turn selection is STRUCTURAL (`mapGrokLine`, exported so the dated `SPEC_TARGET` mapping is pinned): user turns are `type:'user'` text blocks WITHOUT `synthetic_reason` (injected system_reminder/task_completed rows are `typed`, i.e. intentionally text-free, as are tool_result-only user arrays); assistant turns need non-empty string `content` (tool-only rows — `content` ''/null WITH `tool_calls` — are `typed`); system/reasoning/tool_result/backend_tool_call rows are `typed`; unknown row types `skip`. A recognised HUMAN-turn row whose content this parser cannot decode (user `content` missing / non-string / non-array / an array holding non-block entries; assistant non-string `content` with no `tool_calls`) is `malformed` and counted as SKIPPED, never typed, so a file made only of such rows is never `expectedEmpty` — the ingest drift signal fires (`bytesRead > 0`, sessions 0, `cleanScan=false`, watermark frozen) and `zeroSessionsReason` names the malformed row count, instead of an upstream schema change silently advancing the watermark past whole conversations. `chat_history.jsonl` carries NO per-message timestamps: session times come from the sibling `summary.json` (`created_at`/`last_active_at`; a malformed summary is ignored, an unparseable date is never fabricated) and, because grok writes `summary.json` at session END, an in-progress session or partial rsync falls back to the log file's own mtime — a real filesystem time — with `raw.timestamp_source` stamped `'summary.json'` vs `'file_mtime'` so consumers can tell them apart (without the fallback the render refusal would freeze the `--since-last` watermark for the whole grok root). Every message carries the session bounds (last message = `last_active_at`, the rest = start). Session id: summary → UUID dir name → `stableIdFromPath` (a sha256 prefix of the log path, never the bare `chat_history` basename, which would collapse every such session onto one page). Sidecars (updates.jsonl, events.jsonl, rewind_points.jsonl, summary.json, prompt_history.jsonl) are not sessions — discover.ts's grok-sidecar filter is scoped to PROVEN grok trees and the head sniff rejects claude-family keys (grok detection runs after claude-code; an oversized system head still detects through the truncated-line sniff); a percent-encoded cwd segment that fails to decode yields `cwd` undefined with the session id intact.- `src/core/transcripts/capture-spec.ts` + `codex-hook-lane.ts` — the per-harness session-end capture seam. `capture-spec.ts`: the satisfies-anchored `CAPTURE_SPECS` record ({confine, parse, discover?}) for the STDIN-DRIVEN lanes (claude-code, codex); `captureSpecFor()` resolves unknown/undefined/opencode to the claude spec (golden-pinned by `test/codex-hook-lane.test.ts`); openclaw is deliberately NOT a member (its lane is in-process, trusted-plane — see context-engine.ts). `codex-hook-lane.ts`: `confineCodexTranscriptPath` (the same S3#8 ladder as the claude root, pinned at BOTH `codexSessionsDir()` AND `codexArchivedSessionsDir()` — codex MOVES a rollout into the flat `archived_sessions` store on archive, so fencing only the live store refused a still-valid path; both CODEX_HOME-resolved since the spawner IS codex; an explicitly pinned test-seam `root` stays single-root; ENOENT/ENOTDIR on the path is `missing_path` — the rung hook.ts gates its discovery fallback on — while `unreadable` is reserved for EACCES/IO faults, so the codex session-end heartbeat reason for a nonexistent `transcript_path` after a failed discovery is `transcript_missing_path`, not `transcript_unreadable`; no WSL branch v1), `parseCodexHookTranscript` (ParsedTranscript shape over the adapter's exported `mapCodexLine`; same OPT-IN `collectToolCalls` contract as `parseTranscript`, and the same `capToolCallInput` bound on observed args; head+tail over budget so session_meta identity survives; tool calls from the OBSERVED args keys — `custom_tool_call.input` fixture-verified, `function_call.arguments` source-verified at rust-v0.147.0; tolerant JSON-string parse; NO `result` join — 0.147.0 persists no success flag on `*_output` rows; `compacted` rows become boundary positions), and `discoverNewestCodexRollout` (bounded newest-first walk over the dated live store, then a flat pass over the archived store under the SAME 4096 dirent cap — skipped once the cap trips; id-in-filename match, and an id-matched archived hit keeps `transcript_discovered` (never relabelled `_newest`, which hook.ts reads as a guess and bars from the relay); symlink-reject — the fallback for `transcript_path: null` or a moved rollout, and the seam for SIGKILL'd sessions, which never fire SessionEnd). Engine-free by construction; never imports discover.ts. Pinned by `test/codex-hook-lane.test.ts` + `test/codex-hook-lane-archived.test.ts` + the runHook-driven matrix in `test/memorable-relay.serial.test.ts`.@@ -697,7 +707,9 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; sidecar-marked exactly-once). Bounded, fail-soft, never throws; armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `GBRAIN_SWEEP=0` kills it. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created.- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.-- `src/core/secret-scan.ts` — pattern scanner for USER workspaces (own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml`, which is a public-repo CI fixture policy); redacted previews only; `redactFindings` is the corpus-write mode.+- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, gbrain), JWTs, whole-block PEM keys, plus two catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept). Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit AND clears 3.5 bits/char. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy). Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database URL with userinfo in this file's comments (`scripts/check-pg-url-redaction.sh`). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), and `PEM_BLOCK_RE`'s lazy body (≤`PEM_BODY_MAX_CHARS` = 16384; a longer body degrades to the header-only match) — plus a per-pattern `precheck` substring gate on the two catch-alls (`@`; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list: a repetitive tail against 64 short claimed values meant millions of candidate objects and hundreds of MB of RSS for 64 findings, ahead of message truncation) (never an alternation RegExp — O(text × Σ|values|) on prefix-sharing values; never over emitted tokens, so a value spelling a pattern name cannot nest). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). Perf pins: `test/secret-scan-perf.test.ts`.+- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts under the embed-skip threshold.+- `src/core/context/sensitivity-scan.ts` — composed detector for compiled-context entries (secret-scan → PII → path shapes → operator blocklist → operator pattern file). secret-scan OWNS credential-shaped families it also matches: a PII finding whose value (raw, or with the `Bearer ` keyword stripped) matches a secret finding's fingerprint is not reported twice; short bearer tokens under secret-scan's floor still surface as `pii:bearer`. Every family honors the same `.gbrain-scan-allow` fingerprint escape hatch.- `src/core/backup/status-file.ts` — ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (`~/.gbrain/backup-status.json`, schema `gbrain-backup-status-v1`; fail-open load, atomic tmp+rename write, `invalidateBackupStatus()` fired by the fix paths — `bootstrap repo` receipt write, `sources harden`, `workspacePush` finish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (`backupNoticeText(s, 'human'|'aggregate')` — human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (`backupNagGate(channel, s)` on `backup-nag-state.json`, OWN schema `gbrain-backup-nag-v1` — skillpack `loadNagState` would drop the extra fields on round-trip, so only the pure policy fns `decideNagAction`/`recordNagDisplay` are reused). Budget = AND of: 24h cross-channel dampener (`last_shown_at`), per-channel ceiling 3 per pseudo-version (`YYYY-MM(checked_at)` + no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (`global_shown_count`/`global_month`). `backupNagReadOnlyConsult` is the OpenClaw context-engine's never-writes variant; `backupSpawnDue`/`recordBackupSpawn` debounce the session-end detached spawn (no sidecar file); `maybeEmitBackupNag` is the cli.ts startup rail body (skip set incl. serve/call/jobs; `BACKUP_LOCAL_ONLY <n>` machine marker + human line). Off switches: `GBRAIN_BACKUP_CHECK=0`, config `backup.check_enabled`; interval env `GBRAIN_BACKUP_CHECK_DAYS` > config `backup.check_interval_days` > 30; values <1 or non-numeric fall back to the 30-day default (`DAYS=0` never means "always stale"; `config set` rejects <1 outright). Tests: `test/backup-status-file.serial.test.ts`.- `src/core/backup/coverage.ts` — engine-side compute for the backup check. `computeBackupCoverage(engine, {localGitProbes})` assesses: source repos (deduped by `discoverGitRoot`, capped 500 roots with a logged skip count; `originRemoteState` — a positive tri-state, deliberately NOT sync-git's `hasOriginRemote`, which collapses probe failures into a false "no remote" — plus `hasRemoteTrackingRef` (origin configured but never pushed is also `no_remote`), `aheadCount`, `isWorkingTreeDirty` — local read-only git subcommands only, no network), the bootstrap workspace (receipt `repo_url` + push statuses, file plane only), db_only tiering (info row with the `gbrain export --dir` fix), harness skill dirs (info — installed copies), and the DB-only-brain worst case (pages>0, nothing git-backed → warn on PGLite / info with different copy on postgres — the engine.kind branch). `no_remote` alone flips `overall: 'warn'`. `getBackupStatus` is the single choke point (fresh cache → file read; probed results persist, probe-less results NEVER persist; a failed compute returns the prior cache — never clobbers). `maybeRefreshBackupStatusInProcess(engine)` is the serve-side single-flight refresher — called from `mcp/dispatch.ts` gated on `opts.transport === 'stdio'` (the locality axis; 'http'/UNSET ⇒ fail-closed, pinned by test), recomputes on stale-or-absent OR warn+>24h, 1h attempt floor. Trust boundary: same as `extraction-sync.ts` — git probes only in trusted-local contexts. Consumers: `commands/backup.ts` (`gbrain backup status|check`, PGLite-lock fallback to cache), `advisor/collect-backup-coverage.ts`, `doctor/checks/backup-coverage.ts` (`backup_coverage`, localOnly probes / remote cache-only), `commands/sync.ts` post-sync stale-only refresh, hook session-end detached spawn. Docs: `docs/operations/backup-check.md`. Tests: `test/backup-coverage.serial.test.ts`, `test/advisor-backup-coverage.serial.test.ts`, `test/doctor-backup-coverage.serial.test.ts`, `test/hook-backup-notice.serial.test.ts`, `test/mcp-backup-nag.serial.test.ts`.- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo).diff --git a/docs/guardrails.md b/docs/guardrails.mdindex 01cd877b2f..af7307f30a 100644--- a/docs/guardrails.md+++ b/docs/guardrails.md@@ -92,11 +92,42 @@ The module may export any of: a default-exported provider, a default-exportedprovider array, a named `guardrailProviders` array, or a`register(registerGuardrailProvider)` function (sync or async).+**Where the variable may come from.** The spec must be an **absolute path**+or a **`~/` path**. Cwd-relative specs (`./x`, `../x`) are refused: they would+resolve against whatever directory gbrain happens to run in. Bare package+names (`some-guardrail`, `@scope/pkg`) are refused too: in the compiled binary+a package name resolves from the *current directory's* `node_modules`, so a+cloned repository could supply the module. The variable is honored from your+shell environment, from a service `EnvironmentFile`, or from+**`~/.gbrain/.env`** (the operator-owned secrets file, loaded before the+guardrails loader runs). It is **never** honored from a `.env` file in the+*current directory*: Bun auto-loads those files, and a cloned repository must+not be able to choose what your gbrain executes. When a cwd `.env` assigns+`GBRAIN_GUARDRAILS_MODULE`, gbrain drops the variable, prints one stderr line+(`[env] Ignoring GBRAIN_GUARDRAILS_MODULE because a .env file in the current+directory assigns it …`) and then — because it cannot tell a value you exported+from the file's — refuses to run rather than re-running without your firewall+(the fail-closed rule below). Every other protected variable is dropped the same+way and gbrain re-runs itself with the sanitized environment so nothing it+spawns sees the value either. Running gbrain from *inside*+`~/.gbrain` is the one exception: that `.env` is your own, and it is honored+without a warning. The same rule covers the other security-relevant `GBRAIN_*`+variables and the loader / git / node / proxy / AI-CLI hijack families — see+the "Environment variables and cwd `.env` files" section of `SECURITY.md`.+**Loading is fail-closed.** If `GBRAIN_GUARDRAILS_MODULE` is set but the modulefails to import or registers zero providers, the CLI exits 1 instead of-silently running without the firewall you configured. (The *classify* path-stays fail-open — a registered provider that throws never breaks an ingest.)-Unset, the variable costs nothing and gbrain stays inert.+silently running without the firewall you configured. The same holds at the+cwd boundary: when a `.env` in the current directory assigns+`GBRAIN_GUARDRAILS_MODULE` and a non-empty value was dropped, gbrain does+**not** re-run without it — it refuses to run (exit 1,+`guardrails: GBRAIN_GUARDRAILS_MODULE is assigned by a .env file in the+current directory; refusing to run without the operator's firewall …`),+because Bun merges that file before gbrain starts and the value you exported+cannot be told apart from the file's. Remove the assignment from the project's+`.env` or run from another directory; a benign repository never sets this key.+(The *classify* path stays fail-open — a registered provider that throws never+breaks an ingest.) Unset, the variable costs nothing and gbrain stays inert.### Provider responsibilitiesdiff --git a/docs/guides/agent-to-gbrain.md b/docs/guides/agent-to-gbrain.mdindex b487b89c7f..a56945c634 100644--- a/docs/guides/agent-to-gbrain.md+++ b/docs/guides/agent-to-gbrain.md@@ -160,13 +160,17 @@ The agent's host needs a worker that processes shell jobs:gbrain jobs submit shell --params '{...}' --follow# Persistent worker (Postgres only — PGLite uses --follow inline):-GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work+gbrain jobs work --allow-shell-jobs # or: GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work```-`GBRAIN_ALLOW_SHELL_JOBS=1` is the worker-side opt-in. Without it, shell jobs-sit in `waiting` indefinitely. Set it on the worker process env (or in your-deploy unit / launchd plist), not per-submission — submitter env is a weak-proxy for worker env.+`--allow-shell-jobs` (equivalently `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the+worker; a `.env` in the worker's directory cannot set it) is the worker-side+opt-in. The handler is always registered but guarded: an unflagged worker that+claims a shell job dead-letters it immediately (`UnrecoverableError`, no+retries) — a shell job that stays in `waiting` means no worker is running at+all. Put the flag on the worker's command line (or the variable in its deploy+unit / launchd plist), not per-submission — submitter env is a weak proxy for+worker env.## Decision tablediff --git a/docs/guides/minions-deployment.md b/docs/guides/minions-deployment.mdindex 1b7a8cb4ce..35cc7ff57e 100644--- a/docs/guides/minions-deployment.md+++ b/docs/guides/minions-deployment.md@@ -418,11 +418,14 @@ gbrain jobs list --status active --limit 10gbrain jobs list --status dead --limit 10# Shell jobs enabled on the worker? There is no supervisor-status JSON field-# for this — the gate is the GBRAIN_ALLOW_SHELL_JOBS=1 env var on the worker-# process (the handler is always registered but guarded). Inspect the-# supervisor's environment directly:-ps eww -p "$(gbrain jobs supervisor status --json | jq -r '.supervisor_pid')" \- | grep -o 'GBRAIN_ALLOW_SHELL_JOBS=[^ ]*' || echo "flag not set"+# for this — the gate is the worker's opt-in (the handler is always registered+# but guarded). A supervisor started with --allow-shell-jobs (or with+# GBRAIN_ALLOW_SHELL_JOBS=1 exported) passes `--allow-shell-jobs` on the+# worker's command line AND sets the env var on it. Inspect the worker+# process directly (args + environment):+for pid in $(pgrep -f 'gbrain jobs work'); do ps eww -p "$pid"; done \+ | grep -o -e '--allow-shell-jobs' -e 'GBRAIN_ALLOW_SHELL_JOBS=[^ ]*' | sort -u \+ || echo "shell jobs not enabled"# An unflagged worker that claims a shell job dead-letters it instantly:gbrain jobs list --status dead --name shell --limit 3```diff --git a/docs/guides/minions-shell-jobs.md b/docs/guides/minions-shell-jobs.mdindex 10250d177b..422b89885a 100644--- a/docs/guides/minions-shell-jobs.md+++ b/docs/guides/minions-shell-jobs.md@@ -39,12 +39,15 @@ pass:`ctx.remote === true` (MCP callers). Independent of the env flag. Remoteagents can never submit shell jobs. `MinionQueue.add('shell', ...)` has itsown guard too, so an in-process handler can't programmatically bypass this.-2. **Env flag.** The shell handler is ALWAYS registered on the worker, but it- is guarded: unless `GBRAIN_ALLOW_SHELL_JOBS=1` is set on the worker process,- a claimed shell job throws `UnrecoverableError` and goes straight to `dead`- (no retries). Default: off. Your agent opts in per-host. (Always-registered- guarded mode — not "unregistered", so unflagged workers fail shell jobs- loudly instead of leaving them `waiting` forever.)+2. **Worker opt-in.** The shell handler is ALWAYS registered on the worker, but+ it is guarded: unless the worker was started with+ `gbrain jobs work --allow-shell-jobs` (equivalently, `GBRAIN_ALLOW_SHELL_JOBS=1`+ exported in the worker's environment), a claimed shell job throws+ `UnrecoverableError` and goes straight to `dead` (no retries). Default: off.+ Your agent opts in per-host. A `.env` file in the worker's working directory+ cannot set the variable — gbrain ignores it there. (Always-registered guarded+ mode — not "unregistered", so unflagged workers fail shell jobs loudly+ instead of leaving them `waiting` forever.)**What the env allowlist does AND does not do.** Shell jobs run with a minimalenv: `PATH, HOME, USER, LANG, TZ, NODE_ENV`. Your secrets like `OPENAI_API_KEY`@@ -76,7 +79,7 @@ secrets in `env:` instead.On one terminal, start a persistent worker:```bash-GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work+gbrain jobs work --allow-shell-jobs # or: GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work```Rewrite crontab to submit shell jobs (no `--follow`):@@ -253,7 +256,7 @@ cat ~/.gbrain/audit/shell-jobs-*.jsonl | jq '.'# The handler is always registered but guarded: an unflagged worker that claims# a shell job dead-letters it immediately (UnrecoverableError, no retries).gbrain jobs list --status dead --name shell-# → error_text: "shell handler disabled on this worker (set GBRAIN_ALLOW_SHELL_JOBS=1 ...)"+# → error_text: "shell handler disabled on this worker (start it with --allow-shell-jobs or GBRAIN_ALLOW_SHELL_JOBS=1 ...)"# `waiting` pileups mean NO worker is running at all (flagged or not) — check# `gbrain jobs supervisor status` in that case.```diff --git a/docs/guides/queue-operations-runbook.md b/docs/guides/queue-operations-runbook.mdindex a4586a3ce8..7a74985fdc 100644--- a/docs/guides/queue-operations-runbook.md+++ b/docs/guides/queue-operations-runbook.md@@ -216,7 +216,7 @@ If the list is empty AND your submissions keep piling up, no worker isclaiming. Start one:```bash-GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work --concurrency 4+gbrain jobs work --concurrency 4 --allow-shell-jobs # drop --allow-shell-jobs if you never submit shell jobs```## Reading the DB-probe verdicts (pool starved vs server unreachable)diff --git a/docs/integrations/qm-harness.md b/docs/integrations/qm-harness.mdindex cbdcb648de..de4a639996 100644--- a/docs/integrations/qm-harness.md+++ b/docs/integrations/qm-harness.md@@ -165,7 +165,7 @@ In the org's qm deployment repo (the directory `qm init` produced):1. **Tool:** copy [`qm-harness-snippets/tool.json`](qm-harness-snippets/tool.json)to `sandbox/tools/gbrain/tool.json` and drop the compiled `gbrain` binary- beside it (`bun build --compile --outfile gbrain src/cli.ts`, built for+ beside it (`bun build --compile --no-compile-autoload-bunfig --outfile gbrain src/cli.ts`, built forthe sandbox image's OS/arch). `auth.credentialPaths` marks`~/.gbrain/config.json` as the scope's resident credential file;`auth.check` wires `gbrain whoami` into qm's connector status (read-scope;diff --git a/docs/mcp/CHATGPT.md b/docs/mcp/CHATGPT.mdindex 97b7c32037..1fe57ab541 100644--- a/docs/mcp/CHATGPT.md+++ b/docs/mcp/CHATGPT.md@@ -113,6 +113,20 @@ from the `/admin` dashboard or the CLI, then reconnect. Manualregistration per step 2 above never hits this — you pick the scopesexplicitly.+**DCR scope ceiling.** The reverse also holds: a self-registering connector+may request at most `read write`, and while `--enable-dcr` is on, OAuth+discovery (`scopes_supported` in both the authorization-server and the+protected-resource metadata) advertises exactly that set — so a connector+that copies the advertised scopes into its registration succeeds. If it+explicitly asks for `admin` anyway, registration fails with HTTP 400+`invalid_client_metadata` rather than being quietly narrowed, and the+connector shows a connection error. Either register the client manually+(step 2) with the scopes you want, or let it self-register with `read+write` and widen it afterwards with+`gbrain auth rescope-client <client_id> --scopes ...`. Every self-registered+connection also stops at the admin dashboard for your approval before a+token is issued.+## Troubleshooting**"Invalid redirect_uri" during the ChatGPT connector OAuth handshake**diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.mdindex e088131765..7315ce9aaf 100644--- a/docs/mcp/DEPLOY.md+++ b/docs/mcp/DEPLOY.md@@ -20,6 +20,26 @@ Existing sessions are preserved. Before upgrading an installation with queuedwork, follow the [authorization and worker upgrade guide](../guides/authorization-upgrade.md)for the coordinated cutover, consent recovery, and Bun requirements.+**The owner-approval step.** `/authorize` never returns an authorization code+on its own. It records a pending request and redirects the browser to the admin+dashboard (`/admin/?oauth_request=…`), where the brain owner signs in (bootstrap+token or magic link), reviews the client name, redirect URI and requested+scopes, and approves or denies. Only an approval mints the code, which is then+delivered to the client's registered redirect URI; a denial returns+`error=access_denied`. This applies to every authorization-code client,+including clients that self-registered via DCR — self-registration alone never+yields a token. Pending requests expire after ten minutes, do not survive a+server restart, and are bounded: at most ten awaiting-decision requests per+client and a fixed server-wide ceiling. Beyond either, `/authorize` sends the+client back to its registered redirect URI with `error=too_many_requests`+(and no code) until earlier requests are decided or expire; a `429` status on+`/authorize` comes only from the MCP SDK's per-IP rate limit.++**Say to your agent:** *"Start the brain server over HTTP with self-service+registration, then approve my client in the admin dashboard — your agent runs+`gbrain serve --http --enable-dcr` and you finish the connection by approving+it at `/admin/`."*+## Three Paths### Local stdio (zero setup)@@ -211,6 +231,40 @@ await oauthProvider.registerClientManual(For self-service client registration (Dynamic Client Registration, RFC 7591),start the server with `--enable-dcr`. DCR is off by default.+**Say to your agent:** *"Start my brain's MCP server with self-service client+registration — your agent runs `gbrain serve --http --enable-dcr`, and you+approve each new connection in the admin UI."*++A self-registered client goes through three gates:++1. **Scope ceiling at registration.** Dynamic registration may request at most+ `read write`. A request naming `admin`, `sources_admin`, `users_admin`, or+ `agent` is rejected with HTTP 400 `invalid_client_metadata` (never silently+ narrowed), and the error text points at the operator path. Under+ `--enable-dcr-insecure`, a `client_credentials` registration is capped at+ `read` — a grant that skips owner approval never carries `write`. While+ DCR is enabled (either mode), OAuth discovery advertises the `read write`+ self-registration ceiling as `scopes_supported` (authorization-server and+ protected-resource metadata alike), so a client that registers with the+ advertised scopes succeeds;+ with DCR off, discovery lists every scope an operator-registered client+ may hold. `agent` is never advertised — it needs delegation bindings no+ OAuth request can carry.+2. **Owner approval on `/authorize`.** Every authorization-code connection+ redirects to the admin dashboard, where you see the client, its redirect+ URI, and the requested scopes, and approve or deny. No code is minted+ until you approve. Consent never widens the registered scope.+3. **Per-request clamp.** Issued codes and tokens are re-intersected with the+ client's current registered scope, so a later `rescope-client` takes effect+ on the next request.++To give a self-registered client more than `read write`, widen it yourself+after the fact — `gbrain auth rescope-client <client_id> --scopes read,write,sources_admin`+(or the admin dashboard's Agents page) — or pre-register it with+`gbrain auth register-client` / the admin API, which accept every scope.+`gbrain doctor` warns about active clients that hold a privileged scope but+look self-registered.+Native MCP clients register cleanly: `redirect_uris` may use an app customscheme (RFC 8252, e.g. `myapp://callback`) or `http://` loopback alongside`https://`; scopes the server doesn't know are filtered rather than fatal;diff --git a/llms-full.txt b/llms-full.txtindex 0a23ab87af..ab26b707cf 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1507,7 +1507,7 @@ ms, max waiters) for `--json`; a one-line summary prints to stderr.## Build-`bun build --compile --outfile bin/gbrain src/cli.ts`+`bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts`## Version locations (single source of truth: `VERSION` file)@@ -2963,10 +2963,14 @@ How the open-loop engine decides who's waiting: [`docs/guides/open-loops.md`](doYour other agents' histories import in one command. `gbrain transcripts ingest`parses agent session logs (Claude Code, Codex, OpenClaw, Hermes, Grok Build) and extractedconsumer chat exports (ChatGPT / Claude.ai `conversations.json`) into readable-conversation pages with provenance back to the exact session file. Secrets are-scrubbed from message bodies, titles, speakers, and session metadata before-anything is written, embedding is off by default for bulk backfills, and-re-runs are free — unchanged sessions skip on content hash:+conversation pages with provenance back to the exact session file. Pattern-based redaction runs over message bodies, titles, speakers, and session+metadata before anything is written — vendor key prefixes, JWTs, cloud/API key+shapes, `Bearer` headers, connection-string credentials, and high-entropy+`KEY=`/`TOKEN=` assignments become `<REDACTED:…>` placeholders (preview with+`--dry-run`; no pattern set is complete, so if a secret still lands see+["If a secret reached the brain"](SECURITY.md#if-a-secret-reached-the-brain):+rotate it, then `gbrain delete <slug> --purge`). Embedding is off by default+for bulk backfills, and re-runs are free — unchanged sessions skip on content hash:```bashgbrain transcripts ingest # discover importable session logs@@ -3666,7 +3670,10 @@ cwd-.env guard (gbrain never adopts a `DATABASE_URL` that Bun auto-loadedfrom the working directory's `.env` family: `.env`, `.env.local`, and the`.env.<NODE_ENV>` / `.env.<NODE_ENV>.local` variants for `development`,`production` and `test`; with the precedence note when both `GBRAIN_DATABASE_URL` and-`DATABASE_URL` are set), redacted URLs only, and — on Postgres — a+`DATABASE_URL` are set — this `DATABASE_URL` guard matches the file's VALUE; the+security-relevant `GBRAIN_*` variables get the stricter key-presence quarantine+described under "Environment variables and cwd `.env` files" in `SECURITY.md`),+redacted URLs only, and — on Postgres — azero-round-trip pooler block (Supabase pooler detection, prepared-statementresolution, pool sizes, direct/session-pooler derivability). `--brain <id>`resolves a mounted brain and reports the MOUNT's engine and URL source, never@@ -5780,6 +5787,26 @@ Existing sessions are preserved. Before upgrading an installation with queuedwork, follow the [authorization and worker upgrade guide](../guides/authorization-upgrade.md)for the coordinated cutover, consent recovery, and Bun requirements.+**The owner-approval step.** `/authorize` never returns an authorization code+on its own. It records a pending request and redirects the browser to the admin+dashboard (`/admin/?oauth_request=…`), where the brain owner signs in (bootstrap+token or magic link), reviews the client name, redirect URI and requested+scopes, and approves or denies. Only an approval mints the code, which is then+delivered to the client's registered redirect URI; a denial returns+`error=access_denied`. This applies to every authorization-code client,+including clients that self-registered via DCR — self-registration alone never+yields a token. Pending requests expire after ten minutes, do not survive a+server restart, and are bounded: at most ten awaiting-decision requests per+client and a fixed server-wide ceiling. Beyond either, `/authorize` sends the+client back to its registered redirect URI with `error=too_many_requests`+(and no code) until earlier requests are decided or expire; a `429` status on+`/authorize` comes only from the MCP SDK's per-IP rate limit.++**Say to your agent:** *"Start the brain server over HTTP with self-service+registration, then approve my client in the admin dashboard — your agent runs+`gbrain serve --http --enable-dcr` and you finish the connection by approving+it at `/admin/`."*+## Three Paths### Local stdio (zero setup)@@ -5971,6 +5998,40 @@ await oauthProvider.registerClientManual(For self-service client registration (Dynamic Client Registration, RFC 7591),start the server with `--enable-dcr`. DCR is off by default.+**Say to your agent:** *"Start my brain's MCP server with self-service client+registration — your agent runs `gbrain serve --http --enable-dcr`, and you+approve each new connection in the admin UI."*++A self-registered client goes through three gates:++1. **Scope ceiling at registration.** Dynamic registration may request at most+ `read write`. A request naming `admin`, `sources_admin`, `users_admin`, or+ `agent` is rejected with HTTP 400 `invalid_client_metadata` (never silently+ narrowed), and the error text points at the operator path. Under+ `--enable-dcr-insecure`, a `client_credentials` registration is capped at+ `read` — a grant that skips owner approval never carries `write`. While+ DCR is enabled (either mode), OAuth discovery advertises the `read write`+ self-registration ceiling as `scopes_supported` (authorization-server and+ protected-resource metadata alike), so a client that registers with the+ advertised scopes succeeds;+ with DCR off, discovery lists every scope an operator-registered client+ may hold. `agent` is never advertised — it needs delegation bindings no+ OAuth request can carry.+2. **Owner approval on `/authorize`.** Every authorization-code connection+ redirects to the admin dashboard, where you see the client, its redirect+ URI, and the requested scopes, and approve or deny. No code is minted+ until you approve. Consent never widens the registered scope.+3. **Per-request clamp.** Issued codes and tokens are re-intersected with the+ client's current registered scope, so a later `rescope-client` takes effect+ on the next request.++To give a self-registered client more than `read write`, widen it yourself+after the fact — `gbrain auth rescope-client <client_id> --scopes read,write,sources_admin`+(or the admin dashboard's Agents page) — or pre-register it with+`gbrain auth register-client` / the admin API, which accept every scope.+`gbrain doctor` warns about active clients that hold a privileged scope but+look self-registered.+Native MCP clients register cleanly: `redirect_uris` may use an app customscheme (RFC 8252, e.g. `myapp://callback`) or `http://` loopback alongside`https://`; scopes the server doesn't know are filtered rather than fatal;diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 52c57f8cb7..b5bc237826 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.50.4.0",+ "version": "0.50.5.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 51e58962d6..64d84bf658 100644--- a/package.json+++ b/package.json@@ -34,8 +34,8 @@},"scripts": {"dev": "bun run src/cli.ts",- "build": "bun build --compile --outfile bin/gbrain src/cli.ts",- "build:all": "bun build --compile --target=bun-darwin-arm64 --outfile bin/gbrain-darwin-arm64 src/cli.ts && bun build --compile --target=bun-linux-x64 --outfile bin/gbrain-linux-x64 src/cli.ts",+ "build": "bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts",+ "build:all": "bun build --compile --no-compile-autoload-bunfig --target=bun-darwin-arm64 --outfile bin/gbrain-darwin-arm64 src/cli.ts && bun build --compile --no-compile-autoload-bunfig --target=bun-linux-x64 --outfile bin/gbrain-linux-x64 src/cli.ts","build:admin": "cd admin && bun run build && cd .. && bun run scripts/build-admin-embedded.ts","build:admin-embedded": "bun run scripts/build-admin-embedded.ts","build:schema": "bash scripts/build-schema.sh",@@ -115,6 +115,7 @@"check:guard-self-test": "bash scripts/guard-self-test.sh","check:no-legacy-getconnection": "bash scripts/check-no-legacy-getconnection.sh","check:module-size": "bash scripts/check-module-size.sh",+ "check:compile-autoload": "bash scripts/check-compile-autoload.sh","check:structural-manifest": "bash scripts/check-structural-manifest.sh","check:orphan-modules": "node scripts/check-orphan-modules.mjs","build:harness-docs": "bun run scripts/build-harness-docs.ts"@@ -175,7 +176,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.50.4.0",+ "version": "0.50.5.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 3ade67c893..51e4017668 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.50.4.0",+ "version": "0.50.5.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 9179aeef6c..9e912cbf6d 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.50.4.0",+ "version": "0.50.5.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 2aeab7abbb..78b8dc84fd 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.50.4.0 -->+<!-- gbrain-plugin-tree-stamp: 0.50.5.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 2c6cb37b0d..693f226600 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.50.4.0",+ "version": "0.50.5.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex c8e1bc93c4..dd57d58f35 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.50.4.0",+ "version": "0.50.5.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 32be69ee03..5ad817d8e1 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.50.4.0 -->+<!-- gbrain-plugin-tree-stamp: 0.50.5.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin-variants/gbrain-daily/skills/bulk-ingestion/MANIFEST-PATTERN.md b/plugin-variants/gbrain-daily/skills/bulk-ingestion/MANIFEST-PATTERN.mdindex d7ec52d496..31da771d82 100644--- a/plugin-variants/gbrain-daily/skills/bulk-ingestion/MANIFEST-PATTERN.md+++ b/plugin-variants/gbrain-daily/skills/bulk-ingestion/MANIFEST-PATTERN.md@@ -193,7 +193,8 @@ a recurring shell job shaped like:gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && git add projects/<pipeline-name> <output-dirs> && git commit -m \"<pipeline-name> ingest checkpoint\" && git push"}'```-Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see+Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`+(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — seeminion-orchestrator Preconditions. Do not set it yourself: it is an RCE-classauthorization that belongs to the operator running the daemon, and a submit-sideenv prefix (`GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit ...`) is a no-op indiff --git a/plugin-variants/gbrain-daily/skills/bulk-ingestion/SKILL.md b/plugin-variants/gbrain-daily/skills/bulk-ingestion/SKILL.mdindex d484c8dbbe..b498ed8db4 100644--- a/plugin-variants/gbrain-daily/skills/bulk-ingestion/SKILL.md+++ b/plugin-variants/gbrain-daily/skills/bulk-ingestion/SKILL.md@@ -283,7 +283,8 @@ gbrain jobs submit shell --params '{"cmd": "<your pipeline command> --offset 0 -gbrain agent run "Read skills/<pipeline-name>/SKILL.md and process the next 50 pending manifest items"```-Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see+Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`+(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — seeminion-orchestrator Preconditions; do not set it yourself (it is an RCE-classoperator authorization, and a submit-side env prefix is a no-op in the daemonlane). Small sets (<1000 items) can run inline in chunks; anything that mustdiff --git a/plugin-variants/gbrain-daily/skills/conversation-archive/SKILL.md b/plugin-variants/gbrain-daily/skills/conversation-archive/SKILL.mdindex ccd6e1458a..4e468718e1 100644--- a/plugin-variants/gbrain-daily/skills/conversation-archive/SKILL.md+++ b/plugin-variants/gbrain-daily/skills/conversation-archive/SKILL.md@@ -81,11 +81,18 @@ fingerprint — running with a different cap (or dropping it) starts a freshwatermark scope, so a capped run's skipped tail is never mistaken foralready-scanned.-Native-vs-manual delta to know: the native lane redacts SECRETS (key-patterns) plus your `~/.gbrain/harvest-private-patterns.txt` regexes and-counts agent-directed imperatives into frontmatter, but broad PII detection-(names, phones, addresses) remains YOUR review pass — the manual procedure's-human scrub step still applies to sensitive corpora. Two more deltas: the+Native-vs-manual delta to know: the native lane redacts SECRETS by FORMAT+(vendor key prefixes, JWTs, cloud/API key shapes, `Bearer` headers,+connection strings carrying inline passwords, PEM private keys, and+high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignments) plus your+`~/.gbrain/harvest-private-patterns.txt` regexes and counts agent-directed+imperatives into frontmatter, but broad PII detection (names, phones,+addresses) remains YOUR review pass — the manual procedure's human scrub step+still applies to sensitive corpora. Preview what will be scrubbed with+`--dry-run` before a bulk `--all`. If a secret still reached a page, rotate+it first, then remove the page immediately with+`gbrain delete <slug> --purge` (local CLI only — no 72h tombstone); the+brain-repo git history or a synced file may still hold it. Two more deltas: thenative lane caps each message at ~4K characters in the page body (readablearchive, not verbatim — the session file named in `source_uri` stays theverbatim record), and tool/thinking traffic appears only as one-line@@ -141,9 +148,11 @@ Before writing each page, scan the transcript for secret-shaped strings andPII, and redact each match to a labeled placeholder (`[REDACTED_API_KEY]`,`[REDACTED_TOKEN]`, `[REDACTED_EMAIL]`):-- OpenAI-style keys (`sk-…`), GitHub tokens (`ghp_…`), AWS access-key ids- (`AKIA…`), bearer/authorization tokens, and long high-entropy hex or base64- blobs.+- Vendor-prefixed keys (`sk-…`, `ghp_…`, `AKIA…`/`ASIA…`, `AIza…`,+ `sk_live_…`, `glpat-…`, `npm_…`, `hf_…`), format-only credentials with NO+ prefix (JWTs `eyJ….eyJ….…`, account SIDs, connection strings with an inline+ password), bearer/authorization tokens, PEM private-key blocks, and+ `KEY=`/`TOKEN=`/`PASSWORD=` assignments whose value is high-entropy.- Personal data the transcript wasn't meant to publish: phone numbers, homeaddresses, government ids, private emails.@@ -400,9 +409,12 @@ This skill guarantees:`conversations/<provider>/YYYY-MM-DD-<slug>.md` with `type: conversation`,a `date:` frontmatter field, and a verbatim transcript in aparser-recognized message format.-- Every conversation is scanned for secret-shaped strings and PII before its- page is written; matches are redacted to labeled placeholders and counted in- the import receipt (untrusted-content convention).+- Every conversation is scanned for secret-shaped strings (by wire format,+ not just vendor prefix — JWTs, cloud/API key shapes, connection-string+ credentials, high-entropy assignments) and PII before its page is written;+ matches are redacted to labeled placeholders and counted in the import+ receipt (untrusted-content convention). A page that still captured a+ secret is removed immediately with `gbrain delete <slug> --purge`.- Colliding slugs (untitled/same-day threads) are disambiguated with a shortstable thread hash and check-before-write, never overwritten.- Every import run validates a sample via `gbrain conversation-parser scan`diff --git a/plugin/README.md b/plugin/README.mdindex 07da071b96..3305b17de4 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.50.4.0 -->+<!-- gbrain-plugin-tree-stamp: 0.50.5.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/plugin/skills/bulk-ingestion/MANIFEST-PATTERN.md b/plugin/skills/bulk-ingestion/MANIFEST-PATTERN.mdindex d7ec52d496..31da771d82 100644--- a/plugin/skills/bulk-ingestion/MANIFEST-PATTERN.md+++ b/plugin/skills/bulk-ingestion/MANIFEST-PATTERN.md@@ -193,7 +193,8 @@ a recurring shell job shaped like:gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && git add projects/<pipeline-name> <output-dirs> && git commit -m \"<pipeline-name> ingest checkpoint\" && git push"}'```-Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see+Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`+(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — seeminion-orchestrator Preconditions. Do not set it yourself: it is an RCE-classauthorization that belongs to the operator running the daemon, and a submit-sideenv prefix (`GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit ...`) is a no-op indiff --git a/plugin/skills/bulk-ingestion/SKILL.md b/plugin/skills/bulk-ingestion/SKILL.mdindex d484c8dbbe..b498ed8db4 100644--- a/plugin/skills/bulk-ingestion/SKILL.md+++ b/plugin/skills/bulk-ingestion/SKILL.md@@ -283,7 +283,8 @@ gbrain jobs submit shell --params '{"cmd": "<your pipeline command> --offset 0 -gbrain agent run "Read skills/<pipeline-name>/SKILL.md and process the next 50 pending manifest items"```-Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see+Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`+(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — seeminion-orchestrator Preconditions; do not set it yourself (it is an RCE-classoperator authorization, and a submit-side env prefix is a no-op in the daemonlane). Small sets (<1000 items) can run inline in chunks; anything that mustdiff --git a/plugin/skills/conversation-archive/SKILL.md b/plugin/skills/conversation-archive/SKILL.mdindex ccd6e1458a..4e468718e1 100644--- a/plugin/skills/conversation-archive/SKILL.md+++ b/plugin/skills/conversation-archive/SKILL.md@@ -81,11 +81,18 @@ fingerprint — running with a different cap (or dropping it) starts a freshwatermark scope, so a capped run's skipped tail is never mistaken foralready-scanned.-Native-vs-manual delta to know: the native lane redacts SECRETS (key-patterns) plus your `~/.gbrain/harvest-private-patterns.txt` regexes and-counts agent-directed imperatives into frontmatter, but broad PII detection-(names, phones, addresses) remains YOUR review pass — the manual procedure's-human scrub step still applies to sensitive corpora. Two more deltas: the+Native-vs-manual delta to know: the native lane redacts SECRETS by FORMAT+(vendor key prefixes, JWTs, cloud/API key shapes, `Bearer` headers,+connection strings carrying inline passwords, PEM private keys, and+high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignments) plus your+`~/.gbrain/harvest-private-patterns.txt` regexes and counts agent-directed+imperatives into frontmatter, but broad PII detection (names, phones,+addresses) remains YOUR review pass — the manual procedure's human scrub step+still applies to sensitive corpora. Preview what will be scrubbed with+`--dry-run` before a bulk `--all`. If a secret still reached a page, rotate+it first, then remove the page immediately with+`gbrain delete <slug> --purge` (local CLI only — no 72h tombstone); the+brain-repo git history or a synced file may still hold it. Two more deltas: thenative lane caps each message at ~4K characters in the page body (readablearchive, not verbatim — the session file named in `source_uri` stays theverbatim record), and tool/thinking traffic appears only as one-line@@ -141,9 +148,11 @@ Before writing each page, scan the transcript for secret-shaped strings andPII, and redact each match to a labeled placeholder (`[REDACTED_API_KEY]`,`[REDACTED_TOKEN]`, `[REDACTED_EMAIL]`):-- OpenAI-style keys (`sk-…`), GitHub tokens (`ghp_…`), AWS access-key ids- (`AKIA…`), bearer/authorization tokens, and long high-entropy hex or base64- blobs.+- Vendor-prefixed keys (`sk-…`, `ghp_…`, `AKIA…`/`ASIA…`, `AIza…`,+ `sk_live_…`, `glpat-…`, `npm_…`, `hf_…`), format-only credentials with NO+ prefix (JWTs `eyJ….eyJ….…`, account SIDs, connection strings with an inline+ password), bearer/authorization tokens, PEM private-key blocks, and+ `KEY=`/`TOKEN=`/`PASSWORD=` assignments whose value is high-entropy.- Personal data the transcript wasn't meant to publish: phone numbers, homeaddresses, government ids, private emails.@@ -400,9 +409,12 @@ This skill guarantees:`conversations/<provider>/YYYY-MM-DD-<slug>.md` with `type: conversation`,a `date:` frontmatter field, and a verbatim transcript in aparser-recognized message format.-- Every conversation is scanned for secret-shaped strings and PII before its- page is written; matches are redacted to labeled placeholders and counted in- the import receipt (untrusted-content convention).+- Every conversation is scanned for secret-shaped strings (by wire format,+ not just vendor prefix — JWTs, cloud/API key shapes, connection-string+ credentials, high-entropy assignments) and PII before its page is written;+ matches are redacted to labeled placeholders and counted in the import+ receipt (untrusted-content convention). A page that still captured a+ secret is removed immediately with `gbrain delete <slug> --purge`.- Colliding slugs (untitled/same-day threads) are disambiguated with a shortstable thread hash and check-before-write, never overwritten.- Every import run validates a sample via `gbrain conversation-parser scan`diff --git a/plugin/skills/minion-orchestrator/SKILL.md b/plugin/skills/minion-orchestrator/SKILL.mdindex 801e372b82..9db10818a6 100644--- a/plugin/skills/minion-orchestrator/SKILL.md+++ b/plugin/skills/minion-orchestrator/SKILL.md@@ -117,9 +117,12 @@ tasks where no LLM reasoning loop is needed.### Preconditions (read before submitting your first shell job)-- **`GBRAIN_ALLOW_SHELL_JOBS=1` must be set on the worker environment.**- Without it, the shell handler refuses to register and submissions sit in- `waiting` silently. Gate lives in `src/core/minions/handlers/shell.ts`.+- **The worker must be started with `gbrain jobs work --allow-shell-jobs`** (equivalently `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker; a `.env` in the worker's directory cannot set it).+ The shell handler is always registered but guarded: an unflagged worker that+ claims a shell job dead-letters it immediately (`UnrecoverableError`, straight+ to `dead`, no retries) with the flag named in `error_text`. A job that sits in+ `waiting` means NO worker is running at all — check+ `gbrain jobs supervisor status`. Gate lives in `src/core/minions/handlers/shell.ts`.- **Security:** flipping `GBRAIN_ALLOW_SHELL_JOBS=1` authorizes arbitrarycommand execution on the worker. On a shared queue, this is a remote codeexecution surface. Treat as privileged infrastructure authorization.@@ -314,7 +317,8 @@ bare background shell except this skill saying don't.### Rung 1 — Minion job + deadman (Postgres + worker)Requires: Postgres engine, a running `gbrain jobs work` worker, and — for-the shell lane — `GBRAIN_ALLOW_SHELL_JOBS=1` on the worker. All the+the shell lane — a worker started with `--allow-shell-jobs` (or+`GBRAIN_ALLOW_SHELL_JOBS=1` exported on it). All thePreconditions above still hold: the flag defaults OFF, shell submission isCLI-only across the MCP trust boundary, and PGLite has no worker daemon(see Rung 3). Nothing in this section loosens that contract.diff --git a/scripts/check-compile-autoload.sh b/scripts/check-compile-autoload.shnew file mode 100755index 0000000000..cb1f426f47--- /dev/null+++ b/scripts/check-compile-autoload.sh@@ -0,0 +1,64 @@+#!/usr/bin/env bash+# CI guard: every `bun build --compile` invocation must carry+# `--no-compile-autoload-bunfig`.+#+# Why: a compiled Bun binary auto-loads a `bunfig.toml` from the CURRENT+# DIRECTORY at startup and runs its `preload` scripts BEFORE any of the+# binary's own code — before cli-preflight.ts, before the cwd-.env quarantine.+# gbrain is a globally installed CLI that runs from arbitrary checkouts, so a+# hostile repository carrying `bunfig.toml` + `preload = ["./x.ts"]` would get+# code execution from a plain `gbrain --version` (verified on Bun 1.3.13). The+# flag makes a cwd bunfig.toml inert for the compiled binary. The dev runtime+# (`bun src/cli.ts`) stays bun-native: a contributor's cwd is trusted.+#+# Invocation shapes checked (one line each):+# (a) shell / YAML / markdown: `bun build --compile … --outfile …`+# (b) TS/JS spawn arrays: ['build', '--compile', …] / ["build", "--compile", …]+# Prose that merely names `bun build --compile` (no --outfile) is not an+# invocation and is ignored.+#+# Scan set: package.json, CLAUDE.md, CONTRIBUTING.md, .github/, scripts/, docs/+# (relative to the guard root). test/ compile helpers are deliberately out of+# scope here — they build throwaway binaries run from temp dirs.+#+# Self-test seam: GBRAIN_GUARD_ROOT (fixture tree root) — guard-self-test.sh+# runs this against test/fixtures/guards/check-compile-autoload.sh/{bad,good}.+#+# Usage: scripts/check-compile-autoload.sh+# Exit: 0 when every invocation carries the flag, 1 otherwise.++set -uo pipefail++ROOT="${GBRAIN_GUARD_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"+cd "$ROOT" || exit 1++FLAG='--no-compile-autoload-bunfig'+SELF="scripts/$(basename "$0")"++TARGETS=()+for t in package.json CLAUDE.md CONTRIBUTING.md .github scripts docs; do+ [ -e "$t" ] && TARGETS+=("$t")+done+if [ "${#TARGETS[@]}" -eq 0 ]; then+ echo "FAIL: nothing to scan under $ROOT (expected package.json / .github / scripts / docs)" >&2+ exit 1+fi++# (a) one-line CLI invocation: `bun build --compile` followed later on the line by `--outfile`+# (b) spawn-array form: 'build', '--compile' (either quote style, optional whitespace)+SHAPE_A='bun build --compile[^`]*--outfile'+SHAPE_B="['\"]build['\"],[[:space:]]*['\"]--compile['\"]"++hits="$(grep -rnE --exclude="$(basename "$SELF")" -e "$SHAPE_A" -e "$SHAPE_B" "${TARGETS[@]}" 2>/dev/null | grep -v -- "$FLAG" || true)"++if [ -n "$hits" ]; then+ echo "ERROR: bun build --compile invocation(s) without $FLAG:" >&2+ echo "$hits" >&2+ echo >&2+ echo " A compiled binary auto-loads a cwd bunfig.toml and runs its preload scripts" >&2+ echo " before any gbrain code. Add $FLAG to every compile invocation" >&2+ echo " (CLI form: right after --compile; spawn arrays: as the element after '--compile')." >&2+ exit 1+fi++echo "OK: every bun build --compile invocation carries $FLAG"diff --git a/scripts/check-image-decoders-embedded.sh b/scripts/check-image-decoders-embedded.shindex 2df52d756d..c10fcab2b1 100755--- a/scripts/check-image-decoders-embedded.sh+++ b/scripts/check-image-decoders-embedded.sh@@ -20,7 +20,7 @@ cd "$REPO_ROOT"OUT_BIN="$(mktemp /tmp/gbrain-img-decoders-check.XXXXXX)"trap 'rm -f "$OUT_BIN"' EXIT-bun build --compile --outfile "$OUT_BIN" scripts/image-decoders-smoketest.ts >/dev/null 2>&1+bun build --compile --no-compile-autoload-bunfig --outfile "$OUT_BIN" scripts/image-decoders-smoketest.ts >/dev/null 2>&1OUTPUT="$("$OUT_BIN" 2>&1 || true)"diff --git a/scripts/check-pglite-embedded.sh b/scripts/check-pglite-embedded.shindex a41f210c01..05e1d9d110 100755--- a/scripts/check-pglite-embedded.sh+++ b/scripts/check-pglite-embedded.sh@@ -46,7 +46,7 @@ ln -s "$REPO_ROOT/node_modules" "$BUILD_DIR/node_modules"# Compile a focused smoketest (imports PGLiteEngine, not the whole CLI) so the# failure mode is laser-focused on PGLite asset embedding, not unrelated wiring.-if ! (cd "$BUILD_DIR" && bun build --compile --outfile "$OUT_BIN" scripts/pglite-embedded-smoketest.ts >"$BUILD_DIR/compile.log" 2>&1); then+if ! (cd "$BUILD_DIR" && bun build --compile --no-compile-autoload-bunfig --outfile "$OUT_BIN" scripts/pglite-embedded-smoketest.ts >"$BUILD_DIR/compile.log" 2>&1); then# In some sandboxes `bun build --compile` is unavailable (no network for the# baseline download, seccomp, etc). Fail SOFT there — like the compiled-binary# e2e — so local dev without compile support isn't blocked. CI has compile.diff --git a/scripts/check-wasm-embedded.sh b/scripts/check-wasm-embedded.shindex fdeafd10d5..7e1b4a4d81 100755--- a/scripts/check-wasm-embedded.sh+++ b/scripts/check-wasm-embedded.sh@@ -34,7 +34,7 @@ ln -s "$REPO_ROOT/node_modules" "$BUILD_DIR/node_modules"# Build a minimal smoketest binary that imports the chunker. We compile this# instead of the full gbrain CLI so the failure mode is laser-focused on# chunker + WASM path resolution, not unrelated CLI wiring.-if ! (cd "$BUILD_DIR" && bun build --compile --outfile "$OUT_BIN" scripts/chunker-smoketest.ts >/dev/null); then+if ! (cd "$BUILD_DIR" && bun build --compile --no-compile-autoload-bunfig --outfile "$OUT_BIN" scripts/chunker-smoketest.ts >/dev/null); thenecho "[check-wasm-embedded] FAIL: bun could not compile the smoketest binary." >&2exit 1fidiff --git a/scripts/dx-explore.ts b/scripts/dx-explore.tsindex 0d2c547fff..5c2bb4ecd3 100644--- a/scripts/dx-explore.ts+++ b/scripts/dx-explore.ts@@ -187,7 +187,7 @@ function ensureGbrainBinary(explicit: string | undefined, rebuild: boolean): str}fs.mkdirSync(binDir, { recursive: true });log('compiling gbrain (bun build --compile)…');- const res = spawnSync('bun', ['build', '--compile', '--outfile', binPath, 'src/cli.ts'], {+ const res = spawnSync('bun', ['build', '--compile', '--no-compile-autoload-bunfig', '--outfile', binPath, 'src/cli.ts'], {cwd: REPO_ROOT,encoding: 'utf8',timeout: 300_000,diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex b1d8cd4c68..21b42a297d 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -46,6 +46,7 @@ check-key-files-current-state.sh scanner todocheck-exports-count.sh scanner todo was reachable from neither verify nor CI pre-W0 (check:all only)check-trailing-newline.sh scanner todo was reachable from neither verify nor CI pre-W0 (check:all only)check-test-isolation.sh scanner todo allowlist data file: check-test-isolation.allowlist+check-compile-autoload.sh scanner yes every `bun build --compile` invocation (CLI one-liners + TS spawn arrays) in package.json/.github/scripts/docs/CLAUDE.md/CONTRIBUTING.md must carry --no-compile-autoload-bunfig (a cwd bunfig.toml preload runs before cli-preflight in a compiled binary)check-admin-build.sh buildfresh exempt runs the admin build; the build is the testcheck-admin-embedded.sh buildfresh exempt embed freshness diff; not in verify CHECKS: duplicates check:admin-build's buildcheck-admin-scope-drift.sh buildfresh exempt regenerates + diffsdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 726e313fd9..2daabd8cc9 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,13 +3,13 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 4088 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; +1 host-only call refusal hint (#5102)+src/cli.ts 4078 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wavesrc/commands/autopilot.ts 2671 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loopsrc/commands/doctor.ts 4641 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-upsrc/commands/embed.ts 2147 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment)src/commands/extract-conversation-facts.ts 2105 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failedsrc/commands/extract.ts 2643 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges-src/commands/jobs.ts 3189 ratchet +3 #4786 x #2139 pre-landing: sync handler gates embed-backfill on syncProducedEmbeddableContent (no_new_content skip reason); grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); +12 global freshness excludes explicit incomplete children and deferred maintenance+src/commands/jobs.ts 3202 ratchet +3 #4786 x #2139 pre-landing: sync handler gates embed-backfill on syncProducedEmbeddableContent (no_new_content skip reason); grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); +10 GHSA wave v0.50.5.0: `jobs work --allow-shell-jobs` flag parse re-asserting GBRAIN_ALLOW_SHELL_JOBS after the cwd-.env quarantine, help row, starvation hint prefers the flag; +3 pre-landing review A5: run-child re-asserts GBRAIN_ALLOW_SHELL_JOBS from the --allow-shell-jobs flag buildChildArgs passes; re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wavesrc/commands/serve-http.ts 3382 ratchet lowered to the merged line count after master v0.50.0.0 shrank the file; +20 #4866: RFC 9728 PRM resource=/mcp + root-path alias rewrite; grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helper; +15: metrics wiring — tracker mount + admin-gated /metrics route, helpers live in serve-http-metrics.ts (#3893); +7 test-gap wave C6: adminAuthRateLimiter on admin login + magic-link issuance, 429 JSON envelope; +29 ambient-writeback: per-request buildMcpInstructions (writeback bundle + write-scope gate + allowed-ops extract_facts probe); +6 adversarial fix wave: remember-op bound-client fence probe gates the ambient section; +2 #4748: startup resolveMcpInstructions (deployment identity) threaded into the per-request MCP server | merged v0.48.1.0: master #4788 writeback resolve + wave #4748 identity; master: | merged v0.48.1.0 true-up; +40 #4955: trackServerSockets() holds accepted sockets via WeakRef — Bun never emits socket close on server-side sockets, so the strong Set retained one socket per connection forever; +19 pre-landing review: bounded close() backstop in waitForHttpServerLifecycle (WeakRef-collected keep-alive wrappers leave native handles close() waits on); +10 pre-landing review r2: a close() error landing after the deadline is logged, not droppedsrc/core/ai/gateway.ts 4914 ratchet +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback)src/commands/sync.ts 5967 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed@@ -20,10 +20,10 @@ src/core/engine.ts 2645 ratchet grown v0.46.26.0 megawave: relational/visibilitysrc/core/import-file.ts 2332 ratchet +3 pre-landing review: refreshSourcePath short-circuits on the getPage-projected source_path (no per-unchanged-file UPDATE); re-summed to the merged line count after merging master v0.50.0.0 with the wave; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); +24 #4588: refreshSourcePath heals a drifted source_path on the import skip path; +48 transactional write-through and post-persistence embedding; +4 typed deferred completion lets page-owned locks release before enrichment; +2 verify the indexed revision before canonical publicationsrc/core/migrate.ts 712 region-exempt runner-region count re-summed after merging master v0.50.0.0 with the wave; append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); +19 (#4613: links_link_source_check every-pass self-heal wiring, logic lives in link-source-check-repair.ts); +3 (#4613 pre-landing review: ledger gate >= v114 around the self-heal)src/core/operations.ts 321 ratchet 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-src/core/pglite-engine.ts 6126 ratchet re-summed to the merged line count after merging master v0.50.0.0 with the wave; +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity-src/core/postgres-engine.ts 5590 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); +13: #4558 migrateFactsToCanonical row_num offset past canonical MAX+src/core/pglite-engine.ts 6127 ratchet re-summed to the merged line count after merging master v0.50.0.0 with the wave; +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; +1 GHSA wave v0.50.5.0: getRawData where.push(p.deleted_at IS NULL) unless includeDeleted (parity twin)+src/core/postgres-engine.ts 5591 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); +13: #4558 migrateFactsToCanonical row_num offset past canonical MAX; +1 GHSA wave v0.50.5.0: getRawData `alive` fragment (AND p.deleted_at IS NULL unless includeDeleted) folded into the six branchessrc/core/search/hybrid.ts 3306 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call-src/core/types.ts 2126 ratchet +2 pre-landing review: Page.source_path (getPage projection feeds the import skip-path short-circuit); +6 #5004: safe_index_pending degraded stage + doc; +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+src/core/types.ts 2126 ratchet +2 pre-landing review: Page.source_path (getPage projection feeds the import skip-path short-circuit); +6 #5004: safe_index_pending degraded stage + doc; +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; +2 GHSA wave v0.50.5.0: PageReadScope.includeDeleted so getRawData follows the page soft-delete with an explicit opt-in; lowered to 2126: pre-landing review C6 narrowed includeDeleted to the getRawData signature (off PageReadScope)src/core/minions/queue.ts 2484 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 enforcedsrc/commands/init.ts 2050 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 normalized ZE provider check; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only initsrc/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -36,8 +36,8 @@ src/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1560 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment)src/commands/hook.ts 1881 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name bankingsrc/core/chunkers/code.ts 1582 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES-src/core/config.ts 1843 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); +1 schema_pack key registration (#5104)+src/core/config.ts 1794 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wavesrc/core/bootstrap/harness.ts 2443 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched)src/core/oauth-provider.ts 1235 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies-src/core/ops/pages.ts 1484 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression+src/core/ops/pages.ts 1522 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; +23 GHSA wave v0.50.5.0: delete_page `purge` param (strict boolean, trusted-local only, remote -> permission_denied, non-boolean -> invalid_params), purge branches, dry-run action, hint text, purged responses carry a residuals hint; +21 review cycle 4 (O4-2): purge retries the artifact removal on the already-soft-deleted path (tombstone-resolved recorded path) and fails closed with storage_error when the file cannot be removed (assertPurgeArtifactGone, both purge paths); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wavesrc/core/search/mode.ts 1756 ratchet +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twicediff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex e8ade0f35b..e0259542b9 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -123,6 +123,8 @@ CHECKS=(# Containment sprint: module-size ratchet + structural-suite freshness."check:module-size""check:structural-manifest"+ # v0.50.5.0 security wave: compiled binaries must not autoload a cwd bunfig.toml.+ "check:compile-autoload")if [ "${#CHECKS[@]}" -eq 0 ]; thendiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 7a6060e1af..16cd8f9e07 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -139,6 +139,7 @@ test/e2e/openclaw-reference-compat.test.ts OpenClaw reference workspace compat (test/e2e/skillpack-flow.test.ts skillpack flow (E2E) 17 readFileSynctest/e2e/workspace-generic-compat.test.ts generic agent-workspace compat (INSTALL_FOR_AGENTS.md flow) 6 readFileSynctest/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistency wiring (T6) 4 doctor-source-helper+test/env-trust-protected-keys.test.ts CWD_DOTENV_PROTECTED_KEYS covers every suspicious GBRAIN_* env read in src/ 3 readFileSynctest/eval-brainbench-e2e.slow.test.ts --llm availability gate 1 exec-scantest/eval-brainbench-e2e.slow.test.ts privacy guard violation branches (negative path) 1 exec-scantest/eval-brainbench-e2e.slow.test.ts render-brainbench-delta.ts (the CI step-summary block) 2 exec-scan@@ -177,6 +178,8 @@ test/fix-wave-structural.test.ts v0.42.43.0 #2095 — volunteer-events sink + cytest/frontmatter-install-hook.test.ts frontmatter install-hook (B13) 22 readFileSynctest/harness-onboarding.test.ts harness identity and private handoff 5 readFileSynctest/hook-command.serial.test.ts user-prompt 14 readFileSync+test/hook-push-spawn-env.test.ts spawnDetachedPush env handoff 2 readFileSync+test/hook-push-spawn-env.test.ts tryExecAsync env handoff 1 readFileSynctest/integrations-install.test.ts installRecipeIntoHostRepo — happy path 6 readFileSynctest/integrations.test.ts CLI integration 3 readFileSynctest/jobs-embed-background-parity.serial.test.ts embed job background parity (D7) 2 readFileSyncdiff --git a/skills/bulk-ingestion/MANIFEST-PATTERN.md b/skills/bulk-ingestion/MANIFEST-PATTERN.mdindex d7ec52d496..31da771d82 100644--- a/skills/bulk-ingestion/MANIFEST-PATTERN.md+++ b/skills/bulk-ingestion/MANIFEST-PATTERN.md@@ -193,7 +193,8 @@ a recurring shell job shaped like:gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && git add projects/<pipeline-name> <output-dirs> && git commit -m \"<pipeline-name> ingest checkpoint\" && git push"}'```-Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see+Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`+(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — seeminion-orchestrator Preconditions. Do not set it yourself: it is an RCE-classauthorization that belongs to the operator running the daemon, and a submit-sideenv prefix (`GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit ...`) is a no-op indiff --git a/skills/bulk-ingestion/SKILL.md b/skills/bulk-ingestion/SKILL.mdindex d484c8dbbe..b498ed8db4 100644--- a/skills/bulk-ingestion/SKILL.md+++ b/skills/bulk-ingestion/SKILL.md@@ -283,7 +283,8 @@ gbrain jobs submit shell --params '{"cmd": "<your pipeline command> --offset 0 -gbrain agent run "Read skills/<pipeline-name>/SKILL.md and process the next 50 pending manifest items"```-Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see+Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`+(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — seeminion-orchestrator Preconditions; do not set it yourself (it is an RCE-classoperator authorization, and a submit-side env prefix is a no-op in the daemonlane). Small sets (<1000 items) can run inline in chunks; anything that mustdiff --git a/skills/conversation-archive/SKILL.md b/skills/conversation-archive/SKILL.mdindex ccd6e1458a..4e468718e1 100644--- a/skills/conversation-archive/SKILL.md+++ b/skills/conversation-archive/SKILL.md@@ -81,11 +81,18 @@ fingerprint — running with a different cap (or dropping it) starts a freshwatermark scope, so a capped run's skipped tail is never mistaken foralready-scanned.-Native-vs-manual delta to know: the native lane redacts SECRETS (key-patterns) plus your `~/.gbrain/harvest-private-patterns.txt` regexes and-counts agent-directed imperatives into frontmatter, but broad PII detection-(names, phones, addresses) remains YOUR review pass — the manual procedure's-human scrub step still applies to sensitive corpora. Two more deltas: the+Native-vs-manual delta to know: the native lane redacts SECRETS by FORMAT+(vendor key prefixes, JWTs, cloud/API key shapes, `Bearer` headers,+connection strings carrying inline passwords, PEM private keys, and+high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignments) plus your+`~/.gbrain/harvest-private-patterns.txt` regexes and counts agent-directed+imperatives into frontmatter, but broad PII detection (names, phones,+addresses) remains YOUR review pass — the manual procedure's human scrub step+still applies to sensitive corpora. Preview what will be scrubbed with+`--dry-run` before a bulk `--all`. If a secret still reached a page, rotate+it first, then remove the page immediately with+`gbrain delete <slug> --purge` (local CLI only — no 72h tombstone); the+brain-repo git history or a synced file may still hold it. Two more deltas: thenative lane caps each message at ~4K characters in the page body (readablearchive, not verbatim — the session file named in `source_uri` stays theverbatim record), and tool/thinking traffic appears only as one-line@@ -141,9 +148,11 @@ Before writing each page, scan the transcript for secret-shaped strings andPII, and redact each match to a labeled placeholder (`[REDACTED_API_KEY]`,`[REDACTED_TOKEN]`, `[REDACTED_EMAIL]`):-- OpenAI-style keys (`sk-…`), GitHub tokens (`ghp_…`), AWS access-key ids- (`AKIA…`), bearer/authorization tokens, and long high-entropy hex or base64- blobs.+- Vendor-prefixed keys (`sk-…`, `ghp_…`, `AKIA…`/`ASIA…`, `AIza…`,+ `sk_live_…`, `glpat-…`, `npm_…`, `hf_…`), format-only credentials with NO+ prefix (JWTs `eyJ….eyJ….…`, account SIDs, connection strings with an inline+ password), bearer/authorization tokens, PEM private-key blocks, and+ `KEY=`/`TOKEN=`/`PASSWORD=` assignments whose value is high-entropy.- Personal data the transcript wasn't meant to publish: phone numbers, homeaddresses, government ids, private emails.@@ -400,9 +409,12 @@ This skill guarantees:`conversations/<provider>/YYYY-MM-DD-<slug>.md` with `type: conversation`,a `date:` frontmatter field, and a verbatim transcript in aparser-recognized message format.-- Every conversation is scanned for secret-shaped strings and PII before its- page is written; matches are redacted to labeled placeholders and counted in- the import receipt (untrusted-content convention).+- Every conversation is scanned for secret-shaped strings (by wire format,+ not just vendor prefix — JWTs, cloud/API key shapes, connection-string+ credentials, high-entropy assignments) and PII before its page is written;+ matches are redacted to labeled placeholders and counted in the import+ receipt (untrusted-content convention). A page that still captured a+ secret is removed immediately with `gbrain delete <slug> --purge`.- Colliding slugs (untitled/same-day threads) are disambiguated with a shortstable thread hash and check-before-write, never overwritten.- Every import run validates a sample via `gbrain conversation-parser scan`diff --git a/skills/minion-orchestrator/SKILL.md b/skills/minion-orchestrator/SKILL.mdindex 801e372b82..9db10818a6 100644--- a/skills/minion-orchestrator/SKILL.md+++ b/skills/minion-orchestrator/SKILL.md@@ -117,9 +117,12 @@ tasks where no LLM reasoning loop is needed.### Preconditions (read before submitting your first shell job)-- **`GBRAIN_ALLOW_SHELL_JOBS=1` must be set on the worker environment.**- Without it, the shell handler refuses to register and submissions sit in- `waiting` silently. Gate lives in `src/core/minions/handlers/shell.ts`.+- **The worker must be started with `gbrain jobs work --allow-shell-jobs`** (equivalently `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker; a `.env` in the worker's directory cannot set it).+ The shell handler is always registered but guarded: an unflagged worker that+ claims a shell job dead-letters it immediately (`UnrecoverableError`, straight+ to `dead`, no retries) with the flag named in `error_text`. A job that sits in+ `waiting` means NO worker is running at all — check+ `gbrain jobs supervisor status`. Gate lives in `src/core/minions/handlers/shell.ts`.- **Security:** flipping `GBRAIN_ALLOW_SHELL_JOBS=1` authorizes arbitrarycommand execution on the worker. On a shared queue, this is a remote codeexecution surface. Treat as privileged infrastructure authorization.@@ -314,7 +317,8 @@ bare background shell except this skill saying don't.### Rung 1 — Minion job + deadman (Postgres + worker)Requires: Postgres engine, a running `gbrain jobs work` worker, and — for-the shell lane — `GBRAIN_ALLOW_SHELL_JOBS=1` on the worker. All the+the shell lane — a worker started with `--allow-shell-jobs` (or+`GBRAIN_ALLOW_SHELL_JOBS=1` exported on it). All thePreconditions above still hold: the flag defaults OFF, shell submission isCLI-only across the MCP trust boundary, and PGLite has no worker daemon(see Rung 3). Nothing in this section loosens that contract.diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex ebb9c88873..47eb449bf8 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -27,8 +27,8 @@"brain-taxonomist/routing-eval.jsonl": "8b485b3d735aace60be703854f0f2e9d97c52d52564efdaf7334a0c39e8d20ae","briefing/SKILL.md": "f86ad2238104de20433436dcc8f2cc5534e7df8dad4e4845252f85b8290cde53","briefing/routing-eval.jsonl": "c056fea88f673e324d6a72cb70438cd6fcdbd09ec2cd036d44eb31a9ea6bf33d",- "bulk-ingestion/MANIFEST-PATTERN.md": "0df53fdf8b59bf14601761f6c1cce413bb494f0d5ebc3e6fa96feccfda7e5737",- "bulk-ingestion/SKILL.md": "bf23978d710d53884252b15f647212c7f59e7ca081b05aa2fb5a93941893f546",+ "bulk-ingestion/MANIFEST-PATTERN.md": "6180f09d2dc8d9af5749149f2b3c34c40213f5d6b262b69484e864adbb652b47",+ "bulk-ingestion/SKILL.md": "8149c1ff02b320b80c3850d5f837cbebbdc8e088b24da7da9a78046f919ba9aa","bulk-ingestion/routing-eval.jsonl": "2bf8ffaf90b8ef761fa3cef54bf3af2eb8cc3ef736d054b5bf8b9361f6448d5a","capture/SKILL.md": "98568ac96331f57397ea072749641d9748b1ce31e8b09d512b8db25c8fcda65f","chat-connectors/SKILL.md": "f0218cab53f7e82d1543ba8c6f574b39821ecae780219aa5d408586a00de8062",@@ -60,7 +60,7 @@"conventions/subagent-routing.md": "8b8830b815a9a8581a12b489f966c0b0a39eb9b5f66e905a691a03653eef348d","conventions/test-before-bulk.md": "6b2c52cda9e2cd5f04c15152b3d92aeb7187ab193a15082be0f8a3991a6a5725","conventions/untrusted-content.md": "259384d490892cd0e1e8e054decf752d7354f516c83aee57b332c1a96aac6a6e",- "conversation-archive/SKILL.md": "de2b44da329c4601da8c77536a627b094e52a93c8f45032335571b29b311d736",+ "conversation-archive/SKILL.md": "0d27c637f56fc10f8d27c1f0a02aedf70e2bac4355436e9f67f81b0bc120e3ba","conversation-archive/routing-eval.jsonl": "ae087a84b1fd5b108b7cdab8d035a09b3ccecd8aad53ba5f71e463059108cfca","correction-pipeline/SKILL.md": "caf1264b7afec46569d30f6d92b07f37ae375e3f4e6aeddd58866aec327053de","correction-pipeline/routing-eval.jsonl": "7f8d96606a8d7bed3d79fdcee6904764c8abb9fa0b506adb414b5c4805b69d0b",@@ -143,7 +143,7 @@"migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a","migrations/v0.9.0.md": "773fab0a8d7f330576265a3f510c1f318f47789b6136c46d43e08121acbc20eb","migrations/v0.9.1.md": "75761bad6c0ad37b69ec8197c6a678bb6a1484f9a76e4b70f2d1e86dc80102b3",- "minion-orchestrator/SKILL.md": "63e7ead284ae03f039e5789e1479d9e49d8897cb2cedf1663746c727d86fd3be",+ "minion-orchestrator/SKILL.md": "10686e03951d793cbdadfa9111325f05fabf27a4fa0c18894f4857288203dbaa","minion-orchestrator/routing-eval.jsonl": "501ed2e19cb16847ff8425219d246b7a774de1accd42cb28fd44edbb64204992","perplexity-research/SKILL.md": "c25f5c471cbe3c6e0f975d8397e8382b00a85f8aa75302231d53c52855369e97","perplexity-research/routing-eval.jsonl": "f1a40d87e710d5d2acd602a372d83f46c95da022b6e635228fffeaacb3bb2b27",diff --git a/src/cli.ts b/src/cli.tsindex 5dcdadbc99..f80b723f31 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -36,6 +36,7 @@ import type { Operation, OperationContext } from './core/operations.ts';import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery } from './core/cli-force-exit.ts';import { serializeMarkdown } from './core/markdown.ts';import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';+import { runCliPreflight } from './core/cli-preflight.ts';import { conceptNudge } from './core/search/query-intent.ts';import type { CliOptions } from './core/cli-options.ts';import { callRemoteTool, RemoteMcpError, unpackToolResult, extractResponseMeta } from './core/mcp-client.ts';@@ -449,6 +450,9 @@ function maybeEmitUpdateMarker(command: string): void {}async function main() {+ // cwd-.env quarantine → ~/.gbrain/.env → #3688 guardrails loader (fail-closed).+ await runCliPreflight();+// Parse global flags (--quiet / --progress-json / --progress-interval)// BEFORE command dispatch, so `gbrain --progress-json doctor` works.// The stripped argv is what the command sees.@@ -456,20 +460,6 @@ async function main() {const { cliOpts, rest: args } = parseGlobalFlags(rawArgs);setCliOptions(cliOpts);- // #3688: operator-configured guardrail providers load before ANY command- // dispatch. Fail-closed by design: when GBRAIN_GUARDRAILS_MODULE is set but- // broken, abort rather than silently run without the operator's firewall.- // (Unset → zero cost, the OSS distribution stays inert.)- if (process.env.GBRAIN_GUARDRAILS_MODULE) {- try {- const { loadGuardrailProvidersFromEnv } = await import('./core/guardrails.ts');- await loadGuardrailProvidersFromEnv();- } catch (err) {- console.error(`guardrails: ${(err as Error)?.message ?? String(err)}`);- process.exit(1);- }- }-let command = args[0];if (!command || command === '--help' || command === '-h') {diff --git a/src/commands/doctor/checks/core-health.ts b/src/commands/doctor/checks/core-health.tsindex 85373e1e7d..37c5b403b1 100644--- a/src/commands/doctor/checks/core-health.ts+++ b/src/commands/doctor/checks/core-health.ts@@ -44,10 +44,11 @@ export function resolveWhoknowsFixturePath(env: NodeJS.ProcessEnv = process.env,moduleUrl: string = import.meta.url,): string | null {- if (env.GBRAIN_WHOKNOWS_FIXTURE_PATH) {- return isAbsolute(env.GBRAIN_WHOKNOWS_FIXTURE_PATH)- ? env.GBRAIN_WHOKNOWS_FIXTURE_PATH- : resolvePath(process.cwd(), env.GBRAIN_WHOKNOWS_FIXTURE_PATH);+ // cwd-dotenv-ok: doctor test-fixture path override; the check only READS that jsonl, never loads or executes it.+ const override = env.GBRAIN_WHOKNOWS_FIXTURE_PATH;+ if (override) {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- override is the operator-set GBRAIN_WHOKNOWS_FIXTURE_PATH doctor test-fixture path (the check only READS that jsonl, never loads or executes it); absolutizing the operator's own relative path against the process cwd is the intent, unchanged from the pre-hoist form+ return isAbsolute(override) ? override : resolvePath(process.cwd(), override);}try {diff --git a/src/commands/doctor/checks/routing-federation.ts b/src/commands/doctor/checks/routing-federation.tsindex 9049d6eb52..26f817c8e1 100644--- a/src/commands/doctor/checks/routing-federation.ts+++ b/src/commands/doctor/checks/routing-federation.ts@@ -9,8 +9,18 @@ import type { BrainEngine } from '../../../core/engine.ts';import { gbrainPath } from '../../../core/config.ts';import { embedBackfillWorkerSurface } from '../../../core/minions/embed-backfill-admission.ts';import { isUndefinedTableError, isUndefinedColumnError } from '../../../core/utils.ts';+import { ALLOWED_SCOPES_LIST, DCR_REGISTRABLE_SCOPES } from '../../../core/scope.ts';import type { Check } from '../../doctor.ts';+/**+ * Scopes beyond the anonymous-DCR ceiling — DERIVED as the complement of+ * `DCR_REGISTRABLE_SCOPES` over `ALLOWED_SCOPES_LIST` (never hand-copied), so+ * a scope added to scope.ts is audited by arm (c) below automatically.+ */+export const DCR_PRIVILEGED_SCOPES: ReadonlyArray<string> = Object.freeze(+ ALLOWED_SCOPES_LIST.filter((s) => !DCR_REGISTRABLE_SCOPES.has(s)),+);+/*** v0.37.7.0 — Tier 5K source_routing_health (D5 lock: 200-page total cap).*@@ -264,7 +274,52 @@ export async function checkOauthClientScopeHealth(engine: BrainEngine): Promise<if (!(isUndefinedTableError(e) && /facts/i.test(msg))) throw e;orphaned = await engine.executeRaw<{ id: string }>(orphanSql(false), [WORKSPACE_SUFFIX]);}+ // (c) PRIVILEGED SELF-REGISTERED CLIENTS — an active row whose scope+ // exceeds the DCR ceiling (read/write) AND carries the anonymous-DCR+ // signature: grant_revision = 0 with no oauth_grant_audit 'register' row+ // (every operator path writes one). Nothing sweeps such rows on upgrade,+ // so this is the operator's visibility into clients that were registered+ // before the ceiling existed (or that predate the grant audit log — the+ // same signature, hence ADVISORY). Fail-open to "unknown" when the audit+ // table / revision column is absent: without them the signature cannot be+ // evaluated and guessing would either lie green or cry wolf.+ let privilegedDcr: Array<{ client_id: string; client_name: string | null; scope: string }> = [];+ let privilegedDcrNote: string | null = null;+ // Word-bounded match over the DERIVED complement (scope ids are [a-z_]+,+ // so the alternation needs no escaping); bound as a parameter, never+ // interpolated into the SQL text.+ const privilegedScopeRegex = `(^|[[:space:]])(${DCR_PRIVILEGED_SCOPES.join('|')})([[:space:]]|$)`;+ const dcrCeiling = [...DCR_REGISTRABLE_SCOPES];+ try {+ privilegedDcr = await engine.executeRaw<{ client_id: string; client_name: string | null; scope: string }>(+ `SELECT c.client_id, c.client_name, c.scope+ FROM oauth_clients c+ WHERE c.deleted_at IS NULL+ AND COALESCE(c.grant_revision, 0) = 0+ AND COALESCE(c.scope, '') ~ $1+ AND NOT EXISTS (+ SELECT 1 FROM oauth_grant_audit a+ WHERE a.client_id = c.client_id AND a.action = 'register'+ )+ ORDER BY c.client_id`,+ [privilegedScopeRegex],+ );+ } catch (e) {+ if (!(isUndefinedTableError(e) || isUndefinedColumnError(e, 'grant_revision'))) throw e;+ privilegedDcrNote = 'self-registered-client scope audit skipped: grant audit schema not present (run `gbrain apply-migrations --yes`), so privileged self-registered clients are unknown';+ }const problems: string[] = [];+ if (privilegedDcr.length > 0) {+ const shown = privilegedDcr.slice(0, 5)+ .map(c => `"${c.client_name ?? c.client_id}" (${c.client_id}) scope=${c.scope}`);+ problems.push(+ `${privilegedDcr.length} active OAuth client(s) hold a scope beyond the self-registration ceiling (${dcrCeiling.join('/')}) ` ++ `and look self-registered (no operator grant record): ${shown.join('; ')}` ++ (privilegedDcr.length > 5 ? ` (+${privilegedDcr.length - 5} more)` : '') ++ `. If you did not register these yourself, narrow with \`gbrain auth rescope-client <client_id> --scopes ${dcrCeiling.join(',')}\` ` ++ `or remove with \`gbrain auth revoke-client <client_id>\`.`,+ );+ }if (dangling.length > 0) {const byClient = new Map<string, { name: string | null; grants: string[] }>();for (const d of dangling) {@@ -298,7 +353,8 @@ export async function checkOauthClientScopeHealth(engine: BrainEngine): Promise<return {name: 'oauth_client_scope_health',status: 'ok',- message: 'Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources)',+ message: 'Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources' ++ (privilegedDcrNote ? `; ${privilegedDcrNote})` : ', no privileged self-registered clients)'),};} catch (e) {const msg = e instanceof Error ? e.message : String(e);diff --git a/src/commands/export.ts b/src/commands/export.tsindex da292c0183..f2efcb208a 100644--- a/src/commands/export.ts+++ b/src/commands/export.ts@@ -144,6 +144,7 @@ export async function runExport(engine: BrainEngine, args: string[]) {// page's own on a key collision.const rawData = await engine.getRawData(page.slug, undefined, {sourceId: page.source_id,+ includeDeleted: true, // the page list decides which rows export; raw follows its page});if (rawData.length > 0) {const slugParts = page.slug.split('/');diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 0dcc64a62f..ec35af924c 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -719,10 +719,10 @@ async function statusFileNotice(): Promise<string | null> {const HOOK_GIT_TIMEOUT_MS = 1000;/**- * Async execFile wrapper: the hook push paths must NEVER block the event- * loop with execFileSync — a slow repo/network would keep withDeadline's- * timer from ever firing and stall the harness for minutes. null on any- * failure (missing binary, non-zero exit, timeout).+ * Async execFile wrapper: hook push paths must NEVER block the event loop with+ * execFileSync (a slow repo/network would stall withDeadline's timer for minutes).+ * null on any failure (missing binary, non-zero exit, timeout). Explicit `env`:+ * git must see the cwd-.env quarantine (env-trust.ts), not Bun's startup snapshot.*/function tryExecAsync(bin: string, args: string[], timeoutMs = HOOK_GIT_TIMEOUT_MS): Promise<string | null> {return new Promise((resolve) => {@@ -730,7 +730,7 @@ function tryExecAsync(bin: string, args: string[], timeoutMs = HOOK_GIT_TIMEOUT_execFile(bin,args,- { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 },+ { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024, env: process.env },(err, stdout) => resolve(err ? null : stdout.toString().trim()),);} catch {@@ -813,7 +813,9 @@ function spawnDetachedPush(root: string): void {// Compiled binary: execPath IS gbrain. Dev (bun src/cli.ts): re-exec the// entrypoint — the jobs.ts --detach precedent.const argv = /[/\\]gbrain(\.exe)?$/.test(exec) ? pushArgs : [process.argv[1], ...pushArgs];- const child = spawn(exec, argv, { detached: true, stdio: 'ignore' });+ // Explicit env: a child spawned without one does not see the parent's+ // cwd-.env quarantine deletions (core/env-trust.ts).+ const child = spawn(exec, argv, { detached: true, stdio: 'ignore', env: process.env });child.unref();}diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex ebc25f0947..384f3ca94e 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -435,9 +435,9 @@ HANDLER TYPES (built in)extract Extract links + timeline entries; '{"mode":"all"}'backlinks Check or fix back-links; '{"action":"fix"}'autopilot-cycle One autopilot pass (sync+extract+embed+backlinks)- shell Run a command or argv. Requires GBRAIN_ALLOW_SHELL_JOBS=1- on the worker. Params: {cmd?, argv?, cwd, env?}.- See: docs/guides/minions-shell-jobs.md+ shell Run a command or argv. Requires --allow-shell-jobs (or+ GBRAIN_ALLOW_SHELL_JOBS=1) on the worker. Params: {cmd?,+ argv?, cwd, env?}. See: docs/guides/minions-shell-jobs.mdDetailed help: gbrain jobs {work|supervisor|submit|watch|prune} --helpOther subcommands are fully described above.@@ -456,10 +456,13 @@ const JOBS_SUBCOMMAND_HELP: Record<string, string> = {USAGEgbrain jobs work [--queue Q] [--concurrency N] [--max-rss MB][--health-interval MS] [--nice N]- [--job-isolation inline|process]+ [--job-isolation inline|process] [--allow-shell-jobs]OPTIONS--queue Q Queue to claim from (default: default)+ --allow-shell-jobs Enable the shell handler on this worker. Equivalent to+ exporting GBRAIN_ALLOW_SHELL_JOBS=1 from your shell; a+ .env in the working directory cannot set it.--job-isolation M inline (default): handlers run in the worker process.process: each claimed job runs in its own childprocess — a stuck handler is group-SIGKILLed instead@@ -811,18 +814,19 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):} catch { /* audit failures never block submission */ }// Starvation warning (DX polish). Fire for every non-`--follow` shell submit- // regardless of the submitter's own `GBRAIN_ALLOW_SHELL_JOBS` — the submitter- // env is a weak proxy for the worker env (they may run on different machines),- // so the warning remains useful any time the job might sit in 'waiting'.+ // regardless of the submitter's own `GBRAIN_ALLOW_SHELL_JOBS` — submitter env+ // is a weak proxy for worker env. Two outcomes: no worker → the job waits;+ // an UNFLAGGED worker → the always-registered guarded handler dead-letters it.if (!follow && name === 'shell') {process.stderr.write(- `\n⚠ Shell jobs require GBRAIN_ALLOW_SHELL_JOBS=1 on the worker process.\n` +- ` Your job was queued (id=${job.id}) but will sit in 'waiting' until a\n` +- ` worker with the env flag starts. To run now:\n\n` ++ `\n⚠ Shell jobs require the shell handler enabled on the worker process\n` ++ ` (--allow-shell-jobs, or GBRAIN_ALLOW_SHELL_JOBS=1 exported from your shell).\n` ++ ` Your job was queued (id=${job.id}). It waits until a worker starts; a worker\n` ++ ` WITHOUT shell jobs enabled dead-letters it immediately (no retries). To run now:\n\n` +` GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit shell \\\n` +` --params '...' --follow\n\n` +` Or start a persistent worker (Postgres only — PGLite uses --follow):\n\n` +- ` GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work\n\n`,+ ` gbrain jobs work --allow-shell-jobs\n\n`,);}@@ -1483,6 +1487,9 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):// exit. Deliberately absent from user-facing help. The CLI layer owns// engine.disconnect() + process.exit() (engine-ownership invariant).{+ // --allow-shell-jobs (buildChildArgs pass-through): same re-assert as+ // `work` — this child's preflight re-ran the cwd-.env quarantine.+ if (hasFlag(args, '--allow-shell-jobs')) process.env.GBRAIN_ALLOW_SHELL_JOBS = '1';const config = loadConfig();if (config?.engine === 'pglite') {console.error('[run-child] process isolation requires the Postgres engine.');@@ -1538,6 +1545,12 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):process.exit(1);}+ // --allow-shell-jobs (supervisor pass-through, see buildWorkerArgs): the+ // startup cwd-.env quarantine drops GBRAIN_ALLOW_SHELL_JOBS when a .env+ // in this worker's cwd assigns it, so the flag re-asserts the operator's+ // opt-in AFTER preflight. Read sites keep checking the env var.+ if (hasFlag(args, '--allow-shell-jobs')) process.env.GBRAIN_ALLOW_SHELL_JOBS = '1';+const queueName = parseFlag(args, '--queue') ?? 'default';const concurrency = resolveWorkerConcurrency(args);// --max-rss: explicit value wins (including 0 to disable the watchdog).@@ -1987,7 +2000,7 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):healthInterval = parsed;}const allowShellJobs = hasFlag(args, '--allow-shell-jobs') ||- !!process.env.GBRAIN_ALLOW_SHELL_JOBS;+ process.env.GBRAIN_ALLOW_SHELL_JOBS === '1'; // same literal the shell handler checksconst detach = hasFlag(args, '--detach');// Supervisor's --max-rss: explicit wins; absent → cgroup-aware auto-size// (issue #1678). The supervisor is the main production path, so the@@ -2816,17 +2829,17 @@ export async function registerBuiltinHandlers(};});- // Shell handler is always registered. Runtime env guard lives inside the- // handler so claimed jobs emit a clear rejection log on workers missing- // GBRAIN_ALLOW_SHELL_JOBS=1.+ // Shell handler is always registered. Runtime guard lives inside the handler+ // so claimed jobs emit a clear rejection log on workers started without+ // --allow-shell-jobs (the flag sets GBRAIN_ALLOW_SHELL_JOBS=1 after preflight).{const { shellHandler } = await import('../core/minions/handlers/shell.ts');worker.register('shell', shellHandler);if (!quiet) {if (process.env.GBRAIN_ALLOW_SHELL_JOBS === '1') {- process.stderr.write('[minion worker] shell handler enabled (GBRAIN_ALLOW_SHELL_JOBS=1)\n');+ process.stderr.write('[minion worker] shell handler enabled (--allow-shell-jobs / GBRAIN_ALLOW_SHELL_JOBS=1)\n');} else {- process.stderr.write('[minion worker] shell handler registered in guarded mode (set GBRAIN_ALLOW_SHELL_JOBS=1 to execute shell jobs)\n');+ process.stderr.write('[minion worker] shell handler registered in guarded mode (start with `gbrain jobs work --allow-shell-jobs`, or export GBRAIN_ALLOW_SHELL_JOBS=1, to execute shell jobs)\n');}}}diff --git a/src/commands/migrate-engine.ts b/src/commands/migrate-engine.tsindex c4b2bab3ec..47d70b34ce 100644--- a/src/commands/migrate-engine.ts+++ b/src/commands/migrate-engine.ts@@ -551,8 +551,9 @@ export async function copyPageToTarget(}, sourceOpts);}- // Copy raw data- const rawData = await source.getRawData(page.slug, undefined, sourceOpts);+ // Copy raw data (includeDeleted: a migration copies whatever the page row+ // carries — the page list already decided which rows travel).+ const rawData = await source.getRawData(page.slug, undefined, { ...sourceOpts, includeDeleted: true });for (const rd of rawData) {await target.putRawData(page.slug, rd.source, rd.data, sourceOpts);}diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex f69df61833..a7817d4990 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -49,7 +49,7 @@ import {dcrRegistrationContext,DEFAULT_DCR_TTL_MIN_SECONDS,} from '../core/oauth-provider.ts';-import { hasScope, ALLOWED_SCOPES_LIST, normalizeScopesInput } from '../core/scope.ts';+import { hasScope, scopesSupportedForDiscovery, normalizeScopesInput } from '../core/scope.ts';import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';import { normalizeSourceInput, normalizeFederatedReadInput } from '../core/source-id.ts';import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult } from '../mcp/dispatch.ts';@@ -993,15 +993,15 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// logs, not buried in the neutral "DCR: enabled" banner line.if (enableDcr) {console.error(- 'SECURITY WARNING: Dynamic Client Registration (--enable-dcr) is ON. ' +- 'Any network caller can self-register an OAuth client. DCR clients default ' +- 'to the authorization_code (consent-bearing) grant. See SECURITY.md.',+ 'SECURITY WARNING: Dynamic Client Registration (--enable-dcr) is ON. Any network caller ' ++ 'can self-register an OAuth client, limited to read/write (read-only for client_credentials ' ++ 'under --enable-dcr-insecure); every authorization_code connection needs owner approval in the admin UI. See SECURITY.md.',);if (enableDcrInsecure) {console.error(- 'SECURITY WARNING: --enable-dcr-insecure is ON — self-registered DCR ' +- 'clients may request the client_credentials grant, which BYPASSES the ' +- '/authorize consent screen. Only use this on a trusted network.',+ 'SECURITY WARNING: --enable-dcr-insecure is ON — self-registered DCR clients may ' ++ 'request the client_credentials grant, which BYPASSES owner approval (they are capped ' ++ 'at read-only scope). Only use this on a trusted network.',);}}@@ -1216,7 +1216,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionconst authRouterOptions: any = {provider: oauthProvider,issuerUrl,- scopesSupported: ALLOWED_SCOPES_LIST.filter(scope => scope !== 'agent'),+ scopesSupported: scopesSupportedForDiscovery({ enableDcr }),resourceName: 'GBrain MCP Server',// Advertise /mcp as the protected resource (see mcpResourceUrl above).resourceServerUrl: mcpResourceUrl,@@ -3319,7 +3319,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption║ Engine: ${(config.engine || 'pglite').padEnd(40)}║║ Issuer: ${issuerUrl.origin.padEnd(40)}║║ Clients: ${String((clientCount[0] as any).count).padEnd(40)}║-║ DCR: ${(enableDcr ? (enableDcrInsecure ? 'enabled (INSECURE: client_credentials)' : 'enabled') : 'disabled').padEnd(40)}║+║ DCR: ${(enableDcr ? (enableDcrInsecure ? 'enabled (INSECURE: read-only M2M)' : 'enabled (consent; DCR max read write)') : 'disabled').padEnd(40)}║║ Skills: ${skillStatus.bannerValue.padEnd(40)}║║ Token TTL: ${(tokenTtl + 's').padEnd(40)}║╠══════════════════════════════════════════════════════╣diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 4dcab78fc3..2a1a965374 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -23,13 +23,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--background', '--brain', '--dir', '--explain', '--follow', '--help', '--into', '--json', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--verify'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],- 'book-mirror': ['--access', '--allow-empty', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],+ 'book-mirror': ['--access', '--allow-empty', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--purge', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-verify', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],'cache': ['--brain', '--help', '--json', '--source', '--yes'],- 'calibration': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],+ 'calibration': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--purge', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],'call': ['--brain', '--help', '--json', '--source'],- 'capture': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--depth', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--quiet', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--trusted-extraction', '--type', '--types', '--url', '--what', '--where', '--who', '--yes'],+ 'capture': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--depth', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--purge', '--quiet', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--trusted-extraction', '--type', '--types', '--url', '--what', '--where', '--who', '--yes'],'check-backlinks': ['--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],'check-update': ['--brain', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],@@ -45,19 +45,19 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'conversation-parser': ['--brain', '--help', '--json', '--source'],'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],- 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-unverified-remote', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embedding', '--no-hooks', '--no-migrate', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--restore-only', '--resume', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],+ 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embedding', '--no-hooks', '--no-migrate', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--restore-only', '--resume', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--include-null-signature', '--json', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to'],'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],- 'enrich': ['--access', '--allow-empty', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],+ 'enrich': ['--access', '--allow-empty', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--purge', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--markdown', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],'export': ['--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type'],'extract': ['--background', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--dry-run', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],'extract-conversation-facts': ['--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embedding', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--segment-limit', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--workers', '--yes'],'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--rebuild', '--refresh', '--repo', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],'files': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--yes'],- 'forget': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],+ 'forget': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--purge', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--get', '--git-common-dir', '--help', '--include-catch-all', '--json', '--name-only', '--no-verify', '--others', '--source', '--type', '--uninstall'],@@ -68,26 +68,26 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--purge', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--abort', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--explain', '--file', '--fix', '--follow', '--get', '--git-dir', '--git-path', '--help', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--safe', '--scope', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--federated-read', '--harness', '--help', '--if-version', '--install', '--json', '--limit', '--profile', '--queue', '--resume', '--root', '--source', '--timeout-ms', '--token-ttl', '--url'],'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-retry', '--force-sunset-target', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--locks', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--to'],'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--target-high', '--target-low', '--target-medium', '--to'],- 'onboard': ['--access', '--allow-empty', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--page', '--params', '--path', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--yes'],+ 'onboard': ['--access', '--allow-empty', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--page', '--params', '--path', '--purge', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--yes'],'orphans': ['--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--yes'],'post-upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--concurrency', '--cost-estimate', '--dim', '--embedding-dimensions', '--embedding-model', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--pglite', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--swap-only', '--target', '--to', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],- 'protocol': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],+ 'protocol': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--purge', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],'providers': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--to', '--touchpoint'],'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--markdown', '--no-embed', '--source', '--source-id', '--stale'],- 'recall': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],+ 'recall': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--purge', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],'reconcile-links': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],'reindex': ['--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--workers', '--yes'],'reindex-code': ['--background', '--brain', '--concurrency', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--markdown', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--timeout', '--to', '--workers', '--yes'],@@ -114,13 +114,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],- 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--restore-only', '--resume', '--retry-failed', '--scope', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--bind', '--brain', '--calibration-holder', '--enable-dcr', '--enable-dcr-insecure', '--help', '--http', '--json', '--log-full-params', '--mcp-only', '--model', '--port', '--print-admin-token', '--public-url', '--rounds', '--save', '--since', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--take', '--token-ttl', '--until', '--with-calibration', '--yes'],'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--concurrency', '--cost-estimate', '--dim', '--embedding-dimensions', '--embedding-model', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--pglite', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--swap-only', '--target', '--to', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],- 'whoknows': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],+ 'whoknows': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--purge', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],'ze-switch': ['--background', '--brain', '--confirm-reembed', '--dim', '--dry-run', '--explain', '--follow', '--force', '--help', '--ignore-env-override', '--ignore-missing-key', '--json', '--markdown', '--non-interactive', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--resume', '--source', '--timeout', '--to', '--undo', '--yes'],};diff --git a/src/core/cli-preflight.ts b/src/core/cli-preflight.tsnew file mode 100644index 0000000000..92a95606a9--- /dev/null+++ b/src/core/cli-preflight.ts@@ -0,0 +1,595 @@+/**+ * CLI startup preflight — the FIRST statement of `cli.ts:main()`, before+ * global-flag parsing and any command dispatch. Ordered steps:+ *+ * 0. Sanitized re-run detection. When this process IS the re-run described+ * in step 1b (verified, never trusted on the marker's say-so — see+ * "Loop guard"), switch back to the caller's directory, arm the+ * die-with-wrapper watchdog (see "Die with the wrapper") and skip step 1:+ * the parent already quarantined and warned.+ * 1. `quarantineCwdDotenv()` — drop every protected key (env-trust.ts: the+ * security-relevant GBRAIN_* keys plus the loader / git / node / XDG /+ * TLS-trust / proxy / AI-endpoint hijack families) that a `.env` in the+ * cwd assigns. GBRAIN_HOME is on that list, so it is quarantined BEFORE+ * step 2 resolves the config dir. The 8 cwd .env files are parsed ONCE+ * here and the parse is shared with the cwd == config dir check.+ * 1b. Re-run gbrain with the sanitized environment whenever anything was+ * dropped (see "Why the re-run" below).+ * 2. `loadGbrainEnvFile(configDir)` — fill process.env from `~/.gbrain/.env`+ * (never overriding an exported variable). `loadConfig()` does this too,+ * but the guardrails loader in step 3 runs before any `loadConfig()`;+ * without this step `~/.gbrain/.env` could not be the operator's home+ * for GBRAIN_GUARDRAILS_MODULE.+ * 3. The #3688 guardrails loader (moved from cli.ts; now passes+ * `skipCwdCheck`). Fail-closed: set-but-broken aborts rather than+ * silently running without the operator's firewall; unset costs nothing.+ *+ * Fail-closed corollary of step 1 (see "GBRAIN_GUARDRAILS_MODULE" below): when+ * the quarantine dropped a NON-EMPTY `GBRAIN_GUARDRAILS_MODULE`, preflight+ * refuses to run at all instead of re-running without it.+ *+ * Every runtime entry — commands, `hook *`, `serve` (stdio and --http),+ * `mcp`, the supervisor-spawned `jobs work`, the per-job `jobs run-child` —+ * dispatches through `main()`, so this one call covers every gbrain process.+ * (`src/commands/auth.ts`'s `import.meta.main` seam is a dev-only+ * direct-script entry.)+ *+ * ## Why the re-run (step 1b)+ *+ * Deleting a key from process.env changes only THIS process's view. Bun hands+ * every child spawned without an explicit `env` option the environ snapshot+ * it took at startup — cwd-.env values included — so git, the claude CLI and+ * workers would still see the planted keys (verified on Bun 1.3.13: a `.env`+ * carrying `GIT_CONFIG_COUNT=1 / GIT_CONFIG_KEY_0=core.fsmonitor /+ * GIT_CONFIG_VALUE_0=./x.sh` runs x.sh from a plain `git status`). When the+ * quarantine dropped anything, preflight therefore spawns gbrain again with+ * an explicit, sanitized environment and exits with the re-run's status;+ * every descendant of the re-run inherits the clean view.+ *+ * The re-run starts in a NEUTRAL cwd: a fresh, empty `mkdtemp` directory that+ * is ours and by construction holds none of the `.env` family. Bun loads+ * `.env` from the process cwd only (no parent walk — verified on 1.3.13), so+ * the re-run's Bun never sees the hostile file and its environ simply LACKS+ * the dropped keys. They are deleted, never carried as empty strings: git and+ * the dynamic loader PRESENCE-check some of them (`GIT_SSL_NO_VERIFY=`+ * disables TLS verification, `LD_TRACE_LOADED_OBJECTS=` turns every+ * dynamically linked child into ldd, `GIT_DIR=` / `GIT_AUTHOR_NAME=` are hard+ * errors), so `''` would not have been neutral. Preflight in the re-run then+ * `chdir`s back to the caller's directory before anything else runs, so+ * relative arguments resolve exactly as typed. Nothing in cli.ts's import+ * graph captures `process.cwd()` at module-evaluation time (audited); every+ * read happens after this chdir.+ *+ * ## Loop guard+ *+ * The re-run carries `GBRAIN_CWD_ENV_QUARANTINED=<JSON {cwd, neutral,+ * wrapperPid}>`. The marker is NOT trusted by itself — a hostile .env could+ * plant one (the key is also on the protected list, so a planted copy is+ * dropped and named in the warning). It is honoured only when ALL of: it+ * parses to two strings (`wrapperPid` is informational — a positive integer+ * or ignored), this process's startup cwd IS `neutral` (realpath-compared),+ * and `neutral` contains none of the `.env` family. A process started from a hostile+ * directory fails the second check (its startup cwd has a `.env`) and the+ * third if it names its own directory — so it ignores the marker entirely+ * and never chdirs on one. Termination is structural: the re-run's startup+ * cwd has no `.env`, so it never drops anything and never re-runs. gbrain+ * self-spawns (supervisor → worker, hook → detached push, worker →+ * run-child) that start in the hostile cwd reload the file and perform the+ * hop once for their own subtree — accepted; one warning per subtree.+ *+ * ## Signals+ *+ * Handlers are installed BEFORE the spawn (a signal in the gap would take the+ * default action, kill the wrapper and orphan the re-run). The wrapper has no+ * duties of its own, so every listener some earlier module attached for the+ * forwarded signals is removed first: cli.ts installs its cleanup handlers+ * (process-cleanup.ts, SIGTERM → exit 143 / SIGHUP → exit 129) in its+ * `import.meta.main` block before `main()` reaches this preflight, and with+ * both attached a SIGTERM made the wrapper exit 143 before the re-run had+ * finished and before the neutral dir was removed. The wrapper's exit is+ * ALWAYS the child's. SIGTERM and SIGHUP — which a supervisor sends to the+ * wrapper pid alone — are always forwarded. SIGINT depends on whether the+ * process has a CONTROLLING TERMINAL (probed by opening `/dev/tty`; the+ * stdio `isTTY` flags on Windows), not on whether stdin is a tty:+ * - a controlling terminal exists: the re-run shares the wrapper's+ * foreground process group, so the terminal delivers Ctrl-C to it+ * directly — ALSO when stdin/stdout/stderr are redirected+ * (`serve --http </dev/null >log 2>&1` in a foreground shell). The wrapper+ * does NOT forward (a second delivery would consume a `once('SIGINT')`+ * graceful-shutdown handler such as serve-http's and turn Ctrl-C into an+ * abrupt kill) and ignores the signal itself so it survives to relay the+ * re-run's exit status.+ * - no controlling terminal (a supervisor, cron, a detached agent harness):+ * nothing does process-group delivery, so a SIGINT that reaches the+ * wrapper pid alone would otherwise orphan the re-run. Each received+ * SIGINT is forwarded once. (A harness that signals the whole group+ * instead delivers twice here — accepted: no terminal, no graceful Ctrl-C+ * expectation. A harness WITH a controlling terminal that signals the+ * wrapper pid alone with SIGINT is not forwarded — the terminal is the+ * delivery channel there; SIGTERM is what such harnesses send to stop a+ * child, and it is always forwarded.)+ * Exit status: the re-run's code, or 128+signal when a signal killed it+ * (shell convention).+ *+ * ## Die with the wrapper+ *+ * SIGKILL cannot be forwarded. A supervisor that tracks the pid it spawned —+ * the WRAPPER's — and escalates to SIGKILL (minions/supervisor.ts+ * `restartCurrentChild`, job-isolation children, hook pushes) would leave the+ * real re-run running as an orphan while a replacement starts. So the marker+ * carries the wrapper's pid and a VERIFIED re-run arms a watchdog: every+ * second it compares `process.ppid` with that pid (Bun's `process.ppid` is+ * live — it flips to the reaper's pid once the parent is gone, whether it+ * exited or was killed; verified on 1.3.13) and, when they differ, prints one+ * line, removes the now-orphaned neutral dir (`rmdirSync` — it is empty by+ * construction, and a non-recursive remove can never take anything else+ * with it) and exits 137, mirroring the SIGKILL the wrapper took. The timer+ * is `unref()`ed so it never keeps a finished command alive. A marker without+ * a usable `wrapperPid` (planted, foreign, older) arms nothing.+ *+ * ## Runtime flags across the hop+ *+ * `bun <flags> src/cli.ts` re-inserts `process.execArgv` into the re-run (a+ * compiled binary has none). Bun reports path-bearing flags verbatim in both+ * spellings (`["--preload", "./x"]` and `["--preload=./x"]`) and resolves a+ * relative value against the process cwd — which for the re-run is the EMPTY+ * neutral dir, so `--preload ./probe.ts` died with `preload not found`. For+ * `--preload`/`-r`/`--require`/`--import`, `--config`/`-c`, `--env-file` and+ * `--tsconfig-override`, a value that is `./`- or `../`-relative, or a bare+ * relative name that exists in the original cwd, is resolved against the+ * ORIGINAL cwd; absolute values, bare package specifiers and every other+ * flag pass through untouched, in order.+ *+ * ## HOME after the drop+ *+ * HOME / USERPROFILE are on the protected list (a cron/systemd unit often has+ * HOME unset, and a planted value then reaches process.env and every child).+ * Dropping them must not leave the re-run with NO home at all: git fails+ * (`Author identity unknown`, `$HOME not set`) and every raw+ * `process.env.HOME || ''` read resolves cwd-relative INTO the checkout. So+ * when the quarantine dropped HOME (USERPROFILE on Windows), the sanitized env+ * gets it back from `os.userInfo().homedir` — Bun derives that from the REAL+ * startup environ (passwd when the variable was unset) BEFORE the .env merge,+ * so the planted value never reaches it (verified on Bun 1.3.13). Only a+ * DROPPED key is restored: a home that was simply never set stays unset, so a+ * hopped run and a plain run see the same environment.+ *+ * ## Script mode + cwd bunfig.toml+ *+ * The compiled binary is built with `--no-compile-autoload-bunfig`, so a cwd+ * `bunfig.toml` is inert for it. The documented install (`bun install -g+ * github:…`, `git clone` + `bun link`) maps the `gbrain` bin to src/cli.ts,+ * which runs as an ordinary Bun SCRIPT — and for a script Bun applies the cwd+ * bunfig.toml before any of the script's code: a top-level `preload` has+ * already run by the time preflight starts. Nothing here can undo that; only+ * `bun --config=/dev/null <entry>` suppresses it (verified on Bun 1.3.13: no+ * `-c`/`--no-bunfig` spelling and no `BUN_CONFIG_*` variable does). What+ * preflight CAN do is say so: when it detects the shape (script runtime + a+ * top-level `preload` in the startup cwd's bunfig.toml) it prints one stderr+ * line. The checkout that contains the running entry itself (a contributor's+ * own repo, whose bunfig is theirs) is exempt; the sanitized re-run started in+ * the neutral dir never saw a bunfig and does not repeat the warning.+ *+ * ## GBRAIN_GUARDRAILS_MODULE: fail closed, not open+ *+ * The quarantine is key-presence: when a cwd .env assigns the key, the value+ * in process.env is dropped whether it came from the file or from the+ * operator's shell (Bun merges the file before any code runs and never+ * overrides a live variable, so the two are indistinguishable). For every+ * other protected key a false drop is a loud downgrade with the fix in the+ * warning. For THIS key it would be the opposite of the #3688 contract: the+ * re-run would simply have no module and run without the operator's firewall,+ * with nothing but a stderr line. So when a non-empty value was dropped,+ * preflight refuses to run (exit 1). A benign repository never assigns this+ * gbrain-specific key, and the `~/.gbrain/.env` home is unaffected: it is+ * read AFTER the quarantine (step 2), never dropped by it.+ *+ * Zero cost on the normal path: no .env in the cwd, or nothing protected+ * assigned there, means no spawn.+ *+ * ## cwd == config dir+ *+ * Running gbrain from INSIDE `~/.gbrain` (or `$GBRAIN_HOME/.gbrain`) makes Bun+ * load the operator's own `.env` as a "cwd .env". That file is operator-owned,+ * so the quarantine and the guardrails loader's cwd check are skipped when+ * `realpath(cwd) === realpath(configDir())` — but ONLY when no cwd .env file+ * assigns any key the config dir is DERIVED from: GBRAIN_HOME, HOME or+ * USERPROFILE (a hostile checkout laid out as `<checkout>/.gbrain` could+ * otherwise try to point the home at itself to manufacture the collision; a+ * planted home is never the operator's config dir). Measured on Bun 1.3.13,+ * `os.homedir()` is captured from the real startup environ before the .env+ * merge, so a planted HOME does not actually reach `configDir()` — the check+ * is belt-and-braces against that implementation detail changing.+ */+import { closeSync, constants as fsConstants, existsSync, mkdtempSync, openSync, readFileSync, realpathSync, rmdirSync, rmSync } from 'fs';+import { constants as osConstants, homedir, tmpdir, userInfo } from 'os';+import { dirname, isAbsolute, join, resolve } from 'path';+import {+ CWD_DOTENV_FILES,+ cwdDotenvAssignsKey,+ parseCwdDotenv,+ quarantineCwdDotenv,+ type DotenvAssignment,+} from './env-trust.ts';+import { loadGbrainEnvFile } from './gbrain-env-file.ts';+import { configDir } from './config.ts';++/**+ * Set on the sanitized re-run to `JSON {cwd, neutral}` (see "Loop guard").+ * Internal — not a setting; verified against the startup cwd, never trusted.+ */+export const CWD_ENV_QUARANTINED_MARKER = 'GBRAIN_CWD_ENV_QUARANTINED';++interface HopMarker {+ /** The caller's directory the re-run must switch back to. */+ cwd: string;+ /** The fresh empty directory the re-run was started in. */+ neutral: string;+ /** The wrapper's pid, for the die-with-wrapper watchdog; absent → no watchdog. Informational, not part of verification. */+ wrapperPid?: number;+}++function parseHopMarker(raw: string | undefined): HopMarker | null {+ if (!raw) return null;+ try {+ const v: unknown = JSON.parse(raw);+ if (+ v !== null && typeof v === 'object' &&+ typeof (v as HopMarker).cwd === 'string' && (v as HopMarker).cwd !== '' &&+ typeof (v as HopMarker).neutral === 'string' && (v as HopMarker).neutral !== ''+ ) {+ const marker: HopMarker = { cwd: (v as HopMarker).cwd, neutral: (v as HopMarker).neutral };+ const pid = (v as HopMarker).wrapperPid;+ if (typeof pid === 'number' && Number.isSafeInteger(pid) && pid > 0) marker.wrapperPid = pid;+ return marker;+ }+ } catch {+ // not JSON — a planted or foreign value; ignored+ }+ return null;+}++const WRAPPER_WATCHDOG_INTERVAL_MS = 1000;++/** See "Die with the wrapper". Only ever called for a VERIFIED hop. */+function installWrapperWatchdog(hop: HopMarker): void {+ const wrapperPid = hop.wrapperPid;+ if (wrapperPid === undefined) return;+ const t = setInterval(() => {+ if (process.ppid === wrapperPid) return;+ console.error('[env] sanitized re-run lost its wrapper (killed); exiting');+ try { rmdirSync(hop.neutral); } catch { /* already gone, or not empty — never ours to force */ }+ process.exit(137);+ }, WRAPPER_WATCHDOG_INTERVAL_MS);+ t.unref(); // must never keep a finished command alive+}++/**+ * The marker, but ONLY when this process provably is the re-run: it started+ * inside the neutral dir the marker names, and that dir holds no .env family+ * member. Anything else (absent, malformed, planted from a hostile cwd) → null.+ */+function verifiedHop(startupCwd: string): HopMarker | null {+ const marker = parseHopMarker(process.env[CWD_ENV_QUARANTINED_MARKER]);+ if (!marker) return null;+ try {+ if (realpathSync(startupCwd) !== realpathSync(marker.neutral)) return null;+ } catch {+ return null;+ }+ for (const name of CWD_DOTENV_FILES) {+ if (existsSync(join(marker.neutral, name))) return null;+ }+ return marker;+}++/** The keys `configDir()` is derived from; a cwd .env assigning any of them forfeits the cwd == config dir exemption. */+const CONFIG_DIR_SOURCE_KEYS: readonly string[] = ['GBRAIN_HOME', 'HOME', 'USERPROFILE'];++/**+ * True when `cwd` IS the operator's config dir (see "cwd == config dir") and+ * no cwd .env file assigns a key the config dir is derived from. Exported for+ * tests.+ */+export function cwdIsOperatorConfigDir(cwd: string, assignments: readonly DotenvAssignment[]): boolean {+ for (const key of CONFIG_DIR_SOURCE_KEYS) {+ if (cwdDotenvAssignsKey(key, assignments)) return false;+ }+ try {+ return realpathSync(cwd) === realpathSync(configDir());+ } catch {+ return false; // invalid GBRAIN_HOME or a config dir that does not exist yet — no collision+ }+}++/**+ * argv (after execPath) that runs THIS gbrain again. A compiled Bun binary+ * reports its virtual entrypoint as argv[1] (`/$bunfs/root/...`; `~BUN` on+ * Windows) and execPath IS gbrain, so the user args are the whole argv;+ * `bun src/cli.ts` needs the runtime flags (`--inspect`, `--preload`, … from+ * process.execArgv, relative paths resolved against `originalCwd` — see+ * "Runtime flags across the hop") and the entry file re-inserted — Bun+ * reports the entry as an absolute path, so it survives the neutral-cwd start+ * (cli.ts computes rawArgs as `process.argv.slice(2)` in both modes). null+ * when there is no re-runnable entry (`bun -e`).+ */+function selfArgv(originalCwd: string): string[] | null {+ const entry = process.argv[1];+ const userArgs = process.argv.slice(2);+ if (!isScriptRuntime()) return userArgs;+ if (!entry || entry.startsWith('-')) return null;+ return [...resolveRuntimePaths(process.execArgv, originalCwd), entry, ...userArgs];+}++/** Bun runtime flags whose value is a filesystem path (or, for the preload family, a path OR a package specifier). */+const PATH_RUNTIME_FLAGS: ReadonlySet<string> = new Set([+ '--preload', '-r', '--require', '--import',+ '--config', '-c',+ '--env-file',+ '--tsconfig-override',+]);++/** A path-flag value the re-run must see from `cwd`: relative → absolute; everything else verbatim. */+function resolveRuntimePath(value: string, cwd: string): string {+ if (value === '' || isAbsolute(value)) return value;+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- value is a --preload/--env-file/... path the operator passed on THIS process's own bun command line (process.execArgv) and cwd is the process's own startup cwd; absolutizing it so the sanitized re-run (which starts in a neutral dir) sees the same file IS the point, and no fs operation happens here+ if (/^\.\.?(?:[\\/]|$)/.test(value)) return resolve(cwd, value); // ./x ../x . ..+ try {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- same operator-supplied runtime-flag value against the process's own cwd; existsSync only decides whether a bare name is a file here or a package specifier+ if (existsSync(resolve(cwd, value))) return resolve(cwd, value); // a bare relative name that IS a file here (`--env-file .env.ci`)+ } catch {+ // unreadable — treat as a specifier+ }+ return value; // a package specifier (`--preload some-pkg`) or a non-path+}++/** `execArgv` with every path-bearing flag's relative value resolved against `cwd`; order and every other flag preserved. */+function resolveRuntimePaths(execArgv: readonly string[], cwd: string): string[] {+ const out: string[] = [];+ for (let i = 0; i < execArgv.length; i++) {+ const arg = execArgv[i]!;+ const eq = arg.indexOf('=');+ const flag = eq === -1 ? arg : arg.slice(0, eq);+ if (!PATH_RUNTIME_FLAGS.has(flag)) {+ out.push(arg);+ continue;+ }+ if (eq !== -1) {+ out.push(`${flag}=${resolveRuntimePath(arg.slice(eq + 1), cwd)}`); // --flag=value+ continue;+ }+ out.push(arg); // --flag value+ if (i + 1 < execArgv.length) out.push(resolveRuntimePath(execArgv[++i]!, cwd));+ }+ return out;+}++/**+ * True when this process is `bun <entry>` (the dev runtime or a `bun install+ * -g` / `bun link` install running src/cli.ts through its shebang), false for+ * a compiled binary (execPath IS gbrain; the entry is a `/$bunfs/` virtual+ * path, `~BUN` on Windows).+ */+function isScriptRuntime(): boolean {+ const entry = process.argv[1];+ const bunfsEntry = entry !== undefined && (/^\/\$bunfs\//.test(entry) || /[\\/]~BUN[\\/]/.test(entry));+ const devRuntime = /[/\\](bun|node)(\.exe)?$/.test(process.execPath);+ return !bunfsEntry && devRuntime;+}++/**+ * The one line preflight prints for the shape described in "Script mode + cwd+ * bunfig.toml". Exported for tests.+ */+export const SCRIPT_MODE_BUNFIG_WARNING =+ '[env] gbrain is running as a bun script (not the compiled binary) and the bunfig.toml in the current ' ++ 'directory declares a top-level preload — Bun ran it before gbrain started. A cwd bunfig.toml is untrusted: ' ++ 'run gbrain from a directory you control, or start it as `bun --config=/dev/null <path-to-gbrain/src/cli.ts> …`.';++/**+ * Does `bunfig.toml` in `dir` declare a TOP-LEVEL `preload` (the one Bun+ * applies to `bun <entry>`; a `[test]`-section preload applies to `bun test`+ * only)? Lines before the first `[section]` header are the top level.+ * Fail-quiet: unreadable → false (Bun would have failed on it first).+ */+function bunfigDeclaresTopLevelPreload(dir: string): boolean {+ let text: string;+ try {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- dir is the process's own startup cwd (process.cwd() in runCliPreflight) and the tail is the fixed literal 'bunfig.toml'; read-only probe for a top-level preload declaration+ text = readFileSync(join(dir, 'bunfig.toml'), 'utf-8');+ } catch {+ return false;+ }+ for (const line of text.split(/\r?\n/)) {+ if (/^\s*\[/.test(line)) return false; // first section header: top level ends+ if (/^\s*preload\s*=/.test(line)) return true;+ }+ return false;+}++/** The startup cwd is the checkout that contains the running entry (`<root>/src/cli.ts`). */+function cwdIsOwnCheckout(startupCwd: string): boolean {+ const entry = process.argv[1];+ if (!entry) return false;+ try {+ return realpathSync(startupCwd) === realpathSync(dirname(dirname(entry)));+ } catch {+ return false;+ }+}++function warnScriptModeBunfig(startupCwd: string): void {+ if (!isScriptRuntime()) return;+ if (!bunfigDeclaresTopLevelPreload(startupCwd)) return;+ if (cwdIsOwnCheckout(startupCwd)) return;+ console.error(SCRIPT_MODE_BUNFIG_WARNING);+}++/**+ * Does this process have a controlling terminal — i.e. will a terminal deliver+ * Ctrl-C to the whole foreground process group (wrapper AND re-run) itself?+ * POSIX: `open("/dev/tty")` succeeds exactly then (ENXIO otherwise), whatever+ * stdin/stdout/stderr are redirected to. Windows has no /dev/tty; the stdio+ * `isTTY` flags are the closest proxy there.+ */+function hasControllingTerminal(): boolean {+ if (process.platform === 'win32') {+ return Boolean(process.stdin.isTTY || process.stdout.isTTY || process.stderr.isTTY);+ }+ try {+ closeSync(openSync('/dev/tty', fsConstants.O_RDONLY | fsConstants.O_NOCTTY));+ return true;+ } catch {+ return false;+ }+}++/**+ * The operator's real home for "HOME after the drop": `os.userInfo().homedir`+ * (Bun: the startup environ's value, passwd when unset — never the merged+ * .env value), then `os.homedir()`. undefined when neither is available+ * (uid-less containers throw from userInfo).+ */+function realHomeDir(): string | undefined {+ try {+ const h = userInfo().homedir;+ if (h) return h;+ } catch {+ // no passwd entry for this uid — fall through+ }+ try {+ return homedir() || undefined;+ } catch {+ return undefined;+ }+}++/**+ * A fresh, empty directory that is ours, as an ABSOLUTE canonical path.+ * `tmpdir()` first — it reads TMPDIR/TMP/TEMP at call time, and those are on+ * the protected list, so a value planted by the cwd .env (a relative `t`, a+ * path inside the checkout) is already gone when this runs; the home dir when+ * the temp root is unusable. A mkdtemp dir is new by definition, so neither+ * can hold a .env. `realpathSync` so the marker's `neutral` and the re-run's+ * startup cwd compare canonically even if a caller-exported TMPDIR is+ * relative or a symlink.+ */+function makeNeutralDir(): string {+ let dir: string;+ try {+ dir = mkdtempSync(join(tmpdir(), 'gbrain-hop-'));+ } catch {+ dir = mkdtempSync(join(homedir(), '.gbrain-hop-'));+ }+ return realpathSync(dir);+}++/** The home variables restored after a drop (see "HOME after the drop"): HOME everywhere, USERPROFILE on Windows. */+const HOME_KEYS: readonly string[] = process.platform === 'win32' ? ['HOME', 'USERPROFILE'] : ['HOME'];++async function reexecSanitized(originalCwd: string, dropped: readonly string[]): Promise<void> {+ const argv = selfArgv(originalCwd);+ if (!argv) return; // in-process view is clean; nothing re-runnable for the descendants' sake+ const neutral = makeNeutralDir();+ // The quarantine already deleted the dropped keys from process.env; they are+ // NOT added back (not even empty — see "Why the re-run") …+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(process.env)) {+ if (v !== undefined) env[k] = v;+ }+ // … except a dropped HOME, which comes back as the operator's REAL home+ // (see "HOME after the drop") — the planted value is still discarded.+ for (const key of HOME_KEYS) {+ if (!dropped.includes(key) || env[key] !== undefined) continue;+ const real = realHomeDir();+ if (real) env[key] = real;+ }+ env[CWD_ENV_QUARANTINED_MARKER] = JSON.stringify({ cwd: originalCwd, neutral, wrapperPid: process.pid } satisfies HopMarker);+ let code: number;+ let signalCode: string | null;+ // See "Signals". Installed BEFORE the spawn; the spawn is synchronous in the+ // same tick, so a handler can only ever run with `child` set.+ let child: ReturnType<typeof Bun.spawn> | null = null;+ const forward = (sig: NodeJS.Signals) => () => {+ try { child?.kill(sig); } catch { /* already exited */ }+ };+ // The wrapper's only job is to relay the child. Any listener an earlier+ // module attached for these signals (cli.ts's cleanup handlers: SIGTERM →+ // exit 143 / SIGHUP → exit 129, installed before main()) would exit the+ // wrapper on its own schedule — before the child has finished and before the+ // neutral dir is removed. Remove them; the forwarders below are the only ones.+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) process.removeAllListeners(sig);+ process.on('SIGTERM', forward('SIGTERM'));+ process.on('SIGHUP', forward('SIGHUP'));+ // controlling terminal: it already delivered Ctrl-C to the child; only outlive it.+ // none: nothing else will deliver it — forward.+ process.on('SIGINT', hasControllingTerminal() ? () => {} : forward('SIGINT'));+ try {+ child = Bun.spawn([process.execPath, ...argv], {+ cwd: neutral,+ env,+ stdio: ['inherit', 'inherit', 'inherit'],+ });+ code = await child.exited;+ signalCode = child.signalCode;+ } finally {+ rmSync(neutral, { recursive: true, force: true });+ }+ if (signalCode) {+ const signals = osConstants.signals as Record<string, number | undefined>;+ process.exit(128 + (signals[signalCode] ?? 1)); // shell convention for a signal death+ }+ process.exit(code);+}++/**+ * The refusal printed when a non-empty GBRAIN_GUARDRAILS_MODULE was dropped+ * (see "GBRAIN_GUARDRAILS_MODULE: fail closed, not open"). Exported for tests.+ */+export const GUARDRAILS_ASSIGNED_BY_CWD_DOTENV =+ 'guardrails: GBRAIN_GUARDRAILS_MODULE is assigned by a .env file in the current directory; ' ++ "refusing to run without the operator's firewall. Bun merges that file before gbrain starts, " ++ "so a value you exported cannot be told apart from the file's — remove the assignment from the " ++ "project's .env, or run gbrain from a directory that does not assign it. Your own setting " ++ 'belongs in your shell environment or in ~/.gbrain/.env (never in a project .env).';++export async function runCliPreflight(): Promise<void> {+ const startupCwd = process.cwd();+ const hop = verifiedHop(startupCwd);+ if (hop) {+ delete process.env[CWD_ENV_QUARANTINED_MARKER]; // never inherited further: a later self-spawn decides for itself+ try {+ process.chdir(hop.cwd);+ } catch (err) {+ console.error(`[env] cannot return to ${hop.cwd} after the sanitized re-run: ${(err as Error)?.message ?? String(err)}`);+ process.exit(1);+ }+ installWrapperWatchdog(hop); // after the chdir: the neutral dir may be removed only from outside it+ } else {+ // Bun applied the STARTUP cwd's bunfig.toml to this process (script mode+ // only); the re-run started in the neutral dir, so it has nothing to say.+ warnScriptModeBunfig(startupCwd);+ }+ const cwd = process.cwd();+ const assignments = parseCwdDotenv(cwd);+ const collision = cwdIsOperatorConfigDir(cwd, assignments);+ if (!hop && !collision) {+ const hadGuardrailsModule = (process.env.GBRAIN_GUARDRAILS_MODULE ?? '').trim() !== '';+ const dropped = quarantineCwdDotenv(process.env, cwd, { assignments });+ if (hadGuardrailsModule && dropped.includes('GBRAIN_GUARDRAILS_MODULE')) {+ console.error(GUARDRAILS_ASSIGNED_BY_CWD_DOTENV);+ process.exit(1);+ }+ if (dropped.length > 0) await reexecSanitized(cwd, dropped);+ }+ loadGbrainEnvFile(configDir);+ if (process.env.GBRAIN_GUARDRAILS_MODULE) {+ try {+ const { loadGuardrailProvidersFromEnv } = await import('./guardrails.ts');+ await loadGuardrailProvidersFromEnv(process.env, { skipCwdCheck: collision });+ } catch (err) {+ console.error(`guardrails: ${(err as Error)?.message ?? String(err)}`);+ process.exit(1);+ }+ }+}diff --git a/src/core/config.ts b/src/core/config.tsindex 8e3a54178f..1402793cd1 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -5,6 +5,7 @@ import type { EngineConfig, EmbeddingColumnConfig } from './types.ts';import { applyDbPlaneReadSideMerge, type DbPlaneEngineReader } from './config-db-merge.ts';import { loadConfigSnapshot } from './config-snapshot.ts';import { loadGbrainEnvFile } from './gbrain-env-file.ts';+import { dotenvValuesForKey } from './env-trust.ts';import { REMOTE_PRIVATE_PAGES_KEY } from './search/private-visibility.ts';/**@@ -644,68 +645,18 @@ export function loadConfigFileOnly(): GBrainConfig | null {* #427 guard — DATABASE_URL hijack via Bun's cwd .env auto-load.** Bun merges `.env` files from the process cwd into process.env before any- * user code runs. For a globally-installed tool that is a footgun: running- * gbrain inside any checkout whose `.env` defines DATABASE_URL (Next.js,- * Hono, Supabase, most web apps) silently retargets the brain at that app's- * database. Reads hit the wrong DB; `apply-migrations` can write gbrain's- * schema — including its DDL event trigger — into a production app database- * (see the v0.42.8 report on #427).- *- * Bun gives no way to ask which vars came from a .env file (the merge- * happens before module load), so we re-parse the .env files Bun auto-loads- * from cwd and treat DATABASE_URL as "not operator-provided" when its value- * matches one of them. Deliberate overrides still work two ways:- * - GBRAIN_DATABASE_URL: namespaced to this tool, never auto-ignored;- * - exporting DATABASE_URL in the shell: exported vars win over .env in- * Bun, and a deliberate export that happens to EQUAL the cwd .env value- * would have selected the same database anyway — ignoring it changes- * the outcome only by honoring the brain config, which is the safe- * reading of ambiguous intent.- *- * The file list is a superset of Bun's auto-load set across NODE_ENV values- * so the guard doesn't depend on replicating Bun's exact selection logic.+ * user code runs, so running gbrain inside any checkout whose `.env` defines+ * DATABASE_URL (Next.js, Hono, Supabase, most web apps) would silently+ * retarget the brain at that app's database — `apply-migrations` could write+ * gbrain's schema into a production app database (the v0.42.8 report on #427).+ * The cwd-.env parser (`CWD_DOTENV_FILES`, `dotenvValuesForKey`) lives in+ * env-trust.ts beside the key-presence security quarantine; both symbols are+ * re-exported here so import sites never chase the move. This guard keeps+ * VALUE-match semantics: a DATABASE_URL equal to a cwd-.env assignment is+ * file-origin; a deliberate export that happens to EQUAL it would have chosen+ * the same database anyway, and GBRAIN_DATABASE_URL is never auto-ignored.*/-const CWD_DOTENV_FILES = [- '.env', '.env.local',- '.env.development', '.env.development.local',- '.env.production', '.env.production.local',- '.env.test', '.env.test.local',-];--/**- * All values assigned to `key` across the .env files in `dir`. Collecting- * every assignment (rather than emulating override order) keeps the guard- * independent of dotenv precedence rules — a match against ANY assignment- * means the value is file-origin. Exported for tests.- */-export function dotenvValuesForKey(key: string, dir: string = process.cwd()): Set<string> {- const values = new Set<string>();- const assignment = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;- for (const name of CWD_DOTENV_FILES) {- let content: string;- try {- content = readFileSync(join(dir, name), 'utf-8');- } catch {- continue; // missing/unreadable file — nothing to guard against- }- for (const rawLine of content.split('\n')) {- const line = rawLine.trim();- if (!line || line.startsWith('#')) continue;- const m = line.match(assignment);- if (!m || m[1] !== key) continue;- let v = m[2].trim();- if ((v.startsWith('"') && v.endsWith('"') && v.length >= 2) ||- (v.startsWith("'") && v.endsWith("'") && v.length >= 2)) {- v = v.slice(1, -1);- } else {- const hash = v.indexOf(' #');- if (hash !== -1) v = v.slice(0, hash).trim();- }- if (v) values.add(v);- }- }- return values;-}+export { CWD_DOTENV_FILES, dotenvValuesForKey } from './env-trust.ts';let warnedCwdEnvDbUrlIgnored = false;diff --git a/src/core/context/sensitivity-scan.ts b/src/core/context/sensitivity-scan.tsindex c94fda5a2d..25226c2cf7 100644--- a/src/core/context/sensitivity-scan.ts+++ b/src/core/context/sensitivity-scan.ts@@ -224,13 +224,28 @@ export function scanSensitive(const out: SensitivityFinding[] = [];// (a) Secrets — scanText applies the fingerprint allowlist itself.+ const secretFingerprints = new Set<string>();for (const f of scanText(text, { allowlist: config.allowlist })) {out.push({ family: `secret:${f.pattern}`, fingerprint: f.fingerprint });+ secretFingerprints.add(f.fingerprint);}- // (b) PII — detection over the ordered PII_PATTERNS families.+ // (b) PII — detection over the ordered PII_PATTERNS families. secret-scan+ // OWNS the credential-shaped families it also matches (jwt, bearer): a+ // value the secret pass already reported is not reported a second time+ // under `pii:*`. Dedupe is by fingerprint, not by family name, so a short+ // bearer token under the secret-scan floor still reaches `pii:bearer`, and+ // `Bearer <vendor key>` collapses onto the vendor finding. The PII bearer+ // match includes the `Bearer ` keyword; the token-only fingerprint is the+ // one secret-scan emits, so both spellings are checked.for (const f of findPii(text)) {- pushUnlessAllowed(out, `pii:${f.family}`, text.slice(f.start, f.end), config.allowlist);+ const value = text.slice(f.start, f.end);+ const tokenOnly = value.replace(/^[Bb]earer\s+/, '');+ if (+ secretFingerprints.has(fingerprintValue(value).fingerprint) ||+ secretFingerprints.has(fingerprintValue(tokenOnly).fingerprint)+ ) continue;+ pushUnlessAllowed(out, `pii:${f.family}`, value, config.allowlist);}// (c1) Private path shapes.diff --git a/src/core/engine.ts b/src/core/engine.tsindex 737d025144..0997c20406 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1768,11 +1768,11 @@ export interface BrainEngine {*/putRawData(slug: string, source: string, data: object, opts?: { sourceId?: string }): Promise<void>;/**- * v0.31.8 (D21): `opts.sourceId` source-scopes the page-id lookup. Without- * it, multi-source brains return raw_data rows from every same-slug page- * (preserved via two-branch query for back-compat).+ * v0.31.8 (D21): `opts.sourceId` source-scopes the page-id lookup (without+ * it, multi-source brains return rows from every same-slug page). Rows+ * follow the page's soft-delete; `includeDeleted` (export/migration) opts in.*/- getRawData(slug: string, source?: string, opts?: PageReadScope): Promise<RawData[]>;+ getRawData(slug: string, source?: string, opts?: PageReadScope & { includeDeleted?: boolean }): Promise<RawData[]>;// Files (v0.27.1: binary asset metadata + storage_path. Image bytes never// enter the DB; storage_path references a path inside the brain repo or andiff --git a/src/core/env-trust.ts b/src/core/env-trust.tsnew file mode 100644index 0000000000..3e955d55bc--- /dev/null+++ b/src/core/env-trust.ts@@ -0,0 +1,360 @@+/**+ * Trust boundary for environment variables that Bun auto-loaded from the+ * CURRENT DIRECTORY's `.env` files.+ *+ * Bun merges `.env`, `.env.local` and the `.env.<NODE_ENV>[.local]` variants+ * from the process cwd into process.env before any user code runs — for+ * `bun run` AND for `bun build --compile` binaries alike (verified on Bun+ * 1.3.10 and 1.3.13). For a globally installed CLI the cwd is arbitrary: any+ * cloned repository can carry a `.env`, so those files are UNTRUSTED input.+ * Bun gives no way to ask which variables came from a file (the merge happens+ * before module load), so this module re-parses the same files and reasons+ * about them. Two guards sit on top of that parse:+ *+ * - The #427 DATABASE_URL guard (`config.ts:effectiveEnvDatabaseUrl`) is a+ * VALUE match: the URL is ignored when it equals a cwd-.env assignment.+ * Running gbrain inside a web-app checkout must not retarget the brain at+ * that app's database. That value guard never touches+ * `GBRAIN_DATABASE_URL`; the key-presence quarantine below is what drops+ * it when a cwd .env ASSIGNS it (a planted brain URL is never intent).+ * - The security quarantine below is a KEY-PRESENCE match: a protected key+ * that any cwd .env file assigns is dropped, whatever its value. Value+ * matching is unsound for a security list because Bun expands `${VAR}`+ * inside .env values — `KEY=${PWD}/x` lands in process.env as an absolute+ * path that never equals the file text.+ *+ * What the quarantine covers: the code-loading, exec-target, root-redirect,+ * endpoint-redirect and posture-widening GBRAIN_* keys+ * (`CWD_DOTENV_PROTECTED_KEYS`) AND the loader / git / node / XDG-config /+ * TLS-trust / pager-editor / proxy / AI-endpoint / shell-startup hijack families+ * a cwd .env could plant for the programs gbrain spawns (`CWD_DOTENV_PROTECTED_PREFIXES`,+ * `CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS`) — `isCwdDotenvProtectedKey` is the+ * single predicate. Routing/tuning GBRAIN_* keys and everything not listed+ * still load from a cwd .env. Dropping is in-process; making the drop reach+ * the programs gbrain spawns is `cli-preflight.ts`'s neutral-cwd re-run.+ *+ * Grammar: this parser must accept AT LEAST every line shape Bun's loader+ * accepts, or an assignment Bun honours becomes invisible to the guard. Bun+ * treats `\n`, `\r\n` AND a bare `\r` as line terminators (`A=x\rB=1` sets+ * BOTH keys), keeps U+2028/U+2029 as ordinary value bytes, and does not strip+ * a leading BOM (we strip it anyway — counting one more assignment is the+ * safe side). The right-hand side is therefore matched as "everything up to+ * the line terminator", never as `.*$`: `.` skips `\r` and U+2028/2029, and+ * the `$` anchor then fails, hiding the whole assignment.+ *+ * fs/path only — this runs before anything else in the CLI.+ */+import { readFileSync } from 'fs';+import { join } from 'path';++/**+ * The .env names Bun auto-loads from cwd — a superset across NODE_ENV values+ * so the guards don't depend on replicating Bun's exact selection logic.+ */+export const CWD_DOTENV_FILES: readonly string[] = [+ '.env', '.env.local',+ '.env.development', '.env.development.local',+ '.env.production', '.env.production.local',+ '.env.test', '.env.test.local',+];++// Bun's terminator set: CRLF first so it is consumed as one break.+const LINE_TERMINATOR = /\r\n|\r|\n/;++/**+ * Split .env file content into lines the way Bun's loader does (see the+ * grammar note above) and strip a leading BOM. Shared with the+ * `~/.gbrain/.env` loader in gbrain-env-file.ts so both files speak the same+ * grammar.+ */+export function splitDotenvLines(content: string): string[] {+ const body = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;+ return body.split(LINE_TERMINATOR);+}++// `export KEY=...` is accepted so a shell-styled .env still counts as an+// assignment (the guard errs toward "file-origin"). RHS: see the grammar note.+const ASSIGNMENT = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*([^\r\n]*)$/;++/** One `KEY=<raw rhs>` pair as a cwd .env file spells it (rhs untrimmed, unquoted). */+export type DotenvAssignment = readonly [key: string, raw: string];++/** Every `KEY=<raw rhs>` pair across the cwd .env files in `dir`, in file order. */+function* dotenvAssignments(dir: string): Generator<DotenvAssignment> {+ for (const name of CWD_DOTENV_FILES) {+ let content: string;+ try {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- name iterates the fixed CWD_DOTENV_FILES list and dir is the cwd under audit (process.cwd() by default); read-only scan of the .env files Bun auto-loads from there+ content = readFileSync(join(dir, name), 'utf-8');+ } catch {+ continue; // missing/unreadable file — nothing to guard against+ }+ for (const rawLine of splitDotenvLines(content)) {+ const line = rawLine.trim();+ if (!line || line.startsWith('#')) continue;+ const m = line.match(ASSIGNMENT);+ if (m) yield [m[1]!, m[2] ?? ''];+ }+ }+}++/**+ * Materialise every assignment across the cwd .env files in `dir` — ONE read+ * of the 8 files that `cwdDotenvAssignsKey` and `quarantineCwdDotenv` both+ * accept in place of `dir`, so cli-preflight.ts parses once per process.+ */+export function parseCwdDotenv(dir: string = process.cwd()): DotenvAssignment[] {+ return [...dotenvAssignments(dir)];+}++/** `dir` (parse now) or an already-parsed list from `parseCwdDotenv`. */+type DirOrAssignments = string | readonly DotenvAssignment[];+function assignmentsOf(source: DirOrAssignments): Iterable<DotenvAssignment> {+ return typeof source === 'string' ? dotenvAssignments(source) : source;+}++/**+ * All values assigned to `key` across the .env files in `dir`. Collecting+ * every assignment (rather than emulating override order) keeps the #427+ * guard independent of dotenv precedence rules — a match against ANY+ * assignment means the value is file-origin. Exported for tests.+ */+export function dotenvValuesForKey(key: string, dir: string = process.cwd()): Set<string> {+ const values = new Set<string>();+ for (const [k, raw] of dotenvAssignments(dir)) {+ if (k !== key) continue;+ let v = raw.trim();+ if ((v.startsWith('"') && v.endsWith('"') && v.length >= 2) ||+ (v.startsWith("'") && v.endsWith("'") && v.length >= 2)) {+ v = v.slice(1, -1);+ } else {+ const hash = v.indexOf(' #');+ if (hash !== -1) v = v.slice(0, hash).trim();+ }+ if (v) values.add(v);+ }+ return values;+}++/**+ * True when ANY cwd .env file in `dir` assigns `key` — the value is ignored+ * (an empty assignment still shadows the key in Bun's loader). This is the+ * predicate the security quarantine and the guardrails loader use. The second+ * argument may be a pre-parsed `parseCwdDotenv(dir)` list.+ */+export function cwdDotenvAssignsKey(key: string, dir: DirOrAssignments = process.cwd()): boolean {+ for (const [k] of assignmentsOf(dir)) {+ if (k === key) return true;+ }+ return false;+}++/**+ * GBRAIN_* variables a cwd `.env` file must never be allowed to set. Each+ * one either makes gbrain load or execute something, relocates its+ * operator-owned roots, or widens a security posture — so a value planted by+ * a cloned repository is never operator intent.+ *+ * Deliberately NOT listed (documented container/service deployments may+ * legitimately co-locate them with the process cwd, and the attack model is+ * a hostile cloned repo, not a serve cwd — SECURITY.md says to launch+ * `serve --http` from a directory you control): GBRAIN_ADMIN_BOOTSTRAP_TOKEN,+ * GBRAIN_HTTP_CORS_ORIGIN, GBRAIN_HTTP_TRUST_PROXY. Deferred for a later+ * decision (TODOS): GBRAIN_SKILLS_DIR, GBRAIN_RECIPES_DIR, GBRAIN_GITHUB_PAT.+ * `test/env-trust-protected-keys.test.ts` fails when a new suspicious-looking+ * read (`_BIN|_CLI|_MODULE|_PATH|_HOME|_URL` suffix, `GBRAIN_ALLOW_` prefix)+ * appears in src/ without a decision here or a `cwd-dotenv-ok:` annotation at+ * the read site.+ */+export const CWD_DOTENV_PROTECTED_KEYS: readonly string[] = [+ // --- code-loading: gbrain import()s the named module -------------------+ 'GBRAIN_GUARDRAILS_MODULE', // guardrail provider module loaded before dispatch+ 'GBRAIN_PLUGIN_PATH', // plugin / skillpack module path+ // --- exec-target: gbrain spawns the named program ------------------------+ 'GBRAIN_CLAUDE_CLI_BIN', // binary run for the claude-cli language model+ 'GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG', // becomes that binary's CLAUDE_CONFIG_DIR → its hooks/settings+ 'GBRAIN_JOB_CHILD_CLI', // CLI the job-isolation worker spawns per job+ 'GBRAIN_BIN_OVERRIDE', // gbrain binary used by claw-test+ // --- root / registry redirect ------------------------------------------+ 'GBRAIN_HOME', // relocates ~/.gbrain (config, .env, keys, registry)+ 'GBRAIN_MOUNTS_PATH', // brain mounts registry file+ 'GBRAIN_DATABASE_URL', // THE brain connection string: a cwd .env would retarget every hook, query and write at a planted database; the #427 value guard covers only the bare DATABASE_URL, and this key is "stated intent" everywhere it is read+ 'GBRAIN_DIRECT_DATABASE_URL', // direct-pool override (connection-manager.ts): retargets brain writes at a planted host; has no #427 value guard+ 'GBRAIN_REMOTE_MCP_URL', // `init --remote` default: where the thin client sends its MCP traffic and bearer token+ 'GBRAIN_REMOTE_ISSUER_URL', // `init --remote` default: the OAuth issuer the client trusts and hands its credential to+ 'GBRAIN_OAUTH_RELAY_URL', // the OAuth relay that hands back Google tokens (creds/relay-client.ts): a planted relay is token theft+ // --- re-run marker ------------------------------------------------------+ 'GBRAIN_CWD_ENV_QUARANTINED', // cli-preflight.ts's sanitized re-run marker; only honoured when the startup cwd IS the .env-free dir it names, so a planted one is inert — listed so it is also dropped and named in the warning+ // --- posture-widening ----------------------------------------------------+ 'GBRAIN_ALLOW_SHELL_JOBS', // enables the shell job handler (arbitrary exec on the worker)+ 'GBRAIN_ALLOW_PRIVATE_REMOTES', // permits git remotes on private networks+ 'GBRAIN_ALLOW_UNVERIFIED_REMOTE', // skips remote verification on workspace push+ 'GBRAIN_GIT_ALLOW_FILE_TRANSPORT', // permits the git file:// transport+ 'GBRAIN_ALLOW_MASS_RECONCILE', // lifts the mass-delete reconcile guard+ 'GBRAIN_ALLOW_DEFAULT_WRITE', // permits writes into the 'default' source+ 'GBRAIN_NO_SANITY', // disables content sanity checks+ 'GBRAIN_REMOTE_PRIVATE_PAGES', // exposes private pages to remote callers+];++/**+ * Non-GBRAIN hijack families a cwd `.env` could plant for the PROGRAMS gbrain+ * spawns (git, the claude CLI, bun/node workers, shell jobs). These are+ * normally absent from an operator's environment, which is exactly why a+ * file-planted value lands (Bun never overrides a variable that already+ * exists). Matched by PREFIX because each family is open-ended+ * (`GIT_CONFIG_KEY_<n>`, `LD_*`, `BUN_CONFIG_*`); a family member the shell+ * DID export is untouched unless a cwd .env assigns that same name.+ */+export const CWD_DOTENV_PROTECTED_PREFIXES: readonly string[] = [+ 'LD_', // glibc loader injection (LD_PRELOAD / LD_LIBRARY_PATH / LD_AUDIT) into every dynamically linked child+ 'DYLD_', // the macOS loader's equivalents (DYLD_INSERT_LIBRARIES, DYLD_LIBRARY_PATH)+ 'GIT_', // git config/hook/exec injection: GIT_CONFIG_COUNT/KEY_n/VALUE_n (core.fsmonitor, core.hooksPath), GIT_EXEC_PATH, GIT_SSH*, GIT_ASKPASS+ 'BUN_', // bun runtime hijack for bun-based children: BUN_OPTIONS (--preload), BUN_INSTALL, BUN_CONFIG_*+ 'NPM_CONFIG_', // npm registry / script-shell / node-options redirection for npm-based children+ 'npm_config_', // the lowercase spelling npm actually reads+ 'BASH_FUNC_', // exported-function injection (`BASH_FUNC_name%%=() {…}`): bash imports the body as a function into every child shell+];++/**+ * Exact non-GBRAIN keys with the same effect as the prefix families above but+ * no shared prefix. Same rule: dropped only when a cwd .env assigns them.+ */+export const CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS: readonly string[] = [+ // --- node preload / resolution / TLS --------------------------------------+ 'NODE_OPTIONS', // --require/--import a module into every node child (the claude CLI among them)+ 'NODE_PATH', // extra module-resolution roots → dependency shadowing+ 'NODE_EXTRA_CA_CERTS', // trusts a planted CA → TLS interception of API traffic+ 'NODE_TLS_REJECT_UNAUTHORIZED', // =0 disables certificate verification outright+ // --- ssh credential prompts -----------------------------------------------+ 'SSH_ASKPASS', // program ssh/git run to obtain a passphrase+ 'SSH_ASKPASS_REQUIRE', // forces that program even when a tty is present+ // --- per-user config roots the spawned tools read as GLOBAL config --------+ 'XDG_CONFIG_HOME', // git reads $XDG_CONFIG_HOME/git/config as global config even when ~/.gitconfig exists → core.fsmonitor / core.hooksPath (no GIT_ prefix); the claude CLI and opencode resolve their config dirs from it too+ 'XDG_DATA_HOME', // per-user data root (credential stores, tool state) the children load from+ 'XDG_CACHE_HOME', // per-user cache root — a planted cache is replayed as trusted state+ 'GNUPGHOME', // gpg home for git commit/tag signing → planted keyring and agent config+ // --- TLS trust roots for the non-node children (git via curl, python, …) --+ 'SSL_CERT_FILE', 'SSL_CERT_DIR', // OpenSSL trust store override → a planted CA intercepts every HTTPS call the children make+ 'CURL_CA_BUNDLE', // curl's (and libcurl-linked git's) CA bundle override+ 'REQUESTS_CA_BUNDLE', // python requests' CA bundle override+ // --- OpenSSL code loading: every OpenSSL-linked child (git over https, curl, python, ssh) ---+ 'OPENSSL_CONF', // a planted openssl.cnf names a provider/engine .so that OpenSSL dlopen()s at init+ 'OPENSSL_ENGINES', // the directory OpenSSL loads engine .so files from+ 'OPENSSL_MODULES', // the directory OpenSSL 3 loads provider .so files from+ // --- per-user roots read raw from the environment by gbrain AND its children ---+ 'TMPDIR', 'TMP', 'TEMP', // os.tmpdir() honours these at call time: a planted (even relative) value steers the sanitized re-run's neutral dir and every temp write into the hostile tree+ 'HOME', 'USERPROFILE', // inert while exported (Bun never overrides a live variable) but under systemd/cron HOME is often UNSET, and the planted value then reaches process.env.HOME and every child's $HOME → ~/.gitconfig, ~/.ssh, ~/.gbrain resolve inside the checkout+ // --- programs the children hand control to -------------------------------+ 'EDITOR', 'VISUAL', // takes.ts spawns $EDITOR || $VISUAL — an arbitrary program+ 'PAGER', // git (and other children) pipe output through it — an arbitrary program+ // --- interpreter preload for scripted children (git's own helpers included)+ 'PYTHONPATH', // python module shadowing+ 'PYTHONSTARTUP', // python startup script+ 'PERL5LIB', // perl library path+ 'PERL5OPT', // implicit perl -M module load+ 'RUBYOPT', // implicit ruby -r preload+ 'RUBYLIB', // ruby library path+ // --- shell startup files / interpreter homes: every NON-INTERACTIVE shell gbrain's children start (the git hooks gbrain writes, `sh -c` in workspace-push and shell jobs) reads these before its first command ---+ 'BASH_ENV', // bash sources this file at the start of every non-interactive shell — arbitrary code before the script's first line+ // `ENV` (sh/ksh startup file) is deliberately NOT listed: every shell gbrain's children run reads it for INTERACTIVE shells only, and `ENV=production` is a routine key in project .env files.+ 'SHELLOPTS', // imported read-only into every bash: an inherited `xtrace` turns PS4 into code that runs on every traced command+ 'PS4', // the xtrace prompt — expanded, `$(…)` command substitution included, before each traced command+ 'BASHOPTS', // imported shopt set for every bash (expand_aliases, sourcepath, …) — changes how the child parses its own script+ 'PROMPT_COMMAND', // executed before every bash prompt — any interactive child shell (an $EDITOR's shell escape, a hook that drops to a shell) runs it+ 'ZDOTDIR', // relocates zsh's startup files: .zshenv is sourced by EVERY zsh, scripts included+ 'PYTHONHOME', // relocates the python stdlib → the interpreter imports planted code on start (PYTHONPATH is listed above)+ 'PERLLIB', // perl's other library-path variable (PERL5LIB is listed above)+ 'GCONV_PATH', // glibc loads iconv gconv modules — shared objects — from this directory on any charset conversion, in every glibc-linked child+ // --- proxy MITM of every HTTP client gbrain or its children run -----------+ 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY',+ 'http_proxy', 'https_proxy', 'all_proxy',+ // --- AI CLI / API endpoint redirection ------------------------------------+ 'CLAUDE_CONFIG_DIR', // the claude CLI's config dir → its hooks and settings+ 'ANTHROPIC_BASE_URL', // redirects Anthropic API traffic (and the key with it) to a planted host+ 'ANTHROPIC_AUTH_TOKEN', // substitutes the bearer credential the SDK / claude CLI send+ 'OPENAI_BASE_URL', // redirects OpenAI-compatible API traffic+ // --- the same redirection for every other provider gbrain's gateway / probes / recipes read from env (build-gateway-config.ts, probes.ts, recipes/*) — the API key travels to the planted host+ 'OPENROUTER_BASE_URL',+ 'LITELLM_BASE_URL',+ 'OLLAMA_BASE_URL',+ 'LMSTUDIO_BASE_URL',+ 'LLAMA_SERVER_BASE_URL',+ 'LLAMA_SERVER_RERANKER_BASE_URL',+];++const PROTECTED_EXACT: ReadonlySet<string> = new Set([+ ...CWD_DOTENV_PROTECTED_KEYS,+ ...CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS,+]);++/** The one predicate: is `key` something a cwd .env must never be allowed to set? */+export function isCwdDotenvProtectedKey(key: string): boolean {+ if (PROTECTED_EXACT.has(key)) return true;+ for (const prefix of CWD_DOTENV_PROTECTED_PREFIXES) {+ if (key.startsWith(prefix)) return true;+ }+ return false;+}++export interface QuarantineOpts {+ /** Warning sink; default writes one line to stderr. Injectable for tests. */+ warn?: (line: string) => void;+ /** Pre-parsed `parseCwdDotenv(dir)` list; when given, `dir` is not re-read. */+ assignments?: readonly DotenvAssignment[];+}++/** The remediation every cwd-.env refusal ends with (also used by guardrails.ts). */+export const CWD_DOTENV_REMEDIATION =+ 'cwd .env files are untrusted for security settings. Export it from your shell or set it ' ++ 'in ~/.gbrain/.env.';++export function formatQuarantineWarning(keys: readonly string[]): string {+ return (+ `[env] Ignoring ${keys.join(', ')} because a .env file in the current directory assigns it — ` ++ CWD_DOTENV_REMEDIATION+ );+}++/**+ * Drop every protected key present in `env` that a cwd .env file in `dir`+ * assigns, and print ONE stderr warning naming them (sorted). Returns the+ * dropped keys, sorted. Iterates the keys the .env files ASSIGN (not a fixed+ * list) so the prefix families are covered.+ *+ * Semantics worth knowing:+ * - Per-process, in-process. Deleting a key from process.env is NOT seen by+ * children spawned without an explicit `env` option (Bun hands them the+ * environ snapshot it took at startup — verified on Bun 1.3.13). So+ * whenever this returns a non-empty list, `cli-preflight.ts` re-runs+ * gbrain once from a fresh EMPTY temporary directory with the sanitized+ * environment: the re-run's Bun never sees the cwd .env, its environ+ * simply LACKS the dropped keys (deleted, never carried as `''` — git and+ * the dynamic loader presence-check `GIT_SSL_NO_VERIFY=` /+ * `LD_TRACE_LOADED_OBJECTS=`), and every descendant inherits that view.+ * The re-run switches back to the original cwd in its own preflight.+ * - Key presence, not value. A value the operator exported from the shell+ * is ALSO dropped while a cwd .env assigns the same key: Bun's `${VAR}`+ * expansion makes the two indistinguishable, and for this fixed security+ * list a false drop (loud, with the fix in the message) is the safe side.+ * - Fail-soft on I/O: an unreadable .env is treated as absent.+ */+export function quarantineCwdDotenv(+ env: Record<string, string | undefined> = process.env,+ dir: string = process.cwd(),+ opts: QuarantineOpts = {},+): string[] {+ const dropped: string[] = [];+ const seen = new Set<string>();+ for (const [key] of opts.assignments ?? dotenvAssignments(dir)) {+ if (seen.has(key)) continue;+ seen.add(key);+ if (env[key] === undefined || !isCwdDotenvProtectedKey(key)) continue;+ delete env[key];+ dropped.push(key);+ }+ dropped.sort();+ if (dropped.length > 0) {+ (opts.warn ?? ((line: string) => console.error(line)))(formatQuarantineWarning(dropped));+ }+ return dropped;+}diff --git a/src/core/gbrain-env-file.ts b/src/core/gbrain-env-file.tsindex b879f80bba..9a42a6ce1e 100644--- a/src/core/gbrain-env-file.ts+++ b/src/core/gbrain-env-file.ts@@ -12,11 +12,15 @@*/import { existsSync, readFileSync } from 'fs';import { join } from 'path';+import { splitDotenvLines } from './env-trust.ts';// KEY=VALUE with a POSIX-shaped name. `export KEY=...` is deliberately not// accepted: this is an env FILE, not a shell script (same stance as Bun's-// own .env loader).-const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;+// own .env loader). Line grammar is shared with the cwd-.env guard+// (env-trust.ts): `\n`, `\r\n` AND a bare `\r` terminate a line, a leading+// BOM is stripped, and the RHS is "everything up to the terminator" — never+// `.*$`, which cannot match past a `\r` or U+2028 and would hide the line.+const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*([^\r\n]*)$/;/*** Parse `<dir>/.env` and fill process.env with its assignments.@@ -30,7 +34,7 @@ export function loadGbrainEnvFile(resolveDir: () => string): void {const envPath = join(resolveDir(), '.env');if (!existsSync(envPath)) return;const raw = readFileSync(envPath, 'utf-8');- for (const rawLine of raw.split('\n')) {+ for (const rawLine of splitDotenvLines(raw)) {const line = rawLine.trim();if (!line || line.startsWith('#')) continue;const m = line.match(ASSIGNMENT);diff --git a/src/core/guardrails.ts b/src/core/guardrails.tsindex aa51fc9733..6f94e309e7 100644--- a/src/core/guardrails.ts+++ b/src/core/guardrails.ts@@ -33,6 +33,10 @@** @module guardrails*/+import { homedir } from 'node:os';+import { isAbsolute, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { CWD_DOTENV_REMEDIATION, cwdDotenvAssignsKey } from './env-trust.ts';/*** The boundary at which a guardrail is being consulted. Stable string union so@@ -141,8 +145,8 @@ export interface GuardrailEnvLoadResult {/*** #3688 — the operator wiring path. Loads guardrail providers from the module- * named by `GBRAIN_GUARDRAILS_MODULE` (an absolute/relative file path or a- * bare package specifier). Accepted module shapes, all additive:+ * named by `GBRAIN_GUARDRAILS_MODULE`: an ABSOLUTE file path or a `~/` path.+ * Accepted module shapes, all additive:** - `export default provider` (a single {@link GuardrailProvider})* - `export default [providerA, providerB]`@@ -152,23 +156,55 @@ export interface GuardrailEnvLoadResult {* Unset env var → no-op (the OSS distribution stays inert). Set-but-broken —* import failure, or a module that registers zero providers — throws* {@link GuardrailLoadError} (fail-closed; see class doc).+ *+ * Origin checks (all throw {@link GuardrailLoadError} BEFORE any import):+ * - cwd-relative specs (`./x`, `../x`, bare `.`) are refused — they would+ * resolve against whatever directory the process happens to run in.+ * - bare package specifiers (`some-pkg`, `@scope/pkg`, `pkg/sub`) are+ * refused — in the compiled binary Bun's module walk-up starts at the+ * CURRENT DIRECTORY, so a hostile checkout's `node_modules/<name>/` is+ * what would load. Only an absolute or `~/` path names a module the+ * operator chose.+ * - when `env` is `process.env` (or `opts.cwd` is given), a spec that a cwd+ * `.env` file assigns is refused whatever its value: Bun auto-loads those+ * files and expands `${VAR}` inside them, so a cloned repository could+ * otherwise pick the module. The CLI already quarantines the variable at+ * startup (`cli-preflight.ts` → `env-trust.ts`); this is belt-and-braces+ * for `gbrain/core/guardrails` library callers. `opts.skipCwdCheck` is+ * for the one legitimate collision — the cwd IS the operator's config+ * dir, so the "cwd .env" is `~/.gbrain/.env` itself (preflight decides).*/export async function loadGuardrailProvidersFromEnv(env: Record<string, string | undefined> = process.env,+ opts: { cwd?: string; skipCwdCheck?: boolean } = {},): Promise<GuardrailEnvLoadResult> {const spec = env.GBRAIN_GUARDRAILS_MODULE?.trim();if (!spec) return { loaded: 0, modulePath: null };- // File paths import via file:// URL so relative specs resolve against the- // operator's cwd, not against this module's location.- let target = spec;- if (spec.startsWith('.') || spec.startsWith('/') || spec.startsWith('~')) {- const { resolve } = await import('node:path');- const { pathToFileURL } = await import('node:url');- const { homedir } = await import('node:os');- const expanded = spec.startsWith('~') ? spec.replace(/^~/, homedir()) : spec;- target = pathToFileURL(resolve(expanded)).href;+ if (spec.startsWith('.')) {+ throw new GuardrailLoadError(+ `GBRAIN_GUARDRAILS_MODULE=${spec} is a cwd-relative path and is not loaded; ` ++ `use an absolute path or a ~/ path.`,+ );+ }+ const homePath = spec.startsWith('~/') || spec.startsWith('~\\');+ if (!homePath && !isAbsolute(spec)) {+ throw new GuardrailLoadError(+ `GBRAIN_GUARDRAILS_MODULE=${spec} must be an absolute path or a ~/ path (package names ` ++ `resolve from the current directory's node_modules and are not loaded).`,+ );}+ if (!opts.skipCwdCheck && (env === process.env || opts.cwd !== undefined) &&+ cwdDotenvAssignsKey('GBRAIN_GUARDRAILS_MODULE', opts.cwd)) {+ throw new GuardrailLoadError(+ 'GBRAIN_GUARDRAILS_MODULE is assigned by a .env file in the current directory and is ' ++ `not loaded — ${CWD_DOTENV_REMEDIATION}`,+ );+ }++ // Import via file:// URL so the spec is taken literally rather than+ // resolved against this module's location.+ const target = pathToFileURL(resolve(homePath ? homedir() + spec.slice(1) : spec)).href;// #3688 residual: snapshot BEFORE the import, not after. A module that// registers its providers as a top-level side effect (callingdiff --git a/src/core/minions/child-job-runner.ts b/src/core/minions/child-job-runner.tsindex 3c9526b97f..1f6f8946a2 100644--- a/src/core/minions/child-job-runner.ts+++ b/src/core/minions/child-job-runner.ts@@ -162,7 +162,7 @@ export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {const inv = buildSpawnInvocation(opts.tiniPath, opts.invocation.cmd, [...opts.invocation.argsPrefix,- ...buildChildArgs(opts.jobId),+ ...buildChildArgs(opts.jobId, base),]);let child: ChildProcess;diff --git a/src/core/minions/handlers/shell-redact.ts b/src/core/minions/handlers/shell-redact.tsindex 9ca87b8020..9a6f5eb9cd 100644--- a/src/core/minions/handlers/shell-redact.ts+++ b/src/core/minions/handlers/shell-redact.ts@@ -30,14 +30,19 @@* scrubbed text; original is not mutated.** @param text The stdout/stderr/error text to scrub.- * @param secrets Map of inherit-name → resolved value. Empty values are skipped.- * Order doesn't matter (each value is independently replaced).+ * @param secrets inherit-name → resolved value pairs: a Map, or any ordered+ * iterable of `[name, value]` (secret-scan passes an array so+ * two values can share a pattern name). Empty values are+ * skipped. Values are replaced in iteration order; that only+ * matters when one value is a substring of another — put the+ * longer value first, or its span is corrupted by the shorter+ * replacement before it is reached.*/export function redactSecretsInText(text: string,- secrets: ReadonlyMap<string, string>,+ secrets: Iterable<readonly [string, string]>,): string {- if (text.length === 0 || secrets.size === 0) return text;+ if (text.length === 0) return text;let result = text;for (const [name, value] of secrets) {if (value.length === 0) continue;diff --git a/src/core/minions/handlers/shell.ts b/src/core/minions/handlers/shell.tsindex 9079ecc03b..223f2190d6 100644--- a/src/core/minions/handlers/shell.ts+++ b/src/core/minions/handlers/shell.ts@@ -206,11 +206,13 @@ class TailBuffer {export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResult> {if (process.env.GBRAIN_ALLOW_SHELL_JOBS !== '1') {const warning =- `[shell] Job #${ctx.id} rejected: GBRAIN_ALLOW_SHELL_JOBS=1 not set on this worker.\n` +- ' Shell jobs require the env var on the worker process.';+ `[shell] Job #${ctx.id} rejected: shell jobs are not enabled on this worker.\n` ++ ' Start it with `gbrain jobs work --allow-shell-jobs` (or export GBRAIN_ALLOW_SHELL_JOBS=1\n' ++ ' from your shell; a .env in the working directory cannot set it).';console.warn(warning);throw new UnrecoverableError(- 'shell handler disabled on this worker (set GBRAIN_ALLOW_SHELL_JOBS=1 to execute shell jobs)',+ 'shell handler disabled on this worker (start it with --allow-shell-jobs or ' ++ 'GBRAIN_ALLOW_SHELL_JOBS=1 to execute shell jobs)',);}diff --git a/src/core/minions/job-isolation.ts b/src/core/minions/job-isolation.tsindex 2160649963..7e4194d8df 100644--- a/src/core/minions/job-isolation.ts+++ b/src/core/minions/job-isolation.ts@@ -221,9 +221,17 @@ export async function decodeChildOutcomeFileAsync(return parseChildOutcome(await readFile(path, 'utf8'), size, maxBytes);}-/** argv for the child invocation (appended after the resolved CLI). */-export function buildChildArgs(jobId: number): string[] {- return ['jobs', 'run-child', '--job-id', String(jobId)];+/**+ * argv for the child invocation (appended after the resolved CLI). The shell+ * opt-in travels as a FLAG as well as env: the child is a fresh gbrain process+ * that re-runs the startup cwd-.env quarantine (core/env-trust.ts) in the+ * worker's cwd and would drop GBRAIN_ALLOW_SHELL_JOBS again whenever a .env+ * there assigns it; `jobs run-child` re-asserts the env var from the flag.+ */+export function buildChildArgs(jobId: number, env: Record<string, string | undefined> = process.env): string[] {+ const args = ['jobs', 'run-child', '--job-id', String(jobId)];+ if (env.GBRAIN_ALLOW_SHELL_JOBS === '1') args.push('--allow-shell-jobs');+ return args;}export interface ChildCliInvocation {diff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.tsindex 793ac94e70..644247a6ea 100644--- a/src/core/minions/supervisor.ts+++ b/src/core/minions/supervisor.ts@@ -82,7 +82,9 @@ export interface SupervisorOpts {healthInterval: number;/** Path to the gbrain CLI executable (MUST be a compiled binary; .ts sources cannot be spawned). */cliPath: string;- /** Allow shell jobs on child worker. Default: false. When true, sets GBRAIN_ALLOW_SHELL_JOBS=1 on child env. */+ /** Allow shell jobs on child worker. Default: false. When true, sets GBRAIN_ALLOW_SHELL_JOBS=1 on the+ * child env AND passes `--allow-shell-jobs` (buildWorkerArgs) so the worker's cwd-.env quarantine+ * cannot silently drop the opt-in. */allowShellJobs: boolean;/** JSON mode: emit JSONL events on stderr, reserve stdout for data payloads. Default: false. */json: boolean;@@ -180,7 +182,8 @@ const DEFAULTS: Omit<SupervisorOpts, 'cliPath'> = {* niceness also inherits to the worker's own children automatically.*/export function buildWorkerArgs(- opts: Pick<SupervisorOpts, 'concurrency' | 'queue' | 'maxRssMb' | 'nice_requested' | 'jobIsolation'>,+ opts: Pick<SupervisorOpts, 'concurrency' | 'queue' | 'maxRssMb' | 'nice_requested' | 'jobIsolation'> &+ Partial<Pick<SupervisorOpts, 'allowShellJobs'>>,): string[] {const args = ['jobs', 'work',@@ -198,6 +201,14 @@ export function buildWorkerArgs(if (opts.jobIsolation === 'process') {args.push('--job-isolation', 'process');}+ // Conditional push: the shell opt-in travels as a flag as well as env. The+ // worker's startup cwd-.env quarantine (core/env-trust.ts) drops+ // GBRAIN_ALLOW_SHELL_JOBS whenever a .env in the worker's cwd assigns it,+ // so an env-only handoff could silently disable shell jobs; `jobs work`+ // re-asserts the env from this flag after its preflight.+ if (opts.allowShellJobs) {+ args.push('--allow-shell-jobs');+ }return args;}diff --git a/src/core/oauth-grants.ts b/src/core/oauth-grants.tsindex 9ec9b0814c..dfd29cd873 100644--- a/src/core/oauth-grants.ts+++ b/src/core/oauth-grants.ts@@ -63,6 +63,16 @@ export class OAuthConsentError extends Error {constructor(readonly status: number, readonly code: string, message: string) { super(message); }}+/** Global ceiling on the in-memory pending store; a full store rejects new requests rather than evicting live ones. */+const MAX_PENDING_TOTAL = 1000;+/**+ * Per-client ceiling on requests still awaiting a decision. Without it a handful of callers could fill+ * the global store on behalf of one self-registered client; with it, no single client_id can consume+ * more than a sliver of the capacity every other client shares. Decided (approved/denied/failed) entries+ * stay in the store until expiry but do not count: only the owner can move a request out of `pending`.+ */+const MAX_PENDING_PER_CLIENT = 10;+export class OAuthGrants {private readonly pending = new Map<string, PendingAuthorization>();constructor(private readonly options: {@@ -90,9 +100,20 @@ export class OAuthGrants {}}- async begin(clientId: string, params: AuthorizationParams): Promise<string> {+ /** Synchronous: prune, then enforce the global and per-client ceilings. Callers must not await between this and the insert. */+ private assertCapacity(clientId: string): void {this.prune();- if (this.pending.size >= 1000) throw new TooManyRequestsError('Too many pending requests. Try again shortly.');+ if (this.pending.size >= MAX_PENDING_TOTAL) throw new TooManyRequestsError('Too many pending requests. Try again shortly.');+ let awaiting = 0;+ for (const pending of this.pending.values()) {+ if (pending.status === 'pending' && pending.details.clientId === clientId && ++awaiting >= MAX_PENDING_PER_CLIENT) {+ throw new TooManyRequestsError('Too many pending requests for this client. Complete or wait for an earlier request before starting another.');+ }+ }+ }++ async begin(clientId: string, params: AuthorizationParams): Promise<string> {+ this.assertCapacity(clientId);if (!/^[A-Za-z0-9_-]{43}$/.test(params.codeChallenge)) throw new InvalidRequestError('S256 PKCE challenge required');const [row] = await this.options.sql`SELECT * FROM oauth_clients WHERE client_id = ${clientId}`;assertActive(row);@@ -102,9 +123,8 @@ export class OAuthGrants {if (!Array.isArray(row.redirect_uris) || !row.redirect_uris.some(uri => typeof uri === 'string' && redirectUriMatches(params.redirectUri, uri))) {throw new InvalidRequestError('Redirect URI does not match registered client');}- // No await between the capacity check and insert: concurrent DB reads cannot overfill the store.- this.prune();- if (this.pending.size >= 1000) throw new TooManyRequestsError('Too many pending requests. Try again shortly.');+ // No await between the capacity check and insert: concurrent DB reads cannot overfill the store or a client's budget.+ this.assertCapacity(clientId);const id = generateToken('');const details: OAuthConsentDetails = {id, clientId, clientName: typeof row.client_name === 'string' ? row.client_name : clientId,diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex d1d349352c..28a50b69d2 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -34,6 +34,7 @@ import {parseScopeString,InvalidScopeError,ALLOWED_SCOPES_LIST,+ dcrScopeViolation,} from './scope.ts';import type { AuthInfo as CoreAuthInfo } from './operations.ts';import { parseLegacyTokenScope, parseTakesHoldersAllowList, coerceLegacyPermissions, normalizeTokenScopes } from './legacy-token-scope.ts';@@ -241,11 +242,11 @@ interface GBrainOAuthProviderOptions {/*** Allow the consent-bypassing `client_credentials` grant on the unauthenticated* Dynamic Client Registration path. Default false (#1353): a self-registered- * DCR client defaults to `authorization_code` (which goes through /authorize- * consent), and an explicit `client_credentials` request is rejected. Operators- * who genuinely need machine-to-machine DCR clients opt in via- * `--enable-dcr-insecure`. Manual CLI / admin registration is unaffected- * (operator-trusted, registers grants directly).+ * DCR client defaults to `authorization_code` (owner approval on /authorize),+ * and an explicit `client_credentials` request is rejected. Operators who opt+ * in via `--enable-dcr-insecure` get anonymous READ-ONLY machine clients: the+ * DCR scope ceiling (`dcrScopeViolation` in scope.ts) caps them at `read`.+ * Manual CLI / admin registration is unaffected (operator-trusted).*/allowClientCredentialsDcr?: boolean;/**@@ -365,17 +366,31 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {validateRedirectUri(String(uri));}- // Scope policy for DCR: filter unknowns (RFC 7591 value replacement)- // instead of hard-rejecting. Spec-compliant clients and OIDC-flavored- // stacks often append `offline_access` / `openid`; rejecting those as- // 500 made every such client fail registration. authorize() already- // clamps issued tokens to the registered grant, so dropping extras is- // safe. Empty-after-filter with a non-empty request is a hard 400.- // Operator CLI/admin paths still use assertAllowedScopes (typo-loud).- const requestedScopes = parseScopeString(client.scope);- if (requestedScopes.includes('agent')) {- throw new InvalidClientMetadataError('agent scope requires an operator-approved grant with explicit delegation bindings; dynamic registration cannot grant it');+ // v0.42 (#1353): the DCR path is the unauthenticated network entry point.+ // `client_credentials` skips /authorize owner approval entirely, so a+ // self-registered DCR client must NOT get it unless the operator opted in+ // via `--enable-dcr-insecure`. Gated BEFORE the scope ceiling: when the+ // grant is not on offer at all the reply must say so, not "limited to+ // read" (which implies it is available narrower). CLI/admin paths bypass this.+ grantTypes = client.grant_types?.length ? client.grant_types : ['authorization_code'];+ if (!this.allowClientCredentialsDcr && grantTypes.includes('client_credentials')) {+ throw new InvalidClientMetadataError(+ 'client_credentials grant is not permitted via dynamic client registration; ' ++ 'restart the server with --enable-dcr-insecure to allow it, or register the ' ++ 'client via the gbrain CLI / admin API.',+ );}++ // Scope policy for DCR: (1) ceiling — anonymous registration may hold+ // at most `read write` (`read` for an allowed client_credentials+ // registration); privileged scopes are REJECTED as 400, never silently+ // dropped (scope.ts). The ceiling depends on the grant default above.+ // (2) filter unknowns (RFC 7591 value replacement) instead of+ // hard-rejecting: OIDC-flavored stacks append `offline_access` /+ // `openid`. Empty-after-filter with a non-empty request is a hard 400.+ const requestedScopes = parseScopeString(client.scope);+ const ceilingViolation = dcrScopeViolation(requestedScopes, grantTypes);+ if (ceilingViolation) throw new InvalidClientMetadataError(ceilingViolation);const { allowed, dropped } = filterAllowedScopes(requestedScopes);if (dropped.length > 0) {console.warn(@@ -397,23 +412,6 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {// registration entry points share one allow-list.authMethod = validateTokenEndpointAuthMethod(client.token_endpoint_auth_method);- // v0.42 (#1353): the DCR path is the unauthenticated network entry point.- // `client_credentials` skips /authorize consent entirely, so a self-- // registered DCR client must NOT get it by default. Default the grant to- // `authorization_code` (the consent-bearing flow) when unspecified, and- // reject an explicit `client_credentials` request unless the operator opted- // in via `--enable-dcr-insecure`. Manual CLI/admin registration bypasses- // this store method, so operators can still mint machine clients directly.- grantTypes = (client.grant_types && client.grant_types.length > 0)- ? client.grant_types- : ['authorization_code'];- if (!this.allowClientCredentialsDcr && grantTypes.includes('client_credentials')) {- throw new InvalidClientMetadataError(- 'client_credentials grant is not permitted via dynamic client registration; ' +- 'restart the server with --enable-dcr-insecure to allow it, or register the ' +- 'client via the gbrain CLI / admin API.',- );- }} catch (err) {asClientMetadataError(err);}diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 6ca1625c17..4c8e9d32a6 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -473,6 +473,56 @@ export function sourceScopeOpts(ctx: OperationContext): { sourceId?: string; soureturn {};}+/**+ * Confine an explicitly named source id to the caller's resolved READ scope+ * (#4433 wave-L posture; used by sources_status — the destructive+ * sources_remove keys on `assertSourceInCallerWriteScope` below instead):+ * EVERY untrusted caller (anything not strictly `remote === false`) may only+ * name a source inside the canonical `sourceScopeOpts` ladder — federated+ * grant > scalar bound source. An out-of-scope id answers `not_found`, exactly+ * like a nonexistent source (anti-enumeration). The trusted local CLI passes+ * unconditionally (full operator view). Returns void; throws otherwise.+ */+export function assertSourceInCallerScope(ctx: OperationContext, id: string): void {+ if (ctx.remote === false) return;+ const scope = sourceScopeOpts(ctx);+ const allowed = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null);+ if (allowed && !allowed.includes(id)) {+ throw new OperationError('not_found', `Unknown source: ${id}`);+ }+}++/**+ * WRITE-authority twin of `assertSourceInCallerScope`, for the DESTRUCTIVE+ * source ops (`sources_remove`). Federation (`ctx.auth.allowedSources`) is READ+ * authority by contract (contract.ts: "source ids this OAuth client may READ+ * from") and confers no removal right, so this helper deliberately does NOT+ * consult the `sourceScopeOpts` ladder — a client bound to write `alpha` with+ * `federated_read: [alpha, beta]` may read `beta` but never cascade-delete it.+ *+ * Rules, in order:+ * - trusted local CLI (`remote === false`) passes unconditionally;+ * - an untrusted caller that is BOUND — carries a write source+ * (`ctx.auth.sourceId`, falling back to `ctx.sourceId`; the same notion as+ * delete_page/restore_page's write gate) and/or a federated grant — may+ * name ONLY its write source; a bound caller with no write source (or the+ * `__all__` sentinel as its source) may name nothing;+ * - an UNBOUND untrusted caller (neither axis set — an operator-registered+ * client with no source binding) keeps full authority, unchanged.+ * Out-of-authority ids answer `not_found`, byte-identical to a nonexistent+ * id (anti-enumeration; the same shape the read helper uses, so a caller+ * cannot tell "hidden" from "absent"). Returns void; throws otherwise.+ */+export function assertSourceInCallerWriteScope(ctx: OperationContext, id: string): void {+ if (ctx.remote === false) return;+ const writeSource = ctx.auth?.sourceId ?? ctx.sourceId;+ const bound = writeSource !== undefined || ctx.auth?.allowedSources !== undefined;+ if (!bound) return;+ if (writeSource === undefined || writeSource === ALL_SOURCES || id !== writeSource) {+ throw new OperationError('not_found', `Unknown source: ${id}`);+ }+}+/** Holder permissions are independent of the operator's page-visibility opt-out. */export function readHolders(ctx: OperationContext): string[] | undefined {return ctx.remote === false ? ctx.takesHoldersAllowList : ctx.takesHoldersAllowList ?? ['world'];diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 8d78343998..03f47dad99 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -12,7 +12,7 @@ import { clampSearchLimit } from '../engine.ts';import type { Page, PageType } from '../types.ts';import { importFromContent, type ImportEmbeddingResult } from '../import-file.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { writePageThrough, deletePageThrough, resolvePageWriteTarget, isWriteThroughDisabled, withNoRepoWriteThroughWarning, type WriteThroughResult } from '../write-through.ts';+import { writePageThrough, deletePageThrough, resolvePageWriteTarget, isWriteThroughDisabled, withNoRepoWriteThroughWarning, type PageWriteTarget, type WriteThroughResult } from '../write-through.ts';import { hasSourceFilesystemLock, withSourceFilesystemLock, assertSourceFilesystemActive } from '../minions/source-filesystem.ts';import { LockUnavailableError } from '../db-lock.ts';import { extractPageLinks, isAutoLinkEnabled, isAutoTimelineEnabled, isGlobalBasenameEnabled, parseTimelineEntries, makeResolver, type UnresolvedFrontmatterRef } from '../link-extraction.ts';@@ -1094,12 +1094,21 @@ async function runAutoLink(return { ...result, unresolved };}+/** What a purge cannot reach — surfaced on every purged response so a credential remediation never stops at the row. */+const PURGE_RESIDUALS = 'Brain-repo git history, synced working-tree copies, exports, compiled context files and slug-keyed derived rows (takes, open loops, file records) may still hold the content — rotate the credential and rewrite or regenerate those copies.';+/** A purge that leaves the markdown file behind is not a purge (the next sync re-imports it): an unlink ERROR fails closed, naming the path, and the row stays soft-deleted so the operator fixes the cause and re-runs. Non-error skips (no repo, disabled, file absent) proceed. */+function assertPurgeArtifactGone(slug: string, wt: { removed: boolean; error?: string }, target: PageWriteTarget | undefined): void {+ if (wt.removed || wt.error === undefined) return;+ const path = target?.ok ? target.filePath : 'its markdown file';+ throw new OperationError('storage_error', `purge ${slug}: could not remove ${path}: ${wt.error}`, 'Fix the file permissions (or remove the file by hand) and re-run `gbrain delete <slug> --purge`; the row stays soft-deleted until its file is gone.');+}const delete_page: Operation = {name: 'delete_page',- description: 'Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the result write_through field reports removed + path, or a skipped reason. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed.',+ description: 'Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the result write_through field reports removed + path, or a skipped reason. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. purge: true (local CLI only — `gbrain delete <slug> --purge`) removes the row and its chunks/links/raw data immediately with no recovery window; use it when a page must not linger (e.g. it captured a credential); the response names the copies a purge cannot reach (git history, exports, derived rows) — rotate first. A purge never reports success while the page\'s markdown file remains: on an already-soft-deleted page it retries the file removal against the recorded path, and a removal error (permissions) fails with storage_error naming the file — fix it and re-run; the row stays soft-deleted until the file is gone. Remote/MCP callers asking for purge get permission_denied (the soft-delete path stays available to them); status purged always carries write_through.',params: {slug: { type: 'string', required: true, description: "Slug of the page to soft-delete, e.g. 'people/alice-example'." },source_id: { type: 'string', description: "#4329: source holding the row to soft-delete (a multi-source brain can hold the same slug in several sources). Defaults to ctx.sourceId. Remote callers may only target their write source — federated read grants do not confer delete access." },+ purge: { type: 'boolean', description: 'Hard-delete immediately after the soft-delete (no 72h recovery; status purged). Honored only for the trusted local CLI; remote/MCP callers get permission_denied (a non-boolean value is invalid_params) and keep the soft-delete path.' },},mutating: true,scope: 'write',@@ -1110,7 +1119,18 @@ const delete_page: Operation = {// the delete landed on ctx.sourceId's row — the wrong-source soft-delete).const requestedSource = parseSourceIdParam(p.source_id, 'delete_page');if (requestedSource !== undefined) assertSourceInWriteGrant(ctx, requestedSource);- if (ctx.dryRun) return { dry_run: true, action: 'soft_delete_page', slug };+ // purge: strict boolean, trusted-local only (fail-closed: anything not+ // strictly remote === false is a remote caller). The hard-delete+ // primitive is the point of no return, so it never rides an agent-facing+ // transport — the operator types it.+ if (p.purge !== undefined && typeof p.purge !== 'boolean') {+ throw new OperationError('invalid_params', 'purge must be a boolean.', 'Pass purge: true (CLI: gbrain delete <slug> --purge).');+ }+ const purge = p.purge === true;+ if (purge && ctx.remote !== false) {+ throw new OperationError('permission_denied', 'purge is only available to the local CLI.', 'Remote callers soft-delete only; run `gbrain delete <slug> --purge` on the host to remove a page immediately.');+ }+ if (ctx.dryRun) return { dry_run: true, action: purge ? 'purge_page' : 'soft_delete_page', slug };// v0.31.8 (D7): thread ctx.sourceId so multi-source brains soft-delete the// intended row instead of always targeting (default, slug).const sourceOpts = requestedSource@@ -1140,6 +1160,23 @@ const delete_page: Operation = {if (!existing) {throw new OperationError('page_not_found', `Page not found: ${slug}`, 'Check the slug (and source_id on a multi-source brain).');}+ if (purge) {+ // Remediation path (O4-2): the earlier soft-delete's unlink may have+ // FAILED (permissions), leaving the credential-bearing .md for the next+ // sync to resurrect — so RETRY the removal against the tombstone's OWN+ // recorded path (the active-row resolution above misses it) and fail+ // closed on error before the row is dropped. Same response shape as+ // the live-row purge; the outcome is the real one, never a fabricated skip.+ const tombstoneTarget = isSandboxSubagent+ ? undefined+ : await resolvePageWriteTarget(ctx.engine, slug, wtSourceId, { includeDeleted: true });+ const retried = isSandboxSubagent+ ? { removed: false, skipped: 'subagent_sandbox' as const }+ : await deletePageThrough(ctx.engine, slug, { sourceId: wtSourceId, logger: ctx.logger, target: tombstoneTarget });+ assertPurgeArtifactGone(slug, retried, tombstoneTarget);+ await ctx.engine.deletePage(slug, sourceOpts);+ return { status: 'purged', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), write_through: retried, residuals: PURGE_RESIDUALS };+ }return { status: 'already_soft_deleted', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), deleted_at: existing.deleted_at };}// #4022: remove the on-disk artifact too. Pre-fix this was DB-only, so the@@ -1151,9 +1188,18 @@ const delete_page: Operation = {const writeThrough = isSandboxSubagent? { removed: false, skipped: 'subagent_sandbox' as const }: await deletePageThrough(ctx.engine, slug, { sourceId: wtSourceId, logger: ctx.logger, target });+ if (purge) {+ // Soft-delete first (artifact removal + the same audit shape), then the+ // hard primitive: cascades through chunks/links/raw_data via FKs. An+ // artifact-removal ERROR fails closed here too — the row stays a+ // tombstone and the re-run resumes on the remediation path above.+ assertPurgeArtifactGone(slug, writeThrough, target);+ await ctx.engine.deletePage(slug, sourceOpts);+ return { status: 'purged', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), write_through: writeThrough, residuals: PURGE_RESIDUALS };+ }// Echo the targeted source so a multi-source caller can verify WHICH row// the delete landed on (#4329's false-confidence failure mode).- return { status: 'soft_deleted', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), recoverable_until: 'now + 72h via restore_page', write_through: writeThrough };+ return { status: 'soft_deleted', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), recoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete <slug> --purge, local CLI only)', write_through: writeThrough };},cliHints: { name: 'delete', positional: ['slug'] },};diff --git a/src/core/ops/raw-data.ts b/src/core/ops/raw-data.tsindex ac32f0e19e..6b95d6cba6 100644--- a/src/core/ops/raw-data.ts+++ b/src/core/ops/raw-data.ts@@ -33,7 +33,7 @@ const put_raw_data: Operation = {const get_raw_data: Operation = {name: 'get_raw_data',- description: 'Retrieve raw data for a page',+ description: 'Retrieve raw data for a page. Raw data follows the page\'s soft-delete: a tombstoned (soft-deleted) page returns [] exactly like a missing page; restore_page brings the rows back, and get_page include_deleted: true verifies the tombstone.',params: {slug: { type: 'string', required: true, description: 'Slug of the page whose raw data to fetch.' },source: { type: 'string', description: 'Filter by source' },diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.tsindex 335dbcf33d..c34d9996cf 100644--- a/src/core/ops/sources.ts+++ b/src/core/ops/sources.ts@@ -8,7 +8,7 @@import type { Operation } from './contract.ts';import { OperationError } from './contract.ts';-import { sourceScopeOpts } from './context.ts';+import { assertSourceInCallerScope, assertSourceInCallerWriteScope, sourceScopeOpts } from './context.ts';import { resolveAuthCapabilities } from '../harness/capabilities.ts';// --- v0.28: whoami + sources management ---@@ -193,7 +193,12 @@ const sources_remove: Operation = {'Hard-remove a source (cascades pages/chunks/embeddings). Refuses to ' +'delete the auto-managed clone dir unless its resolved path is confined ' +'under $GBRAIN_HOME/clones/ (realpath+lstat — symlink-safe). For most ' +- 'workflows prefer sources_archive for the soft-delete path.',+ 'workflows prefer the soft-delete path (`gbrain sources archive`). ' ++ "Confined to the caller's WRITE authority, not its read scope: an untrusted " ++ 'caller may remove only its own write source (a federated read grant naming ' ++ 'a source does not make it removable); any other id answers not_found, ' ++ 'indistinguishable from a nonexistent source. Only the trusted local CLI ' ++ '(`gbrain sources remove`) can remove any source.',params: {id: { type: 'string', required: true, description: "Source id to remove, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug." },confirm_destructive: {@@ -210,6 +215,13 @@ const sources_remove: Operation = {mutating: true,scope: 'sources_admin',handler: async (ctx, p) => {+ // Source isolation on the DESTRUCTIVE path keys on WRITE authority (O4-1;+ // supersedes the #4433 wave-L read-ladder check that let a federated read+ // grant hard-delete a sibling source): a `sources_admin` token may remove+ // only its own write source; out-of-authority ids answer not_found+ // (anti-enumeration), an unbound client keeps full authority, trusted+ // local CLI passes. sources_status keeps the READ helper.+ assertSourceInCallerWriteScope(ctx, p.id as string);const { removeSource } = await import('../sources-ops.ts');return removeSource(ctx.engine, {id: p.id as string,@@ -235,19 +247,11 @@ const sources_status: Operation = {},scope: 'read',handler: async (ctx, p) => {- // Source isolation, mirroring sources_list's #4433 wave-L posture- // exactly (the maintainer decision that superseded the wave-g "scalar- // callers keep the full listing" carve-out): EVERY untrusted caller- // (anything not strictly remote === false) is confined through the- // canonical sourceScopeOpts ladder — federated grant > scalar bound- // source. Trusted local CLI keeps the full operator view. Out-of-scope- // ids answer not_found, indistinguishable from a nonexistent source- // (anti-enumeration), matching get_agent_job's shape.- const scope = ctx.remote === false ? {} : sourceScopeOpts(ctx);- const allowed = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null);- if (allowed && !allowed.includes(p.id as string)) {- throw new OperationError('not_found', `Unknown source: ${p.id}`);- }+ // Source isolation (#4433 wave-L posture, the maintainer decision that+ // superseded the wave-g "scalar callers keep the full listing"+ // carve-out), via the helper shared with sources_remove: out-of-scope ids+ // answer not_found (matching get_agent_job's shape), trusted local passes.+ assertSourceInCallerScope(ctx, p.id as string);const { getSourceStatus } = await import('../sources-ops.ts');return getSourceStatus(ctx.engine, p.id as string);},diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 4f1a343fc2..2a68ad51f5 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -4990,12 +4990,13 @@ export class PGLiteEngine implements BrainEngine {async getRawData(slug: string,source?: string,- opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },+ opts?: PageReadScope & { includeDeleted?: boolean },): Promise<RawData[]> {// v0.31.8 (D21): build WHERE clause dynamically. Without opts.sourceId,// no source filter (preserves pre-v0.31.8 cross-source read).const where: string[] = ['p.slug = $1'];if (opts?.excludePrivate) where.push(privatePagesFilterFragment('p'));+ if (!opts?.includeDeleted) where.push('p.deleted_at IS NULL'); // raw_data follows the page soft-deleteconst params: unknown[] = [slug];if (source) {params.push(source);diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 232a1d63bd..1807c6a16f 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -4191,36 +4191,37 @@ export class PostgresEngine implements BrainEngine {async getRawData(slug: string,source?: string,- opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },+ opts?: PageReadScope & { includeDeleted?: boolean },): Promise<RawData[]> {const sql = this.sql;const privacy = opts?.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('p')}`) : sql``;+ const alive = opts?.includeDeleted ? sql`` : sql`AND p.deleted_at IS NULL`; // raw_data follows the page soft-deleteconst sourceIds = opts?.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : undefined;const sourceId = sourceIds ? undefined : opts?.sourceId;let rows;if (source && sourceIds) {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id ${privacy}+ JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}WHERE p.slug = ${slug} AND rd.source = ${source} AND p.source_id = ANY(${sourceIds}::text[])`;} else if (sourceIds) {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id ${privacy}+ JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}WHERE p.slug = ${slug} AND p.source_id = ANY(${sourceIds}::text[])`;} else if (source && sourceId) {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id ${privacy}+ JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}WHERE p.slug = ${slug} AND rd.source = ${source} AND p.source_id = ${sourceId}`;} else if (source) {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id ${privacy}+ JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}WHERE p.slug = ${slug} AND rd.source = ${source}`;} else if (sourceId) {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id ${privacy}+ JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}WHERE p.slug = ${slug} AND p.source_id = ${sourceId}`;} else {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id ${privacy}+ JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}WHERE p.slug = ${slug}`;}return rows as unknown as RawData[];diff --git a/src/core/scope.ts b/src/core/scope.tsindex 0bb7b6f9a6..44b16c7c42 100644--- a/src/core/scope.ts+++ b/src/core/scope.ts@@ -46,6 +46,77 @@ export const ALLOWED_SCOPES_LIST: ReadonlyArray<Scope> = Object.freeze(['write',]);+/**+ * Ceiling for anonymous Dynamic Client Registration (RFC 7591). A network+ * caller that self-registers may hold at most `read write`; every privileged+ * scope needs an operator-created grant (`gbrain auth register-client`, the+ * admin API) or a later `gbrain auth rescope-client`. The owner-approval+ * step on /authorize shows the requested scopes but never narrows them, so+ * the ceiling is what keeps "approve" from meaning "grant admin".+ */+export const DCR_REGISTRABLE_SCOPES: ReadonlySet<Scope> = new Set<Scope>(['read', 'write']);++/**+ * A `client_credentials` DCR client (only reachable under+ * `--enable-dcr-insecure`) mints tokens with NO owner approval at all, so its+ * ceiling is tighter still: read-only.+ */+const DCR_MACHINE_SCOPES: ReadonlySet<Scope> = new Set<Scope>(['read']);++/**+ * null when the requested DCR scopes fit under the ceiling; otherwise the+ * `invalid_client_metadata` message naming the offending scopes + remedy.+ * Unknown scope strings are ignored here (filterAllowedScopes drops them);+ * `agent` keeps its own wording because it also needs delegation bindings.+ */+export function dcrScopeViolation(requested: readonly string[], grantTypes: readonly string[]): string | null {+ if (requested.includes('agent')) {+ return 'agent scope requires an operator-approved grant with explicit delegation bindings; dynamic registration cannot grant it';+ }+ const machine = grantTypes.includes('client_credentials');+ const ceiling = machine ? DCR_MACHINE_SCOPES : DCR_REGISTRABLE_SCOPES;+ const over = [...new Set(requested.filter((s) => isScope(s) && !ceiling.has(s)))];+ if (over.length === 0) return null;+ const limit = [...ceiling].join(' ');+ return (+ `Scope "${over.join(' ')}" cannot be granted through dynamic client registration; ` ++ (machine+ ? `a client_credentials registration is limited to \`${limit}\` because it is issued without owner approval. `+ : `self-registered clients are limited to \`${limit}\`. `) ++ 'Register the client with `gbrain auth register-client` / the admin API instead, ' ++ 'or register with a narrower scope and widen it later with `gbrain auth rescope-client <client_id> --scopes ...`.'+ );+}++/**+ * `scopes_supported` for OAuth discovery. The MCP SDK router emits ONE value+ * into the RFC 8414 authorization-server document and the RFC 9728+ * protected-resource document(s), so this is the single place that decides+ * what a client reading discovery is told it may ask for:+ *+ * - DCR enabled (either mode): exactly the anonymous-registration ceiling,+ * `read write`, in canonical order. Clients commonly copy `scopes_supported`+ * verbatim into their /register request; advertising a privileged scope+ * would steer every such client straight into `dcrScopeViolation` (HTTP 400)+ * even though the server is willing to register it at `read write`. The+ * tighter read-only ceiling for `client_credentials` registrations stays in+ * `dcrScopeViolation` — authorization_code is the DCR default and may hold+ * both, so advertising `read` alone would under-describe it.+ * - DCR disabled: every scope except operator-only `agent`, which also needs+ * delegation bindings no OAuth request can carry. Operator-registered+ * clients see the full set they may hold.+ *+ * Narrowed discovery never narrows an operator-registered client: one that+ * omits `scope` at /authorize or /token receives its full registered set+ * (`grantScopes` in oauth-grants.ts falls back to the row's scope), and an+ * explicit request is intersected with its registration, not with this list.+ */+export function scopesSupportedForDiscovery(opts: { enableDcr: boolean }): Scope[] {+ return opts.enableDcr+ ? ALLOWED_SCOPES_LIST.filter((s) => DCR_REGISTRABLE_SCOPES.has(s))+ : ALLOWED_SCOPES_LIST.filter((s) => s !== 'agent');+}+/*** Hierarchy table: which required scopes are implied by which granted scope.* `admin` implies all (escape hatch for legacy + super-admin tokens).diff --git a/src/core/secret-scan.ts b/src/core/secret-scan.tsindex e47566dde3..a06e14be76 100644--- a/src/core/secret-scan.ts+++ b/src/core/secret-scan.ts@@ -14,9 +14,13 @@* plus a per-workspace override file (`<ws>/.gbrain-scan-allow`, one* glob-or-fingerprint per line, `#` comments).*- * Rendering reuses `redactSecretsInText` [ENG-9] so every surface prints- * `<REDACTED:pattern>` — a finding preview or redacted corpus NEVER contains- * the secret value, and this module never returns raw matched values.+ * Every surface prints the one canonical token `<REDACTED:pattern>` [ENG-9]:+ * finding previews splice the token over every claimed span in the preview+ * window, the corpus writer (`redactFindings`, or `planRedaction` ++ * `applyRedaction` for multi-field documents) splices it over each claimed+ * span and then scrubs bare echoes of the bearer / high-entropy values it+ * claimed (bounded, see there) — neither ever contains the secret value, and+ * this module never returns raw matched values.** The generic high-entropy assignment heuristic is OFF by default (opt-in* via `ScanOpts.highEntropy`) — named-prefix patterns are precise; the@@ -27,7 +31,6 @@import { existsSync, readFileSync, statSync } from 'fs';import { isAbsolute, join, relative, sep } from 'path';import { createHash } from 'crypto';-import { redactSecretsInText } from './minions/handlers/shell-redact.ts';// ── Types ───────────────────────────────────────────────────────────────────@@ -69,15 +72,48 @@ export const SCAN_ALLOW_FILENAME = '.gbrain-scan-allow';// "task-…") never fire. Order matters: 'anthropic' precedes 'openai' and the// per-line claimed-span set prevents a `sk-ant-…` key from double-reporting// as a generic `sk-` match.+//+// FORMAT-BASED, not prefix-only. Credentials without a vendor prefix (a JWT,+// an account SID, a connection string carrying its password) are matched on+// their WIRE SHAPE. Fixed-length shapes carry a trailing negative lookahead so+// a longer alphanumeric run (a digest, an identifier) is not cut into a+// false "key". The two CATCH-ALLS (`bearer`, `db_url_credentials`) are+// appended LAST on purpose: the per-line claimed-span dedupe is first-wins+// for ATTRIBUTION, so `Bearer <vendor key>` keeps its vendor attribution and+// a JWT used as a URL password is reported as `jwt` once — while COVERAGE is+// the union: whatever part of the later catch-all span the earlier claim did+// not cover (the userinfo around that JWT) is still claimed by the catch-all+// (see scanInternal).interface CompiledPattern {name: string;re: RegExp; // 'g' flags; group 1 = boundary, group 2 = the secret value/** When true, a match must also pass the Shannon-entropy gate. */entropyGated?: boolean;+ /** See CorePattern.precheck. */+ precheck?: (line: string) => boolean;}-const CORE_PATTERNS: ReadonlyArray<{ name: string; source: string }> = [+interface CorePattern {+ name: string;+ source: string;+ /**+ * When true, `source` already carries the two-group layout (group 1 =+ * boundary/anchor, group 2 = value) and is compiled as-is instead of being+ * wrapped in the default left-boundary group. Used when the anchor is a+ * literal keyword (e.g. `Bearer `) that must NOT be part of the value.+ */+ prebuilt?: boolean;+ /**+ * Cheap substring gate run BEFORE the regex on every line: when it returns+ * false the line cannot contain a match and the regex is skipped. Used by+ * the catch-alls, whose alternation + negated classes are the costliest+ * shapes here and whose anchor (`earer`, `@`) is a one-call `includes`.+ */+ precheck?: (line: string) => boolean;+}++const CORE_PATTERNS: ReadonlyArray<CorePattern> = [{ name: 'anthropic', source: 'sk-ant-[A-Za-z0-9_-]{16,}' },// Prefixed OpenAI forms (sk-proj-/sk-svcacct-/sk-None-) allow `_`/`-` in the// body, which the bare sk- pattern below deliberately does not. Ordered@@ -88,8 +124,27 @@ const CORE_PATTERNS: ReadonlyArray<{ name: string; source: string }> = [{ name: 'voyage', source: 'pa-[A-Za-z0-9_-]{20,}' },{ name: 'github_pat', source: 'github_pat_[A-Za-z0-9_]{22,}' },{ name: 'github_token', source: 'gh[pousr]_[A-Za-z0-9]{36,}' },+ { name: 'gitlab_pat', source: 'glpat-[A-Za-z0-9_-]{20,}' },{ name: 'slack', source: 'xox[baprs]-[A-Za-z0-9-]{10,}' },- { name: 'aws_access_key', source: 'AKIA[0-9A-Z]{16}' },+ // Long-lived (AKIA) and temporary/STS (ASIA) access-key ids: fixed 16 after+ // the prefix, hard right edge.+ { name: 'aws_access_key', source: '(?:AKIA|ASIA)[0-9A-Z]{16}(?![0-9A-Za-z])' },+ { name: 'google_api_key', source: 'AIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])' },+ // Stripe secret/restricted keys + webhook signing secrets.+ { name: 'stripe', source: '[sr]k_(?:live|test)_[0-9a-zA-Z]{20,}' },+ { name: 'stripe', source: 'whsec_[A-Za-z0-9]{24,}' },+ { name: 'sendgrid', source: 'SG\\.[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{16,}' },+ // Twilio account SID (AC) / API signing key SID (SK): 32 hex, hard right+ // edge so a longer hex digest that happens to start with AC never matches.+ { name: 'twilio', source: '(?:AC|SK)[0-9a-fA-F]{32}(?![0-9A-Za-z])' },+ // Supabase secret (sb_secret_) and management/personal access (sbp_) keys.+ // Deliberately NOT here: `sb_publishable_` (public by design) and the+ // project ref (hostname label or `project_ref=` assignment) — identifiers,+ // not credentials.+ { name: 'supabase_key', source: 'sb_secret_[A-Za-z0-9_-]{20,}' },+ { name: 'supabase_key', source: 'sbp_[a-f0-9]{40}(?![0-9A-Za-z])' },+ { name: 'npm_token', source: 'npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])' },+ { name: 'huggingface', source: 'hf_[A-Za-z0-9]{30,}' },// gbrain's own tokens: generateToken (core/utils.ts) mints 'gbrain_' plus an// optional OAuth infix (at_ access / rt_ refresh / cs_ client secret /// code_ auth code) plus 32 random bytes hex. Without this entry the scanner@@ -98,6 +153,77 @@ const CORE_PATTERNS: ReadonlyArray<{ name: string; source: string }> = [// transcript ingest carries it into pages. gbrain_cl_ client ids are public// identifiers, deliberately not listed here.{ name: 'gbrain_token', source: 'gbrain_(?:at_|rt_|cs_|code_)?[0-9a-f]{64}' },+ // JWT: three base64url segments (header.payload.signature). No vendor+ // prefix — this is the wire format of many service-role / session+ // credentials, so it is matched on shape. Same source as the PII family in+ // eval-capture-scrub.ts; secret-scan is the owner for redaction lanes.+ //+ // Prebuilt so the left boundary can exclude `-` as well as `_`: the value+ // class contains both, so with the default boundary every `-` in a run like+ // `-eyJ-eyJ-eyJ…` was a fresh start that consumed to end-of-line and+ // backtracked — quadratic (a 200 KB run took ~25 s). Each segment is also+ // bounded at 4096 so a start that never finds its `.` does constant work.+ // A JWT immediately preceded by `-` is not a realistic wire shape (headers,+ // JSON, URLs and env files put whitespace, a quote, `=`, `:` or `/` in+ // front of it); a segment over 4096 chars is the accepted miss.+ {+ name: 'jwt',+ source:+ '(^|[^A-Za-z0-9_-])' ++ '(eyJ[A-Za-z0-9_-]{8,4096}\\.[A-Za-z0-9_-]{8,4096}\\.[A-Za-z0-9_-]{8,4096})',+ prebuilt: true,+ },+ // ── Catch-alls: LAST, so vendor/JWT attribution above claims the span first.+ // Bearer: prebuilt two-group layout — the `Bearer ` keyword is the anchor+ // (group 1), only the token is the value (group 2), so the redacted text+ // reads `Bearer <REDACTED:bearer>` and the fingerprint is the token's.+ // RFC 7235 auth-scheme names are case-insensitive; the three spellings+ // seen on the wire (`Bearer`, `bearer`, `BEARER`) are accepted, and the+ // precheck tests both suffix spellings so an all-caps header line is not+ // skipped before the regex runs.+ {+ name: 'bearer',+ source: '((?:^|[^A-Za-z0-9_])[Bb](?:earer|EARER)\\s+)([A-Za-z0-9._~+/=-]{20,})',+ prebuilt: true,+ precheck: (line) => line.includes('earer') || line.includes('EARER'),+ },+ // Connection strings with inline credentials: the value is exactly the+ // scheme://user:pass@ span (an empty user is allowed — a redis URL whose+ // userinfo is just a colon and the password still fires),+ // so the host/db survive redaction for context. Database schemes only;+ // `https://user@host` never fires. Literal example spellings are avoided+ // in this comment on purpose (scripts/check-pg-url-redaction.sh).+ //+ // Both userinfo segments are BOUNDED (user 0-128, password 1-256). The+ // user segment stops at `:` and `/`; the password stops ONLY at whitespace,+ // `@` and the two string delimiters `"` `'`. Everything else is a legal+ // password character — every sub-delim (`!$&()*+,;=`), `:`, `%XX` escapes,+ // and the characters real (copy-pasted, unescaped) passwords carry: `/`+ // from base64, `{` `}` `<` `>` `|` `^` `\` and backtick. An earlier cut+ // excluded those on RFC 3986 grounds and let every such password through+ // unredacted, which is the wrong side of the trade for a redaction lane.+ // The cost is that `scheme://host:port/path@x` (an `@` inside a path) now+ // reads as a credential — a rare, harmless over-redaction.+ //+ // The old unbounded `[^\s@]+` ran to the end of the line and backtracked+ // once per scheme occurrence: quadratic on long @-free lines (a 250 KB+ // minified JSON line of credential-less redis URLs took ~4 s, 160 KB of+ // repeated `redis://:` ~5.6 s, 1 MB minutes). It ALSO turned a+ // credential-less URL followed within 256 chars by any `@` (an email in+ // the same minified JSON object) into a bogus finding, because the string+ // delimiters between them were legal password characters — excluding `"`+ // and `'` is what ends that run at the URL's closing quote; the LENGTH+ // bounds, not the exclusions, are the ReDoS fix. With the bounds the work+ // per scheme occurrence is a constant; the precheck skips the regex on+ // lines with no `@` at all. A password over 256 chars is the accepted miss+ // (a JWT that long is still claimed by `jwt` above).+ {+ name: 'db_url_credentials',+ source:+ '(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|rediss|amqp|mssql):\\/\\/' ++ '[^\\s:/@"\']{0,128}:[^\\s@"\']{1,256}@',+ precheck: (line) => line.includes('@'),+ },// NOTE: private_key_pem is NOT here — a PEM key spans multiple lines and the// per-line scanner below cannot see the base64 body. It is matched over the// WHOLE text by PEM_BLOCK_RE (see scanPemBlocks) so redaction covers the@@ -111,12 +237,23 @@ const CORE_PATTERNS: ReadonlyArray<{ name: string; source: string }> = [* matching the whole span means the key body is scrubbed. The body+footer are* OPTIONAL so a lone/truncated header (a body-only leak, or a header with no* END) still fires the push-block gate — value is then just the header. The- * lazy `[\s\S]*?` stops at the first END marker so two adjacent keys don't- * collapse into one span. `-----BEGIN CERTIFICATE-----` never matches (the- * literal `PRIVATE KEY` is required).+ * lazy body stops at the first END marker so two adjacent keys don't collapse+ * into one span. `-----BEGIN CERTIFICATE-----` never matches (the literal+ * `PRIVATE KEY` is required).+ *+ * The body is BOUNDED at 16384 chars (PEM_BODY_MAX_CHARS). The unbounded lazy+ * `[\s\S]*?` scanned from every header to the end of the text when no END+ * followed — quadratic on header-without-END texts (2000 header-only mentions+ * ahead of a 1 MB tail took ~4 s). With the bound a header does constant+ * work; a real key is far smaller (an RSA-4096 PEM is ~3.3 KB, RSA-16384+ * ~12.5 KB). A body longer than the bound degrades to the header-only match —+ * the gate still fires, the body is the accepted miss.*/-export const PEM_BLOCK_RE =- /-----BEGIN [A-Z ]*PRIVATE KEY-----(?:[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----)?/g;+export const PEM_BODY_MAX_CHARS = 16384;+export const PEM_BLOCK_RE = new RegExp(+ `-----BEGIN [A-Z ]*PRIVATE KEY-----(?:[\\s\\S]{0,${PEM_BODY_MAX_CHARS}}?-----END [A-Z ]*PRIVATE KEY-----)?`,+ 'g',+);// Opt-in: `secret|token|password|api key`-shaped assignment whose value has// high Shannon entropy. Keyword-anchored (compiled inline below so the group@@ -137,12 +274,35 @@ export const PEM_BLOCK_RE =// matched — the value length was doing gating the entropy check is there to// do. Real passwords are frequently 12-16 characters; secrets that long with// 3.5 bits/char of entropy are not prose.+//+// The value must ALSO contain at least one digit. Identifier-shaped values+// (`DefaultAzureCredential`, `/usr/local/bin/aws-vault`, an env-var NAME+// assigned to an `apiKeyEnvVar`) clear the entropy gate on mixed case and+// separators alone and were being redacted out of ordinary code. Real+// machine-minted secrets essentially always carry digits; a digitless+// passphrase is the accepted miss. A 40-hex git sha assigned to a `token:`+// key still redacts (digits + entropy) — documented, acceptable.+//+// Both quantifiers after the keyword are BOUNDED. The trailing identifier+// segments used to be `[A-Za-z0-9_-]*`: because the left boundary admits `-`+// and `_` and that class contains them too, every `-`/`_` in a run like+// `-apikey-apikey…` or `_token_token…` was a fresh keyword start whose+// suffix ran to end-of-line and backtracked — quadratic (210 KB of+// `-apikey` took ~35 s, 180 KB of `_token` ~15 s). At `{0,64}` a start does+// constant work; no real credential key carries 64 identifier characters+// after its keyword. The value is capped at 4096 for the same+// constant-work-per-occurrence guarantee (the jwt segments share the cap):+// a value longer than that is redacted only through its first 4096 chars —+// the accepted miss, well above any real token or base64 key blob.const HIGH_ENTROPY_MIN_BITS_PER_CHAR = 3.5;+const HIGH_ENTROPY_REQUIRES_DIGIT_RE = /[0-9]/;function compilePatterns(opts: ScanOpts): CompiledPattern[] {const out: CompiledPattern[] = CORE_PATTERNS.map((p) => ({name: p.name,- re: new RegExp(`(^|[^A-Za-z0-9_])(${p.source})`, 'g'),+ // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- p.source is a compile-time literal from CORE_PATTERNS (never caller input); every pattern uses bounded quantifiers, pinned by test/secret-scan-perf.test.ts+ re: new RegExp(p.prebuilt ? p.source : `(^|[^A-Za-z0-9_])(${p.source})`, 'g'),+ ...(p.precheck ? { precheck: p.precheck } : {}),}));if (opts.highEntropy) {// Group layout matches the core shape: group 1 = boundary (empty here,@@ -151,7 +311,7 @@ function compilePatterns(opts: ScanOpts): CompiledPattern[] {out.push({name: 'high_entropy_assignment',re: new RegExp(- `((?:^|[^A-Za-z0-9])(?:secret|token|passwd|password|passphrase|credential|api[_-]?key|apikey)[A-Za-z0-9_-]*["']?\\s*[:=]\\s*["']?)([A-Za-z0-9+/_=-]{12,})`,+ `((?:^|[^A-Za-z0-9])(?:secret|token|passwd|password|passphrase|credential|api[_-]?key|apikey)[A-Za-z0-9_-]{0,64}["']?\\s*[:=]\\s*["']?)([A-Za-z0-9+/_=-]{12,4096})`,'gi',),entropyGated: true,@@ -283,23 +443,59 @@ export function pathAllowlisted(relPath: string, allowlist: string[]): boolean {// ── Scanning ────────────────────────────────────────────────────────────────-interface RawHit {+/** One claimed span on a line: where `value` starts within the line text. */+interface LineSpan {pattern: string;- line: number; // 1-basedvalue: string;+ start: number;+}++/**+ * The claimed spans of one scanned line, shared BY REFERENCE between that+ * line's hits (appended to while the line is still being scanned), so+ * buildPreview can redact a hit's neighbours and snap its window to whole+ * spans.+ */+interface LineSpans {+ /** Discovery order (pattern-major). */+ all: LineSpan[];+ /** Lazily built by buildPreview: `all` sorted by `start`. */+ byStart?: LineSpan[];+}++interface RawHit extends LineSpan {+ line: number; // 1-based+ /** Absolute offset of `value` within the scanned text (redactFindings splices on it). */+ abs: number;lineText: string;+ spans: LineSpans;}/*** Whole-text PEM private-key pass. Runs over the FULL text (not per-line) so* the base64 body between header and footer is part of the matched value and* therefore gets redacted, never left behind. `lineText` is set to the whole- * matched block so buildPreview / redactSecretsInText replace the entire span- * with `<REDACTED:private_key_pem>`.+ * matched block so buildPreview renders the entire span as one+ * `<REDACTED:private_key_pem>` token.+ *+ * The 1-based header line is counted INCREMENTALLY: the position of the NEXT+ * `\n` is carried as state across hits (global exec yields them in ascending+ * index order). Each `indexOf` resumes where the previous one stopped and a+ * -1 (no newline left in the text) is sticky, so the newline search touches+ * every character at most once and the pass is O(text) however the newlines+ * are distributed. Two earlier forms were O(hits × text): recomputing+ * `text.slice(0, m.index).split('\n')` per hit, and a cursor that re-ran+ * `text.indexOf('\n', cursor)` per hit — when no `\n` follows the cursor that+ * call rescans to the end of the text and returns -1 once PER HIT (20000+ * header mentions on one line ahead of an 8 MB newline-free tail took ~8 s;+ * ~30 s with a 23 MB tail, inside SCAN_MAX_FILE_BYTES). Pinned in+ * test/secret-scan-perf.test.ts.*/function scanPemBlocks(text: string): RawHit[] {const hits: RawHit[] = [];PEM_BLOCK_RE.lastIndex = 0;+ let line = 1;+ let nextNl = text.indexOf('\n');let m: RegExpExecArray | null;while ((m = PEM_BLOCK_RE.exec(text)) !== null) {const value = m[0];@@ -307,9 +503,12 @@ function scanPemBlocks(text: string): RawHit[] {PEM_BLOCK_RE.lastIndex++; // zero-width safetycontinue;}- // 1-based line of the header start.- const line = text.slice(0, m.index).split('\n').length;- hits.push({ pattern: 'private_key_pem', line, value, lineText: value });+ while (nextNl !== -1 && nextNl < m.index) {+ line++;+ nextNl = text.indexOf('\n', nextNl + 1);+ }+ const span: LineSpan = { pattern: 'private_key_pem', value, start: 0 };+ hits.push({ ...span, line, abs: m.index, lineText: value, spans: { all: [span] } });}return hits;}@@ -321,11 +520,43 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {// named patterns, so order is a belt-and-suspenders guarantee).const hits: RawHit[] = scanPemBlocks(text);const lines = text.split('\n');+ // No per-line length cap, deliberately: a secret on a 1 MB minified line+ // must still be found and redacted, so long lines are scanned in full.+ // What keeps that bounded is (a) every pattern doing constant work per+ // candidate occurrence — the shapes whose value class could otherwise run+ // to end-of-line and backtrack (db_url_credentials, jwt,+ // high_entropy_assignment, and PEM_BLOCK_RE over the whole text) carry+ // bounded quantifiers, and jwt's boundary excludes `-` so a `-` run is+ // never a fresh start — and (b) each catch-all's `precheck`, a substring+ // test that skips its regex on lines without the anchor. The overlap check+ // and the union split are O(value) per hit (claimed-char bitmap) and the+ // preview window is O(log hits) per hit (binary search over the sorted+ // spans), so a line with tens of thousands of hits costs O(hits × value),+ // not O(hits²) — and preview rendering is windowed (buildPreview), not+ // O(hits × line).+ //+ // `offset` is the absolute start of the current line (the `+ 1` is the+ // `\n` split away); each hit records `abs = offset + start` so+ // redactFindings can splice the text once instead of searching it per+ // value.+ let offset = 0;for (let i = 0; i < lines.length; i++) {- const line = lines[i];- if (!line || line.length < 8) continue;- const claimed: Array<[number, number]> = [];+ const line = lines[i] ?? '';+ const lineStart = offset;+ offset += line.length + 1;+ if (line.length < 8) continue;+ const spans: LineSpans = { all: [] };+ // Claimed-character bitmap behind the first-wins dedupe: allocated on the+ // line's FIRST hit only (most lines have none), then O(value) to test and+ // to mark. Same answer as scanning every prior span for an intersection.+ let taken: Uint8Array | null = null;+ const claim = (pattern: string, value: string, start: number): void => {+ taken!.fill(1, start, start + value.length);+ spans.all.push({ pattern, value, start });+ hits.push({ pattern, value, start, abs: lineStart + start, line: i + 1, lineText: line, spans });+ };for (const p of patterns) {+ if (p.precheck && !p.precheck(line)) continue;p.re.lastIndex = 0;let m: RegExpExecArray | null;while ((m = p.re.exec(line)) !== null) {@@ -334,36 +565,129 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {const end = start + value.length;// Zero-width safety: never loop forever on a pathological pattern.if (m[0].length === 0) p.re.lastIndex++;- if (claimed.some(([s, e]) => start < e && end > s)) continue;+ // The entropy gate judges the WHOLE matched value (the rule fired on+ // the assignment's value), before any overlap split.+ if (p.entropyGated && !HIGH_ENTROPY_REQUIRES_DIGIT_RE.test(value)) continue;if (p.entropyGated && shannonEntropy(value) < HIGH_ENTROPY_MIN_BITS_PER_CHAR) continue;- claimed.push([start, end]);- hits.push({ pattern: p.name, line: i + 1, value, lineText: line });+ if (!taken) {+ taken = new Uint8Array(line.length);+ } else if (anyTaken(taken, start, end)) {+ // UNION COVERAGE. An earlier pattern already claimed part of this+ // span. Attribution stays first-wins — a FULLY covered span is+ // skipped, so `Bearer <vendor key>` reports the vendor only — but+ // every still-unclaimed sub-range of the later span is claimed as+ // a hit of the later pattern (value = that slice), so nothing a+ // pattern matched is ever left in the output. Discarding the whole+ // later span shipped the entire PASSWORD of a database URL whose+ // username happened to be a vendor-shaped id (the id was claimed,+ // the surrounding `db_url_credentials` span was dropped).+ for (let a = start, k = start; k <= end; k++) {+ if (k < end && !taken[k]) continue;+ if (a < k) claim(p.name, line.slice(a, k), a);+ a = k + 1;+ }+ continue;+ }+ claim(p.name, value, start);}}}return hits;}+/** True when any character in [start, end) is already claimed. */+function anyTaken(taken: Uint8Array, start: number, end: number): boolean {+ for (let k = start; k < end; k++) if (taken[k]) return true;+ return false;+}+const PREVIEW_MAX_CHARS = 160;+/** Raw context kept before / after the hit when the line is longer than the preview. */+const PREVIEW_CONTEXT_BEFORE = 40;+const PREVIEW_CONTEXT_AFTER = 80;++/**+ * Render the finding preview. ENG-9: every claimed span becomes the one+ * canonical `<REDACTED:name>` token — a value never survives into a preview.+ *+ * Only a WINDOW around the hit is rendered, never the whole line: a+ * minified/bundled line can run to hundreds of KB, and redacting the full+ * line once per hit was O(hits × line) (5000 tokens on one 190 KB line took+ * ~2.6 s; 41 ms one-per-line). Lines that fit the preview are rendered whole,+ * so the short-line output is unchanged.+ *+ * Two leak guards on the window: (1) EVERY claimed span on the line that+ * falls inside it is redacted — by POSITION (spans are disjoint and sorted,+ * so each is spliced at its own offset; a union-coverage slice or a value+ * that is a substring of its neighbour needs no replace ordering), so a+ * preview never carries a sibling secret from the same line; (2) the+ * window's edges snap OUTWARD to the boundary of any span they would cut+ * through, so a neighbouring occurrence is redacted whole instead of leaving+ * a fragment at the edge. Ellipses mark whichever edges were cut.+ */+function buildPreview(hit: RawHit): string {+ const { lineText, value, start, pattern } = hit;+ const end = start + value.length;+ let winStart = 0;+ let winEnd = lineText.length;+ if (lineText.length > PREVIEW_MAX_CHARS) {+ winStart = Math.max(0, start - PREVIEW_CONTEXT_BEFORE);+ winEnd = Math.min(lineText.length, end + PREVIEW_CONTEXT_AFTER);+ }+ // Spans never overlap each other (claimed-span dedupe), so sorted by start+ // they are sorted by end too: binary-search the first span ending after+ // winStart, walk while spans begin before winEnd. Snapping an edge to a+ // span boundary cannot pull a further span into the window — one pass.+ const byStart = (hit.spans.byStart ??= [...hit.spans.all].sort((a, b) => a.start - b.start));+ let lo = 0;+ let hi = byStart.length;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ const sp = byStart[mid]!;+ if (sp.start + sp.value.length <= winStart) lo = mid + 1;+ else hi = mid;+ }+ const inWindow: LineSpan[] = [];+ for (let i = lo; i < byStart.length; i++) {+ const span = byStart[i]!;+ if (span.start >= winEnd) break;+ const e = span.start + span.value.length;+ if (span.start < winStart) winStart = span.start;+ if (e > winEnd) winEnd = e;+ inWindow.push(span);+ }+ const pieces: string[] = [];+ let at = winStart;+ for (const span of inWindow) {+ pieces.push(lineText.slice(at, span.start), `<REDACTED:${span.pattern}>`);+ at = span.start + span.value.length;+ }+ pieces.push(lineText.slice(at, winEnd));+ let redacted = pieces.join('').trim();+ let cutLeft = winStart > 0;+ let cutRight = winEnd < lineText.length;+ if (redacted.length > PREVIEW_MAX_CHARS) {+ const at = Math.max(0, redacted.indexOf(`<REDACTED:${pattern}>`));+ const from = Math.max(0, at - PREVIEW_CONTEXT_BEFORE);+ const to = Math.min(redacted.length, from + PREVIEW_MAX_CHARS);+ cutLeft ||= from > 0;+ cutRight ||= to < redacted.length;+ redacted = redacted.slice(from, to);+ }+ return `${cutLeft ? '…' : ''}${redacted}${cutRight ? '…' : ''}`;+}-function buildPreview(lineText: string, value: string, patternName: string): string {- // ENG-9: render through redactSecretsInText for the canonical- // `<REDACTED:name>` token — the value never survives into the preview.- const redacted = redactSecretsInText(lineText, new Map([[patternName, value]])).trim();- if (redacted.length <= PREVIEW_MAX_CHARS) return redacted;- const at = redacted.indexOf(`<REDACTED:${patternName}>`);- const start = Math.max(0, at - 40);- return (start > 0 ? '…' : '') + redacted.slice(start, start + PREVIEW_MAX_CHARS) + '…';+function sha256Hex(value: string): string {+ return createHash('sha256').update(value).digest('hex');}-function toFinding(hit: RawHit, file?: string): SecretFinding {- const fullHex = createHash('sha256').update(hit.value).digest('hex');+/** `file` is stamped by scanFiles on the way out, not here. */+function toFinding(hit: RawHit, fullHex: string): SecretFinding {return {pattern: hit.pattern,line: hit.line,- redactedPreview: buildPreview(hit.lineText, hit.value, hit.pattern),+ redactedPreview: buildPreview(hit),fingerprint: `sha256:${fullHex.slice(0, 16)}`,- ...(file !== undefined ? { file } : {}),};}@@ -376,9 +700,9 @@ export function scanText(text: string, opts: ScanOpts = {}): SecretFinding[] {const allowlist = opts.allowlist ?? [];const out: SecretFinding[] = [];for (const hit of scanInternal(text, opts)) {- const fullHex = createHash('sha256').update(hit.value).digest('hex');+ const fullHex = sha256Hex(hit.value);if (valueAllowlisted(fullHex, allowlist)) continue;- out.push(toFinding(hit));+ out.push(toFinding(hit, fullHex));}return out;}@@ -439,28 +763,264 @@ export function scanFiles(paths: string[], opts: ScanOpts = {}): SecretFinding[]return out;}+// ── Corpus-write redaction ──────────────────────────────────────────────────+//+// [S3#2] `redactFindings` replaces every CLAIMED span in place with+// `<REDACTED:pattern>` and reports what was redacted. Allowlisted values are+// left intact — the user declared them safe. The output is rebuilt by+// SPAN-SPLICE, O(text + hits): every hit carries its absolute offset from+// scanInternal, the spans are sorted by offset, and the text between+// consecutive spans is copied through once. (The previous implementation ran+// one full-text `replaceAll` per unique (pattern, value) pair — O(unique+// values × text): a 1 MB transcript with ~5k unique high-entropy values took+// ~3-5 s to redact after a ~70 ms scan.)+//+// `redactions` is one finding per CLAIMED span, in scan order (PEM blocks,+// then line order). A span the union-coverage rule split around an earlier+// claim contributes one record per uncovered slice; an echo (below) adds no+// record — it is not a claim.+//+// SEMANTIC DELTA from the replaceAll form (deliberate): the splice redacts+// exactly the claimed spans, so for every pattern OUTSIDE the echo pass+// `redactFindings(text).text` agrees byte-for-byte with what `scanText(text)`+// reports — a claimed value's bytes at a position the scanner did not claim+// (embedded past its left boundary inside a longer identifier) are left+// as-is, and the corpus write and the push gate see the same findings.+// Vendor-prefixed values lose nothing by staying outside the echo pass: they+// re-match on their own wherever they recur.+//+// THE ECHO PASS. A `bearer` token is claimed only where its `Bearer ` keyword+// anchors it and a `high_entropy_assignment` value only where its keyword+// does, yet transcripts routinely echo the same value bare (`Authorization:+// Bearer <tok>` in a tool call, then `<tok>` alone in the reply; a pasted+// `PASSWORD=<v>` line, then `<v>` in prose). So the values those two patterns+// claim form an ECHO DICTIONARY (value → pattern) and every remaining+// occurrence — bare, or embedded inside a longer identifier — is redacted as+// that pattern's token too. Three bounds keep the pass cheap and+// collision-safe: a value must clear its pattern's floor+// (ECHO_MIN_CHARS_BEARER = 20, ECHO_MIN_CHARS_ENTROPY = 12 — the rules' own+// floors, restated so a pattern edit alone can never widen the pass to+// short, collision-prone values), must be at most ECHO_MAX_VALUE_CHARS long,+// and only the first ECHO_MAX_UNIQUE unique values in claim order — ONE cap+// across both patterns — join. A value past either cap is still redacted at+// its claimed span; only its echoes are the accepted miss.+//+// The pass is a streaming merge over the ORIGINAL text: per value, the+// position of its next occurrence at or beyond the emit cursor (found by+// `indexOf` resuming at the cursor); at each step the leftmost-longest+// occurrence that fits inside the current UNCLAIMED GAP is emitted and the+// cursor advances. Retained state is O(values) however long the text is —+// occurrences are never collected into a list, which on a repetitive tail+// (2 MiB of `A` against 64 claimed values of 20–83 `A`s) meant ~3 M candidate+// objects and ~230 MB of RSS for 64 findings, ahead of message truncation.+// Two earlier forms were also wrong on time: one `replaceAll` per unique+// value was O(unique × text) (why the count cap exists), and a single+// escaped-alternation RegExp was O(text × Σ|values|) on prefix-sharing+// values — 64 claimed bearer values of 4 KB sharing a 4000-char prefix ahead+// of a 1 MB tail of the prefix character took ~24 s (the bearer class is+// unbounded, so an attacker-influenced page can plant them); the per-value+// substring seeks take milliseconds on the same input, and the value-length+// cap bounds each compare. Matching only ever runs over the original text,+// never over emitted `<REDACTED:…>` tokens: a claimed bearer value that+// spells a pattern name (`high_entropy_assignment` is 23 bearer-class+// characters) used to turn a sibling token into `<REDACTED:<REDACTED:bearer>>`+// when the pass ran over the spliced output.+//+// SESSION-WIDE DICTIONARY. A multi-field document (a transcript session:+// message bodies, speaker labels, title, metadata values) must scrub an echo+// in one field of a value claimed in ANOTHER. `planRedaction` scans one+// field and adds its eligible values to a caller-supplied shared map under+// the same floors and the same single cap; `applyRedaction` splices later and+// reads the map as it stands THEN — so a caller plans every field first and+// applies afterwards, and a value claimed in the last field is scrubbed from+// the first. `redactFindings` is the one-shot composition for a single text.+/**- * Corpus-write mode [S3#2]: replace every matched span in place with- * `<REDACTED:pattern>` (via redactSecretsInText) and report what was- * redacted. Allowlisted values are left intact — the user declared them- * safe. Returns the redacted text plus one finding per original occurrence.+ * Floor for a `bearer` value to take part in the echo pass. The `bearer`+ * pattern's own class is `{20,}`, so every claimed value already clears it.*/-export function redactFindings(- text: string,- opts: ScanOpts = {},-): { text: string; redactions: SecretFinding[] } {+export const ECHO_MIN_CHARS_BEARER = 20;++/**+ * Floor for a `high_entropy_assignment` value to take part in the echo pass —+ * the rule's own value floor (`{12,4096}`), restated.+ */+export const ECHO_MIN_CHARS_ENTROPY = 12;++/**+ * A claimed value longer than this is redacted at its claimed span but does+ * not join the echo dictionary. Bounds the per-candidate compare of the+ * substring sweeps; no real bearer token or assignment value is this long,+ * and an echo of one is the documented, accepted miss.+ */+export const ECHO_MAX_VALUE_CHARS = 512;++/**+ * Cap on the unique values (bearer + high_entropy_assignment together, claim+ * order, first N) the echo pass will look for. Keeps the pass a bounded+ * number of linear sweeps; an echo of a value past the cap is the+ * documented, accepted miss.+ */+export const ECHO_MAX_UNIQUE = 64;++/** Echo dictionary: claimed value → the pattern that claimed it first. */+export type EchoDictionary = Map<string, string>;++export interface RedactOpts extends ScanOpts {+ /**+ * Shared echo dictionary. `planRedaction` ADDS the eligible values it+ * claims (shared floors, one cap, claim order); `applyRedaction` reads the+ * map at apply time. Pass one map across every field of a document for+ * session-wide echo coverage. Default: a fresh map per `planRedaction`.+ */+ echoValues?: EchoDictionary;+}++/** The scan half of a redaction: what `applyRedaction` splices. */+export interface RedactionPlan {+ /** One finding per claimed span, scan order — the receipt count. */+ redactions: SecretFinding[];+ /** The echo dictionary this plan fed (the caller's map when one was given). */+ echoValues: EchoDictionary;+ /** The original text (splice input). */+ text: string;+ /** Claimed spans, sorted by absolute offset. */+ claimed: Array<{ abs: number; end: number; pattern: string }>;+}++function addEchoValue(into: EchoDictionary, pattern: string, value: string): void {+ const floor =+ pattern === 'bearer'+ ? ECHO_MIN_CHARS_BEARER+ : pattern === 'high_entropy_assignment'+ ? ECHO_MIN_CHARS_ENTROPY+ : Infinity;+ if (value.length < floor || value.length > ECHO_MAX_VALUE_CHARS) return;+ if (into.has(value) || into.size >= ECHO_MAX_UNIQUE) return;+ into.set(value, pattern);+}++/**+ * Scan `text` for redaction: findings (allowlist applied), the claimed spans+ * to splice, and the eligible echo values added to `opts.echoValues` (or a+ * fresh map). Pure with respect to `text`; the only side effect is feeding+ * the shared dictionary.+ */+export function planRedaction(text: string, opts: RedactOpts = {}): RedactionPlan {const allowlist = opts.allowlist ?? [];+ const echoValues = opts.echoValues ?? new Map<string, string>();const redactions: SecretFinding[] = [];- const seen = new Set<string>(); // pattern\0value pairs already replaced- let out = text;+ const claimed: RedactionPlan['claimed'] = [];for (const hit of scanInternal(text, opts)) {- const fullHex = createHash('sha256').update(hit.value).digest('hex');+ const fullHex = sha256Hex(hit.value);if (valueAllowlisted(fullHex, allowlist)) continue;- redactions.push(toFinding(hit));- const key = `${hit.pattern}\0${hit.value}`;- if (seen.has(key)) continue;- seen.add(key);- out = redactSecretsInText(out, new Map([[hit.pattern, hit.value]]));+ redactions.push(toFinding(hit, fullHex));+ claimed.push({ abs: hit.abs, end: hit.abs + hit.value.length, pattern: hit.pattern });+ addEchoValue(echoValues, hit.pattern, hit.value);}- return { text: out, redactions };+ claimed.sort((a, b) => a.abs - b.abs);+ return { redactions, echoValues, text, claimed };+}++/**+ * Echo-sweep state for one `applyRedaction` call: the dictionary values+ * longest-first (a tie at one position resolves to the longest, so a value+ * that is a prefix of another never cuts the longer echo short) and, per+ * value, the position of its next occurrence at or beyond the emit cursor+ * (-1 once exhausted). Occurrences are discovered LAZILY as the cursor+ * advances and are never materialized as a list: a repetitive tail (2 MiB of+ * `A` against 64 claimed values of 20–83 `A`s) has O(text × Σ 1/|value|)+ * non-overlapping occurrences — ~3 M candidate objects, ~230 MB of RSS for+ * 64 findings when they were collected up front — while this state is+ * O(values) however long the text is. Each value's `indexOf` resumes at the+ * cursor and is re-sought only once the cursor has passed its cached+ * position, so the whole sweep stays O(values × text).+ */+interface EchoSweep {+ values: string[];+ tokens: string[];+ next: Int32Array;+}++function startEchoSweep(text: string, dict: EchoDictionary): EchoSweep {+ const entries = [...dict].sort((a, b) => b[0].length - a[0].length);+ const values = entries.map((e) => e[0]);+ const tokens = entries.map((e) => `<REDACTED:${e[1]}>`);+ const next = new Int32Array(values.length);+ for (let k = 0; k < values.length; k++) next[k] = text.indexOf(values[k]!);+ return { values, tokens, next };+}++/**+ * Splice a plan: `<REDACTED:pattern>` over every claimed span, and over every+ * echo-dictionary occurrence that lies ENTIRELY inside an unclaimed gap,+ * leftmost-longest. The dictionary is read now, not at plan time — a caller+ * that planned several fields into one map gets every field's values here.+ * Output is emitted incrementally as the cursor advances; nothing but the+ * output parts and the O(values) sweep state is retained.+ */+export function applyRedaction(plan: RedactionPlan): string {+ const { text, claimed, echoValues } = plan;+ if (claimed.length === 0 && echoValues.size === 0) return text;+ const sweep = echoValues.size > 0 ? startEchoSweep(text, echoValues) : null;+ const parts: string[] = [];+ // Copy text[from, to) through, splicing the echo occurrences inside it. At+ // each step the leftmost (then longest) occurrence at or beyond the cursor+ // that fits before `to` is emitted; one that runs into the claimed span+ // ahead is left alone and re-sought past that span — matching never+ // touches an emitted token.+ const emitGap = (from: number, to: number): void => {+ let at = from;+ if (sweep) {+ const { values, tokens, next } = sweep;+ while (at < to) {+ let best = -1;+ let bestPos = to;+ for (let k = 0; k < values.length; k++) {+ let p = next[k]!;+ if (p === -1) continue;+ if (p < at) {+ p = text.indexOf(values[k]!, at);+ next[k] = p;+ if (p === -1) continue;+ }+ if (p >= bestPos || p + values[k]!.length > to) continue;+ best = k;+ bestPos = p;+ }+ if (best === -1) break;+ if (bestPos > at) parts.push(text.slice(at, bestPos));+ parts.push(tokens[best]!);+ at = bestPos + values[best]!.length;+ }+ }+ if (at < to) parts.push(text.slice(at, to));+ };+ let cur = 0;+ for (const c of claimed) {+ if (c.end <= cur) continue; // fully inside an already-emitted span+ if (c.abs > cur) emitGap(cur, c.abs);+ // Per-line spans are disjoint by construction; one can only overlap a+ // whole-text PEM block (a bearer value whose class admits `-` running+ // into the block's `-----BEGIN`). The uncovered tail of the later span is+ // emitted as its own token rather than skipped, so nothing claimed is+ // ever left in the output.+ parts.push(`<REDACTED:${c.pattern}>`);+ cur = c.end;+ }+ emitGap(cur, text.length);+ return parts.join('');+}++/**+ * Corpus-write mode [S3#2] for a single text: plan + apply. Returns the+ * redacted text, one finding per claimed span, and the echo dictionary the+ * call collected (see the section comment above for every bound).+ */+export function redactFindings(+ text: string,+ opts: RedactOpts = {},+): { text: string; redactions: SecretFinding[]; echoValues: EchoDictionary } {+ const plan = planRedaction(text, opts);+ return { text: applyRedaction(plan), redactions: plan.redactions, echoValues: plan.echoValues };}diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.tsindex c9b45d2a88..d00e36fdca 100644--- a/src/core/transcripts/ingest.ts+++ b/src/core/transcripts/ingest.ts@@ -29,6 +29,7 @@import type { BrainEngine } from '../engine.ts';import { importFromContent } from '../import-file.ts';+import { canonicalJson } from '../remediation-step.ts';import type { TranscriptAdapter, TranscriptFormat } from './types.ts';import { detectAdapter } from './detect.ts';import {@@ -342,12 +343,24 @@ export async function runTranscriptsIngest(// write so healthy re-runs stay write-free.let needsRaw = true;if (allSkipped) {+ // Active rows only: `allSkipped` means the import hash check+ // (which reads ACTIVE rows) just matched every page, so the+ // base page is alive here by construction — a tombstoned+ // page never reaches this branch (it reads as missing and is+ // re-imported, see the "resurrects the page" e2e). No+ // includeDeleted flag: the probe must never read through a+ // soft-delete the hash check did not.const existing = await engine.getRawData(resolvedBaseSlug, rawSource, {sourceId: opts.sourceId,});+ // Key-order-insensitive compare: JSONB hands keys back in+ // its own canonical order, so a plain JSON.stringify never+ // matched the freshly built object and every healthy re-run+ // rewrote the row.needsRaw =existing.length === 0 ||- JSON.stringify(existing[0].data) !== JSON.stringify(redacted.session.meta.raw);+ canonicalJson(existing[0].data) !==+ canonicalJson(JSON.parse(JSON.stringify(redacted.session.meta.raw)));}if (needsRaw) {await engine.putRawData(resolvedBaseSlug, rawSource, redacted.session.meta.raw, {diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.tsindex f0356edb7b..7f8483e4d1 100644--- a/src/core/transcripts/render.ts+++ b/src/core/transcripts/render.ts@@ -31,7 +31,7 @@ import { safeDump } from 'js-yaml';import { homedir } from 'node:os';import { join } from 'node:path';import { DEFAULT_BYTES_BLOCK } from '../content-sanity.ts';-import { redactFindings } from '../secret-scan.ts';+import { applyRedaction, planRedaction, type EchoDictionary, type RedactionPlan } from '../secret-scan.ts';import { loadPatterns } from '../skillpack/harvest-lint.ts';import { sanitizeForJsonb } from '../batch-rows.ts';import { ensureWellFormed, truncateUtf8 } from '../text-safe.ts';@@ -113,6 +113,30 @@ export function loadImportRedactionPatterns(userPatternsPath?: string): ImportRe* persisted (message text, SPEAKER labels, title, raw-meta string fields).* Throws on scanner or pattern failure — page writes are FAIL-CLOSED (unlike* the hook corpus lane, these pages are searchable and synced).+ *+ * Detector classes (all from `secret-scan.ts`, format-based — not just vendor+ * prefixes): vendor key shapes (anthropic/openai/voyage/github/gitlab/slack/+ * aws/google/stripe/sendgrid/twilio/supabase/npm/huggingface/gbrain), JWTs,+ * whole-block PEM private keys, `Bearer <token>` headers, connection strings+ * carrying inline credentials, and — opted in for THIS lane — the+ * high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignment heuristic (value must+ * carry a digit and clear the entropy gate). Transcripts are the corpus where+ * a pasted `.env` line is most likely, so recall wins over the false-positive+ * cost here; the push gate and compiled-context scan keep the heuristic off.+ * Every match becomes `<REDACTED:pattern>`; user patterns become+ * `<REDACTED:user-pattern>`.+ *+ * TWO PHASES, ONE SESSION-WIDE ECHO DICTIONARY. Phase 1 PLANS every persisted+ * field (scan + claimed spans); the eligible bearer / high-entropy values+ * every field claims accumulate in one `echoValues` map under the scanner's+ * shared floors and single cap. Phase 2 APPLIES each plan, and the splice+ * reads the FULL map — so a token claimed in a tool message's+ * `Authorization: Bearer …` header is also scrubbed where the assistant+ * echoed it bare in ANOTHER message (or the title, a speaker label, a+ * metadata value), whichever order the two appear in. Redacting each field+ * independently left those cross-field echoes in the page. The per-field+ * `redactions` that feed `redactionCount` (the receipt) are unchanged by the+ * echo pass: an echo is not a claim and adds no finding.*/export function redactSession(session: ParsedSession,@@ -121,15 +145,19 @@ export function redactSession(const patterns = opts.patterns ?? loadImportRedactionPatterns(opts.userPatternsPath);let redactionCount = 0;let imperativesFlagged = 0;+ const echoValues: EchoDictionary = new Map();- const clean = (text: string): string => {+ const plan = (text: string): RedactionPlan =>// sanitizeForJsonb (NUL-strip + well-form): transcripts capture raw tool// output that legitimately carries U+0000, which Postgres text/jsonb// reject at the write boundary (#4392).- let out = sanitizeForJsonb(text);- const r = redactFindings(out);- redactionCount += r.redactions.length;- out = r.text;+ // highEntropy: transcripts opt into the assignment heuristic (see doc+ // comment above) — the shared scanner keeps it off by default.+ planRedaction(sanitizeForJsonb(text), { highEntropy: true, echoValues });++ const apply = (p: RedactionPlan): string => {+ redactionCount += p.redactions.length;+ let out = applyRedaction(p);for (const { regex } of patterns) {out = out.replace(regex, () => {redactionCount++;@@ -139,7 +167,8 @@ export function redactSession(return out;};- const messages = session.messages.map((m) => {+ // Phase 1: plan every field.+ const planned = session.messages.map((m) => {for (const re of IMPERATIVE_RES) {if (re.test(m.text)) {imperativesFlagged++;@@ -149,25 +178,34 @@ export function redactSession(// Speaker labels are persisted into the anchor line, so they get the// same redaction as bodies (a secret or private name in a display name// must not bypass the scan).- return {- ...m,- text: clean(m.text),- ...(m.speaker ? { speaker: clean(m.speaker) } : {}),- };+ return { m, text: plan(m.text), speaker: m.speaker ? plan(m.speaker) : undefined };});+ const titlePlan = session.meta.title ? plan(session.meta.title) : undefined;+ // Flatness is ENFORCED, not assumed: strings are planned; primitive+ // scalars pass; anything nested (arrays/objects an adapter let through+ // from hostile export data) is DROPPED — it would reach putRawData+ // unscanned otherwise.+ const rawEntries: Array<{ key: string; plan: RedactionPlan | null; scalar: unknown }> = [];+ if (session.meta.raw) {+ for (const [key, v] of Object.entries(session.meta.raw)) {+ if (typeof v === 'string') rawEntries.push({ key, plan: plan(v), scalar: undefined });+ else if (v === null || typeof v === 'number' || typeof v === 'boolean') {+ rawEntries.push({ key, plan: null, scalar: v });+ }+ }+ }+ // Phase 2: apply with the complete dictionary.+ const messages = planned.map(({ m, text, speaker }) => ({+ ...m,+ text: apply(text),+ ...(speaker ? { speaker: apply(speaker) } : {}),+ }));const meta = { ...session.meta };- if (meta.title) meta.title = clean(meta.title);+ if (titlePlan) meta.title = apply(titlePlan);if (meta.raw) {- // Flatness is ENFORCED, not assumed: strings are cleaned; primitive- // scalars pass; anything nested (arrays/objects an adapter let through- // from hostile export data) is DROPPED — it would reach putRawData- // unscanned otherwise.const raw: Record<string, unknown> = {};- for (const [k, v] of Object.entries(meta.raw)) {- if (typeof v === 'string') raw[k] = clean(v);- else if (v === null || typeof v === 'number' || typeof v === 'boolean') raw[k] = v;- }+ for (const e of rawEntries) raw[e.key] = e.plan ? apply(e.plan) : e.scalar;meta.raw = raw;}diff --git a/src/core/write-through.ts b/src/core/write-through.tsindex a42367b79b..805ac67c1d 100644--- a/src/core/write-through.ts+++ b/src/core/write-through.ts@@ -282,6 +282,13 @@ function scannerSourcePath(scanRoot: string, filePath: string): string {* A NULL `source_path` means the page was born via put/capture and has no* file of record yet — the slug-derived path stays correct for those.*+ * `opts.includeDeleted`: resolve from a soft-deleted row too. The default+ * reads ACTIVE rows only (a tombstone must not steer a live write), but the+ * purge remediation path in `delete_page` retries the artifact removal for a+ * TOMBSTONE — whose recorded `source_path` the active-row read would miss,+ * falling back to the slug-derived twin and reporting a clean+ * `file_not_present` while the real file survives for sync to resurrect.+ ** Shared by `writePageThrough` AND the facts fence writer (#4204): the fence* appends to the page's file, so both writers MUST compute the identical* path or the fence lands in a file sync never reads back and the next@@ -291,6 +298,7 @@ export async function resolvePageWriteTarget(engine: BrainEngine,slug: string,sourceId: string,+ opts: { includeDeleted?: boolean } = {},): Promise<PageWriteTarget> {let filePath: string;let writeRoot: string;@@ -307,7 +315,7 @@ export async function resolvePageWriteTarget(const sourceLocalPath = rawLocalPath ? msysToNativePath(rawLocalPath) : null;const pathRows = await engine.executeRaw<{ source_path: string | null; source_uri: string | null }>(- `SELECT source_path, source_uri FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL LIMIT 1`,+ `SELECT source_path, source_uri FROM pages WHERE source_id = $1 AND slug = $2${opts.includeDeleted ? '' : ' AND deleted_at IS NULL'} LIMIT 1`,[sourceId, slug],);const recordedPath = sanitizeRecordedSourcePath(pathRows[0]?.source_path);diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 36c2a7f1e7..0a3e86c2dd 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.50.4.0 -->+<!-- gbrain-template-stamp: 0.50.5.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/child-job-runner.test.ts b/test/child-job-runner.test.tsindex 6bd55e3c50..81a43e3786 100644--- a/test/child-job-runner.test.ts+++ b/test/child-job-runner.test.ts@@ -111,6 +111,21 @@ describe('runJobInChild (real children)', () => {expect(result.argv).toEqual(['jobs', 'run-child', '--job-id', '77']);}, TEST_TIMEOUT_MS);+ // The shell opt-in travels to the isolated child as a FLAG (buildChildArgs):+ // the child re-runs the cwd-.env quarantine in the worker's cwd, so an+ // env-only handoff of GBRAIN_ALLOW_SHELL_JOBS would be dropped again there.+ test('--allow-shell-jobs pass-through: opts.env GBRAIN_ALLOW_SHELL_JOBS=1 appends the flag; any other value does not', async () => {+ const harness = makeHarness(+ 'argv-echo',+ `writeOutcome({ outcome: 'success', result: { argv: process.argv.slice(2) } });\n` ++ `process.exit(0);\n`,+ );+ const on = (await runJobInChild({ ...baseOpts(harness), env: { ...process.env, GBRAIN_ALLOW_SHELL_JOBS: '1' } })) as { argv: string[] };+ expect(on.argv).toEqual(['jobs', 'run-child', '--job-id', '77', '--allow-shell-jobs']);+ const off = (await runJobInChild({ ...baseOpts(harness), env: { ...process.env, GBRAIN_ALLOW_SHELL_JOBS: 'true' } })) as { argv: string[] };+ expect(off.argv).toEqual(['jobs', 'run-child', '--job-id', '77']);+ }, TEST_TIMEOUT_MS);+test('error outcome (exit 0) throws the reconstructed class', async () => {const harness = makeHarness('error-unrecoverable',diff --git a/test/cli-args.test.ts b/test/cli-args.test.tsindex ee40e32752..0ae4fb7dbf 100644--- a/test/cli-args.test.ts+++ b/test/cli-args.test.ts@@ -113,5 +113,13 @@ describe('#4602 — boolean flags consume a literal true/false value token', ()const params = parseOpArgs(operationsByName.add_link, ['page-a', 'page-b', '--json=false']);expect(params).toEqual({ from: 'page-a', to: 'page-b', json: false });});++ test('delete <slug> --purge derives from the contract (boolean param → flag, no cli.ts special case)', () => {+ expect(findUnknownOpFlag(operationsByName.delete_page, ['people/alice-example', '--purge'])).toBeNull();+ expect(parseOpArgs(operationsByName.delete_page, ['people/alice-example', '--purge']))+ .toEqual({ slug: 'people/alice-example', purge: true });+ expect(parseOpArgs(operationsByName.delete_page, ['people/alice-example', '--purge=false']))+ .toEqual({ slug: 'people/alice-example', purge: false });+ });});diff --git a/test/cli-cwd-dotenv-quarantine.test.ts b/test/cli-cwd-dotenv-quarantine.test.tsnew file mode 100644index 0000000000..70c4aa3c9f--- /dev/null+++ b/test/cli-cwd-dotenv-quarantine.test.ts@@ -0,0 +1,1091 @@+/**+ * End-to-end: a `.env` in the CURRENT DIRECTORY must not be able to make the+ * gbrain CLI load code. Bun auto-loads cwd `.env` files (compiled binaries+ * included) and expands `${VAR}` inside them, so both the relative and the+ * `${PWD}`-expanded spellings of a code-loading variable are tried here.+ *+ * This test deliberately does NOT use the shared `cli-spawn.ts` helper under+ * test/helpers/: that helper passes `--no-env-file`, which would keep Bun from loading the hostile `.env`+ * and make every assertion below vacuous. The CLI is spawned directly with a+ * hermetic env (HOME / GBRAIN_HOME in a scratch dir) and the hostile dir as+ * cwd. The quarantine warning on stderr only appears when Bun really loaded+ * the file, so it doubles as the harness self-check.+ */+import { spawn as nodeSpawn } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { afterAll, describe, expect, test } from 'bun:test';+import { cwdIsOperatorConfigDir } from '../src/core/cli-preflight.ts';+import { withEnv } from './helpers/with-env.ts';++function findRepoRoot(from: string): string {+ let dir = from;+ for (;;) {+ if (existsSync(join(dir, 'src', 'cli.ts'))) return dir;+ const parent = dirname(dir);+ if (parent === dir) throw new Error(`no src/cli.ts above ${from}`);+ dir = parent;+ }+}+const REPO_ROOT = findRepoRoot(import.meta.dir);+const CLI_PATH = join(REPO_ROOT, 'src', 'cli.ts');+// The compiled case must RUN where a binary exists: `bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts`+// (bin/ is gitignored); GBRAIN_COMPILED_BIN points at a binary built elsewhere.+const COMPILED_BIN = process.env.GBRAIN_COMPILED_BIN ?? join(REPO_ROOT, 'bin', 'gbrain');+const PREFLIGHT_MODULE = join(REPO_ROOT, 'src', 'core', 'cli-preflight.ts');++const EXPECTED_WARNING =+ '[env] Ignoring GBRAIN_GUARDRAILS_MODULE because a .env file in the current directory ' ++ 'assigns it — cwd .env files are untrusted for security settings. Export it from your ' ++ 'shell or set it in ~/.gbrain/.env.';++const scratch: string[] = [];+afterAll(() => { for (const d of scratch) rmSync(d, { recursive: true, force: true }); });++/** A cloned-repo lookalike: `.env` naming a module inside the repo whose top level drops a marker. */+function hostileRepo(envLine: (dir: string) => string): { dir: string; marker: string } {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-hostile-repo-'));+ scratch.push(dir);+ const marker = join(dir, 'PROBE_RAN');+ mkdirSync(join(dir, 'tooling'));+ writeFileSync(+ join(dir, 'tooling', 'probe.ts'),+ `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, 'ran');\nexport default undefined;\n`,+ );+ writeFileSync(join(dir, '.env'), envLine(dir) + '\n');+ return { dir, marker };+}++function hermeticEnv(cwd: string, extra: Record<string, string> = {}): Record<string, string> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-hostile-home-'));+ scratch.push(home);+ return {+ PATH: process.env.PATH ?? '/usr/bin:/bin',+ HOME: home,+ GBRAIN_HOME: home,+ PWD: cwd, // what a shell would set; feeds Bun's ${PWD} expansion+ GBRAIN_SKIP_STARTUP_HOOKS: '1',+ ...extra,+ };+}++// Reap a hung child before bun's per-test ceiling fires. Named (not a trailing+// numeric literal) so the run-unit-shard timeout-pin lint reads it as a kill+// timer, not a hand-pinned test timeout; the test itself inherits the bunfig default.+const CHILD_KILL_AFTER_MS = 55_000;+// Fixture-body timings (interpolated into the spawned entries' source).+const KEEPALIVE_INTERVAL_MS = 1000; // an idle setInterval that keeps a signal-test child alive+const GRACEFUL_EXIT_DELAY_MS = 400; // a graceful-shutdown handler's delay before it exits++async function runCli(cmd: string[], cwd: string, env: Record<string, string>) {+ const proc = Bun.spawn(cmd, { cwd, env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });+ const timer = setTimeout(() => { try { proc.kill(); } catch { /* exited */ } }, CHILD_KILL_AFTER_MS);+ try {+ const [stdout, stderr, exitCode] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ proc.exited,+ ]);+ return { stdout, stderr, exitCode };+ } finally {+ clearTimeout(timer);+ }+}++describe('cwd .env cannot drive GBRAIN_GUARDRAILS_MODULE (advisory PoC)', () => {+ const cases: Array<[string, (dir: string) => string]> = [+ ['relative spec', () => 'GBRAIN_GUARDRAILS_MODULE=./tooling/probe.ts'],+ ['${PWD}-expanded absolute spec', () => 'GBRAIN_GUARDRAILS_MODULE=${PWD}/tooling/probe.ts'],+ ];++ for (const [label, envLine] of cases) {+ // A3-3: a cwd .env assigning a non-empty GBRAIN_GUARDRAILS_MODULE now fails+ // CLOSED — the module still never runs (marker absent), but instead of+ // quarantining + re-running (the old exit 0) preflight refuses (exit 1), so+ // the process never continues without the firewall the assignment implied.+ test(`${label}: gbrain --version from the hostile dir runs no code and refuses (fail-closed)`, async () => {+ const { dir, marker } = hostileRepo(envLine);+ const r = await runCli([process.execPath, CLI_PATH, '--version'], dir, hermeticEnv(dir));+ expect(existsSync(marker)).toBe(false);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain(EXPECTED_WARNING); // the quarantine warning still prints …+ expect(r.stderr).toContain("refusing to run without the operator's firewall"); // … then the refusal+ expect(r.stdout).not.toMatch(/^gbrain \d/);+ });+ }++ test('control: the same module exported from the shell (absolute path) IS loaded', async () => {+ const { dir, marker } = hostileRepo(() => 'UNRELATED=1');+ const clean = mkdtempSync(join(tmpdir(), 'gbrain-clean-cwd-'));+ scratch.push(clean);+ const env = hermeticEnv(clean, { GBRAIN_GUARDRAILS_MODULE: join(dir, 'tooling', 'probe.ts') });+ const r = await runCli([process.execPath, CLI_PATH, '--version'], clean, env);+ expect(existsSync(marker)).toBe(true); // operator-provided → loader ran the module+ expect(r.exitCode).toBe(1); // …and fail-closed on "registered no guardrail provider"+ expect(r.stderr).toContain('registered no guardrail provider');+ expect(r.stderr).not.toContain('[env] Ignoring');+ });++ // A3-3: fail-CLOSED when a cwd .env assigns GBRAIN_GUARDRAILS_MODULE. Key+ // presence, not value: Bun merges the file before gbrain starts and never+ // overrides a live variable, so an operator-exported module cannot be told+ // apart from the file's. Dropping it and re-running would leave the child+ // with NO firewall (the #3688 contract is fail-closed), so preflight refuses+ // to run at all rather than silently downgrade.+ test('fail-closed: a cwd .env assigning GBRAIN_GUARDRAILS_MODULE (operator also exported one) refuses to run — exit 1, module NOT loaded', async () => {+ const { dir, marker } = hostileRepo(() => 'GBRAIN_GUARDRAILS_MODULE=./tooling/probe.ts');+ const env = hermeticEnv(dir, { GBRAIN_GUARDRAILS_MODULE: join(dir, 'tooling', 'probe.ts') });+ const r = await runCli([process.execPath, CLI_PATH, '--version'], dir, env);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain("refusing to run without the operator's firewall");+ expect(existsSync(marker)).toBe(false); // the module never imported+ expect(r.stdout).not.toMatch(/^gbrain \d/);+ });++ test('control: an exported GBRAIN_GUARDRAILS_MODULE survives when the cwd .env assigns a DIFFERENT protected key — the re-run still loads it', async () => {+ const { dir, marker } = hostileRepo(() => 'GBRAIN_ALLOW_SHELL_JOBS=1'); // a different protected key+ const env = hermeticEnv(dir, { GBRAIN_GUARDRAILS_MODULE: join(dir, 'tooling', 'probe.ts') });+ const r = await runCli([process.execPath, CLI_PATH, '--version'], dir, env);+ // The other key is quarantined and the process re-runs; the exported module+ // rides the sanitized env and the loader still imports it (marker written),+ // then fail-closes on the probe registering zero providers.+ expect(existsSync(marker)).toBe(true);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain('registered no guardrail provider');+ expect(r.stderr).not.toContain("refusing to run without the operator's firewall");+ });++ const compiledTest = existsSync(COMPILED_BIN) ? test : test.skip;+ compiledTest('compiled binary: same fail-closed refusal (bin/gbrain present)', async () => {+ const { dir, marker } = hostileRepo(() => 'GBRAIN_GUARDRAILS_MODULE=./tooling/probe.ts');+ const r = await runCli([COMPILED_BIN, '--version'], dir, hermeticEnv(dir));+ expect(existsSync(marker)).toBe(false);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain(EXPECTED_WARNING);+ expect(r.stderr).toContain("refusing to run without the operator's firewall");+ });+});++// ── Preflight ORDER: quarantine → $GBRAIN_HOME/.gbrain/.env → guardrails ────+//+// Step 2 of cli-preflight.ts exists so the operator-owned ~/.gbrain/.env can+// be the home for GBRAIN_GUARDRAILS_MODULE; step 1 runs first so a cwd .env+// cannot pick WHICH home that is (GBRAIN_HOME is on the protected list).+describe('cli preflight ordering: cwd quarantine → ~/.gbrain/.env → guardrails loader', () => {+ test('the operator-owned $GBRAIN_HOME/.gbrain/.env IS honored as the home for GBRAIN_GUARDRAILS_MODULE', async () => {+ const { dir, marker } = hostileRepo(() => 'UNRELATED=1'); // probe lives here; its .env is harmless+ const clean = mkdtempSync(join(tmpdir(), 'gbrain-clean-cwd-'));+ scratch.push(clean);+ const env = hermeticEnv(clean);+ // configDir() === $GBRAIN_HOME/.gbrain — the loader reads <configDir>/.env.+ mkdirSync(join(env.GBRAIN_HOME, '.gbrain'), { recursive: true });+ writeFileSync(+ join(env.GBRAIN_HOME, '.gbrain', '.env'),+ `GBRAIN_GUARDRAILS_MODULE=${join(dir, 'tooling', 'probe.ts')}\n`,+ );+ const r = await runCli([process.execPath, CLI_PATH, '--version'], clean, env);+ expect(existsSync(marker)).toBe(true); // operator home → loader ran the module …+ expect(r.exitCode).toBe(1); // … and fail-closed on "registered no guardrail provider"+ expect(r.stderr).toContain('registered no guardrail provider');+ expect(r.stderr).not.toContain('[env] Ignoring');+ });++ test('a cwd .env cannot relocate GBRAIN_HOME to smuggle in its own .gbrain/.env: quarantined BEFORE the config dir resolves', async () => {+ const { dir, marker } = hostileRepo(() => 'GBRAIN_HOME=${PWD}/evil-home');+ // The planted "home" carries a .gbrain/.env naming the probe as guardrails module.+ mkdirSync(join(dir, 'evil-home', '.gbrain'), { recursive: true });+ writeFileSync(+ join(dir, 'evil-home', '.gbrain', '.env'),+ `GBRAIN_GUARDRAILS_MODULE=${join(dir, 'tooling', 'probe.ts')}\n`,+ );+ const env = hermeticEnv(dir);+ delete env.GBRAIN_HOME; // exported vars beat .env in Bun; the attack needs the .env value to land+ const r = await runCli([process.execPath, CLI_PATH, '--version'], dir, env);+ expect(existsSync(marker)).toBe(false);+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toMatch(/^gbrain \d/);+ expect(r.stderr).toContain('[env] Ignoring GBRAIN_HOME because a .env file in the current directory assigns it');+ });+});++// ── Descendants: the sanitized re-run from a neutral cwd (A2) ────────────────+//+// Removing a key from the parent environment is invisible to children spawned+// without an explicit `env` — Bun hands them its startup environ snapshot,+// cwd-.env values included. Preflight therefore re-runs gbrain once from a+// fresh EMPTY temp dir with the sanitized environment whenever the quarantine+// dropped anything, and the re-run chdirs back in its own preflight+// (cli-preflight.ts). The entry script below stands in for any gbrain command+// that shells out from the cwd: real preflight, then `git status --porcelain`+// with NO env/cwd option — the exact spawn shape the snapshot would poison —+// plus a `sh` PRESENCE probe: `GIT_SSL_NO_VERIFY=` (empty) still disables TLS+// verification in git, so a dropped key must be ABSENT, not ''.+const GIT_BIN = Bun.which('git');+// util-linux `script` gives the wrapper a real pty so process.stdin.isTTY is+// true — the only way to exercise the tty (ignore-only) SIGINT branch faithfully.+const SCRIPT_BIN = Bun.which('script');+/**+ * The command line handed to `script -c`. `script` runs it through `$SHELL`+ * (falling back to /bin/sh — hermeticEnv sets no SHELL), and the pty delivers+ * Ctrl-C to the WHOLE foreground group, that shell included. Which /bin/sh it+ * is then decides what `script` reports, not the wrapper or the re-run:+ * - bash waits for its foreground child and, when the child did NOT die of+ * SIGINT, treats the signal as handled and relays the child's status (42);+ * - dash (/bin/sh on Debian/Ubuntu, whose package also patches out upstream+ * dash's `sh -c cmd` → exec optimisation) remembers the SIGINT while it+ * waits, then re-raises it on itself once the child returns — `script` sees+ * a child killed by SIGINT and exits 128+2 = 130 although wrapper and+ * re-run both behaved (the ubuntu-latest-only failure of the two pty tests).+ * `exec` replaces the shell with the wrapper, so no intermediate shell is left+ * in the foreground group and the status `script` relays is the wrapper's under+ * either shell. Redirections stay on the exec line: the shell applies them+ * before it execs, so the all-stdio-non-tty shape below still holds.+ */+const ptyCommand = (argv: string, redirects = '') => `exec ${argv}${redirects}`;++const HOSTILE_ENV_LINES = [+ 'GBRAIN_ALLOW_SHELL_JOBS=1',+ 'GIT_CONFIG_COUNT=1',+ 'GIT_CONFIG_KEY_0=core.fsmonitor',+ 'GIT_CONFIG_VALUE_0=./tooling/evil.sh',+ 'GIT_SSL_NO_VERIFY=1', // presence-checked by git: must end up unset, never ''+ 'PROJECT_NAME=demo', // an ordinary project variable: must keep loading+];+const HOSTILE_WARNING_KEYS =+ 'GBRAIN_ALLOW_SHELL_JOBS, GIT_CONFIG_COUNT, GIT_CONFIG_KEY_0, GIT_CONFIG_VALUE_0, GIT_SSL_NO_VERIFY';++/** The default entry body: git probe + presence probe + a one-line report, exit 7. */+const PROBE_BODY = [+ `const r = Bun.spawnSync(['git', 'status', '--porcelain']); // no env/cwd option: inherits the startup snapshot, runs in process.cwd()`,+ `const sh = Bun.spawnSync(['sh', '-c', 'echo "GIT_SSL_NO_VERIFY=[\${GIT_SSL_NO_VERIFY-unset}]"']);`,+ 'process.stdout.write(`GIT_EXIT=${r.exitCode} GIT_CONFIG_COUNT=${JSON.stringify(process.env.GIT_CONFIG_COUNT ?? null)} ' ++ 'PROJECT_NAME=${process.env.PROJECT_NAME ?? ""} CWD=${process.cwd()} ' ++ 'MARKER=${JSON.stringify(process.env.GBRAIN_CWD_ENV_QUARANTINED ?? null)} ' ++ 'ARGS=${JSON.stringify(process.argv.slice(2))} ${sh.stdout.toString().trim()}\\n`);',+ `process.exit(7);`,+].join('\n');++interface HostileGitRepo { dir: string; evilMarker: string; entry: string; ready: string }++/**+ * Hostile checkout: a git repo whose .env plants a git config injection+ * (core.fsmonitor → marker script) next to a GBRAIN_* opt-in. `envLines`+ * replaces the default .env body (a function of the dir for absolute paths);+ * `entryBody` replaces the probe that runs after preflight.+ */+function hostileGitRepo(opts: { envLines?: (dir: string) => string[]; entryBody?: string } = {}): HostileGitRepo {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-hostile-git-'));+ scratch.push(dir);+ Bun.spawnSync([GIT_BIN!, 'init', '-q'], { cwd: dir });+ mkdirSync(join(dir, 'tooling'));+ const evilMarker = join(dir, 'EVIL_RAN');+ writeFileSync(join(dir, 'tooling', 'evil.sh'), `#!/bin/sh\ntouch ${JSON.stringify(evilMarker)}\n`, { mode: 0o755 });+ writeFileSync(join(dir, '.env'), [...(opts.envLines ?? (() => HOSTILE_ENV_LINES))(dir), ''].join('\n'));+ const entry = join(dir, 'tooling', 'entry.ts');+ const ready = join(dir, 'READY');+ writeFileSync(entry, [+ `import { writeFileSync, renameSync } from 'node:fs';`,+ `import { runCliPreflight } from ${JSON.stringify(PREFLIGHT_MODULE)};`,+ `const READY = ${JSON.stringify(ready)};`,+ // Atomic READY write: a plain writeFileSync can be observed mid-write and+ // `Number('')` reads back 0 — write a .tmp then renameSync (atomic on the+ // same fs) so waitReady never sees a partial file.+ `const writeReady = (v) => { writeFileSync(READY + '.tmp', String(v)); renameSync(READY + '.tmp', READY); };`,+ `if (process.argv.includes('--preflight')) await runCliPreflight();`,+ opts.entryBody ?? PROBE_BODY,+ '',+ ].join('\n'));+ return { dir, evilMarker, entry, ready };+}++const warningLines = (stderr: string) => stderr.split('\n').filter((l) => l.startsWith('[env] Ignoring'));++/** Poll for the READY file the signal-test entries write once their handlers are installed. */+async function waitReady(path: string): Promise<number> {+ const deadline = Date.now() + 15_000;+ while (Date.now() < deadline) {+ if (existsSync(path)) return Number(readFileSync(path, 'utf8'));+ await new Promise((r) => setTimeout(r, 25));+ }+ throw new Error('entry never signalled readiness');+}++async function gone(pid: number): Promise<boolean> {+ const deadline = Date.now() + 3_000;+ while (Date.now() < deadline) {+ try { process.kill(pid, 0); } catch { return true; }+ await new Promise((r) => setTimeout(r, 25));+ }+ return false;+}++describe('a cwd .env cannot reach the programs gbrain spawns (sanitized re-run)', () => {+ test.skipIf(!GIT_BIN)('control: without preflight the planted git config runs the script and the TLS knob is live (the PoC is live here)', async () => {+ const { dir, evilMarker, entry } = hostileGitRepo();+ const r = await runCli([process.execPath, entry], dir, hermeticEnv(dir));+ expect(r.exitCode).toBe(7);+ expect(existsSync(evilMarker)).toBe(true);+ expect(r.stdout).toContain('GIT_SSL_NO_VERIFY=[1]');+ });++ test.skipIf(!GIT_BIN)('with preflight: git never sees the injection, dropped keys are ABSENT (not ""), cwd + argv restored, exit code passes through, ONE warning', async () => {+ const { dir, evilMarker, entry } = hostileGitRepo();+ const r = await runCli([process.execPath, entry, '--preflight', '--probe=./relative/thing'], dir, hermeticEnv(dir));+ expect(existsSync(evilMarker)).toBe(false);+ expect(r.exitCode).toBe(7); // the re-run's status, not the wrapper's+ expect(r.stdout).toContain('GIT_EXIT=0');+ expect(r.stdout).toContain('GIT_CONFIG_COUNT=null'); // in-process view: absent+ expect(r.stdout).toContain('GIT_SSL_NO_VERIFY=[unset]'); // presence probe: the sh child never saw the key+ expect(r.stdout).toContain('PROJECT_NAME=demo'); // unprotected keys still load from the cwd .env+ expect(r.stdout).toContain(`CWD=${realpathSync(dir)}`); // the re-run switched back to the caller's directory+ expect(r.stdout).toContain('MARKER=null'); // the internal marker is not visible to the command+ expect(r.stdout).toContain('ARGS=["--preflight","--probe=./relative/thing"]'); // relative argv preserved verbatim+ const warnings = warningLines(r.stderr);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain(`Ignoring ${HOSTILE_WARNING_KEYS} because a .env file in the current directory assigns it`);+ });++ // The marker that tells the re-run "you already hopped" is a plain env var,+ // so a hostile .env can plant one. It is honoured only when the process's+ // startup cwd IS the .env-free neutral dir it names — impossible from a+ // hostile checkout, whose startup cwd has a .env by construction.+ const forged: Array<[label: string, value: (dir: string) => string]> = [+ ['flag-like value', () => '1'],+ ['the real parent pid (the old ppid-shaped guard)', () => String(process.pid)],+ ['JSON naming the hostile dir as neutral', (dir) => `'${JSON.stringify({ cwd: dir, neutral: dir })}'`],+ ['JSON naming a genuine .env-free dir as neutral', (dir) => {+ const decoy = mkdtempSync(join(tmpdir(), 'gbrain-decoy-neutral-'));+ scratch.push(decoy);+ return `'${JSON.stringify({ cwd: dir, neutral: decoy })}'`;+ }],+ ];+ for (const [label, value] of forged) {+ test.skipIf(!GIT_BIN)(`forged marker (${label}) planted in the .env does not suppress the hop`, async () => {+ const { dir, evilMarker, entry } = hostileGitRepo({+ envLines: (d) => [...HOSTILE_ENV_LINES, `GBRAIN_CWD_ENV_QUARANTINED=${value(d)}`],+ });+ const r = await runCli([process.execPath, entry, '--preflight'], dir, hermeticEnv(dir));+ expect(existsSync(evilMarker)).toBe(false);+ expect(r.exitCode).toBe(7);+ expect(r.stdout).toContain('GIT_EXIT=0');+ expect(r.stdout).toContain('GIT_SSL_NO_VERIFY=[unset]');+ expect(r.stdout).toContain('MARKER=null');+ const warnings = warningLines(r.stderr);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain('GBRAIN_CWD_ENV_QUARANTINED'); // planted copy: dropped and named like any protected key+ });+ }++ test.skipIf(!GIT_BIN)('harness self-check: a planted JSON marker really lands in process.env (no preflight)', async () => {+ const { dir, entry } = hostileGitRepo({+ envLines: (d) => [...HOSTILE_ENV_LINES, `GBRAIN_CWD_ENV_QUARANTINED='${JSON.stringify({ cwd: d, neutral: d })}'`],+ });+ const r = await runCli([process.execPath, entry], dir, hermeticEnv(dir));+ expect(r.stdout).toContain(`MARKER=${JSON.stringify(JSON.stringify({ cwd: dir, neutral: dir }))}`);+ });++ test.skipIf(!GIT_BIN)('depth 2: a hopped process that spawns gbrain again from the hostile cwd hops once more and stops — exit code and exactly two warnings', async () => {+ const { dir, evilMarker, entry } = hostileGitRepo({+ entryBody: [+ `if (process.argv.includes('--level1')) { Bun.spawnSync(['git', 'status', '--porcelain']); process.exit(5); }`,+ // level 0: the shape of every gbrain self-spawn — explicit env (the quarantined view), the hostile cwd.+ `const r = Bun.spawnSync([process.execPath, process.argv[1], '--preflight', '--level1'], { env: process.env, cwd: process.cwd(), stdio: ['ignore', 'inherit', 'inherit'] });`,+ `process.exit(r.exitCode ?? 1);`,+ ].join('\n'),+ });+ const r = await runCli([process.execPath, entry, '--preflight'], dir, hermeticEnv(dir));+ expect(r.exitCode).toBe(5);+ expect(existsSync(evilMarker)).toBe(false);+ expect(warningLines(r.stderr)).toHaveLength(2); // one per subtree that started in the hostile cwd; no runaway+ });++ test.skipIf(!GIT_BIN)('SIGTERM sent to the wrapper is forwarded: the re-run exits 99 by its own handler, the wrapper relays 99, the re-run is gone', async () => {+ const { dir, entry, ready } = hostileGitRepo({+ entryBody: [+ `process.on('SIGTERM', () => process.exit(99));`,+ `writeReady(process.pid);`,+ `setInterval(() => {}, 1000);`,+ ].join('\n'),+ });+ const proc = Bun.spawn([process.execPath, entry, '--preflight'], { cwd: dir, env: hermeticEnv(dir), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });+ const timer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* exited */ } }, CHILD_KILL_AFTER_MS);+ try {+ const childPid = await waitReady(ready);+ expect(childPid).not.toBe(proc.pid); // the entry ran in the re-run, not in the wrapper+ proc.kill('SIGTERM');+ const code = await proc.exited;+ expect(code).toBe(99);+ expect(await gone(childPid)).toBe(true);+ } finally {+ clearTimeout(timer);+ }+ });++ test.skipIf(!GIT_BIN)('the re-run killed by SIGKILL → the wrapper exits 137 (128+signal)', async () => {+ const { dir, entry } = hostileGitRepo({ entryBody: `process.kill(process.pid, 'SIGKILL');\nsetInterval(() => {}, 1000);` });+ const r = await runCli([process.execPath, entry, '--preflight'], dir, hermeticEnv(dir));+ expect(r.exitCode).toBe(137);+ });++ // A3-5(b): with a real terminal attached the wrapper's stdin IS a tty, so it+ // takes the ignore-only SIGINT branch. `script` runs the wrapper under a pty;+ // writing \x03 to script's stdin is the terminal Ctrl-C, delivered by the pty+ // to the whole foreground process group (wrapper + re-run) exactly like a real+ // terminal. The tty wrapper does NOT forward, so the re-run receives SIGINT+ // exactly once and its once() graceful handler completes (exit 42) — a second,+ // forwarded delivery would have killed it after once() removed its listener.+ test.skipIf(!GIT_BIN || !SCRIPT_BIN)('Ctrl-C from a real terminal (pty) reaches the re-run exactly once: the tty wrapper ignores SIGINT and the once() graceful handler completes (exit 42)', async () => {+ const { dir, entry, ready } = hostileGitRepo({+ entryBody: [+ // serve-http's shape: once('SIGINT') + a graceful-shutdown delay before exit.+ `process.once('SIGINT', () => { setTimeout(() => process.exit(42), ${GRACEFUL_EXIT_DELAY_MS}); });`,+ `writeReady(process.pid);`,+ `setInterval(() => {}, ${KEEPALIVE_INTERVAL_MS});`,+ ].join('\n'),+ });+ const cmd = ptyCommand(`${process.execPath} ${entry} --preflight`); // exec'd: see ptyCommand+ const proc = Bun.spawn([SCRIPT_BIN!, '-qec', cmd, '/dev/null'], {+ cwd: dir, env: hermeticEnv(dir), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe',+ });+ const drain = (async () => { for await (const _ of proc.stdout) { /* mux pty output */ } })();+ const timer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* exited */ } }, CHILD_KILL_AFTER_MS);+ try {+ await waitReady(ready);+ proc.stdin!.write('\x03'); // terminal Ctrl-C → pty → the foreground group+ proc.stdin!.flush();+ const code = await proc.exited;+ await drain;+ expect(proc.signalCode).toBeNull();+ expect(code).toBe(42);+ } finally {+ clearTimeout(timer);+ }+ });++ // A3-5(b) + E4-6: the mirror case. With NO controlling terminal there is no+ // process-group delivery, so a SIGINT that reaches the wrapper pid alone (a+ // supervisor, cron, a detached agent harness) would orphan the re-run under+ // ignore-only. Such a wrapper forwards it once; the re-run's handler runs+ // (exit 97). `detached: true` starts the wrapper in its own session, which is+ // what actually detaches it from the terminal `bun test` may be running in —+ // piped stdio alone does not (E4-6 below).+ test.skipIf(!GIT_BIN)('SIGINT to a wrapper with NO controlling terminal (own session) is forwarded once: the re-run receives it and exits 97', async () => {+ const { dir, entry, ready } = hostileGitRepo({+ entryBody: [+ `process.on('SIGINT', () => process.exit(97));`,+ `writeReady(process.pid);`,+ `setInterval(() => {}, ${KEEPALIVE_INTERVAL_MS});`,+ ].join('\n'),+ });+ const proc = nodeSpawn(process.execPath, [entry, '--preflight'], { cwd: dir, env: hermeticEnv(dir), detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ proc.stdout!.resume(); proc.stderr!.resume(); // drain+ const exited = new Promise<number | null>((resolve) => proc.on('exit', (code) => resolve(code)));+ const timer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* exited */ } }, CHILD_KILL_AFTER_MS);+ try {+ const childPid = await waitReady(ready);+ expect(childPid).not.toBe(proc.pid); // the handler ran in the re-run+ proc.kill('SIGINT'); // wrapper pid only — no controlling terminal ⇒ nothing else delivers it+ expect(await exited).toBe(97);+ expect(await gone(childPid)).toBe(true);+ } finally {+ clearTimeout(timer);+ }+ });++ // E4-6 (review cycle 4): `process.stdin.isTTY` was the proxy for "a terminal+ // delivers Ctrl-C to the whole group". `gbrain serve --http </dev/null` in a+ // foreground terminal has a non-tty stdin AND a controlling terminal, so+ // Ctrl-C reached wrapper and child and the wrapper forwarded a SECOND SIGINT,+ // aborting the child's once('SIGINT') graceful handler (exit 130). The wrapper+ // now probes for a controlling terminal (open("/dev/tty")) and forwards only+ // when there is none. `script` provides the pty; the shell inside it redirects+ // ALL THREE stdio to non-tty files — the `</dev/null >log 2>&1` shape.+ test.skipIf(!GIT_BIN || !SCRIPT_BIN)('Ctrl-C with a controlling terminal but all three stdio non-tty: the wrapper does NOT forward; the once() graceful handler completes (exit 42)', async () => {+ const { dir, entry, ready } = hostileGitRepo({+ entryBody: [+ `process.once('SIGINT', () => { setTimeout(() => process.exit(42), ${GRACEFUL_EXIT_DELAY_MS}); });`,+ `writeReady(process.pid);`,+ `setInterval(() => {}, ${KEEPALIVE_INTERVAL_MS});`,+ ].join('\n'),+ });+ const out = join(dir, 'wrapper.out');+ const err = join(dir, 'wrapper.err');+ const cmd = ptyCommand(`${process.execPath} ${entry} --preflight`, ` </dev/null >${out} 2>${err}`); // exec'd: see ptyCommand+ const proc = Bun.spawn([SCRIPT_BIN!, '-qec', cmd, '/dev/null'], {+ cwd: dir, env: hermeticEnv(dir), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe',+ });+ const drain = (async () => { for await (const _ of proc.stdout) { /* mux pty output */ } })();+ const timer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* exited */ } }, CHILD_KILL_AFTER_MS);+ try {+ await waitReady(ready);+ proc.stdin!.write('\x03'); // terminal Ctrl-C → pty → the foreground group (wrapper AND re-run)+ proc.stdin!.flush();+ const code = await proc.exited;+ await drain;+ expect(code).toBe(42);+ expect(readFileSync(err, 'utf8')).toContain('[env] Ignoring'); // the wrapper's stderr really was the file, not the pty+ } finally {+ clearTimeout(timer);+ }+ });++ // A3-6(iii): SIGHUP is always forwarded (a supervisor sends it to the wrapper+ // pid alone). The re-run exits 98 by its own handler; the wrapper relays it.+ test.skipIf(!GIT_BIN)('SIGHUP sent to the wrapper is forwarded: the re-run exits 98 by its own handler, the wrapper relays it', async () => {+ const { dir, entry, ready } = hostileGitRepo({+ entryBody: [+ `process.on('SIGHUP', () => process.exit(98));`,+ `writeReady(process.pid);`,+ `setInterval(() => {}, 1000);`,+ ].join('\n'),+ });+ const proc = Bun.spawn([process.execPath, entry, '--preflight'], { cwd: dir, env: hermeticEnv(dir), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });+ const timer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* exited */ } }, CHILD_KILL_AFTER_MS);+ try {+ const childPid = await waitReady(ready);+ proc.kill('SIGHUP');+ const code = await proc.exited;+ expect(code).toBe(98);+ expect(await gone(childPid)).toBe(true);+ } finally {+ clearTimeout(timer);+ }+ });++ // E4-3 (review cycle 4): cli.ts installs its own SIGTERM/SIGHUP handlers+ // (process-cleanup.ts: cleanup pass → exit 143/129) in its import.meta.main+ // block, BEFORE main() reaches preflight. In the wrapper a SIGTERM therefore+ // ran BOTH that handler and the forwarder, and the wrapper exited 143 before+ // the re-run finished and before the neutral dir was removed. The wrapper has+ // no duties of its own, so reexecSanitized removes every pre-existing listener+ // for the forwarded signals: its exit is ALWAYS the child's. This pin goes+ // through the REAL cli.ts (not the preflight-only entry) so cli.ts's handlers+ // are actually installed in the wrapper. The child's graceful shutdown is+ // modelled by an operator-EXPORTED guardrails module: it replaces the child's+ // own prompt SIGTERM exit with a delayed exit(0) and writes a marker first.+ /**+ * An operator-EXPORTED guardrails module that runs `prelude` first, reports+ * its pid through a READY file, then holds its import open — so the real+ * cli.ts child stays alive inside the guardrails loader until a signal (or+ * the watchdog) ends it. `marker` is a path the prelude may write.+ */+ function holdingProvider(prelude: (files: { marker: string }) => string[] = () => []): { path: string; marker: string; ready: string } {+ const d = mkdtempSync(join(tmpdir(), 'gbrain-hold-provider-'));+ scratch.push(d);+ const marker = join(d, 'MARKER');+ const ready = join(d, 'READY');+ const path = join(d, 'provider.mjs');+ writeFileSync(path, [+ `import { writeFileSync, renameSync } from 'node:fs';`,+ ...prelude({ marker }),+ `writeFileSync(${JSON.stringify(ready + '.tmp')}, String(process.pid)); renameSync(${JSON.stringify(ready + '.tmp')}, ${JSON.stringify(ready)});`,+ `setInterval(() => {}, ${KEEPALIVE_INTERVAL_MS});`,+ `await new Promise(() => {});`, // hold the import open+ `export default { id: 'fixture-hold', classify() {} };`,+ '',+ ].join('\n'));+ return { path, marker, ready };+ }+ const hopDirsIn = (tmp: string) => readdirSync(tmp).filter((n) => n.startsWith('gbrain-hop-'));+ /** Poll `cond` until true or `ms` elapsed. */+ async function within(ms: number, cond: () => boolean): Promise<boolean> {+ const deadline = Date.now() + ms;+ while (Date.now() < deadline) {+ if (cond()) return true;+ await new Promise((r) => setTimeout(r, 25));+ }+ return cond();+ }++ test("through cli.ts: SIGTERM to the wrapper — the wrapper outlives the child's graceful exit(0), relays 0, the marker is present, the neutral dir is removed", async () => {+ const { dir } = hostileRepo(() => 'GBRAIN_ALLOW_SHELL_JOBS=1'); // protected, NOT the guardrails key → quarantine + re-run, no refusal+ // The child's cli.ts handler would exit 143 at once; this models a command that shuts down gracefully instead.+ const provider = holdingProvider(({ marker }) => [+ `process.removeAllListeners('SIGTERM');`,+ `process.on('SIGTERM', () => { setTimeout(() => { writeFileSync(${JSON.stringify(marker)}, 'ran'); process.exit(0); }, ${GRACEFUL_EXIT_DELAY_MS}); });`,+ ]);+ const hopTmp = mkdtempSync(join(tmpdir(), 'gbrain-e43-hoptmp-')); // private TMPDIR: the neutral dir is created — and must be removed — in here+ scratch.push(hopTmp);+ const env = hermeticEnv(dir, { GBRAIN_GUARDRAILS_MODULE: provider.path, TMPDIR: hopTmp });+ const proc = Bun.spawn([process.execPath, CLI_PATH, '--version'], { cwd: dir, env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });+ const stdoutP = new Response(proc.stdout).text();+ const stderrP = new Response(proc.stderr).text();+ const timer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* exited */ } }, CHILD_KILL_AFTER_MS);+ let childPid = 0;+ try {+ childPid = await waitReady(provider.ready);+ expect(childPid).not.toBe(proc.pid); // the provider loaded in the re-run, not in the wrapper+ expect(hopDirsIn(hopTmp)).toHaveLength(1); // the neutral dir exists while the child runs+ proc.kill('SIGTERM');+ const [code, stderr] = await Promise.all([proc.exited, stderrP, stdoutP]);+ expect(code).toBe(0); // the CHILD's exit — not cli.ts's own 143+ expect(existsSync(provider.marker)).toBe(true); // written by the child's delayed handler BEFORE the wrapper exited+ expect(hopDirsIn(hopTmp)).toEqual([]); // finally { rmSync(neutral) } ran+ expect(stderr).toContain('Ignoring GBRAIN_ALLOW_SHELL_JOBS because');+ expect(await gone(childPid)).toBe(true);+ } finally {+ clearTimeout(timer);+ if (childPid) { try { process.kill(childPid, 'SIGKILL'); } catch { /* already gone */ } }+ }+ });++ // E5-1 (review cycle 5): a supervisor that tracks the WRAPPER pid escalates+ // to SIGKILL on it (ChildWorkerSupervisor.restartCurrentChild); SIGKILL+ // cannot be forwarded, so the re-run used to survive as an orphan while the+ // supervisor started a replacement. The hop marker now carries the wrapper's+ // pid and the verified re-run runs a 1 s die-with-parent watchdog on+ // `process.ppid` (LIVE in Bun 1.3.13 — measured: it flips to the reaper's pid+ // after the parent dies, whether it exited or was SIGKILLed). The child also+ // removes the (empty) neutral dir the wrapper's own `finally` never reached.+ const WATCHDOG_NOTICE_MS = 4_000; // the watchdog ticks every second; allow for a loaded box+ test('SIGKILL on the wrapper: the re-run notices within seconds, exits (137) and removes the neutral dir the wrapper could not', async () => {+ const { dir } = hostileRepo(() => 'GBRAIN_ALLOW_SHELL_JOBS=1');+ const provider = holdingProvider();+ const hopTmp = mkdtempSync(join(tmpdir(), 'gbrain-e51-hoptmp-'));+ scratch.push(hopTmp);+ const env = hermeticEnv(dir, { GBRAIN_GUARDRAILS_MODULE: provider.path, TMPDIR: hopTmp });+ const proc = Bun.spawn([process.execPath, CLI_PATH, '--version'], { cwd: dir, env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });+ const stdoutP = new Response(proc.stdout).text();+ const stderrP = new Response(proc.stderr).text(); // resolves when the LAST writer (the child) closes the inherited pipe+ const timer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* exited */ } }, CHILD_KILL_AFTER_MS);+ let childPid = 0;+ try {+ childPid = await waitReady(provider.ready);+ expect(childPid).not.toBe(proc.pid);+ expect(hopDirsIn(hopTmp)).toHaveLength(1);+ proc.kill('SIGKILL'); // the supervisor's escalation, aimed at the pid it tracks: the wrapper+ await proc.exited;+ expect(await within(WATCHDOG_NOTICE_MS, () => { try { process.kill(childPid, 0); return false; } catch { return true; } })).toBe(true); // the re-run is gone+ expect(await within(WATCHDOG_NOTICE_MS, () => hopDirsIn(hopTmp).length === 0)).toBe(true); // …and it cleaned up the neutral dir+ const [stderr] = await Promise.all([stderrP, stdoutP]);+ expect(stderr).toContain('[env] sanitized re-run lost its wrapper (killed); exiting');+ } finally {+ clearTimeout(timer);+ if (childPid) { try { process.kill(childPid, 'SIGKILL'); } catch { /* already gone */ } }+ }+ });++ // E4-5 (review cycle 4): dropping a planted HOME must not leave the re-run+ // with NO $HOME — git then fails (`Author identity unknown`, `$HOME not set`)+ // and every raw `process.env.HOME || ''` read resolves INTO the checkout. The+ // sanitized env gets HOME back from os.userInfo().homedir, which Bun derives+ // from the REAL startup environ (passwd when HOME was unset) before the .env+ // merge — the planted value never reaches it (measured on Bun 1.3.13).+ const HOME_PROBE_BODY = `process.stdout.write('HOME=' + JSON.stringify(process.env.HOME ?? null) + '\\n');\nprocess.exit(7);`;+ /** What the wrapper will resolve: userInfo().homedir for a process started with `env` (HOME unset → passwd). */+ async function homeSeenBy(env: Record<string, string>): Promise<string> {+ const p = Bun.spawn(+ [process.execPath, '--no-env-file', '-e', 'process.stdout.write(require("node:os").userInfo().homedir)'],+ { env, stdin: 'ignore', stdout: 'pipe', stderr: 'ignore' },+ );+ const [out] = await Promise.all([new Response(p.stdout).text(), p.exited]);+ return out;+ }++ test.skipIf(!GIT_BIN)('a planted HOME (HOME unset at spawn) is dropped AND the re-run gets the real home back — never the planted path, never empty', async () => {+ const { dir, entry } = hostileGitRepo({ envLines: (d) => [`HOME=${d}`, 'PROJECT_NAME=demo'], entryBody: HOME_PROBE_BODY });+ const env = hermeticEnv(dir);+ delete env.HOME; // cron/systemd shape: nothing exported HOME, so Bun fills it from the .env+ const expected = await homeSeenBy(env);+ expect(expected.length).toBeGreaterThan(0);+ expect(expected).not.toBe(dir);+ const r = await runCli([process.execPath, entry, '--preflight'], dir, env);+ expect(r.exitCode).toBe(7);+ expect(r.stdout).toContain(`HOME=${JSON.stringify(expected)}`);+ const warnings = warningLines(r.stderr);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain('Ignoring HOME because a .env file in the current directory assigns it');+ });++ test.skipIf(!GIT_BIN)("an exported HOME shadowed by a .env assignment (key-presence false drop) comes back as the operator's own value", async () => {+ const { dir, entry } = hostileGitRepo({ envLines: (d) => [`HOME=${d}`], entryBody: HOME_PROBE_BODY });+ const env = hermeticEnv(dir); // HOME exported (scratch home): Bun keeps it, the quarantine still drops it (presence, not value)+ const r = await runCli([process.execPath, entry, '--preflight'], dir, env);+ expect(r.exitCode).toBe(7);+ expect(r.stdout).toContain(`HOME=${JSON.stringify(env.HOME)}`);+ expect(warningLines(r.stderr)[0]).toContain('Ignoring HOME because');+ });++ // A3-6(i): a dev-runtime re-run (`bun src/cli.ts`) must re-insert the runtime+ // flags from process.execArgv, or `--smol`/`--inspect`/`--preload` would be+ // dropped on the hop. Only the re-run reaches entryBody (the wrapper re-execs+ // and exits), so the printed execArgv is the re-run's.+ test.skipIf(!GIT_BIN)('the re-run preserves the dev-runtime execArgv (--smol) across the hop', async () => {+ const { dir, entry } = hostileGitRepo({+ entryBody: `process.stdout.write('EXECARGV=' + JSON.stringify(process.execArgv) + '\\n');\nprocess.exit(7);`,+ });+ const r = await runCli([process.execPath, '--smol', entry, '--preflight'], dir, hermeticEnv(dir));+ expect(r.exitCode).toBe(7);+ expect(r.stdout).toContain('EXECARGV=["--smol"]');+ });++ // E5-2 (review cycle 5): execArgv was copied verbatim, so a RELATIVE runtime+ // path (`bun --preload ./probe.ts src/cli.ts`) resolved from the EMPTY neutral+ // dir and the re-run died with `preload not found`. Path-bearing runtime+ // flags (--preload/-r/--require/--import, --config/-c, --env-file,+ // --tsconfig-override; both `--flag value` and `--flag=value` — Bun reports+ // both spellings verbatim) now have a relative value resolved against the+ // ORIGINAL cwd. pre.ts appends one line per load: parent + re-run = 2.+ const EXECARGV_BODY = `process.stdout.write('EXECARGV=' + JSON.stringify(process.execArgv) + '\\n');\nprocess.exit(7);`;+ function countingPreload(dir: string): { rel: string; abs: string; loads: string } {+ const loads = join(dir, 'PRELOAD_LOADS');+ writeFileSync(join(dir, 'tooling', 'pre.ts'), `import { appendFileSync } from 'node:fs';\nappendFileSync(${JSON.stringify(loads)}, process.pid + '\\n');\n`);+ return { rel: './tooling/pre.ts', abs: join(dir, 'tooling', 'pre.ts'), loads };+ }+ const loadCount = (loads: string) => (existsSync(loads) ? readFileSync(loads, 'utf8').trim().split('\n').length : 0);++ const relativeSpellings: Array<[label: string, argv: (rel: string) => string[]]> = [+ ['--preload ./x (two entries)', (rel) => ['--preload', rel]],+ ['--preload=./x (one entry)', (rel) => [`--preload=${rel}`]],+ ['-r ./x', (rel) => ['-r', rel]],+ ['--smol before --import ./x (order kept)', (rel) => ['--smol', '--import', rel]],+ ];+ for (const [label, argv] of relativeSpellings) {+ test.skipIf(!GIT_BIN)(`a relative runtime path survives the hop: ${label} → loads in the parent AND the re-run, no "preload not found"`, async () => {+ const { dir, entry } = hostileGitRepo({ entryBody: EXECARGV_BODY });+ const pre = countingPreload(dir);+ const r = await runCli([process.execPath, ...argv(pre.rel), entry, '--preflight'], dir, hermeticEnv(dir));+ expect(r.stderr).not.toContain('preload not found');+ expect(r.exitCode).toBe(7);+ expect(loadCount(pre.loads)).toBe(2);+ // The re-run's execArgv carries the ABSOLUTE spelling, other flags untouched, order preserved.+ const expected = argv(pre.rel).map((a) => a.replace(pre.rel, realpathSync(pre.abs)));+ expect(r.stdout).toContain(`EXECARGV=${JSON.stringify(expected)}`);+ });+ }++ test.skipIf(!GIT_BIN)('control: an absolute --preload path is passed through unchanged (still loads twice)', async () => {+ const { dir, entry } = hostileGitRepo({ entryBody: EXECARGV_BODY });+ const pre = countingPreload(dir);+ const r = await runCli([process.execPath, '--preload', pre.abs, entry, '--preflight'], dir, hermeticEnv(dir));+ expect(r.exitCode).toBe(7);+ expect(loadCount(pre.loads)).toBe(2);+ expect(r.stdout).toContain(`EXECARGV=${JSON.stringify(['--preload', pre.abs])}`);+ });++ // A3-4 (red team): a relative `TMPDIR=t` in the .env would make mkdtemp return+ // a relative neutral path, breaking the re-run's realpath marker check. TMPDIR+ // is now protected, so the parent drops it BEFORE makeNeutralDir consults+ // os.tmpdir(); realpathSync then guarantees `neutral` is absolute + canonical.+ // The hop still completes: cwd restored to the caller, marker not leaked.+ test.skipIf(!GIT_BIN)('a relative TMPDIR planted by the .env is quarantined before the neutral dir is made; the hop completes and cwd is restored', async () => {+ const { dir, entry } = hostileGitRepo({+ envLines: () => ['TMPDIR=t', 'PROJECT_NAME=demo'],+ entryBody: `process.stdout.write('CWD=' + process.cwd() + ' MARKER=' + JSON.stringify(process.env.GBRAIN_CWD_ENV_QUARANTINED ?? null) + '\\n');\nprocess.exit(7);`,+ });+ const r = await runCli([process.execPath, entry, '--preflight'], dir, hermeticEnv(dir));+ expect(r.exitCode).toBe(7);+ expect(r.stdout).toContain(`CWD=${realpathSync(dir)}`); // switched back to the caller+ expect(r.stdout).toContain('MARKER=null'); // internal marker not visible+ const warnings = warningLines(r.stderr);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain('Ignoring TMPDIR because a .env file in the current directory assigns it');+ });++ // A2-3 (red team): git reads $XDG_CONFIG_HOME/git/config as GLOBAL config,+ // so a non-GIT_ variable carries the same core.fsmonitor RCE.+ const xdgLines = (d: string) => [`XDG_CONFIG_HOME=${d}/.xdg`, 'PROJECT_NAME=demo'];+ function plantXdgFsmonitor(dir: string): void {+ mkdirSync(join(dir, '.xdg', 'git'), { recursive: true });+ writeFileSync(join(dir, '.xdg', 'git', 'config'), '[core]\n\tfsmonitor = ./tooling/evil.sh\n');+ }++ test.skipIf(!GIT_BIN)('control: XDG_CONFIG_HOME planted by the .env makes git run the script (no preflight)', async () => {+ const { dir, evilMarker, entry } = hostileGitRepo({ envLines: xdgLines });+ plantXdgFsmonitor(dir);+ const r = await runCli([process.execPath, entry], dir, hermeticEnv(dir));+ expect(r.exitCode).toBe(7);+ expect(existsSync(evilMarker)).toBe(true);+ });++ test.skipIf(!GIT_BIN)('with preflight: XDG_CONFIG_HOME is quarantined and git from the original cwd does NOT run the planted fsmonitor', async () => {+ const { dir, evilMarker, entry } = hostileGitRepo({ envLines: xdgLines });+ plantXdgFsmonitor(dir);+ const r = await runCli([process.execPath, entry, '--preflight'], dir, hermeticEnv(dir));+ expect(existsSync(evilMarker)).toBe(false);+ expect(r.exitCode).toBe(7);+ expect(r.stdout).toContain('GIT_EXIT=0');+ expect(r.stdout).toContain(`CWD=${realpathSync(dir)}`);+ expect(r.stdout).toContain('PROJECT_NAME=demo');+ const warnings = warningLines(r.stderr);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain('Ignoring XDG_CONFIG_HOME because a .env file in the current directory assigns it');+ });++ const compiledTest = existsSync(COMPILED_BIN) ? test : test.skip;+ compiledTest.skipIf(!GIT_BIN)('compiled binary from the hostile git checkout: one warning, exit 0, a single stdout line, no script run', async () => {+ // `--version` itself spawns nothing, so the marker check guards the harness;+ // the re-run's argv shape (compiled: user args only, no /$bunfs entry) is+ // what the single clean stdout line + exit 0 prove.+ const { dir, evilMarker } = hostileGitRepo();+ const r = await runCli([COMPILED_BIN, '--version'], dir, hermeticEnv(dir));+ expect(existsSync(evilMarker)).toBe(false);+ expect(r.exitCode).toBe(0);+ expect(r.stdout.trim().split('\n')).toHaveLength(1);+ expect(r.stdout).toMatch(/^gbrain \d/);+ const warnings = warningLines(r.stderr);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain(`Ignoring ${HOSTILE_WARNING_KEYS} because`);+ });+});++// ── cwd == config dir: the operator's own .env is not a "cwd .env" (A4) ──────+describe('running gbrain from inside its own config dir', () => {+ /** A VALID provider module (registers one guardrail) that also drops a marker when imported. */+ function validProvider(): { path: string; marker: string } {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-a4-provider-'));+ scratch.push(dir);+ const marker = join(dir, 'PROVIDER_LOADED');+ const path = join(dir, 'provider.mjs');+ writeFileSync(+ path,+ `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, 'ran');\n` ++ `export default { id: 'fixture-a4', classify() {} };\n`,+ );+ return { path, marker };+ }++ test('$GBRAIN_HOME/.gbrain as cwd: its .env is honored, no quarantine warning, exit 0', async () => {+ const clean = mkdtempSync(join(tmpdir(), 'gbrain-clean-cwd-'));+ scratch.push(clean);+ const env = hermeticEnv(clean);+ const cfgDir = join(env.GBRAIN_HOME, '.gbrain');+ mkdirSync(cfgDir, { recursive: true });+ const { path, marker } = validProvider();+ writeFileSync(join(cfgDir, '.env'), `GBRAIN_GUARDRAILS_MODULE=${path}\n`);+ const r = await runCli([process.execPath, CLI_PATH, '--version'], cfgDir, { ...env, PWD: cfgDir });+ expect(r.stderr).not.toContain('[env] Ignoring');+ expect(r.stderr).not.toContain('guardrails:');+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toMatch(/^gbrain \d/);+ expect(existsSync(marker)).toBe(true); // the operator's provider loaded+ });++ test('hostile variant: a checkout whose .env assigns GBRAIN_HOME to manufacture the collision is still quarantined', async () => {+ const { dir, marker } = hostileRepo(() => 'UNRELATED=1'); // the probe module lives here+ // The checkout IS <dir>/evil-home/.gbrain and points GBRAIN_HOME at <dir>/evil-home, so configDir() === cwd.+ const fakeCfg = join(dir, 'evil-home', '.gbrain');+ mkdirSync(fakeCfg, { recursive: true });+ writeFileSync(+ join(fakeCfg, '.env'),+ `GBRAIN_HOME=${join(dir, 'evil-home')}\nGBRAIN_GUARDRAILS_MODULE=${join(dir, 'tooling', 'probe.ts')}\n`,+ );+ const env = hermeticEnv(fakeCfg);+ delete env.GBRAIN_HOME; // exported vars beat .env in Bun; the attack needs the .env value to land+ const r = await runCli([process.execPath, CLI_PATH, '--version'], fakeCfg, env);+ expect(existsSync(marker)).toBe(false);+ // Both keys are quarantined (one warning names them) and, because the+ // dropped set includes GBRAIN_GUARDRAILS_MODULE, preflight then fails closed.+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain('[env] Ignoring GBRAIN_GUARDRAILS_MODULE, GBRAIN_HOME because a .env file in the current directory assigns it');+ expect(r.stderr).toContain("refusing to run without the operator's firewall");+ expect(r.stdout).not.toMatch(/^gbrain \d/);+ });++ // E4-2 (review cycle 4): the exemption compares cwd with configDir(), which+ // is derived from HOME / USERPROFILE / GBRAIN_HOME. A cwd .env that assigns+ // ANY of those cannot be the operator's own file — a planted home is never+ // the operator's config dir — so the exemption is refused for all three, not+ // just GBRAIN_HOME. Unit: the predicate itself.+ test('cwdIsOperatorConfigDir: refused when the cwd .env assigns HOME / USERPROFILE / GBRAIN_HOME; granted for a genuine collision', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-e42-home-'));+ scratch.push(home);+ const cfgDir = join(home, '.gbrain');+ mkdirSync(cfgDir);+ await withEnv({ GBRAIN_HOME: home }, () => {+ expect(cwdIsOperatorConfigDir(cfgDir, [['UNRELATED', '1']])).toBe(true); // control: a genuine collision+ expect(cwdIsOperatorConfigDir(cfgDir, [['GBRAIN_GUARDRAILS_MODULE', '/x']])).toBe(true); // the operator's own security key in their own .env+ for (const key of ['GBRAIN_HOME', 'HOME', 'USERPROFILE']) {+ expect(cwdIsOperatorConfigDir(cfgDir, [[key, home]])).toBe(false);+ }+ expect(cwdIsOperatorConfigDir(join(home, 'elsewhere'), [['UNRELATED', '1']])).toBe(false); // not the config dir at all+ });+ });++ // E4-2 e2e — the forged-home shape. HOME and GBRAIN_HOME are both ABSENT from+ // the spawn env (a cron / systemd unit), the checkout is laid out as+ // <hostile>/.gbrain and its .env assigns HOME=<hostile> (Bun sets it because+ // nothing exported it) next to GBRAIN_GUARDRAILS_MODULE. Measured on Bun+ // 1.3.13: os.homedir() is captured from the REAL environ before the .env+ // merge, so configDir() never followed the planted HOME and the collision was+ // not manufactured even before the predicate change — this pins the invariant+ // that must hold either way: exemption refused, the planted module never+ // loads, preflight fails closed, and the warning names HOME.+ test('forged home: cwd = <hostile>/.gbrain whose .env assigns HOME (HOME + GBRAIN_HOME unset at spawn) — module not loaded, exit 1, warning names HOME', async () => {+ const { dir, marker } = hostileRepo(() => 'UNRELATED=1'); // the probe module lives here+ const fakeCfg = join(dir, '.gbrain');+ mkdirSync(fakeCfg);+ writeFileSync(join(fakeCfg, '.env'), `HOME=${dir}\nGBRAIN_GUARDRAILS_MODULE=${join(dir, 'tooling', 'probe.ts')}\n`);+ const env = hermeticEnv(fakeCfg);+ delete env.HOME;+ delete env.GBRAIN_HOME; // the cron/systemd shape: Bun fills HOME from the .env because nothing exported it+ const r = await runCli([process.execPath, CLI_PATH, '--version'], fakeCfg, env);+ expect(existsSync(marker)).toBe(false);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain('[env] Ignoring GBRAIN_GUARDRAILS_MODULE, HOME because a .env file in the current directory assigns it');+ expect(r.stderr).toContain("refusing to run without the operator's firewall");+ expect(r.stdout).not.toMatch(/^gbrain \d/);+ });+});+++// ── A3-1: a cwd bunfig.toml cannot preload code into the COMPILED binary ─────+//+// A standalone Bun executable auto-loads a `bunfig.toml` from the process cwd+// and runs its `preload` scripts BEFORE any of the binary's own code — before+// cli-preflight, before the cwd-.env quarantine. gbrain is a global CLI that+// runs from arbitrary checkouts, so a hostile repo carrying bunfig.toml ++// `preload` would get RCE from a plain `gbrain --version`. The binary is now+// built with `--no-compile-autoload-bunfig`, which makes a cwd bunfig.toml+// inert (guarded at build time by scripts/check-compile-autoload.sh). The dev+// runtime `bun src/cli.ts` stays bun-native — a contributor's cwd is trusted —+// so this behavior is only assertable against a compiled binary.+describe('a cwd bunfig.toml cannot preload code into the compiled binary', () => {+ /** A hostile checkout: bunfig.toml whose preload script drops a marker. */+ function hostileBunfig(): { dir: string; marker: string } {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-hostile-bunfig-'));+ scratch.push(dir);+ const marker = join(dir, 'PRELOAD_RAN');+ mkdirSync(join(dir, 'tooling'));+ writeFileSync(+ join(dir, 'tooling', 'pre.ts'),+ `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, 'ran');\n`,+ );+ writeFileSync(join(dir, 'bunfig.toml'), 'preload = ["./tooling/pre.ts"]\n');+ return { dir, marker };+ }++ const compiledTest = existsSync(COMPILED_BIN) ? test : test.skip;+ compiledTest('the preload script does NOT run under the compiled binary', async () => {+ const { dir, marker } = hostileBunfig();+ const r = await runCli([COMPILED_BIN, '--version'], dir, hermeticEnv(dir));+ expect(existsSync(marker)).toBe(false); // --no-compile-autoload-bunfig made it inert+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toMatch(/^gbrain \d/);+ });+});++// ── E4-4 (review cycle 4): script mode honours a cwd bunfig.toml — say so ────+//+// The documented install (`bun install -g github:…`, `git clone` + `bun link`)+// maps the `gbrain` bin to src/cli.ts, so gbrain runs as an ordinary Bun+// SCRIPT and Bun applies the cwd bunfig.toml — a top-level `preload` runs+// before any gbrain code (measured on Bun 1.3.13: only `--config=/dev/null`+// suppresses it; `-c`, `--no-bunfig`, `BUN_CONFIG_*` and a `[test]`-section+// preload do not / do not apply). Preflight cannot undo what already ran; it+// prints ONE stderr line naming the fact when it detects the shape — script+// runtime + a top-level preload in the startup cwd's bunfig.toml — except when+// the cwd IS the checkout containing the running entry (a contributor's own+// repo). The compiled binary is protected at build time (pinned above).+describe('script mode + cwd bunfig.toml: preflight names the already-applied preload (E4-4)', () => {+ const SCRIPT_MODE_WARNING_HEAD =+ '[env] gbrain is running as a bun script (not the compiled binary) and the bunfig.toml in the current directory declares a top-level preload';+ const scriptModeWarnings = (stderr: string) => stderr.split('\n').filter((l) => l.startsWith(SCRIPT_MODE_WARNING_HEAD));++ /** A dir whose bunfig.toml is `bunfig`; tooling/pre.ts drops the returned marker when Bun preloads it. */+ function bunfigDir(bunfig: string, prefix = 'gbrain-script-bunfig-'): { dir: string; marker: string } {+ const dir = mkdtempSync(join(tmpdir(), prefix));+ scratch.push(dir);+ const marker = join(dir, 'PRELOAD_RAN');+ mkdirSync(join(dir, 'tooling'));+ writeFileSync(join(dir, 'tooling', 'pre.ts'), `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, 'ran');\n`);+ writeFileSync(join(dir, 'bunfig.toml'), bunfig);+ return { dir, marker };+ }+ const TOP_LEVEL_PRELOAD = 'preload = ["./tooling/pre.ts"]\n';++ test('bun src/cli.ts from a dir whose bunfig.toml has a top-level preload: the preload RUNS (Bun, before gbrain) and preflight prints the one-line warning', async () => {+ const { dir, marker } = bunfigDir(TOP_LEVEL_PRELOAD);+ const r = await runCli([process.execPath, CLI_PATH, '--version'], dir, hermeticEnv(dir));+ expect(existsSync(marker)).toBe(true); // honest: script mode cannot prevent this — the warning IS the mitigation+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toMatch(/^gbrain \d/);+ expect(scriptModeWarnings(r.stderr)).toHaveLength(1);+ });++ test('controls: a [test]-section preload (not applied by bun run) and no bunfig at all → no warning', async () => {+ const testOnly = bunfigDir('[test]\npreload = ["./tooling/pre.ts"]\n');+ const r1 = await runCli([process.execPath, CLI_PATH, '--version'], testOnly.dir, hermeticEnv(testOnly.dir));+ expect(existsSync(testOnly.marker)).toBe(false);+ expect(r1.exitCode).toBe(0);+ expect(scriptModeWarnings(r1.stderr)).toEqual([]);+ const none = mkdtempSync(join(tmpdir(), 'gbrain-clean-cwd-'));+ scratch.push(none);+ const r2 = await runCli([process.execPath, CLI_PATH, '--version'], none, hermeticEnv(none));+ expect(r2.exitCode).toBe(0);+ expect(scriptModeWarnings(r2.stderr)).toEqual([]);+ });++ test('the checkout containing the running entry is exempt; the same entry from a foreign preload dir warns; a hop warns exactly once (wrapper only)', async () => {+ // A package-shaped checkout: <pkg>/src/entry.ts (preflight only) + <pkg>/bunfig.toml with a top-level preload.+ const pkg = bunfigDir(TOP_LEVEL_PRELOAD, 'gbrain-script-pkg-');+ mkdirSync(join(pkg.dir, 'src'));+ const entry = join(pkg.dir, 'src', 'entry.ts');+ writeFileSync(entry, `import { runCliPreflight } from ${JSON.stringify(PREFLIGHT_MODULE)};\nawait runCliPreflight();\nprocess.exit(3);\n`);+ // cwd == the entry's own package root → a contributor's checkout → exempt.+ const own = await runCli([process.execPath, entry], pkg.dir, hermeticEnv(pkg.dir));+ expect(existsSync(pkg.marker)).toBe(true);+ expect(own.exitCode).toBe(3);+ expect(scriptModeWarnings(own.stderr)).toEqual([]);+ // The same entry run from a foreign dir carrying a preload bunfig → warns.+ const foreign = bunfigDir(TOP_LEVEL_PRELOAD);+ const far = await runCli([process.execPath, entry], foreign.dir, hermeticEnv(foreign.dir));+ expect(existsSync(foreign.marker)).toBe(true);+ expect(far.exitCode).toBe(3);+ expect(scriptModeWarnings(far.stderr)).toHaveLength(1);+ // Foreign dir with BOTH a preload bunfig and a protected-key .env → the wrapper warns once; the re-run (started in the neutral dir) does not.+ const hop = bunfigDir(TOP_LEVEL_PRELOAD);+ writeFileSync(join(hop.dir, '.env'), 'GBRAIN_ALLOW_SHELL_JOBS=1\n');+ const hopped = await runCli([process.execPath, entry], hop.dir, hermeticEnv(hop.dir));+ expect(hopped.exitCode).toBe(3);+ expect(scriptModeWarnings(hopped.stderr)).toHaveLength(1);+ expect(warningLines(hopped.stderr)).toHaveLength(1);+ });+});++// ── A3-6(ii): the sanitized re-run chdirs back to the caller ─────────────────+//+// On a verified hop the re-run switches back to the caller's directory before+// anything else runs. If that directory has vanished, it aborts with a clear+// message rather than continuing from the neutral temp dir. Both branches are+// driven by planting a VALID hop marker (startup cwd IS the .env-free neutral+// dir it names) so verifiedHop honours it.+describe('sanitized re-run: chdir back to the caller', () => {+ function preflightOnlyEntry(): string {+ const d = mkdtempSync(join(tmpdir(), 'gbrain-preflight-entry-'));+ scratch.push(d);+ const p = join(d, 'entry.ts');+ writeFileSync(p, [+ `import { realpathSync } from 'node:fs';`,+ `import { runCliPreflight } from ${JSON.stringify(PREFLIGHT_MODULE)};`,+ `await runCliPreflight();`,+ `process.stdout.write('CWD=' + realpathSync(process.cwd()) + '\\n');`,+ `process.exit(3);`,+ '',+ ].join('\n'));+ return p;+ }++ test('a re-run whose original cwd vanished aborts with a clear error (exit 1)', async () => {+ const entry = preflightOnlyEntry();+ const gone = mkdtempSync(join(tmpdir(), 'gbrain-vanished-cwd-'));+ const neutral = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-neutral-'))); scratch.push(neutral);+ rmSync(gone, { recursive: true, force: true }); // the caller's dir no longer exists+ const env = { ...hermeticEnv(neutral), GBRAIN_CWD_ENV_QUARANTINED: JSON.stringify({ cwd: gone, neutral }) };+ const r = await runCli([process.execPath, entry, '--preflight'], neutral, env);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain(`[env] cannot return to ${gone}`);+ });++ test('a re-run with a live original cwd chdirs back and proceeds (exit 3)', async () => {+ const entry = preflightOnlyEntry();+ const live = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-live-cwd-'))); scratch.push(live);+ const neutral = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-neutral-'))); scratch.push(neutral);+ const env = { ...hermeticEnv(neutral), GBRAIN_CWD_ENV_QUARANTINED: JSON.stringify({ cwd: live, neutral }) };+ const r = await runCli([process.execPath, entry, '--preflight'], neutral, env);+ expect(r.exitCode).toBe(3);+ expect(r.stdout).toContain(`CWD=${live}`);+ expect(r.stderr).not.toContain('cannot return');+ });+});diff --git a/test/config-gbrain-env-file.test.ts b/test/config-gbrain-env-file.test.tsindex 64e707618f..b3a7dda5e8 100644--- a/test/config-gbrain-env-file.test.ts+++ b/test/config-gbrain-env-file.test.ts@@ -113,6 +113,19 @@ describe('loadConfig — ~/.gbrain/.env secrets file (#3893)', () => {);});+ test('a bare CR terminates a line, as in Bun\'s own loader (grammar shared with env-trust.ts)', async () => {+ await withEnvFile(+ 'GBRAIN_TEST_ENV_FILE_A=first\rGBRAIN_TEST_ENV_FILE_B=second\r\nGBRAIN_TEST_ENV_FILE_C=third\n',+ { GBRAIN_TEST_ENV_FILE_A: undefined, GBRAIN_TEST_ENV_FILE_B: undefined, GBRAIN_TEST_ENV_FILE_C: undefined },+ () => {+ loadConfig();+ expect(process.env.GBRAIN_TEST_ENV_FILE_A).toBe('first');+ expect(process.env.GBRAIN_TEST_ENV_FILE_B).toBe('second');+ expect(process.env.GBRAIN_TEST_ENV_FILE_C).toBe('third');+ },+ );+ });+test('a missing ~/.gbrain/.env is not an error', async () => {await withEnvFile(null, {}, () => {const cfg = loadConfig();diff --git a/test/doctor-oauth-client-scope-health.test.ts b/test/doctor-oauth-client-scope-health.test.tsindex 4e12e549fb..72731d946b 100644--- a/test/doctor-oauth-client-scope-health.test.ts+++ b/test/doctor-oauth-client-scope-health.test.ts@@ -18,6 +18,8 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { checkOauthClientScopeHealth } from '../src/commands/doctor.ts';+import { DCR_PRIVILEGED_SCOPES } from '../src/commands/doctor/checks/routing-federation.ts';+import { ALLOWED_SCOPES_LIST, DCR_REGISTRABLE_SCOPES } from '../src/core/scope.ts';let engine: PGLiteEngine;@@ -119,4 +121,228 @@ describe('checkOauthClientScopeHealth', () => {const r = await checkOauthClientScopeHealth(engine);expect(r.status).toBe('ok');});++ // (c) Privileged self-registered clients. A row created through the+ // anonymous DCR path carries grant_revision = 0 and no oauth_grant_audit+ // 'register' row (operator paths write one). Rows that hold a scope beyond+ // the DCR ceiling with that signature predate the ceiling (or predate the+ // grant audit log) and deserve an operator look — advisory WARN with the+ // rescope / revoke remedy.+ describe('privileged self-registered (DCR-signature) clients', () => {+ async function seedClient(id: string, scope: string, opts: { audited?: boolean; revision?: number; deleted?: boolean } = {}): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at)+ VALUES ($1, $2, $3, 'default', $4, $5, ${opts.deleted ? 'now()' : 'NULL'})`,+ [id, `${id}-name`, scope, ['default'], opts.revision ?? 0],+ );+ if (opts.audited) {+ await engine.executeRaw(+ `INSERT INTO oauth_grant_audit (client_id, actor, action, revision, before_grant, after_grant)+ VALUES ($1, 'operator', 'register', 0, NULL, '{}'::jsonb)`,+ [id],+ );+ }+ }++ beforeEach(async () => {+ await (engine as any).db.exec('DELETE FROM oauth_grant_audit');+ });++ test('admin-scoped DCR-signature row → warn naming the client + rescope/revoke remedy', async () => {+ await seedClient('c-dcr-admin', 'read admin');+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('warn');+ expect(r.message).toMatch(/c-dcr-admin/);+ expect(r.message).toMatch(/admin/);+ expect(r.message).toMatch(/rescope-client <client_id> --scopes read,write|rescope-client .*--scopes/);+ expect(r.message).toMatch(/revoke-client/);+ });++ test('sources_admin and users_admin also trip the arm; the client name is shown', async () => {+ await seedClient('c-dcr-sources', 'sources_admin');+ await seedClient('c-dcr-users', 'read users_admin');+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('warn');+ expect(r.message).toMatch(/c-dcr-sources-name/);+ expect(r.message).toMatch(/c-dcr-users-name/);+ });++ test('read/write DCR-signature rows are within the ceiling → NOT flagged', async () => {+ await seedClient('c-dcr-rw', 'read write');+ await seedClient('c-dcr-empty', '');+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('ok');+ });++ test('operator-registered admin client (audit register row) → NOT flagged', async () => {+ await seedClient('c-op-admin', 'admin', { audited: true });+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('ok');+ });++ test('rescoped admin client (grant_revision > 0) → NOT flagged', async () => {+ await seedClient('c-rescoped-admin', 'admin', { revision: 2 });+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('ok');+ });++ test('revoked (deleted_at) DCR-signature admin row → NOT flagged', async () => {+ await seedClient('c-dcr-revoked', 'admin', { deleted: true });+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('ok');+ });++ test('grant audit table missing → arm skipped with an explicit note, other arms intact', async () => {+ await seedClient('c-dcr-admin-noaudit', 'admin');+ await (engine as any).db.exec('DROP TABLE oauth_grant_audit');+ try {+ const r = await checkOauthClientScopeHealth(engine);+ // Fail-open: cannot tell operator rows from self-registered ones+ // without the audit log, so the arm reports unknown instead of+ // guessing — and says so.+ expect(r.status).toBe('ok');+ expect(r.message).toMatch(/self-registered.*(skipped|unknown)|(skipped|unknown).*self-registered/i);+ } finally {+ const { GRANT_AUDIT_SCHEMA_SQL } = await import('../src/core/grants/schema.ts');+ await (engine as any).db.exec(GRANT_AUDIT_SCHEMA_SQL);+ }+ });+ });+});++// Arm (c) edge shapes not pinned above: the `agent` scope (seeded with the+// delegation bindings its check constraint demands), the 5-client display cap+// with its "+N more" tail, and the word-bounded scope match (a token that+// merely CONTAINS a privileged word is not one).+describe('checkOauthClientScopeHealth — arm (c) edge shapes', () => {+ async function seed(id: string, scope: string): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at)+ VALUES ($1, $2, $3, 'default', $4, 0, NULL)`,+ [id, `${id}-name`, scope, ['default']],+ );+ }++ beforeEach(async () => {+ await truncate();+ await (engine as any).db.exec('DELETE FROM oauth_grant_audit');+ });++ test('agent-scoped DCR-signature row is flagged (agent sits beyond the ceiling too)', async () => {+ // `oauth_clients_complete_agent_grant` (grants/schema.ts) refuses an agent+ // scope without complete delegation bindings — seed a complete one.+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at,+ bound_tools, bound_source_id, delegated_namespace, delegated_slug_prefixes, bound_max_concurrent)+ VALUES ('c-dcr-agent', 'c-dcr-agent-name', 'read agent', 'default', $1, 0, NULL,+ $2, 'default', 'job', NULL, 1)`,+ [['default'], ['get_page']],+ );+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('warn');+ expect(r.message).toMatch(/c-dcr-agent/);+ expect(r.message).toContain('scope=read agent');+ });++ // (client_name is NOT NULL in the schema, so the `?? client_id` display+ // fallback cannot be reached through the database — not pinned here.)++ test('more than five offenders: five shown (ordered by client_id), the rest counted', async () => {+ for (let i = 0; i < 7; i++) await seed(`c-dcr-many-${i}`, 'admin');+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('warn');+ expect(r.message).toMatch(/^7 active OAuth client\(s\)/);+ for (let i = 0; i < 5; i++) expect(r.message).toContain(`(c-dcr-many-${i})`);+ expect(r.message).not.toContain('(c-dcr-many-5)');+ expect(r.message).not.toContain('(c-dcr-many-6)');+ expect(r.message).toContain('(+2 more)');+ });++ test('a scope token that merely CONTAINS a privileged word is not flagged (word-bounded match)', async () => {+ await seed('c-dcr-substring', 'readmin write');+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('ok');+ });++ test('grant_revision column missing → arm skipped with the explicit note, other arms intact', async () => {+ // A brain whose oauth_clients predates the grant schema: the DCR+ // signature cannot be evaluated, so the arm reports unknown (ok + note)+ // rather than guessing — even with an admin-scoped row present.+ await (engine as any).db.exec('ALTER TABLE oauth_clients DROP COLUMN grant_revision');+ try {+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, deleted_at)+ VALUES ('c-dcr-norev', 'c-dcr-norev-name', 'admin', 'default', $1, NULL)`,+ [['default']],+ );+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('ok');+ expect(r.message).toMatch(/self-registered.*(skipped|unknown)|(skipped|unknown).*self-registered/i);+ expect(r.message).not.toMatch(/c-dcr-norev/);+ } finally {+ await (engine as any).db.exec('ALTER TABLE oauth_clients ADD COLUMN grant_revision integer NOT NULL DEFAULT 0');+ }+ });+});++// The privileged set arm (c) matches is DERIVED from scope.ts (the complement+// of the DCR ceiling), never a hand-copied literal — so a scope added to+// ALLOWED_SCOPES_LIST without joining DCR_REGISTRABLE_SCOPES is audited+// automatically, and the copy names the ceiling from the same constant.+describe('checkOauthClientScopeHealth — arm (c) privileged set is the derived complement of the DCR ceiling', () => {+ const complement = ALLOWED_SCOPES_LIST.filter((s) => !DCR_REGISTRABLE_SCOPES.has(s));++ test('DCR_PRIVILEGED_SCOPES === ALLOWED_SCOPES_LIST \\ DCR_REGISTRABLE_SCOPES (disjoint, jointly exhaustive)', () => {+ expect([...DCR_PRIVILEGED_SCOPES]).toEqual(complement);+ expect(DCR_PRIVILEGED_SCOPES.length).toBeGreaterThan(0);+ for (const s of DCR_PRIVILEGED_SCOPES) expect(DCR_REGISTRABLE_SCOPES.has(s as any)).toBe(false);+ expect([...DCR_PRIVILEGED_SCOPES, ...DCR_REGISTRABLE_SCOPES].sort()).toEqual([...ALLOWED_SCOPES_LIST].sort());+ });++ /** Seed a DCR-signature row; `agent` needs complete delegation bindings (check constraint). */+ async function seedDcrSignature(id: string, scope: string): Promise<void> {+ if (scope.split(' ').includes('agent')) {+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at,+ bound_tools, bound_source_id, delegated_namespace, delegated_slug_prefixes, bound_max_concurrent)+ VALUES ($1, $2, $3, 'default', $4, 0, NULL, $5, 'default', 'job', NULL, 1)`,+ [id, `${id}-name`, scope, ['default'], ['get_page']],+ );+ return;+ }+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at)+ VALUES ($1, $2, $3, 'default', $4, 0, NULL)`,+ [id, `${id}-name`, scope, ['default']],+ );+ }++ beforeEach(async () => {+ await truncate();+ await (engine as any).db.exec('DELETE FROM oauth_grant_audit');+ });++ test('every scope in the complement trips the arm on its own; every ceiling scope does not', async () => {+ for (const scope of complement) {+ await (engine as any).db.exec('DELETE FROM oauth_clients');+ await seedDcrSignature(`c-dcr-${scope}`, scope);+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('warn');+ expect(r.message).toContain(`(c-dcr-${scope}) scope=${scope}`);+ }+ for (const scope of DCR_REGISTRABLE_SCOPES) {+ await (engine as any).db.exec('DELETE FROM oauth_clients');+ await seedDcrSignature(`c-dcr-${scope}`, scope);+ const r = await checkOauthClientScopeHealth(engine);+ expect(r.status).toBe('ok');+ }+ });++ test('the remedy copy names the ceiling from the constant, not a literal', async () => {+ await seedDcrSignature('c-dcr-copy', complement[0]);+ const r = await checkOauthClientScopeHealth(engine);+ const ceiling = [...DCR_REGISTRABLE_SCOPES];+ expect(r.message).toContain(`self-registration ceiling (${ceiling.join('/')})`);+ expect(r.message).toContain(`--scopes ${ceiling.join(',')}`);+ });});diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.tsindex e938972600..20716d008c 100644--- a/test/e2e/engine-parity.test.ts+++ b/test/e2e/engine-parity.test.ts@@ -2519,3 +2519,57 @@ describeBoth('Engine parity — getCalleesOf bare-name fallback (#4670)', () =>}});});++// getRawData soft-delete filter. Companion to the #4587 soft-delete blocks+// above, but NOT behind describeBoth: the PGLite arm always runs (so the+// filter is exercised in every sandbox) and the Postgres arm joins when+// DATABASE_URL is configured (CI docker Postgres).+describe('getRawData soft-delete filter — parity (PGLite always; Postgres when DATABASE_URL is set)', () => {+ let pglite: PGLiteEngine;+ const arms: Array<{ name: string; eng: BrainEngine }> = [];++ beforeAll(async () => {+ pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ arms.push({ name: 'pglite', eng: pglite });+ if (!SKIP_PG) arms.push({ name: 'postgres', eng: await setupDB() });+ }, 90_000);++ afterAll(async () => {+ await pglite.disconnect();+ if (!SKIP_PG) await teardownDB();+ }, 30_000);++ test('putRawData → softDeletePage hides raw_data on every read shape; includeDeleted:true still returns it; restorePage makes it visible again', async () => {+ expect(arms.length).toBeGreaterThan(0);+ for (const { name, eng } of arms) {+ const slug = 'wiki/raw-soft-delete';+ await eng.putPage(slug, { type: 'note', title: 'raw', compiled_truth: 'body', timeline: '' }, { sourceId: 'default' });+ await eng.putRawData(slug, 'transcript:test', { k: 'v' }, { sourceId: 'default' });+ expect((await eng.getRawData(slug, undefined, { sourceId: 'default' })).length).toBe(1);++ expect(await eng.softDeletePage(slug, { sourceId: 'default' })).not.toBeNull();+ // Every WHERE shape (unscoped, scalar source, federated sourceIds,+ // with/without a raw source filter) hides the soft-deleted page.+ const hidden = [+ await eng.getRawData(slug),+ await eng.getRawData(slug, 'transcript:test'),+ await eng.getRawData(slug, undefined, { sourceId: 'default' }),+ await eng.getRawData(slug, 'transcript:test', { sourceId: 'default' }),+ await eng.getRawData(slug, undefined, { sourceIds: ['default'] }),+ await eng.getRawData(slug, 'transcript:test', { sourceIds: ['default'] }),+ ];+ for (const rows of hidden) expect({ arm: name, rows }).toEqual({ arm: name, rows: [] });++ // Explicit opt-in (export / engine migration / ingest healing) still sees it.+ expect((await eng.getRawData(slug, undefined, { sourceId: 'default', includeDeleted: true })).length).toBe(1);+ expect((await eng.getRawData(slug, 'transcript:test', { sourceIds: ['default'], includeDeleted: true })).length).toBe(1);+ expect((await eng.getRawData(slug, undefined, { includeDeleted: true })).length).toBe(1);++ expect(await eng.restorePage(slug, { sourceId: 'default' })).toBe(true);+ expect((await eng.getRawData(slug, undefined, { sourceId: 'default' })).length).toBe(1);+ await eng.deletePage(slug, { sourceId: 'default' });+ }+ });+});diff --git a/test/e2e/serve-http-consent.test.ts b/test/e2e/serve-http-consent.test.tsindex 7f8232d426..94960fd2ed 100644--- a/test/e2e/serve-http-consent.test.ts+++ b/test/e2e/serve-http-consent.test.ts@@ -5,11 +5,17 @@ import { join } from 'node:path';import { tmpdir } from 'node:os';import { createServer } from 'node:net';import { spawn, type ChildProcess } from 'node:child_process';-import { TEST_PKCE_CHALLENGE } from '../helpers/oauth.ts';+import { TEST_PKCE_CHALLENGE, TEST_PKCE_VERIFIER } from '../helpers/oauth.ts';let child: ChildProcess;let home: string;let base: string;+// ONE admin login for the whole file (the shared admin auth limiter is+// 10/min/IP and the consent routes draw from the same bucket), taken in+// beforeAll so every test is order-independent. `adminSetCookie` keeps the+// raw header for the attribute assertions.+let adminCookie = '';+let adminSetCookie = '';const BOOTSTRAP = 'synthetic-consent-admin-test-token';beforeAll(async () => {home = mkdtempSync(join(tmpdir(), 'gbrain-consent-test-'));@@ -28,12 +34,17 @@ beforeAll(async () => {let output = '';child.stderr?.on('data', chunk => { output += chunk.toString(); });child.stdout?.on('data', chunk => { output += chunk.toString(); });- for (let attempt = 0; attempt < 150; attempt++) {+ let up = false;+ for (let attempt = 0; attempt < 150 && !up; attempt++) {if (child.exitCode !== null) throw new Error(`Consent server exited: ${output.slice(-2000)}`);- try { if ((await fetch(`${base}/health`)).ok) return; } catch { /* starting */ }- await Bun.sleep(100);+ try { up = (await fetch(`${base}/health`)).ok; } catch { /* starting */ }+ if (!up) await Bun.sleep(100);}- throw new Error(`Consent server did not start: ${output.slice(-2000)}`);+ if (!up) throw new Error(`Consent server did not start: ${output.slice(-2000)}`);+ const login = await fetch(`${base}/admin/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: BOOTSTRAP }) });+ if (login.status !== 200) throw new Error(`admin login failed: ${login.status}`);+ adminSetCookie = login.headers.get('set-cookie') ?? '';+ adminCookie = adminSetCookie.split(';')[0];}, 30_000);afterAll(async () => {if (child && child.exitCode === null) {@@ -55,13 +66,13 @@ test('login, magic-link recovery, consent authentication and single-use approvalconst authorization = await fetch(`${base}/authorize?${query}`, { redirect: 'manual' });const pendingUrl = new URL(authorization.headers.get('location')!, base);expect(pendingUrl.pathname).toBe('/admin/');+ expect(pendingUrl.searchParams.has('code')).toBe(false);const id = pendingUrl.searchParams.get('oauth_request')!;expect((await fetch(pendingUrl)).status).toBe(200); // unauthenticated page shellexpect((await fetch(`${base}/admin/api/oauth-requests/${id}`)).status).toBe(401);- const login = await fetch(`${base}/admin/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: BOOTSTRAP }) });- expect(login.status).toBe(200);- const oldCookie = login.headers.get('set-cookie')!.split(';')[0];- expect(login.headers.get('set-cookie')).toContain('SameSite=Strict');+ expect(adminCookie).not.toBe('');+ const oldCookie = adminCookie; // the beforeAll login session+ expect(adminSetCookie).toContain('SameSite=Strict');const oldDetails = await (await fetch(`${base}/admin/api/oauth-requests/${id}`, { headers: { Cookie: oldCookie } })).json() as any;const magic = await fetch(`${base}/admin/api/issue-magic-link`, { method: 'POST', headers: { Authorization: `Bearer ${BOOTSTRAP}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ oauth_request: id, return_url: 'https://untrusted.example' }) });expect(magic.status).toBe(200);@@ -84,3 +95,74 @@ test('login, magic-link recovery, consent authentication and single-use approvalexpect(redirect.searchParams.get('code')).toStartWith('gbrain_code_');expect((await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify({ decision: 'approve', csrf: details.csrf }) })).status).toBe(410);}, 15_000);++/** Anonymous self-registration with a foreign redirect_uri: no code without the owner, forged codes do not redeem, revocation closes /authorize. */+test('a self-registered public client cannot obtain or redeem a code without owner approval', async () => {+ const foreignRedirect = 'https://client-example.invalid/cb';+ const register = async (body: Record<string, unknown>) => {+ const response = await fetch(`${base}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({+ client_name: 'synthetic self-registered client', redirect_uris: [foreignRedirect], token_endpoint_auth_method: 'none', ...body }) });+ expect(response.status).toBe(201);+ return response.json() as Promise<any>;+ };+ const authorize = async (clientId: string, scope?: string) => {+ const query = new URLSearchParams({ client_id: clientId, response_type: 'code', redirect_uri: foreignRedirect, code_challenge: TEST_PKCE_CHALLENGE, code_challenge_method: 'S256', state: 'attacker-state' });+ if (scope !== undefined) query.set('scope', scope);+ return fetch(`${base}/authorize?${query}`, { redirect: 'manual' });+ };+ const expectPending = async (clientId: string, scope?: string) => {+ const response = await authorize(clientId, scope);+ expect(response.status).toBe(302);+ const location = new URL(response.headers.get('location')!, base);+ expect(location.pathname).toBe('/admin/');+ expect(location.searchParams.has('code')).toBe(false);+ return location.searchParams.get('oauth_request')!;+ };++ // grant_types omitted: the default is the consent-bearing authorization_code flow.+ const client = await register({ scope: 'read write' });+ expect(client.client_secret).toBeUndefined();+ await expectPending(client.client_id, 'read write');+ const forged = await fetch(`${base}/token`, { method: 'POST', body: new URLSearchParams({+ grant_type: 'authorization_code', code: 'gbrain_code_' + 'a'.repeat(43), code_verifier: TEST_PKCE_VERIFIER,+ client_id: client.client_id, redirect_uri: foreignRedirect }) });+ expect(forged.status).toBe(400);+ expect((await forged.json() as any).error).toBe('invalid_grant');++ // scope omitted: nothing is registered and the consent request carries no scopes (one consent GET).+ const unscoped = await register({ grant_types: ['authorization_code'] });+ expect(unscoped.scope ?? '').toBe('');+ const id = await expectPending(unscoped.client_id);+ const details = await fetch(`${base}/admin/api/oauth-requests/${id}`, { headers: { Cookie: adminCookie } });+ expect(details.status).toBe(200);+ expect((await details.json() as any).scopes).toEqual([]);++ // Revoked self-registered client: /authorize is refused before any consent request exists.+ const revoked = await fetch(`${base}/admin/api/revoke-client`, { method: 'POST', headers: { Cookie: adminCookie, 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: client.client_id }) });+ expect(revoked.status).toBe(200);+ const refused = await authorize(client.client_id, 'read write');+ expect(refused.status).toBe(400);+ expect((await refused.json() as any).error).toBe('invalid_client');+}, 15_000);++/** With self-registration on, discovery advertises exactly what a self-registering client may request — and a client that copies it registers. */+test('OAuth discovery advertises the self-registration ceiling and a client that copies it registers', async () => {+ const metadata = await (await fetch(`${base}/.well-known/oauth-authorization-server`)).json() as any;+ expect(metadata.scopes_supported).toEqual(['read', 'write']);+ expect(new URL(metadata.registration_endpoint).pathname).toBe('/register');+ const register = (scope: string) => fetch(`${base}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({+ client_name: 'synthetic discovered-scopes client', redirect_uris: ['https://client-example.invalid/cb'], grant_types: ['authorization_code', 'refresh_token'],+ response_types: ['code'], token_endpoint_auth_method: 'none', scope }) });+ const response = await register(metadata.scopes_supported.join(' '));+ expect(response.status).toBe(201);+ const client = await response.json() as any;+ expect(client.scope.split(' ')).toEqual(metadata.scopes_supported);+ for (const path of ['/.well-known/oauth-protected-resource/mcp', '/.well-known/oauth-protected-resource']) {+ const resource = await (await fetch(`${base}${path}`)).json() as any;+ expect(resource.scopes_supported).toEqual(metadata.scopes_supported);+ }+ // Narrowed discovery does not loosen the ceiling: an explicit privileged request is still refused.+ const refused = await register('read write admin');+ expect(refused.status).toBe(400);+ expect((await refused.json() as any).error).toBe('invalid_client_metadata');+}, 15_000);diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.tsindex d04f79bb27..3f3a442099 100644--- a/test/e2e/serve-http-oauth.test.ts+++ b/test/e2e/serve-http-oauth.test.ts@@ -361,22 +361,24 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {expect(meta.token_endpoint).toContain('/token');expect(meta.scopes_supported).toContain('read');expect(meta.scopes_supported).toContain('write');- expect(meta.scopes_supported).toContain('admin');+ // This server runs with --enable-dcr: discovery advertises the+ // self-registration ceiling, never a privileged scope+ // (scopesSupportedForDiscovery in src/core/scope.ts).+ expect(meta.scopes_supported).not.toContain('admin');});- // T2 (eng-review): scopes_supported advertises the full ALLOWED_SCOPES_LIST- // so MCP clients (Claude Desktop, ChatGPT, Perplexity) can discover the- // v0.28 sources_admin and users_admin scopes via standard discovery.- // Pre-v0.28 the list was hardcoded to ['read','write','admin'] in- // serve-http.ts:195 and this assertion would have failed.- test('OAuth metadata advertises all 5 v0.28 scopes (sources_admin + users_admin)', async () => {+ // With --enable-dcr, scopes_supported is exactly the DCR ceiling (`read write`,+ // canonical order) so a client that copies discovery into /register is+ // accepted. The full operator list (admin, read, sources_admin, users_admin,+ // write) is still advertised WITHOUT DCR — pinned by+ // test/e2e/sources-remote-mcp.test.ts ('OAuth /.well-known advertises all 5 scopes').+ test('OAuth metadata under --enable-dcr advertises exactly the self-registration ceiling', async () => {const res = await fetch(`${BASE}/.well-known/oauth-authorization-server`);const meta = await res.json() as any;- expect(meta.scopes_supported).toContain('sources_admin');- expect(meta.scopes_supported).toContain('users_admin');- expect(meta.scopes_supported).toEqual(- expect.arrayContaining(['admin', 'read', 'sources_admin', 'users_admin', 'write']),- );+ expect(meta.scopes_supported).toEqual(['read', 'write']);+ for (const privileged of ['admin', 'sources_admin', 'users_admin', 'agent']) {+ expect(meta.scopes_supported).not.toContain(privileged);+ }});// =========================================================================@@ -402,9 +404,9 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {expect(meta.resource).toBe(`${BASE}/mcp`);expect(meta.resource).not.toBe(`${BASE}/`);expect(meta.authorization_servers).toContain(`${BASE}/`);- expect(meta.scopes_supported).toEqual(- expect.arrayContaining(['admin', 'read', 'sources_admin', 'users_admin', 'write']),- );+ // --enable-dcr server: the protected-resource document mirrors the AS+ // metadata's self-registration ceiling.+ expect(meta.scopes_supported).toEqual(['read', 'write']);});// Setting resourceServerUrl moves the SDK's document to the path-inserteddiff --git a/test/e2e/sources-remote-mcp.test.ts b/test/e2e/sources-remote-mcp.test.tsindex 59282b31d7..e928450166 100644--- a/test/e2e/sources-remote-mcp.test.ts+++ b/test/e2e/sources-remote-mcp.test.ts@@ -372,45 +372,106 @@ describeE2E('sources-remote-mcp E2E (gstack /setup-gbrain Path 4)', () => {});// -------------------------------------------------------------------------- // sources_remove: cascade + clone cleanup+ // sources_remove: WRITE authority, cascade + clone cleanup// -------------------------------------------------------------------------- test('sources_remove deletes row + cleans up the clone (managed path)', async () => {- // Recreate the clone first (the previous test rmd it for the missing- // assertion). We do this via sources_add since that path is exercised.- // (Could call sources_add again but the row is still there from earlier;- // simpler: insert a fresh fixture.)- await callMcp(token!, 'sources_add', {- id: 'e2e-removable',- url: TEST_URL,+ /**+ * sources_remove is confined to the caller's WRITE authority (O4-1, review+ * cycle 4): a sources_admin token may hard-delete only its own write source.+ * The federated read grant (`--federated-read`) is READ authority by+ * contract and confers no removal right — widening it makes a source+ * visible to sources_status / sources_list, yet sources_remove still+ * answers not_found (indistinguishable from a nonexistent source). Over+ * HTTP every client carries a write source (registration default+ * 'default'), and a client's own row FK-RESTRICTs the removal of that very+ * source, so hard-removing a source is an operator action on the host CLI+ * (`gbrain sources remove`) — mirrored here.+ */+ async function widenGrantTo(...sourceIds: string[]): Promise<void> {+ const { execFileSync } = await import('child_process');+ execFileSync('bun', ['run', 'src/cli.ts', 'auth', 'rescope-client', clientId!,+ '--federated-read', sourceIds.join(',')], {+ cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },+ });+ }++ async function rescopeWriteSource(sourceId: string): Promise<void> {+ const { execFileSync } = await import('child_process');+ execFileSync('bun', ['run', 'src/cli.ts', 'auth', 'rescope-client', clientId!,+ '--source', sourceId], {+ cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },});+ }++ /** The trusted local path: `gbrain sources remove <id> --confirm-destructive` on the host. */+ async function operatorRemovesSource(id: string): Promise<string> {+ const { execFileSync } = await import('child_process');+ return execFileSync('bun', ['run', 'src/cli.ts', 'sources', 'remove', id, '--confirm-destructive'], {+ cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },+ });+ }++ test('sources_remove: a federated READ grant naming the source is not removal authority; the operator removes it on the host CLI', async () => {+ await callMcp(token!, 'sources_add', { id: 'e2e-removable', url: TEST_URL });const clonePath = join(GBRAIN_HOME, '.gbrain', 'clones', 'e2e-removable');expect(existsSync(clonePath)).toBe(true);- const result = await callMcp(token!, 'sources_remove', {+ // Outside the token's grant entirely → not_found, and nothing is removed.+ const fenced = await callMcp(token!, 'sources_remove', {id: 'e2e-removable',confirm_destructive: true,});- expect(result.clone_removed).toBe(true);- expect(existsSync(clonePath)).toBe(false);+ expect(fenced.__isError).toBe(true);+ expect(JSON.stringify(fenced.parsed)).toMatch(/not_found/);+ expect(existsSync(clonePath)).toBe(true);+ // Operator widens the READ grant; the live token now reads the source...+ await widenGrantTo('default', 'e2e-yc-artifacts', 'e2e-removable');+ const status = await callMcp(token!, 'sources_status', { id: 'e2e-removable' });+ expect(status.clone_state).toBe('healthy');+ // ...but removal is WRITE authority: still not_found, still on disk.+ const stillFenced = await callMcp(token!, 'sources_remove', {+ id: 'e2e-removable',+ confirm_destructive: true,+ });+ expect(stillFenced.__isError).toBe(true);+ expect(JSON.stringify(stillFenced.parsed)).toMatch(/not_found/);+ expect(existsSync(clonePath)).toBe(true);+ // The operator removes it on the host CLI (trusted local path).+ const out = await operatorRemovesSource('e2e-removable');+ expect(out).toMatch(/Removed source "e2e-removable"/);+ const after = await callMcp(token!, 'sources_list', {});+ expect(after.sources.find((s: any) => s.id === 'e2e-removable')).toBeUndefined();+ // Drop the dead id from the read grant (hygiene for the tests below).+ await widenGrantTo('default', 'e2e-yc-artifacts');});- test('sources_remove without confirm_destructive refuses on populated source', async () => {- // Add a fresh source with no pages — should still need confirm_destructive- // semantically because remove is hard-delete (vs archive).+ test('sources_remove: rescoping the WRITE source moves the authority — a federated-readable non-write source stays not_found while sources_status still answers', async () => {await callMcp(token!, 'sources_add', { id: 'e2e-confirm-test', url: TEST_URL });- const result = await callMcp(token!, 'sources_remove', {- id: 'e2e-confirm-test',- // omit confirm_destructive- });- // A source with 0 pages may pass — the gate is page-count-aware. Our- // newly-added source has 0 pages so this should succeed. Tweak:- // exercise the throw path by inserting a page first via raw SQL,- // but that's heavy. For now assert the result shape exists.- if (result.__isError) {- expect(JSON.stringify(result.parsed)).toMatch(/confirm/i);- } else {- // 0-page source: allowed without confirm. Still verify clone cleaned.- expect(typeof result.clone_removed).toBe('boolean');+ await widenGrantTo('default', 'e2e-yc-artifacts', 'e2e-confirm-test');+ await rescopeWriteSource('e2e-confirm-test');+ try {+ const identity = await callMcp(token!, 'whoami', {});+ expect(identity.source_id).toBe('e2e-confirm-test');+ // e2e-yc-artifacts is readable (federated) but is not the write source.+ const fenced = await callMcp(token!, 'sources_remove', {+ id: 'e2e-yc-artifacts',+ confirm_destructive: true,+ });+ expect(fenced.__isError).toBe(true);+ expect(JSON.stringify(fenced.parsed)).toMatch(/not_found/);+ const status = await callMcp(token!, 'sources_status', { id: 'e2e-yc-artifacts' });+ expect(status.id).toBe('e2e-yc-artifacts');+ // 'default' is neither readable-only nor the write source now: same+ // not_found (the fence answers before the op's protected-id guard).+ const def = await callMcp(token!, 'sources_remove', { id: 'default', confirm_destructive: true });+ expect(def.__isError).toBe(true);+ expect(JSON.stringify(def.parsed)).toMatch(/not_found/);+ } finally {+ // Restore the write source BEFORE the operator removes the fixture — a+ // client row referencing it would FK-RESTRICT the removal.+ await rescopeWriteSource('default');}+ const out = await operatorRemovesSource('e2e-confirm-test');+ expect(out).toMatch(/Removed source "e2e-confirm-test"/);+ await widenGrantTo('default', 'e2e-yc-artifacts');});});diff --git a/test/e2e/transcripts-ingest-pglite.test.ts b/test/e2e/transcripts-ingest-pglite.test.tsindex bb9f676ec4..b251b152be 100644--- a/test/e2e/transcripts-ingest-pglite.test.ts+++ b/test/e2e/transcripts-ingest-pglite.test.ts@@ -646,3 +646,198 @@ describe('putRawData zero-row parity (PGLite)', () => {).rejects.toThrow(/not found/);});});++// ── Format-based redaction lands in the STORED page ─────────────────────────+//+// Synthetic, runtime-joined values (>= 2 fragments each) so no committed line+// carries a credential-shaped literal. Read back through the engine (never+// grep the PGLite data dir — its paged format hides plaintext from grep).+const SEEDED_JWT = [+ 'eyJhbGciOiJIUzI1NiJ9',+ 'eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaWF0IjoxNzAwMDAwMDAwfQ',+ 'c2lnbmF0dXJlLXBsYWNlaG9sZGVyLTAwMDA',+].join('.');+const SEEDED_SID = ['AC', '0123456789abcdef', '0123456789abcdef'].join('');+const SEEDED_GOOGLE = ['AIza', 'SyD1-Fake_Example0123456789abcdefGH'].join('');+const SEEDED_STRIPE = ['sk_live_', '4eC39HqLyjWDarjtT1zdp7dc'].join('');+const SEEDED_DB_URL = ['postgres://', 'dbuser', ':', 'p4ssw0rd', '@db.internal:5432/app'].join('');+const SEEDED_ENTROPIC = ['aB3xK9mQ', '2pR7sT1vW4yZ8bC5'].join('');+const SEEDED_OPAQUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');++function claudeCodeLine(type: 'user' | 'assistant', uuid: string, ts: string, content: string): string {+ return JSON.stringify({+ type,+ message: { role: type, content },+ uuid,+ timestamp: ts,+ cwd: '/tmp/poc',+ sessionId: 'poc-0001',+ version: '2.1.0',+ gitBranch: 'main',+ });+}++describe('format-based redaction before write (unprefixed credential shapes)', () => {+ test('claude-code session: JWT / account SID / connection string / cloud keys land as placeholders only — and a bare echo in ANOTHER message goes with them', async () => {+ const p = join(tmp, 'poc-session.jsonl');+ writeFileSync(+ p,+ [+ claudeCodeLine('user', 'seed-0000', '2026-08-25T23:00:00.000Z', `deploy is failing. service role key ${SEEDED_JWT} and project ref zfakerefzfakeref0000`),+ // The opaque token appears BARE here, two messages before the header+ // that claims it; the entropic value appears bare AFTER its claim.+ claudeCodeLine('assistant', 'seed-0001', '2026-08-25T23:00:01.000Z', `twilio sid ${SEEDED_SID} and maps key ${SEEDED_GOOGLE} need rotating; the token ${SEEDED_OPAQUE} expired too`),+ claudeCodeLine('user', 'seed-0002', '2026-08-25T23:00:02.000Z', `stripe ${SEEDED_STRIPE} plus DATABASE_URL=${SEEDED_DB_URL} and SMTP_TOKEN=${SEEDED_ENTROPIC}`),+ claudeCodeLine('assistant', 'seed-0003', '2026-08-25T23:00:03.000Z', `retried with the header Authorization: Bearer ${SEEDED_OPAQUE} and pasted ${SEEDED_ENTROPIC} into the env`),+ ].join('\n') + '\n',+ );+ const r = await runTranscriptsIngest(engine, baseOpts([p]));+ expect(r.sessionsImported).toBe(1);+ expect(r.pages.imported).toBe(1);+ // Seven CLAIMS; the two bare echoes add no count.+ expect(r.redactions).toBeGreaterThanOrEqual(7);++ const slug = r.slugsTouched[0];+ const page = await engine.getPage(slug, { sourceId: 'default' });+ expect(page).not.toBeNull();+ const body = page!.compiled_truth;+ // Positive control: harmless prose from the same page is present.+ expect(body).toContain('deploy is failing');+ for (const v of [SEEDED_JWT, SEEDED_SID, SEEDED_GOOGLE, SEEDED_STRIPE, SEEDED_ENTROPIC, SEEDED_OPAQUE, 'p4ssw0rd']) {+ expect(body).not.toContain(v);+ }+ for (const tag of [+ '<REDACTED:jwt>', '<REDACTED:twilio>', '<REDACTED:google_api_key>', '<REDACTED:stripe>',+ '<REDACTED:db_url_credentials>', '<REDACTED:high_entropy_assignment>', '<REDACTED:bearer>',+ ]) {+ expect(body).toContain(tag);+ }+ // The session-wide echo dictionary: the token's bare mention in an+ // EARLIER message and the entropic value's in a LATER one are scrubbed.+ expect(body).toContain('the token <REDACTED:bearer> expired too');+ expect(body).toContain('pasted <REDACTED:high_entropy_assignment> into the env');+ // A project ref is an identifier, not a credential — deliberately kept.+ expect(body).toContain('zfakerefzfakeref0000');+ // Whatever session metadata rode along carries no seeded value either.+ const raw = await engine.getRawData(slug, undefined, { sourceId: 'default' });+ const stored = JSON.stringify(raw);+ for (const v of [SEEDED_JWT, SEEDED_SID, SEEDED_GOOGLE, SEEDED_STRIPE, 'p4ssw0rd']) {+ expect(stored).not.toContain(v);+ }+ });+});++/** Count calls to an engine method for one block; restores the original. */+async function spyEngine<K extends 'getRawData' | 'putRawData'>(+ method: K,+ run: () => Promise<void>,+): Promise<unknown[][]> {+ const calls: unknown[][] = [];+ const original = (engine as any)[method].bind(engine);+ (engine as any)[method] = (...args: unknown[]) => { calls.push(args); return original(...args); };+ try { await run(); } finally { delete (engine as any)[method]; }+ return calls;+}++function writePlainSession(path: string): void {+ writeFileSync(+ path,+ [+ JSON.stringify({ type: 'session', version: 3, id: 'plain-02', timestamp: '2026-08-09T11:00:00.000Z', cwd: '/tmp/plain' }),+ JSON.stringify({+ type: 'message',+ id: 'm-1',+ timestamp: '2026-08-09T11:00:01.000Z',+ message: { role: 'user', timestamp: '2026-08-09T11:00:01.000Z', content: [{ type: 'text', text: 'plain question two' }] },+ }),+ ].join('\n') + '\n',+ );+}++describe('re-ingest over a soft-deleted base page', () => {+ test('resurrects the page (hash check reads ACTIVE rows only) — the compare probe never runs, raw is rewritten', async () => {+ const p = join(tmp, 'plain-session-2.jsonl');+ writePlainSession(p);+ const r1 = await runTranscriptsIngest(engine, baseOpts([p]));+ expect(r1.pages.imported).toBe(1);+ const slug = r1.slugsTouched[0];+ expect(await engine.softDeletePage(slug, { sourceId: 'default' })).not.toBeNull();+ expect(await engine.getPage(slug, { sourceId: 'default' })).toBeNull();++ let r2: Awaited<ReturnType<typeof runTranscriptsIngest>> | undefined;+ let putCalls: unknown[][] = [];+ const probeCalls = await spyEngine('getRawData', async () => {+ putCalls = await spyEngine('putRawData', async () => {+ r2 = await runTranscriptsIngest(engine, baseOpts([p]));+ });+ });+ // No abort; the tombstoned base page reads as missing to the import+ // hash check, so it is IMPORTED again (not skipped) and comes back alive.+ expect(r2!.sessionsImported).toBe(1);+ expect(r2!.sessionsErrored).toBe(0);+ expect(r2!.cleanScan).toBe(true);+ expect(r2!.pages.imported).toBe(1);+ expect(r2!.pages.skipped).toBe(0);+ const alive = await engine.getPage(slug, { sourceId: 'default' });+ expect(alive).not.toBeNull();+ expect(alive!.deleted_at).toBeNull();+ // Because the session was NOT all-skipped, the compare-before-write+ // probe is not reached; the raw row is written fresh over the+ // resurrected page. (The probe reads ACTIVE rows only — it never needs+ // to see through a tombstone, because a tombstoned base page never+ // reaches the all-skipped branch: this test is that proof.)+ expect(probeCalls).toEqual([]);+ expect(putCalls.length).toBe(1);+ expect((await engine.getRawData(slug, undefined, { sourceId: 'default' })).length).toBe(1);+ });++ test('the compare probe fires only on an all-skipped (alive) re-run, and a content-equal row is not rewritten', async () => {+ const p = join(tmp, 'plain-session-3.jsonl');+ writePlainSession(p);+ const r1 = await runTranscriptsIngest(engine, baseOpts([p]));+ const slug = r1.slugsTouched[0];+ let putCalls: unknown[][] = [];+ const probeCalls = await spyEngine('getRawData', async () => {+ putCalls = await spyEngine('putRawData', async () => {+ const r2 = await runTranscriptsIngest(engine, baseOpts([p]));+ expect(r2.pages.skipped).toBe(1);+ expect(r2.pages.imported).toBe(0);+ });+ });+ expect(probeCalls.length).toBe(1);+ expect(probeCalls[0][0]).toBe(slug);+ expect(probeCalls[0][1]).toBe('transcript:openclaw');+ expect(probeCalls[0][2]).toEqual({ sourceId: 'default' }); // active rows only — no includeDeleted+ expect(putCalls).toEqual([]);+ });+});++describe('raw_data follows the page soft-delete', () => {+ test('after softDeletePage the session metadata is invisible; includeDeleted:true still reads it; restore brings it back', async () => {+ const p = join(tmp, 'plain-session.jsonl');+ writeFileSync(+ p,+ [+ JSON.stringify({ type: 'session', version: 3, id: 'plain-01', timestamp: '2026-08-09T10:00:00.000Z', cwd: '/tmp/plain' }),+ JSON.stringify({+ type: 'message',+ id: 'm-1',+ timestamp: '2026-08-09T10:00:01.000Z',+ message: { role: 'user', timestamp: '2026-08-09T10:00:01.000Z', content: [{ type: 'text', text: 'plain question' }] },+ }),+ ].join('\n') + '\n',+ );+ const r = await runTranscriptsIngest(engine, baseOpts([p]));+ expect(r.sessionsImported).toBe(1);+ const slug = r.slugsTouched[0];+ expect((await engine.getRawData(slug, undefined, { sourceId: 'default' })).length).toBeGreaterThan(0);++ expect(await engine.softDeletePage(slug, { sourceId: 'default' })).not.toBeNull();+ expect(await engine.getRawData(slug, undefined, { sourceId: 'default' })).toEqual([]);+ expect(await engine.getRawData(slug)).toEqual([]);+ expect((await engine.getRawData(slug, undefined, { sourceId: 'default', includeDeleted: true })).length).toBeGreaterThan(0);++ expect(await engine.restorePage(slug, { sourceId: 'default' })).toBe(true);+ expect((await engine.getRawData(slug, undefined, { sourceId: 'default' })).length).toBeGreaterThan(0);+ });+});diff --git a/test/env-trust-protected-keys.test.ts b/test/env-trust-protected-keys.test.tsnew file mode 100644index 0000000000..32457f845c--- /dev/null+++ b/test/env-trust-protected-keys.test.ts@@ -0,0 +1,69 @@+/**+ * Structural guard: the cwd-.env quarantine list cannot silently rot.+ *+ * Every `process.env.GBRAIN_*` / `Bun.env.GBRAIN_*` / `env.GBRAIN_*` read in src/ whose NAME looks+ * like a code-loading, exec-target, root-redirect, endpoint-redirect or+ * posture-widening knob (`_BIN`, `_CLI`, `_MODULE`, `_PATH`, `_HOME`, `_URL`+ * suffix or `GBRAIN_ALLOW_` prefix) must either be in CWD_DOTENV_PROTECTED_KEYS+ * or carry a `cwd-dotenv-ok: <why>` annotation on the same or the previous line.+ * Adding a new such variable without deciding its cwd-.env posture fails here.+ * (`_URL` — review cycle 3: a cwd .env retargeting GBRAIN_DATABASE_URL or the+ * OAuth relay is endpoint redirection with the operator's credentials attached.)+ */+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';+import { describe, expect, test } from 'bun:test';+import { CWD_DOTENV_PROTECTED_KEYS } from '../src/core/env-trust.ts';++const SRC_ROOT = join(import.meta.dir, '..', 'src');+const SUSPICIOUS_NAME = /_BIN$|_CLI$|_MODULE$|_PATH$|_URL$|^GBRAIN_ALLOW_|_HOME$/;+const READ_SITE = /(?:process\.env|Bun\.env|\benv)(?:\.(GBRAIN_[A-Z0-9_]+)|\[['"](GBRAIN_[A-Z0-9_]+)['"]\])/g;+const OK_MARKER = 'cwd-dotenv-ok:';++function* walk(dir: string): Generator<string> {+ for (const name of readdirSync(dir)) {+ const p = join(dir, name);+ if (statSync(p).isDirectory()) yield* walk(p);+ else if (p.endsWith('.ts') && !p.endsWith('.d.ts') && !p.endsWith('.test.ts')) yield p;+ }+}++describe('CWD_DOTENV_PROTECTED_KEYS covers every suspicious GBRAIN_* env read in src/', () => {+ test('scanner self-test: a Bun.env read of a suspicious name is flagged', () => {+ const hits = [...'const b = Bun.env.GBRAIN_FAKE_BIN; const p = process.env["GBRAIN_FAKE_MODULE"];'.matchAll(READ_SITE)]+ .map((m) => m[1] ?? m[2]!);+ expect(hits).toEqual(['GBRAIN_FAKE_BIN', 'GBRAIN_FAKE_MODULE']);+ for (const h of hits) expect(SUSPICIOUS_NAME.test(h)).toBe(true);+ expect(SUSPICIOUS_NAME.test('GBRAIN_DATABASE_URL')).toBe(true);+ expect(SUSPICIOUS_NAME.test('GBRAIN_OAUTH_RELAY_URL')).toBe(true);+ expect(SUSPICIOUS_NAME.test('GBRAIN_SOURCE')).toBe(false);+ });++ test('list is non-empty and de-duplicated', () => {+ expect(CWD_DOTENV_PROTECTED_KEYS.length).toBeGreaterThan(10);+ expect(new Set(CWD_DOTENV_PROTECTED_KEYS).size).toBe(CWD_DOTENV_PROTECTED_KEYS.length);+ });++ test('each suspicious read is protected or annotated', () => {+ const protectedSet = new Set<string>(CWD_DOTENV_PROTECTED_KEYS);+ const offenders: string[] = [];+ let scanned = 0;+ for (const file of walk(SRC_ROOT)) {+ const lines = readFileSync(file, 'utf-8').split('\n'); // every `file` lives under 'src/' (walk(SRC_ROOT))+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]!;+ for (const m of line.matchAll(READ_SITE)) {+ const name = m[1] ?? m[2]!;+ if (!SUSPICIOUS_NAME.test(name)) continue;+ scanned++;+ if (protectedSet.has(name)) continue;+ const prev = i > 0 ? lines[i - 1]! : '';+ if (line.includes(OK_MARKER) || prev.includes(OK_MARKER)) continue;+ offenders.push(`${relative(SRC_ROOT, file)}:${i + 1} reads ${name}`);+ }+ }+ }+ expect(scanned).toBeGreaterThan(5); // the scanner itself must be finding the known sites+ expect(offenders).toEqual([]);+ });+});diff --git a/test/env-trust.test.ts b/test/env-trust.test.tsnew file mode 100644index 0000000000..e426cfd65a--- /dev/null+++ b/test/env-trust.test.ts@@ -0,0 +1,383 @@+/**+ * cwd `.env` quarantine for security-relevant GBRAIN_* variables.+ *+ * Bun auto-loads `.env` from the process cwd (compiled binaries included), so+ * a `.env` committed into a cloned repository lands in process.env before any+ * gbrain code runs. The #427 DATABASE_URL guard matches VALUES, but Bun also+ * expands `${VAR}` inside .env values, so a value-match guard can never+ * recognise `KEY=${PWD}/x` — the quarantine therefore works on KEY PRESENCE:+ * a protected key that any cwd .env file assigns is dropped from the env,+ * whatever its value.+ *+ * The dir is injected instead of process.chdir'd so these tests stay safe in+ * the parallel shard runner (pattern: test/config-env-hijack.test.ts). Scratch+ * dirs are removed in `afterAll` — `process.on('exit')` never fires under+ * `bun test`, which leaked one tmp dir per fixture per run.+ */+import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { afterAll, describe, expect, test } from 'bun:test';+import {+ CWD_DOTENV_FILES,+ CWD_DOTENV_PROTECTED_KEYS,+ CWD_DOTENV_PROTECTED_PREFIXES,+ CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS,+ CWD_DOTENV_REMEDIATION,+ cwdDotenvAssignsKey,+ dotenvValuesForKey,+ isCwdDotenvProtectedKey,+ parseCwdDotenv,+ quarantineCwdDotenv,+} from '../src/core/env-trust.ts';+import { withEnv } from './helpers/with-env.ts';++const dirs: string[] = [];+function tmpProject(envFiles: Record<string, string>): string {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-env-trust-'));+ dirs.push(dir);+ for (const [name, content] of Object.entries(envFiles)) {+ writeFileSync(join(dir, name), content);+ }+ return dir;+}+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });++describe('cwdDotenvAssignsKey', () => {+ test('true when any auto-loaded .env variant assigns the key, regardless of value', () => {+ const dir = tmpProject({+ '.env': 'UNRELATED=1\n',+ '.env.production.local': 'GBRAIN_GUARDRAILS_MODULE=${PWD}/tooling/probe.ts\n',+ });+ expect(cwdDotenvAssignsKey('GBRAIN_GUARDRAILS_MODULE', dir)).toBe(true);+ expect(cwdDotenvAssignsKey('UNRELATED', dir)).toBe(true);+ expect(cwdDotenvAssignsKey('GBRAIN_HOME', dir)).toBe(false);+ });++ test('accepts export prefix, quoting, and an EMPTY value (presence, not value)', () => {+ const dir = tmpProject({+ '.env': ['# comment', 'export GBRAIN_ALLOW_SHELL_JOBS="1"', 'GBRAIN_HOME=', ''].join('\n'),+ });+ expect(cwdDotenvAssignsKey('GBRAIN_ALLOW_SHELL_JOBS', dir)).toBe(true);+ // An empty assignment still shadows the key in Bun's loader.+ expect(cwdDotenvAssignsKey('GBRAIN_HOME', dir)).toBe(true);+ // A commented-out assignment is not an assignment.+ expect(cwdDotenvAssignsKey('comment', dir)).toBe(false);+ });++ test('false when no .env file exists, or the name is outside the auto-load set', () => {+ const none = tmpProject({});+ expect(cwdDotenvAssignsKey('GBRAIN_GUARDRAILS_MODULE', none)).toBe(false);+ const staging = tmpProject({ '.env.staging': 'GBRAIN_GUARDRAILS_MODULE=/x\n' });+ expect(cwdDotenvAssignsKey('GBRAIN_GUARDRAILS_MODULE', staging)).toBe(false);+ expect(CWD_DOTENV_FILES).toContain('.env');+ expect(CWD_DOTENV_FILES).not.toContain('.env.staging');+ });++ test('dotenvValuesForKey (moved from config.ts) still collects values', () => {+ const dir = tmpProject({ '.env': 'DATABASE_URL=postgres://app.example.test/db\n' });+ expect(dotenvValuesForKey('DATABASE_URL', dir).has('postgres://app.example.test/db')).toBe(true);+ });+});++describe('CWD_DOTENV_PROTECTED_KEYS', () => {+ test('covers the code-loading, exec-target, redirect and posture-widening keys', () => {+ for (const k of [+ 'GBRAIN_GUARDRAILS_MODULE', 'GBRAIN_PLUGIN_PATH',+ 'GBRAIN_CLAUDE_CLI_BIN', 'GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG', 'GBRAIN_JOB_CHILD_CLI', 'GBRAIN_BIN_OVERRIDE',+ 'GBRAIN_HOME', 'GBRAIN_MOUNTS_PATH',+ 'GBRAIN_ALLOW_SHELL_JOBS', 'GBRAIN_ALLOW_PRIVATE_REMOTES', 'GBRAIN_ALLOW_UNVERIFIED_REMOTE',+ 'GBRAIN_GIT_ALLOW_FILE_TRANSPORT', 'GBRAIN_ALLOW_MASS_RECONCILE', 'GBRAIN_ALLOW_DEFAULT_WRITE',+ 'GBRAIN_NO_SANITY', 'GBRAIN_REMOTE_PRIVATE_PAGES',+ ]) {+ expect(CWD_DOTENV_PROTECTED_KEYS).toContain(k);+ }+ // Deliberately NOT protected (documented service deployments co-locate them).+ for (const k of ['GBRAIN_ADMIN_BOOTSTRAP_TOKEN', 'GBRAIN_HTTP_CORS_ORIGIN', 'GBRAIN_HTTP_TRUST_PROXY']) {+ expect(CWD_DOTENV_PROTECTED_KEYS).not.toContain(k);+ }+ });++ // Review cycle 3: a cwd .env that assigns GBRAIN_DATABASE_URL retargets every+ // hook, query and write at a planted database (the sibling+ // GBRAIN_DIRECT_DATABASE_URL was already protected for the same reason), and a+ // planted OAuth relay is handed the operator's tokens. The #427 VALUE guard in+ // config.ts is untouched — it still never auto-ignores GBRAIN_DATABASE_URL —+ // the KEY-PRESENCE quarantine is what drops a cwd-.env-assigned one.+ test('GBRAIN_DATABASE_URL and GBRAIN_OAUTH_RELAY_URL are protected (review cycle 3)', () => {+ for (const k of ['GBRAIN_DATABASE_URL', 'GBRAIN_OAUTH_RELAY_URL']) {+ expect(CWD_DOTENV_PROTECTED_KEYS).toContain(k);+ expect(isCwdDotenvProtectedKey(k)).toBe(true);+ }+ const dir = tmpProject({ '.env': 'GBRAIN_DATABASE_URL=postgres://planted.example.test/brain\n' });+ const env: Record<string, string | undefined> = { GBRAIN_DATABASE_URL: 'postgres://planted.example.test/brain' };+ const warnings: string[] = [];+ expect(quarantineCwdDotenv(env, dir, { warn: (m) => warnings.push(m) })).toEqual(['GBRAIN_DATABASE_URL']);+ expect('GBRAIN_DATABASE_URL' in env).toBe(false);+ expect(warnings[0]).toContain('Ignoring GBRAIN_DATABASE_URL because a .env file in the current directory assigns it');+ });++ test('endpoint-redirect GBRAIN_* keys and the sanitized re-run marker are protected (review cycle 2)', () => {+ for (const k of ['GBRAIN_DIRECT_DATABASE_URL', 'GBRAIN_REMOTE_MCP_URL', 'GBRAIN_REMOTE_ISSUER_URL', 'GBRAIN_CWD_ENV_QUARANTINED']) {+ expect(CWD_DOTENV_PROTECTED_KEYS).toContain(k);+ expect(isCwdDotenvProtectedKey(k)).toBe(true);+ }+ });+});++// ── Parse once (A2-7): the pre-parsed list is interchangeable with `dir` ─────+describe('parseCwdDotenv — one read shared by both consumers', () => {+ test('cwdDotenvAssignsKey and quarantineCwdDotenv give identical answers for `dir` and for parseCwdDotenv(dir)', () => {+ const dir = tmpProject({+ '.env': 'GIT_CONFIG_COUNT=1\nGBRAIN_HOME=${PWD}/h\nPROJECT_NAME=demo\n',+ '.env.local': 'export XDG_CONFIG_HOME="/x"\n',+ });+ const assignments = parseCwdDotenv(dir);+ expect(assignments).toEqual([+ ['GIT_CONFIG_COUNT', '1'], ['GBRAIN_HOME', '${PWD}/h'], ['PROJECT_NAME', 'demo'], ['XDG_CONFIG_HOME', '"/x"'],+ ]);+ for (const k of ['GIT_CONFIG_COUNT', 'GBRAIN_HOME', 'PROJECT_NAME', 'XDG_CONFIG_HOME', 'ABSENT']) {+ expect(cwdDotenvAssignsKey(k, assignments)).toBe(cwdDotenvAssignsKey(k, dir));+ }+ const mk = () => ({ GIT_CONFIG_COUNT: '1', GBRAIN_HOME: `${dir}/h`, PROJECT_NAME: 'demo', XDG_CONFIG_HOME: '/x', GIT_AUTHOR_NAME: 'shell' });+ const viaDir = mk(); const viaList = mk();+ const w1: string[] = []; const w2: string[] = [];+ const d1 = quarantineCwdDotenv(viaDir, dir, { warn: (m) => w1.push(m) });+ const d2 = quarantineCwdDotenv(viaList, '/nonexistent/never-read', { warn: (m) => w2.push(m), assignments });+ expect(d2).toEqual(d1);+ expect(d2).toEqual(['GBRAIN_HOME', 'GIT_CONFIG_COUNT', 'XDG_CONFIG_HOME']);+ expect(viaList).toEqual(viaDir);+ expect(w2).toEqual(w1);+ });++ test('parseCwdDotenv of a dir without .env files is empty', () => {+ expect(parseCwdDotenv(tmpProject({}))).toEqual([]);+ });+});++describe('quarantineCwdDotenv', () => {+ test('drops a protected key the cwd .env assigns — including the ${PWD}-expanded case', () => {+ const dir = tmpProject({ '.env': 'GBRAIN_GUARDRAILS_MODULE=${PWD}/tooling/probe.ts\n' });+ // What Bun actually puts in process.env after expansion: an ABSOLUTE path+ // that no value-match against the literal file text could recognise.+ const env: Record<string, string | undefined> = {+ GBRAIN_GUARDRAILS_MODULE: `${dir}/tooling/probe.ts`,+ GBRAIN_UNRELATED_THING: 'kept',+ PATH: '/usr/bin',+ };+ const warnings: string[] = [];+ const dropped = quarantineCwdDotenv(env, dir, { warn: (m) => warnings.push(m) });+ expect(dropped).toEqual(['GBRAIN_GUARDRAILS_MODULE']);+ expect('GBRAIN_GUARDRAILS_MODULE' in env).toBe(false);+ expect(env.GBRAIN_UNRELATED_THING).toBe('kept');+ expect(env.PATH).toBe('/usr/bin');+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toBe(+ '[env] Ignoring GBRAIN_GUARDRAILS_MODULE because a .env file in the current directory ' ++ 'assigns it — cwd .env files are untrusted for security settings. Export it from your ' ++ 'shell or set it in ~/.gbrain/.env.',+ );+ });++ test('several protected keys → ONE warning naming all of them; unprotected assigned keys untouched', () => {+ const dir = tmpProject({+ '.env': 'GBRAIN_ALLOW_SHELL_JOBS=1\nGBRAIN_SOURCE=wiki\n',+ '.env.local': 'GBRAIN_HOME=/tmp/elsewhere\n',+ });+ const env: Record<string, string | undefined> = {+ GBRAIN_ALLOW_SHELL_JOBS: '1',+ GBRAIN_HOME: '/tmp/elsewhere',+ GBRAIN_SOURCE: 'wiki',+ };+ const warnings: string[] = [];+ const dropped = quarantineCwdDotenv(env, dir, { warn: (m) => warnings.push(m) });+ expect(dropped.sort()).toEqual(['GBRAIN_ALLOW_SHELL_JOBS', 'GBRAIN_HOME']);+ expect(env.GBRAIN_ALLOW_SHELL_JOBS).toBeUndefined();+ expect(env.GBRAIN_HOME).toBeUndefined();+ expect(env.GBRAIN_SOURCE).toBe('wiki'); // not a protected key+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain('GBRAIN_ALLOW_SHELL_JOBS');+ expect(warnings[0]).toContain('GBRAIN_HOME');+ });++ test('a protected key that is set in env but NOT assigned by any cwd .env is honored', () => {+ const dir = tmpProject({ '.env': 'SOMETHING_ELSE=1\n' });+ const env: Record<string, string | undefined> = { GBRAIN_ALLOW_SHELL_JOBS: '1' };+ const warnings: string[] = [];+ expect(quarantineCwdDotenv(env, dir, { warn: (m) => warnings.push(m) })).toEqual([]);+ expect(env.GBRAIN_ALLOW_SHELL_JOBS).toBe('1');+ expect(warnings).toHaveLength(0);+ });++ test('no .env files → no-op, no warning; assigned-but-unset key → nothing to drop', () => {+ const none = tmpProject({});+ const env: Record<string, string | undefined> = { GBRAIN_HOME: '/tmp/x' };+ const warnings: string[] = [];+ expect(quarantineCwdDotenv(env, none, { warn: (m) => warnings.push(m) })).toEqual([]);+ expect(env.GBRAIN_HOME).toBe('/tmp/x');+ // Assigned in .env but absent from env (e.g. a `--no-env-file` run): nothing to report.+ const dir = tmpProject({ '.env': 'GBRAIN_HOME=/tmp/y\n' });+ expect(quarantineCwdDotenv({}, dir, { warn: (m) => warnings.push(m) })).toEqual([]);+ expect(warnings).toHaveLength(0);+ });++ test('quarantining process.env is visible to a child spawned with env: process.env', async () => {+ const dir = tmpProject({ '.env': 'GBRAIN_ALLOW_SHELL_JOBS=1\n' });+ await withEnv({ GBRAIN_ALLOW_SHELL_JOBS: '1' }, async () => {+ const dropped = quarantineCwdDotenv(process.env, dir, { warn: () => {} });+ expect(dropped).toEqual(['GBRAIN_ALLOW_SHELL_JOBS']);+ expect(process.env.GBRAIN_ALLOW_SHELL_JOBS).toBeUndefined();+ const proc = Bun.spawn(+ [process.execPath, '--no-env-file', '-e', 'process.stdout.write(String(process.env.GBRAIN_ALLOW_SHELL_JOBS ?? "<unset>"))'],+ { cwd: tmpProject({}), env: process.env as Record<string, string>, stdout: 'pipe', stderr: 'pipe' },+ );+ const [out] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);+ expect(out).toBe('<unset>');+ });+ });+});++// ── A1: line terminators / encoding must match Bun's loader ──────────────────+//+// Bun treats a bare `\r` as a .env line terminator (verified on 1.3.13:+// `KEY=/e\rvil` loads as `/e`, and `A=x\rB=1` loads BOTH keys). A parser that+// split on `\n` only saw one over-long line whose RHS the `(.*)$` anchor could+// not match (`.` skips `\r` and U+2028/2029), so the assignment vanished and+// the quarantine let the key through. Every case below must count as+// "assigned" — erring toward file-origin is the safe side of this guard.+describe('dotenv grammar: CR / CRLF / BOM / U+2028 (A1)', () => {+ const cases: Array<[label: string, body: string]> = [+ ['CR-only file', 'UNRELATED=1\rGBRAIN_GUARDRAILS_MODULE=${PWD}/evil.js\r'],+ ['mid-line bare CR hiding a second assignment', 'UNRELATED=${PWD}/x\rGBRAIN_GUARDRAILS_MODULE=${PWD}/evil.js\nX=1\n'],+ ['CRLF file', 'UNRELATED=1\r\nGBRAIN_GUARDRAILS_MODULE=${PWD}/evil.js\r\n'],+ ['BOM-prefixed first line', 'GBRAIN_GUARDRAILS_MODULE=${PWD}/evil.js\n'],+ ['U+2028 inside a value', 'GBRAIN_GUARDRAILS_MODULE=${PWD}/ev il.js\n'],+ ];+ for (const [label, body] of cases) {+ test(`${label}: the key counts as assigned and is quarantined`, () => {+ const dir = tmpProject({ '.env': body });+ expect(cwdDotenvAssignsKey('GBRAIN_GUARDRAILS_MODULE', dir)).toBe(true);+ const env: Record<string, string | undefined> = { GBRAIN_GUARDRAILS_MODULE: `${dir}/evil.js` };+ const warnings: string[] = [];+ expect(quarantineCwdDotenv(env, dir, { warn: (m) => warnings.push(m) })).toEqual(['GBRAIN_GUARDRAILS_MODULE']);+ expect('GBRAIN_GUARDRAILS_MODULE' in env).toBe(false);+ expect(warnings).toHaveLength(1);+ });+ }++ test('a bare CR terminates the value for the #427 guard too, and the hidden key is an assignment', () => {+ const dir = tmpProject({ '.env': 'DATABASE_URL=postgres://app.example.test/db\rOTHER=1\n' });+ expect(dotenvValuesForKey('DATABASE_URL', dir).has('postgres://app.example.test/db')).toBe(true);+ expect(cwdDotenvAssignsKey('OTHER', dir)).toBe(true);+ });+});++// ── A2: loader / git / node / proxy / AI-CLI hijack families ─────────────────+describe('non-GBRAIN hijack families (A2)', () => {+ test('isCwdDotenvProtectedKey: exact GBRAIN_* keys, prefix families, exact toolchain keys', () => {+ for (const k of [+ 'GBRAIN_HOME', 'GBRAIN_GUARDRAILS_MODULE',+ 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'DYLD_INSERT_LIBRARIES',+ 'GIT_CONFIG_COUNT', 'GIT_CONFIG_KEY_0', 'GIT_CONFIG_VALUE_0', 'GIT_SSH_COMMAND', 'GIT_EXEC_PATH',+ 'BUN_OPTIONS', 'BUN_INSTALL', 'NPM_CONFIG_REGISTRY', 'npm_config_registry',+ 'NODE_OPTIONS', 'NODE_PATH', 'NODE_EXTRA_CA_CERTS', 'NODE_TLS_REJECT_UNAUTHORIZED',+ 'SSH_ASKPASS', 'SSH_ASKPASS_REQUIRE', 'PYTHONPATH', 'PYTHONSTARTUP', 'PERL5LIB', 'PERL5OPT', 'RUBYOPT', 'RUBYLIB',+ 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy',+ 'CLAUDE_CONFIG_DIR', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'OPENAI_BASE_URL',+ ]) {+ expect(isCwdDotenvProtectedKey(k)).toBe(true);+ }+ // Ordinary project variables keep loading from a cwd .env.+ for (const k of ['GITHUB_TOKEN', 'GBRAIN_SOURCE', 'DATABASE_URL', 'PATH', 'LDFLAGS', 'NODE_ENV', 'OPENAI_API_KEY', 'GITLAB_CI', 'BUNDLE_PATH', 'TMPFILE', 'HOMEBREW_PREFIX']) {+ expect(isCwdDotenvProtectedKey(k)).toBe(false);+ }+ // Review cycle 2 (red team): XDG config roots git reads as GLOBAL config, TLS trust roots,+ // the programs children hand control to, and every provider endpoint the gateway reads from env.+ for (const k of [+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'GNUPGHOME',+ 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'CURL_CA_BUNDLE', 'REQUESTS_CA_BUNDLE',+ 'EDITOR', 'VISUAL', 'PAGER',+ 'OPENROUTER_BASE_URL', 'LITELLM_BASE_URL', 'OLLAMA_BASE_URL', 'LMSTUDIO_BASE_URL',+ 'LLAMA_SERVER_BASE_URL', 'LLAMA_SERVER_RERANKER_BASE_URL',+ ]) {+ expect(CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS).toContain(k);+ expect(isCwdDotenvProtectedKey(k)).toBe(true);+ }+ // Review cycle 3: OpenSSL code loading for every OpenSSL-linked child, the temp+ // root the sanitized re-run's neutral dir is created under, and HOME (inert while+ // exported, live when a cron/systemd unit leaves it unset).+ for (const k of ['OPENSSL_CONF', 'OPENSSL_ENGINES', 'OPENSSL_MODULES', 'TMPDIR', 'TMP', 'TEMP', 'HOME', 'USERPROFILE']) {+ expect(CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS).toContain(k);+ expect(isCwdDotenvProtectedKey(k)).toBe(true);+ }+ for (const p of ['LD_', 'DYLD_', 'GIT_', 'BUN_', 'NPM_CONFIG_', 'npm_config_']) expect(CWD_DOTENV_PROTECTED_PREFIXES).toContain(p);+ expect(CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS).toContain('NODE_OPTIONS');+ expect(new Set(CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS).size).toBe(CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS.length);+ });++ test('a GIT_CONFIG_* injection planted by the cwd .env is dropped (prefix family), ONE warning naming the keys', () => {+ const dir = tmpProject({+ '.env': 'GIT_CONFIG_COUNT=1\nGIT_CONFIG_KEY_0=core.fsmonitor\nGIT_CONFIG_VALUE_0=./tooling/evil.sh\nGBRAIN_ALLOW_SHELL_JOBS=1\nGIT_UNSET_IN_ENV=1\nPROJECT_NAME=demo\n',+ });+ const env: Record<string, string | undefined> = {+ GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'core.fsmonitor', GIT_CONFIG_VALUE_0: `${dir}/tooling/evil.sh`,+ GBRAIN_ALLOW_SHELL_JOBS: '1', PROJECT_NAME: 'demo', GIT_AUTHOR_NAME: 'from-the-shell', PATH: '/usr/bin',+ };+ const warnings: string[] = [];+ const dropped = quarantineCwdDotenv(env, dir, { warn: (m) => warnings.push(m) });+ expect(dropped).toEqual(['GBRAIN_ALLOW_SHELL_JOBS', 'GIT_CONFIG_COUNT', 'GIT_CONFIG_KEY_0', 'GIT_CONFIG_VALUE_0']);+ for (const k of dropped) expect(k in env).toBe(false);+ expect(env.PROJECT_NAME).toBe('demo'); // not protected+ expect(env.GIT_AUTHOR_NAME).toBe('from-the-shell'); // protected family, but NOT assigned by the cwd .env+ expect(env.PATH).toBe('/usr/bin');+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toMatch(/^\[env\] Ignoring GBRAIN_ALLOW_SHELL_JOBS, GIT_CONFIG_COUNT, GIT_CONFIG_KEY_0, GIT_CONFIG_VALUE_0 because a \.env file in the current directory assigns it — /);+ expect(warnings[0]).toContain(CWD_DOTENV_REMEDIATION);+ });+});++// ── Review cycle 4 (E4-1): shell-startup files + interpreter homes ───────────+//+// Every non-interactive shell gbrain's children start (git hooks gbrain writes,+// `sh -c` in workspace-push and shell jobs) sources $BASH_ENV first; an+// imported SHELLOPTS=xtrace with a `$(…)` PS4 runs on every traced command;+// PYTHONHOME / PERLLIB / GCONV_PATH relocate code the interpreters and glibc+// load. None of these carry a listed prefix, so each is an exact key here;+// BASH_FUNC_ (exported-function injection) is a prefix family.+describe('shell-startup / interpreter-home family (review cycle 4)', () => {+ const SHELL_STARTUP_KEYS = [+ 'BASH_ENV', 'SHELLOPTS', 'PS4', 'BASHOPTS', 'PROMPT_COMMAND', 'ZDOTDIR',+ 'PYTHONHOME', 'PERLLIB', 'GCONV_PATH',+ ];++ test('each shell-startup / interpreter-home key is an exact protected toolchain key', () => {+ for (const k of SHELL_STARTUP_KEYS) {+ expect(CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS).toContain(k);+ expect(isCwdDotenvProtectedKey(k)).toBe(true);+ }+ expect(new Set(CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS).size).toBe(CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS.length);+ });++ test('BASH_FUNC_ is a protected prefix (exported-function injection), by prefix not by exact name', () => {+ expect(CWD_DOTENV_PROTECTED_PREFIXES).toContain('BASH_FUNC_');+ for (const k of ['BASH_FUNC_git%%', 'BASH_FUNC_ls()', 'BASH_FUNC_x']) expect(isCwdDotenvProtectedKey(k)).toBe(true);+ // Neighbours that must keep loading from a cwd .env.+ for (const k of ['BASH_VERSION', 'BASH', 'ENVIRONMENT', 'PS1', 'SHELL', 'PYTHONDONTWRITEBYTECODE', 'PERL_BADLANG']) {+ expect(isCwdDotenvProtectedKey(k)).toBe(false);+ }+ });++ test('a planted BASH_ENV (the ${PWD}-expanded shape) is dropped from the env and named in the ONE warning', () => {+ const dir = tmpProject({ '.env': 'BASH_ENV=${PWD}/tooling/rc.sh\nSHELLOPTS=xtrace\nPS4=$(touch /tmp/x)\nPROJECT_NAME=demo\n' });+ const env: Record<string, string | undefined> = {+ BASH_ENV: `${dir}/tooling/rc.sh`, SHELLOPTS: 'xtrace', PS4: '$(touch /tmp/x)', PROJECT_NAME: 'demo', PATH: '/usr/bin',+ };+ const warnings: string[] = [];+ expect(quarantineCwdDotenv(env, dir, { warn: (m) => warnings.push(m) })).toEqual(['BASH_ENV', 'PS4', 'SHELLOPTS']);+ for (const k of ['BASH_ENV', 'PS4', 'SHELLOPTS']) expect(k in env).toBe(false);+ expect(env.PROJECT_NAME).toBe('demo');+ expect(env.PATH).toBe('/usr/bin');+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain('Ignoring BASH_ENV, PS4, SHELLOPTS because a .env file in the current directory assigns it');+ });+});diff --git a/test/export-raw-include-deleted.test.ts b/test/export-raw-include-deleted.test.tsnew file mode 100644index 0000000000..511bcebcd8--- /dev/null+++ b/test/export-raw-include-deleted.test.ts@@ -0,0 +1,72 @@+/**+ * `gbrain export` reads each page's raw_data with `includeDeleted: true` —+ * the page list decides which rows export, raw follows its page. Pins the+ * opt-in against the engine-side soft-delete filter so a page the list+ * carries can never export with a silently vanished sidecar. Real PGLite;+ * the engine read is observed through an instance-level wrapper.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runExport } from '../src/commands/export.ts';++let engine: PGLiteEngine;+let tmp: string;+let originalLog: typeof console.log;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gbrain-export-raw-'));+ originalLog = console.log;+ console.log = () => {};+});++afterEach(() => {+ console.log = originalLog;+ rmSync(tmp, { recursive: true, force: true });+});++describe('export — raw_data sidecar read', () => {+ test('getRawData is called with includeDeleted: true and the page source; the sidecar lands', async () => {+ await engine.putPage(+ 'notes/alive',+ { type: 'note', title: 'alive', compiled_truth: 'body', timeline: '' },+ { sourceId: 'default' },+ );+ await engine.putRawData('notes/alive', 'feed', { k: 'v' }, { sourceId: 'default' });++ const seen: unknown[] = [];+ const real = engine.getRawData;+ (engine as unknown as { getRawData: unknown }).getRawData = async (+ slug: string, source: string | undefined, opts: unknown,+ ) => {+ seen.push({ slug, source, opts });+ return real.call(engine, slug, source, opts as never);+ };+ try {+ await runExport(engine, ['--dir', join(tmp, 'out')]);+ } finally {+ delete (engine as unknown as { getRawData?: unknown }).getRawData; // back to the prototype method+ }++ expect(seen).toContainEqual({+ slug: 'notes/alive',+ source: undefined,+ opts: { sourceId: 'default', includeDeleted: true },+ });+ const sidecar = join(tmp, 'out', 'notes', '.raw', 'alive.json');+ expect(existsSync(sidecar)).toBe(true);+ expect(JSON.parse(readFileSync(sidecar, 'utf-8'))).toEqual({ feed: { k: 'v' } });+ });+});diff --git a/test/fixtures/guards/check-compile-autoload.sh/bad/docs/prose.md b/test/fixtures/guards/check-compile-autoload.sh/bad/docs/prose.mdnew file mode 100644index 0000000000..f9274fc62e--- /dev/null+++ b/test/fixtures/guards/check-compile-autoload.sh/bad/docs/prose.md@@ -0,0 +1 @@+Prose that names `bun build --compile` without an invocation is fine and must not trip the guard.diff --git a/test/fixtures/guards/check-compile-autoload.sh/bad/package.json b/test/fixtures/guards/check-compile-autoload.sh/bad/package.jsonnew file mode 100644index 0000000000..540cdd5a3d--- /dev/null+++ b/test/fixtures/guards/check-compile-autoload.sh/bad/package.json@@ -0,0 +1,6 @@+{+ "name": "fixture-bad",+ "scripts": {+ "build": "bun build --compile --outfile bin/tool src/cli.ts"+ }+}diff --git a/test/fixtures/guards/check-compile-autoload.sh/bad/scripts/build-thing.ts b/test/fixtures/guards/check-compile-autoload.sh/bad/scripts/build-thing.tsnew file mode 100644index 0000000000..4cf6d481b1--- /dev/null+++ b/test/fixtures/guards/check-compile-autoload.sh/bad/scripts/build-thing.ts@@ -0,0 +1,6 @@+// Known-BAD: spawn-array compile WITHOUT --no-compile-autoload-bunfig.+declare const spawnSync: (cmd: string, args: string[], opts: unknown) => unknown;+declare const binPath: string;+declare const ROOT: string;+spawnSync('bun', ['build', '--compile', '--outfile', binPath, 'src/cli.ts'], { cwd: ROOT });+export {};diff --git a/test/fixtures/guards/check-compile-autoload.sh/good/.github/workflows/release.yml b/test/fixtures/guards/check-compile-autoload.sh/good/.github/workflows/release.ymlnew file mode 100644index 0000000000..bc2eb7de4a--- /dev/null+++ b/test/fixtures/guards/check-compile-autoload.sh/good/.github/workflows/release.yml@@ -0,0 +1,4 @@+jobs:+ build:+ steps:+ - run: bun build --compile --no-compile-autoload-bunfig --target=${{ matrix.target }} --outfile bin/${{ matrix.artifact }} src/cli.tsdiff --git a/test/fixtures/guards/check-compile-autoload.sh/good/docs/prose.md b/test/fixtures/guards/check-compile-autoload.sh/good/docs/prose.mdnew file mode 100644index 0000000000..9177042133--- /dev/null+++ b/test/fixtures/guards/check-compile-autoload.sh/good/docs/prose.md@@ -0,0 +1,2 @@+Prose that names `bun build --compile` without an invocation (no --outfile) must not trip the guard.+The `bun build --compile` binary embeds PGLite assets.diff --git a/test/fixtures/guards/check-compile-autoload.sh/good/package.json b/test/fixtures/guards/check-compile-autoload.sh/good/package.jsonnew file mode 100644index 0000000000..cb8cfd1af9--- /dev/null+++ b/test/fixtures/guards/check-compile-autoload.sh/good/package.json@@ -0,0 +1,7 @@+{+ "name": "fixture-good",+ "scripts": {+ "build": "bun build --compile --no-compile-autoload-bunfig --outfile bin/tool src/cli.ts",+ "build:all": "bun build --compile --no-compile-autoload-bunfig --target=bun-linux-x64 --outfile bin/tool-linux src/cli.ts"+ }+}diff --git a/test/fixtures/guards/check-compile-autoload.sh/good/scripts/build-thing.ts b/test/fixtures/guards/check-compile-autoload.sh/good/scripts/build-thing.tsnew file mode 100644index 0000000000..d05ef9b92b--- /dev/null+++ b/test/fixtures/guards/check-compile-autoload.sh/good/scripts/build-thing.ts@@ -0,0 +1,6 @@+// Known-GOOD: spawn-array compile carrying the flag on the same line.+declare const spawnSync: (cmd: string, args: string[], opts: unknown) => unknown;+declare const binPath: string;+declare const ROOT: string;+spawnSync('bun', ['build', '--compile', '--no-compile-autoload-bunfig', '--outfile', binPath, 'src/cli.ts'], { cwd: ROOT });+export {};diff --git a/test/fixtures/guards/check-compile-autoload.sh/good/scripts/smoke.sh b/test/fixtures/guards/check-compile-autoload.sh/good/scripts/smoke.shnew file mode 100644index 0000000000..9641e4c78e--- /dev/null+++ b/test/fixtures/guards/check-compile-autoload.sh/good/scripts/smoke.sh@@ -0,0 +1,3 @@+#!/usr/bin/env bash+# Known-good shell form; a comment that says `bun build --compile` builds a binary is prose.+bun build --compile --no-compile-autoload-bunfig --outfile "$OUT_BIN" scripts/smoketest.tsdiff --git a/test/guardrails-env-load.test.ts b/test/guardrails-env-load.test.tsindex 257707fc51..f2f1ad0d98 100644--- a/test/guardrails-env-load.test.ts+++ b/test/guardrails-env-load.test.ts@@ -11,10 +11,10 @@* - fail-CLOSED: module that registers nothing throws GuardrailLoadError*/-import { describe, test, expect, beforeEach, afterAll } from 'bun:test';-import { mkdtempSync, writeFileSync, rmSync } from 'fs';-import { join } from 'path';-import { tmpdir } from 'os';+import { describe, test, expect, beforeEach, afterAll, spyOn } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'fs';+import { join, relative } from 'path';+import { homedir, tmpdir } from 'os';import {__resetGuardrailProvidersForTests,hasGuardrails,@@ -22,6 +22,7 @@ import {runGuardrails,GuardrailLoadError,} from '../src/core/guardrails.ts';+import { withEnv } from './helpers/with-env.ts';// One fresh mkdtemp per fixture: bun caches a directory's listing after the// first dynamic import from it, so a second module written into the SAME dir@@ -145,3 +146,157 @@ describe('#3688 residual — top-level side-effect registration counts', () => {expect(hasGuardrails()).toBe(true);});});++describe('cwd-relative specs and cwd-.env-assigned specs are refused', () => {+ /** Fixture whose TOP LEVEL drops a marker — proves the module was never imported. */+ function markerFixture(): { path: string; marker: string; dir: string } {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-guardrails-relspec-'));+ dirs.push(dir);+ const marker = join(dir, 'PROBE_RAN');+ const path = join(dir, 'probe.mjs');+ writeFileSync(path, `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, 'ran');\nexport default undefined;\n`);+ return { path, marker, dir };+ }++ test('a cwd-relative spec (./, ../, bare .) throws GuardrailLoadError WITHOUT importing', async () => {+ const { marker } = markerFixture();+ for (const spec of ['./probe.mjs', '../probe.mjs', '.']) {+ const err = await loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: spec }).then(+ () => null,+ (e: unknown) => e,+ );+ expect(err).toBeInstanceOf(GuardrailLoadError);+ expect((err as Error).message).toContain('absolute');+ }+ expect(existsSync(marker)).toBe(false);+ expect(hasGuardrails()).toBe(false);+ });++ test('an absolute spec that a cwd .env file assigns is refused (opts.cwd)', async () => {+ const { path, marker, dir } = markerFixture();+ writeFileSync(join(dir, '.env'), 'GBRAIN_GUARDRAILS_MODULE=${PWD}/probe.mjs\n');+ await expect(+ loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: path }, { cwd: dir }),+ ).rejects.toBeInstanceOf(GuardrailLoadError);+ expect(existsSync(marker)).toBe(false);+ // Same spec, a cwd WITHOUT a .env assigning the key → loads normally.+ const clean = mkdtempSync(join(tmpdir(), 'gbrain-guardrails-clean-cwd-'));+ dirs.push(clean);+ await expect(+ loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: path }, { cwd: clean }),+ ).rejects.toBeInstanceOf(GuardrailLoadError); // imported (marker) but registers nothing+ expect(existsSync(marker)).toBe(true);+ });++ test('process.env path: the cwd check applies when env is process.env', async () => {+ const { path, marker, dir } = markerFixture();+ writeFileSync(join(dir, '.env'), 'GBRAIN_GUARDRAILS_MODULE=./probe.mjs\n');+ await withEnv({ GBRAIN_GUARDRAILS_MODULE: path }, async () => {+ await expect(loadGuardrailProvidersFromEnv(process.env, { cwd: dir })).rejects.toBeInstanceOf(GuardrailLoadError);+ });+ expect(existsSync(marker)).toBe(false);+ });+});++describe('bare package specifiers are refused (A3)', () => {+ /**+ * In the compiled binary a bare specifier resolves through Bun's module+ * walk-up FROM THE CWD, so a hostile checkout's node_modules/<name>/ is what+ * gets loaded. Only absolute and `~/` paths name a module the operator chose.+ */+ function cwdWithPackage(name: string): { dir: string; marker: string } {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-guardrails-barespec-'));+ dirs.push(dir);+ const marker = join(dir, 'PROBE_RAN');+ const pkgDir = join(dir, 'node_modules', ...name.split('/'));+ mkdirSync(pkgDir, { recursive: true });+ writeFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name, main: 'index.js' }));+ writeFileSync(+ join(pkgDir, 'index.js'),+ `require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'ran');\nmodule.exports = { id: 'fixture-bare', classify() {} };\n`,+ );+ return { dir, marker };+ }++ test('a bare name, a scoped name and a subpath all throw GuardrailLoadError BEFORE any import', async () => {+ for (const spec of ['gbrain-fixture-guardrail', '@fixture-scope/guardrail', 'gbrain-fixture-guardrail/register']) {+ const { dir, marker } = cwdWithPackage(spec.startsWith('@') ? spec : spec.split('/')[0]!);+ const err = await loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: spec }, { cwd: dir }).then(+ () => null,+ (e: unknown) => e,+ );+ expect(err).toBeInstanceOf(GuardrailLoadError);+ expect((err as Error).message).toContain('must be an absolute path or a ~/ path');+ expect((err as Error).message).toContain("node_modules");+ expect(existsSync(marker)).toBe(false);+ }+ expect(hasGuardrails()).toBe(false);+ });++ test('the relative-spec message no longer advertises package names', async () => {+ const err = await loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: './x.mjs' }).then(() => null, (e: unknown) => e);+ expect((err as Error).message).not.toContain('package name');+ });+});++describe('zero-arg library call: env defaults to process.env, cwd to process.cwd() (A8)', () => {+ test('loadGuardrailProvidersFromEnv() refuses a spec that the cwd .env assigns', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-guardrails-zeroarg-'));+ dirs.push(dir);+ const marker = join(dir, 'PROBE_RAN');+ const path = join(dir, 'probe.mjs');+ writeFileSync(path, `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, 'ran');\nexport default undefined;\n`);+ writeFileSync(join(dir, '.env'), 'GBRAIN_GUARDRAILS_MODULE=${PWD}/probe.mjs\n');+ // Never process.chdir() in a shared test process — mock the cwd read instead.+ const cwdSpy = spyOn(process, 'cwd').mockReturnValue(dir);+ try {+ await withEnv({ GBRAIN_GUARDRAILS_MODULE: path }, async () => {+ const err = await loadGuardrailProvidersFromEnv().then(() => null, (e: unknown) => e);+ expect(err).toBeInstanceOf(GuardrailLoadError);+ expect((err as Error).message).toContain('assigned by a .env file in the current directory');+ });+ } finally {+ cwdSpy.mockRestore();+ }+ expect(existsSync(marker)).toBe(false);+ expect(hasGuardrails()).toBe(false);+ });+});++// The `~/` branch now goes through STATIC node:path / node:url / node:os+// imports (the runtime dynamic imports were removed alongside the origin+// checks). Pin that a `~/` spec still expands against the home dir and is+// imported. Bun caches os.homedir() at first call, so a HOME override cannot+// drive this: the probe is written into a cleaned-up temp dir under the REAL+// home (skipped when that home is not writable, e.g. a read-only CI HOME).+// Computed ONCE at module scope so the skip decision is visible in the report+// instead of a silent early return inside the test body.+const canWriteHome = (() => {+ try {+ const probe = mkdtempSync(join(homedir(), '.gbrain-guardrails-tilde-probe-'));+ rmSync(probe, { recursive: true, force: true });+ return true;+ } catch {+ return false;+ }+})();++describe('~/ specs expand against the home directory', () => {+ test.skipIf(!canWriteHome)('a ~/ spec resolves under homedir() and is imported (then fail-closed on zero providers)', async () => {+ const home = mkdtempSync(join(homedir(), '.gbrain-guardrails-tilde-'));+ try {+ const marker = join(home, 'PROBE_RAN');+ writeFileSync(+ join(home, 'probe.mjs'),+ `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, 'ran');\nexport default undefined;\n`,+ );+ const spec = '~/' + relative(homedir(), join(home, 'probe.mjs'));+ await expect(loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: spec }))+ .rejects.toBeInstanceOf(GuardrailLoadError);+ expect(existsSync(marker)).toBe(true); // expanded + imported; the rejection is the zero-provider rule+ expect(hasGuardrails()).toBe(false);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});diff --git a/test/hook-push-spawn-env.test.ts b/test/hook-push-spawn-env.test.tsnew file mode 100644index 0000000000..f939b9c3e5--- /dev/null+++ b/test/hook-push-spawn-env.test.ts@@ -0,0 +1,45 @@+/**+ * `gbrain hook` fires `gbrain sources push` as a DETACHED child. A child+ * spawned WITHOUT an explicit `env` option does not see the parent's cwd-.env+ * quarantine deletions (core/env-trust.ts — verified on Bun 1.3.10), so a+ * hostile repo's GBRAIN_* keys would resurface inside the push process. The+ * spawn is private and fire-and-forget, so this is a source-shape guard (the+ * proven `autopilot-*-wiring.test.ts` pattern).+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++// test-reads-source-ok: the property under test is a source SHAPE — every detached/exec spawn in hook.ts must pass `env: process.env` so the cwd-.env quarantine reaches the child; a runtime probe cannot enumerate spawn sites, only grepping the source can.+const SRC = readFileSync(join(import.meta.dir, '../src/commands/hook.ts'), 'utf8');++function spawnDetachedPushBody(): string {+ const start = SRC.indexOf('function spawnDetachedPush(');+ expect(start).toBeGreaterThan(-1);+ const end = SRC.indexOf('\n}\n', start);+ expect(end).toBeGreaterThan(start);+ return SRC.slice(start, end);+}++describe('spawnDetachedPush env handoff', () => {+ test('the detached push child is spawned with the (quarantined) process.env, explicitly', () => {+ const body = spawnDetachedPushBody();+ expect(body).toMatch(/spawn\([^)]*\{[^}]*detached:\s*true[^}]*env:\s*process\.env[^}]*\}/s);+ });++ test('every detached spawn in hook.ts carries an explicit env option', () => {+ const detachedSpawns = SRC.match(/spawn\([^;]*detached:\s*true[^;]*;/gs) ?? [];+ expect(detachedSpawns.length).toBeGreaterThan(0);+ // Either the quarantined object itself, or a fresh object spread FROM it (both see the deletions).+ for (const s of detachedSpawns) expect(s).toMatch(/env:\s*(?:process\.env|\{\s*\.\.\.process\.env)/);+ });+});++describe('tryExecAsync env handoff', () => {+ test('the git exec wrapper passes the (quarantined) process.env explicitly', () => {+ const start = SRC.indexOf('function tryExecAsync(');+ expect(start).toBeGreaterThan(-1);+ const body = SRC.slice(start, SRC.indexOf('\n}\n', start));+ expect(body).toMatch(/execFile\([\s\S]*?\{[^}]*env:\s*process\.env[^}]*\}/);+ });+});diff --git a/test/job-isolation-allow-shell-jobs.test.ts b/test/job-isolation-allow-shell-jobs.test.tsnew file mode 100644index 0000000000..bd0c9f8d01--- /dev/null+++ b/test/job-isolation-allow-shell-jobs.test.ts@@ -0,0 +1,24 @@+/**+ * `--job-isolation process`: the per-job child (`gbrain jobs run-child`) is a+ * fresh gbrain process that re-runs the startup cwd-.env quarantine in the+ * SAME cwd as the worker, so an env-only handoff of GBRAIN_ALLOW_SHELL_JOBS is+ * dropped again whenever a .env there assigns it — exactly the hole+ * `jobs work --allow-shell-jobs` closes for the supervisor → worker hop. The+ * opt-in therefore travels to the child as a flag too (`buildChildArgs`), and+ * the `run-child` case re-asserts the env var from it after preflight.+ */+import { describe, expect, test } from 'bun:test';+import { buildChildArgs } from '../src/core/minions/job-isolation.ts';++describe('buildChildArgs — --allow-shell-jobs pass-through (A5)', () => {+ test('appends --allow-shell-jobs when the spawning env carries GBRAIN_ALLOW_SHELL_JOBS=1', () => {+ expect(buildChildArgs(42, { GBRAIN_ALLOW_SHELL_JOBS: '1' }))+ .toEqual(['jobs', 'run-child', '--job-id', '42', '--allow-shell-jobs']);+ });++ test('omits the flag when the opt-in is absent or not exactly "1" (argv byte-identical)', () => {+ expect(buildChildArgs(42, {})).toEqual(['jobs', 'run-child', '--job-id', '42']);+ expect(buildChildArgs(7, { GBRAIN_ALLOW_SHELL_JOBS: 'true' })).not.toContain('--allow-shell-jobs');+ expect(buildChildArgs(7, { GBRAIN_ALLOW_SHELL_JOBS: '' })).not.toContain('--allow-shell-jobs');+ });+});diff --git a/test/jobs-work-allow-shell-jobs-flag.test.ts b/test/jobs-work-allow-shell-jobs-flag.test.tsnew file mode 100644index 0000000000..5689c3c745--- /dev/null+++ b/test/jobs-work-allow-shell-jobs-flag.test.ts@@ -0,0 +1,102 @@+/**+ * `gbrain jobs work --allow-shell-jobs` re-asserts GBRAIN_ALLOW_SHELL_JOBS=1+ * AFTER the startup cwd-.env quarantine (core/env-trust.ts drops that env var+ * whenever a .env in the worker's cwd assigns it), so a supervisor-spawned+ * worker (buildWorkerArgs pass-through) keeps its shell handler enabled.+ *+ * The `work` case is a long-running daemon, so the test stops it at the very+ * next validation exit — `--health-interval abc` → process.exit(1) — which+ * sits AFTER the flag line; process.exit is stubbed to throw (the+ * storage-export.test.ts convention). No worker loop ever starts and nothing+ * connects to a database: the config only has to be non-PGLite to get past+ * the `work` case's PGLite refusal.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runJobs } from '../src/commands/jobs.ts';+import { saveConfig } from '../src/core/config.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { JOB_CHILD_EXIT_USAGE } from '../src/core/minions/worker-exit-codes.ts';+import { withEnv } from './helpers/with-env.ts';++const EXIT = '__test_exit__';+let home: string;+let originalExit: typeof process.exit;+let originalError: typeof console.error;+let stderr: string[];++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-jobs-work-flag-'));+ stderr = [];+ originalExit = process.exit;+ process.exit = ((code?: number) => {+ throw new Error(`${EXIT}:${code ?? 0}`);+ }) as typeof process.exit;+ originalError = console.error;+ console.error = (...args: unknown[]) => {+ stderr.push(args.map(String).join(' '));+ };+});++afterEach(() => {+ process.exit = originalExit;+ console.error = originalError;+ rmSync(home, { recursive: true, force: true });+});++/** Run `jobs work <args> --health-interval abc`; returns the env var as the flag line left it. */+async function runWork(args: string[]): Promise<string> {+ return withEnv(+ { GBRAIN_HOME: home, GBRAIN_ALLOW_SHELL_JOBS: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },+ async () => {+ saveConfig({ engine: 'postgres', database_url: 'postgresql://worker.invalid/brain' } as never);+ const err = await runJobs({} as unknown as BrainEngine, ['work', ...args, '--health-interval', 'abc'])+ .then(() => null, (e: unknown) => e);+ expect((err as Error).message).toBe(`${EXIT}:1`);+ expect(stderr.join('\n')).toContain('--health-interval must be a non-negative integer');+ return process.env.GBRAIN_ALLOW_SHELL_JOBS ?? '<unset>';+ },+ );+}++describe('jobs work --allow-shell-jobs', () => {+ test('the flag re-asserts GBRAIN_ALLOW_SHELL_JOBS=1 after preflight (before any worker starts)', async () => {+ expect(await runWork(['--allow-shell-jobs'])).toBe('1');+ });++ test('without the flag the env var stays unset — no implicit shell opt-in', async () => {+ expect(await runWork([])).toBe('<unset>');+ });+});++// ── `jobs run-child --allow-shell-jobs` (A5) ─────────────────────────────────+//+// The process-isolation child re-runs preflight in the worker's cwd, so the+// flag `buildChildArgs` appends must re-assert the env var there too. The+// `run-child` case exits at its usage check when no --job-id is given (after+// the re-assert), which is the observation point — no job, no DB, no handler.+describe('jobs run-child --allow-shell-jobs', () => {+ async function runChild(args: string[]): Promise<string> {+ return withEnv(+ { GBRAIN_HOME: home, GBRAIN_ALLOW_SHELL_JOBS: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },+ async () => {+ saveConfig({ engine: 'postgres', database_url: 'postgresql://worker.invalid/brain' } as never);+ const engine = { disconnect: async () => {} } as unknown as BrainEngine;+ const err = await runJobs(engine, ['run-child', ...args]).then(() => null, (e: unknown) => e);+ expect((err as Error).message).toBe(`${EXIT}:${JOB_CHILD_EXIT_USAGE}`);+ expect(stderr.join('\n')).toContain('[run-child] internal command');+ return process.env.GBRAIN_ALLOW_SHELL_JOBS ?? '<unset>';+ },+ );+ }++ test('the flag re-asserts GBRAIN_ALLOW_SHELL_JOBS=1 in the child after preflight', async () => {+ expect(await runChild(['--allow-shell-jobs'])).toBe('1');+ });++ test('without the flag the child has no implicit shell opt-in', async () => {+ expect(await runChild([])).toBe('<unset>');+ });+});diff --git a/test/migrate-engine-raw-include-deleted.test.ts b/test/migrate-engine-raw-include-deleted.test.tsnew file mode 100644index 0000000000..bd0b168d6f--- /dev/null+++ b/test/migrate-engine-raw-include-deleted.test.ts@@ -0,0 +1,66 @@+/**+ * copyPageToTarget reads raw_data with `includeDeleted: true`. Both engines'+ * getRawData now follow the page soft-delete (`deleted_at IS NULL`), so+ * without the opt-in a migration would silently drop the raw_data of every+ * tombstoned page the page list decided to carry. Fake engines, same shape as+ * migrate-engine-page-copy-failure.serial.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { copyPageToTarget } from '../src/commands/migrate-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { Page } from '../src/core/types.ts';++function fakePage(overrides: Partial<Page> = {}): Page {+ return {+ id: 7,+ slug: 'notes/tombstoned',+ type: 'note',+ title: 't',+ compiled_truth: 'body',+ timeline: '',+ frontmatter: {},+ source_id: 'beta',+ created_at: new Date(),+ updated_at: new Date(),+ ...overrides,+ };+}++describe('copyPageToTarget — raw_data read opts', () => {+ test('reads raw_data with includeDeleted: true scoped to the page source, and forwards every row', async () => {+ const getRawDataCalls: unknown[] = [];+ const putRawDataCalls: unknown[] = [];+ const rows = [+ { source: 'transcript:claude-code', data: { cwd: '/tmp/x' }, fetched_at: new Date() },+ { source: 'feed', data: { a: 1 }, fetched_at: new Date() },+ ];+ const source = {+ getChunksWithEmbeddings: async () => [],+ getTags: async () => [],+ getTimeline: async () => [],+ getRawData: async (slug: string, rawSource: unknown, opts: unknown) => {+ getRawDataCalls.push({ slug, rawSource, opts });+ return rows;+ },+ } as unknown as BrainEngine;+ const target = {+ putPage: async () => fakePage(),+ executeRaw: async () => [],+ putRawData: async (slug: string, rawSource: string, data: unknown, opts: unknown) => {+ putRawDataCalls.push({ slug, rawSource, data, opts });+ },+ } as unknown as BrainEngine;++ // A tombstoned source row: the page list decided it travels, raw must follow.+ const stats = await copyPageToTarget(source, target, fakePage({ deleted_at: new Date() }));++ expect(getRawDataCalls).toEqual([+ { slug: 'notes/tombstoned', rawSource: undefined, opts: { sourceId: 'beta', includeDeleted: true } },+ ]);+ expect(putRawDataCalls).toEqual([+ { slug: 'notes/tombstoned', rawSource: 'transcript:claude-code', data: { cwd: '/tmp/x' }, opts: { sourceId: 'beta' } },+ { slug: 'notes/tombstoned', rawSource: 'feed', data: { a: 1 }, opts: { sourceId: 'beta' } },+ ]);+ expect(stats.raw_data).toBe(2);+ });+});diff --git a/test/oauth-authorize-scope-default.test.ts b/test/oauth-authorize-scope-default.test.tsindex 612dc66f8c..7928e76208 100644--- a/test/oauth-authorize-scope-default.test.ts+++ b/test/oauth-authorize-scope-default.test.ts@@ -88,3 +88,45 @@ describe('authorize() scope default — omitted scope inherits client grant', ()expect(await authorizeAndReadScopes('read write', ['admin'])).toEqual([]);});});++// A self-registered (DCR) client is capped at `read write` at registration;+// the /authorize clamp then bounds every code it mints to that registered+// grant. Together: an anonymous registrant can never mint a privileged code,+// however it phrases the /authorize request.+describe('authorize() clamp on a DCR-registered client', () => {+ async function dcrAuthorizeAndReadScopes(requested: string[]): Promise<string[]> {+ const info = await provider.clientsStore.registerClient!({+ client_name: 'dcr-authz-clamp',+ redirect_uris: ['https://example.test/cb'],+ grant_types: ['authorization_code'],+ scope: 'read write',+ token_endpoint_auth_method: 'none',+ } as any);+ expect(info.scope).toBe('read write');+ const client = await provider.clientsStore.getClient(info.client_id);+ expect(client).toBeTruthy();+ await authorizeAsOwner(provider,+ client!,+ {+ scopes: requested,+ codeChallenge: TEST_PKCE_CHALLENGE,+ redirectUri: 'https://example.test/cb',+ state: 'xyz',+ } as any,+ noopRes,+ );+ const rows = (await sql`+ SELECT scopes FROM oauth_codes WHERE client_id = ${info.client_id}+ `) as Array<{ scopes: string[] }>;+ expect(rows.length).toBe(1);+ return rows[0].scopes ?? [];+ }++ test('request "read write admin" → code carries ["read","write"]', async () => {+ expect((await dcrAuthorizeAndReadScopes(['read', 'write', 'admin'])).sort()).toEqual(['read', 'write']);+ });++ test('request "admin" alone → code carries []', async () => {+ expect(await dcrAuthorizeAndReadScopes(['admin'])).toEqual([]);+ });+});diff --git a/test/oauth-consent-security.test.ts b/test/oauth-consent-security.test.tsindex 6c1424a5c0..1381f15a12 100644--- a/test/oauth-consent-security.test.ts+++ b/test/oauth-consent-security.test.ts@@ -226,18 +226,123 @@ describe('owner-approved HTTP authorization', () => {});});+/** In-memory grant store whose client row echoes the queried client_id, so many distinct clients can be simulated. */+function memoryGrants() {+ const row = { client_name: 'synthetic', scope: 'read', grant_types: ['authorization_code'], redirect_uris: [REDIRECT] };+ const clock = { now: 0 };+ const options = { sql: (async (_strings: TemplateStringsArray, ...values: unknown[]) => [{ ...row, client_id: values[0] }]) as SqlQuery, tokenTtl: 60, refreshTtl: 3600, now: () => clock.now };+ return { grants: new OAuthGrants(options), options, clock, params: { codeChallenge: TEST_PKCE_CHALLENGE, redirectUri: REDIRECT } };+}++/** Anonymous dynamic registration (the advisory shape) must land on the same owner-consent gate as operator-registered clients. */+describe('dynamically registered public clients', () => {+ const ATTACKER_REDIRECT = 'https://client-example.invalid/cb';+ async function registerDcr(overrides: Record<string, unknown> = {}, omit: string[] = []) {+ const body: Record<string, unknown> = { client_name: 'synthetic self-registered client', redirect_uris: [ATTACKER_REDIRECT],+ grant_types: ['authorization_code'], response_types: ['code'], scope: 'read write', token_endpoint_auth_method: 'none', ...overrides };+ for (const key of omit) delete body[key];+ const response = await fetch(`${base}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });+ expect(response.status).toBe(201);+ return response.json() as Promise<any>;+ }+ async function authorizeRaw(clientId: string, scope?: string) {+ const query = new URLSearchParams({ client_id: clientId, response_type: 'code', redirect_uri: ATTACKER_REDIRECT,+ code_challenge: TEST_PKCE_CHALLENGE, code_challenge_method: 'S256', state: 'attacker-state' });+ if (scope !== undefined) query.set('scope', scope);+ return fetch(`${base}/authorize?${query}`, { redirect: 'manual' });+ }+ async function expectPending(clientId: string, scope?: string) {+ const response = await authorizeRaw(clientId, scope);+ expect(response.status).toBe(302);+ const location = new URL(response.headers.get('location')!, base);+ expect(location.pathname).toBe('/admin/');+ expect(location.searchParams.has('code')).toBe(false);+ expect(location.hash).toBe('#oauth-consent');+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${clientId}`).toHaveLength(0);+ return location.searchParams.get('oauth_request')!;+ }++ test('anonymous registration with a foreign redirect_uri yields a consent request, never a code, and forged codes do not redeem', async () => {+ const client = await registerDcr();+ expect(client.client_id).toStartWith('gbrain_cl_');+ expect(client.client_secret).toBeUndefined();+ const id = await expectPending(client.client_id, 'read write');+ expect(provider.grants.hasPending(id)).toBe(true);+ const forged = await fetch(`${base}/token`, { method: 'POST', body: new URLSearchParams({+ grant_type: 'authorization_code', code: 'gbrain_code_' + 'a'.repeat(43), code_verifier: TEST_PKCE_VERIFIER,+ client_id: client.client_id, redirect_uri: ATTACKER_REDIRECT }) });+ expect(forged.status).toBe(400);+ expect((await forged.json() as any).error).toBe('invalid_grant');+ expect(await sql`SELECT * FROM oauth_tokens WHERE client_id = ${client.client_id}`).toHaveLength(0);+ });++ test('registration omitting grant_types defaults to the consent-bearing authorization_code flow', async () => {+ const client = await registerDcr({}, ['grant_types']);+ expect(client.grant_types ?? ['authorization_code']).toEqual(['authorization_code']);+ await expectPending(client.client_id, 'read write');+ });++ test('registration omitting scope registers no scope and its consent request carries no scopes', async () => {+ const client = await registerDcr({}, ['scope']);+ expect(client.scope ?? '').toBe('');+ const id = await expectPending(client.client_id);+ expect((await details(id)).scopes).toEqual([]);+ });++ test('the eleventh pending request for one client is a redirect carrying error=too_many_requests, not a 429', async () => {+ // Contract pin for the docs: the per-client cap trips inside+ // provider.authorize(), which the MCP SDK's phase-2 catch turns into a+ // 302 back to the registered redirect_uri with error parameters. A 429+ // body on /authorize only ever comes from the SDK's per-IP limiter.+ const client = await registerDcr();+ for (let i = 0; i < 10; i++) await expectPending(client.client_id, 'read');+ const response = await authorizeRaw(client.client_id, 'read');+ expect(response.status).toBe(302);+ const location = new URL(response.headers.get('location')!);+ expect(location.origin + location.pathname).toBe(ATTACKER_REDIRECT);+ expect(location.searchParams.get('error')).toBe('too_many_requests');+ expect(location.searchParams.get('error_description')).toMatch(/pending requests for this client/);+ expect(location.searchParams.get('state')).toBe('attacker-state');+ expect(location.searchParams.has('code')).toBe(false);+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${client.client_id}`).toHaveLength(0);+ });++ test('a revoked self-registered client is rejected before any consent request is created', async () => {+ const client = await registerDcr();+ await provider.revokeClient(client.client_id);+ const response = await authorizeRaw(client.client_id, 'read write');+ expect(response.status).toBe(400);+ expect((await response.json() as any).error).toBe('invalid_client');+ await expect(provider.grants.begin(client.client_id, { codeChallenge: TEST_PKCE_CHALLENGE, redirectUri: ATTACKER_REDIRECT, scopes: ['read'] }))+ .rejects.toThrow('revoked');+ });+});+test('pending authorization expires, restart forgets it, and capacity is bounded without evicting live requests', async () => {- const row = { client_id: 'synthetic', client_name: 'synthetic', scope: 'read', grant_types: ['authorization_code'], redirect_uris: [REDIRECT] };- let now = 0;- const options = { sql: (async () => [row]) as SqlQuery, tokenTtl: 60, refreshTtl: 3600, now: () => now };- const grants = new OAuthGrants(options);- const params = { codeChallenge: TEST_PKCE_CHALLENGE, redirectUri: REDIRECT };+ // Fill the global store from many distinct clients (the per-client cap bounds any single client well below this).+ const { grants, options, clock, params } = memoryGrants();const first = await grants.begin('synthetic', params);- for (let i = 1; i < 1000; i++) await grants.begin('synthetic', params);- await expect(grants.begin('synthetic', params)).rejects.toThrow('Too many pending');+ for (let i = 1; i < 1000; i++) await grants.begin(`synthetic-${i}`, params);+ await expect(grants.begin('synthetic-overflow', params)).rejects.toThrow('Too many pending');expect(grants.details(first).clientId).toBe('synthetic');expect(() => new OAuthGrants(options).details(first)).toThrow('server restarted');- now = 600_001;+ clock.now = 600_001;expect(() => grants.details(first)).toThrow('expired');await expect(grants.begin('synthetic', params)).resolves.toBeString();});++test('a single client cannot hold more than ten pending requests, without starving other clients', async () => {+ const { grants, clock, params } = memoryGrants();+ const ids: string[] = [];+ for (let i = 0; i < 10; i++) ids.push(await grants.begin('noisy', params));+ await expect(grants.begin('noisy', params)).rejects.toThrow('Too many pending');+ await expect(grants.begin('noisy', params)).rejects.toThrow('this client');+ await expect(grants.begin('quiet', params)).resolves.toBeString();+ expect(grants.details(ids[0]).clientId).toBe('noisy');+ // Only requests still awaiting a decision count against the client's budget.+ await grants.decide(ids[0], false);+ await expect(grants.begin('noisy', params)).resolves.toBeString();+ await expect(grants.begin('noisy', params)).rejects.toThrow('Too many pending');+ clock.now = 600_001;+ await expect(grants.begin('noisy', params)).resolves.toBeString();+});diff --git a/test/oauth-dcr-scope-ceiling.test.ts b/test/oauth-dcr-scope-ceiling.test.tsnew file mode 100644index 0000000000..e76d0df386--- /dev/null+++ b/test/oauth-dcr-scope-ceiling.test.ts@@ -0,0 +1,247 @@+/**+ * DCR scope ceiling — anonymous Dynamic Client Registration (RFC 7591) may+ * register at most `read write`; a `client_credentials` registration (only+ * reachable under --enable-dcr-insecure, where no owner approval happens)+ * is capped at `read`. Privileged scopes are REJECTED with+ * invalid_client_metadata (HTTP 400), never silently dropped, so a client+ * that asked for more learns why and gets pointed at the operator path.+ *+ * Operator-trusted registration (`registerClientManual`, the CLI, the admin+ * API) is unaffected and still accepts every canonical scope.+ *+ * Setup mirrors test/oauth-dcr-ttl.test.ts (in-memory PGLite).+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGlite } from '@electric-sql/pglite';+import { vector } from '@electric-sql/pglite/vector';+import { pg_trgm } from '@electric-sql/pglite/contrib/pg_trgm';+import { InvalidClientMetadataError } from '@modelcontextprotocol/sdk/server/auth/errors.js';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';+import { DCR_REGISTRABLE_SCOPES, dcrScopeViolation } from '../src/core/scope.ts';+import { pgliteOAuthTransaction } from './helpers/oauth.ts';++let db: PGlite;+let sql: (strings: TemplateStringsArray, ...values: unknown[]) => Promise<any>;++beforeAll(async () => {+ db = new PGlite({ extensions: { vector, pg_trgm } });+ await db.exec(PGLITE_SCHEMA_SQL);+ sql = async (strings: TemplateStringsArray, ...values: unknown[]) => {+ const query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? `$${i + 1}` : ''), '');+ const result = await db.query(query, values as any[]);+ return result.rows;+ };+}, 30_000);++afterAll(async () => {+ if (db) await db.close();+}, 15_000);++function makeProvider(opts: { allowClientCredentialsDcr?: boolean } = {}) {+ return new GBrainOAuthProvider({+ transaction: pgliteOAuthTransaction(db), sql,+ tokenTtl: 60,+ ...opts,+ });+}++/** authorization_code public client — the shape a browser MCP connector sends. */+function authCodeMetadata(scope: string | undefined, extra: Record<string, unknown> = {}) {+ return {+ client_name: 'dcr-ceiling-test',+ redirect_uris: ['https://client.example/cb'],+ grant_types: ['authorization_code'],+ token_endpoint_auth_method: 'none',+ ...(scope === undefined ? {} : { scope }),+ ...extra,+ } as any;+}++/** client_credentials confidential client — only registrable under --enable-dcr-insecure. */+function machineMetadata(scope: string) {+ return {+ client_name: 'dcr-ceiling-m2m',+ redirect_uris: [],+ grant_types: ['client_credentials'],+ token_endpoint_auth_method: 'client_secret_post',+ scope,+ } as any;+}++// registerClient is typed `T | Promise<T>` by the SDK store interface.+async function expectRejected(pending: unknown, naming: RegExp): Promise<InvalidClientMetadataError> {+ try {+ await pending;+ } catch (e) {+ // The MCP SDK maps InvalidClientMetadataError to HTTP 400+ // invalid_client_metadata; a plain Error would surface as an opaque 500.+ expect(e).toBeInstanceOf(InvalidClientMetadataError);+ expect((e as Error).message).toMatch(naming);+ return e as InvalidClientMetadataError;+ }+ throw new Error('expected registration to be rejected');+}++describe('dcrScopeViolation (pure policy)', () => {+ test('ceiling constant is exactly read + write', () => {+ expect([...DCR_REGISTRABLE_SCOPES].sort()).toEqual(['read', 'write']);+ });++ test('read / write / empty under authorization_code → ok', () => {+ expect(dcrScopeViolation(['read'], ['authorization_code'])).toBeNull();+ expect(dcrScopeViolation(['read', 'write'], ['authorization_code'])).toBeNull();+ expect(dcrScopeViolation([], ['authorization_code'])).toBeNull();+ });++ test('unknown scopes are not the ceiling check\'s business (filter handles them)', () => {+ expect(dcrScopeViolation(['read', 'offline_access', 'openid'], ['authorization_code'])).toBeNull();+ });++ test('each privileged scope violates and is named', () => {+ for (const s of ['admin', 'sources_admin', 'users_admin']) {+ const v = dcrScopeViolation(['read', s], ['authorization_code']);+ expect(v).not.toBeNull();+ expect(v!).toContain(s);+ expect(v!).toMatch(/rescope-client|register-client/);+ }+ });++ test('agent keeps its specific operator-approved wording', () => {+ expect(dcrScopeViolation(['read', 'agent'], ['authorization_code'])).toMatch(/operator-approved/);+ });++ test('client_credentials ceiling is read only — write violates', () => {+ expect(dcrScopeViolation(['read'], ['client_credentials'])).toBeNull();+ const v = dcrScopeViolation(['read', 'write'], ['client_credentials']);+ expect(v).not.toBeNull();+ expect(v!).toContain('write');+ // Mixed grant lists take the stricter ceiling.+ expect(dcrScopeViolation(['write'], ['authorization_code', 'client_credentials'])).not.toBeNull();+ });+});++describe('registerClient (DCR) enforces the scope ceiling', () => {+ test.each([+ ['admin', /admin/],+ ['sources_admin', /sources_admin/],+ ['users_admin', /users_admin/],+ ['read admin', /admin/],+ ['write users_admin', /users_admin/],+ ])('scope "%s" → 400 invalid_client_metadata naming the scope', async (scope, naming) => {+ const provider = makeProvider();+ await expectRejected(provider.clientsStore.registerClient!(authCodeMetadata(scope)), naming);+ const rows = await sql`SELECT client_id FROM oauth_clients WHERE client_name = 'dcr-ceiling-test'`;+ expect(rows.length).toBe(0);+ });++ test('rejection names the operator remedy (register-client / rescope-client)', async () => {+ const provider = makeProvider();+ const err = await expectRejected(provider.clientsStore.registerClient!(authCodeMetadata('admin')), /admin/);+ expect(err.message).toMatch(/rescope-client/);+ expect(err.message).toMatch(/register-client|admin API/);+ });++ test('"read write" → stored verbatim', async () => {+ const provider = makeProvider();+ const info = await provider.clientsStore.registerClient!(authCodeMetadata('read write'));+ expect(info.scope).toBe('read write');+ const stored = await provider.clientsStore.getClient(info.client_id);+ expect(stored!.scope).toBe('read write');+ });++ test('"read offline_access" → "read" (unknown-scope filter unchanged)', async () => {+ const provider = makeProvider();+ const info = await provider.clientsStore.registerClient!(authCodeMetadata('read offline_access'));+ expect(info.scope).toBe('read');+ });++ test('scope omitted → "" (documented zero-scope shape; rescope later)', async () => {+ const provider = makeProvider();+ const info = await provider.clientsStore.registerClient!(authCodeMetadata(undefined));+ expect(info.scope ?? '').toBe('');+ const stored = await provider.clientsStore.getClient(info.client_id);+ expect(stored!.scope ?? '').toBe('');+ });++ test('grant_types omitted still defaults to authorization_code and gets the read write ceiling', async () => {+ const provider = makeProvider();+ const md = authCodeMetadata('read write');+ delete md.grant_types;+ const info = await provider.clientsStore.registerClient!(md);+ expect(info.scope).toBe('read write');+ const stored = await provider.clientsStore.getClient(info.client_id);+ expect(stored!.grant_types).toEqual(['authorization_code']);+ // and the privileged request is still rejected when grant_types is omitted+ const bad = authCodeMetadata('admin');+ delete bad.grant_types;+ await expectRejected(provider.clientsStore.registerClient!(bad), /admin/);+ });++ test('agent scope keeps the specific operator-approved wording', async () => {+ const provider = makeProvider();+ await expectRejected(provider.clientsStore.registerClient!(authCodeMetadata('read agent')), /operator-approved/);+ });+});++describe('registerClient (DCR) under --enable-dcr-insecure: client_credentials is read-only', () => {+ test('client_credentials + "read write" → rejected naming write', async () => {+ const provider = makeProvider({ allowClientCredentialsDcr: true });+ await expectRejected(provider.clientsStore.registerClient!(machineMetadata('read write')), /write/);+ });++ test('client_credentials + "read" → stored and usable', async () => {+ const provider = makeProvider({ allowClientCredentialsDcr: true });+ const info = await provider.clientsStore.registerClient!(machineMetadata('read'));+ expect(info.scope).toBe('read');+ const tokens = await provider.exchangeClientCredentials(info.client_id, info.client_secret!, 'read');+ expect(tokens.scope).toBe('read');+ });++ test('client_credentials + "admin" → rejected naming admin', async () => {+ const provider = makeProvider({ allowClientCredentialsDcr: true });+ await expectRejected(provider.clientsStore.registerClient!(machineMetadata('admin')), /admin/);+ });+});++describe('registerClient (DCR) WITHOUT --enable-dcr-insecure: the grant gate answers before the ceiling', () => {+ // A client_credentials request is not available at all here, so the reply+ // must say so — not "limited to read because issued without owner+ // approval", which implies the grant is on offer at a narrower scope.+ test('client_credentials + "read write" → the not-permitted message, never the machine ceiling', async () => {+ const provider = makeProvider();+ const before = (await sql`SELECT client_id FROM oauth_clients WHERE client_name = 'dcr-ceiling-m2m'`).length;+ const err = await expectRejected(+ provider.clientsStore.registerClient!(machineMetadata('read write')),+ /not permitted via dynamic client registration/,+ );+ expect(err.message).toMatch(/--enable-dcr-insecure/);+ expect(err.message).not.toMatch(/limited to/);+ const after = (await sql`SELECT client_id FROM oauth_clients WHERE client_name = 'dcr-ceiling-m2m'`).length;+ expect(after).toBe(before); // nothing stored+ });++ test('client_credentials + "read" (inside the machine ceiling) is still refused for the same reason', async () => {+ const provider = makeProvider();+ await expectRejected(+ provider.clientsStore.registerClient!(machineMetadata('read')),+ /not permitted via dynamic client registration/,+ );+ });+});++describe('operator-trusted registration is unaffected', () => {+ test('registerClientManual still accepts admin', async () => {+ const provider = makeProvider();+ const { clientId } = await provider.registerClientManual('operator-admin', ['client_credentials'], 'admin');+ const stored = await provider.clientsStore.getClient(clientId);+ expect(stored!.scope).toBe('admin');+ });++ test('registerClientManual still accepts client_credentials + read write', async () => {+ const provider = makeProvider();+ const { clientId } = await provider.registerClientManual('operator-m2m', ['client_credentials'], 'read write');+ const stored = await provider.clientsStore.getClient(clientId);+ expect(stored!.scope).toBe('read write');+ });+});diff --git a/test/pages-purge-artifact.test.ts b/test/pages-purge-artifact.test.tsnew file mode 100644index 0000000000..b7bccceb33--- /dev/null+++ b/test/pages-purge-artifact.test.ts@@ -0,0 +1,293 @@+/**+ * delete_page purge — the markdown artifact must be GONE before the row is.+ *+ * O4-2 (v0.50.2.0 security wave, review cycle 4): `purge: true` on a page+ * that was already soft-deleted used to skip file removal outright+ * (`{ removed: false, skipped: 'already_soft_deleted' }`) and hard-delete the+ * row. If the earlier soft-delete's unlink had FAILED (permissions, read-only+ * mount), the credential-bearing `.md` survived on disk and the next+ * `gbrain sync` re-imported it — a "purge" that resurrected the secret.+ *+ * Contract pinned here:+ * - the tombstone path resolves the page's recorded file from the+ * soft-deleted row itself and RETRIES the removal before dropping the row;+ * - `write_through` reports the real outcome (`removed: true` / `removed:+ * false, error` / `skipped: 'file_not_present'`), never a fabricated skip;+ * - a removal ERROR fails closed: `OperationError('storage_error')` naming+ * the path, the row stays (soft-deleted) so the operator can fix the+ * cause and re-run — a purge that leaves the file is not a purge. This+ * applies to the live-row purge too (the soft-delete lands, the+ * hard-delete does not).+ *+ * Two ways to make the artifact undeletable:+ * - `chmod 0555` on its directory (the realistic permissions case) — only+ * bites for a caller without CAP_DAC_OVERRIDE, so those tests probe once+ * at load and skip (with the reason in the name) for root / capability-+ * bearing sandboxes / Windows;+ * - a DIRECTORY sitting where the `.md` should be — `unlink(2)` on a+ * directory fails for every uid (EISDIR/EPERM), so the fail-closed path+ * is exercised unconditionally.+ */++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';++let engine: PGLiteEngine;+let tmpRoot: string;+let brainDir: string;+const delete_page = operations.find(o => o.name === 'delete_page')!;++/** Does `chmod 0555 <dir>` actually stop THIS process from unlinking inside it? */+function chmodBites(): boolean {+ if (process.platform === 'win32' || process.getuid?.() === 0) return false;+ const probe = mkdtempSync(join(tmpdir(), 'gbrain-chmod-probe-'));+ const dir = join(probe, 'd');+ const file = join(dir, 'f');+ try {+ mkdirSync(dir);+ writeFileSync(file, 'x');+ chmodSync(dir, 0o555);+ try { unlinkSync(file); return false; } catch { return true; }+ } finally {+ try { chmodSync(dir, 0o755); } catch { /* best-effort */ }+ rmSync(probe, { recursive: true, force: true });+ }+}+const CHMOD_BITES = chmodBites();+const chmodTest = CHMOD_BITES ? test : test.skip;+const CHMOD_NOTE = CHMOD_BITES ? '' : ' [skipped: chmod does not bite for this uid/capabilities/platform]';++const SLUG = 'secrets/leaked-key';+const REL_PATH = 'secrets/leaked-key.md';+const CONTENT = '---\ntitle: Leaked key\ntype: note\n---\n\n# Body\n\nAKIA-EXAMPLE-NOT-REAL\n';++function localCtx(): OperationContext {+ return {+ engine: engine as any,+ config: {} as any,+ logger: { info() {}, warn() {}, error() {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ } as OperationContext;+}++async function seedPageWithFile(rel = REL_PATH): Promise<string> {+ await importFromContent(engine, SLUG, CONTENT, { noEmbed: true, sourceId: 'default', sourcePath: rel });+ const filePath = join(brainDir, rel);+ mkdirSync(join(brainDir, rel.split('/')[0]), { recursive: true });+ writeFileSync(filePath, CONTENT);+ return filePath;+}++/** Make the artifact path undeletable for ANY uid: a non-empty directory where the file was. */+function replaceFileWithDirectory(filePath: string): void {+ rmSync(filePath);+ mkdirSync(filePath);+ writeFileSync(join(filePath, 'keep'), '');+}+/** Undo replaceFileWithDirectory: put the markdown file back. */+function restoreFile(filePath: string): void {+ rmSync(filePath, { recursive: true, force: true });+ writeFileSync(filePath, CONTENT);+}++async function rowState(): Promise<'absent' | 'live' | 'tombstone'> {+ const rows = await engine.executeRaw<{ deleted_at: string | null }>(+ `SELECT deleted_at FROM pages WHERE source_id = 'default' AND slug = $1`, [SLUG],+ );+ if (rows.length === 0) return 'absent';+ return rows[0].deleted_at === null ? 'live' : 'tombstone';+}++async function softDelete(): Promise<Record<string, any>> {+ return await delete_page.handler(localCtx(), { slug: SLUG }) as Record<string, any>;+}+async function purge(): Promise<Record<string, any>> {+ return await delete_page.handler(localCtx(), { slug: SLUG, purge: true }) as Record<string, any>;+}+async function purgeError(): Promise<OperationError> {+ try {+ await purge();+ } catch (e) {+ expect(e).toBeInstanceOf(OperationError);+ return e as OperationError;+ }+ throw new Error('expected purge to throw storage_error while the file could not be removed');+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ if (engine) await engine.disconnect();+}, 60_000);++beforeEach(async () => {+ await resetPgliteState(engine);+ _resetWriteThroughCacheForTest();+ tmpRoot = mkdtempSync(join(tmpdir(), 'gbrain-purge-artifact-'));+ brainDir = join(tmpRoot, 'brain');+ mkdirSync(brainDir, { recursive: true });+ await engine.setConfig('sync.repo_path', brainDir);+});++afterEach(() => {+ // Restore the write bit first so the temp tree can actually be removed.+ try { chmodSync(join(brainDir, 'secrets'), 0o755); } catch { /* may not exist */ }+ rmSync(tmpRoot, { recursive: true, force: true });+});++describe('delete_page purge — artifact retry on the tombstone path', () => {+ test('soft-delete whose unlink FAILED (undeletable artifact), then purge: storage_error naming the path, row + file stay; once removable → purged, removed: true, file gone', async () => {+ const filePath = await seedPageWithFile();+ replaceFileWithDirectory(filePath);++ // The earlier soft-delete is best-effort: the row tombstones, the unlink+ // fails, the artifact survives — the setup the resurrection needs.+ const soft = await softDelete();+ expect(soft.status).toBe('soft_deleted');+ expect(soft.write_through.removed).toBe(false);+ expect(typeof soft.write_through.error).toBe('string');+ expect(existsSync(filePath)).toBe(true);+ expect(await rowState()).toBe('tombstone');++ // Purge while the artifact still cannot be removed: fail closed. The row+ // is NOT dropped — dropping it would orphan the file for sync to re-import.+ const err = await purgeError();+ expect(err.code).toBe('storage_error');+ expect(err.message).toContain(filePath);+ expect(String(err.suggestion)).toContain('--purge');+ expect(await rowState()).toBe('tombstone');+ expect(existsSync(filePath)).toBe(true);++ // Operator fixes the cause and re-runs: the retry removes the real+ // artifact and only then does the hard-delete land.+ restoreFile(filePath);+ const res = await purge();+ expect(res.status).toBe('purged');+ expect(res.write_through).toMatchObject({ removed: true, path: filePath });+ expect(res.write_through).not.toHaveProperty('skipped');+ expect(existsSync(filePath)).toBe(false);+ expect(await rowState()).toBe('absent');+ expect(String(res.residuals)).toContain('git history');+ });++ chmodTest(`permissions case: soft-delete under a read-only directory, purge → storage_error until chmod is fixed${CHMOD_NOTE}`, async () => {+ const filePath = await seedPageWithFile();+ chmodSync(join(brainDir, 'secrets'), 0o555);++ const soft = await softDelete();+ expect(soft.status).toBe('soft_deleted');+ expect(soft.write_through.removed).toBe(false);+ expect(String(soft.write_through.error)).toMatch(/EACCES|EPERM/);+ expect(existsSync(filePath)).toBe(true);++ const err = await purgeError();+ expect(err.code).toBe('storage_error');+ expect(err.message).toContain(filePath);+ expect(await rowState()).toBe('tombstone');+ expect(existsSync(filePath)).toBe(true);++ chmodSync(join(brainDir, 'secrets'), 0o755);+ const res = await purge();+ expect(res.status).toBe('purged');+ expect(res.write_through).toMatchObject({ removed: true, path: filePath });+ expect(existsSync(filePath)).toBe(false);+ expect(await rowState()).toBe('absent');+ });++ test('tombstone whose file is STILL on disk (unlink never ran): purge removes the file, reports removed: true, never a fabricated skip', async () => {+ const filePath = await seedPageWithFile();+ // Soft-delete at the engine layer — no write-through ran, so the artifact+ // is exactly what a failed/absent unlink leaves behind.+ expect(await engine.softDeletePage(SLUG, { sourceId: 'default' })).not.toBeNull();+ expect(existsSync(filePath)).toBe(true);++ const res = await purge();+ expect(res.status).toBe('purged');+ expect(res.write_through).toMatchObject({ removed: true, path: filePath });+ expect(res.write_through.skipped).toBeUndefined();+ expect(existsSync(filePath)).toBe(false);+ expect(await rowState()).toBe('absent');+ });++ test('tombstone whose file is already gone: purge reports the real no-op (skipped: file_not_present) and drops the row', async () => {+ const filePath = await seedPageWithFile();+ rmSync(filePath);+ expect(await engine.softDeletePage(SLUG, { sourceId: 'default' })).not.toBeNull();++ const res = await purge();+ expect(res.status).toBe('purged');+ expect(res.write_through).toEqual({ removed: false, path: filePath, skipped: 'file_not_present' });+ expect(await rowState()).toBe('absent');+ });++ test('the tombstone retry resolves the RECORDED source_path, not a slug-derived twin', async () => {+ // Human-authored vault layout: the on-disk name is not the slug.+ const filePath = await seedPageWithFile('Secrets/Leaked Key.md');+ expect(await engine.softDeletePage(SLUG, { sourceId: 'default' })).not.toBeNull();++ const res = await purge();+ expect(res.status).toBe('purged');+ expect(res.write_through).toMatchObject({ removed: true, path: filePath });+ expect(existsSync(filePath)).toBe(false);+ expect(existsSync(join(brainDir, `${SLUG}.md`))).toBe(false);+ expect(await rowState()).toBe('absent');+ });+});++describe('delete_page purge — live-row path fails closed too', () => {+ test('live row whose artifact cannot be removed: storage_error, the row is soft-deleted (not dropped); once removable → second purge completes', async () => {+ const filePath = await seedPageWithFile();+ replaceFileWithDirectory(filePath);++ const err = await purgeError();+ expect(err.code).toBe('storage_error');+ expect(err.message).toContain(filePath);+ // The soft-delete landed (hidden from reads, recoverable), the hard+ // primitive did not run — a re-run resumes on the tombstone path.+ expect(await rowState()).toBe('tombstone');+ expect(existsSync(filePath)).toBe(true);++ restoreFile(filePath);+ const res = await purge();+ expect(res.status).toBe('purged');+ expect(res.write_through).toMatchObject({ removed: true, path: filePath });+ expect(existsSync(filePath)).toBe(false);+ expect(await rowState()).toBe('absent');+ });++ chmodTest(`permissions case: live-row purge under a read-only directory → storage_error, tombstone kept${CHMOD_NOTE}`, async () => {+ const filePath = await seedPageWithFile();+ chmodSync(join(brainDir, 'secrets'), 0o555);+ const err = await purgeError();+ expect(err.code).toBe('storage_error');+ expect(await rowState()).toBe('tombstone');+ expect(existsSync(filePath)).toBe(true);+ chmodSync(join(brainDir, 'secrets'), 0o755);+ expect((await purge()).status).toBe('purged');+ expect(existsSync(filePath)).toBe(false);+ });++ test('a plain (non-purge) soft-delete stays best-effort: an unlink failure is reported, never thrown', async () => {+ const filePath = await seedPageWithFile();+ replaceFileWithDirectory(filePath);+ const res = await softDelete();+ expect(res.status).toBe('soft_deleted');+ expect(res.write_through.removed).toBe(false);+ expect(typeof res.write_through.error).toBe('string');+ expect(existsSync(filePath)).toBe(true);+ expect(await rowState()).toBe('tombstone');+ });+});diff --git a/test/pages-source-scoping-4329.test.ts b/test/pages-source-scoping-4329.test.tsindex 0feac044da..83cae3206d 100644--- a/test/pages-source-scoping-4329.test.ts+++ b/test/pages-source-scoping-4329.test.ts@@ -199,6 +199,119 @@ describe('#4329 — delete_page source_id', () => {});});+describe('delete_page purge — immediate removal for the trusted local CLI only', () => {+ test('contract: purge is a boolean param (so the generated CLI accepts `gbrain delete <slug> --purge`)', () => {+ expect(delete_page.params.purge?.type).toBe('boolean');+ });++ test('trusted local purge: soft-delete then hard-delete of the targeted row only; status purged', async () => {+ const res = await delete_page.handler(ctxOf({ remote: false }), { slug: 'shared/doc', source_id: 'beta', purge: true }) as Record<string, unknown>;+ expect(res.status).toBe('purged');+ expect(res.source_id).toBe('beta');+ expect(res).not.toHaveProperty('recoverable_until');+ // Shape pin: the live-row purge carries the artifact-removal outcome, same+ // as a plain soft-delete (removed + path, or a skipped reason).+ expect(typeof (res.write_through as { removed?: unknown }).removed).toBe('boolean');+ const rows = await deletedAtBySource('shared/doc');+ expect(rows.beta).toBeUndefined(); // row is GONE, not tombstoned+ expect(rows.default).toBeNull(); // the other source's copy is untouched+ expect(await engine.getPage('shared/doc', { sourceId: 'beta', includeDeleted: true })).toBeNull();+ expect((await engine.getRawData('shared/doc', undefined, { sourceId: 'beta', includeDeleted: true })).length).toBe(0);+ });++ test('purge completes the removal of a row that was already soft-deleted (the remediation path)', async () => {+ await engine.softDeletePage('shared/doc', { sourceId: 'default' });+ const res = await delete_page.handler(ctxOf({ remote: false }), { slug: 'shared/doc', purge: true }) as Record<string, unknown>;+ expect(res.status).toBe('purged');+ // Shape pin: ONE response shape for status purged — the remediation path+ // RETRIES the artifact removal against the tombstone's recorded path and+ // reports the real outcome (here: no repo is configured, so nothing to+ // unlink) instead of a fabricated 'already_soft_deleted' skip. The+ // retry itself is pinned by test/pages-purge-artifact.test.ts.+ expect(res.write_through).toEqual({ removed: false, skipped: 'no_repo_configured' });+ expect((await deletedAtBySource('shared/doc')).default).toBeUndefined();+ // Unknown slug is still a clean not-found, even with purge.+ await expect(delete_page.handler(ctxOf({ remote: false }), { slug: 'shared/doc', purge: true }))+ .rejects.toMatchObject({ code: 'page_not_found' });+ });++ test('remote callers (anything not strictly remote === false) get permission_denied and nothing is deleted', async () => {+ // Local-only lane convention (connectors_status, get_recent_transcripts):+ // a well-formed request the caller is not allowed to make is+ // permission_denied, not invalid_params (that code is for shape errors).+ await expect(delete_page.handler(ctxOf(), { slug: 'shared/doc', purge: true }))+ .rejects.toMatchObject({ code: 'permission_denied', suggestion: expect.stringContaining('gbrain delete <slug> --purge') });+ await expect(delete_page.handler(ctxOf({ remote: undefined as unknown as boolean }), { slug: 'shared/doc', purge: true }))+ .rejects.toMatchObject({ code: 'permission_denied' });+ const authed = ctxOf({ auth: authOf({ sourceId: 'default', allowedSources: ['default'], scopes: ['read', 'write', 'admin'] }) as any });+ await expect(delete_page.handler(authed, { slug: 'shared/doc', purge: true }))+ .rejects.toMatchObject({ code: 'permission_denied' });+ const rows = await deletedAtBySource('shared/doc');+ expect(rows.default).toBeNull(); // not even soft-deleted+ expect(rows.beta).toBeNull();+ // ...and the same remote caller can still soft-delete without purge.+ const res = await delete_page.handler(ctxOf(), { slug: 'shared/doc' }) as Record<string, unknown>;+ expect(res.status).toBe('soft_deleted');+ });++ test('a non-boolean purge value is rejected, never coerced (shape error stays invalid_params)', async () => {+ await expect(delete_page.handler(ctxOf({ remote: false }), { slug: 'shared/doc', purge: 'yes' }))+ .rejects.toMatchObject({ code: 'invalid_params' });+ // A remote caller with a malformed purge is a shape error first.+ await expect(delete_page.handler(ctxOf(), { slug: 'shared/doc', purge: 'yes' }))+ .rejects.toMatchObject({ code: 'invalid_params' });+ expect((await deletedAtBySource('shared/doc')).default).toBeNull();+ });++ test('purge: false behaves as a plain soft delete, and the hint names the purge path', async () => {+ const res = await delete_page.handler(ctxOf({ remote: false }), { slug: 'shared/doc', purge: false }) as Record<string, unknown>;+ expect(res.status).toBe('soft_deleted');+ expect(String(res.recoverable_until)).toContain('gbrain delete <slug> --purge');+ expect((await deletedAtBySource('shared/doc')).default).not.toBeNull();+ });++ test('dry-run purge previews the hard removal without touching the row', async () => {+ const res = await delete_page.handler(ctxOf({ remote: false, dryRun: true }), { slug: 'shared/doc', purge: true }) as Record<string, unknown>;+ expect(res.dry_run).toBe(true);+ expect(res.action).toBe('purge_page');+ expect((await deletedAtBySource('shared/doc')).default).toBeNull();+ });+});++// get_raw_data follows the page's soft-delete (op-level pin of the engine+// rule): a tombstoned page's raw rows read as [] — exactly like a missing+// page — and restore_page brings them back. Remote callers get no+// include_deleted knob on this op; get_page include_deleted verifies the+// tombstone instead.+describe('get_raw_data follows the page soft-delete', () => {+ const get_raw_data = operations.find(o => o.name === 'get_raw_data')!;++ test('contract: no remote-facing include_deleted param; description states the soft-delete rule', () => {+ expect(get_raw_data.params.include_deleted).toBeUndefined();+ expect(get_raw_data.description).toMatch(/soft-delete/);+ expect(get_raw_data.description).toMatch(/restore_page/);+ });++ test('[] after softDeletePage, rows again after restorePage (trusted local and remote alike)', async () => {+ await engine.putRawData('shared/doc', 'crustdata', { k: 'v' }, { sourceId: 'default' });+ const read = (ctx: OperationContext) => get_raw_data.handler(ctx, { slug: 'shared/doc' }) as Promise<unknown[]>;+ expect((await read(ctxOf({ remote: false }))).length).toBe(1);+ expect((await read(ctxOf())).length).toBe(1);++ expect(await engine.softDeletePage('shared/doc', { sourceId: 'default' })).not.toBeNull();+ expect(await read(ctxOf({ remote: false }))).toEqual([]);+ expect(await read(ctxOf())).toEqual([]);+ // The tombstone is verifiable through get_page include_deleted.+ const tomb = await get_page.handler(ctxOf({ remote: false }), { slug: 'shared/doc', include_deleted: true }) as Record<string, unknown>;+ expect(tomb.deleted_at).not.toBeNull();++ const res = await restore_page.handler(ctxOf({ remote: false }), { slug: 'shared/doc' }) as Record<string, unknown>;+ expect(res.status).toBe('restored');+ expect((await read(ctxOf({ remote: false }))).length).toBe(1);+ expect((await read(ctxOf())).length).toBe(1);+ });+});+describe('#4329 — restore_page source_id', () => {beforeEach(async () => {await engine.softDeletePage('shared/doc', { sourceId: 'default' });@@ -342,3 +455,41 @@ describe('#3070 — sole_non_default emptiness guard (real engine, both ways)',});});});++// purge's reason to exist is "a page must not linger (e.g. it captured a+// credential)" — so the dependents that carry the page's bytes (raw_data,+// chunks, tags) must go with the row, and only for the targeted source.+describe('delete_page purge — cascades through the row\'s dependents, leaves the other source alone', () => {+ test('raw_data / tags / chunks of the purged row are gone; the same slug in another source keeps its rows', async () => {+ for (const sourceId of ['default', 'beta']) {+ await engine.putRawData('shared/doc', 'transcript:claude-code', { note: `${sourceId} meta` }, { sourceId });+ await engine.addTag('shared/doc', `tag-${sourceId}`, { sourceId });+ await engine.upsertChunks('shared/doc', [+ { chunk_index: 0, chunk_text: `${sourceId} chunk`, chunk_source: 'compiled_truth' },+ ], { sourceId });+ }+ const ids = await engine.executeRaw<{ id: number; source_id: string }>(+ `SELECT id, source_id FROM pages WHERE slug = 'shared/doc'`,+ );+ const idOf = Object.fromEntries(ids.map(r => [r.source_id, r.id])) as Record<string, number>;+ const dependents = async (pageId: number) => {+ const count = async (table: string) => {+ const [row] = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM ${table} WHERE page_id = $1`, [pageId],+ );+ return row.n;+ };+ return { raw: await count('raw_data'), tags: await count('tags'), chunks: await count('content_chunks') };+ };+ expect(await dependents(idOf.default)).toEqual({ raw: 1, tags: 1, chunks: 1 });+ expect(await dependents(idOf.beta)).toEqual({ raw: 1, tags: 1, chunks: 1 });++ const res = await delete_page.handler(ctxOf({ remote: false }), { slug: 'shared/doc', purge: true }) as Record<string, unknown>;+ expect(res.status).toBe('purged');+ expect(res.source_id).toBe('default');+ expect(await dependents(idOf.default)).toEqual({ raw: 0, tags: 0, chunks: 0 });+ expect(await dependents(idOf.beta)).toEqual({ raw: 1, tags: 1, chunks: 1 });+ expect((await engine.getRawData('shared/doc', undefined, { sourceId: 'beta' })).length).toBe(1);+ expect((await deletedAtBySource('shared/doc')).beta).toBeNull(); // beta copy alive, not even tombstoned+ });+});diff --git a/test/scope.test.ts b/test/scope.test.tsindex bff7a8975f..28aa47f1e9 100644--- a/test/scope.test.ts+++ b/test/scope.test.ts@@ -4,6 +4,9 @@ import {isScope,ALLOWED_SCOPES,ALLOWED_SCOPES_LIST,+ DCR_REGISTRABLE_SCOPES,+ dcrScopeViolation,+ scopesSupportedForDiscovery,assertAllowedScopes,filterAllowedScopes,InvalidScopeError,@@ -225,3 +228,33 @@ describe('parseScopeString', () => {expect(parseScopeString('read flying-unicorn')).toEqual(['read', 'flying-unicorn']);});});++// ---------------------------------------------------------------------------+// scopesSupportedForDiscovery — what `scopes_supported` advertises+// ---------------------------------------------------------------------------+describe('scopesSupportedForDiscovery', () => {+ test('DCR on: exactly the self-registration ceiling, in ALLOWED_SCOPES_LIST order', () => {+ expect(scopesSupportedForDiscovery({ enableDcr: true })).toEqual(['read', 'write']);+ });+ test('DCR off: every scope except operator-only agent (the pre-ceiling advertisement)', () => {+ const list = scopesSupportedForDiscovery({ enableDcr: false });+ expect(list).toEqual(['admin', 'read', 'sources_admin', 'users_admin', 'write']);+ expect(list).toEqual(ALLOWED_SCOPES_LIST.filter((s) => s !== 'agent'));+ });+ test('neither list advertises agent (delegation bindings are operator-only)', () => {+ expect(scopesSupportedForDiscovery({ enableDcr: true })).not.toContain('agent');+ expect(scopesSupportedForDiscovery({ enableDcr: false })).not.toContain('agent');+ });+ test('DCR-on list is a subset of DCR_REGISTRABLE_SCOPES and every member passes the DCR ceiling', () => {+ const advertised = scopesSupportedForDiscovery({ enableDcr: true });+ expect(advertised.length).toBeGreaterThan(0);+ for (const s of advertised) expect(DCR_REGISTRABLE_SCOPES.has(s)).toBe(true);+ // A client that copies discovery into its /register request is accepted...+ expect(dcrScopeViolation(advertised, ['authorization_code', 'refresh_token'])).toBeNull();+ // ...and so is each advertised scope on its own.+ for (const s of advertised) expect(dcrScopeViolation([s], ['authorization_code'])).toBeNull();+ });+ test('the DCR-off list would trip the ceiling — which is why DCR-on discovery must narrow', () => {+ expect(dcrScopeViolation(scopesSupportedForDiscovery({ enableDcr: false }), ['authorization_code'])).not.toBeNull();+ });+});diff --git a/test/secret-scan-format-detectors-extra.test.ts b/test/secret-scan-format-detectors-extra.test.tsnew file mode 100644index 0000000000..1baf026a4c--- /dev/null+++ b/test/secret-scan-format-detectors-extra.test.ts@@ -0,0 +1,102 @@+/**+ * Format-based detector edges not pinned by test/secret-scan.test.ts: the+ * remaining connection-string schemes, the AKIA arm's new hard right edge,+ * and the bearer catch-all's length floor + left boundary. Every value is+ * synthetic and runtime-joined from >= 2 fragments; constant names keep+ * scanner keywords away from the `=`.+ */+import { describe, expect, test } from 'bun:test';+import { redactFindings, scanText } from '../src/core/secret-scan.ts';++const USERINFO = ['dbuser', ':', 'p4ssw0rd', '@'].join('');+const AKIA_ID = ['AKIA', 'IOSFODNN7EXAMPLE'].join('');+const OPAQUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');++describe('db_url_credentials — every listed scheme', () => {+ for (const scheme of ['postgresql', 'mysql', 'mongodb', 'rediss', 'amqp', 'mssql']) {+ test(`${scheme}:// with inline credentials fires once and keeps the host`, () => {+ const url = `${scheme}://${USERINFO}host.internal/db`;+ expect(scanText(`url ${url}`).map((f) => f.pattern)).toEqual(['db_url_credentials']);+ const { text } = redactFindings(url);+ expect(text).toBe('<REDACTED:db_url_credentials>host.internal/db');+ expect(text.includes('p4ssw0rd')).toBe(false);+ });+ }++ test('a database URL with an EMPTY password (user, trailing colon) does not fire', () => {+ expect(scanText('postgres://dbuser:@host.internal/db')).toEqual([]);+ });++ // Real copy-pasted passwords carry base64 `/`, braces, angle brackets,+ // pipes, carets, backticks and backslashes UNESCAPED. An earlier cut of the+ // password class excluded those on RFC 3986 grounds and every such password+ // sailed through unredacted (0 findings on all of these). The only+ // exclusions the class keeps are whitespace, `@`, `"` and `'` — the string+ // delimiters that end a credential-less URL inside minified JSON before an+ // unrelated `@` (pinned in secret-scan-perf (i-b)).+ const UNESCAPED_PW_CASES: Array<[string, string, string, string]> = [+ ['base64 slash', 'postgres://', 'admin', 'aB3dEf/GhIjKlmno12'],+ ['braces', 'postgres://', 'svc', 'p{assw0rd}Zx9'],+ ['angle brackets', 'redis://', 'user', 'tok<en>Val0ue99'],+ ['pipe caret backtick backslash', 'mysql://', 'svc', 'a|b^c`d\\e0F9'],+ ];+ for (const [label, scheme, user, pw] of UNESCAPED_PW_CASES) {+ test(`an unescaped ${label} password is still a credential: value ends at @, host survives`, () => {+ const creds = [scheme, user, ':', pw, '@'].join('');+ const url = creds + 'db.internal:5432/app';+ expect(scanText(`u ${url}`).map((f) => f.pattern)).toEqual(['db_url_credentials']);+ const { text } = redactFindings(`u ${url}`);+ expect(text).toBe('u <REDACTED:db_url_credentials>db.internal:5432/app');+ expect(text.includes(pw)).toBe(false);+ });+ }+});++describe('aws_access_key — AKIA keeps firing, now with a hard right edge', () => {+ test('bare AKIA id fires', () => {+ expect(scanText(`aws ${AKIA_ID}`).map((f) => f.pattern)).toEqual(['aws_access_key']);+ });++ test('AKIA followed by more alphanumerics is an identifier, not a key id', () => {+ expect(scanText(`${AKIA_ID}XYZ`)).toEqual([]);+ expect(scanText(`${AKIA_ID}1`)).toEqual([]);+ });+});++describe('bearer catch-all — floor and left boundary', () => {+ test('a token under 20 chars does not reach the bearer floor', () => {+ expect(scanText('Authorization: Bearer abcdef1234')).toEqual([]);+ });++ test('the keyword needs a non-word left boundary; punctuation counts as one', () => {+ expect(scanText(`xBearer ${OPAQUE}`)).toEqual([]);+ expect(scanText(`(Bearer ${OPAQUE})`).map((f) => f.pattern)).toEqual(['bearer']);+ });++ test('the redaction keeps the header keyword and drops only the token', () => {+ const { text } = redactFindings(`(Bearer ${OPAQUE})`);+ expect(text).toBe('(Bearer <REDACTED:bearer>)');+ });++ // RFC 7235 auth-scheme names are case-insensitive; an all-caps header used+ // to miss BOTH the regex (`[Bb]earer`) and the `earer` precheck, so the+ // line was never even scanned by the catch-all.+ test('an all-caps BEARER scheme fires as bearer and keeps the keyword', () => {+ const line = `Authorization: BEARER ${OPAQUE}`;+ expect(scanText(line).map((f) => f.pattern)).toEqual(['bearer']);+ expect(redactFindings(line).text).toBe('Authorization: BEARER <REDACTED:bearer>');+ });++ test('a token claimed behind an all-caps BEARER header is echo-redacted where it recurs bare', () => {+ // The echo pass keys on the claimed VALUE, not the keyword spelling, so a+ // token anchored by any accepted spelling is scrubbed at its bare echoes.+ const { text, redactions } = redactFindings(`Authorization: BEARER ${OPAQUE}\nretrying with ${OPAQUE}`);+ expect(redactions.length).toBe(1);+ expect(text).toBe('Authorization: BEARER <REDACTED:bearer>\nretrying with <REDACTED:bearer>');+ });++ test('BEARER <vendor key> still keeps the vendor attribution', () => {+ const anthropicShape = ['sk-ant-', 'api03-Zz9Yy8Xx7Ww6Vv5Uu4Tt3'].join('');+ expect(scanText(`BEARER ${anthropicShape}`).map((f) => f.pattern)).toEqual(['anthropic']);+ });+});diff --git a/test/secret-scan-perf.test.ts b/test/secret-scan-perf.test.tsnew file mode 100644index 0000000000..353237329c--- /dev/null+++ b/test/secret-scan-perf.test.ts@@ -0,0 +1,416 @@+/**+ * secret-scan performance regressions. The per-line scanner runs+ * SYNCHRONOUSLY over untrusted content (transcript ingest, `sources push`+ * blobs up to 25 MB, compiled context), so a pattern that is quadratic on a+ * long line is a denial-of-service lever, not a slow path. Pre-fix timings+ * for the inputs below were seconds (8000 credential-less redis URLs on one+ * JSON line: ~4 s; 160k chars of repeated `redis://:`: ~5.6 s; 5000 Bearer+ * tokens on one line: ~2.6 s vs 41 ms one-per-line; 200 KB of `-eyJ`: ~25 s;+ * 210 KB of `-apikey`: ~42 s; 2000 PEM headers without END ahead of a 1 MB+ * tail: ~3.8 s; 20000 PEM headers on ONE line ahead of an 8 MB newline-free+ * tail: ~8 s (~30 s at 23 MB); redacting a 1 MB transcript with ~5k unique+ * values: ~3 s; the echo pass as ONE escaped-alternation RegExp over 64+ * claimed 4 KB bearer values sharing a 4000-char prefix ahead of a 1 MB tail+ * of the prefix character: ~24 s). The thresholds sit 2-50x above the fixed+ * timings and 10-1000x below the broken ones, so they bind on a regression+ * without flaking on a loaded CI box.+ *+ * Every credential-shaped value is synthetic and runtime-joined from >= 2+ * fragments; constant names keep scanner keywords away from the `=`.+ */+import { describe, expect, test } from 'bun:test';+import { createHash } from 'crypto';+import { ECHO_MAX_UNIQUE, ECHO_MAX_VALUE_CHARS, redactFindings, scanText } from '../src/core/secret-scan.ts';++function elapsedMs(fn: () => void): number {+ const t0 = performance.now();+ fn();+ return performance.now() - t0;+}++const OPAQUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');+const USERINFO = ['alice-example', ':', 's3cr3t', '@'].join('');+const PG_URL_CREDS = ['postgres://', USERINFO].join('');+const PG_URL = PG_URL_CREDS + 'db.example.com:5432/app';++/** One minified JSON line of credential-less redis URLs (~248k chars). */+function redisJsonLine(extraElement = ''): string {+ const items = Array.from({ length: 8000 }, (_, i) => `{"u":"redis://localhost:${6379 + (i % 7)}"}`);+ if (extraElement) items.push(extraElement);+ return `[${items.join(',')}]`;+}++describe('db_url_credentials is linear on long lines', () => {+ test('(i) 8000 credential-less redis URLs on one JSON line: 0 findings, < 200ms', () => {+ const line = redisJsonLine();+ expect(line.length).toBeGreaterThan(160_000);+ let findings: unknown[] = [];+ const ms = elapsedMs(() => { findings = scanText(line); });+ expect(findings).toEqual([]);+ expect(ms).toBeLessThan(200);+ });++ test('(i-b) the same line WITH an @ elsewhere (the cheap precheck passes): still 0 findings, < 200ms', () => {+ // An email address means the `@` precheck cannot skip the pattern — this+ // pins the bounded quantifiers on their own, not the precheck. It also+ // pins the FALSE POSITIVE the unbounded form had: the run from the last+ // URL's port through `"},{"owner":"ops` to the email's `@` was one bogus+ // db_url_credentials finding, because string delimiters were legal+ // password characters. Second element: the same shape through the+ // USER segment (`cache"},{"contact":"ops` + `:oncall@`).+ const line = redisJsonLine('{"owner":"[email protected]"},{"u":"redis://cache"},{"contact":"ops:[email protected]"}');+ let findings: unknown[] = [];+ const ms = elapsedMs(() => { findings = scanText(line); });+ expect(findings).toEqual([]);+ expect(ms).toBeLessThan(200);+ });++ test('(ii) 160k chars of repeated `redis://:` (no @): < 200ms', () => {+ const line = 'redis://:'.repeat(17_778);+ expect(line.length).toBeGreaterThan(160_000);+ let findings: unknown[] = [];+ const ms = elapsedMs(() => { findings = scanText(line); });+ expect(findings).toEqual([]);+ expect(ms).toBeLessThan(200);+ });++ test('(ii-b) 160k chars of repeated `redis://:` followed by a single @: one bounded finding, < 200ms', () => {+ // `/` is a legal password character (base64 passwords are pasted+ // unescaped), so the ≤256 chars of `redis://:` runs ahead of the `@` read+ // as `user="" password="redis://:redis://:…"` — ONE credential-shaped+ // finding whose value ends at the `@`, not one per scheme occurrence and+ // not a run to the end of the line. The timing is the pin; the count+ // shows the bound is doing the work.+ const line = 'redis://:'.repeat(17_778) + '@';+ let findings: ReturnType<typeof scanText> = [];+ const ms = elapsedMs(() => { findings = scanText(line); });+ expect(findings.map((f) => f.pattern)).toEqual(['db_url_credentials']);+ expect(ms).toBeLessThan(200);+ });+});++describe('preview + corpus redaction are linear in hits on one line', () => {+ const bearerLine = Array.from({ length: 5000 }, () => `Bearer ${OPAQUE}`).join(' ');++ test('(iii) 5000 Bearer tokens on one 190k line: scanText < 1500ms, one finding per occurrence', () => {+ expect(bearerLine.length).toBeGreaterThan(160_000);+ let findings: ReturnType<typeof scanText> = [];+ const ms = elapsedMs(() => { findings = scanText(bearerLine); });+ expect(findings.length).toBe(5000);+ expect(findings.every((f) => f.pattern === 'bearer')).toBe(true);+ expect(JSON.stringify(findings).includes(OPAQUE)).toBe(false);+ expect(ms).toBeLessThan(1500);+ });++ test('(iii-b) redactFindings over the same line: < 1500ms, no raw token survives', () => {+ let result = { text: '', redactions: [] as ReturnType<typeof scanText> };+ const ms = elapsedMs(() => { result = redactFindings(bearerLine); });+ expect(result.redactions.length).toBe(5000);+ expect(result.text.includes(OPAQUE)).toBe(false);+ expect(result.text.startsWith('Bearer <REDACTED:bearer> Bearer <REDACTED:bearer>')).toBe(true);+ expect(ms).toBeLessThan(1500);+ });++ test('(iii-c) hit count scales linearly: 20000 tokens on one 760k line < 1500ms', () => {+ // The first-wins overlap check and the preview window used to walk every+ // prior span per hit (O(hits²)): 5000 hits 305 ms, 10000 1.4 s, 20000+ // 5.4 s. The overlap check is O(value) per hit now (claimed-char bitmap)+ // and the preview window O(log hits) (binary search over sorted spans).+ const line = Array.from({ length: 20_000 }, () => `Bearer ${OPAQUE}`).join(' ');+ let findings: ReturnType<typeof scanText> = [];+ const ms = elapsedMs(() => { findings = scanText(line); });+ expect(findings.length).toBe(20_000);+ expect(ms).toBeLessThan(1500);+ });+});++describe('the bounded connection-string pattern still fires on real credentials', () => {+ test('(iv) scheme://user:pass@host: value is exactly the credential span ending at @', () => {+ const findings = scanText(`DATABASE_URL=${PG_URL}`);+ expect(findings.map((f) => f.pattern)).toEqual(['db_url_credentials']);+ // The fingerprint is the sha256 of the span that ends at `@` — host/db+ // are not part of the value.+ const expected = createHash('sha256').update(PG_URL_CREDS).digest('hex').slice(0, 16);+ expect(findings[0]!.fingerprint).toBe(`sha256:${expected}`);+ const { text } = redactFindings(`DATABASE_URL=${PG_URL}`);+ expect(text).toBe('DATABASE_URL=<REDACTED:db_url_credentials>db.example.com:5432/app');+ });++ test('an empty user (redis-style `://:pw@`) still fires', () => {+ const url = ['redis://', ':', 'r3dis', '@cache.internal:6379'].join('');+ expect(scanText(url).map((f) => f.pattern)).toEqual(['db_url_credentials']);+ expect(redactFindings(url).text).toBe('<REDACTED:db_url_credentials>cache.internal:6379');+ });++ test('the password bound is exactly 256 chars (pinned so an edit is a visible edit)', () => {+ const pw256 = 'p4'.repeat(128);+ expect(pw256.length).toBe(256);+ const ok = ['mysql://', 'svc', ':', pw256, '@h/db'].join('');+ expect(scanText(ok).map((f) => f.pattern)).toEqual(['db_url_credentials']);+ // 257 is the accepted miss: a JWT that long is still claimed by `jwt`;+ // an opaque password that long is not a realistic wire shape.+ const over = ['mysql://', 'svc', ':', pw256 + 'x', '@h/db'].join('');+ expect(scanText(over)).toEqual([]);+ });++ test('the RFC 3986 sub-delims, a `:` and a %XX escape are still legal password characters', () => {+ // `'` is the one sub-delim deliberately NOT accepted: it is a string+ // delimiter in minified JS/YAML, the same false-positive shape as `"`.+ const pw = ['p%40ss', '!$&()*+,;=~-._:x'].join('');+ const url = ['mysql://', 'svc', ':', pw, '@h/db'].join('');+ const findings = scanText(`u ${url}`);+ expect(findings.map((f) => f.pattern)).toEqual(['db_url_credentials']);+ expect(redactFindings(url).text).toBe('<REDACTED:db_url_credentials>h/db');+ });++ test('the user bound is 128 chars; the user segment stops at `/`, the password does not', () => {+ const user128 = 'u'.repeat(128);+ expect(scanText(['amqp://', user128, ':', 'p4ss', '@h'].join('')).map((f) => f.pattern)).toEqual(['db_url_credentials']);+ expect(scanText(['amqp://', user128 + 'u', ':', 'p4ss', '@h'].join(''))).toEqual([]);+ // A `/` in the USER segment ends it (`scheme://host/path:x@y` is not a+ // credential); a `/` in the PASSWORD is legal — base64 passwords are+ // pasted unescaped all the time, and an earlier cut that excluded it let+ // every such password through (pinned positively in+ // secret-scan-format-detectors-extra).+ expect(scanText(['mssql://', 'sv/c', ':', 'p4ss', '@h'].join(''))).toEqual([]);+ expect(scanText(['mssql://', 'svc', ':', 'pa/th0', '@h'].join('')).map((f) => f.pattern)).toEqual(['db_url_credentials']);+ });+});++describe('jwt + high_entropy_assignment are linear on adversarial `-`/`_` runs', () => {+ // Both value classes contain `-` and `_`. When the LEFT BOUNDARY admits the+ // same characters, every `-`/`_` in the run is a fresh start whose value+ // consumes to end-of-line and backtracks — quadratic. jwt now excludes `-`+ // from its boundary and bounds each segment; the entropy rule bounds the+ // keyword's trailing identifier segments (`{0,64}`) and the value.+ test('200 KB of `-eyJ`: 0 findings, < 200ms (was ~25 s)', () => {+ const line = '-eyJ'.repeat(50_000);+ let findings: unknown[] = [];+ const ms = elapsedMs(() => { findings = scanText(line); });+ expect(findings).toEqual([]);+ expect(ms).toBeLessThan(200);+ });++ test('210 KB of `-apikey` with highEntropy: 0 findings, < 200ms (was ~42 s)', () => {+ const line = '-apikey'.repeat(30_000);+ let findings: unknown[] = [];+ const ms = elapsedMs(() => { findings = scanText(line, { highEntropy: true }); });+ expect(findings).toEqual([]);+ expect(ms).toBeLessThan(200);+ });++ test('180 KB of `_token` with highEntropy: 0 findings, < 200ms (was ~18 s)', () => {+ const line = '_token'.repeat(30_000);+ let findings: unknown[] = [];+ const ms = elapsedMs(() => { findings = scanText(line, { highEntropy: true }); });+ expect(findings).toEqual([]);+ expect(ms).toBeLessThan(200);+ });+});++describe('PEM_BLOCK_RE is linear in headers and text', () => {+ const MB_TAIL = 'x'.repeat(1024 * 1024);+ const PEM_BODY_LINE = ['MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSj', 'AgEAAoIBAQC7VJTUt9Us8cKj'].join('');+ // Header/footer joined from fragments so the committed source never carries a whole PEM block (gitleaks private-key rule).+ const PEM_KEY = [['-----BEGIN', ' RSA PRIVATE KEY', '-----'].join(''), PEM_BODY_LINE, ['-----END', ' RSA PRIVATE KEY', '-----'].join('')].join('\n');++ test('2000 header-only mentions ahead of a 1 MB tail: 2000 findings, < 300ms (was ~3.8 s)', () => {+ // The unbounded lazy body scanned from EVERY header to the end of the+ // text looking for an END that never comes. Bounded at+ // PEM_BODY_MAX_CHARS, each header does constant work.+ const text = Array.from({ length: 2000 }, () => 'leaked -----BEGIN RSA PRIVATE KEY----- here').join('\n') + '\n' + MB_TAIL;+ let findings: ReturnType<typeof scanText> = [];+ const ms = elapsedMs(() => { findings = scanText(text); });+ expect(findings.length).toBe(2000);+ expect(findings.every((f) => f.pattern === 'private_key_pem')).toBe(true);+ expect(ms).toBeLessThan(300);+ });++ test('2000 well-formed keys ahead of a 1 MB tail: 2000 findings with correct lines, < 300ms', () => {+ // The 1-based header line used to be recomputed per hit as+ // `text.slice(0, index).split('\n').length` — O(hits × text). It is a+ // running cursor now; the line numbers must still be exact.+ const text = Array.from({ length: 2000 }, () => PEM_KEY).join('\n') + '\n' + MB_TAIL;+ let findings: ReturnType<typeof scanText> = [];+ const ms = elapsedMs(() => { findings = scanText(text); });+ expect(findings.length).toBe(2000);+ expect(findings.map((f) => f.line)).toEqual(Array.from({ length: 2000 }, (_, k) => 3 * k + 1));+ expect(JSON.stringify(findings).includes(PEM_BODY_LINE)).toBe(false);+ expect(ms).toBeLessThan(300);+ });++ test('2000 well-formed keys AFTER a 1 MB preamble: exact lines, < 300ms (was ~1.1 s)', () => {+ // The shape that isolates the per-hit line recount: every hit sits+ // behind >= 1 MB of text, so O(hits × prefix) slicing is >= 2 GB of+ // characters, while the running cursor walks the preamble once.+ const preamble = Array.from({ length: 10_000 }, () => 'x'.repeat(104)).join('\n');+ expect(preamble.length).toBeGreaterThan(1024 * 1024);+ const text = preamble + '\n' + Array.from({ length: 2000 }, () => PEM_KEY).join('\n');+ let findings: ReturnType<typeof scanText> = [];+ const ms = elapsedMs(() => { findings = scanText(text); });+ expect(findings.length).toBe(2000);+ expect(findings.map((f) => f.line)).toEqual(Array.from({ length: 2000 }, (_, k) => 10_001 + 3 * k));+ expect(ms).toBeLessThan(300);+ });++ test('20000 header mentions on ONE line ahead of an 8 MB newline-free tail: 20000 findings on line 1, < 1500ms (was ~8 s)', () => {+ // The running cursor used to call `text.indexOf('\n', cursor)` once per+ // hit; with no `\n` anywhere after the cursor each call rescanned to the+ // end of the text and returned -1 — O(hits × text) through a different+ // door (~30 s with a 23 MB tail, inside SCAN_MAX_FILE_BYTES). The+ // next-newline position is carried as state now and a -1 is sticky, so+ // the newline search is O(text) total. What remains of the timing is the+ // bounded PEM body probe (20000 headers × PEM_BODY_MAX_CHARS) plus the+ // per-line patterns over the 8 MB line — the accepted constants.+ const header = ['-----BEGIN', ' RSA PRIVATE KEY', '-----'].join('');+ const text = Array.from({ length: 20_000 }, () => header + ' ').join('') + 'x'.repeat(8 << 20);+ let findings: ReturnType<typeof scanText> = [];+ const ms = elapsedMs(() => { findings = scanText(text); });+ expect(findings.length).toBe(20_000);+ expect(findings.every((f) => f.pattern === 'private_key_pem' && f.line === 1)).toBe(true);+ expect(ms).toBeLessThan(1500);+ });++ test('the carried newline position stays exact when hits and newlines interleave on and between lines', () => {+ const header = ['-----BEGIN', ' RSA PRIVATE KEY', '-----'].join('');+ const text = `a\n${header}\nb\nc\n${header} ${header}\n\n${header}`;+ expect(scanText(text).map((f) => f.line)).toEqual([2, 5, 5, 7]);+ });+});++describe(`the echo pass is at most ${ECHO_MAX_UNIQUE} substring sweeps over the text`, () => {+ // One `indexOf` sweep per dictionary value (the count is capped, the value+ // length is capped at ECHO_MAX_VALUE_CHARS), candidates spliced into the+ // unclaimed gaps. Never one replaceAll per unique value (5000 unique Bearer+ // tokens on one line stays under the 200 ms pin below with only the first+ // 64 in the dictionary) and never a single escaped-alternation RegExp,+ // which was O(text × Σ|values|) on prefix-sharing values (the last pin).+ const vals = Array.from({ length: ECHO_MAX_UNIQUE }, (_, k) => `${OPAQUE}${k.toString(36).padStart(4, 'z')}`);++ test('64 unique bearer claims ahead of an 8 MB tail with no echo: redact < 400ms', () => {+ const text = vals.map((v) => `Bearer ${v}`).join(' ') + '\n' + 'x'.repeat(8 << 20);+ let result = { text: '', redactions: [] as ReturnType<typeof scanText> };+ const ms = elapsedMs(() => { result = redactFindings(text); });+ expect(result.redactions.length).toBe(ECHO_MAX_UNIQUE);+ expect(result.text.includes(OPAQUE)).toBe(false);+ expect(ms).toBeLessThan(400);+ });++ test('the adversarial tail — 4 MB of bearer-class chars sharing the values\' prefix, so every 7th position is a candidate start for all 64 values: < 1500ms', () => {+ // Each sweep rejects a candidate position after the shared prefix; 64+ // sweeps over 4 MB. Linear in the text, bounded by the cap.+ const text = vals.map((v) => `Bearer ${v}`).join(' ') + '\n' + 'opaqueT'.repeat((4 << 20) / 7);+ let result = { text: '', redactions: [] as ReturnType<typeof scanText> };+ const ms = elapsedMs(() => { result = redactFindings(text); });+ expect(result.redactions.length).toBe(ECHO_MAX_UNIQUE);+ expect(result.text.includes(OPAQUE)).toBe(false);+ expect(ms).toBeLessThan(1500);+ });++ test(`the every-position adversary — ${ECHO_MAX_UNIQUE} claimed values of ${ECHO_MAX_VALUE_CHARS} chars sharing a 500-char prefix ahead of a 1 MB tail of the prefix character: < 300ms (the alternation form took ~24 s)`, () => {+ // The bearer class is `{20,}`, so an attacker-influenced page can plant+ // long prefix-sharing tokens. With the alternation, every position of the+ // tail was a candidate start that walked the shared prefix once per+ // alternative — O(text × Σ|values|). Per-value substring sweeps stay+ // linear here, and the value-length cap bounds each compare.+ const prefix = 'A'.repeat(500);+ const vals512 = Array.from({ length: ECHO_MAX_UNIQUE }, (_, k) => prefix + k.toString(36).padStart(ECHO_MAX_VALUE_CHARS - prefix.length, 'B'));+ expect(vals512.every((v) => v.length === ECHO_MAX_VALUE_CHARS)).toBe(true);+ const tail = 'A'.repeat(1 << 20);+ const text = vals512.map((v) => `Bearer ${v}`).join(' ') + '\n' + tail;+ let result!: ReturnType<typeof redactFindings>;+ const ms = elapsedMs(() => { result = redactFindings(text); });+ expect(result.redactions.length).toBe(ECHO_MAX_UNIQUE);+ expect(result.redactions.every((r) => r.pattern === 'bearer')).toBe(true);+ // Every value joined the dictionary (exactly at the length cap) and the+ // tail carries no echo, so it comes through intact.+ expect(result.echoValues.size).toBe(ECHO_MAX_UNIQUE);+ expect(result.text).toBe(Array.from({ length: ECHO_MAX_UNIQUE }, () => 'Bearer <REDACTED:bearer>').join(' ') + '\n' + tail);+ expect(ms).toBeLessThan(300);+ });++ test(`the repetitive-tail adversary — ${ECHO_MAX_UNIQUE} claimed values of 20..83 repeated \`A\`s, then a 2 MiB \`A\` tail: heap delta < 64 MiB, RSS delta < 96 MiB, < 1500ms, no run of 20 \`A\`s survives`, () => {+ // Retained memory must be independent of text size. Collecting every+ // non-overlapping occurrence of every value up front is O(text × Σ+ // 1/|value|) objects — ~3 M candidates here, ~230 MB of RSS for 64+ // findings (and redactSession runs BEFORE message truncation). The+ // streaming merge keeps O(values) state and emits as it goes.+ const vals = Array.from({ length: ECHO_MAX_UNIQUE }, (_, k) => 'A'.repeat(20 + k));+ const tail = 'A'.repeat(2 << 20);+ const text = vals.map((v) => `Bearer ${v}`).join('\n') + '\n' + tail;+ const gc = (globalThis as { Bun?: { gc?: (force: boolean) => void } }).Bun?.gc;+ gc?.(true);+ const before = process.memoryUsage();+ let result!: ReturnType<typeof redactFindings>;+ const ms = elapsedMs(() => { result = redactFindings(text); });+ const after = process.memoryUsage();+ expect(result.redactions.length).toBe(ECHO_MAX_UNIQUE);+ expect(/A{20}/.test(result.text)).toBe(false);+ // 2 MiB = 25266 × 83 + 74 and 74 is itself a claimed length, so the tail+ // is covered wall to wall by echo tokens.+ expect(result.text.split('\n').at(-1)!.replaceAll('<REDACTED:bearer>', '')).toBe('');+ expect((after.heapUsed - before.heapUsed) / (1 << 20)).toBeLessThan(64);+ expect((after.rss - before.rss) / (1 << 20)).toBeLessThan(96);+ expect(ms).toBeLessThan(1500);+ });+});++describe('redactFindings is linear in unique values (span-splice, not replaceAll per value)', () => {+ test('1 MB transcript with 5000 UNIQUE high-entropy values: redact < 400ms (was ~3 s for a ~70 ms scan)', () => {+ // One full-text replaceAll per unique (pattern, value) pair made the+ // rebuild O(unique × text); the output is now spliced from the claimed+ // spans in one pass. Two prose lines between assignments keep the+ // transcript ~1 MB and mostly non-secret, as a real session is.+ const prose = 'the quick brown fox jumps over the lazy dog and keeps going for a while yet more prose to pad it out';+ const base = ['aB3xZ9qL7m', 'Np2Rt5Vw8Yk1D4'].join('');+ const values = Array.from({ length: 5000 }, (_, k) => base + k.toString(36).padStart(6, 'Q'));+ const lines: string[] = [];+ for (const v of values) lines.push(`api_key = "${v}"`, prose, prose);+ const text = lines.join('\n');+ expect(text.length).toBeGreaterThan(1024 * 1024);+ let result = { text: '', redactions: [] as ReturnType<typeof scanText> };+ const ms = elapsedMs(() => { result = redactFindings(text, { highEntropy: true }); });+ expect(result.redactions.length).toBe(5000);+ expect(result.text.split('<REDACTED:high_entropy_assignment>').length - 1).toBe(5000);+ for (const v of [values[0], values[2499], values[4999]]) expect(result.text.includes(v!)).toBe(false);+ expect(result.text.startsWith(`api_key = "<REDACTED:high_entropy_assignment>"\n${prose}\n${prose}\napi_key = "<REDACTED:high_entropy_assignment>"`)).toBe(true);+ expect(ms).toBeLessThan(400);+ });++ test('1 MB transcript with 5000 UNIQUE high-entropy values, each echoed bare once: only the first 64 echoes are scrubbed, < 400ms', () => {+ // The echo pass now covers high_entropy_assignment. What keeps this+ // linear is the dictionary cap: 64 sweeps over the text, not 5000 —+ // echoes of values past the cap are the documented, accepted miss (their+ // CLAIMS are still redacted).+ const prose = 'the quick brown fox jumps over the lazy dog and keeps going for a while yet more prose to pad it out';+ const base = ['aB3xZ9qL7m', 'Np2Rt5Vw8Yk1D4'].join('');+ // Uppercase pad: base36 renders lowercase, so `Q0` can never collide with+ // a padded single digit the way a lowercase `q` pad did (k=936 → `q0`).+ const values = Array.from({ length: 5000 }, (_, k) => base + k.toString(36).padStart(6, 'Q'));+ expect(new Set(values).size).toBe(5000);+ const lines: string[] = [];+ for (const v of values) lines.push(`api_key = "${v}"`, `then the agent pasted ${v} into the shell`, prose);+ const text = lines.join('\n');+ expect(text.length).toBeGreaterThan(1024 * 1024);+ let result = { text: '', redactions: [] as ReturnType<typeof scanText> };+ const ms = elapsedMs(() => { result = redactFindings(text, { highEntropy: true }); });+ expect(result.redactions.length).toBe(5000);+ expect(result.text.split('<REDACTED:high_entropy_assignment>').length - 1).toBe(5000 + ECHO_MAX_UNIQUE);+ expect(result.text.includes(values[0]!)).toBe(false);+ expect(result.text.includes(values[ECHO_MAX_UNIQUE - 1]!)).toBe(false);+ // The 65th value: claim redacted, bare echo survives.+ expect(result.text).toContain(`then the agent pasted ${values[ECHO_MAX_UNIQUE]} into the shell`);+ expect(result.text).not.toContain(`api_key = "${values[ECHO_MAX_UNIQUE]}"`);+ expect(ms).toBeLessThan(400);+ });++ test('5000 UNIQUE Bearer tokens on one line: redact < 200ms (was ~360 ms; the echo pass adds only its 64 sweeps)', () => {+ const line = Array.from({ length: 5000 }, (_, k) => `Bearer ${OPAQUE}${k.toString(36).padStart(4, 'z')}`).join(' ');+ let result = { text: '', redactions: [] as ReturnType<typeof scanText> };+ const ms = elapsedMs(() => { result = redactFindings(line); });+ expect(result.redactions.length).toBe(5000);+ expect(result.text.includes(OPAQUE)).toBe(false);+ expect(result.text).toBe(Array.from({ length: 5000 }, () => 'Bearer <REDACTED:bearer>').join(' '));+ expect(ms).toBeLessThan(200);+ });+});diff --git a/test/secret-scan.test.ts b/test/secret-scan.test.tsindex d608ff8d23..741d71922c 100644--- a/test/secret-scan.test.ts+++ b/test/secret-scan.test.ts@@ -15,6 +15,8 @@ import { tmpdir } from 'os';import {scanText, scanFiles, redactFindings, loadWorkspaceAllowlist, matchesGlob,globToRegExp, shannonEntropy, pathAllowlisted, SCAN_ALLOW_FILENAME,+ PEM_BODY_MAX_CHARS, ECHO_MIN_CHARS_BEARER, ECHO_MIN_CHARS_ENTROPY, ECHO_MAX_UNIQUE,+ ECHO_MAX_VALUE_CHARS, planRedaction, applyRedaction,} from '../src/core/secret-scan.ts';// Synthetic fixture values (never real keys).@@ -287,6 +289,42 @@ describe('redactFindings (corpus-write mode, S3#2)', () => {const header = scanText('leaked: -----BEGIN RSA PRIVATE KEY-----\n');expect(header.map((f) => f.pattern)).toEqual(['private_key_pem']);});++ test('several PEM blocks report exact 1-based header lines (incremental line cursor)', () => {+ // Header/footer joined from fragments so the committed source never carries a whole PEM block (gitleaks private-key rule).+ const key = (b: string) => [['-----BEGIN', ' EC PRIVATE KEY', '-----'].join(''), b, ['-----END', ' EC PRIVATE KEY', '-----'].join('')].join('\n');+ const text = [+ 'a', // 1+ key('MHcCAQEEIBody0001'), // 2-4+ 'b', // 5+ key('MHcCAQEEIBody0002'), // 6-8+ 'c', // 9+ ['-----BEGIN', ' RSA PRIVATE KEY', '-----'].join(''), // 10, header-only, last so no later END can extend it+ ].join('\n');+ const findings = scanText(text);+ expect(findings.map((f) => f.pattern)).toEqual(['private_key_pem', 'private_key_pem', 'private_key_pem']);+ expect(findings.map((f) => f.line)).toEqual([2, 6, 10]);+ const { text: out } = redactFindings(text);+ expect(out).toBe('a\n<REDACTED:private_key_pem>\nb\n<REDACTED:private_key_pem>\nc\n<REDACTED:private_key_pem>');+ });++ test(`the PEM body bound is exactly ${PEM_BODY_MAX_CHARS} chars (pinned so an edit is a visible edit)`, () => {+ // Body = everything between the header and the END marker, newlines+ // included. At the bound the whole block (body + END) is one redacted+ // span; one char over degrades to the header-only match — the gate still+ // fires, the body is the accepted miss (an RSA-16384 PEM is ~12.5 KB).+ // Header/footer joined from fragments (see above).+ const wrap = (body: string) => ['-----BEGIN', ' RSA PRIVATE KEY', '-----', body, '-----END', ' RSA PRIVATE KEY', '-----'].join('');+ const atBound = wrap('\n' + 'Q'.repeat(PEM_BODY_MAX_CHARS - 2) + '\n');+ let { text: out } = redactFindings(atBound);+ expect(out).toBe('<REDACTED:private_key_pem>');+ const overBound = wrap('\n' + 'Q'.repeat(PEM_BODY_MAX_CHARS - 1) + '\n');+ const findings = scanText(overBound);+ expect(findings.map((f) => f.pattern)).toEqual(['private_key_pem']);+ ({ text: out } = redactFindings(overBound));+ expect(out.startsWith('<REDACTED:private_key_pem>\nQ')).toBe(true);+ expect(out.endsWith('-----END RSA PRIVATE KEY-----')).toBe(true);+ });});describe('glob dialect (shared with the push deny-list)', () => {@@ -341,6 +379,26 @@ describe('high-entropy assignment reaches compound credential keys', () => {}});+ test('the keyword may carry up to 64 trailing identifier chars before the `=` (bounded, closes a quadratic)', () => {+ // `[A-Za-z0-9_-]*` after the keyword ran to end-of-line and backtracked+ // once per `-`/`_` in an adversarial run (secret-scan-perf pins the+ // timing); `{0,64}` keeps AWS_SECRET_ACCESS_KEY-style compounds and+ // anything a real config key could plausibly be named.+ const tail64 = '_' + 'X'.repeat(63);+ expect(scanText(`SECRET${tail64}=${HI}`, { highEntropy: true }).map((f) => f.pattern)).toEqual(['high_entropy_assignment']);+ expect(scanText(`SECRET${tail64}X=${HI}`, { highEntropy: true })).toEqual([]);+ });++ test('the value is redacted through 4096 chars (pinned so a bound edit is a visible edit)', () => {+ // The cap gives the rule constant work per occurrence; a longer value is+ // redacted only through its first 4096 chars — the accepted miss, well+ // above any real token or base64 key blob.+ const v4096 = (HI + '0').repeat(4096 / (HI.length + 1) + 1).slice(0, 4096);+ expect(v4096.length).toBe(4096);+ expect(redactFindings(`token=${v4096}`, { highEntropy: true }).text).toBe('token=<REDACTED:high_entropy_assignment>');+ expect(redactFindings(`token=${v4096}Z`, { highEntropy: true }).text).toBe('token=<REDACTED:high_entropy_assignment>Z');+ });+/** Known limitation, asserted so it stays visible rather than being* rediscovered. The left boundary requires the keyword to START at a* non-alphanumeric, so a camelCase compound (`apiAccessToken`) is out of@@ -364,3 +422,584 @@ describe('high-entropy assignment reaches compound credential keys', () => {}});});++// ── Format-based detectors (unprefixed credential shapes) ───────────────────+//+// Every seeded value below is SYNTHETIC and assembled at runtime from >= 2+// fragments so no committed line carries a credential-shaped literal (the+// wave security scan runs gitleaks with the allowlist stripped). Constant+// names keep scanner keywords away from the `=`.+const JWT_SEGMENTS = [+ 'eyJhbGciOiJIUzI1NiJ9',+ 'eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaWF0IjoxNzAwMDAwMDAwfQ',+ 'c2lnbmF0dXJlLXBsYWNlaG9sZGVyLTAwMDA',+];+const JWT = JWT_SEGMENTS.join('.');+const ASIA_ID = ['ASIA', 'Q3EXAMPLE7ABCDEF'].join(''); // 16 after the prefix+const GOOGLE_SHAPE = ['AIza', 'SyD1-Fake_Example0123456789abcdefGH'].join('');+const STRIPE_LIVE = ['sk_live_', '4eC39HqLyjWDarjtT1zdp7dc'].join('');+const STRIPE_RESTRICTED = ['rk_test_', 'Ab12Cd34Ef56Gh78Ij90Kl'].join('');+const STRIPE_WEBHOOK = ['whsec_', 'Ab12Cd34Ef56Gh78Ij90Kl12Mn34'].join('');+const SENDGRID_SHAPE = ['SG', '.abcDEF123_ghiJKL456', '.mnoPQR789-stuVWX012'].join('');+const TWILIO_SID = ['AC', '0123456789abcdef', '0123456789abcdef'].join('');+const TWILIO_SIGNING = ['SK', 'fedcba9876543210', 'fedcba9876543210'].join('');+const SUPABASE_SB = ['sb_secret_', 'exampleplaceholdervalue00'].join(''); // low-entropy value: matches sb_secret_[A-Za-z0-9_-]{20,} but stays under gitleaks' generic-api-key entropy gate+const SUPABASE_SBP = ['sbp_', '0123456789abcdef0123456789abcdef01234567'].join('');+const GITLAB_SHAPE = ['glpat-', 'Ab12Cd34Ef56Gh78Ij90Kl'].join('');+const NPM_SHAPE = ['npm_', 'Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56Qr78'].join('');+const HF_SHAPE = ['hf_', 'AbCdEfGhIjKlMnOpQrStUvWxYz0123456789'].join('');+const OPAQUE_BEARER_VALUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');+const DB_URL_CREDS = ['postgres://', 'dbuser', ':', 'p4ssw0rd', '@'].join('');+const DB_URL = DB_URL_CREDS + 'db.internal:5432/app';+const MONGO_SRV_URL = ['mongodb+srv://', 'app', ':', 'p4ss', '@cluster0.internal/db'].join('');+const REDIS_NOUSER_URL = ['redis://', ':', 'r3dis', '@cache.internal:6379'].join('');++describe('format-based detectors — attribution per pattern (unprefixed credential shapes)', () => {+ const cases: Array<[string, string, string]> = [+ ['jwt', 'service role', JWT],+ ['aws_access_key', 'temporary aws id', ASIA_ID],+ ['google_api_key', 'maps', GOOGLE_SHAPE],+ ['stripe', 'live', STRIPE_LIVE],+ ['stripe', 'restricted', STRIPE_RESTRICTED],+ ['stripe', 'webhook signing', STRIPE_WEBHOOK],+ ['sendgrid', 'mail', SENDGRID_SHAPE],+ ['twilio', 'account sid', TWILIO_SID],+ ['twilio', 'signing key', TWILIO_SIGNING],+ ['supabase_key', 'sb_secret form', SUPABASE_SB],+ ['supabase_key', 'sbp management token', SUPABASE_SBP],+ ['gitlab_pat', 'gitlab', GITLAB_SHAPE],+ ['npm_token', 'npm', NPM_SHAPE],+ ['huggingface', 'hf', HF_SHAPE],+ ['db_url_credentials', 'postgres url', DB_URL],+ ['db_url_credentials', 'mongodb+srv url', MONGO_SRV_URL],+ ['db_url_credentials', 'redis url with empty user', REDIS_NOUSER_URL],+ ];+ for (const [pattern, label, value] of cases) {+ test(`${pattern} (${label}) fires exactly once and never leaks the value`, () => {+ const findings = scanText(`note: ${value} end`);+ expect(findings.map((f) => f.pattern)).toEqual([pattern]);+ expect(JSON.stringify(findings).includes(value)).toBe(false);+ expect(findings[0]!.redactedPreview).toContain(`<REDACTED:${pattern}>`);+ const { text } = redactFindings(`x ${value} y`);+ expect(text.includes(value)).toBe(false);+ expect(text).toContain(`<REDACTED:${pattern}>`);+ });+ }++ test('connection-string redaction keeps the host/db, drops only the credential span', () => {+ const { text } = redactFindings(`DATABASE_URL=${DB_URL}`);+ expect(text).toBe('DATABASE_URL=<REDACTED:db_url_credentials>db.internal:5432/app');+ expect(text.includes('p4ssw0rd')).toBe(false);+ });++ test('the advisory-shaped session line: JWT + account SID both redacted, prose intact', () => {+ const line = `deploy is failing. service role key ${JWT} and twilio sid ${TWILIO_SID}`;+ const { text, redactions } = redactFindings(line);+ expect(redactions.map((r) => r.pattern).sort()).toEqual(['jwt', 'twilio']);+ expect(text).toBe('deploy is failing. service role key <REDACTED:jwt> and twilio sid <REDACTED:twilio>');+ });+});++describe('format-based detectors — ordering + catch-all attribution', () => {+ test('Bearer <jwt> attributes to jwt (specific wins over the bearer catch-all)', () => {+ const findings = scanText(`Authorization: Bearer ${JWT}`);+ expect(findings.map((f) => f.pattern)).toEqual(['jwt']);+ });++ test('Bearer <opaque token> attributes to bearer; the header word survives redaction', () => {+ const findings = scanText(`Authorization: Bearer ${OPAQUE_BEARER_VALUE}`);+ expect(findings.map((f) => f.pattern)).toEqual(['bearer']);+ const { text } = redactFindings(`Authorization: Bearer ${OPAQUE_BEARER_VALUE}`);+ expect(text).toBe('Authorization: Bearer <REDACTED:bearer>');+ // lowercase header word too+ expect(scanText(`authorization: bearer ${OPAQUE_BEARER_VALUE}`).map((f) => f.pattern)).toEqual(['bearer']);+ });++ test('Bearer <vendor key> keeps the vendor attribution (existing contract, pinned against the catch-all)', () => {+ expect(scanText(`Bearer ${ANTHROPIC}`).map((f) => f.pattern)).toEqual(['anthropic']);+ expect(scanText(`Bearer gbrain_at_${GBRAIN_HEX}`).map((f) => f.pattern)).toEqual(['gbrain_token']);+ expect(scanText(`Bearer ${GHP}`).map((f) => f.pattern)).toEqual(['github_token']);+ });++ test('a JWT used as a connection-string password: jwt reports the token once; db_url_credentials still covers the userinfo around it', () => {+ // Attribution is first-wins (the JWT is never double-reported as a+ // connection-string credential); coverage is the UNION (the username and+ // the `@` the catch-all matched around the JWT are claimed as its slices).+ const url = ['postgres://', 'svc', ':', JWT, '@db.internal/app'].join('');+ const findings = scanText(url);+ expect(findings.filter((f) => f.pattern === 'jwt').length).toBe(1);+ expect(findings.map((f) => f.pattern)).toEqual(['jwt', 'db_url_credentials', 'db_url_credentials']);+ const { text } = redactFindings(url);+ expect(text).toBe('<REDACTED:db_url_credentials><REDACTED:jwt><REDACTED:db_url_credentials>db.internal/app');+ expect(text.includes(JWT)).toBe(false);+ expect(text.includes('svc')).toBe(false);+ });+});++// ── Union coverage ───────────────────────────────────────────────────────────+//+// The per-line dedupe is first-wins for ATTRIBUTION only. A later span that+// partially overlaps an earlier claim has its UNCLAIMED slices claimed as hits+// of the later pattern (value = the slice), so nothing a pattern matched is+// left in the output or a preview; a fully covered later span is skipped.+// Discarding the whole later span used to ship the entire password of a+// database URL whose username was a vendor-shaped id.+describe('union coverage — a later span overlapping an earlier claim still covers its uncovered slices', () => {+ const PW = ['s3cr3t', 'P4ssw0rdXyz'].join('');+ const EXPECTED = '<REDACTED:db_url_credentials><REDACTED:twilio><REDACTED:db_url_credentials>db.internal/app';++ test('a database URL whose USERNAME is a vendor-shaped id: username AND password redacted, in the text and in every preview', () => {+ const url = ['postgres://', TWILIO_SID, ':', PW, '@db.internal/app'].join('');+ const findings = scanText(url);+ // One record per claimed span: the id, then the two db_url slices around it.+ expect(findings.map((f) => f.pattern)).toEqual(['twilio', 'db_url_credentials', 'db_url_credentials']);+ for (const f of findings) {+ expect(f.redactedPreview).toBe(EXPECTED);+ expect(f.redactedPreview.includes(PW)).toBe(false);+ expect(f.redactedPreview.includes(TWILIO_SID)).toBe(false);+ }+ const { text, redactions } = redactFindings(url);+ expect(text).toBe(EXPECTED);+ expect(redactions.length).toBe(3);+ });++ test('the slices carry their own fingerprints, so a slice can be allowlisted like any finding', () => {+ const url = ['postgres://', TWILIO_SID, ':', PW, '@db.internal/app'].join('');+ const [, , tail] = scanText(url);+ const { text, redactions } = redactFindings(url, { allowlist: [tail!.fingerprint] });+ expect(redactions.map((r) => r.pattern)).toEqual(['twilio', 'db_url_credentials']);+ expect(text).toBe(`<REDACTED:db_url_credentials><REDACTED:twilio>:${PW}@db.internal/app`);+ });++ test('a FULLY covered later span is skipped: Bearer <vendor key> reports the vendor only, no bearer record', () => {+ for (const key of [ANTHROPIC, GHP, `gbrain_at_${GBRAIN_HEX}`]) {+ const { text, redactions } = redactFindings(`Authorization: Bearer ${key}`);+ expect(redactions.length).toBe(1);+ expect(redactions[0]!.pattern).not.toBe('bearer');+ expect(text).toBe(`Authorization: Bearer <REDACTED:${redactions[0]!.pattern}>`);+ }+ });++ test('a JWT inside a longer opaque bearer token: jwt keeps the JWT, bearer covers the tail', () => {+ const tail = ['.extra', 'Segment0123456789'].join('');+ const line = `Authorization: Bearer ${JWT}${tail}`;+ expect(scanText(line).map((f) => f.pattern)).toEqual(['jwt', 'bearer']);+ const { text } = redactFindings(line);+ expect(text).toBe('Authorization: Bearer <REDACTED:jwt><REDACTED:bearer>');+ expect(text.includes(tail)).toBe(false);+ });++ test('a span split around TWO earlier claims yields one slice per gap', () => {+ // Two vendor ids inside one connection-string span: `user` is a twilio+ // SID and the password a JWT — the catch-all covers the scheme, the `:`+ // between them and the trailing `@`.+ const url = ['mysql://', TWILIO_SID, ':', JWT, '@h/db'].join('');+ const { text, redactions } = redactFindings(url);+ expect(redactions.map((r) => r.pattern)).toEqual(['twilio', 'jwt', 'db_url_credentials', 'db_url_credentials', 'db_url_credentials']);+ expect(text).toBe('<REDACTED:db_url_credentials><REDACTED:twilio><REDACTED:db_url_credentials><REDACTED:jwt><REDACTED:db_url_credentials>h/db');+ });+});++describe('format-based detectors — negatives (identifiers and public shapes stay put)', () => {+ test('uppercase 64-hex digest starting with AC is not a Twilio SID', () => {+ const digest = 'AC' + 'DEADBEEF'.repeat(7) + 'DEADBE';+ expect(digest.length).toBe(64);+ expect(scanText(`sha256: ${digest}`)).toEqual([]);+ });++ test('URLs with userinfo but no password, or non-database schemes, do not fire', () => {+ for (const s of [+ 'https://[email protected]/path',+ 'https://user:[email protected]/path', // not a database scheme — by design+ 'postgres://db.internal:5432/app', // no credentials+ '[email protected]:org/repo.git',+ ]) {+ expect(scanText(s)).toEqual([]);+ }+ });++ test('fixed-length shapes require a hard right edge (longer runs are identifiers)', () => {+ for (const s of [+ `${ASIA_ID}XYZ`, // 19 after ASIA — not a 16-char key id+ `${TWILIO_SID}ff`, // 34 hex after AC+ `${GOOGLE_SHAPE}zz`, // 37 after AIza+ `${NPM_SHAPE}Q`, // 37 after npm_+ `${SUPABASE_SBP}9`, // 41 hex after sbp_+ ]) {+ expect(scanText(s)).toEqual([]);+ }+ });++ test('Supabase publishable keys and project refs are identifiers, not credentials', () => {+ // sb_publishable_ is public by design; a bare 20-char project ref is an+ // identifier (deliberately NOT a pattern).+ expect(scanText(`anon: sb_publishable_${'Ab12Cd34Ef56Gh78Ij90Kl12'}`)).toEqual([]);+ expect(scanText('project ref zfakerefzfakeref0000 at zfakerefzfakeref0000.supabase.co')).toEqual([]);+ });++ test('the JWT prefix alone, or two segments, does not fire', () => {+ expect(scanText(`header ${JWT_SEGMENTS[0]} only`)).toEqual([]);+ expect(scanText(`two ${JWT_SEGMENTS[0]}.${JWT_SEGMENTS[1]} segments`)).toEqual([]);+ });++ test('a JWT fires after every real wire delimiter; `-` is not a boundary (documented, closes a quadratic)', () => {+ // The jwt boundary excludes `-` (as well as `_`): with `-` admitted, every+ // `-` in a `-eyJ-eyJ…` run was a fresh start that consumed to end-of-line+ // and backtracked (secret-scan-perf pins the timing). Headers, JSON, env+ // files and URLs put one of these in front of a token instead.+ for (const prefix of ['Bearer ', '"', '=', ':', '/', '(', '\t']) {+ expect(scanText(`x${prefix}${JWT}`).map((f) => f.pattern)).toEqual(['jwt']);+ }+ expect(scanText(`x-${JWT}`)).toEqual([]);+ expect(scanText(`x_${JWT}`)).toEqual([]);+ });++ test('embedded inside an identifier, vendor prefixes still do not fire', () => {+ expect(scanText(`x_${STRIPE_LIVE}`)).toEqual([]);+ expect(scanText(`my${GITLAB_SHAPE}`)).toEqual([]);+ });+});++describe('high-entropy assignment requires a digit in the value', () => {+ test('code-shaped assignments without a digit do not fire (probe lines)', () => {+ for (const s of [+ 'credentials = DefaultAzureCredential()',+ 'credential_process = /usr/local/bin/aws-vault',+ 'apiKeyEnvVar = "OPENAI_API_KEY_PRODUCTION"',+ 'secret_name = my-app/prod/database-credentials',+ 'api_key_header: X-Api-Key-Authorization-Header',+ ]) {+ expect(scanText(s, { highEntropy: true })).toEqual([]);+ }+ });++ test('a TOKEN= assignment with a digit-bearing entropic value still fires', () => {+ const v = ['aB3xK9mQ', '2pR7sT1vW4yZ8bC5'].join('');+ expect(scanText(`SMTP_TOKEN=${v}`, { highEntropy: true }).map((f) => f.pattern)).toEqual(['high_entropy_assignment']);+ });++ /** Known, accepted limitation: a 40-hex git sha assigned to a `token:` key+ * has digits AND passes the entropy gate, so it redacts. Pinned so the+ * trade-off stays visible. */+ test('a 40-hex sha after token: still redacts (documented trade-off)', () => {+ const sha = '3e365f5f1a2b4c8d9e0f1a2b3c4d5e6f70819293';+ expect(shannonEntropy(sha)).toBeGreaterThanOrEqual(3.5);+ expect(scanText(`token: ${sha}`, { highEntropy: true }).map((f) => f.pattern)).toEqual(['high_entropy_assignment']);+ });+});++// ── Preview windowing + corpus redaction (span-splice) ───────────────────────+//+// buildPreview renders a WINDOW around the hit (not the whole line) and+// redacts every claimed span inside it; redactFindings rebuilds the text by+// splicing `<REDACTED:pattern>` over exactly the CLAIMED spans (sorted by+// absolute offset, one pass) — not by replaceAll per unique value — and fills+// the unclaimed gaps with the bounded echo pass over the bearer / high-entropy+// values it claimed (pinned in its own describe below). Values below are+// synthetic and runtime-joined from >= 2 fragments.+describe('redactFindings — span-splice semantics and preview window', () => {+ const OPAQUE_VALUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');+ /** PREVIEW_MAX_CHARS (160) plus a leading and a trailing ellipsis. */+ const PREVIEW_CEILING = 162;++ test('a value that is a substring of another value: both redact whole', () => {+ // The bearer token is discovered first (line 1) and is ALSO the password+ // inside the line-2 connection string. The replaceAll form needed a+ // longest-first sort here (replacing the short value first corrupted the+ // longer span, leaving the username and a bare `<REDACTED:bearer>`).+ // Claimed spans never overlap, so the splice has no ordering hazard —+ // kept as the regression pin for that shape.+ const url = ['postgres://', 'svc', ':', OPAQUE_VALUE, '@db.internal/app'].join('');+ const { text, redactions } = redactFindings(`Authorization: Bearer ${OPAQUE_VALUE}\nDATABASE_URL=${url}\n`);+ expect(text).toBe('Authorization: Bearer <REDACTED:bearer>\nDATABASE_URL=<REDACTED:db_url_credentials>db.internal/app\n');+ expect(redactions.map((r) => r.pattern)).toEqual(['bearer', 'db_url_credentials']);+ });++ test('redacts exactly the claimed spans (every pattern outside the echo pass): the corpus write agrees with what scanText reports', () => {+ // Documented semantic delta from the replaceAll form: a claimed value's+ // bytes at a position the scanner did NOT claim (embedded past its left+ // boundary inside a longer identifier) are left as-is, so+ // `redactFindings(t).text` never redacts something `scanText(t)` would+ // not have reported. The exception is the bounded echo pass over the+ // bearer + high_entropy_assignment values (pinned in the next describe);+ // vendor shapes lose nothing by staying outside it — a repeat that clears+ // the boundary IS claimed on its own and both occurrences go.+ const text = `k=${OPENAI} again ${OPENAI}\nid=prefix${OPENAI}\nsid ${TWILIO_SID} vs x${TWILIO_SID}\n`;+ const findings = scanText(text);+ expect(findings.map((f) => [f.pattern, f.line])).toEqual([['openai', 1], ['openai', 1], ['twilio', 3]]);+ const { text: out, redactions } = redactFindings(text);+ expect(redactions.length).toBe(findings.length);+ expect(out).toBe(`k=<REDACTED:openai> again <REDACTED:openai>\nid=prefix${OPENAI}\nsid <REDACTED:twilio> vs x${TWILIO_SID}\n`);+ });++ test('a per-line span running into a PEM block: both spans redact, nothing claimed survives', () => {+ // The bearer value class admits `-`, so a token glued to a PEM header+ // claims `<token>-----BEGIN` on its line while the whole-text PEM pass+ // claims the block from `-----BEGIN`. The splice emits the later span's+ // uncovered tail as its own token instead of skipping it. (The replaceAll+ // form redacted the longer PEM value first, after which the bearer value+ // no longer existed in the text and the token survived.)+ const body = ['MIIEvQIBADANBgkqhkiG9w0BAQEF', 'AASCBKcwggSjAgEAAoIBAQC7VJTU'].join('');+ const text = `Authorization: Bearer ${OPAQUE_VALUE}${['-----BEGIN', ' RSA PRIVATE KEY', '-----'].join('')}\n${body}\n${['-----END', ' RSA PRIVATE KEY', '-----'].join('')}\nafter`;+ const { text: out, redactions } = redactFindings(text);+ expect(redactions.map((r) => r.pattern).sort()).toEqual(['bearer', 'private_key_pem']);+ expect(out).toBe('Authorization: Bearer <REDACTED:bearer><REDACTED:private_key_pem>\nafter');+ expect(out.includes(OPAQUE_VALUE)).toBe(false);+ expect(out.includes(body)).toBe(false);+ });++ test('one redaction record per occurrence even when the same value repeats', () => {+ const { text, redactions } = redactFindings(`a ${OPENAI}\nb ${OPENAI}\nc ${OPENAI}\n`);+ expect(redactions.length).toBe(3);+ expect(text).toBe('a <REDACTED:openai>\nb <REDACTED:openai>\nc <REDACTED:openai>\n');+ });++ test('a preview never carries a SIBLING secret from the same line', () => {+ const findings = scanText(`a=${OPENAI} b=${SLACK}`);+ expect(findings.map((f) => f.pattern).sort()).toEqual(['openai', 'slack']);+ for (const f of findings) {+ expect(f.redactedPreview.includes(OPENAI)).toBe(false);+ expect(f.redactedPreview.includes(SLACK)).toBe(false);+ expect(f.redactedPreview).toContain(`<REDACTED:${f.pattern}>`);+ }+ // The line is short, so the preview is the whole line with both spans redacted.+ expect(findings[0]!.redactedPreview).toBe('a=<REDACTED:openai> b=<REDACTED:slack>');+ });++ test('a preview on a long line is a window around the hit, marked with ellipses', () => {+ const pad = 'x'.repeat(300);+ const [f] = scanText(`${pad} k=${OPENAI} ${pad}`);+ expect(f!.redactedPreview).toContain('<REDACTED:openai>');+ expect(f!.redactedPreview.startsWith('…')).toBe(true);+ expect(f!.redactedPreview.endsWith('…')).toBe(true);+ expect(f!.redactedPreview.length).toBeLessThanOrEqual(PREVIEW_CEILING);+ expect(f!.redactedPreview.includes(OPENAI)).toBe(false);+ // Hit at the very start: no leading ellipsis, trailing one only.+ const [g] = scanText(`k=${OPENAI} ${pad}`);+ expect(g!.redactedPreview.startsWith('k=<REDACTED:openai> ')).toBe(true);+ expect(g!.redactedPreview.startsWith('…')).toBe(false);+ expect(g!.redactedPreview.endsWith('…')).toBe(true);+ // Short line: whole line, no ellipses (unchanged contract).+ expect(scanText(`k=${OPENAI}`)[0]!.redactedPreview).toBe('k=<REDACTED:openai>');+ });++ test('repeated occurrences of one value on a long line never leave a FRAGMENT in any preview', () => {+ // 40-char tokens spaced so a naive fixed window (hit-40 … hit+80) would+ // cut straight through the third occurrence. The window must snap to+ // span boundaries instead.+ const long = [OPAQUE_VALUE, '0123456789'].join('');+ expect(long.length).toBe(40);+ const line = Array.from({ length: 12 }, () => `Bearer ${long}`).join(' ');+ const findings = scanText(line);+ expect(findings.length).toBe(12);+ for (const f of findings) {+ expect(f.redactedPreview.includes(long.slice(0, 12))).toBe(false);+ expect(f.redactedPreview.includes(long.slice(-12))).toBe(false);+ expect(f.redactedPreview).toContain('<REDACTED:bearer>');+ }+ });+});++// ── Bounded echo pass (bearer + high_entropy_assignment) ─────────────────────+//+// A bearer token is claimed only where `Bearer ` anchors it and an entropic+// value only where its keyword does, yet a transcript routinely echoes the+// same value bare (in a tool call's header, then alone in the reply; a pasted+// `PASSWORD=` line, then the value in prose). redactFindings collects the+// values those two patterns claim (ECHO_MAX_UNIQUE unique values in claim+// order — ONE cap across both patterns — each clearing its pattern's floor+// and at most ECHO_MAX_VALUE_CHARS long) and redacts every remaining+// occurrence with that pattern's token. The pass runs per-value `indexOf`+// sweeps over the ORIGINAL text and splices into the unclaimed gaps — never+// an alternation RegExp (quadratic on prefix-sharing values, see the perf+// file), never over already-emitted tokens. It adds no findings.+describe('redactFindings — bounded echo pass', () => {+ const OPAQUE_VALUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');+ const unique = (k: number) => `${OPAQUE_VALUE}${k.toString(36).padStart(4, 'z')}`;+ const HI = ['aB3xZ9qL7m', 'Np2Rt5Vw8Yk1D4'].join('');++ test('the transcript shape: anchored in a tool call, echoed bare and embedded in the reply — every site is redacted, only the claim is counted', () => {+ const text = `tool: curl -H "Authorization: Bearer ${OPAQUE_VALUE}" https://api.example/v1\nassistant: the token ${OPAQUE_VALUE} expired; id=prefix${OPAQUE_VALUE} embeds it\n`;+ const findings = scanText(text);+ expect(findings.map((f) => [f.pattern, f.line])).toEqual([['bearer', 1]]);+ const { text: out, redactions } = redactFindings(text);+ // An echo is not a claim: `redactions` stays one record per CLAIMED occurrence.+ expect(redactions.length).toBe(1);+ expect(out).toBe('tool: curl -H "Authorization: Bearer <REDACTED:bearer>" https://api.example/v1\nassistant: the token <REDACTED:bearer> expired; id=prefix<REDACTED:bearer> embeds it\n');+ expect(out.includes(OPAQUE_VALUE)).toBe(false);+ });++ test('a keyword-anchored high-entropy value echoed bare (and embedded) is redacted as <REDACTED:high_entropy_assignment>', () => {+ // The transcripts lane runs with highEntropy on, so a pasted `.env` line+ // followed by the value in prose used to ship the prose copy.+ const text = `PASSWORD=${HI}\nthen the agent pasted ${HI} again; id=x${HI}y\n`;+ const { text: out, redactions } = redactFindings(text, { highEntropy: true });+ expect(redactions.map((r) => r.pattern)).toEqual(['high_entropy_assignment']);+ expect(out).toBe('PASSWORD=<REDACTED:high_entropy_assignment>\nthen the agent pasted <REDACTED:high_entropy_assignment> again; id=x<REDACTED:high_entropy_assignment>y\n');+ });++ test('each echo carries the token of the pattern that claimed the value', () => {+ const text = `Bearer ${OPAQUE_VALUE} TOKEN=${HI}\necho ${HI} and ${OPAQUE_VALUE}\n`;+ const { text: out } = redactFindings(text, { highEntropy: true });+ expect(out).toBe('Bearer <REDACTED:bearer> TOKEN=<REDACTED:high_entropy_assignment>\necho <REDACTED:high_entropy_assignment> and <REDACTED:bearer>\n');+ });++ test('a vendor key behind Bearer keeps its vendor attribution everywhere; the echo pass has nothing to do', () => {+ // Vendor shapes are claimed on their own wherever they appear, so both+ // occurrences are vendor tokens and no `<REDACTED:bearer>` is emitted.+ const { text: out, redactions } = redactFindings(`Bearer ${ANTHROPIC}\nbare ${ANTHROPIC}\n`);+ expect(redactions.map((r) => r.pattern)).toEqual(['anthropic', 'anthropic']);+ expect(out).toBe('Bearer <REDACTED:anthropic>\nbare <REDACTED:anthropic>\n');+ });++ test("other patterns' values are not echoed: a vendor key embedded past its boundary stays (it re-matches on its own wherever it clears the boundary)", () => {+ const { text: out } = redactFindings(`k=${OPENAI}\nid=prefix${OPENAI}\n`);+ expect(out).toBe(`k=<REDACTED:openai>\nid=prefix${OPENAI}\n`);+ });++ test(`the cap is exactly ${ECHO_MAX_UNIQUE} unique values in claim order; the next value's echo is the accepted miss`, () => {+ expect(ECHO_MAX_UNIQUE).toBe(64);+ const vals = Array.from({ length: ECHO_MAX_UNIQUE + 1 }, (_, k) => unique(k));+ const text = vals.map((v) => `Bearer ${v}`).join('\n') + `\necho ${vals[0]} ${vals[ECHO_MAX_UNIQUE - 1]} ${vals[ECHO_MAX_UNIQUE]}`;+ const { text: out, redactions } = redactFindings(text);+ // Every CLAIM past the cap is still redacted and counted — the cap bounds+ // the echo pass, not the splice.+ expect(redactions.length).toBe(ECHO_MAX_UNIQUE + 1);+ expect(out.endsWith(`echo <REDACTED:bearer> <REDACTED:bearer> ${vals[ECHO_MAX_UNIQUE]}`)).toBe(true);+ expect(out.split('<REDACTED:bearer>').length - 1).toBe(ECHO_MAX_UNIQUE + 1 + 2);+ });++ test('the cap is ONE budget across both patterns: 32 bearer + 32 entropy values fill it, a 65th (entropy) value does not echo', () => {+ const bearers = Array.from({ length: 32 }, (_, k) => unique(k));+ const entropics = Array.from({ length: 33 }, (_, k) => `${HI}${k.toString(36).padStart(4, 'q')}`);+ const text = [+ ...bearers.map((v) => `Bearer ${v}`),+ ...entropics.map((v) => `PASSWORD=${v}`),+ `echo ${bearers[0]} ${bearers[31]} ${entropics[0]} ${entropics[31]} ${entropics[32]}`,+ ].join('\n');+ const { text: out, redactions } = redactFindings(text, { highEntropy: true });+ expect(redactions.length).toBe(65);+ expect(out.endsWith(`echo <REDACTED:bearer> <REDACTED:bearer> <REDACTED:high_entropy_assignment> <REDACTED:high_entropy_assignment> ${entropics[32]}`)).toBe(true);+ });++ test('repeated claims of one value take one cap slot (the cap counts unique values, not occurrences)', () => {+ const text = Array.from({ length: ECHO_MAX_UNIQUE }, () => `Bearer ${unique(0)}`).join('\n') + `\nBearer ${unique(1)}\necho ${unique(1)}`;+ const { text: out, redactions } = redactFindings(text);+ expect(redactions.length).toBe(ECHO_MAX_UNIQUE + 1);+ expect(out.endsWith('echo <REDACTED:bearer>')).toBe(true);+ });++ test(`the floors are exactly ${ECHO_MIN_CHARS_BEARER} (bearer) and ${ECHO_MIN_CHARS_ENTROPY} (high_entropy_assignment) — each rule's own floor, restated (pinned so an edit is a visible edit)`, () => {+ expect(ECHO_MIN_CHARS_BEARER).toBe(20);+ expect(ECHO_MIN_CHARS_ENTROPY).toBe(12);+ const v20 = ['opaque', 'Tok0123456789X'].join('');+ expect(v20.length).toBe(20);+ expect(redactFindings(`Bearer ${v20}\necho ${v20}`).text).toBe('Bearer <REDACTED:bearer>\necho <REDACTED:bearer>');+ const v12 = ['aB3x', 'Z9qL7mN2'].join('');+ expect(v12.length).toBe(12);+ expect(redactFindings(`TOKEN=${v12}\necho ${v12}`, { highEntropy: true }).text).toBe('TOKEN=<REDACTED:high_entropy_assignment>\necho <REDACTED:high_entropy_assignment>');+ });++ test(`a value longer than ${ECHO_MAX_VALUE_CHARS} chars is redacted at its claim but does not echo (the length cap)`, () => {+ expect(ECHO_MAX_VALUE_CHARS).toBe(512);+ const v512 = 'aB3xZ9qL7m'.repeat(51) + 'Q2';+ expect(v512.length).toBe(512);+ expect(redactFindings(`Bearer ${v512}\necho ${v512}`).text).toBe('Bearer <REDACTED:bearer>\necho <REDACTED:bearer>');+ const v513 = v512 + 'z';+ expect(redactFindings(`Bearer ${v513}\necho ${v513}`).text).toBe(`Bearer <REDACTED:bearer>\necho ${v513}`);+ });++ test('an allowlisted bearer value is neither claimed nor echo-redacted (declared safe)', () => {+ const text = `Bearer ${OPAQUE_VALUE}\necho ${OPAQUE_VALUE}`;+ const [f] = scanText(text);+ const { text: out, redactions } = redactFindings(text, { allowlist: [f!.fingerprint] });+ expect(redactions).toEqual([]);+ expect(out).toBe(text);+ });++ test('a claimed value that is a prefix of another: leftmost-longest, neither echo is cut short', () => {+ const short = OPAQUE_VALUE;+ const long = OPAQUE_VALUE + 'MORE0';+ const text = `Bearer ${short}\nBearer ${long}\necho ${long} then ${short}`;+ expect(redactFindings(text).text).toBe('Bearer <REDACTED:bearer>\nBearer <REDACTED:bearer>\necho <REDACTED:bearer> then <REDACTED:bearer>');+ });++ test('values match literally: `.` and `+` in the bearer class are not metacharacters', () => {+ const v = ['abc.def+ghi', '=jkl~mno/pqr012345'].join('');+ expect(redactFindings(`Bearer ${v}\nbare ${v}`).text).toBe('Bearer <REDACTED:bearer>\nbare <REDACTED:bearer>');+ const nearMiss = v.replace('.', 'X');+ expect(redactFindings(`Bearer ${v}\nbare ${nearMiss}`).text).toBe(`Bearer <REDACTED:bearer>\nbare ${nearMiss}`);+ });++ test('the echo pass never touches an emitted token: a bearer value spelling a pattern name cannot nest', () => {+ // `high_entropy_assignment` is 23 bearer-class characters. Running the+ // echo pass over the SPLICED output turned the sibling token into+ // `<REDACTED:<REDACTED:bearer>>`; matching over the original text's+ // unclaimed gaps cannot.+ const text = `Authorization: Bearer high_entropy_assignment\nPASSWORD=${HI}\n`;+ const { text: out, redactions } = redactFindings(text, { highEntropy: true });+ expect(redactions.map((r) => r.pattern)).toEqual(['bearer', 'high_entropy_assignment']);+ expect(out).toBe('Authorization: Bearer <REDACTED:bearer>\nPASSWORD=<REDACTED:high_entropy_assignment>\n');+ expect(out.includes('<REDACTED:<')).toBe(false);+ });++ test('an echo that straddles a claimed span is left to the claim (nothing is emitted twice, nothing is skipped)', () => {+ // Line 2's connection string claims `…:<OPAQUE>@`; the bearer echo of+ // OPAQUE inside it is entirely within the claimed span and is not+ // re-emitted; the bare echo on line 3 is.+ const url = ['postgres://', 'svc', ':', OPAQUE_VALUE, '@db.internal/app'].join('');+ const { text: out } = redactFindings(`Bearer ${OPAQUE_VALUE}\n${url}\nbare ${OPAQUE_VALUE}\n`);+ expect(out).toBe('Bearer <REDACTED:bearer>\n<REDACTED:db_url_credentials>db.internal/app\nbare <REDACTED:bearer>\n');+ });+});++// ── Session-wide dictionary: planRedaction + applyRedaction ──────────────────+//+// A multi-field document (a transcript session) plans every field into ONE+// shared map first and applies afterwards, so an echo in an earlier field of+// a value claimed in a later field is scrubbed too. Same floors, same single+// cap; the plan's `redactions` are unchanged by the echo pass.+describe('planRedaction / applyRedaction — one echo dictionary across several texts', () => {+ const OPAQUE_VALUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');+ const HI = ['aB3xZ9qL7m', 'Np2Rt5Vw8Yk1D4'].join('');++ test('a value claimed in a LATER text is scrubbed from an EARLIER one once every plan is applied after every scan', () => {+ const echoValues = new Map<string, string>();+ const a = planRedaction(`the token ${OPAQUE_VALUE} expired`, { echoValues });+ const b = planRedaction(`Authorization: Bearer ${OPAQUE_VALUE}`, { echoValues });+ const c = planRedaction(`pasted ${HI} into the env`, { echoValues, highEntropy: true });+ const d = planRedaction(`SMTP_PASSWORD=${HI}`, { echoValues, highEntropy: true });+ expect(a.redactions).toEqual([]);+ expect(b.redactions.map((r) => r.pattern)).toEqual(['bearer']);+ expect(c.redactions).toEqual([]);+ expect(d.redactions.map((r) => r.pattern)).toEqual(['high_entropy_assignment']);+ expect([...echoValues]).toEqual([[OPAQUE_VALUE, 'bearer'], [HI, 'high_entropy_assignment']]);+ expect(applyRedaction(a)).toBe('the token <REDACTED:bearer> expired');+ expect(applyRedaction(b)).toBe('Authorization: Bearer <REDACTED:bearer>');+ expect(applyRedaction(c)).toBe('pasted <REDACTED:high_entropy_assignment> into the env');+ expect(applyRedaction(d)).toBe('SMTP_PASSWORD=<REDACTED:high_entropy_assignment>');+ });++ test('the shared map is one budget across texts: a value claimed past the cap in a later text does not echo anywhere', () => {+ const echoValues = new Map<string, string>();+ const vals = Array.from({ length: ECHO_MAX_UNIQUE + 1 }, (_, k) => `${OPAQUE_VALUE}${k.toString(36).padStart(4, 'z')}`);+ const early = planRedaction(`seen first: ${vals[ECHO_MAX_UNIQUE]} and ${vals[0]}`, { echoValues });+ const plans = vals.map((v) => planRedaction(`Bearer ${v}`, { echoValues }));+ expect(echoValues.size).toBe(ECHO_MAX_UNIQUE);+ expect(echoValues.has(vals[ECHO_MAX_UNIQUE]!)).toBe(false);+ expect(applyRedaction(early)).toBe(`seen first: ${vals[ECHO_MAX_UNIQUE]} and <REDACTED:bearer>`);+ // The over-cap CLAIM is still redacted at its own span.+ expect(applyRedaction(plans[ECHO_MAX_UNIQUE]!)).toBe('Bearer <REDACTED:bearer>');+ });++ test('redactFindings returns the dictionary it collected', () => {+ const { echoValues } = redactFindings(`Bearer ${OPAQUE_VALUE}`);+ expect([...echoValues]).toEqual([[OPAQUE_VALUE, 'bearer']]);+ expect(redactFindings('nothing here').echoValues.size).toBe(0);+ });++ test('a text with no claims and a non-empty shared map is still swept (the echo pass is not gated on local claims)', () => {+ const echoValues = new Map<string, string>([[OPAQUE_VALUE, 'bearer']]);+ expect(applyRedaction(planRedaction(`just ${OPAQUE_VALUE}`, { echoValues }))).toBe('just <REDACTED:bearer>');+ });+});diff --git a/test/sensitivity-scan.test.ts b/test/sensitivity-scan.test.tsindex 4387c3b625..a69c8ba49b 100644--- a/test/sensitivity-scan.test.ts+++ b/test/sensitivity-scan.test.ts@@ -258,3 +258,33 @@ describe('PII refactor regression — scrubPii bytes + findPii semantics', () =>expect(findPii('')).toEqual([]);});});++describe('secret-scan owns the jwt/bearer shapes — no double report with the PII pass', () => {+ // Runtime-joined synthetic values (never committed as one literal).+ const JWT = [+ 'eyJhbGciOiJIUzI1NiJ9',+ 'eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaWF0IjoxNzAwMDAwMDAwfQ',+ 'c2lnbmF0dXJlLXBsYWNlaG9sZGVyLTAwMDA',+ ].join('.');+ const OPAQUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');++ test('one JWT → exactly one finding, attributed to the secret scanner', () => {+ const findings = scanSensitive(`service role ${JWT} here`, makeConfig(ws()));+ expect(findings.map((f) => f.family)).toEqual(['secret:jwt']);+ });++ test('one opaque Bearer header → exactly one finding (secret:bearer), not pii:bearer as well', () => {+ const findings = scanSensitive(`Authorization: Bearer ${OPAQUE}`, makeConfig(ws()));+ expect(findings.map((f) => f.family)).toEqual(['secret:bearer']);+ });++ test('Bearer <vendor key> → one vendor finding only', () => {+ const findings = scanSensitive(`Bearer ${ANTHROPIC}`, makeConfig(ws()));+ expect(findings.map((f) => f.family)).toEqual(['secret:anthropic']);+ });++ test('a short bearer token (below the secret-scan floor) still reaches pii:bearer — coverage is not lost', () => {+ const findings = scanSensitive('Bearer abcdef1234', makeConfig(ws()));+ expect(findings.map((f) => f.family)).toEqual(['pii:bearer']);+ });+});diff --git a/test/sources-mcp.test.ts b/test/sources-mcp.test.tsindex 192fec4639..dc073fdc36 100644--- a/test/sources-mcp.test.ts+++ b/test/sources-mcp.test.ts@@ -18,6 +18,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { operations, OperationError } from '../src/core/operations.ts';import type { OperationContext, AuthInfo, Operation } from '../src/core/operations.ts';import { hasScope } from '../src/core/scope.ts';+import { assertSourceInCallerScope, assertSourceInCallerWriteScope } from '../src/core/ops/context.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { withEnv } from './helpers/with-env.ts';@@ -74,6 +75,13 @@ beforeEach(async () => {mkdirSync(GBRAIN_HOME, { recursive: true });});+/** Drop the write-source axis entirely — an explicit `sourceId: undefined` is not the same shape as an absent key. */+function withoutSourceId(ctx: OperationContext): OperationContext {+ const { sourceId: _drop, ...rest } = ctx;+ void _drop;+ return rest as OperationContext;+}+function findOp(name: string): Operation {const op = operations.find(o => o.name === name);if (!op) throw new Error(`op not found: ${name}`);@@ -258,7 +266,12 @@ describe('sources_* handlers — happy path', () => {url: 'https://github.com/example/repo',})) as any;const removeOp = findOp('sources_remove');- const result = (await removeOp.handler(ctxRemote(['sources_admin']), {+ // Removal is WRITE authority: the caller's write source must BE the+ // target (a federated read grant naming it does not count — see the+ // fence test below). A freshly added source is outside the caller's+ // authority until the operator rescopes the client's write source+ // onto it (`gbrain auth rescope-client <id> --source mcp-remove-test`).+ const result = (await removeOp.handler({ ...ctxRemote(['sources_admin']), sourceId: 'mcp-remove-test' }, {id: 'mcp-remove-test',confirm_destructive: true,})) as any;@@ -266,6 +279,88 @@ describe('sources_* handlers — happy path', () => {expect(existsSync(row.local_path)).toBe(false);});});++ test('sources_remove: an UNBOUND remote sources_admin caller (no write source, no federated grant) keeps full authority', async () => {+ await withEnv({ GBRAIN_HOME, PATH: fakePath() }, async () => {+ const row = (await findOp('sources_add').handler(ctxRemote(['sources_admin']), {+ id: 'mcp-remove-unbound',+ url: 'https://github.com/example/repo',+ })) as any;+ // Operator-registered client with neither axis set: the pre-O4-1+ // authority is unchanged (the fence is about BOUND callers).+ const unbound: OperationContext = withoutSourceId(ctxRemote(['sources_admin']));+ const result = (await findOp('sources_remove').handler(unbound, {+ id: 'mcp-remove-unbound',+ confirm_destructive: true,+ })) as any;+ expect(result.clone_removed).toBe(true);+ expect(existsSync(row.local_path)).toBe(false);+ });+ });++ test('sources_remove: untrusted caller is confined to its source scope; out-of-scope → not_found, nothing removed', async () => {+ await withEnv({ GBRAIN_HOME, PATH: fakePath() }, async () => {+ const addOp = findOp('sources_add');+ const row = (await addOp.handler(ctxRemote(['sources_admin']), {+ id: 'mcp-remove-fenced',+ url: 'https://github.com/example/repo',+ })) as any;+ const removeOp = findOp('sources_remove');+ const errFor = async (ctx: OperationContext, id: string): Promise<OperationError> => {+ try {+ await removeOp.handler(ctx, { id, confirm_destructive: true });+ } catch (e) {+ expect(e).toBeInstanceOf(OperationError);+ return e as OperationError;+ }+ throw new Error(`expected sources_remove(${id}) to throw for the confined caller`);+ };+ // Scalar-bound remote caller (sourceId 'default', no federated grant):+ // an existing out-of-scope source answers not_found and survives.+ const scalar = await errFor(ctxRemote(['sources_admin']), 'mcp-remove-fenced');+ expect(scalar.code).toBe('not_found');+ // Federated grant that does not name the id: same answer.+ const fed = await errFor(ctxRemote(['sources_admin'], ['other-src']), 'mcp-remove-fenced');+ expect(fed.code).toBe('not_found');+ // O4-1: a federated READ grant that DOES name the id is still not+ // removal authority — federation is read-only by contract (contract.ts+ // AuthInfo.allowedSources), so a client bound to write 'default' with+ // federated_read [default, mcp-remove-fenced] cannot cascade-delete the+ // sibling. Same not_found (stays hidden until the operator rescopes the+ // WRITE source, not the read grant).+ const fedNamed = await errFor(ctxRemote(['sources_admin'], ['default', 'mcp-remove-fenced']), 'mcp-remove-fenced');+ expect(fedNamed.code).toBe('not_found');+ expect(existsSync(row.local_path)).toBe(true);+ // ...while that very grant still READS it: sources_status keeps the+ // read ladder, so the two helpers diverge exactly on write authority.+ const fedStatus = (await findOp('sources_status').handler(ctxRemote(['read'], ['default', 'mcp-remove-fenced']), { id: 'mcp-remove-fenced' })) as any;+ expect(fedStatus.id).toBe('mcp-remove-fenced');+ // A bound caller with a federated grant but NO write source removes nothing.+ const noWrite = await errFor(withoutSourceId(ctxRemote(['sources_admin'], ['mcp-remove-fenced'])), 'mcp-remove-fenced');+ expect(noWrite.code).toBe('not_found');+ // Anti-enumeration: a genuinely missing id yields the IDENTICAL message+ // after id substitution, so the error cannot be used as an existence oracle.+ const missing = await errFor(ctxRemote(['sources_admin']), 'no-such-source');+ expect(missing.code).toBe('not_found');+ expect(fed.message.replaceAll('mcp-remove-fenced', '<id>'))+ .toBe(missing.message.replaceAll('no-such-source', '<id>'));+ // `remote: undefined` is untrusted too (fail-closed), same fence.+ const undef = await errFor({ ...ctxRemote(['sources_admin']), remote: undefined as any }, 'mcp-remove-fenced');+ expect(undef.code).toBe('not_found');+ // The source and its clone are untouched.+ expect(existsSync(row.local_path)).toBe(true);+ const local: OperationContext = { ...ctxRemote(['read']), remote: false };+ const status = (await findOp('sources_status').handler(local, { id: 'mcp-remove-fenced' })) as any;+ expect(status.id).toBe('mcp-remove-fenced');+ // Trusted local CLI keeps the full operator view and can remove it.+ const result = (await removeOp.handler(+ { ...ctxRemote(['sources_admin']), remote: false },+ { id: 'mcp-remove-fenced', confirm_destructive: true },+ )) as any;+ expect(result.clone_removed).toBe(true);+ expect(existsSync(row.local_path)).toBe(false);+ });+ });});// ---------------------------------------------------------------------------@@ -333,6 +428,132 @@ describe('sources_* scope enforcement (simulates serve-http gate)', () => {// remote URLs, not arbitrary host-path writes).// ---------------------------------------------------------------------------+// The READ scope→allowed→not_found ladder sources_status uses (#4433 wave-L;+// sources_remove moved to the write twin below), as a unit: the four caller+// shapes that decide it.+describe('assertSourceInCallerScope (shared confinement helper)', () => {+ const base = (): OperationContext => ({+ engine: engine as any,+ config: { engine: 'pglite' } as any,+ logger: { info() {}, warn() {}, error() {} },+ dryRun: false,+ remote: true,+ sourceId: 'alpha',+ });++ test('scalar-bound remote caller: only its own source passes; anything else is not_found', () => {+ const ctx = base();+ expect(() => assertSourceInCallerScope(ctx, 'alpha')).not.toThrow();+ let err: unknown;+ try { assertSourceInCallerScope(ctx, 'beta'); } catch (e) { err = e; }+ expect(err).toBeInstanceOf(OperationError);+ expect((err as OperationError).code).toBe('not_found');+ expect((err as OperationError).message).toBe('Unknown source: beta');+ });++ test('federated grant wins over the scalar bind: every granted id passes, the bound-but-ungranted one does not', () => {+ const ctx: OperationContext = { ...base(), auth: { ...ctxRemote(['read'], ['beta', 'gamma']).auth! } };+ expect(() => assertSourceInCallerScope(ctx, 'beta')).not.toThrow();+ expect(() => assertSourceInCallerScope(ctx, 'gamma')).not.toThrow();+ expect(() => assertSourceInCallerScope(ctx, 'alpha')).toThrow('Unknown source: alpha');+ expect(() => assertSourceInCallerScope(ctx, 'ghost')).toThrow('Unknown source: ghost');+ });++ test('remote: undefined is untrusted (fail-closed) — confined exactly like remote: true', () => {+ const ctx = { ...base(), remote: undefined as unknown as boolean };+ expect(() => assertSourceInCallerScope(ctx, 'alpha')).not.toThrow();+ expect(() => assertSourceInCallerScope(ctx, 'beta')).toThrow('Unknown source: beta');+ });++ test('trusted local (remote === false) passes unconditionally — even an id that exists nowhere', () => {+ const ctx = { ...base(), remote: false };+ expect(() => assertSourceInCallerScope(ctx, 'alpha')).not.toThrow();+ expect(() => assertSourceInCallerScope(ctx, 'beta')).not.toThrow();+ expect(() => assertSourceInCallerScope(ctx, 'does-not-exist')).not.toThrow();+ });+});++// The WRITE-authority twin sources_remove uses (O4-1): federation is read+// authority by contract, so the destructive op keys on the write source only.+describe('assertSourceInCallerWriteScope (destructive-op confinement helper)', () => {+ const base = (): OperationContext => ({+ engine: engine as any,+ config: { engine: 'pglite' } as any,+ logger: { info() {}, warn() {}, error() {} },+ dryRun: false,+ remote: true,+ sourceId: 'alpha',+ });+ const notFound = (ctx: OperationContext, id: string): void => {+ let err: unknown;+ try { assertSourceInCallerWriteScope(ctx, id); } catch (e) { err = e; }+ expect(err).toBeInstanceOf(OperationError);+ expect((err as OperationError).code).toBe('not_found');+ expect((err as OperationError).message).toBe(`Unknown source: ${id}`);+ };++ test('scalar-bound remote caller: only its write source passes; anything else is not_found', () => {+ const ctx = base();+ expect(() => assertSourceInCallerWriteScope(ctx, 'alpha')).not.toThrow();+ notFound(ctx, 'beta');+ notFound(ctx, 'ghost');+ });++ test('a federated READ grant naming the id confers nothing — the read helper passes it, the write helper does not', () => {+ const ctx: OperationContext = { ...base(), auth: { ...ctxRemote(['sources_admin'], ['beta', 'gamma']).auth! } };+ // Read ladder (sources_status): granted ids pass, the bound-but-ungranted write source does not.+ expect(() => assertSourceInCallerScope(ctx, 'beta')).not.toThrow();+ expect(() => assertSourceInCallerScope(ctx, 'alpha')).toThrow('Unknown source: alpha');+ // Write ladder (sources_remove): ONLY the write source passes.+ expect(() => assertSourceInCallerWriteScope(ctx, 'alpha')).not.toThrow();+ notFound(ctx, 'beta');+ notFound(ctx, 'gamma');+ notFound(ctx, 'ghost');+ });++ test('write authority is ctx.auth.sourceId, falling back to ctx.sourceId (same notion as delete_page/restore_page)', () => {+ const ctx: OperationContext = { ...base(), auth: { ...ctxRemote(['sources_admin']).auth!, sourceId: 'beta' } };+ expect(() => assertSourceInCallerWriteScope(ctx, 'beta')).not.toThrow();+ notFound(ctx, 'alpha');+ });++ test('bound by a federated grant with NO write source: nothing is removable', () => {+ const ctx: OperationContext = withoutSourceId({ ...base(), auth: { ...ctxRemote(['sources_admin'], ['alpha', 'beta']).auth! } });+ notFound(ctx, 'alpha');+ notFound(ctx, 'beta');+ // An empty federated array is still a binding (fail-closed), not "unbound".+ const empty: OperationContext = withoutSourceId({ ...base(), auth: { ...ctxRemote(['sources_admin']).auth!, allowedSources: [] } });+ notFound(empty, 'alpha');+ });++ test('the __all__ sentinel is never a write source for an untrusted caller', () => {+ const ctx: OperationContext = { ...base(), sourceId: '__all__' };+ notFound(ctx, 'alpha');+ notFound(ctx, '__all__');+ });++ test('UNBOUND remote caller (no write source, no federated grant) keeps full authority — unchanged', () => {+ const ctx: OperationContext = withoutSourceId(base());+ expect(() => assertSourceInCallerWriteScope(ctx, 'alpha')).not.toThrow();+ expect(() => assertSourceInCallerWriteScope(ctx, 'anything')).not.toThrow();+ const withAuth: OperationContext = { ...ctx, auth: { ...ctxRemote(['sources_admin']).auth! } };+ expect(() => assertSourceInCallerWriteScope(withAuth, 'anything')).not.toThrow();+ });++ test('remote: undefined is untrusted (fail-closed) — confined exactly like remote: true', () => {+ const ctx = { ...base(), remote: undefined as unknown as boolean };+ expect(() => assertSourceInCallerWriteScope(ctx, 'alpha')).not.toThrow();+ notFound(ctx, 'beta');+ });++ test('trusted local (remote === false) passes unconditionally', () => {+ const ctx = { ...base(), remote: false };+ expect(() => assertSourceInCallerWriteScope(ctx, 'alpha')).not.toThrow();+ expect(() => assertSourceInCallerWriteScope(ctx, 'beta')).not.toThrow();+ expect(() => assertSourceInCallerWriteScope(ctx, 'does-not-exist')).not.toThrow();+ });+});+describe('sources_add — remote callers ignore path/clone_dir overrides', () => {test('remote sources_admin: clone_dir override is silently ignored', async () => {await withEnv({ GBRAIN_HOME, PATH: fakePath() }, async () => {diff --git a/test/supervisor-build-worker-args.test.ts b/test/supervisor-build-worker-args.test.tsindex 542946a206..5530179625 100644--- a/test/supervisor-build-worker-args.test.ts+++ b/test/supervisor-build-worker-args.test.ts@@ -51,3 +51,26 @@ describe('buildWorkerArgs', () => {.not.toContain('--job-isolation');});});++describe('buildWorkerArgs — --allow-shell-jobs pass-through', () => {+ // The shell-handler opt-in travels as a FLAG, not only as env: the worker's+ // cwd-.env quarantine drops GBRAIN_ALLOW_SHELL_JOBS whenever a .env in the+ // worker's cwd assigns it, so an env-only handoff could silently disable+ // shell jobs on a supervised worker.+ test('appends --allow-shell-jobs when allowShellJobs is true', () => {+ expect(buildWorkerArgs({ concurrency: 2, queue: 'default', maxRssMb: 0, allowShellJobs: true }))+ .toEqual(['jobs', 'work', '--concurrency', '2', '--queue', 'default', '--allow-shell-jobs']);+ });++ test('omits --allow-shell-jobs when false or undefined (argv byte-identical)', () => {+ expect(buildWorkerArgs({ concurrency: 1, queue: 'q', maxRssMb: 0, allowShellJobs: false }))+ .toEqual(['jobs', 'work', '--concurrency', '1', '--queue', 'q']);+ expect(buildWorkerArgs({ concurrency: 1, queue: 'q', maxRssMb: 0 }))+ .not.toContain('--allow-shell-jobs');+ });++ test('composes after --nice / --job-isolation in a stable order', () => {+ expect(buildWorkerArgs({ concurrency: 2, queue: 'default', maxRssMb: 0, nice_requested: 5, jobIsolation: 'process', allowShellJobs: true }))+ .toEqual(['jobs', 'work', '--concurrency', '2', '--queue', 'default', '--nice', '5', '--job-isolation', 'process', '--allow-shell-jobs']);+ });+});diff --git a/test/transcript-render.test.ts b/test/transcript-render.test.tsindex c6c90c170b..c757641ee8 100644--- a/test/transcript-render.test.ts+++ b/test/transcript-render.test.ts@@ -298,3 +298,146 @@ describe('part splitting [embed-skip is the binding limit]', () => {expect(matches).toHaveLength(2);});});++// ── Format-based redaction on every persisted surface ───────────────────────+//+// Synthetic, runtime-joined values (>= 2 fragments each, never one literal in+// committed bytes). Constant names keep scanner keywords away from the `=`.+const SEEDED_JWT = [+ 'eyJhbGciOiJIUzI1NiJ9',+ 'eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaWF0IjoxNzAwMDAwMDAwfQ',+ 'c2lnbmF0dXJlLXBsYWNlaG9sZGVyLTAwMDA',+].join('.');+const SEEDED_SID = ['AC', '0123456789abcdef', '0123456789abcdef'].join('');+const SEEDED_STRIPE = ['sk_live_', '4eC39HqLyjWDarjtT1zdp7dc'].join('');+const SEEDED_GOOGLE = ['AIza', 'SyD1-Fake_Example0123456789abcdefGH'].join('');+const SEEDED_SENDGRID = ['SG', '.abcDEF123_ghiJKL456', '.mnoPQR789-stuVWX012'].join('');+const SEEDED_GITLAB = ['glpat-', 'Ab12Cd34Ef56Gh78Ij90Kl'].join('');+const SEEDED_NPM = ['npm_', 'Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56Qr78'].join('');+const SEEDED_OPAQUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');+const SEEDED_DB_URL = ['postgres://', 'dbuser', ':', 'p4ssw0rd', '@db.internal:5432/app'].join('');+const SEEDED_ENTROPIC = ['aB3xK9mQ', '2pR7sT1vW4yZ8bC5'].join('');++describe('redactSession — format-based classes reach text, speaker, title and raw meta', () => {+ test('a claude-code session seeded with unprefixed credential shapes persists placeholders only', () => {+ const dirty = session(+ [+ { role: 'user', timestamp: '2026-08-25T23:00:00.000Z', text: `deploy is failing. service role key ${SEEDED_JWT} and sid ${SEEDED_SID}` },+ {+ role: 'assistant',+ timestamp: '2026-08-25T23:00:01.000Z',+ speaker: `helper ${SEEDED_GOOGLE}`,+ text: `stripe ${SEEDED_STRIPE}, db ${SEEDED_DB_URL}, header Bearer ${SEEDED_OPAQUE}`,+ },+ { role: 'user', timestamp: '2026-08-25T23:00:02.000Z', text: `env has SMTP_TOKEN=${SEEDED_ENTROPIC} set` },+ ],+ {+ harness: 'claude-code',+ sessionId: 'poc-0001',+ title: `deploy notes ${SEEDED_SENDGRID}`,+ raw: { cwd: `/tmp/${SEEDED_GITLAB}`, note: SEEDED_NPM, version: '2.1.0', count: 1 },+ },+ );+ const red = redactSession(dirty, { userPatternsPath: '/nonexistent' });++ const blob = JSON.stringify(red.session);+ for (const v of [+ SEEDED_JWT, SEEDED_SID, SEEDED_STRIPE, SEEDED_GOOGLE, SEEDED_SENDGRID,+ SEEDED_GITLAB, SEEDED_NPM, SEEDED_OPAQUE, SEEDED_ENTROPIC, 'p4ssw0rd',+ ]) {+ expect(blob).not.toContain(v);+ }++ const [m0, m1, m2] = red.session.messages;+ expect(m0.text).toBe('deploy is failing. service role key <REDACTED:jwt> and sid <REDACTED:twilio>');+ expect(m1.text).toContain('<REDACTED:stripe>');+ expect(m1.text).toContain('<REDACTED:db_url_credentials>db.internal:5432/app');+ expect(m1.text).toContain('Bearer <REDACTED:bearer>');+ expect(m1.speaker).toBe('helper <REDACTED:google_api_key>');+ // The transcripts lane opts into the high-entropy assignment rule.+ expect(m2.text).toBe('env has SMTP_TOKEN=<REDACTED:high_entropy_assignment> set');+ expect(red.session.meta.title).toBe('deploy notes <REDACTED:sendgrid>');+ expect(red.session.meta.raw!.cwd).toBe('/tmp/<REDACTED:gitlab_pat>');+ expect(red.session.meta.raw!.note).toBe('<REDACTED:npm_token>');+ expect(red.session.meta.raw!.version).toBe('2.1.0'); // benign strings untouched+ expect(red.session.meta.raw!.count).toBe(1);+ expect(red.redactionCount).toBeGreaterThanOrEqual(10);++ // The rendered page carries the same guarantee.+ const content = renderSessionParts(red).parts[0].content;+ for (const v of [SEEDED_JWT, SEEDED_SID, SEEDED_STRIPE, SEEDED_GOOGLE, SEEDED_OPAQUE, 'p4ssw0rd']) {+ expect(content).not.toContain(v);+ }+ expect(content).toContain('<REDACTED:jwt>');+ });++ test('a code-shaped assignment without digits is NOT redacted by the entropy rule (false-positive guard)', () => {+ const clean = session([+ { role: 'user', timestamp: '2026-08-25T23:00:00.000Z', text: 'credentials = DefaultAzureCredential()' },+ ]);+ const red = redactSession(clean, { userPatternsPath: '/nonexistent' });+ expect(red.session.messages[0].text).toBe('credentials = DefaultAzureCredential()');+ });+});++// ── Session-wide echo dictionary ─────────────────────────────────────────────+//+// redactSession plans every persisted field into ONE echo dictionary before+// applying any of them, so a bearer / high-entropy value claimed in one field+// is scrubbed where it recurs bare in ANY other field, in either order.+// Redacting fields independently shipped the cross-message echo. Echoes add+// no findings: redactionCount stays the number of CLAIMS.+describe('redactSession — the echo dictionary spans every field of the session', () => {+ const CLAUDE = { harness: 'claude-code', sessionId: 'echo-0001' } as const;++ test('a tool message carries the Bearer header, the assistant echoes the bare token in ANOTHER message: both scrubbed, count unchanged', () => {+ const two = session(+ [+ { role: 'user', timestamp: '2026-08-25T23:00:00.000Z', text: `tool output: curl -H "Authorization: Bearer ${SEEDED_OPAQUE}" https://api.example/v1` },+ { role: 'assistant', timestamp: '2026-08-25T23:00:01.000Z', text: `the token ${SEEDED_OPAQUE} expired; rotate it` },+ ],+ CLAUDE,+ );+ const red = redactSession(two, { userPatternsPath: '/nonexistent' });+ expect(red.redactionCount).toBe(1);+ expect(red.session.messages[0].text).toBe('tool output: curl -H "Authorization: Bearer <REDACTED:bearer>" https://api.example/v1');+ expect(red.session.messages[1].text).toBe('the token <REDACTED:bearer> expired; rotate it');+ const content = renderSessionParts(red).parts[0].content;+ expect(content).not.toContain(SEEDED_OPAQUE);+ expect(content.split('<REDACTED:bearer>').length - 1).toBe(2);+ });++ test('order does not matter: a bare echo in an EARLIER message than the claim is scrubbed too', () => {+ const reversed = session(+ [+ { role: 'assistant', timestamp: '2026-08-25T23:00:00.000Z', text: `retrying with ${SEEDED_OPAQUE} now` },+ { role: 'user', timestamp: '2026-08-25T23:00:01.000Z', text: `tool output: Authorization: Bearer ${SEEDED_OPAQUE}` },+ ],+ CLAUDE,+ );+ const red = redactSession(reversed, { userPatternsPath: '/nonexistent' });+ expect(red.redactionCount).toBe(1);+ expect(red.session.messages[0].text).toBe('retrying with <REDACTED:bearer> now');+ expect(red.session.messages[1].text).toBe('tool output: Authorization: Bearer <REDACTED:bearer>');+ });++ test('a high-entropy assignment in one message reaches its bare echoes in the title, a speaker label and raw metadata', () => {+ const spread = session(+ [+ { role: 'user', timestamp: '2026-08-25T23:00:00.000Z', speaker: `ops ${SEEDED_ENTROPIC}`, text: `see ${SEEDED_ENTROPIC} in the env` },+ { role: 'assistant', timestamp: '2026-08-25T23:00:01.000Z', text: `env has SMTP_TOKEN=${SEEDED_ENTROPIC} set` },+ ],+ { ...CLAUDE, title: `rotate ${SEEDED_ENTROPIC}`, raw: { note: SEEDED_ENTROPIC, count: 2 } },+ );+ const red = redactSession(spread, { userPatternsPath: '/nonexistent' });+ expect(red.redactionCount).toBe(1);+ expect(JSON.stringify(red.session)).not.toContain(SEEDED_ENTROPIC);+ expect(red.session.messages[0].text).toBe('see <REDACTED:high_entropy_assignment> in the env');+ expect(red.session.messages[0].speaker).toBe('ops <REDACTED:high_entropy_assignment>');+ expect(red.session.messages[1].text).toBe('env has SMTP_TOKEN=<REDACTED:high_entropy_assignment> set');+ expect(red.session.meta.title).toBe('rotate <REDACTED:high_entropy_assignment>');+ expect(red.session.meta.raw!.note).toBe('<REDACTED:high_entropy_assignment>');+ expect(red.session.meta.raw!.count).toBe(2);+ expect(renderSessionParts(red).parts[0].content).not.toContain(SEEDED_ENTROPIC);+ });+});diff --git a/test/workspace-push.serial.test.ts b/test/workspace-push.serial.test.tsindex 28fd96229a..035c2523c8 100644--- a/test/workspace-push.serial.test.ts+++ b/test/workspace-push.serial.test.ts@@ -247,6 +247,24 @@ describe('secret-scan gate', () => {expect(git(work, 'diff', '--cached', '--name-only')).toBe('');expect(readFileSync(join(work, 'payload.md'), 'utf-8')).toContain('SECRET_PLACEHOLDER');}, T);++ test('a connection string with an inline password blocks the push (db_url_credentials)', async () => {+ // Runtime-joined synthetic URL — no committed line carries the shape.+ const url = ['postgres://', 'dbuser', ':', 'p4ssw0rd', '@db.internal:5432/app'].join('');+ writeFileSync(join(work, 'infra.md'), `DATABASE_URL=${url}\n`);+ const before = commitCount(work);+ const r = await push();+ expect(r.status).toBe('blocked_secrets');+ expect(r.ok).toBe(false);+ expect(r.findings?.length).toBe(1);+ expect(r.findings?.[0]?.file).toBe('infra.md');+ expect(r.findings?.[0]?.pattern).toBe('db_url_credentials');+ expect(JSON.stringify(r).includes('p4ssw0rd')).toBe(false); // value never surfaces+ expect(commitCount(work)).toBe(before); // NOTHING committed+ // The documented escape hatch still works for a declared-safe value.+ writeFileSync(join(work, SCAN_ALLOW_FILENAME), `${r.findings![0]!.fingerprint}\n`);+ expect((await push()).status).toBe('pushed');+ }, T);});describe('secret-scan gate — fails CLOSED on unscannable staged blobs', () => {