Files
gbrain/docs/integrations/qm-harness.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

12 KiB

qm (multi-user agent harness) — gbrain as the company brain

Connect gbrain to qm — the multiplayer agent harness where each employee and each channel gets an isolated agent scope — so every scope's agent can search and write one shared, indexed, isolation-enforced company brain. The same recipe fits any harness with per-person sandboxes that can run a CLI.

Shape: one central gbrain serve --http (OAuth 2.1) next to qm's core; the gbrain binary baked into qm's sandbox image as a thin client; one OAuth client per employee, read-fenced by source federation and write-fenced by bound_slug_prefixes. Zero qm code changes — everything lives in the qm deployment directory.

qm's native memory (per-scope notebook) stays as-is for fast per-turn recall. gbrain adds what qm doesn't have: semantic + hybrid search, cross-scope knowledge, entity graphs, and durable memory that outlives a scope.

Topology

gbrain concept qm concept
one brain (one Postgres/Supabase DB) the org
source agents (path-less, shared) all agent-written memory
slug prefix emp-<slug>/ in agents an employee's personal scope
slug prefix chan-<slug>/ in agents a channel/room scope
source org-wiki (git-backed, read-only) company docs
OAuth client qm-emp-<slug> one employee's agent identity

Isolation model:

  • Reads are source-granular, SQL-enforced (federated_read): every employee client reads agents + the read-only sources you grant.
  • Writes are slug-prefix-granular, server-enforced (bound_slug_prefixes): a client can only mutate pages under its own emp-<slug>/ and its channels' chan-<x>/ prefixes — on put_page, delete_page, restore_page, add_tag, remove_tag, add_link/remove_link, add_timeline_entry, revert_version and put_raw_data, plus the POST /ingest webhook route. Not by convention.
  • Every op that is not a plain read is denied unless allow-listed. Ops that write by a key other than a slug — extract_entities and extract_facts (which mutate people/* and companies/*), forget_fact (targets a fact by numeric id, across sources), ontology_propose, and the sources_admin pair sources_add/sources_remove — cannot be fenced by slug, so a bound client gets permission_denied at dispatch. The gate keys on "not a pure read", not on a list of scope strings, so a write op added later (or one carrying a bespoke scope) is denied until it is explicitly fenced and added to CLIENT_FENCED_WRITE_OPS (src/core/operations.ts). think is allow-listed because remote callers cannot persist from it; submit_agent because it enforces this same column itself.
  • Indirect write paths are gated too, not just the ops. put_page's facts backstop would otherwise extract entities from the page body and write fact rows (and a ## Facts fence on git-backed sources) onto people/* pages the caller never named — the same capability extract_facts is denied for, reached through an in-prefix write. It is skipped for bound clients. POST /ingest is refused outright: its handler bypasses the op layer, so enforceClientSlugFence never runs and a bound client could write any slug inside its granted source.

Known limitations — read these before you rely on the fence

The write fence is a write boundary within a source. It is not a privacy boundary, and it does not make every side effect prefix-clean:

  • The fence follows a delegated write. When a client with agent scope hands work to a subagent via submit_agent, that subagent runs under its own slug confinement rather than the parent's OAuth binding. Both confinements are enforced, including on the path where deduplication redirects a write onto an existing page: the redirected target is checked against whichever confinement the calling context actually carries, so delegation does not widen what a client can write.

  • add_link/remove_link fence the from endpoint only. A bound client can create an edge pointing AT a page it cannot write; the edge's context text surfaces in that page's backlinks and contributes to its search ranking. Fencing to would break legitimate cross-referencing into org-wiki, so this is deliberate — treat inbound-edge context as untrusted content, the same way you treat page bodies.

  • Reads are source-granular, never prefix-granular. Everyone entitled to a source can read every prefix in it. If a scope needs genuine read privacy, give it its own source.

  • put_page can create one reverse graph edge outside the fence. If a page body cites a code location (src/x.ts:42) and a code page for it exists in the same source, doc↔impl reconciliation adds an edge originating from that code page. It affects graph/backlink ranking, not page content. Unreachable in the layout above (the agents source is path-less and holds no code pages); it applies only if you point employee writes at a code-synced source.

  • Stored contradiction reports are temporarily local-only. find_contradictions returns stored findings only to trusted local callers without a source filter. Harness clients receive { contradictions: [], note } with an availability note. Other brain-wide read ops (get_recent_salience, find_anomalies, and sources_list/sources_status) honor the federated grant; sources_status answers not_found for an out-of-grant ID.

  • Reads touch last_retrieved_at on the pages they return, including pages in read-only sources. Freshness/usage signals are therefore writable-by-reading; nothing else about the page is.

  • POST /ingest writes land in the calling client's granted source. The write source is resolved server-side from oauth_clients.source_id; the caller-supplied X-Gbrain-Source-Id header does not route anything, so a client cannot choose its own write partition. A client registered without a source writes to default, and a write falls back to default if its source is unregistered, archived, or deleted mid-write (the job result reports this via source_fallback). If you point a webhook integration at this route, give its client an explicit --source so its captures do not accumulate in the brain's default source. Bound clients are still refused the route outright, because the slug fence cannot run on this path.

  • Tradeoff to state out loud: read isolation is per-source, so within the shared agents source every employee can read every prefix (including other employees' emp-*/). That matches qm's transparent-by-default, everything-audited posture. If you need hard read privacy for personal memory, give those employees their own write source instead of a prefix (one sources add emp-<slug> + --source emp-<slug> per client) and keep channel prefixes in agents via a second, channels-only client — at the cost of two credentials in that sandbox.

