Files
gbrain/CONTRIBUTING.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

18 KiB
Raw Blame History

Contributing to GBrain

Setup

git clone https://github.com/garrytan/gbrain.git
cd gbrain
bun install
bun test

Requires Bun 1.3.11 or newer, matching package.json.

Windows

bun run test, verify, ci:local and test:e2e all dispatch through bash, so the shell scripts under scripts/ must be checked out with Unix line endings. The root .gitattributes pins *.sh text eol=lf, which overrides the core.autocrlf=true that Git for Windows installs by default. A fresh clone is correct with no extra steps.

.gitattributes pins *.md text eol=lf for the same reason. The frontmatter readers anchor on a --- fence followed by a Unix line ending, so a CRLF checkout makes a well-formed document parse as having no frontmatter. That failure is silent: no error, the field just comes back empty.

If you cloned before either pin existed, your working copy still has the old Windows line endings. Bash will fail with $'\r': command not found, and frontmatter will read as absent. Refresh it once, from the repository root:

git rm --cached -r . -q
git reset --hard
bash -n scripts/run-unit-parallel.sh          # silence means bash can read the scripts
git ls-files --eol -- '*.md' | grep -cE 'w/(crlf|mixed)' # 0 means Markdown is clean

Every check:* entry in package.json invokes its script as bash scripts/<name>.sh rather than relying on the shebang, because bun on Windows cannot exec a .sh directly. Keep that prefix when you add a new shell-script check.

Project structure

