Files
gbrain/docs/guides/agent-to-gbrain.md
Garry Tan 668b9bac30 v0.50.5.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins (#5130)
* v0.50.2.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins

Closes the critical- and high-severity items from six privately reported
advisories (GHSA-548g-mhxp-p66h, GHSA-42r8-3jfh-82vr, GHSA-62gp-q5hj-r9mv,
GHSA-q374-hhfh-f79x, GHSA-ghfq-gqmq-7fm4, GHSA-q5p9-qr3g-6v38). Squashed to a
single commit so no intermediate revision carries a test-fixture credential
shape through the gitleaks range gate.

Cluster A — OAuth consent gate (GHSA-548g / -42r8 / -62gp). The v0.50.0.0
owner-approval flow is pinned end to end against a real `serve --http
--enable-dcr` process and in-process: anonymous /authorize mints no code, a
forged code is rejected at /token, revoked clients are refused at grants.begin,
and OAuthGrants.begin() now caps awaiting-decision requests per client_id.

Cluster B — DCR scope ceiling (GHSA-q374 defect B, GHSA-548g fix #2).
registerClient rejects admin/sources_admin/users_admin/agent with HTTP 400 via
scope.ts:dcrScopeViolation; client_credentials DCR clients are read-only.
Remote sources_remove is source-fenced like sources_status. doctor's
oauth_client_scope_health flags privileged self-registered clients.

Cluster C — format-based secret detection (GHSA-ghfq). secret-scan.ts gains
jwt/aws(AKIA|ASIA)/google/stripe/sendgrid/twilio/supabase/gitlab/npm/hf plus
bearer and db_url_credentials catch-alls; the transcripts lane opts into the
digit-gated high-entropy rule; getRawData follows the page soft-delete on both
engines; delete_page --purge (local-CLI only) hard-removes a leaked page.

Cluster D — cwd .env quarantine (GHSA-q5p9). New env-trust.ts + cli-preflight.ts
drop a fixed list of code-loading / exec-target / posture-widening GBRAIN_*
variables when a working-directory .env assigns them (key-presence, since Bun
expands ${VAR}); the guardrails loader refuses cwd-relative and cwd-.env specs.

Release artifacts: VERSION/package.json/three plugin manifests bumped to
0.50.2.0; CHANGELOG entry (reporters credited); SECURITY.md, README, DEPLOY.md,
CHATGPT.md, guardrails.md, ENGINES.md and KEY_FILES updated; template + plugin
trees, skills.lock, flag registry and llms bundle regenerated; module-size
ceilings adjusted with per-row reasons; TODOS follow-ups filed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: pre-landing review fixes (v0.50.2.0 security wave)

Review cycle 1 of the ship: 6 specialists + red team + coverage audit.

Security / red team:
- env-trust: parse .env with Bun's line grammar (bare CR terminates a line;
  BOM/U+2028 cannot hide an assignment); protect the loader / git / node /
  proxy / AI-CLI variable families a checkout could plant for the programs
  gbrain spawns; cli-preflight re-execs gbrain once with the sanitized
  environment so git, the agent CLI and workers inherit the clean view;
  cwd == ~/.gbrain no longer quarantines the operator's own .env.
- guardrails: GBRAIN_GUARDRAILS_MODULE accepts only absolute or ~/ paths
  (a package name resolves from the cwd's node_modules).
- secret-scan: bounded db_url_credentials quantifiers + per-pattern
  prechecks (linear on long lines), windowed previews that redact every
  sibling span, single-pass longest-first replacement.
- TODOS: follow-up entries reworded to the functional level.

API contract / maintainability:
- delete_page purge: remote callers get permission_denied; a purged
  response always carries write_through; get_raw_data description states
  the soft-delete follow; includeDeleted narrowed to the getRawData
  signature; client_credentials gate evaluated before the DCR ceiling;
  doctor privileged set derived from the scope registry; sources_remove /
  sources_status share assertSourceInCallerScope; shell-job opt-in reaches
  --job-isolation process children as --allow-shell-jobs; stale help copy.
- transcripts ingest: raw-metadata compare uses canonical JSON (JSONB key
  order made every healthy re-run rewrite unchanged rows).

Coverage audit: 5 new test files + 4 extended (25 cases), plus RED-verified
pins for every fix above. Docs/KEY_FILES/CHANGELOG/SECURITY updated; llms
bundle, flag registry, tool catalog, structural suites regenerated;
module-size rows adjusted with reasons.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 2 (v0.50.2.0 security wave)

Re-exec redesign (security + red team + adversarial findings):
- cli-preflight re-runs gbrain from an empty temporary directory so the
  sanitized child never reloads the hostile .env: dropped keys are absent,
  never carried as '' (git and the dynamic loader presence-check
  GIT_SSL_NO_VERIFY / LD_TRACE_LOADED_OBJECTS; '' broke git ident).
- The re-run marker is JSON {cwd, neutral} honoured only when the process
  provably started in that empty directory — a marker planted via a cwd
  .env is ignored (the ppid-keyed marker was forgeable under systemd/docker).
- SIGINT is delivered by the tty once (wrapper no longer forwards it);
  SIGTERM/SIGHUP forwarded; execArgv preserved under the dev runtime.
- Protected families widened: XDG config roots (git reads
  $XDG_CONFIG_HOME/git/config as global config), GNUPGHOME, TLS trust
  stores, EDITOR/VISUAL/PAGER, every provider endpoint variable, the
  GBRAIN_REMOTE_* / GBRAIN_DIRECT_DATABASE_URL redirects, and the marker.
- cwd dotenv parsed once per start; jobs start uses the same '1' literal.

secret-scan (cycle-2 findings):
- db_url_credentials password class only stops at whitespace, '@' and
  string delimiters again (unescaped / { } < > | ^ ` \ passwords redact);
  BEARER uppercase recognized; jwt / high_entropy_assignment / PEM body
  bounded (adversarial '-eyJ' / '_token' runs and header-only PEM texts
  were quadratic); incremental PEM line cursor; redactFindings rebuilds
  the text by span-splice in one pass (was O(unique values x text)).

Contract / docs:
- delete_page purge responses carry a residuals hint (git history, exports,
  compiled context, slug-keyed derived rows); CHANGELOG states a single
  truth for GBRAIN_GUARDRAILS_MODULE (absolute or ~/ only, listed under
  Changed with a migration note); SECURITY.md / KEY_FILES / docs guides /
  minion-orchestrator skill describe the new mechanism and the
  --allow-shell-jobs opt-in; TODOS follow-ups filed; test-reads-source
  marker on the hook spawn-shape test; new PEM fixtures fragmented.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 3 (v0.50.2.0 security wave)

- Compiled binaries: every `bun build --compile` invocation passes
  `--no-compile-autoload-bunfig`; new `scripts/check-compile-autoload.sh`
  guard (self-tested, in verify CHECKS) keeps it that way.
- cwd `.env` quarantine: `GBRAIN_DATABASE_URL`, `GBRAIN_OAUTH_RELAY_URL`,
  OpenSSL config/engine/module loaders, temp roots and HOME/USERPROFILE
  join the protected set; the neutral hop dir is realpath'd; signal
  handlers are installed before the spawn; non-tty wrappers forward SIGINT
  once; guardrails fail closed when a dropped GBRAIN_GUARDRAILS_MODULE had
  a value.
- secret-scan: PEM header-line cursor is O(text) on newline-free tails;
  bounded bearer echo pass redacts bare re-occurrences of claimed tokens.
- transcripts ingest: raw-metadata probe reads active rows only.
- Tests: afterAll cleanup, execArgv/SIGHUP/chdir-back pins, pty SIGINT,
  perf pins; docs/CHANGELOG/TODOS/KEY_FILES/SECURITY updated; llms +
  skills.lock + plugin trees regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 4 (v0.50.2.0 security wave)

Cross-model adversarial pass (Codex) + Claude verifier findings:
- env-trust: shell-startup / interpreter-home family (BASH_ENV, SHELLOPTS,
  PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH,
  BASH_FUNC_* prefix) protected; sh `ENV` deliberately excluded.
- cli-preflight: config-dir exemption refused when the cwd .env assigns
  GBRAIN_HOME/HOME/USERPROFILE; wrapper removes pre-existing signal
  listeners so its exit is always the child's; SIGINT forwarded only
  without a controlling terminal (/dev/tty probe); a dropped planted HOME
  is restored from the passwd home; script-mode runs warn once when the
  cwd bunfig.toml declares a top-level preload.
- secret-scan: overlapping matches redact the UNION of matched spans;
  echo pass covers bearer + high-entropy values (64 unique, <=512 chars)
  via per-value sweeps over unclaimed gaps only; planRedaction/
  applyRedaction share a session-wide echo dictionary in transcripts
  render.
- sources_remove keys on write authority (assertSourceInCallerWriteScope);
  federated read grants confer no removal right.
- delete_page --purge retries the tombstone's file removal and fails
  closed (storage_error) while the file remains.
- Docs: SECURITY.md quarantine example no longer uses the one key that
  refuses instead of re-running; KEY_FILES/CHANGELOG/TODOS updated; llms.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* v0.50.3.0 chore: re-bump the security wave to 0.50.3.0 (master claimed 0.50.2.0 in #5122)

Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header/date + TODOS
follow-up refs + bun.lock, template repo and plugin trees regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 5 — Codex structured-review gate (v0.50.3.0 security wave)

- cli-preflight: hop marker carries the wrapper pid; a verified re-run arms
  an unref'd 1 s watchdog and exits 137 (removing its neutral dir) when the
  wrapper is force-killed, so supervisor restarts never orphan a worker;
  relative path-bearing runtime flags (--preload/-r/--require/--import,
  --config/-c, --env-file, --tsconfig-override) are resolved against the
  original cwd before the hop.
- secret-scan: echo pass is a streaming leftmost-longest merge with O(values)
  retained state (Codex repro: 64 short claims + 2 MiB repetitive tail went
  from +233 MiB RSS / 1.4 s to +16 MiB / 140 ms); repetitive tails are now
  covered wall-to-wall.
- Docs: KEY_FILES, SECURITY.md, CHANGELOG; llms regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs: update project documentation for v0.50.3.0

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(ci): green the three failing checks on the v0.50.3.0 wave

- semgrep: six `nosemgrep` suppressions with justifications for the
  path-join/resolve and non-literal-RegExp taint heuristics on operator-
  controlled cwd/flag paths and compile-time pattern sources (no behaviour
  change).
- test (2): the two pty Ctrl-C pins ran the wrapper through `script -c`'s
  intermediate /bin/sh; on ubuntu-latest that is dash, which re-raises the
  pty's SIGINT on itself after the child exits (130) instead of relaying
  the child's 42. The pty command now `exec`s the wrapper so no shell stays
  in the foreground group; documented in a `ptyCommand` helper.
- Selected E2E: with --enable-dcr, OAuth discovery now advertises exactly
  the self-registration ceiling (`read write`) via
  `scopesSupportedForDiscovery`, so a connector that copies
  `scopes_supported` into /register succeeds (master's #5122 pin); without
  DCR the full operator list minus `agent` is unchanged. Sibling e2e
  assertions that expected privileged scopes on the DCR-enabled server
  updated; unit + PGLite e2e pins added; docs/TODOS/CHANGELOG/KEY_FILES
  updated; llms regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* v0.50.5.0 chore: re-bump the security wave to 0.50.5.0 (master claimed 0.50.4.0 in #5131)

Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header + TODOS follow-up
refs + bun.lock, template repo and plugin trees regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-15 21:40:59 -07:00

13 KiB

How a downstream agent should talk to gbrain

This guide is for authors of downstream agents (your OpenClaw, any downstream fork) that need to call gbrain operations from their own runtime. Reading this first will save you a debugging cycle: gbrain has two distinct surfaces, and which one you pick depends on the operation.

The two surfaces

                       ┌─────────────────────────────────────────────┐
                       │                gbrain process                │
                       │                                              │
   Agent (OpenClaw,    │  ┌──────────────────┐    ┌────────────────┐ │
   or any fork) ───────┼──▶  MCP ops surface  │    │  local-only    │ │
                       │  │ (HTTP + OAuth)    │    │  commands      │ │
                       │  │                   │    │                │ │
                       │  │  search, query,   │    │  sync, embed,  │ │
                       │  │  put_page,        │    │  extract,      │ │
                       │  │  get_page,        │    │  dream,        │ │
                       │  │  find_experts,    │    │  enrich, ...   │ │
                       │  │  ...              │    │                │ │
                       │  └──────────────────┘    └────────────────┘ │
                       │           ▲                       ▲          │
                       │           │                       │          │
                       │           │                       │          │
                       │     thin-client OAuth      shell-job `inherit:`│
                       │     (preferred for          (only path for   │
                       │      MCP-equivalent ops)    local-only work) │
                       └─────────────────────────────────────────────┘

The two surfaces are not interchangeable. Pick by op, not by preference.

Surface 1 — MCP ops over HTTP (thin-client + OAuth)

Use for any operation that has an MCP equivalent: search, query, put_page, get_page, find_experts, find_orphans, find_anomalies, get_recent_salience, find_trajectory, and so on. The canonical list is the set of ops in src/core/operations.ts whose localOnly flag is unset (or false).

Setup

The host runs gbrain as a long-lived HTTP server:

gbrain serve --http --port 3131

The packaged path is gbrain agent register (run on the brain host — it is a trusted local operation, never a delegation mechanism). One command mints a scoped OAuth client plus a 30-day access token AND prints the exact wiring block for the target harness:

gbrain agent register aurora-coder \
  --harness claude-code \
  --preset coding-agent \
  --federated-read proj-widget \
  --url https://brain.example.com/mcp

The raw primitive underneath is gbrain auth register-client (one-time, prints client_id + client_secret and nothing else — you do the token exchange and the harness wiring yourself):

gbrain auth register-client aurora-coder \
  --grant-types client_credentials \
  --scopes "read write"
# Prints client_id + client_secret one-time. Store securely.

The agent's runtime calls /mcp with a bearer token from client_credentials grant. Secrets stay in the gbrain serve process; the agent never sees DATABASE_URL or API keys.

Thin-client mode (gbrain init --mcp-only) gives the agent the same client-credentials wiring, plus the gbrain CLI itself routes MCP-eligible commands through the configured remote MCP. The agent can call gbrain search / gbrain query directly and the CLI does the OAuth dance.

Onboarding paths — the decision table

This is THE onboarding-paths table. Other docs link here; none copy it.

Path When to use Credential kind Print vs write Serve location
gbrain agent register <name> --harness <h> The packaged path: onboarding an agent harness (Claude Code, Codex, opencode, your OpenClaw) onto a shared brain. Presets (daily-driver, coding-agent), starter tool surface, 30-day token TTL, --reissue secret rotation. Scoped OAuth client + a minted access token (source-scoped, expiring) PRINTS the harness block (redacted unless --show-token); writes nothing to harness configs Runs ON the brain host against a remote-reachable gbrain serve --http; --url or --port required (a live PGLite serve blocks it by design — stop the serve first; a serve too old to enforce scoped tokens is refused — upgrade it, or pass --allow-old-serve to accept the risk)
gbrain connect <mcp-url> --token <t> You already hold a bearer token and want ONE coding agent pointed at a running serve, from any machine. Legacy bearer token (full-access unless minted with --scopes); --oauth variant for OAuth-capable connectors. /mcp verifies both kinds; a client status flag of needsAuth from an unauthenticated probe is not a bearer failure — see DEPLOY.md — Dual-mode auth Prints the add command by default; --install runs it Any machine; targets a remote gbrain serve --http
gbrain bootstrap harness Framework-spawned harnesses (claude -p / codex exec / opencode run) on the SAME box that hosts the brain; wires MCP registration + lifecycle hooks with receipts and mint-first token rotation. Legacy bearer token, minted per run and rotated by receipt WRITES managed config blocks (Claude Code user scope, codex TOML, opencode JSONC) + hooks Local loopback serve on the same box (non-loopback URL requires an explicit supplied token)
gbrain auth register-client <name> The raw primitive: custom flows — PKCE/authorization-code clients, bound submit_agent clients, slug-prefix write fences, provisioning scripts that parse output. Scoped OAuth client only (no token exchange, no TTL default beyond the server's) Prints client_id + client_secret one time; you do all wiring Credential is server-side state; run on the brain host

Why this is preferred for MCP ops

  • Secrets never leave the server process.
  • OAuth scopes give you read, write, admin separation — agent only gets what it needs.
  • Source-scoped tokens (--source dept-x on register-client) confine the agent to a specific source within a federated brain.
  • One audit surface (mcp_request_log) covers every op call uniformly.

Surface 2 — local-only work via shell-job inherit:

Two mechanisms keep local-only work off the remote surface, and they operate at different layers:

  • Op layer: operations flagged localOnly: true in src/core/operations.ts are filtered out of the HTTP MCP surface entirely — a remote caller never sees them.
  • CLI layer: on a thin-client install (remote MCP configured, no local engine), commands that require a local engine or the local filesystem are refused at dispatch with a pinpoint hint naming the closest alternative. The authoritative set is THIN_CLIENT_REFUSED_COMMANDS in src/cli.ts — read it there rather than trusting any list copied into a doc; it covers sync, embed, extract, dream, enrich, serve, config, and a couple dozen more.

Notable non-members: doctor is NOT refused on a thin client — it reroutes to an outbound-HTTP probe set (src/core/doctor-remote.ts); bootstrap and hook are engine-free and work on any install shape.

For refused commands, the agent cannot route through HTTP MCP. The path is to run gbrain as a CLI subprocess. The recommended pattern is to submit the subprocess as a shell job to the gbrain Minions worker so retry / backoff / DLQ / audit trail all come for free.

Setup

gbrain jobs submit shell --params '{
  "cmd": "gbrain sync --skip-failed && gbrain embed --stale",
  "cwd": "/data/gbrain",
  "inherit": ["database_url"]
}'

The inherit: ["database_url"] field tells the worker to look up database_url from its loadConfig() and inject the value into the child env as GBRAIN_DATABASE_URL. The DB row in minion_jobs.data carries the names only — inherit: ["database_url"] — never the value. See minions-shell-jobs.md#secrets for the full validation rules and error catalog.

Why this is preferred over writing secrets into env: per-job

  • Passing env: { GBRAIN_DATABASE_URL: "postgresql://..." } per job would land the URL plaintext in minion_jobs.data and the shell-audit JSONL — visible to anyone with brain-DB read access (or a brain dump, or a shared brain via mounts). Pre-enqueue validation rejects it; the error message names inherit: ["database_url"] as the replacement.

Worker setup (one-time, per host)

The agent's host needs a worker that processes shell jobs:

# One-shot inline execution (PGLite or Postgres):
gbrain jobs submit shell --params '{...}' --follow

# Persistent worker (Postgres only — PGLite uses --follow inline):
gbrain jobs work --allow-shell-jobs        # or: GBRAIN_ALLOW_SHELL_JOBS=1 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) 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 table

Operation Surface Why
search / query HTTP MCP via thin-client Has MCP op; OAuth-scoped.
get_page / list_pages HTTP MCP Same.
put_page HTTP MCP Same; respects subagent allow-list when applicable.
find_experts / find_orphans HTTP MCP Same.
sync / embed / extract Shell job + inherit: Thin-client refused; needs local engine + FS.
dream Shell job + inherit: Thin-client refused; synthesis runs on the host.
doctor Run directly (any install) Not refused: thin clients get the remote probe set.
autopilot Run as a daemon directly on the host Long-lived, not job-shaped.
init / config One-time host setup Operator action, not agent action.
  • Prefer inherit: for secrets you don't want in the row. Names land in minion_jobs.data; values resolve at child-spawn from the worker's config. If a brain DB ever traverses a trust boundary, secrets stay out.
  • Free-form names. inherit: accepts any snake_case config-key on your worker — database_url, anthropic_api_key, openai_api_key, openrouter_api_key, voyage_api_key, groq_api_key, zeroentropy_api_key, or any custom field you stuff into ~/.gbrain/config.json. The agent picks what it needs.
  • env: still works for non-secret values, or for cases where you WANT the value in the row (e.g. an opaque correlation token your audit flow needs to read back later). The validator doesn't second-guess you.
  • Never try to route a refused command through a thin client. The CLI refuses it at dispatch with a hint. Use shell-job + inherit: (for secrets) or env: (for non-secrets) on the host instead.
  • Push-based context. Beyond request/response ops, MCP clients can receive volunteered context via the volunteer_context op — see push-context.md.

Migration: from env:-passed secrets

If your agent submits shell jobs that pass secrets via env::

// Rejected at submit: the URL would persist in minion_jobs.data plaintext.
{
  "cmd": "gbrain sync --skip-failed",
  "cwd": "/data/gbrain",
  "env": { "GBRAIN_DATABASE_URL": "postgresql://..." }
}

Switch to (recommended):

// Name in row, value resolved at child-spawn from worker config.
{
  "cmd": "gbrain sync --skip-failed",
  "cwd": "/data/gbrain",
  "inherit": ["database_url"]
}

Make sure the worker host has database_url configured (either via gbrain config set database_url <value> — file-plane routed, so it lands in the ~/.gbrain/config.json the worker's loadConfig() reads and works even when the DB is unreachable — or via GBRAIN_DATABASE_URL / DATABASE_URL env on the worker process). If the worker can't resolve the key, the validator rejects the job at submit time with a paste-ready hint.