Host setup (the machine running qm's core, or any box its sandboxes can reach)

# 1. Engine: Postgres/Supabase. PGLite is single-process and cannot serve
#    many concurrent sandboxes.
gbrain init --supabase --embedding-model voyage:voyage-4-large

# 2. Modes + gates (publish_* default OFF and fail as silent 403s):
gbrain config set search.mode balanced
gbrain config set mcp.publish_skills true
gbrain config set mcp.publish_advisor true

# 3. Read-only org sources + first sync:
gbrain sources add org-wiki --path ~/brains/org-wiki
gbrain sync --all        # cron this

# 4. Serve over HTTP MCP (OAuth 2.1):
gbrain serve --http --bind 0.0.0.0 --port 3131 \
  --public-url https://brain.acme-example.com

Never hand sandboxes DATABASE_URL — direct DB access bypasses OAuth, source federation, and the write fence entirely.

Provision scopes from a roster

qm-harness-snippets/provision-scopes.sh converges the brain to a roster file (roster.example.tsv):

bash provision-scopes.sh roster.tsv --read-sources org-wiki
  • Creates the path-less agents source (agent-written memory needs no git clone; if the host has sync.repo_path configured, pages also write through to .sources/agents/ for git-backed durability).
  • Registers qm-emp-<slug> clients: --scopes "read write", --source agents, --federated-read agents,org-wiki, --bound-slug-prefixes emp-<slug>/,chan-<a>/,..., per-day budget.
  • Idempotent: re-run after every roster edit; existing clients are rescope-cliented in place (channel joins/leaves update the write fence without rotating secrets).
  • New client secrets land once in <roster>.new-credentials.tsv — deliver each row to its scope (qm keychain / one-time secret drop), then delete the file.

qm deployment directory

In the org's qm deployment repo (the directory qm init produced):

  1. Tool: copy qm-harness-snippets/tool.json to sandbox/tools/gbrain/tool.json and drop the compiled gbrain binary beside it (bun build --compile --no-compile-autoload-bunfig --outfile gbrain src/cli.ts, built for the 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; see the note below on why remote doctor cannot be used here).
  2. Skill: copy qm-harness-snippets/SKILL.md to sandbox/skills/gbrain/SKILL.md (edit slug conventions to taste).
  3. Ship it: qm sandbox build && qm sandbox publish && qm up.

Per scope, one-time (agent- or operator-run, credentials from the handoff):

gbrain init --mcp-only \
  --issuer-url https://brain.acme-example.com \
  --mcp-url https://brain.acme-example.com/mcp \
  --oauth-client-id gbrain_cl_... --oauth-client-secret gbrain_cs_...
gbrain whoami                       # must succeed

Use --oauth-client-secret, not GBRAIN_REMOTE_CLIENT_SECRET: an env-sourced secret is deliberately not written to ~/.gbrain/config.json (src/commands/init.ts), so with the env var alone every later command fails once it leaves scope — and qm's sandbox.secretEnv is org-wide, so there is no per-scope env to keep it in. With the flag, the credential lands in the config file on the scope's durable disk and this runs once per scope, ever.

gbrain remote doctor is not the health check here: run_doctor is an admin-scope op and these clients are read write on purpose. gbrain whoami is read-scope and reports the client's identity, source, and grants.

Verify isolation before rollout

From two differently-scoped sandboxes (or two thin-client configs):

# alice-example (bound to emp-alice-example/, chan-eng/):
gbrain put emp-alice-example/notes/test --content "mine"        # OK
gbrain put chan-eng/notes/test --content "shared"               # OK
gbrain put emp-bob-example/notes/test --content "not mine"      # permission_denied
gbrain put chan-product/notes/test --content "not my channel"   # permission_denied
gbrain search "test"                                            # sees agents + org-wiki only

Cost + operations

  • search.mode balanced (12K token budget, relational retrieval on) is the right default for a startup fleet; see docs/guides/search-modes.md for the cost matrix before changing it.
  • Budgets: --budget-usd-per-day is recorded on the client but only enforced on the submit_agent path (src/core/minions/budget-meter.ts), which these read write clients cannot reach — so it does not cap spend from ordinary search/put_page traffic. Treat runaway-agent containment as an open item: watch the admin SPA (/admin) and gbrain search stats, and cap at the model/harness layer.
  • Backfills on a live brain: gbrain embed --stale --pace (see Pace Mode in CLAUDE.md / docs/operations/spend-controls.md).

Deliberately deferred

  • qm MemoryService decorator (mirror notebook captures into gbrain, fan recall out and merge, volunteer_context push): needs a qm code change; today's integration is agent-initiated via the CLI + skill.
  • MCP-native attach: qm pins strictMcpConfig with only its in-process server, so gbrain's MCP-discovered brain-resident skillpacks don't reach qm agents; the sandbox skill above covers it.
  • Read-side prefix fencing (hard privacy for emp-*/ inside a shared source) — tracked upstream; the roster layout is forward-compatible with it.