src/
  cli.ts                  CLI entry point
  commands/               CLI-only commands (init, upgrade, import, export, etc.)
    doctor.ts             gbrain doctor façade (buildChecks/runDoctor/output)
    doctor/               Peeled doctor modules: checks/* bundles + tail clusters
    sync.ts               gbrain sync CLI + performSync/performFullSync
  core/
    operations.ts         Operation contract assembly (façade over ops/)
    ops/                  Contract types + security fences + the op domain modules
    engine.ts             BrainEngine interface
    engine-factory.ts     Engine factory (dynamic import of the configured engine)
    postgres-engine.ts    Postgres + pgvector implementation (façade)
    postgres-engine/      Narrow-deps engine modules (facts, takes, code-edges, salience)
    pglite-engine.ts      PGLite (embedded Postgres via WASM) implementation (façade)
    pglite-engine/        Narrow-deps engine modules (facts, takes, code-edges, salience)
    db.ts                 Connection management + schema loader
    import-file.ts        Import pipeline (chunk + embed + tags)
    sync-*.ts             Peeled sync clusters (cost-gate, git, anchor, lock, reconcile, status-report, ...)
    types.ts              TypeScript types
    markdown.ts           Frontmatter parsing
    config.ts             Config file management
    storage.ts            Pluggable storage interface
    storage/              Storage backends (S3, Supabase, local)
    supabase-admin.ts     Supabase admin API
    file-resolver.ts      MIME detection + content hashing
    migrate.ts            Migration helpers
    bootstrap/            Agent-bootstrap flow (interview, hooks, repo, verify)
    yaml-lite.ts          Lightweight YAML parser
    chunkers/             3-tier chunking (recursive, semantic, llm)
    search/               Hybrid search (vector, keyword, hybrid, expansion, dedup)
    embedding.ts          Embedding service (provider-routed; Voyage default)
  mcp/
    server.ts             MCP stdio server (generated from operations)
    http-transport.ts     HTTP MCP transport (OAuth, body caps)
    dispatch.ts           Op dispatch + scope enforcement + param redaction
    rate-limit.ts         Rate limiting
  schema.sql              Postgres DDL
skills/                   Fat markdown skills for AI agents
test/                     Unit tests (bun test, no DB required)
test/e2e/                 E2E tests (requires DATABASE_URL, real Postgres+pgvector)
  fixtures/               Miniature realistic brain corpus (16 files)
  helpers.ts              DB lifecycle, fixture import, timing
  mechanical.test.ts      All operations against real DB
  mcp.test.ts             MCP tool generation verification
  skills.test.ts          Tier 2 skill tests (requires OpenClaw + API keys)
docs/                     Architecture docs

Per-file invariants live in docs/architecture/KEY_FILES.md — read a file's entry before editing it.

Running tests

The canonical reference for test tiers, isolation rules, timing, and the E2E lifecycle is docs/TESTING.md. The short version:

# Inner edit loop (~8min full suite on a Mac dev box; single files in seconds)
bun run test                      # parallel 4-shard fan-out (memory-adaptive) + serial post-pass; PGLite snapshot default-on
bun test test/markdown.test.ts    # specific unit test

# Pre-push gate (50+ parallel checks + typecheck)
bun run verify

# Pre-merge sanity (everything CI runs)
bun run test:full                 # verify + parallel unit + slow + smart e2e

# Slow / serial / e2e in isolation
bun run test:slow                 # *.slow.test.ts only (cold-path correctness)
bun run test:serial               # *.serial.test.ts only (pooled per-file processes, heaviest-first)
bun run test:e2e                  # real-Postgres E2E (requires DATABASE_URL)

# E2E setup (Postgres with pgvector)
docker compose -f docker-compose.test.yml up -d
DATABASE_URL=postgresql://postgres:postgres@localhost:5434/gbrain_test bun run test:e2e

# Or use your own Postgres / Supabase
DATABASE_URL=postgresql://... bun run test:e2e

Heads-up: a bare bun test refuses to start while DATABASE_URL or GBRAIN_DATABASE_URL is set in your environment — some tests run destructive SQL against whatever those URLs point at. Unset the variable for unit runs (they need no database) or use the wrappers: the unit/slow runners strip the variables at their boundary, and bun run test:e2e opts in at its own. The refusal message walks you through it; details in docs/TESTING.md ("Database-URL run guard"). If you point bun run test:e2e at your own Postgres or Supabase, a second floor applies: the database name must carry "test" as a word segment (like gbrain_test above) or destructive tests refuse to run — opt a differently-named database in one-shot with GBRAIN_E2E_ALLOW_DB=<name>.

Use bun run verify before pushing. It runs 50+ guard checks in parallel (scripts/run-verify-parallel.sh), including: banned fork-name leaks (scripts/check-privacy.sh), JSON.stringify(x)::jsonb interpolation patterns (scripts/check-jsonb-pattern.sh), \r progress bleed to stdout (scripts/check-progress-to-stdout.sh), test-isolation rule violations (scripts/check-test-isolation.sh — see "Writing tests that survive the parallel loop" below), silent fallback to recursive chunking in the compiled binary (scripts/check-wasm-embedded.sh), stale admin-dashboard build artifacts (scripts/check-admin-build.sh), resolver drift on bundled skills (bun run check:resolver), and typecheck. The guard REGISTRY is scripts/guards-manifest.tsv, and scripts/guard-self-test.sh (also in verify) proves each self-tested scanner guard (selftest=yes in the manifest; coverage ratchets up from the todo rows) can actually fail by running it against known-bad fixtures — a new scripts/check-* guard must be registered in the manifest or the build fails. There is no check:all script; the trailing-newline, exports-count, and no-legacy-getconnection checks run in verify with everything else.

Writing tests that survive the parallel loop

bun run test shards 1000+ unit-test files across up to 4 worker processes, capping total concurrency (shards × intra-shard files) to available memory and re-running OOM-killed or externally-killed files serially before calling them failures (see docs/TESTING.md for the rescue-pass details and knobs). Files in the same shard share a process, so process-global state leaks between them. Four lint rules (scripts/check-test-isolation.sh, R1–R4) enforce isolation: no direct process.env mutation (use withEnv() from test/helpers/with-env.ts), no mock.module(...) outside *.serial.test.ts, and every new PGLiteEngine( goes inside the canonical beforeAll block with a paired afterAll(disconnect).

The full rules, the canonical PGLite block, the withEnv pattern, and the *.serial.test.ts quarantine policy live in docs/TESTING.md — read that before writing a new test file. Files that predate the rules are listed in scripts/check-test-isolation.allowlist; the allow-list MUST shrink over time — never add new entries.

Discrimination test — required for every fix (#3665)

A fix's test is only worth anything if it fails without the fix. A test that passes both ways is worse than no test: it inflates reviewer confidence, gets weighted into the CI shards forever, and keeps passing after a future refactor silently breaks the behavior. (An adversarial review pass found PRs where 7 of 8 new tests passed on master.)

Every PR that fixes behavior must fill the Discrimination test field in the PR template with the actual result of checking this:

Discrimination test: reverted <source file(s)> to <ref>, ran <test file> → N pass / M fail. Restored → all pass.

The helper does the whole dance in one command:

bash scripts/check-test-discriminates.sh <test-file> <source-file> [<source-file>...]

It reverts the source files to the pre-fix state (plain file copies, no git stash), runs the test file, requires at least one EXECUTED test to fail — exit ≠ 0 alone does not count, because a missing file or import crash also exits non-zero (exit 3, the vacuous-failure class) — restores, and prints the paste-ready field line. Exit 1 means the test passed with the fix reverted: tighten the assertions before asking for review.

Vacuous-assertion shapes to avoid (they recur):

  • asserting only exit ≠ 0 (a missing binary also exits non-zero);
  • asserting membership in a set that covers every reachable value (['warn','fail'] when those are the only outputs);
  • asserting a substring that would also appear in the broken output — assert parsed structure instead.

Relatedly: a test whose only assertion is a regex over readFileSync'd source text pins spelling, not behavior. New tests that read src/ text need a test-reads-source-ok: <why> comment (or a behavioral assertion alongside); test/test-reads-source-smell.test.ts enforces this for new files and ratchets the pre-existing list down.

bun run ci:local         # full gate: gitleaks + guards/typecheck + 4-shard parallel unit + E2E
bun run ci:local:diff    # gate with diff-aware E2E selector
bun run ci:select-e2e    # print which E2E files the selector would run

ci:local spins up four pgvector services plus a transaction-mode PgBouncer via docker-compose.ci.yml, runs everything PR CI runs plus the full E2E suite sharded 4 ways in parallel, then tears down. Named volumes keep the install warm across runs. Requires Docker (Docker Desktop, OrbStack, or Colima) and gitleaks on host (brew install gitleaks). Override the postgres host port with GBRAIN_CI_PG_PORT=5435 bun run ci:local if 5434 collides.

Fail-closed selector: an unmapped src/ change runs ALL E2E files. Hand-tune narrower mappings via scripts/e2e-test-map.ts.

PR-side security checks

Besides the test gate, PRs may trigger three security workflows: Semgrep CE SAST (every PR — blocking for findings new since the PR base, so a net-new issue fails the check while pre-existing findings never block an unrelated PR; scheduled/dispatch runs do a full-tree report-only scan), OSV-Scanner (only when package.json or bun.lock change), and actionlint (only when .github/workflows/** change). See SECURITY.md → "Automated security scanning" for details.

Building

bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts

Adding a new operation

GBrain uses a contract-first architecture. Add your operation to one domain module and it automatically appears in the CLI, MCP server, and tools-json:

  1. Add your operation to the matching domain module under src/core/ops/ (pages.ts, search.ts, takes.ts, jobs.ts, ... — define params, handler, cliHints there). src/core/operations.ts is the assembly façade that spreads every domain module into the single operations array: a new op in an existing domain needs no façade change; a brand-new domain module gets one spread line in operations.ts. Shared contract types live in src/core/ops/contract.ts, the security/scope fences in src/core/ops/context.ts.
  2. Add tests
  3. That's it. The CLI, MCP server, and tools-json are generated from operations.

For CLI-only commands (init, upgrade, import, export, files, embed, doctor, sync):

  1. Create src/commands/mycommand.ts
  2. Add the case to src/cli.ts
  3. Regenerate the flag registry: bun run build:flag-registry. The CLI rejects unknown flags before dispatch; each CLI-only command's legal flag set is derived from its source into src/core/cli-flag-registry.generated.ts. test/cli-flag-validation.test.ts pins registry freshness, drift, and consumption evidence (a safety flag like --dry-run may only be advertised if the command's code actually reads it), so a stale registry fails the build. At runtime a missing registry entry fails open — a forgotten regen never bricks a command. Rerun the regen whenever you add or remove a flag on an existing command, too.

Parity tests (test/parity.test.ts) verify CLI/MCP/tools-json stay in sync.

Adding a new engine

See docs/ENGINES.md for the full guide. In short:

  1. Create src/core/myengine-engine.ts implementing BrainEngine
  2. Add to the engine factory in src/core/engine-factory.ts
  3. Run the test suite against your engine
  4. Document in docs/

The original SQLite engine plan was superseded by PGLite (embedded Postgres 17 via WASM), which uses the same SQL dialect as Postgres and eliminates the need for a separate FTS5/sqlite-vss translation layer. See docs/ENGINES.md for the engine architecture and the rationale.

CONTRIBUTOR_MODE — turn on the dev loop

gbrain captures retrieval traffic so you can replay real queries against your code changes before merging. This is off by default (production users get a quiet brain, no surprise data accumulation). Contributors turn it on with one shell rc line:

# In ~/.zshrc or ~/.bashrc:
export GBRAIN_CONTRIBUTOR_MODE=1

That's it. Every query / search you (or agents pointed at your dev brain) run from that shell now writes a row to eval_candidates, and the replay tool has data to work against.

What CONTRIBUTOR_MODE actually does:

  • Turns on query/search capture into the local eval_candidates table. Without it the gate is closed and capture is a no-op.
  • That's all. PII scrubbing, retention, and replay are independent.

Resolution order (most explicit wins):

  1. eval.capture: true in ~/.gbrain/config.json → on
  2. eval.capture: false in ~/.gbrain/config.json → off
  3. GBRAIN_CONTRIBUTOR_MODE=1 → on
  4. otherwise → off

Quick check that capture is actually running:

gbrain query "anything" >/dev/null
psql $DATABASE_URL -c 'SELECT count(*) FROM eval_candidates'
# (or `gbrain doctor` — surfaces silent capture failures cross-process)

To disable capture even with the env var set, write {"eval": {"capture": false}} to ~/.gbrain/config.json — explicit config beats the env var both directions.

Running real-world eval benchmarks (touching retrieval code)

If your PR touches retrieval — search ranking, RRF fusion, embeddings, intent classification, query expansion, source boost, or the query / search op handlers — run gbrain eval replay against a snapshot of real traffic before merging. Requires CONTRIBUTOR_MODE (above) so you have captured rows to replay against.

Quick loop:

gbrain eval export --since 7d > baseline.ndjson    # snapshot before your change
# ... make your change ...
gbrain eval replay --against baseline.ndjson       # diff retrieval, get Jaccard@k

Three numbers come back: mean Jaccard@k between captured and current slug sets, top-1 stability, and mean latency Δ. The replay tool flags the worst regressions so you can eyeball whether the change is hurting real queries.

Trigger paths (rerun if your diff touches any of these):

  • src/core/search/hybrid.ts
  • src/core/search/source-boost.ts, sql-ranking.ts
  • src/core/search/query-intent.ts, expansion.ts, dedup.ts
  • src/core/embedding.ts
  • src/core/ops/search.ts (query / search op handlers)
  • src/core/postgres-engine.ts / pglite-engine.ts (searchKeyword / searchVector SQL)

See docs/eval-bench.md for the full guide including CI integration, hand-crafted NDJSON corpora (so a fresh checkout without captured data can still replay), and cost considerations. The NDJSON wire format is documented in docs/eval-capture.md.

For public benchmark coverage on top of replay, gbrain eval longmemeval <dataset.jsonl> runs LongMemEval against gbrain's hybrid retrieval. One in-memory PGLite per question, runtime-enumerated TRUNCATE between questions, ground-truth scoring via LongMemEval's published evaluate_qa.py. Use it alongside replay when changes affect retrieval quality on long-context conversational data — replay catches regressions on YOUR queries, LongMemEval catches them on a public set the benchmark community already cites. See the "Public benchmarks: LongMemEval" section in docs/eval-bench.md.

Shipping

Releases go through the /ship skill, never hand-rolled. The full release + contributor process (CHANGELOG voice, version-locations sync, PR conventions, community-PR-wave workflow) lives in docs/RELEASING.md. Community PRs are batched into release waves rather than merged one-by-one; contributor attribution stays attached via Co-Authored-By: trailers and every accepted contribution is credited in CHANGELOG.md.

Welcome PRs

  • Additional engine implementations (see docs/ENGINES.md)
  • Docker Compose for self-hosted Postgres
  • Additional migration sources
  • New enrichment API integrations
  • Performance optimizations