Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.13.0 feat(auth): the shared brain — agent register, scoping presets, multi-agent continuity + isolation proofs (#4238)

Garry Tanb57bcd8f601d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 7a91793c7e..878700204b 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.12.3",
+ "version": "0.46.13.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.json
index 674f8fe58a..1796eff804 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.12.3",
+ "version": "0.46.13.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/e2e.yml b/.github/workflows/e2e.yml
index dc9ed47876..3e7dee0b21 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -121,7 +121,7 @@ jobs:
needs: e2e-cache-check
if: needs.e2e-cache-check.outputs.hit != 'true' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
- timeout-minutes: 20
+ timeout-minutes: 30
services:
postgres:
image: pgvector/pgvector:pg16
@@ -164,6 +164,16 @@ jobs:
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
+ - name: Run multi-agent serve suite
+ # cathedral-6 (T7): multi-agent continuity + isolation over a real
+ # `gbrain serve --http`. Own invocation line (engine-parity
+ # precedent): the file spawns two serves on fixed ports
+ # (19133/19134) and SIGKILLs one mid-hammer — never fold it into the
+ # shared-process tier1 line above. Named files only, no glob.
+ run: bun test --timeout=60000 test/e2e/serve-http-multi-agent.test.ts
+ env:
+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
tier2:
name: Tier 2 (LLM Skills)
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 51a09d921b..a85e2e98fa 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.12.3 -->
+<!-- gbrain-runbook-stamp: 0.46.13.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4dd47804a9..2990b58d2b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,87 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.13.0] - 2026-08-16
+
+**One brain can now safely serve many agents.** `gbrain agent register` mints
+a scoped OAuth client and a working access token in one command and prints the
+exact wiring for your harness — a daily-driver agent, a coding agent, and a
+teammate's agent all share the same institutional memory, each seeing only
+what its token grants. This is the shared-brain wave (cathedral 6): the
+multi-user core the brain always had, finally packaged for multiple agents.
+
+### Added
+- `gbrain agent register <name> --harness claude-code|codex|opencode|openclaw`
+ — mints a scoped OAuth client, writes a real 30-day token TTL (the server
+ default is one hour — a printed "long-lived" config used to die silently),
+ and prints a paste-ready block per harness. `--json` is a stable machine
+ contract (`schema_version: 1`) with credential redaction unless
+ `--show-token`; typed failure envelopes for every refusal.
+- Presets that stay honest to the scoping model: `daily-driver` (read-broad
+ via a registration-time snapshot of your sources — other agents' workspace
+ scratch sources excluded, grant one explicitly to share it — starter tool
+ surface) and `coding-agent` (write-isolated `<name>-workspace` source,
+ requires the project sources it may read). Explicit flags always win;
+ neither preset can grant operator scopes. Surface tiers land through the
+ audited operator path.
+- `--reissue <client-id>` rotates a client secret and reprints the wiring —
+ outstanding tokens stay valid until expiry, and the output says so.
+- Cross-agent memory continuity: `recall` now honors federated read grants,
+ so a fact one agent saved in a shared source is recallable by every agent
+ granted that source (world-visible facts only; private stays local).
+- The company-brain tutorial gains a "many agents, one brain" recipe, and
+ `docs/guides/agent-to-gbrain.md` carries the single decision table for the
+ four onboarding paths. `gbrain auth clients` now shows each client's write
+ source and federated reads; a new doctor check surfaces dangling read
+ grants and orphaned empty workspace sources (a workspace holding only
+ facts counts as data, never orphaned).
+- `gbrain auth register-client --token-ttl <seconds>` for per-client token
+ lifetimes from the CLI.
+
+### Changed
+- Registering on a thin client or against a live PGLite serve is refused
+ up front with exact guidance (previously: dead credentials in a scratch
+ brain, or a silent 30-second lock hang). Registration also probes the
+ target serve and refuses one too old to enforce the token's scope grant —
+ upgrade the serve, or pass `--allow-old-serve` to accept the risk (an
+ unreachable serve stays a warning).
+- The admin register API validates source existence, archived state, and
+ token TTL bounds with structured 400s, refuses duplicate client names
+ (409), and composes the same registration core as the CLI — atomically,
+ under the same name lock — so the two paths can never drift.
+- Deleting or purging a source that an OAuth client still references is
+ refused with the exact revoke commands — including clients that were
+ revoked-but-retained, which still block deletion at the database level.
+ Recurring maintenance now skips such sources instead of aborting entirely,
+ and a source's git scaffolding is torn down only after the deletion
+ commits, so a refused delete leaves it fully intact.
+- Multi-agent write throughput: same-slug writes in different sources no
+ longer serialize on each other (source-scoped advisory locks, with an
+ eleven-site audit documenting every intentionally-global lock). Restart
+ your serve and upgrade CLIs together when picking this up.
+- Brains that predate the scoped-client schema are refused at registration
+ with a one-line migration command instead of failing mid-transaction.
+
+### Fixed
+- `recall --supersessions` now applies the same world-only visibility filter
+ as every other remote read arm, and federated recall merges each arm on its
+ own semantic timestamp.
+- `gbrain agent run -- --help` submits the literal prompt instead of printing
+ help; `gbrain agent … --help` answers on a machine with no brain configured.
+
+### Infrastructure
+- A 12-case end-to-end suite proves continuity, isolation, write-concurrency,
+ chaos-kill integrity, and secret rotation over a real HTTP serve with real
+ tokens, wired as its own CI step. BrainBench gains the first fixture
+ exercising the leak detector's non-default active-source arm. 100+ new
+ unit tests pin the registration contract byte-for-byte.
+
+To take advantage of v0.46.13.0: on the brain host, run
+`gbrain agent register <name> --harness <your-harness> --preset coding-agent
+--federated-read <project-sources> --url <your-serve-url>` and paste the
+printed block into your agent. Existing setups keep working unchanged; if
+`gbrain doctor` flags dangling read grants or orphaned workspace sources, the
+message names the exact fix.
## [0.46.12.3] - 2026-08-16
**Supply-chain hardening for how gbrain updates and how community code lands.**
diff --git a/README.md b/README.md
index 621b15d57b..d8bb6caf7b 100644
--- a/README.md
+++ b/README.md
@@ -149,6 +149,8 @@ gbrain connect https://your-host/mcp --token gbrain_xxx --install
gbrain connect https://your-host/mcp --token gbrain_xxx --agent codex --install # Codex
```
+Onboarding a whole agent harness onto a shared brain? On the brain host, `gbrain agent register <name> --harness claude-code` mints a scoped OAuth client plus a 30-day token and prints the paste-ready wiring block — presets for daily-driver and write-isolated coding agents. The [onboarding decision table](docs/guides/agent-to-gbrain.md#onboarding-paths--the-decision-table) says which path fits.
+
**Brain-only install into another coding agent** (Cursor, Claude Cowork, or anything that can fetch a URL and run shell commands) — paste the OpenClaw/Hermes block above (`INSTALL_FOR_AGENTS.md`); it installs the brain, skills, and dream cycle without the personal-agent identity layer. Tested with Codex, Claude Code, Claude Cowork, Cursor, and AlphaClaw.
**[→ Full walkthrough: give your coding agent a memory](docs/tutorials/connect-coding-agent.md)** — the memory-only paths end to end, plus the brain-first protocol you paste into `CLAUDE.md` / `AGENTS.md` and the four habits that make it actually change how you work.
diff --git a/TODOS.md b/TODOS.md
index a14048d192..db29c99152 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,59 @@
# TODOS
+## Multi-agent wave follow-ups (cathedral-6, `gbrain agent register`)
+
+- [ ] **P2 — archived sources keep previously-granted federated reads until
+ re-registration.** **What:** grants are validated at mint time only — a
+ client whose `federated_read` names a source that is archived AFTER
+ registration keeps reading it; there is no per-request archived-source
+ filtering and no grant invalidation on archive. **How:** this is a
+ platform-wide read-path decision affecting every federated op (recall,
+ search, entity, boundary verbs), not just recall — either fold an
+ `archived = false` join into the shared source-scope resolution or sweep
+ grants on `sources archive`; decide once, apply everywhere. **Where:**
+ `src/core/ops/context.ts` (sourceScopeOpts consumers), engine read paths,
+ `src/core/destructive-guard.ts` (archive lifecycle). **Effort:** M.
+ **Priority:** P2.
+- [ ] **P2 — federate the remaining read verbs across allowedSources.**
+ **What:** `recall` now honors a federated grant (every fact arm fans out
+ across `ctx.auth.allowedSources` and merges per-arm — see the `factSources`
+ ladder in `src/core/ops/facts.ts` as the pattern), but the rest of the
+ frozen-verb read surface stays scalar: `entity` (card assembly) and the
+ `context_pack`/`delta` ambient boundary verbs resolve `ctx.sourceId ?? 'default'`
+ only. A client granted N sources gets cross-source recall but single-source
+ entity cards and boundary packs — the surface splits silently. **How:** route
+ each through `sourceScopeOpts(ctx)` and fan out + merge like recall; for the
+ perf-clean shape push the source set INTO the engine query instead of
+ N round-trips — `findTrajectory`'s `sourceIds` ANY() branch is the
+ engine-level filter to mirror. **Where:** `src/core/ops/facts.ts`
+ (context_pack/delta), `src/core/verbs.ts` (entity),
+ `src/core/context/turn-context.ts`, engine fact/entity list APIs.
+ **Effort:** M. **Priority:** P2.
+- [ ] **P3 — E5: content-level BrainBench leak detection.** **What:** the
+ isolation gate asserts STRUCTURAL leak-absence (every result's source_id is
+ inside the caller's grant); a content-level arm would seed known-plaintext
+ canary strings into a foreign source and assert no returned text (snippets,
+ synthesized answers, graph annotations) contains them — catching join/
+ snippet/synthesis leak classes a source_id check can't see. **Where:**
+ `evals/brainbench/`. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — OpenClaw native remote-MCP register block, when upstream ships
+ remote support.** **What:** `gbrain agent register` renders the honest
+ thin-client CLI block for openclaw today (`openclawThinClientBlock` in
+ `src/core/mcp-registration.ts`) because OpenClaw has no native remote-MCP
+ client; when upstream ships one, add a native client-credentials wiring
+ block and demote the CLI block to the fallback. Blocked upstream. **Where:**
+ `src/core/mcp-registration.ts`, `src/commands/agent-register.ts`.
+ **Effort:** S. **Priority:** P3.
+- [ ] **P3 — E2: `gbrain agent list` / `gbrain agent revoke` conveniences.**
+ **What:** sugar over `gbrain auth clients` / `gbrain auth revoke-client`
+ filtered to agent-register-minted clients, with revoke-by-name. Motivation
+ is partly retired: `gbrain auth clients` now shows source_id +
+ federated_read columns, so the remaining value is the agent-only filter +
+ name-based revoke. Build only if operators ask. **Where:**
+ `src/commands/agent.ts`. **Effort:** S. **Priority:** P3.
+
+
+
## Security-sweep mitigation follow-ups (filed 2026-08-16)
- [ ] **P1 — `gbrain upgrade` binary lane returns success exit status on failure (autopilot false-success).** **What:** `runUpgrade`'s `binary` case logs every failure reason (`smoke_failed`, `download_failed`, `integrity_failed`, `integrity_unavailable`, `version_mismatch`, `replace_failed`) but never sets a non-zero CLI exit verdict, so callers see exit 0. **Why:** autopilot (`src/commands/autopilot.ts`) can read a false success, record "applied," relaunch, and then mark a transiently-unavailable version permanently bad — an amplification loop, now more reachable because `integrity_unavailable` fires on ordinary GitHub API rate limits. **Context:** PRE-EXISTING for the whole binary lane (not introduced by the v0.46.12.3 integrity work); surfaced by that PR's adversarial review with 2-model consensus. Fix needs care: distinguish hard-fail (`integrity_failed`/`version_mismatch` → exit non-zero, autopilot should NOT mark-bad on a security rejection) from transient (`integrity_unavailable` → retry, not a version fault), with autopilot-loop tests — hence its own PR, not a rushed rider. **Start:** `src/commands/upgrade.ts` binary case + `setCliExitVerdict` + `src/commands/autopilot.ts` upgrade handling.
@@ -986,12 +1040,10 @@ master before starting, several fixes landed independently).
into one UNION ALL query and extract a shared targets constant
(src/core/jsonb-integrity-targets.ts) consumed by both. Where:
`src/commands/doctor.ts` jsonbIntegrityCheck, `src/commands/repair-jsonb.ts`.
-- [ ] **P3 — register-client HTTP-level e2e (ship-review follow-up).** The
- source/federatedRead lane is covered by unit normalizers + a structural
- route pin; a DATABASE_URL-gated serve-http e2e (register with bindings →
- assert stored client via /admin/api/agents; invalid source → 400
- invalid_source) closes the wire-level gap. Where:
- `test/e2e/serve-http-oauth.test.ts`.
+- [x] **P3 — register-client HTTP-level e2e (ship-review follow-up).** ABSORBED
+ into the cathedral-6 multi-agent e2e suite on `garrytan/cathedral-6`
+ (test/e2e/serve-http-multi-agent.test.ts — wire-level register + scoped
+ round-trips + invalid source → 400).
- [ ] **P3 — get_chunks `__all__` sentinel narrows to 'default' (red-team,
Wave 3 territory).** `sourceScopeOpts` returns `{}` for a trusted local
`--source __all__` caller (documented "spans the brain"), but both engines'
@@ -3823,9 +3875,9 @@ contributor traps.
## MCP fix wave follow-ups (v0.34.1)
-- [ ] **v0.34.x: Source-scope `takes_*` ops (pre-existing leak surfaced during v0.34.1 adversarial review).** `takes_list`, `takes_search`, `takes_scorecard`, `takes_calibration` in `src/core/operations.ts:1248-1335` thread `ctx.takesHoldersAllowList` but never `ctx.sourceId`. An auth'd OAuth client scoped to `source_id='canon-a'` can call `takes_list --page_slug=foo` (slug in `canon-b`) and read takes attached to foreign-source pages. Pre-existing, not introduced by v0.34.1, but the wave was framed as "P0 source-isolation seal on the read path" and `takes_*` surfaces were missed. Fix: extend `TakesListOpts` in `src/core/engine.ts:186` with `sourceId?: string` + `sourceIds?: string[]`; thread `sourceScopeOpts(ctx)` at each op handler; engine `listTakes`/`searchTakes` filter via the `pages` JOIN.
+- [x] **v0.34.x: Source-scope `takes_*` ops (pre-existing leak surfaced during v0.34.1 adversarial review).** DONE — verified already fixed and pinned on `garrytan/cathedral-6`: all four `takes_*` ops route through `sourceScopeOpts(ctx)` at `src/core/ops/takes.ts:30/57/86/113`.
-- [ ] **v0.34.x: Extend `sourceScopeOpts(ctx)` to the 14 read-side ops PR #861 didn't touch.** `get_page`, `get_tags`, `get_links`, `get_backlinks`, `get_timeline`, `list_files`, `get_file`, and the four `takes_*` ops (above) still use the v0.31.8-era `const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {}` pattern. NOT a leak (scalar `ctx.sourceId` IS threaded), but federated_read (#876, `ctx.auth?.allowedSources`) is silently dropped. A "WeCare L3 dept" client gets correct federated results from `search`/`query`/`list_pages`/`traverse_graph`/`find_experts` but only sees its scalar `source_id` for `get_page`/`get_tags`/etc. Fix: route all 14 sites through `sourceScopeOpts(ctx)`.
+- [ ] **v0.34.x: Extend `sourceScopeOpts(ctx)` to the remaining read-side ops on the v0.31.8-era scalar pattern.** Most of the original list is fixed: `get_page`/`list_pages` route through `federatedSearchScope` (#3242), the four `takes_*` ops route through `sourceScopeOpts` (ops/takes.ts), and links/timeline-read/tag-set reads were converted (#2200). Still on `const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {}`: `ops/tags.ts:26,45`, `ops/timeline.ts:51`, `ops/raw-data.ts:27`, `ops/sync-status.ts:31`, `ops/admin.ts:158`, `ops/extraction.ts:83,187`, and `ops/pages.ts:252,775,808` (the pages.ts/extraction.ts arms are write-adjacent — audit each before switching; write authority is deliberately scalar). NOT a leak (scalar `ctx.sourceId` IS threaded), but federated_read (#876, `ctx.auth?.allowedSources`) is silently dropped on those reads.
- [ ] **v0.34.x: Migration v60 idempotency guard against `--force-retry` race with v64.** `gbrain apply-migrations --force-retry 58` after v64 has already run will re-install the FK with `ON DELETE SET NULL`, silently downgrading the v64 RESTRICT posture. Probability low (operator has to explicitly force-retry 58) but failure mode is invisible. Fix: v60 should probe `pg_constraint.confdeltype` before re-adding and refuse to clobber `'r'` (RESTRICT) with `'n'` (SET NULL).
@@ -3833,7 +3885,7 @@ contributor traps.
- [ ] **v0.34.x: Doctor check `oauth_orphan_source_id`** — surfaces OAuth clients whose source_id was nulled by the v60 D10 silent-widen path (`GBRAIN_ACCEPT_SILENT_WIDEN=1`). Closes the observability gap from v0.34.1's D4 decision. Sibling to the `rls_event_trigger` check pattern in `src/commands/doctor.ts`.
-- [ ] **v0.34.x: `gbrain sources purge` FK error UX.** Post-v0.34, deleting a source is refused if any oauth_client references it (v64 ON DELETE RESTRICT). The CLI currently surfaces the raw Postgres FK violation. Fix: pre-check via `SELECT client_id, client_name FROM oauth_clients WHERE source_id = $1`, print "N OAuth clients reference this source: ... Revoke first via `gbrain auth revoke-client <id>`." Mirrors `assessDestructiveImpact` in destructive-guard.ts (v0.26.5).
+- [x] **v0.34.x: `gbrain sources purge` FK error UX.** DONE on `garrytan/cathedral-6`: `clientsReferencingSource` + `formatClientReferentsBlock` in `src/core/destructive-guard.ts` pre-check remove/purge/auto-purge in `src/commands/sources.ts` and print the named-client refusal (revoke hint included) instead of the raw FK violation; `assessDestructiveImpact` carries `oauthClientCount`.
- [ ] **v0.34.x: `hybrid.ts:223` explicit-pick refactor.** The SearchOpts rebuild manually picks fields from HybridSearchOpts. This is the bug shape that caused the original v0.34.1 P0 leak — a new SearchOpts field is silently dropped if not manually added here. The wave added `sourceId` + `sourceIds` to the pick; future fields will keep hitting this footgun. Fix: refactor to spread + TypeScript `Pick<>` helper that narrows HybridSearchOpts → SearchOpts type-safely.
diff --git a/VERSION b/VERSION
index 0fe350b077..5465571245 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.12.3
\ No newline at end of file
+0.46.13.0
\ No newline at end of file
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index d565389960..5bba7e6da4 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -66,7 +66,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); pure `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → 0; else/null-content → wall-clock). `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `isSourceUnchangedSinceSync(..., {requireCleanWorkingTree:'ignore-untracked'}) ? 0 : wall-clock` (live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)`, NO git subprocess (trust boundary). `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`.
- `src/core/npm-squat-check.ts` — classifies `gbrain` PATH entries as real, foreign npm package, broken, or unknown for doctor's `npm_squat` check. On Windows it normalizes Git Bash/MSYS drive paths (`/c/...` → `C:/...`) and tries the native `.exe` suffix before reporting a broken entry; non-Windows classification keeps the original single-candidate behavior. Pinned by `test/npm-squat-check.test.ts`.
- `src/core/git-remote.ts` — SSRF-hardened git invocations for remote-source `cloneRepo`, `pullRepo`, and `fetchRemote(repoPath, branch)` (the last added for the sync cost-estimator's fetch-first path, #2139, so a cost preview / dry-run fetches through the same hardened flags + `GIT_TERMINAL_PROMPT=0` as real sync rather than a less-protected route). Exports two distinct flag constants because `git`'s argv grammar treats them differently: `GIT_SSRF_FLAGS` (3 `-c` config flags — `protocol.allow=user`, `protocol.file.allow=never`, `http.allowRedirects=false`) is global config, spread BEFORE the subcommand verb; `GIT_SSRF_SUBCOMMAND_FLAGS = ['--no-recurse-submodules']` is subcommand-scoped, spread AFTER the verb (a combined array would spread `--no-recurse-submodules` before the verb where real git rejects it exit 129). `cloneRepo` argv: `git <GIT_SSRF_FLAGS> clone <GIT_SSRF_SUBCOMMAND_FLAGS> --depth=1 [--branch X] -- <url> <dir>`. `pullRepo` argv: `git <GIT_SSRF_FLAGS> -C <dir> pull <GIT_SSRF_SUBCOMMAND_FLAGS> --ff-only`. Pinned by `test/git-remote.test.ts` position-anchored regression guard (`argv.indexOf('--no-recurse-submodules') > argv.indexOf(verb)`). Also exports the durability-side helpers that power `gbrain sources harden/pull`: `GIT_ENV_AUTH` (the no-prompt env minus the askpass `/bin/false` overrides, so an auth'd push/fetch can consult the repo's configured credential helper while `GIT_TERMINAL_PROMPT=0` still fails fast on a missing credential), `divergenceSafePull(repoPath, branch)` (fetch + `pull --rebase`; returns `skipped_dirty` on a dirty tree, `conflict_aborted` on a rebase conflict after `rebase --abort` so the tree is never left mid-rebase, else `up_to_date`/`advanced`), `detectDefaultBranch` (origin/HEAD → current branch → `main`), `pushProbe(repoPath, branch)` (authenticated `push --dry-run` that proves push access and classifies `auth`/`protected`/`unreachable`), and `isWorkingTreeDirty`. These auth'd paths route their `protocol.file.allow` through `GBRAIN_GIT_ALLOW_FILE_TRANSPORT` (default `never`; set `=1` for self-hosted filesystem remotes), unlike clone/pull which stay strict.
-- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a confirmed push and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (#2426; hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted) and runs before `sources remove`. CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`.
+- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a confirmed push and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (#2426; hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`.
- `src/commands/storage.ts` — `gbrain storage status [--repo P] [--json]`. Split into pure data (`getStorageStatus`) + JSON formatter + human formatter (ASCII-only) matching the `orphans.ts` pattern. `PageCountsByTier` and `DiskUsageByTier` are distinct nominal types so swaps fail at compile time.
- `gbrain.yml` (brain repo root) — Optional storage tiering config. Top-level `storage:` section with `db_tracked:` and `db_only:` array-valued keys. `gbrain sync` auto-manages `.gitignore` for `db_only` paths on successful sync (skips on dry-run, blocked-by-failures, submodule context, or `GBRAIN_NO_GITIGNORE=1`). `gbrain export --restore-only [--repo P] [--type T] [--slug-prefix S]` repopulates missing `db_only` files from the database.
- `src/core/supabase-admin.ts` — Supabase admin API (project discovery, pgvector check).
@@ -221,7 +221,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0; pre-v104 brains report `ok`. CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).
- `src/commands/import.ts` — `gbrain import <path> [--source-id <id>]`: page import with the path-set checkpoint. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`, byte-identical to the old behavior. Pinned by `test/import-abort-error.test.ts`. `--source-id <id>` routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`). Pinned by `test/import-source-id.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Uses a path-set checkpoint via `src/core/import-checkpoint.ts` (the walk still applies `sortNewestFirst()` for embed-cost ordering, but checkpoint correctness no longer depends on sort order). A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. This closes three classes: parallel-import-with-slow-worker dropping the slow file on crash-resume (the slow file isn't in `completed` until its own `processFile` resolves), failed-file-bumps-counter-past-itself (failures don't add to `completed`), and sort-flip-drops-newest-N-on-cross-version-resume (order is no longer part of the checkpoint). Old positional checkpoints are detected and discarded with a stderr line on first resume (re-walking is cheap because `content_hash` short-circuits unchanged files). Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry regression). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` imported (and resurrected soft-deleted) pages incremental sync excludes (#2607). Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs, #753/#774; the resume checkpoint stays dir-relative per `resumeFilter`'s contract).- `src/core/import-checkpoint.ts` — `loadCheckpoint(brainDir)`, `saveCheckpoint(brainDir, completed)`, `resumeFilter(files, completed, brainDir)`, `clearCheckpoint()`, plus the `ImportCheckpoint` type. Path-set format `{schema_version, brainDir, completed: string[]}`. Atomic write via `.tmp` + `rename()` so a mid-write crash never leaves a partial JSON. `loadCheckpoint` returns `null` on: missing file, malformed JSON, brainDir mismatch (ran against a different brain), and the old positional format (logged to stderr before discard). `resumeFilter` returns `{toProcess, skippedCount}` — pure, no I/O, deterministic. `clearCheckpoint` is no-op-on-missing for clean-exit cleanup. Honors `GBRAIN_HOME` via `gbrainPath()` so `withEnv({GBRAIN_HOME: tmpdir})` test isolation works without monkey-patching fs. Best-effort persistence — `saveCheckpoint` logs warnings on write errors but never throws.
- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). Foreign-edge footer always present (`X foreign edges (use --include-foreign to traverse)`) so cross-source edges never disappear silently; `--include-foreign` widens the SQL filter to walk them. Pinned by `test/graph-query.test.ts`.
-- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit}`. `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.
+- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit}`. `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.
- `src/commands/reindex-frontmatter.ts` — `gbrain reindex-frontmatter`. `reindexFrontmatterCli(engine, args)` takes the ALREADY-CONNECTED engine from cli.ts's dispatch (#1963); it must never build/connect its own engine — a second connect on the same PGLite data dir self-deadlocks on the data-dir lock (this process already holds it) and timed out 100% of the time on PGLite. Same rule applies to `runBackfillCommand(engine, args)` in `src/commands/backfill.ts` and any future command dispatched from cli.ts's engine-connected switch. Pinned by `test/reindex-frontmatter-connect.test.ts` (library path) and `test/reindex-frontmatter-pglite-spawn.serial.test.ts` (CLI dispatch seam, both commands).
- `src/core/source-config-sql.ts` + `src/core/sources-load.ts` — canonical recovery for historical 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'`, 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` (14 cases), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`).
@@ -280,8 +280,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the FOV-6b fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition (an out-of-sync copy in the collector once produced a perpetual bogus unused-starter finding). `parseSurfaceFlag` (strict, loud reject), `resolveSurface` (flag > config `mcp_surface` > full), `filterOpsForSurface`, `allowedOpNames`. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). WP4 per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped) and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases).
- `src/commands/protocol.ts` — `gbrain protocol [--json] | conformance [--target <http-url|stdio-cmd>] [--token] [--synthesize] | stats [--days N]`. `--json` emits input schemas from the LIVE Operation defs + RESPONSE_SCHEMAS (doc/code can't drift). Conformance default target self-spawns gbrain's own stdio server (dev `.ts` entry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the clean `unavailable` error). Stats aggregates the usage sidecar + the measured TTHW; output states "local JSONL only — never uploaded". CLI_ONLY + SELF_HELP wired in cli.ts; no pre-bound engine.
- `src/core/minions/attachments.ts` — Attachment validation (path traversal, null byte, oversize, base64, duplicate detection).
-- `src/commands/agent.ts` — `gbrain agent run <prompt> [flags]` CLI. 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.
+- `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 regression 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 — the #2194/#2227 mixed-scope fix) 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 the brain-wide `GLOBAL_PHASES` once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` on success. `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 gains 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 #2849 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).
- `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 (no inline `crashCount`/`startWorker`/`child.on('exit')`); `--max-rss 2048` and `maxCrashes: 5` preserved. `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` adds `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` adds 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 (stale lock from a crashed process no longer blocks). (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.
@@ -294,14 +295,14 @@ 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` (amendment 30), consumed by `gbrain auth clients --usage` (E4), the advisor `mcp-client-fit` collector (E3), 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. D12 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. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. 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 at `operations.ts:1391` saw a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs — RCE). `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(sql, engineName, version, timeoutMs)` racing `sql\`SELECT 1\`` against the exported `HEALTH_TIMEOUT_MS = 3000` (returns the same `ProbeHealthResult` tagged-union as `probeHealth`, single timer-cleanup site, single 503 envelope); body shape `{status, version, engine}` only. Full stats moved to 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. Every OAuth/admin/audit SQL call 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, in the `default` source, since untrusted payloads carry no source grant). 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; pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the WP1 honest catalog: per-request filters (token scope incl. the FOV-4 `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` (amendment 23 stopgap). 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'` (amendment 33/D10; 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).
+- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. 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 at `operations.ts:1391` saw a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs — RCE). `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(sql, engineName, version, timeoutMs)` racing `sql\`SELECT 1\`` against the exported `HEALTH_TIMEOUT_MS = 3000` (returns the same `ProbeHealthResult` tagged-union as `probeHealth`, single timer-cleanup site, single 503 envelope); body shape `{status, version, engine}` only. Full stats moved to 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. Every OAuth/admin/audit SQL call 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, in the `default` source, since untrusted payloads carry no source grant). 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 WP1 honest catalog: per-request filters (token scope incl. the FOV-4 `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` (amendment 23 stopgap). 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'` (amendment 33/D10; 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).
- `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 (the #2339 class; 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`. 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 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. Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases). Credit @Aragorn2046 + @seungsu-kr.
- `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. Auth codes single-use with 10-minute TTL via atomic `DELETE...RETURNING` (closes RFC 6749 §10.5 TOCTOU); refresh rotation also `DELETE...RETURNING` (§10.4 stolen-token detection). `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); bare `catch {}` in `verifyAccessToken`/`getClient` replaced by `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`).
- `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.
-- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar) and `--federated-read <S1,S2,...>` (read scope, array) and prints the resolved `Write source` + `Federated reads`; pre-v0.34 clients backfill to `source_id='default'` via migration v60. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)` (the inline version used `rest[takesIdx + 1]` resolving to `rest[0]` when `takesIdx === -1`, excluding the name from the positional search). Pinned by `test/auth-create-args.test.ts`.
+- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; pre-v0.34 clients backfill to `source_id='default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)` (the inline version used `rest[takesIdx + 1]` resolving to `rest[0]` when `takesIdx === -1`, excluding the name from the positional search). Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.
- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses JSON error envelopes first, falls back to substring detection for legacy server messages. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.
-- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which now names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (required for `--install` in non-TTY), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing an inline `bearer_token` managed block because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/e2e/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/e2e/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts` (the `test/audit/batch-retry-audit.test.ts` ENOENT case was made hermetic — it had read the real `~/.gbrain/audit`).
+- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which now names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`, `issuerFromMcpUrl`, the `OAUTH_SECRET_NOTE` secret-hygiene constant, and `openclawThinClientBlock` — the honest openclaw wiring print: a scoped `gbrain init --mcp-only` thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them — `OAUTH_SECRET_NOTE` included — so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (required for `--install` in non-TTY), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing an inline `bearer_token` managed block because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/e2e/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/e2e/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts` (the `test/audit/batch-retry-audit.test.ts` ENOENT case was made hermetic — it had read the real `~/.gbrain/audit`).
- `src/commands/upgrade.ts` — self-update CLI. `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally.
- `src/commands/migrations/` — TS migration registry (compiled into the binary; no runtime walk of `skills/migrations/*.md`). `index.ts` lists migrations in semver order. `v0_11_0.ts` = Minions adoption orchestrator (8 phases). `v0_12_0.ts` = Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify); `phaseASchema` has a 600s timeout for duplicate-heavy brains. `v0_12_2.ts` = JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record). `v0_14_0.ts` = shell-jobs + autopilot cooperative (pending-host-work ping for skills/migrations/v0.14.0.md). All orchestrators are idempotent and resumable from `partial` status. The RUNNER owns all ledger writes — orchestrators return `OrchestratorResult` and `apply-migrations.ts` persists a canonical `{version, status, phases}` shape (orchestrators no longer call `appendCompletedMigration`). `statusForVersion` prefers `complete` over `partial` (never regresses); 3 consecutive partials → wedged → `--force-retry <version>` writes a `'retry'` reset marker. Schema-only migrations v14 (`pages_updated_at_index`) + v15 (`minion_jobs_max_stalled_default_5` with UPDATE backfill) live in the `MIGRATIONS` array in `src/core/migrate.ts`. `in-process.ts` exports `runMigrateOnlyCore({timeoutMs?})` — single source of truth for "bring schema to head" (`configureGateway` → `createEngine` → `connect` → `initSchema` → `disconnect`, idempotent, 600s `MIGRATE_ONLY_TIMEOUT_MS` guard, throws `MigrateOnlyError` on no-config / timeout); the orchestrators' 9 schema phases AND `init.ts:initMigrateOnly` both delegate to it so schema bring-up can't drift (running in-process removes the spawn that died with `getaddrinfo ENOTFOUND` on Windows + bun + Supabase pooler). `runGbrainSubprocess` is the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error. `v0_13_1.ts:phaseCGrandfather` is a CHUNKED bulk SQL pass keyed on `pages.id` (globally unique PK, NOT slug — slug uniqueness is `(source_id, slug)`), filters `deleted_at IS NULL` (no tombstones), chunked in `CHUNK_SIZE` batches (DELETE_BATCH_SIZE convention) for bounded lock-hold; the rollback log carries `{id, slug, source_id, pre_frontmatter}` so rollback is unambiguous across sources; idempotent + resumable (each UPDATE flips its rows out of `GRANDFATHER_WHERE`). Pinned by `test/migration-in-process.serial.test.ts` and `test/migrations-v0_13_1-grandfather.test.ts`.
- `src/commands/migrations/v0_46_3.ts` — ZeroEntropy sunset notice migration, detect-and-notify ONLY. Detects the HOST brain's exposure via `src/core/ze-exposure.ts` (read-only); when exposed — or when exposure is UNKNOWN, fail-safe — prints the ACTION REQUIRED banner and appends one idempotent entry to `~/.gbrain/migrations/pending-host-work.jsonl` pointing the host agent at `skills/migrations/v0.46.3.0.md`. Performs NO config writes, NO pinning, and never invokes `migrate embeddings` (the migration costs money and needs a target key — that decision belongs to the user/agent via the playbook). UNKNOWN returns `complete` with an `exposure_unknown` detail rather than `partial` (three consecutive partials would wedge the whole migration chain behind `--force-retry`); the stage-2 upgrade banner and `gbrain doctor` carry the ongoing nag instead. Host-scoped (apply-migrations runs once per host with a global completed.jsonl); mounted/team brains are covered by the per-brain stage-2 banner (`ze_sunset_notice_v2_shown` in each brain's own DB config) + doctor gates.
@@ -414,7 +415,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/backlinks.ts` — Back-link checker and fixer (enforces Iron Law)
- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. with `src/commands/sources.ts`: `gbrain lint` gains a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` becomes disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the new quarantine/flag dispositions.
- `src/commands/report.ts` — Structured report saver (audit trail for maintenance/enrichment)
-- `src/core/destructive-guard.ts` — three-layer protection against accidental data loss. `assessDestructiveImpact(engine, sourceId)` counts pages/chunks/embeddings/files for a source. `checkDestructiveConfirmation(impact, opts)` is the fail-closed gate (`--confirm-destructive` required when data is present; `--yes` alone is rejected). `softDeleteSource` / `restoreSource` / `listArchivedSources` / `purgeExpiredSources` drive the source-level archive lifecycle via `sources.archived BOOLEAN`, `archived_at TIMESTAMPTZ`, `archive_expires_at TIMESTAMPTZ`. Page-level analog: `BrainEngine.softDeletePage` / `restorePage` / `purgeDeletedPages` plus `pages.deleted_at TIMESTAMPTZ` and a partial purge index. The MCP `delete_page` op rewires to `softDeletePage`; ops `restore_page` (`scope: write`) and `purge_deleted_pages` (`scope: admin`, `localOnly: true`) round out the surface. Search visibility (`buildVisibilityClause` in `src/core/search/sql-ranking.ts`) hides soft-deleted pages and archived sources from `searchKeyword` / `searchKeywordChunks` / `searchVector` in both engines. The autopilot cycle's `purge` phase calls `purgeExpiredSources` + `engine.purgeDeletedPages(72)` so the 72h TTL is real.
+- `src/core/destructive-guard.ts` — three-layer protection against accidental data loss. `assessDestructiveImpact(engine, sourceId)` counts pages/chunks/embeddings/files/facts for a source (a fact-only source — a revoked agent's workspace, since facts are the primary agent write lane — is data at stake, not empty; pre-facts brains degrade to 0), plus `oauthClientCount` — OAuth clients whose `source_id` references it. `checkDestructiveConfirmation(impact, opts)` is the fail-closed gate (`--confirm-destructive` required when data is present; `--yes` alone is rejected). FK-RESTRICT lifecycle: `clientsReferencingSource(engine, sourceId)` lists ALL physical OAuth-client rows referencing a source via `oauth_clients.source_id` — the FK is PHYSICAL (ON DELETE RESTRICT ignores `deleted_at`), so soft-deleted (revoked-but-retained) rows BLOCK a hard delete too and come back tagged `deleted`; pre-migration brains without `deleted_at` fall back to untagged referents (42703-retry idiom) and brains without the table have none by construction. `formatClientReferentsBlock` renders the shared refusal `sources remove`/`sources purge` print (naming each client — `[revoked, retained]` for soft-deleted rows — + the revoke command) so the raw Postgres FK violation never reaches the operator. `softDeleteSource` / `restoreSource` / `listArchivedSources` / `purgeExpiredSources` drive the source-level archive lifecycle via `sources.archived BOOLEAN`, `archived_at TIMESTAMPTZ`, `archive_expires_at TIMESTAMPTZ`; `purgeExpiredSources` SKIPS client-referenced sources via a physical `NOT EXISTS` (soft-deleted clients count) so recurring maintenance keeps sweeping the rest instead of aborting. Page-level analog: `BrainEngine.softDeletePage` / `restorePage` / `purgeDeletedPages` plus `pages.deleted_at TIMESTAMPTZ` and a partial purge index. The MCP `delete_page` op rewires to `softDeletePage`; ops `restore_page` (`scope: write`) and `purge_deleted_pages` (`scope: admin`, `localOnly: true`) round out the surface. Search visibility (`buildVisibilityClause` in `src/core/search/sql-ranking.ts`) hides soft-deleted pages and archived sources from `searchKeyword` / `searchKeywordChunks` / `searchVector` in both engines. The autopilot cycle's `purge` phase calls `purgeExpiredSources` + `engine.purgeDeletedPages(72)` so the 72h TTL is real.
- `src/commands/pages.ts` — `gbrain purge-deleted [--older-than HOURS|Nd] [--dry-run] [--json]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff; cascades to content_chunks/page_links/chunk_relations.
- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. Replaces per-op file-backed JSON checkpoints scattered across `import.ts`, `embed.ts`, `reindex.ts`. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), killing the old O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit now implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects — the #2339 bug that aborted every multi-source sync at the first pin write (PGLite parsed it silently, so it shipped). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` was NOT migrated to this primitive — both checkpoint systems coexist without conflict; migrating requires async-propagating 4 sync call sites in `src/commands/import.ts` and rewriting 18 tests, deferred.
- `src/core/brain-score-recommendations.ts` — pure data layer consumed by both `gbrain doctor --remediation-plan` / `--remediate` and `gbrain features`. `computeRecommendations(checks, opts)` returns `Remediation[]` with stable `id`, content-hash `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on` (references stable ids, not check names — so plan order is reproducible). `classifyChecks(report)` triages every doctor check three-state into `remediable | human_only | blocked` (`human_only` covers RLS warnings and other human-judgment gates; `blocked` covers dependency chains where a parent check failed). `maxReachableScore(checks)` computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull from `anthropic-pricing.ts` (synthesize/patterns/consolidate) and `embedding-pricing.ts` (embed jobs). Pinned by `test/brain-score-recommendations.test.ts` (~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).
@@ -544,7 +545,8 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/bootstrap/repo.ts` / `attach.ts` / `uninstall.ts` — private-repo lifecycle. `createPrivateRepo`: gh gates, slugified name probe, `gh repo create --private --source --push`, privacy verified via `gh api .private` (rate-limit/5xx is VERIFY_UNAVAILABLE, distinct from not-private) before any push, idempotency keyed off the remote URL. A pre-existing origin is adopted (disposition 'adopted') when the authed gh user owns it, there's no recorded `repo_url`, and it is SAFE — empty or already carrying our history (`assertAdoptableOrigin`; a foreign-content repo is refused `ORIGIN_NOT_EMPTY`, never a silent no-op); this is the create-repo-first path. Org-owned origins and anything else are refused and pointed at attach. Repo-local git identity is set in both create and adopt paths before commit; `repo_url` is recorded only after a successful push. `attachWorkspace` (machine two): requires an `initialized` manifest, writes this machine's receipt, returns structured wiring steps. `uninstallWorkspace`: receipt-keyed, refuses under a live serve (read-only lock probe — never opens the engine), removes exactly receipt-recorded paths + marker-keyed host entries, keeps the brain unless `--delete-brain` AND bootstrap created it; never wholesale-deletes the gbrain home. All gh/git through an injectable ExecRunner seam.
- `src/core/bootstrap/hooks.ts` + `host-specs.ts` — host wiring. `host-specs.ts` is the ONE module owning host-format assumptions (dated spec targets with verifiedAt + doc references: claude-code hooks/settings shapes incl. the 10,000-char hook-output cap and the five hook events; codex mcp-add argv, the streamable-HTTP `url`+`bearer_token` config shape verified against codex-cli 0.147.0, `codexConfigPath()` honoring CODEX_HOME, `claudeUserSettingsPath()` honoring CLAUDE_CONFIG_DIR/$HOME explicitly — Bun's homedir() ignores a remapped HOME, which would point sandboxed writers at the operator's real settings — and the opencode shapes: `opencodeConfigDir`/`opencodeGlobalConfigPath` (XDG-only resolution; the `.jsonc` name preferred for parity with `opencode mcp add`; OPENCODE_CONFIG/_CONFIG_DIR/_CONFIG_CONTENT deliberately NOT honored — observed INERT in opencode 1.18.18, honoring them would write registrations into a file opencode never reads), `opencodeProjectConfigPath`, `opencodeGlobalSiblingPath` (the OTHER member of the global filename pair — writers reconcile `mcp.<name>` across it because opencode merges both), and `OPENCODE_HAS_HOOKS=false` — 'gbrain does not wire opencode's plugin/event system yet', not 'opencode has no hooks'). The settings writers are path+marker parameterized: `writeClaudeHooksAt`/`removeClaudeHooksAt` take an explicit settings file and a marker VALUE (workspace installs stamp `bootstrap-v1` in `.claude/settings.local.json`; harness installs stamp `bootstrap-harness-v1` in user-scope settings or a --project dir — the two coexist and each removal strips only its own; `refuseOnForeignGbrainMarker` blocks same-file double-wiring), fail-closed on broken JSON (a settings file that doesn't parse THROWS with the path — a writer must never relocate or overwrite a config it can't read), mode-preserving realpath-resolved atomic writes (dotfile symlinks survive), and fixed-or-timestamped backups. `addPermissionsAllowEntry`/`removePermissionsAllowEntry` manage the harness lane's `mcp__<name>` headless pre-approval with set semantics and NO marker (ownership rides the harness receipt; foreign entries always survive); the add path fails CLOSED when an existing `permissions` key or `permissions.allow` carries a shape it doesn't understand (host security policy is never rewritten on a guess), while removal leaves shapes it can't read untouched and reports nothing-to-remove. `registerClaudeMcp`/`registerCodexMcp` build argv only (Claude Code takes `--scope`, project default; Codex has no scope flag — `codex mcp add` is always user-global; `-e`/`--env GBRAIN_SOURCE` so MCP writes land in the workspace source, and `serve --surface full` pinned so a pre-existing `mcp_surface: verbs` config row can't silently narrow the bootstrap op surface). The opencode workspace lane execs NOTHING — registration is the direct `opencode-json.ts` write with an INVERTED scope default (user-global; opencode spawns project-config servers with no trust prompt, so `MCP_SCOPE=project` is an explicit opt-in that writes the committed-candidate `opencode.json` with a PATH-resolved command and prints the sharing warning), verification is config parse-back + a best-effort `opencode mcp list --pure` probe — the probe spawns via a held Bun.spawn handle from a fresh EMPTY temp-dir cwd (never the invoking cwd: opencode merges a project opencode.json from cwd and spawns its servers with no trust prompt), is SKIPPED entirely for project scope (printed note; parse-back is authoritative) and on plugin-bearing configs (`mcp list` is a code-execution surface), and on timeout actually kills the child (SIGTERM → SIGKILL, bounded pipe drain, code 124 into the could-not-confirm branch; `probeSpawn` is the injectable seam). User-scope writes also reconcile the SIBLING global filename first (ours → removed with a note; foreign → refuse naming both files) so a merge-shadow registration can never survive. `detectHarness` probes `OPENCODE`/`OPENCODE_PID` (set in opencode's bash-tool children, observed 1.18.18).
`writeCommittedClaudeHooks` is the second, COMMITTED hook carrier: it writes marker-keyed entries into the workspace's checked-in `.claude/settings.json` using `buildPortableClaudeHookCommand` (PATH-resolved `gbrain`, fail-open when the binary is absent) so teammates cloning the repo inherit the hooks; `committedHookEvents(ws)` feeds the local writer's `carriedEvents` so the two carriers never double-wire an event, and `removeClaudeHooks` strips both.
-- `src/core/bootstrap/codex-toml.ts` — the ONE direct codex-config writer (the CX2-17 revisit, fired by #4043: `codex mcp add` cannot express an inline `bearer_token`, and framework-spawned codex inherits no shell profile for the env-var lane). One `[mcp_servers.<name>]` table between full-line markers; everything outside survives byte-for-byte. Foreign-server detection PARSES the config (Bun.TOML.parse, no dependency) with our block stripped — a header-only regex would false-negative inline-table/dotted/quoted spellings into a codex-bricking duplicate table; rewrites re-anchor at EOF; renders are parse-validated with an ours-keys-exactly assert before rename; damaged markers refuse; 0600 tmp/target/.bak (the .bak carries the previous token on re-runs); CRLF preserved, missing trailing newline repaired. Pinned by `test/codex-toml.test.ts`.
+- `src/core/bootstrap/codex-toml.ts` — the ONE direct codex-config writer (the CX2-17 revisit, fired by #4043: `codex mcp add` cannot express an inline `bearer_token`, and framework-spawned codex inherits no shell profile for the env-var lane). One `[mcp_servers.<name>]` table between full-line markers; everything outside survives byte-for-byte. Foreign-server detection PARSES the config (Bun.TOML.parse, no dependency) with our block stripped — a header-only regex would false-negative inline-table/dotted/quoted spellings into a codex-bricking duplicate table; rewrites re-anchor at EOF; renders are parse-validated with an ours-keys-exactly assert before rename; damaged markers refuse; 0600 tmp/target/.bak (the .bak carries the previous token on re-runs); CRLF preserved, missing trailing newline repaired. Also exports `renderCodexHttpServerBlock({name, url, bearerToken})` — a MARKER-FREE, parse-validated `[mcp_servers.<name>]` TOML render for paste-into-config surfaces (`gbrain agent register`'s codex block); rendering only, never writes a file. Pinned by `test/codex-toml.test.ts`.
+- `src/core/bootstrap/serve-health.ts` — serve `/health` probe + scopes version-skew floor, peeled from `harness.ts` (which re-exports the entire surface — import sites never chase the peel). `probeServeHealth(mcpUrl, fetchFn, timeoutMs=3000)` GETs `<base>/health` and returns `{ok, version?, engine?, detail?}`, never throws; `fetchFn` is an explicit argument (no ambient fetch, no engine, no config). `isServeOlderThanScopes(v)` compares against the PINNED `SCOPES_MIN_SERVE_VERSION` constant — a comparison against the moving CLI VERSION would false-flag every scope-aware serve on the next release. An older serve verifies scoped tokens as FULL ACCESS, so callers print the floor line unconditionally.
- `src/core/bootstrap/opencode-json.ts` — the ONE direct opencode-config writer (workspace stdio lane, harness remote lane, connect `--install`). ALL edits ride jsonc-parser `modify`/`applyEdits` (comments/formatting/EOLs survive byte-for-byte outside the edited range — opencode's own `mcp add` preserves comments, and JSONC is its effective grammar for BOTH `.json` and `.jsonc` filenames, which MERGE when both exist). Ownership is a 4-state STRUCTURAL FINGERPRINT (`opencodeEntryKind` → ours-same-source | ours-other-source | foreign | absent; GBRAIN_SOURCE EQUALITY for local entries, receipt-url match or the `{env:GBRAIN_REMOTE_TOKEN}` interpolation for remote), never a marker key (a future strict-schema flip must not brick the host). Distinct read-failure classes (ENOENT create / empty-as-{} / unreadable refuse); foreign refusal on write AND remove; post-render validation (our entry round-trips + every other key survives) keeps the original on failure; 0600 for inline-bearer targets; backups are UNIQUE per operation (`<config>.bak-<hex>`, returned in the result with `writtenText`, the exact rendered bytes) so overlapping runs can never clobber each other's snapshot, and a backup is chmod'd 0600 whenever the COPIED content carries an inline bearer (write AND remove paths); the ours-other-source refusal is caller-appropriate (url + `--force` wording on the remote/expect-url path, GBRAIN_SOURCE wording on the local path); `removeOpencodeMcpEntry` takes a caller expectation + optional `skipOtherSource` — the uninstall lane passes THIS workspace's source id so an ours-other-source match becomes a calm skip-with-note (another workspace's registration is never deleted; foreign still refuses); `reconcileOpencodeSiblingGlobal` clears a same-name gbrain entry from the OTHER global filename before a global write (foreign → refuse naming both files) — opencode merges both, so a leftover sibling entry is a shadow registration; the bun-run ownership lane is ANCHORED (an exact `gbrain`/`gbrain-*` path segment in some arg — a gbrainy-fork cli path is NOT ours, fail-closed); `parseOpencodeEntryBearer` recovers the harness `--status` token url-matched only; `opencodeRemoteEntryExists` is the stdio-lane ownership arbiter (codexBlockOwnsName analog). Callers hold `acquireBootstrapLock` (config-dir → opencode-dir ordering). Pinned by `test/opencode-json.test.ts` (incl. the fingerprint truth-table suite).
- `src/core/bootstrap/atomic-write.ts` — the ONE atomic config-file writer for bootstrap host surfaces (rule-of-three extraction): 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` (#4043): 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 #4029 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); 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`.
diff --git a/docs/guides/agent-to-gbrain.md b/docs/guides/agent-to-gbrain.md
index 679944fe84..89ce7329a8 100644
--- a/docs/guides/agent-to-gbrain.md
+++ b/docs/guides/agent-to-gbrain.md
@@ -1,8 +1,8 @@
# How a downstream agent should talk to gbrain
-This guide is for authors of downstream agents (hermes, openclaw, future
-forks) that need to call gbrain operations from their own runtime. Reading
-this first will save you a debugging cycle: gbrain has **two distinct
+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
@@ -11,8 +11,8 @@ surfaces**, and which one you pick depends on the operation.
┌─────────────────────────────────────────────┐
│ gbrain process │
│ │
- Agent (hermes, │ ┌──────────────────┐ ┌────────────────┐ │
- openclaw, fork) ────┼──▶ MCP ops surface │ │ local-only │ │
+ Agent (OpenClaw, │ ┌──────────────────┐ ┌────────────────┐ │
+ or any fork) ───────┼──▶ MCP ops surface │ │ local-only │ │
│ │ (HTTP + OAuth) │ │ commands │ │
│ │ │ │ │ │
│ │ search, query, │ │ sync, embed, │ │
@@ -48,12 +48,27 @@ The host runs gbrain as a long-lived HTTP server:
gbrain serve --http --port 3131
```
-The agent registers as an OAuth client (one-time):
+**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:
```bash
-gbrain auth register-client hermes \
+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):
+
+```bash
+gbrain auth register-client aurora-coder \
--grant-types client_credentials \
- --scopes read,write
+ --scopes "read write"
# Prints client_id + client_secret one-time. Store securely.
```
@@ -66,6 +81,17 @@ 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 | 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.
diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.md
index fb9a47d01d..d883c00d43 100644
--- a/docs/tutorials/company-brain.md
+++ b/docs/tutorials/company-brain.md
@@ -248,6 +248,49 @@ Bob should see the performance-review notes from `internal`, plus anything relat
If both queries return correctly scoped results, isolation is working. (There is no per-query "act as client X" flag — the thin-client config decides which credential the CLI uses; only the client secret can be overridden at call time via `GBRAIN_REMOTE_CLIENT_SECRET`.)
+### Multi-agent: one brain, many agents (`gbrain agent register`)
+
+The raw `register-client` flow above is the per-teammate primitive. When the client you're onboarding is an **AI agent harness** (a teammate's Claude Code, a coding agent working a project repo, your OpenClaw), there's a packaged one-command path: `gbrain agent register` mints the scoped OAuth client, mints a 30-day access token, and prints the exact wiring block for the harness — all in one step. It runs on the brain host and is a trusted local operation — not a delegation mechanism. (When to use which path lives in [the onboarding decision table](../guides/agent-to-gbrain.md#onboarding-paths--the-decision-table) — link there, it's the single copy.)
+
+Two presets cover the common shapes, with semantics worth knowing honestly:
+
+- **`daily-driver`** — a personal assistant agent: writes to one source, reads broadly. The read grant is a **snapshot** of all non-archived sources at registration time, excluding other agents' `*-workspace` scratch sources (name one explicitly in `--federated-read` to share it) — a source you add next month is NOT automatically readable; re-grant with `gbrain auth rescope-client <client_id> --federated-read <updated list>`.
+- **`coding-agent`** — a write-isolated project agent: its writes land in an auto-created, DB-only `<name>-workspace` source (so a misbehaving agent can't scribble on your wiki), and it reads only the project sources you name via `--federated-read` (required — a coding agent that can read nothing but its own scratch space is a misconfiguration).
+
+Both presets start the client on the **starter** tool surface (the ~27-op daily set, not the full brain-admin surface). Override at registration with `--surface`, or widen a specific client later with `gbrain auth rescope-client <client_id> --surface full`.
+
+A worked example — a coding agent for alice-example's widget project, wired into Claude Code:
+
+```bash
+# On the brain host. proj-widget is the project source it may read
+# (create it first with `gbrain sources add proj-widget` if needed).
+gbrain agent register aurora-coder \
+ --harness claude-code \
+ --preset coding-agent \
+ --federated-read proj-widget,shared \
+ --url https://brain.acme-co.com/mcp
+```
+
+The output prints the client id, the resolved scoping (write source `aurora-coder-workspace`, federated reads, surface tier, token expiry), and a paste-ready block for the harness. Credentials print redacted by default; re-run with `--show-token` when you're ready to paste, or use `--json` for provisioning scripts. A `daily-driver` for yourself looks like `gbrain agent register nova-daily --harness claude-code --preset daily-driver --url https://brain.acme-co.com/mcp`.
+
+Verify the new agent's scoping the same way you verified teammates above — a thin-client install acting as that client (`--force` overwrites the scratch config from the previous check):
+
+```bash
+# On a machine that is NOT the brain host (or the same scratch shell)
+gbrain init --mcp-only --force \
+ --issuer-url https://brain.acme-co.com \
+ --mcp-url https://brain.acme-co.com/mcp \
+ --oauth-client-id <aurora-coder's client_id> \
+ --oauth-client-secret <aurora-coder's client_secret>
+
+gbrain whoami
+gbrain search "widget launch plan"
+```
+
+`gbrain whoami` should name the aurora-coder client; the search should return results only from `proj-widget`, `shared`, and its own workspace.
+
+**Renewal.** The minted access token defaults to a 30-day TTL (registration always writes a per-client TTL — the server default for CLI-minted tokens is one hour, which would be useless in a pasted config). When a token expires, rotate with `gbrain agent register --reissue <client_id> --harness claude-code --url https://brain.acme-co.com/mcp`: it rotates the client secret, mints a fresh token, and reprints the block. Rotation is not revocation — outstanding access tokens stay valid until they expire; revoke the client (`gbrain auth revoke-client <client_id>`) to kill them immediately.
+
---
## Part 6: Set up per-person crons
@@ -412,7 +455,7 @@ The thin-client install creates a local config that knows how to talk to your br
**2. Their AI client, connected directly to `https://brain.acme-co.com/mcp`.** Each client has its own connection shape; the per-client pages in [`docs/mcp/`](../mcp/) are the reference:
-- **Claude Code / Codex** — one command from anywhere `gbrain` is installed: `gbrain connect https://brain.acme-co.com/mcp --token <token> --install` (see [CLAUDE_CODE.md](../mcp/CLAUDE_CODE.md) / [CODEX.md](../mcp/CODEX.md)). Note the credential type: `gbrain connect` for these two agents uses **bearer tokens** (`gbrain auth create <name>`), which are full-access. That's fine for you as the admin; for source-scoped teammates, the scoped credential is their OAuth client — use it via the thin-client CLI above and the OAuth-capable clients below.
+- **Claude Code / Codex** — the scoped path is `gbrain agent register <name> --harness claude-code|codex --url https://brain.acme-co.com/mcp` run on the brain host (the Part 5 multi-agent subsection): it mints a source-scoped OAuth client plus a 30-day token and prints the exact paste block for the harness. The older `gbrain connect https://brain.acme-co.com/mcp --token <token> --install` lane (see [CLAUDE_CODE.md](../mcp/CLAUDE_CODE.md) / [CODEX.md](../mcp/CODEX.md)) still works but uses **bearer tokens** (`gbrain auth create <name>`), which are full-access unless minted with `--scopes` — fine for you as the admin, wrong for source-scoped teammates.
- **Claude Desktop** — remote servers are added through the GUI: **Settings > Integrations**, URL `https://brain.acme-co.com/mcp`. Do **not** put a remote server in `claude_desktop_config.json`; that file only works for local stdio servers and fails silently for remote ones. See [CLAUDE_DESKTOP.md](../mcp/CLAUDE_DESKTOP.md).
- **ChatGPT** ([CHATGPT.md](../mcp/CHATGPT.md)) and **Perplexity** ([PERPLEXITY.md](../mcp/PERPLEXITY.md)) — both speak OAuth to the server directly, so per-teammate scoping carries into those tools. Perplexity uses the same `client_credentials` clients you registered in Part 5. ChatGPT needs an `authorization_code` (PKCE) client — register one per teammate with the same `--source` / `--federated-read` flags.
- **OpenClaw / Hermes forks** — if the teammate's own agent runs on a machine with a full local gbrain install, it can use local stdio (`gbrain serve`) against its own brain and reach yours over HTTP MCP like any other remote client.
diff --git a/evals/brainbench/README.md b/evals/brainbench/README.md
index ab74b1dd89..3a90ca07fc 100644
--- a/evals/brainbench/README.md
+++ b/evals/brainbench/README.md
@@ -65,7 +65,12 @@ documented future extension.
Hand-authored spike fixtures (`kta-001`, `kta-002`, `ms-001`, `wb-001`,
`cont-001-*`) froze the schema before the generator scaled it; they remain part
-of the corpus.
+of the corpus. `ms-002-nondefault-active` is hand-authored too: it is the only
+fixture with a non-`default` `active_source` (the generator pins gen-ms
+fixtures to `active_source: default`), exercising the cross-source leak
+detector's other arm — a twin slug seeded into `default` AND `teambrain`, a
+teambrain-only page, and a default-only leak canary, replayed with
+`active_source: teambrain`.
## Fixture authoring (contributions welcome)
diff --git a/evals/brainbench/_ledger.json b/evals/brainbench/_ledger.json
index e18fbfba3e..df749f18e1 100644
--- a/evals/brainbench/_ledger.json
+++ b/evals/brainbench/_ledger.json
@@ -22,5 +22,18 @@
"date": "2026-06-12",
"agreement": 0.964,
"findings": "continuity-writer rationale-clause drift (5 gold files) fixed in this corpus version; wb-001 MRR fact added; conventions documented in README"
+ },
+ "hand_authored": {
+ "fixtures": 7,
+ "ids": [
+ "cont-001-widget-pass-reader",
+ "cont-001-widget-pass-writer",
+ "kta-001-deal-recall",
+ "kta-002-quiet-smalltalk",
+ "ms-001-two-source-alias",
+ "ms-002-nondefault-active",
+ "wb-001-pricing-concern"
+ ],
+ "note": "Outside the generator contract (drift guard counts gen-* files only). ms-002-nondefault-active is the sole non-default active_source fixture, added to exercise the harness cross-source leak detector's non-default arm. gen.ts rewrites this file on regen; re-add this block if it drops."
}
}
diff --git a/evals/brainbench/baselines/main.json b/evals/brainbench/baselines/main.json
index 8cd7612e16..324366876b 100644
--- a/evals/brainbench/baselines/main.json
+++ b/evals/brainbench/baselines/main.json
@@ -1,6 +1,6 @@
{
"schema_version": 1,
- "fixtures_hash": "76f201590dd3ad7a929e2e12efc9bf1406627b10ef4edbcfe7caf379aafd4090",
+ "fixtures_hash": "509fd20d7cda693350030393b6d54154e2685516d30f017ca219bd25e92c0e57",
"config": {
"include_holdout": false,
"llm": false,
@@ -16,6 +16,7 @@
"write-back"
]
},
+ "justification": "ms-002-nondefault-active added (hand-authored): exercises the cross-source leak detector's non-default active_source arm — active_source=teambrain with a twin slug seeded into default+teambrain, a teambrain-only page, and a default-only leak canary. +3 know-to-ask gold turns and +2 push gold turns per harness, all passing on all three harnesses; every gated metric moved favorably or held, source_isolation_violations stays 0.",
"cells": {
"claude-code/continuity": {
"avg_injected_tokens": 75.3333,
@@ -23,15 +24,15 @@
"source_isolation_violations": 0
},
"claude-code/know-to-ask": {
- "avg_injected_tokens": 30.9247,
- "false_fire_rate": 0.0233,
- "know_to_ask_failure_rate": 0.15,
+ "avg_injected_tokens": 31.2416,
+ "false_fire_rate": 0.023,
+ "know_to_ask_failure_rate": 0.1452,
"source_isolation_violations": 0
},
"claude-code/push": {
- "avg_injected_tokens": 38.8077,
+ "avg_injected_tokens": 39.028,
"push_precision": 1,
- "push_recall": 0.6596,
+ "push_recall": 0.6667,
"source_isolation_violations": 0
},
"claude-code/write-back": {
@@ -44,15 +45,15 @@
"source_isolation_violations": 0
},
"codex/know-to-ask": {
- "avg_injected_tokens": 40.7123,
+ "avg_injected_tokens": 41,
"false_fire_rate": 0,
- "know_to_ask_failure_rate": 0.15,
+ "know_to_ask_failure_rate": 0.1452,
"source_isolation_violations": 0
},
"codex/push": {
- "avg_injected_tokens": 48.5865,
+ "avg_injected_tokens": 48.7664,
"push_precision": 1,
- "push_recall": 0.4468,
+ "push_recall": 0.4583,
"source_isolation_violations": 0
},
"codex/write-back": {
@@ -65,15 +66,15 @@
"source_isolation_violations": 0
},
"openclaw/know-to-ask": {
- "avg_injected_tokens": 33.7945,
+ "avg_injected_tokens": 34.0537,
"false_fire_rate": 0,
- "know_to_ask_failure_rate": 0.15,
+ "know_to_ask_failure_rate": 0.1452,
"source_isolation_violations": 0
},
"openclaw/push": {
- "avg_injected_tokens": 44.1346,
+ "avg_injected_tokens": 44.2056,
"push_precision": 1,
- "push_recall": 0.8085,
+ "push_recall": 0.8125,
"source_isolation_violations": 0
},
"openclaw/write-back": {
@@ -87,11 +88,11 @@
"gold_failed": 0
},
"claude-code/know-to-ask": {
- "gold_total": 146,
+ "gold_total": 149,
"gold_failed": 11
},
"claude-code/push": {
- "gold_total": 94,
+ "gold_total": 96,
"gold_failed": 32
},
"claude-code/write-back": {
@@ -103,11 +104,11 @@
"gold_failed": 0
},
"codex/know-to-ask": {
- "gold_total": 146,
+ "gold_total": 149,
"gold_failed": 9
},
"codex/push": {
- "gold_total": 94,
+ "gold_total": 96,
"gold_failed": 52
},
"codex/write-back": {
@@ -119,11 +120,11 @@
"gold_failed": 0
},
"openclaw/know-to-ask": {
- "gold_total": 146,
+ "gold_total": 149,
"gold_failed": 9
},
"openclaw/push": {
- "gold_total": 94,
+ "gold_total": 96,
"gold_failed": 18
},
"openclaw/write-back": {
diff --git a/evals/brainbench/fixtures/ms-002-nondefault-active.fixture.json b/evals/brainbench/fixtures/ms-002-nondefault-active.fixture.json
new file mode 100644
index 0000000000..ed7b3286bb
--- /dev/null
+++ b/evals/brainbench/fixtures/ms-002-nondefault-active.fixture.json
@@ -0,0 +1,33 @@
+{
+ "schema_version": 1,
+ "fixture_id": "ms-002-nondefault-active",
+ "suites": ["know-to-ask", "push"],
+ "category": "multi-source",
+ "sources": ["teambrain"],
+ "active_source": "teambrain",
+ "seed_pages": [
+ {
+ "slug": "people/bianca-example",
+ "content": "---\ntitle: Bianca Example\ntype: person\naliases: [bianca]\nsummary: Founder of Latticework Co (personal notes).\n---\n\nBianca Example is the founder of Latticework Co. Personal-source twin copy — must not be the one graded while the team brain is active.\n"
+ },
+ {
+ "slug": "people/bianca-example",
+ "source_id": "teambrain",
+ "content": "---\ntitle: Bianca Example\ntype: person\naliases: [bianca]\nsummary: Candidate profile in the team brain.\n---\n\nBianca Example, candidate profile. TEAM BRAIN copy — the active source's copy for this fixture.\n"
+ },
+ {
+ "slug": "projects/orbit-example",
+ "source_id": "teambrain",
+ "content": "---\ntitle: Orbit Example\ntype: project\nsummary: Team-brain-only project page.\n---\n\nOrbit Example exists ONLY in the team brain. Injecting it while teambrain is active is correct, not a leak.\n"
+ },
+ {
+ "slug": "companies/widgetline-example",
+ "content": "---\ntitle: Widgetline Example\ntype: company\nsummary: Personal-brain-only company page.\n---\n\nWidgetline Example exists ONLY in the personal source. It must never surface while the team brain is active.\n"
+ }
+ ],
+ "turns": [
+ { "turn_id": 1, "role": "user", "text": "What do we know about Bianca Example?" },
+ { "turn_id": 2, "role": "user", "text": "What do I know about Orbit Example?" },
+ { "turn_id": 3, "role": "user", "text": "Anything on Widgetline Example in here?" }
+ ]
+}
diff --git a/evals/brainbench/gold/ms-002-nondefault-active.gold.json b/evals/brainbench/gold/ms-002-nondefault-active.gold.json
new file mode 100644
index 0000000000..1a88672ddb
--- /dev/null
+++ b/evals/brainbench/gold/ms-002-nondefault-active.gold.json
@@ -0,0 +1,16 @@
+{
+ "fixture_id": "ms-002-nondefault-active",
+ "turns": {
+ "1": {
+ "should_retrieve": true,
+ "gold_slugs": ["people/bianca-example"]
+ },
+ "2": {
+ "should_retrieve": true,
+ "gold_slugs": ["projects/orbit-example"]
+ },
+ "3": {
+ "should_retrieve": false
+ }
+ }
+}
diff --git a/llms-full.txt b/llms-full.txt
index be43c0951c..0d08b6a5ba 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1823,6 +1823,8 @@ gbrain connect https://your-host/mcp --token gbrain_xxx --install
gbrain connect https://your-host/mcp --token gbrain_xxx --agent codex --install # Codex
```
+Onboarding a whole agent harness onto a shared brain? On the brain host, `gbrain agent register <name> --harness claude-code` mints a scoped OAuth client plus a 30-day token and prints the paste-ready wiring block — presets for daily-driver and write-isolated coding agents. The [onboarding decision table](docs/guides/agent-to-gbrain.md#onboarding-paths--the-decision-table) says which path fits.
+
**Brain-only install into another coding agent** (Cursor, Claude Cowork, or anything that can fetch a URL and run shell commands) — paste the OpenClaw/Hermes block above (`INSTALL_FOR_AGENTS.md`); it installs the brain, skills, and dream cycle without the personal-agent identity layer. Tested with Codex, Claude Code, Claude Cowork, Cursor, and AlphaClaw.
**[→ Full walkthrough: give your coding agent a memory](docs/tutorials/connect-coding-agent.md)** — the memory-only paths end to end, plus the brain-first protocol you paste into `CLAUDE.md` / `AGENTS.md` and the four habits that make it actually change how you work.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 782601857a..d4aad4abfb 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.12.3",
+ "version": "0.46.13.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 5b5eb97334..e4c17944d2 100644
--- a/package.json
+++ b/package.json
@@ -170,7 +170,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.12.3",
+ "version": "0.46.13.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin/README.md b/plugin/README.md
index 6cf45405c3..0d321fe3f0 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.12.3 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.13.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/plugin/skills/setup/SKILL.md b/plugin/skills/setup/SKILL.md
index e2b8be71f4..6701355f4c 100644
--- a/plugin/skills/setup/SKILL.md
+++ b/plugin/skills/setup/SKILL.md
@@ -132,6 +132,11 @@ Continue with the existing `gbrain init --supabase` / `--pglite` setup below.
`gbrain remote doctor` (Tier B convenience commands) call MCP ops with
`admin` scope. `read,write` alone breaks ping/doctor.
+ For agent harnesses (Claude Code, Codex, opencode, OpenClaw), the host
+ operator can instead run `gbrain agent register` — it mints the scoped
+ client AND prints the paste-ready harness config in one step (see
+ https://github.com/garrytan/gbrain/blob/master/docs/guides/agent-to-gbrain.md).
+
3. **Run thin-client init on this machine:**
```bash
gbrain init --mcp-only \
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f78392b510..e0fde3a067 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -10,12 +10,12 @@ src/core/pglite-engine.ts 5660 ratchet peel target: containment sprint C15; grow
src/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted
src/commands/sync.ts 4300 ratchet peel target: containment sprint C13-C14; grown v0.46.11.0 five-issue wave
src/core/ai/gateway.ts 4117 ratchet watchlist
-src/cli.ts 3385 ratchet watchlist; +21 gap-closure wave: thin-client routing call sites (logic in commands/thin-client-routing.ts)
+src/cli.ts 3433 ratchet watchlist; +21 gap-closure wave thin-client routing; +cathedral-6 agent-register pre-connect guards + `--`-aware help + shared thin-client message import
src/core/cycle.ts 2933 ratchet
-src/commands/serve-http.ts 2836 ratchet
+src/commands/serve-http.ts 2962 ratchet grown cathedral-6 multi-agent wave (admin register route composes registerScopedClient in one tx under the name advisory lock; ttl validation + brain_too_old preflight)
src/commands/jobs.ts 2950 ratchet grown v0.46.11.0 five-issue wave
src/core/search/hybrid.ts 2479 ratchet
-src/core/engine.ts 2343 ratchet
+src/core/engine.ts 2345 ratchet
src/commands/autopilot.ts 2301 ratchet
src/commands/extract.ts 2161 ratchet
src/commands/extract-conversation-facts.ts 1968 ratchet
@@ -30,6 +30,6 @@ src/commands/integrations.ts 1675 ratchet
src/core/minions/handlers/subagent.ts 1643 ratchet
src/commands/bootstrap.ts 1923 ratchet grandfathered at merge (grew past the 1500 cap on master)
src/core/minions/worker.ts 1560 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave
-src/commands/sources.ts 1586 ratchet
-src/core/bootstrap/harness.ts 1947 ratchet
+src/commands/sources.ts 1642 ratchet grown cathedral-6 fix wave (remove: in-tx referents re-check + DELETE commits before external teardown)
+src/core/bootstrap/harness.ts 1914 ratchet
src/commands/hook.ts 1525 ratchet
diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh
index c7754199a8..c993034312 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -227,13 +227,17 @@ for f in "${files[@]}"; do
# assertion output, which reads like a mystery failure. CI runs those
# files in their own job WITHOUT this wrapper (see .github/workflows/
# e2e.yml tier2), so the cap only ever bit local runs: give them 4x.
+ # serve-http-multi-agent rides the same carve-out for a different reason:
+ # it spawns TWO `gbrain serve --http` subprocesses (19133 + a chaos serve
+ # on 19134) plus several CLI register subprocesses, so its wall clock is
+ # process-spawn-bound, not test-bound.
file_timeout="${GBRAIN_E2E_FILE_TIMEOUT:-${E2E_FILE_TIMEOUT_SECS:-180}}"
# Digits-only validation (same strict positive-int posture as the TS env
# knobs): a malformed value falls back to the default instead of
# word-splitting into extra gtimeout arguments or breaking the 4x math.
case "$file_timeout" in ''|*[!0-9]*) file_timeout=180 ;; esac
case "$f" in
- */skills.test.ts|*/zeroentropy-live.test.ts) file_timeout=$((file_timeout * 4)) ;;
+ */skills.test.ts|*/zeroentropy-live.test.ts|*/serve-http-multi-agent.test.ts) file_timeout=$((file_timeout * 4)) ;;
esac
if command -v gtimeout >/dev/null 2>&1; then
TIMEOUT_CMD="gtimeout $file_timeout"
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index ffc23f5c8d..33dce90cd1 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -2,6 +2,9 @@
# GENERATED by scripts/classify-tests.ts; freshness-checked in verify.
# Fix misclassifications in the classifier, never by hand-editing rows.
# Columns: file suite cases detector
+test/agent-register.test.ts PGLite integration (pre-flight → tx → audit → exchange) 3 readFileSync
+test/agent-register.test.ts resolvePreset 7 readFileSync
+test/agent-register.test.ts structural guards 2 readFileSync
test/apply-migrations.test.ts failed migration prints phase detail (#921) 1 readFileSync
test/apply-migrations.test.ts resolveSchemaBehind (#1530) 5 readFileSync
test/apply-migrations.test.ts runApplyMigrations exit codes (v0.36.1.x #1062) 1 readFileSync
@@ -57,6 +60,9 @@ test/cycle-patterns-deadline-budget.test.ts deadline plumbing wiring (structural
test/cycle-patterns.test.ts patterns phase wiring 9 readFileSync
test/cycle-patterns.test.ts patterns scope filter 6 readFileSync
test/cycle/cycle-lock-ttl.test.ts cycle lock TTL (T2 regression pin) 1 readFileSync
+test/destructive-guard.test.ts FK-RESTRICT lifecycle (clientsReferencingSource + purge skip) 9 readFileSync
+test/destructive-guard.test.ts assessDestructiveImpact 5 readFileSync
+test/destructive-guard.test.ts formatters (display helpers) 4 readFileSync
test/doctor-embedding-env-override.test.ts cross-surface parity (source-grep regression guard) 1 doctor-source-helper
test/doctor-fix.test.ts gbrain doctor --fix CLI integration 3 readFileSync
test/doctor-frontmatter-partial.test.ts doctor frontmatter_integrity — load-bearing render strings 5 doctor-source-helper
diff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.md
index e2b8be71f4..6701355f4c 100644
--- a/skills/setup/SKILL.md
+++ b/skills/setup/SKILL.md
@@ -132,6 +132,11 @@ Continue with the existing `gbrain init --supabase` / `--pglite` setup below.
`gbrain remote doctor` (Tier B convenience commands) call MCP ops with
`admin` scope. `read,write` alone breaks ping/doctor.
+ For agent harnesses (Claude Code, Codex, opencode, OpenClaw), the host
+ operator can instead run `gbrain agent register` — it mints the scoped
+ client AND prints the paste-ready harness config in one step (see
+ https://github.com/garrytan/gbrain/blob/master/docs/guides/agent-to-gbrain.md).
+
3. **Run thin-client init on this machine:**
```bash
gbrain init --mcp-only \
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 7d20b10f65..5ae71ab23a 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -151,7 +151,7 @@
"resolve-before-asking/routing-eval.jsonl": "bac1bcf30337f5255ef4ce1a2a8a2b38d58ebcd576503c483190c79ec6e69489",
"schema-author/SKILL.md": "1dd11a44dabcb7d57244be4cf5f4903feb9d146bcbb4363fc150daefc01d04ce",
"schema-unify/SKILL.md": "e9ac84018d673d35f749a1f74380d635512308fa50951995a7cb339ab4c85fa6",
- "setup/SKILL.md": "7f11b70ed89d4bff87096aa7e7bb0d41191eb46682066f3b2cffa7a326b56330",
+ "setup/SKILL.md": "f014513080eb81e90f0cc0203ca944698fdff250059be0267f0498c5b69c5416",
"signal-detector/SKILL.md": "c85772f129b3a5b5b0edfa191e11b1048942e52b7472bbaea224e7188f8af75a",
"skill-autobench/SKILL.md": "144572ec76f3784a97645dfde587ab13d77e804f50b00dc7fbe678204de6ff21",
"skill-autobench/routing-eval.jsonl": "8d961ed6403b7e2f690948e4c18529d40f26f6f21064befc56d465966b1a9ec0",
diff --git a/src/cli.ts b/src/cli.ts
index d345fccc1c..ae21b076aa 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -80,6 +80,12 @@ export const CLI_ONLY = new Set(['init', 'reinit-pglite', 'pglite-repair', 'upgr
// per-subcommand usage stays reachable.
const CLI_ONLY_SELF_HELP = new Set([
'upgrade', 'post-upgrade', 'check-update',
+ // cathedral-6: agent ships per-subcommand help (run/logs/register) inside
+ // runAgent, answered before any engine or queue is touched. Paired with the
+ // SELF_HELP_WITHOUT_ENGINE entry below so a brainless machine gets real
+ // help, and with the `--`-aware help scan in main() so
+ // `agent run -- --help` submits the literal prompt instead.
+ 'agent',
// whoknows honours --help first (runWhoknows HELP block, whoknows.ts).
'whoknows',
// #3502 sweep: pages + bench print their own usage (pages.ts printHelp,
@@ -197,6 +203,9 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, () => Promise<(engine: never, arg
// runDream accepts BrainEngine | null; --help (and `retriage --help`) is
// answered before any engine-bearing work per the dream.ts IRON RULE.
dream: async () => (await import('./commands/dream.ts')).runDream as never,
+ // runAgent accepts BrainEngine | null; help (incl. `register --help`) is
+ // answered before any engine or job-queue work (cathedral-6).
+ agent: async () => (await import('./commands/agent.ts')).runAgent as never,
// The retired ze-switch shim answers --help engine-free (arg-order adapter
// lives in ze-switch.ts because runZeSwitch takes (args, engine)).
'ze-switch': async () => (await import('./commands/ze-switch.ts')).runZeSwitchSelfHelp as never,
@@ -442,8 +451,13 @@ async function main() {
return;
}
- // Per-command --help
- if (hasHelpFlag(subArgs)) {
+ // Per-command --help. For `agent`, the scan STOPS at the `--` terminator:
+ // everything after it is literal prompt text, so `agent run -- --help`
+ // must submit the prompt, never print help (cathedral-6 eng review).
+ const helpScanArgs = command === 'agent' && subArgs.includes('--')
+ ? subArgs.slice(0, subArgs.indexOf('--'))
+ : subArgs;
+ if (hasHelpFlag(helpScanArgs)) {
// `eval brainbench` ships a published foreign-runner flag surface — its
// own usage() must win over the generic eval stub (codex P3). Fall
// through to handleCliOnly's no-DB brainbench route, which prints it.
@@ -1740,6 +1754,40 @@ async function handleCliOnly(command: string, args: string[]) {
}
}
+ // cathedral-6: `agent register` guards run PRE-connectEngine. A thin client
+ // would otherwise build a scratch PGLite and mint dead credentials into it;
+ // a live PGLite serve holds the single-writer lock, so connectEngine would
+ // hang ~30s before any handler code could print guidance. (`agent` itself
+ // stays out of THIN_CLIENT_REFUSED_COMMANDS — run/logs work elsewhere.)
+ if (command === 'agent' && args[0] === 'register' && !hasHelpFlag(args)) {
+ const cfg = loadConfig();
+ const wantsJson = args.includes('--json');
+ const refuse = (reason: string, message: string) => {
+ if (wantsJson) {
+ console.log(JSON.stringify({ ok: false, reason, message }));
+ } else {
+ console.error(`Error: ${message}`);
+ }
+ process.exit(1);
+ };
+ if (isThinClient(cfg)) {
+ // Shared verbatim with the in-handler belt-and-braces re-check. Lazy
+ // import: this guard runs pre-connect for `agent register` only, and a
+ // top-level import would eager-load the register module on every CLI
+ // start.
+ const { THIN_CLIENT_REGISTER_MESSAGE } = await import('./commands/agent-register.ts');
+ refuse('thin_client', THIN_CLIENT_REGISTER_MESSAGE);
+ }
+ if (cfg && !cfg.database_url && cfg.database_path) {
+ const { probeLivePgliteHolder } = await import('./core/bootstrap/uninstall.ts');
+ const holder = probeLivePgliteHolder(cfg.database_path);
+ if (holder?.serve) {
+ refuse('pglite_live_serve',
+ `a live \`gbrain serve\` (pid ${holder.pid}) holds this PGLite brain's single-writer lock — stop the serve, run \`gbrain agent register\` again, then restart it. (Postgres brains register fine while the serve runs.)`);
+ }
+ }
+ }
+
// Commands that don't need a database connection
if (command === 'schema') {
const { runSchema } = await import('./commands/schema.ts');
diff --git a/src/commands/agent-register.ts b/src/commands/agent-register.ts
new file mode 100644
index 0000000000..b181057466
--- /dev/null
+++ b/src/commands/agent-register.ts
@@ -0,0 +1,961 @@
+/**
+ * gbrain agent register — mint a scoped OAuth client + access token and print
+ * the exact MCP wiring for a harness (cathedral-6, spec PR-6 "shared brain").
+ *
+ * CLI-ONLY, never an MCP op. Composes existing parts — registerScopedClient
+ * (auth.ts peel), exchangeClientCredentials, the mcp-registration argv
+ * builders, renderCodexHttpServerBlock, openclawThinClientBlock — it builds
+ * no new auth machinery.
+ *
+ * register flow (order is load-bearing):
+ * [cli.ts pre-connect guards: thin client refusal + PGLite live-serve]
+ * → parse (pure, exit 2) → preset resolve (pure)
+ * → validate sources (existence + archived, engine lane)
+ * → column PRE-FLIGHT (outside any tx — 25P02 forbids in-tx degrade)
+ * → ONE engine.transaction:
+ * name advisory lock → duplicate-name pre-check
+ * → ensureWorkspaceSource (create-or-clean-reuse, refuse dirty)
+ * → registerScopedClient (INSERT + ttl UPDATE + surface rescope)
+ * → COMMIT
+ * → audit (fail-open, designed post-commit position)
+ * → exchangeClientCredentials (outer engine — the tx sql is dead)
+ * → optional serve probe (--url/--port; note, never a failure)
+ * → render harness block → print (human) | single JSON doc
+ *
+ * Failure after COMMIT leaves a live client (and possibly a clean, empty
+ * workspace source): we print the client_id + the exact revoke command —
+ * never a false "nothing was created".
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { loadConfig, isThinClient } from '../core/config.ts';
+import { sqlQueryForEngine, type SqlQuery } from '../core/sql-query.ts';
+import { assertAllowedScopes } from '../core/scope.ts';
+import { assertValidSourceId, ALL_SOURCES, SOURCE_ID_RE } from '../core/source-id.ts';
+import { addSource } from '../core/sources-ops.ts';
+import { loadAllSources } from '../core/sources-load.ts';
+import { generateToken, hashToken } from '../core/utils.ts';
+import {
+ normalizeMcpUrl,
+ issuerFromMcpUrl,
+ isValidName,
+ buildClaudeMcpAddArgv,
+ buildCodexMcpAddArgv,
+ buildOpencodeMcpAddArgv,
+ cmdString,
+ shellQuote,
+ openclawThinClientBlock,
+ OAUTH_SECRET_NOTE,
+ REDACTED,
+} from '../core/mcp-registration.ts';
+import { GBRAIN_REMOTE_TOKEN_ENV } from '../core/bootstrap/opencode-json.ts';
+import { renderCodexHttpServerBlock } from '../core/bootstrap/codex-toml.ts';
+import { probeServeHealth, isServeOlderThanScopes, SCOPES_MIN_SERVE_VERSION } from '../core/bootstrap/serve-health.ts';
+import { writeSurfaceChangeAudit } from '../core/surface-audit.ts';
+import {
+ registerScopedClient,
+ preflightOauthClientColumns,
+ parseRegisterClientArgs,
+ parseTokenTtl,
+ type RegisterClientArgs,
+ type RegisteredClient,
+} from './auth.ts';
+
+// ── constants ─────────────────────────────────────────────────────────────
+
+export const REGISTER_HARNESSES = ['claude-code', 'codex', 'opencode', 'openclaw'] as const;
+export type RegisterHarness = (typeof REGISTER_HARNESSES)[number];
+export const REGISTER_PRESETS = ['daily-driver', 'coding-agent'] as const;
+export type RegisterPreset = (typeof REGISTER_PRESETS)[number];
+
+/** Register ALWAYS writes token_ttl: the server default for CLI-minted access
+ * tokens is 3600s — a printed "30-day" config with the default TTL would die
+ * in an hour. 30 days, inside the auth.ts bounds. */
+export const REGISTER_DEFAULT_TOKEN_TTL_SECONDS = 2_592_000;
+
+/** Scopes an agent client may not hold — operators use auth register-client. */
+const SCOPE_BLOCKLIST = new Set(['admin', 'sources_admin', 'users_admin', 'agent']);
+
+/** Derived-workspace source suffix. Exported for the doctor
+ * oauth_client_scope_health orphan heuristic (single source of truth). */
+export const WORKSPACE_SUFFIX = '-workspace';
+/** SOURCE_ID_RE caps ids at 32 chars; '-workspace' is 10. */
+export const WORKSPACE_NAME_MAX = 22;
+
+/** Advisory-lock key for name-scoped registration/rotation serialization.
+ * Cross-process wire contract (pinned in test/lock-keys.test.ts) — every
+ * writer hashing a different string holds a different lock. */
+export function registerClientNameLockKey(name: string): string {
+ return `register_client_name:${name}`;
+}
+
+/** The thin-client refusal, shared verbatim by the cli.ts pre-connect guard
+ * and the in-handler belt-and-braces re-check. */
+export const THIN_CLIENT_REGISTER_MESSAGE =
+ '`gbrain agent register` mints credentials into the HOST brain — run it on the brain host (the machine that runs `gbrain serve --http`), then wire this machine with the printed `gbrain init --mcp-only …` block.';
+
+export type RegisterFailReason =
+ | 'invalid_argument'
+ | 'unknown_source'
+ | 'archived_source'
+ | 'dirty_source'
+ | 'duplicate_name'
+ | 'thin_client'
+ | 'pglite_live_serve'
+ | 'reissue_invalid_target'
+ | 'mint_failed'
+ | 'brain_too_old'
+ | 'serve_too_old'
+ | 'internal';
+
+export class RegisterError extends Error {
+ constructor(
+ public reason: RegisterFailReason,
+ message: string,
+ public clientId?: string,
+ ) {
+ super(message);
+ }
+}
+
+// ── parsing (pure) ────────────────────────────────────────────────────────
+
+export interface AgentRegisterArgs {
+ name?: string;
+ reissueClientId?: string;
+ harness?: RegisterHarness;
+ preset?: RegisterPreset;
+ source?: string;
+ federatedRead?: string[];
+ scopes?: string;
+ url?: string;
+ port?: number;
+ tokenTtlSeconds?: number;
+ surface?: 'verbs' | 'starter' | 'full';
+ showToken: boolean;
+ json: boolean;
+ /** Accept a PROVEN-too-old serve (< SCOPES_MIN_SERVE_VERSION verifies
+ * scoped tokens as FULL ACCESS) instead of failing registration. */
+ allowOldServe: boolean;
+}
+
+const REGISTER_USAGE =
+ 'Usage: gbrain agent register <name> --harness claude-code|codex|opencode|openclaw ' +
+ '[--preset daily-driver|coding-agent] [--source ID] [--federated-read S1,S2] ' +
+ '[--scopes "read write"] (--url URL | --port N) [--token-ttl SECONDS] ' +
+ '[--surface verbs|starter|full] [--allow-old-serve] [--show-token] [--json]\n' +
+ ' gbrain agent register --reissue <client-id> --harness H (--url URL | --port N) [--show-token] [--json]';
+
+export function parseAgentRegisterArgs(args: string[]): AgentRegisterArgs {
+ const out: AgentRegisterArgs = { showToken: false, json: false, allowOldServe: false };
+ let i = 0;
+ while (i < args.length) {
+ const flag = args[i];
+ const value = args[i + 1];
+ const requireValue = () => {
+ if (value === undefined || value.startsWith('--')) {
+ throw new Error(`${flag} requires a value`);
+ }
+ return value;
+ };
+ if (!flag.startsWith('--')) {
+ if (out.name !== undefined) throw new Error(`Unexpected argument: ${flag}`);
+ out.name = flag;
+ i += 1;
+ continue;
+ }
+ switch (flag) {
+ case '--reissue':
+ out.reissueClientId = requireValue();
+ i += 2; break;
+ case '--harness': {
+ const v = requireValue();
+ if (!(REGISTER_HARNESSES as readonly string[]).includes(v)) {
+ throw new Error(`--harness must be one of ${REGISTER_HARNESSES.join(' | ')} (got "${v}")`);
+ }
+ out.harness = v as RegisterHarness;
+ i += 2; break;
+ }
+ case '--preset': {
+ const v = requireValue();
+ if (!(REGISTER_PRESETS as readonly string[]).includes(v)) {
+ throw new Error(`--preset must be ${REGISTER_PRESETS.join(' | ')} (got "${v}")`);
+ }
+ out.preset = v as RegisterPreset;
+ i += 2; break;
+ }
+ case '--source': {
+ const v = requireValue();
+ assertValidSourceId(v);
+ out.source = v;
+ i += 2; break;
+ }
+ case '--federated-read': {
+ const v = requireValue();
+ // Set-dedupe (order-preserving): a repeated id would otherwise fan
+ // out twice in every downstream per-source loop.
+ const ids = [...new Set(v.split(',').map(s => s.trim()).filter(Boolean))];
+ if (ids.length === 0) throw new Error('--federated-read requires at least one source id');
+ for (const id of ids) {
+ if (id === ALL_SOURCES) {
+ throw new Error('no wildcard read grant exists — list sources explicitly (__all__ is a trusted-local sentinel, never a grant)');
+ }
+ assertValidSourceId(id);
+ }
+ out.federatedRead = ids;
+ i += 2; break;
+ }
+ case '--scopes': {
+ // Tokenize exactly like auth.ts's register-client parser, then apply
+ // the agent blocklist per-token, then the shared allowlist.
+ const v = requireValue();
+ const tokens = v.split(/[\s,]+/).filter(Boolean);
+ if (tokens.length === 0) {
+ throw new Error(`--scopes requires at least one scope (got ${JSON.stringify(v)})`);
+ }
+ for (const t of tokens) {
+ if (SCOPE_BLOCKLIST.has(t)) {
+ throw new Error(`scope "${t}" is not grantable to an agent client — use \`gbrain auth register-client\` for operator-grade scopes`);
+ }
+ }
+ assertAllowedScopes(tokens);
+ out.scopes = tokens.join(' ');
+ i += 2; break;
+ }
+ case '--url':
+ out.url = requireValue();
+ i += 2; break;
+ case '--port': {
+ const raw = requireValue();
+ const v = Number(raw);
+ if (!Number.isInteger(v) || v < 1 || v > 65535) {
+ throw new Error(`--port must be an integer between 1 and 65535 (got ${JSON.stringify(raw)})`);
+ }
+ out.port = v;
+ i += 2; break;
+ }
+ case '--token-ttl': {
+ out.tokenTtlSeconds = parseTokenTtl(requireValue(), 'Omit the flag for the 30-day default.');
+ i += 2; break;
+ }
+ case '--surface': {
+ const v = requireValue();
+ if (v !== 'verbs' && v !== 'starter' && v !== 'full') {
+ throw new Error(`--surface must be verbs | starter | full (got "${v}")`);
+ }
+ out.surface = v;
+ i += 2; break;
+ }
+ case '--allow-old-serve': out.allowOldServe = true; i += 1; break;
+ case '--show-token': out.showToken = true; i += 1; break;
+ case '--json': out.json = true; i += 1; break;
+ default:
+ throw new Error(`Unknown flag: ${flag}`);
+ }
+ }
+
+ if (out.reissueClientId !== undefined) {
+ if (out.name !== undefined) throw new Error('--reissue takes a client-id, not a name');
+ if (out.preset || out.source || out.federatedRead || out.scopes || out.surface || out.tokenTtlSeconds !== undefined) {
+ throw new Error('--reissue only rotates the secret and reprints the block — scope flags are not allowed (use `gbrain auth rescope-client` to change scope)');
+ }
+ } else {
+ if (!out.name) throw new Error(`agent register requires a <name>.\n${REGISTER_USAGE}`);
+ if (!isValidName(out.name)) {
+ throw new Error(`invalid name "${out.name}" — lowercase letters, digits, - and _ only (it becomes the MCP server name)`);
+ }
+ }
+ if (!out.harness) throw new Error(`--harness is required.\n${REGISTER_USAGE}`);
+ if (out.url !== undefined && out.port !== undefined) {
+ throw new Error('pass --url OR --port, not both');
+ }
+ return out;
+}
+
+// ── preset resolution (pure descriptor; snapshot resolved by the runner) ──
+
+export interface ResolvedPreset {
+ scopes: string;
+ writeSource: string;
+ /** 'snapshot' = all non-archived sources at registration time. */
+ federatedRead: string[] | 'snapshot';
+ surface?: 'verbs' | 'starter' | 'full';
+ /** The write source is the derived `<name>-workspace` (auto-creatable). */
+ workspaceDerived: boolean;
+}
+
+export function resolvePreset(flags: AgentRegisterArgs): ResolvedPreset {
+ const name = flags.name ?? '';
+ const explicit = <T>(v: T | undefined, fallback: T): T => (v !== undefined ? v : fallback);
+ switch (flags.preset) {
+ case 'daily-driver':
+ return {
+ scopes: explicit(flags.scopes, 'read write'),
+ writeSource: explicit(flags.source, 'default'),
+ federatedRead: flags.federatedRead ?? 'snapshot',
+ // starter is literally "the ~20-op daily-driver set" (mcp/surface.ts).
+ surface: explicit(flags.surface, 'starter'),
+ workspaceDerived: false,
+ };
+ case 'coding-agent': {
+ if (!flags.federatedRead || flags.federatedRead.length === 0) {
+ throw new Error(
+ 'coding-agent requires --federated-read: a coding agent that reads nothing but its own scratch workspace is a misconfiguration. Pass the project sources it should read, e.g. --federated-read proj-widget',
+ );
+ }
+ let writeSource = flags.source;
+ let workspaceDerived = false;
+ if (writeSource === undefined) {
+ if (name.length > WORKSPACE_NAME_MAX || !SOURCE_ID_RE.test(`${name}${WORKSPACE_SUFFIX}`)) {
+ throw new Error(
+ `cannot derive a workspace source from "${name}": "${name}${WORKSPACE_SUFFIX}" must match ${String(SOURCE_ID_RE)} (name ≤ ${WORKSPACE_NAME_MAX} chars, lowercase letters/digits/hyphens). Pass --source <id> or shorten the name.`,
+ );
+ }
+ writeSource = `${name}${WORKSPACE_SUFFIX}`;
+ workspaceDerived = true;
+ }
+ return {
+ scopes: explicit(flags.scopes, 'read write'),
+ writeSource,
+ federatedRead: [writeSource, ...flags.federatedRead.filter(s => s !== writeSource)],
+ // starter, not full: `full` exposes brain-wide unscoped code-intel
+ // reads to a scoped client. Widen per client via
+ // `gbrain auth rescope-client --surface full`.
+ surface: explicit(flags.surface, 'starter'),
+ workspaceDerived,
+ };
+ }
+ default:
+ // No preset → passthrough defaults matching `auth register-client`
+ // (no surface write, no snapshot).
+ return {
+ scopes: explicit(flags.scopes, 'read write'),
+ writeSource: explicit(flags.source, 'default'),
+ federatedRead: flags.federatedRead ?? [explicit(flags.source, 'default')],
+ surface: flags.surface,
+ workspaceDerived: false,
+ };
+ }
+}
+
+/**
+ * daily-driver snapshot grant: all non-archived sources EXCEPT derived agent
+ * workspaces (`*-workspace`). A workspace is another agent's scratch memory
+ * by construction — sharing one requires an explicit --federated-read grant,
+ * never a default-on snapshot sweep. The write source is re-added by the
+ * runner's write-source-always-readable invariant, so an operator who
+ * EXPLICITLY targets a workspace still gets it. Exported for the unit suite.
+ */
+export function snapshotGrantSources(ids: string[]): { granted: string[]; excludedWorkspaces: string[] } {
+ const granted: string[] = [];
+ const excludedWorkspaces: string[] = [];
+ for (const id of ids) {
+ (id.endsWith(WORKSPACE_SUFFIX) ? excludedWorkspaces : granted).push(id);
+ }
+ return { granted, excludedWorkspaces };
+}
+
+// ── runner ────────────────────────────────────────────────────────────────
+
+interface RegisterOutput {
+ registered: RegisteredClient;
+ accessToken?: string;
+ tokenExpiresAt?: string;
+ presetResolved: {
+ preset: string | null;
+ scopes: string;
+ write_source: string;
+ federated_read: string[];
+ surface: string | null;
+ token_ttl: number | null;
+ };
+ serveWarning: string | null;
+ probeNote: string | null;
+ block: string;
+ url: string;
+}
+
+function fail(json: boolean, reason: RegisterFailReason, message: string, exitCode: 1 | 2, clientId?: string): never {
+ if (json) {
+ console.log(JSON.stringify({ ok: false, reason, message, ...(clientId ? { client_id: clientId } : {}) }));
+ } else {
+ console.error(`Error: ${message}`);
+ if (clientId) {
+ console.error(`The OAuth client was created before the failure. Revoke with: gbrain auth revoke-client "${clientId}"`);
+ }
+ }
+ process.exit(exitCode);
+}
+
+export async function runAgentRegister(engine: BrainEngine | null, args: string[]): Promise<void> {
+ // Help is answered by runAgent BEFORE this is called; a null engine here
+ // means the dispatcher's help path leaked a real invocation — refuse.
+ const wantsJson = args.includes('--json');
+ if (engine === null) {
+ fail(wantsJson, 'internal', 'agent register needs a configured brain (no engine available).', 1);
+ }
+
+ // Belt-and-braces: cli.ts refuses pre-connect; re-check here for direct callers.
+ const cfg = loadConfig();
+ if (isThinClient(cfg)) {
+ fail(wantsJson, 'thin_client', THIN_CLIENT_REGISTER_MESSAGE, 1);
+ }
+
+ let flags: AgentRegisterArgs;
+ try {
+ flags = parseAgentRegisterArgs(args);
+ } catch (e: any) {
+ fail(wantsJson, 'invalid_argument', e.message, 2);
+ }
+
+ // --url | --port resolution (required by every harness block). The config
+ // remote_mcp fallback is dead by construction: thin clients are refused.
+ const rawUrl = flags.url ?? (flags.port !== undefined ? `http://localhost:${flags.port}/mcp` : undefined);
+ if (!rawUrl) {
+ fail(flags.json, 'invalid_argument',
+ `pass --url <mcp-url> or --port <serve-port> — every harness block embeds the brain URL. Example: --url https://brain.example.com/mcp\n${REGISTER_USAGE}`, 2);
+ }
+ const urlResult = normalizeMcpUrl(rawUrl);
+ if (!urlResult.ok) {
+ fail(flags.json, 'invalid_argument', urlResult.error, 2);
+ }
+ const url = urlResult.url;
+ const urlWarning = urlResult.warning ?? null;
+
+ const sql = sqlQueryForEngine(engine);
+
+ try {
+ if (flags.reissueClientId !== undefined) {
+ const out = await runReissue(sql, engine, flags, url, urlWarning);
+ printOutput(flags, out);
+ return;
+ }
+
+ const preset = resolvePreset(flags);
+ const name = flags.name!;
+
+ // Existence + not-archived check for a set of source ids. Engine lane
+ // for the ANY() — SqlQuery forbids arrays. Shared by the explicit and
+ // snapshot branches so the write source is validated the same way on both.
+ const validateSourceIds = async (ids: string[]): Promise<void> => {
+ const unique = [...new Set(ids)];
+ if (unique.length === 0) return;
+ const rows = await engine.executeRaw<{ id: string; archived: boolean | null }>(
+ `SELECT id, archived FROM sources WHERE id = ANY($1::text[])`,
+ [unique],
+ );
+ const found = new Map(rows.map(r => [r.id, r]));
+ for (const id of unique) {
+ const row = found.get(id);
+ if (!row) {
+ fail(flags.json, 'unknown_source',
+ `source "${id}" does not exist — create it first (gbrain sources add ${id}) or check the spelling with \`gbrain sources list\`. Only the derived <name>-workspace is auto-created.`, 1);
+ }
+ if (row.archived) {
+ fail(flags.json, 'archived_source',
+ `source "${id}" is archived — unarchive it or drop it from the grant.`, 1);
+ }
+ }
+ };
+
+ // Resolve the snapshot + validate every explicit source id (existence +
+ // not archived).
+ let federated: string[];
+ if (preset.federatedRead === 'snapshot') {
+ const all = await loadAllSources(engine, { includeArchived: false });
+ const snap = snapshotGrantSources(all.map(s => s.id));
+ federated = snap.granted;
+ if (snap.excludedWorkspaces.length > 0) {
+ console.error(
+ `Note: snapshot grant excludes ${snap.excludedWorkspaces.length} agent workspace source(s) ` +
+ `(${snap.excludedWorkspaces.join(', ')}) — agent scratch is not shared by default; ` +
+ `grant one explicitly with --federated-read.`,
+ );
+ }
+ // The snapshot proves existence + non-archived for its members only.
+ // A write source OUTSIDE it (and any explicitly passed --source, even
+ // when it happens to be inside) gets the same check as the explicit
+ // branch — otherwise a typo'd or archived --source would be granted
+ // and then die at the FK (or worse, silently write nowhere readable).
+ if (!federated.includes(preset.writeSource) || flags.source !== undefined) {
+ await validateSourceIds([preset.writeSource]);
+ }
+ } else {
+ federated = preset.federatedRead;
+ const toCheck = federated.filter(id => !(preset.workspaceDerived && id === preset.writeSource));
+ if (!preset.workspaceDerived) toCheck.push(preset.writeSource);
+ await validateSourceIds(toCheck);
+ }
+ // INVARIANT (every branch): the write source is always in the read grant.
+ // A client that can't read its own write source is a remember→recall
+ // black hole.
+ if (!federated.includes(preset.writeSource)) federated.push(preset.writeSource);
+
+ // Column pre-flight: OUTSIDE the tx (25P02 — nothing inside may degrade).
+ const columns = await preflightOauthClientColumns(sql);
+ // Pre-v61 brains lack the scoped-client columns entirely; refuse BEFORE
+ // the tx — registerClientManual's own 42703 retry ladder would die on
+ // 25P02 inside our transaction.
+ if (!columns.has('source_id') || !columns.has('federated_read')) {
+ fail(flags.json, 'brain_too_old',
+ 'this brain predates scoped OAuth clients (source_id/federated_read columns) — run `gbrain apply-migrations --yes` first.', 1);
+ }
+ const ttl = flags.tokenTtlSeconds ?? REGISTER_DEFAULT_TOKEN_TTL_SECONDS;
+ const preflightNotes: string[] = [];
+ if (!columns.has('token_ttl')) {
+ preflightNotes.push('this brain predates the token_ttl column; run `gbrain apply-migrations --yes` — the server default (1 hour) applies until then.');
+ }
+ if (preset.surface !== undefined && !columns.has('surface')) {
+ preflightNotes.push('this brain predates the surface column; run `gbrain apply-migrations --yes` — no per-client surface tier was set.');
+ }
+ for (const note of preflightNotes) console.error(`Note: ${note}`);
+
+ const registerArgs: RegisterClientArgs = {
+ grantTypes: ['client_credentials'],
+ scopes: preset.scopes,
+ sourceId: preset.writeSource,
+ federatedRead: federated,
+ redirectUris: [],
+ tokenEndpointAuthMethod: undefined,
+ boundTools: undefined,
+ boundSourceId: undefined,
+ boundBrainId: undefined,
+ boundSlugPrefixes: undefined,
+ boundMaxConcurrent: undefined,
+ budgetUsdPerDay: undefined,
+ tokenTtlSeconds: undefined,
+ };
+
+ let registered!: RegisteredClient;
+ let createdWorkspace = false;
+ await engine.transaction(async (tx) => {
+ const txSql = sqlQueryForEngine(tx);
+ // Name-scoped advisory lock: no unique index exists on client_name, so
+ // two concurrent registers of the same name would both pass the
+ // pre-check. xact-scoped — released at COMMIT/ROLLBACK.
+ await tx.executeRaw(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [registerClientNameLockKey(name)]);
+
+ const dupRows = columns.has('deleted_at')
+ ? await txSql`SELECT client_id FROM oauth_clients WHERE client_name = ${name} AND deleted_at IS NULL`
+ : await txSql`SELECT client_id FROM oauth_clients WHERE client_name = ${name}`;
+ if (dupRows.length > 0) {
+ throw new RegisterError('duplicate_name',
+ `an OAuth client named "${name}" already exists (${String(dupRows[0].client_id)}). Revoke it first (gbrain auth revoke-client "${String(dupRows[0].client_id)}") or rotate its secret with --reissue.`);
+ }
+
+ if (preset.workspaceDerived) {
+ createdWorkspace = await ensureWorkspaceSource(tx, txSql, preset.writeSource);
+ }
+
+ registered = await registerScopedClient(txSql, name, registerArgs, {
+ tokenTtlSeconds: ttl,
+ surface: preset.surface,
+ columns,
+ });
+ });
+ registered.created.source = createdWorkspace;
+
+ // POST-COMMIT: a client row now exists — from here, EVERY failure must
+ // carry the clientId so fail() prints the revoke guidance (never a false
+ // "nothing was created"). RegisterErrors keep their reason; anything else
+ // maps to mint_failed with the clientId attached.
+ try {
+ // Post-commit, fail-open audit (its designed position — never in the tx).
+ if (registered.surface !== undefined) {
+ await writeSurfaceChangeAudit(engine, {
+ actor: 'operator',
+ client_id: registered.clientId,
+ old: registered.surfaceOld ?? null,
+ new: registered.surface,
+ via: 'register_cli',
+ });
+ }
+
+ const out = await mintAndProbe(engine, flags, registered, name, url, urlWarning, {
+ preset: flags.preset ?? null,
+ scopes: preset.scopes,
+ write_source: preset.writeSource,
+ federated_read: federated,
+ surface: registered.surface ?? null,
+ token_ttl: registered.tokenTtl ?? null,
+ });
+ printOutput(flags, out);
+ } catch (e: any) {
+ if (e instanceof RegisterError) {
+ throw new RegisterError(e.reason, e.message, e.clientId ?? registered.clientId);
+ }
+ throw new RegisterError('mint_failed', e?.message ?? String(e), registered.clientId);
+ }
+ } catch (e: any) {
+ if (e instanceof RegisterError) {
+ fail(flags.json, e.reason, e.message, 1, e.clientId);
+ }
+ fail(flags.json, 'mint_failed', e?.message ?? String(e), 1);
+ }
+}
+
+/** Create the derived workspace source if missing; reuse only when clean.
+ * Returns true when this call created it. Never catches source_id_taken as
+ * control flow — existence is decided by SELECT first. "Clean" means: not
+ * archived, no local path, zero pages AND zero facts AND zero files (facts
+ * are the primary agent write lane, and files can exist page-less — a
+ * pages-only check would silently reuse a source that already holds another
+ * agent's memory). raw_data and links are FK-subsumed: both are page-scoped
+ * (NOT NULL page FKs, ON DELETE CASCADE, no source_id column), so they
+ * cannot be non-zero when the page count is zero; there is no `entities`
+ * table (entity pages count as pages, fact entities count as facts).
+ * Exported for the unit suite. */
+export async function ensureWorkspaceSource(
+ tx: BrainEngine,
+ txSql: SqlQuery,
+ id: string,
+): Promise<boolean> {
+ const existing = await txSql`SELECT id, local_path, archived FROM sources WHERE id = ${id}`;
+ if (existing.length > 0) {
+ if (existing[0].archived === true) {
+ throw new RegisterError('archived_source',
+ `workspace source "${id}" exists but is archived — unarchive it (gbrain sources restore ${id}) or pick another name.`);
+ }
+ const localPath = existing[0].local_path;
+ const pages = await txSql`SELECT count(*) AS n FROM pages WHERE source_id = ${id}`;
+ const nPages = Number(pages[0]?.n ?? 0);
+ const facts = await txSql`SELECT count(*) AS n FROM facts WHERE source_id = ${id}`;
+ const nFacts = Number(facts[0]?.n ?? 0);
+ // files: tolerant of a brain without the table — probed via
+ // information_schema (NEVER try/catch: this runs inside the register tx,
+ // where an aborted statement is a 25P02, not a degrade).
+ let nFiles = 0;
+ const filesTable = await txSql`
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = current_schema() AND table_name = 'files'`;
+ if (filesTable.length > 0) {
+ const files = await txSql`SELECT count(*) AS n FROM files WHERE source_id = ${id}`;
+ nFiles = Number(files[0]?.n ?? 0);
+ }
+ if (localPath != null || nPages > 0 || nFacts > 0 || nFiles > 0) {
+ const why = localPath != null
+ ? 'is backed by a local path'
+ : nPages > 0 ? `holds ${nPages} pages`
+ : nFacts > 0 ? `holds ${nFacts} facts` : `holds ${nFiles} files`;
+ throw new RegisterError('dirty_source',
+ `source "${id}" already exists and ${why} — pass --source ${id} to reuse it deliberately, or pick another agent name.`);
+ }
+ console.error(`Note: reusing existing empty workspace source "${id}".`);
+ return false;
+ }
+ await addSource(tx, { id });
+ return true;
+}
+
+/** Shared tail: exchange client credentials, probe the serve, build the block.
+ * `blockName` is the MCP server name embedded in the harness block: the agent
+ * name on the register lane, the stored client_name (when valid) on reissue. */
+async function mintAndProbe(
+ engine: BrainEngine,
+ flags: AgentRegisterArgs,
+ registered: RegisteredClient,
+ blockName: string,
+ url: string,
+ urlWarning: string | null,
+ presetResolved: RegisterOutput['presetResolved'],
+): Promise<RegisterOutput> {
+ const { GBrainOAuthProvider } = await import('../core/oauth-provider.ts');
+ // The tx-scoped sql is dead after COMMIT — the exchange runs on the OUTER engine.
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine) });
+
+ let accessToken: string | undefined;
+ let tokenExpiresAt: string | undefined;
+ if (registered.clientSecret) {
+ try {
+ const tokens = await provider.exchangeClientCredentials(registered.clientId, registered.clientSecret);
+ accessToken = tokens.access_token;
+ if (typeof tokens.expires_in === 'number') {
+ tokenExpiresAt = new Date(Date.now() + tokens.expires_in * 1000).toISOString();
+ }
+ } catch (e: any) {
+ throw new RegisterError('mint_failed',
+ `client registered but the token exchange failed: ${e?.message ?? String(e)}`, registered.clientId);
+ }
+ }
+
+ // Serve probe. An UNREACHABLE serve stays a note (it proves nothing). A
+ // reachable serve that PROVES version < SCOPES_MIN_SERVE_VERSION fails the
+ // registration lane — that serve verifies the freshly-minted scoped token
+ // as FULL ACCESS — unless the operator passed --allow-old-serve. The
+ // reissue lane keeps the warning: by this point the secret is already
+ // ROTATED, and failing would discard the only copy of the new credential.
+ let probeNote: string | null = null;
+ const health = await probeServeHealth(url, fetch);
+ if (!health.ok) {
+ probeNote = `could not reach ${url.replace(/\/mcp$/, '')}/health — skipping the scoped-token version check (${health.detail ?? 'unreachable'}).`;
+ } else if (health.version && isServeOlderThanScopes(health.version)) {
+ if (flags.reissueClientId === undefined && !flags.allowOldServe) {
+ throw new RegisterError('serve_too_old',
+ `serve at ${url} reports v${health.version} — older than ${SCOPES_MIN_SERVE_VERSION}, so it verifies this scoped token as FULL ACCESS (the scope grant is not enforced). Upgrade the serve, or re-run with --allow-old-serve to accept the risk.`,
+ registered.clientId);
+ }
+ probeNote = `serve at ${url} reports v${health.version} — OLDER than ${SCOPES_MIN_SERVE_VERSION}: it verifies this scoped token as FULL ACCESS. Upgrade the serve.`;
+ } else {
+ probeNote = `serve health: OK${health.version ? ` (v${health.version})` : ''}.`;
+ }
+
+ const block = buildHarnessBlock(flags.harness!, {
+ name: blockName,
+ url,
+ token: accessToken ?? null,
+ clientId: registered.clientId,
+ clientSecret: registered.clientSecret ?? null,
+ showToken: flags.showToken,
+ expiresAt: tokenExpiresAt ?? null,
+ isReissue: flags.reissueClientId !== undefined,
+ });
+
+ return {
+ registered,
+ accessToken,
+ tokenExpiresAt,
+ presetResolved,
+ serveWarning: urlWarning,
+ probeNote,
+ block,
+ url,
+ };
+}
+
+/** --reissue: rotate the client secret and reprint the block. Outstanding
+ * access tokens remain valid until they expire — rotation is not revocation. */
+async function runReissue(
+ sql: SqlQuery,
+ engine: BrainEngine,
+ flags: AgentRegisterArgs,
+ url: string,
+ urlWarning: string | null,
+): Promise<RegisterOutput> {
+ const clientId = flags.reissueClientId!;
+ const columns = await preflightOauthClientColumns(sql);
+ // Projection derived from the pre-flight column set: pre-migration brains
+ // lack source_id/federated_read/token_ttl/deleted_at — drop the absent ones
+ // (the ?? defaults below tolerate missing keys). Column names come from a
+ // fixed allowlist, never caller input.
+ const projection = [
+ 'client_id', 'client_name', 'grant_types', 'client_secret_hash',
+ ...['source_id', 'federated_read', 'token_ttl', 'deleted_at'].filter(c => columns.has(c)),
+ ];
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT ${projection.join(', ')} FROM oauth_clients WHERE client_id = $1`,
+ [clientId],
+ );
+ if (rows.length === 0) {
+ throw new RegisterError('reissue_invalid_target', `no OAuth client with id "${clientId}" — list clients with \`gbrain auth clients\`.`);
+ }
+ const row = rows[0] as Record<string, unknown>;
+ if (row.deleted_at != null) {
+ throw new RegisterError('reissue_invalid_target', `client "${clientId}" is deleted — register a new one.`);
+ }
+ if (row.client_secret_hash == null) {
+ throw new RegisterError('reissue_invalid_target', `client "${clientId}" is a public (PKCE) client — it has no secret to rotate.`);
+ }
+ const grants = Array.isArray(row.grant_types) ? (row.grant_types as string[]) : String(row.grant_types ?? '').split(',');
+ if (!grants.includes('client_credentials')) {
+ throw new RegisterError('reissue_invalid_target', `client "${clientId}" has no client_credentials grant — nothing to reissue.`);
+ }
+
+ const newSecret = await rotateClientSecret(engine, clientId, String(row.client_name));
+
+ const registered: RegisteredClient = {
+ clientId,
+ clientSecret: newSecret,
+ grantTypes: grants,
+ scopes: '(unchanged)',
+ authMethod: 'client_secret_post',
+ redirectUris: [],
+ sourceId: String(row.source_id ?? 'default'),
+ federatedRead: Array.isArray(row.federated_read) ? (row.federated_read as string[]) : [String(row.source_id ?? 'default')],
+ ...(typeof row.token_ttl === 'number' ? { tokenTtl: row.token_ttl } : {}),
+ created: { source: false },
+ };
+
+ // MCP server name: the stored client_name when it is a valid server name
+ // (it was validated at registration, but DCR/legacy rows may carry
+ // arbitrary text) — fall back to the client id otherwise.
+ const clientName = String(row.client_name ?? '');
+ const blockName = isValidName(clientName) ? clientName : clientId;
+ const out = await mintAndProbe(engine, flags, registered, blockName, url, urlWarning, {
+ preset: null,
+ scopes: registered.scopes,
+ write_source: registered.sourceId,
+ federated_read: registered.federatedRead,
+ surface: null,
+ token_ttl: registered.tokenTtl ?? null,
+ });
+ out.probeNote = `${out.probeNote ?? ''}${out.probeNote ? ' ' : ''}Secret ROTATED: the old secret no longer mints tokens; outstanding access tokens stay valid until expiry — revoke the client to kill them now.`;
+ return out;
+}
+
+/** Rotate a confidential client's secret under the same name-scoped advisory
+ * lock registration uses. Rotation is NOT revocation: outstanding access
+ * tokens stay valid until they expire. Exported for the unit suite. */
+export async function rotateClientSecret(engine: BrainEngine, clientId: string, clientName: string): Promise<string> {
+ let newSecret!: string;
+ await engine.transaction(async (tx) => {
+ const txSql = sqlQueryForEngine(tx);
+ await tx.executeRaw(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [registerClientNameLockKey(clientName)]);
+ newSecret = generateToken('gbrain_cs_');
+ const updated = await txSql`
+ UPDATE oauth_clients SET client_secret_hash = ${hashToken(newSecret)}
+ WHERE client_id = ${clientId}
+ RETURNING client_id
+ `;
+ if (updated.length === 0) throw new RegisterError('reissue_invalid_target', `client "${clientId}" vanished mid-rotation.`);
+ });
+ return newSecret;
+}
+
+// ── rendering ─────────────────────────────────────────────────────────────
+
+function buildHarnessBlock(
+ harness: RegisterHarness,
+ p: { name: string; url: string; token: string | null; clientId: string; clientSecret: string | null; showToken: boolean; expiresAt: string | null; isReissue: boolean },
+): string {
+ const shownToken = p.token ? (p.showToken ? p.token : REDACTED) : '<mint-a-token>';
+ const shownSecret = p.clientSecret ? (p.showToken ? p.clientSecret : REDACTED) : REDACTED;
+ // Lane-honest recovery: re-running `agent register <name>` fails on
+ // duplicate_name, so the register lane names the REAL recovery (--reissue);
+ // the reissue lane's re-run genuinely works, so it keeps the simple hint.
+ const hintText = p.isReissue
+ ? '(credentials redacted — re-run with --show-token for a paste-ready block)'
+ : `(credentials redacted — reissue a paste-ready block with: gbrain agent register --reissue ${p.clientId} --harness ${harness} --url ${p.url} --show-token)`;
+ const redactionHint = p.showToken ? [] : [hintText];
+ switch (harness) {
+ case 'claude-code': {
+ const cmd = cmdString('claude', buildClaudeMcpAddArgv({ name: p.name, url: p.url, headerToken: shownToken }));
+ return ['# Paste into Claude Code:', '', ` ${cmd}`, '', ...redactionHint].join('\n');
+ }
+ case 'codex': {
+ const cmd = cmdString('codex', buildCodexMcpAddArgv({ name: p.name, url: p.url, envVar: GBRAIN_REMOTE_TOKEN_ENV }));
+ const toml = renderCodexHttpServerBlock({ name: p.name, url: p.url, bearerToken: shownToken });
+ return [
+ '# Paste into Codex:',
+ '',
+ ` export ${GBRAIN_REMOTE_TOKEN_ENV}=${shellQuote(shownToken)}`,
+ ` ${cmd}`,
+ '',
+ `# Or add to ~/.codex/config.toml directly (then: chmod 600 ~/.codex/config.toml):`,
+ toml,
+ '',
+ ...redactionHint,
+ ].join('\n');
+ }
+ case 'opencode': {
+ const cmd = cmdString('opencode', buildOpencodeMcpAddArgv({ name: p.name, url: p.url, envVar: GBRAIN_REMOTE_TOKEN_ENV }));
+ return [
+ '# Paste into opencode:',
+ '',
+ ` export ${GBRAIN_REMOTE_TOKEN_ENV}=${shellQuote(shownToken)}`,
+ ` ${cmd}`,
+ '',
+ ...redactionHint,
+ ].join('\n');
+ }
+ case 'openclaw':
+ return openclawThinClientBlock({
+ issuerUrl: issuerFromMcpUrl(p.url),
+ mcpUrl: p.url,
+ clientId: p.clientId,
+ clientSecret: shownSecret,
+ }) + (p.showToken ? '' : `\n\n${hintText}`);
+ }
+}
+
+function printOutput(flags: AgentRegisterArgs, out: RegisterOutput): void {
+ const r = out.registered;
+ const expiry = out.tokenExpiresAt ?? null;
+ const floorLine = `token scoping requires serve ≥ ${SCOPES_MIN_SERVE_VERSION}; an older serve verifies this token as full access.`;
+
+ if (flags.json) {
+ // ONE JSON document on stdout; every note goes to stderr.
+ if (out.serveWarning) console.error(out.serveWarning);
+ if (out.probeNote) console.error(out.probeNote);
+ console.error(floorLine);
+ console.log(JSON.stringify({
+ ok: true,
+ schema_version: 1,
+ client_id: r.clientId,
+ client_secret: r.clientSecret ? (flags.showToken ? r.clientSecret : REDACTED) : null,
+ secret_redacted: !!r.clientSecret && !flags.showToken,
+ access_token: out.accessToken ? (flags.showToken ? out.accessToken : REDACTED) : null,
+ token_redacted: !!out.accessToken && !flags.showToken,
+ token_expires_at: expiry,
+ mcp_url: out.url,
+ harness: flags.harness,
+ preset_resolved: out.presetResolved,
+ created_workspace_source: r.created.source,
+ skipped: r.skipped ?? null,
+ // probe_note carries the serve health-probe result; serve_warning is
+ // the URL http-token warning (null when the URL is clean).
+ probe_note: out.probeNote,
+ serve_warning: out.serveWarning ?? null,
+ block: out.block,
+ }));
+ return;
+ }
+
+ // Lane-honest header: rotation is not registration (JSON shape unchanged —
+ // this is the human printer only).
+ const header = flags.reissueClientId !== undefined
+ ? `Agent client secret ROTATED: "${flags.name ?? r.clientId}"`
+ : `Agent client registered: "${flags.name ?? r.clientId}"`;
+ console.log(`${header}\n`);
+ console.log(` Client ID: ${r.clientId}`);
+ if (r.clientSecret) {
+ console.log(` Client Secret: ${flags.showToken ? r.clientSecret : REDACTED}`);
+ }
+ console.log(` Scopes: ${out.presetResolved.scopes}`);
+ console.log(` Write source: ${out.presetResolved.write_source}${r.created.source ? ' (created)' : ''}`);
+ console.log(` Federated reads: ${out.presetResolved.federated_read.join(', ')}`);
+ if (out.presetResolved.surface) {
+ console.log(` Surface tier: ${out.presetResolved.surface} (widen: gbrain auth rescope-client "${r.clientId}" --surface full)`);
+ }
+ if (out.presetResolved.token_ttl) {
+ console.log(` Token TTL: ${out.presetResolved.token_ttl}s`);
+ }
+ if (expiry) {
+ console.log(` Token expires: ${expiry} — reissue with: gbrain agent register --reissue ${r.clientId} --harness ${flags.harness} --url ${out.url}`);
+ }
+ console.log('');
+ console.log(out.block);
+ console.log('');
+ if (out.serveWarning) console.log(out.serveWarning);
+ if (out.probeNote) console.log(out.probeNote);
+ console.log(floorLine);
+ console.log('');
+ console.log(OAUTH_SECRET_NOTE);
+ console.log(`Revoke with: gbrain auth revoke-client "${r.clientId}"`);
+}
+
+// ── help ──────────────────────────────────────────────────────────────────
+
+export function printRegisterHelp(): void {
+ console.log(`gbrain agent register — mint a scoped OAuth client + token and print the harness wiring
+
+${REGISTER_USAGE}
+
+PRESETS
+ daily-driver read-broad, write to one source. Federated reads default to a
+ SNAPSHOT of all current non-archived sources EXCLUDING other
+ agents' *-workspace sources (agent scratch — share one via an
+ explicit --federated-read). New sources need a re-grant via
+ \`gbrain auth rescope-client\`. Surface: starter.
+ coding-agent write-isolated: writes land in <name>${WORKSPACE_SUFFIX} (auto-created,
+ DB-only). Requires --federated-read (the project sources it may
+ read). Surface: starter.
+
+NOTES
+ Runs on the BRAIN HOST (a thin client is refused). Every block embeds the
+ brain URL: pass --url or --port. The minted token defaults to a 30-day TTL
+ (the server default is 1 hour); the printed expiry comes from the exchange.
+ A reachable serve that reports a version older than ${SCOPES_MIN_SERVE_VERSION}
+ FAILS the registration (it would treat the scoped token as full access);
+ pass --allow-old-serve to accept that risk. An unreachable serve is only a
+ note. --reissue <client-id> rotates the client secret and reprints the
+ block; outstanding tokens stay valid until expiry.`);
+}
diff --git a/src/commands/agent.ts b/src/commands/agent.ts
index 141bd25a71..636e3d7a98 100644
--- a/src/commands/agent.ts
+++ b/src/commands/agent.ts
@@ -38,20 +38,40 @@ function isKnownFlag(s: string): boolean {
// ── command dispatcher ────────────────────────────────────
-export async function runAgent(engine: BrainEngine, args: string[]): Promise<void> {
+export async function runAgent(engine: BrainEngine | null, args: string[]): Promise<void> {
const sub = args[0];
if (!sub || sub === '--help' || sub === '-h') {
printHelp();
return;
}
+ // Subcommand-aware help that STOPS at the `--` terminator: `agent run --
+ // --help` submits the LITERAL prompt; only a pre-`--` --help/-h is a help
+ // request. Answered before any engine or queue work, so the
+ // SELF_HELP_WITHOUT_ENGINE lane (engine === null) prints real help on a
+ // brainless machine and can never submit a job (cathedral-6 eng review).
+ const rest = args.slice(1);
+ const dd = rest.indexOf('--');
+ const helpScan = dd === -1 ? rest : rest.slice(0, dd);
+ const wantsHelp = helpScan.includes('--help') || helpScan.includes('-h');
+
switch (sub) {
case 'run':
- await runAgentRun(engine, args.slice(1));
+ if (wantsHelp) { printHelp(); return; }
+ if (!engine) { console.error('gbrain agent run needs a configured brain. Run `gbrain init` first.'); process.exit(1); }
+ await runAgentRun(engine, rest);
return;
case 'logs':
- await runAgentLogsCmd(engine, args.slice(1));
+ if (wantsHelp) { printHelp(); return; }
+ if (!engine) { console.error('gbrain agent logs needs a configured brain. Run `gbrain init` first.'); process.exit(1); }
+ await runAgentLogsCmd(engine, rest);
+ return;
+ case 'register': {
+ const { printRegisterHelp, runAgentRegister } = await import('./agent-register.ts');
+ if (wantsHelp) { printRegisterHelp(); return; }
+ await runAgentRegister(engine, rest);
return;
+ }
default:
console.error(`gbrain agent: unknown subcommand "${sub}"`);
printHelp();
@@ -65,6 +85,7 @@ function printHelp(): void {
USAGE
gbrain agent run <prompt> [flags]
gbrain agent logs <job_id> [--follow] [--since <spec>]
+ gbrain agent register <name> --harness <h> [flags] (see: gbrain agent register --help)
SUBMITTING
gbrain agent run <prompt>
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index 625b39fe9e..bb74578c4f 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -24,6 +24,7 @@ import { loadConfig, toEngineConfig } from '../core/config.ts';
import { createEngine } from '../core/engine-factory.ts';
import type { BrainEngine } from '../core/engine.ts';
import { assertAllowedScopes } from '../core/scope.ts';
+import { isUndefinedColumnError, isUndefinedTableError } from '../core/utils.ts';
import { TOKEN_ID_RE } from '../core/token-mint.ts';
import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';
import { sqlQueryForEngine, executeRawJsonb, type SqlQuery } from '../core/sql-query.ts';
@@ -419,7 +420,7 @@ async function revokeClient(clientId: string) {
* and `--token-endpoint-auth-method` is recognized. Repeatable flags
* accumulate into arrays. Unknown flags throw a usage error.
*/
-interface RegisterClientArgs {
+export interface RegisterClientArgs {
grantTypes: string[];
scopes: string;
sourceId: string;
@@ -432,6 +433,29 @@ interface RegisterClientArgs {
boundSlugPrefixes: string[] | undefined;
boundMaxConcurrent: number | undefined;
budgetUsdPerDay: string | undefined;
+ tokenTtlSeconds: number | undefined;
+}
+
+/** --token-ttl bounds: 1 minute .. 90 days. The SERVER default for CLI-minted
+ * access tokens is 3600s (oauth-provider.ts tokenTtl) — NOT 30 days; callers
+ * that promise long-lived tokens must write oauth_clients.token_ttl. */
+export const TOKEN_TTL_MIN_SECONDS = 60;
+export const TOKEN_TTL_MAX_SECONDS = 7_776_000;
+
+/**
+ * Shared --token-ttl value parser (auth register-client + agent register).
+ * `hint` is the parser-specific tail naming what omitting the flag means
+ * (the two commands have different defaults). Throws the canonical bounds
+ * message on anything outside [TOKEN_TTL_MIN_SECONDS, TOKEN_TTL_MAX_SECONDS].
+ */
+export function parseTokenTtl(raw: string, hint: string): number {
+ const v = Number(raw);
+ if (!Number.isInteger(v) || v < TOKEN_TTL_MIN_SECONDS || v > TOKEN_TTL_MAX_SECONDS) {
+ throw new Error(
+ `--token-ttl must be an integer number of seconds between ${TOKEN_TTL_MIN_SECONDS} and ${TOKEN_TTL_MAX_SECONDS} (90 days); got ${JSON.stringify(raw)}. ${hint}`,
+ );
+ }
+ return v;
}
export function parseRegisterClientArgs(args: string[]): RegisterClientArgs {
@@ -448,6 +472,7 @@ export function parseRegisterClientArgs(args: string[]): RegisterClientArgs {
boundSlugPrefixes: undefined,
boundMaxConcurrent: undefined,
budgetUsdPerDay: undefined,
+ tokenTtlSeconds: undefined,
};
let i = 0;
let grantTypesSet = false;
@@ -538,6 +563,10 @@ export function parseRegisterClientArgs(args: string[]): RegisterClientArgs {
out.budgetUsdPerDay = v;
i += 2; break;
}
+ case '--token-ttl': {
+ out.tokenTtlSeconds = parseTokenTtl(requireValue(), 'Omit the flag to keep the server default.');
+ i += 2; break;
+ }
default:
throw new Error(`Unknown flag: ${flag}`);
}
@@ -552,19 +581,75 @@ export function parseRegisterClientArgs(args: string[]): RegisterClientArgs {
return out;
}
-async function registerClient(name: string, args: string[]) {
- if (!name) {
- console.error('Usage: auth register-client <name> [--grant-types G] [--scopes S] [--source SOURCE] [--federated-read SRC1,SRC2,...] [--redirect-uri URI ...] [--token-endpoint-auth-method client_secret_post|client_secret_basic|none] [--bound-tools T1,T2] [--bound-source SOURCE] [--bound-brain BRAIN] [--bound-slug-prefixes P1,P2] [--bound-max-concurrent N] [--budget-usd-per-day USD]');
- process.exit(1);
- }
- let parsed: RegisterClientArgs;
- try {
- parsed = parseRegisterClientArgs(args);
- } catch (e: any) {
- console.error(`Error: ${e.message}`);
- console.error('Usage: auth register-client <name> [--grant-types G] [--scopes S] [--source SOURCE] [--federated-read SRC1,SRC2,...] [--redirect-uri URI ...] [--token-endpoint-auth-method client_secret_post|client_secret_basic|none] [--bound-tools T1,T2] [--bound-source SOURCE] [--bound-brain BRAIN] [--bound-slug-prefixes P1,P2] [--bound-max-concurrent N] [--budget-usd-per-day USD]');
- process.exit(1);
- }
+/**
+ * Column pre-flight (cathedral-6): decide statement shapes BEFORE any
+ * transaction. Postgres/PGLite abort the whole tx on any statement error
+ * (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue"
+ * is impossible inside a tx — optional-column degrades must be decided here,
+ * outside, once.
+ */
+export async function preflightOauthClientColumns(sql: SqlQuery): Promise<Set<string>> {
+ const rows = await sql`
+ SELECT column_name FROM information_schema.columns
+ WHERE table_name = 'oauth_clients'
+ AND table_schema = current_schema()
+ AND column_name IN ('token_ttl', 'surface', 'federated_read', 'source_id', 'deleted_at')
+ `;
+ return new Set(rows.map(r => String(r.column_name)));
+}
+
+export interface RegisterScopedClientOpts {
+ /** Per-client access-token TTL to persist (oauth_clients.token_ttl). */
+ tokenTtlSeconds?: number;
+ /** Per-client tool-surface tier, written via provider.rescopeClient — the
+ * ONLY surface-column writer (sets surface_set_by='operator', the lock
+ * request_tools cannot override). Never a raw column UPDATE. */
+ surface?: 'verbs' | 'starter' | 'full';
+ /** Result of preflightOauthClientColumns — decides which optional-column
+ * writes are attempted. Absent → attempt everything (caller owns errors). */
+ columns?: Set<string>;
+}
+
+/**
+ * The data a scoped-client registration produces — everything a printer
+ * (auth register-client's byte-pinned block, agent register's summary,
+ * or the admin HTTP route) needs, with ZERO console output produced here.
+ */
+export interface RegisteredClient {
+ clientId: string;
+ clientSecret?: string;
+ grantTypes: string[];
+ scopes: string;
+ authMethod: string;
+ redirectUris: string[];
+ sourceId: string;
+ federatedRead: string[];
+ surface?: 'verbs' | 'starter' | 'full';
+ tokenTtl?: number;
+ created: { source: boolean };
+ /** Previous surface row value when opts.surface was written (for the
+ * post-commit audit row — audit is fail-open and NEVER runs in the tx). */
+ surfaceOld?: string | null;
+ /** Optional-column writes skipped by the pre-flight (pre-migration brain). */
+ skipped?: { tokenTtl?: boolean; surface?: boolean };
+}
+
+/**
+ * Exit-free, print-free registration core (cathedral-6 seam). Named
+ * registerScopedClient — not run*Core — because unlike the other peels it
+ * returns data instead of printing. Takes an INJECTED SqlQuery handle:
+ * callers on the engine-bound CLI lane pass the dispatcher's engine's sql
+ * (a second withConfiguredSql engine self-deadlocks PGLite's single-writer
+ * lock); `registerClient` below keeps withConfiguredSql for the
+ * early-routed auth lane. Throws on failure — the thin callers own
+ * exit/print mapping.
+ */
+export async function registerScopedClient(
+ sql: SqlQuery,
+ name: string,
+ parsed: RegisterClientArgs,
+ opts: RegisterScopedClientOpts = {},
+): Promise<RegisteredClient> {
const { grantTypes, scopes, sourceId, federatedRead, redirectUris, tokenEndpointAuthMethod } = parsed;
const agentBindings = parsed.boundTools || parsed.boundSourceId || parsed.boundBrainId ||
parsed.boundSlugPrefixes || parsed.boundMaxConcurrent !== undefined || parsed.budgetUsdPerDay !== undefined
@@ -577,46 +662,135 @@ async function registerClient(name: string, args: string[]) {
budgetUsdPerDay: parsed.budgetUsdPerDay,
}
: undefined;
+ const { GBrainOAuthProvider } = await import('../core/oauth-provider.ts');
+ const provider = new GBrainOAuthProvider({ sql });
+ const { clientId, clientSecret } = await provider.registerClientManual(
+ name, grantTypes, scopes, redirectUris, sourceId, federatedRead, tokenEndpointAuthMethod, agentBindings,
+ );
+
+ const ttl = parsed.tokenTtlSeconds ?? opts.tokenTtlSeconds;
+ let tokenTtl: number | undefined;
+ let ttlSkipped = false;
+ if (ttl !== undefined) {
+ if (opts.columns && !opts.columns.has('token_ttl')) {
+ // Pre-migration brain: the degrade was decided by the pre-flight,
+ // OUTSIDE any transaction — nothing here throws-and-continues.
+ ttlSkipped = true;
+ } else {
+ const updated = await sql`
+ UPDATE oauth_clients SET token_ttl = ${ttl}
+ WHERE client_id = ${clientId}
+ RETURNING client_id
+ `;
+ if (updated.length === 0) {
+ throw new Error(`token_ttl update matched no row for client ${clientId}`);
+ }
+ tokenTtl = ttl;
+ }
+ }
+
+ let surfaceApplied: 'verbs' | 'starter' | 'full' | undefined;
+ let surfaceOld: string | null | undefined;
+ let surfaceSkipped = false;
+ if (opts.surface !== undefined) {
+ if (opts.columns && !opts.columns.has('surface')) {
+ surfaceSkipped = true;
+ } else {
+ const rescoped = await provider.rescopeClient(clientId, { surface: opts.surface });
+ surfaceApplied = opts.surface;
+ surfaceOld = rescoped.surfaceOld ?? null;
+ }
+ }
+
+ return {
+ clientId,
+ ...(clientSecret ? { clientSecret } : {}),
+ grantTypes,
+ scopes,
+ authMethod: tokenEndpointAuthMethod || 'client_secret_post',
+ redirectUris,
+ sourceId,
+ federatedRead: federatedRead && federatedRead.length > 0 ? federatedRead : [sourceId],
+ ...(tokenTtl !== undefined ? { tokenTtl } : {}),
+ ...(surfaceApplied !== undefined ? { surface: surfaceApplied } : {}),
+ ...(surfaceOld !== undefined ? { surfaceOld } : {}),
+ created: { source: false },
+ ...(ttlSkipped || surfaceSkipped
+ ? { skipped: { ...(ttlSkipped ? { tokenTtl: true } : {}), ...(surfaceSkipped ? { surface: true } : {}) } }
+ : {}),
+ };
+}
+
+/**
+ * The exact lines `auth register-client` prints. BYTE-IDENTICAL contract:
+ * connect.ts:defaultRegisterOAuthClient regex-scrapes `Client ID:` /
+ * `Client Secret:` from this output in PRODUCTION, and 7+ e2e assertions pin
+ * it — pinned by test/auth-register-client-output-pin.test.ts. Each array
+ * element is one console.log call (embedded \n are intentional).
+ */
+export function formatRegisterClientOutput(name: string, r: RegisteredClient, parsed: RegisterClientArgs): string[] {
+ const hasBindings = parsed.boundTools || parsed.boundSourceId || parsed.boundBrainId ||
+ parsed.boundSlugPrefixes || parsed.boundMaxConcurrent !== undefined || parsed.budgetUsdPerDay !== undefined;
+ const lines: string[] = [];
+ lines.push(`OAuth client registered: "${name}"\n`);
+ lines.push(` Client ID: ${r.clientId}`);
+ if (r.clientSecret) {
+ lines.push(` Client Secret: ${r.clientSecret}\n`);
+ } else {
+ lines.push(` Client Secret: <public client — none issued>\n`);
+ }
+ lines.push(` Grant types: ${r.grantTypes.join(', ')}`);
+ lines.push(` Scopes: ${r.scopes}`);
+ lines.push(` Token auth method: ${r.authMethod}`);
+ if (r.redirectUris.length > 0) {
+ lines.push(` Redirect URIs: ${r.redirectUris.join(', ')}`);
+ }
+ lines.push(` Write source: ${r.sourceId}`);
+ lines.push(` Federated reads: ${r.federatedRead.join(', ')}`);
+ if (hasBindings) {
+ lines.push(` Bound tools: ${(parsed.boundTools ?? []).join(', ') || '<none>'}`);
+ lines.push(` Bound source: ${parsed.boundSourceId ?? '<none>'}`);
+ lines.push(` Bound brain: ${parsed.boundBrainId ?? '<none>'}`);
+ lines.push(` Bound slug prefixes:${parsed.boundSlugPrefixes ? ' ' + parsed.boundSlugPrefixes.join(', ') : ' <none>'}`);
+ lines.push(` Max concurrency: ${parsed.boundMaxConcurrent ?? 1}`);
+ lines.push(` Daily budget USD: ${parsed.budgetUsdPerDay ?? '<none>'}`);
+ }
+ lines.push('');
+ if (r.clientSecret) {
+ lines.push('Save the client secret — it will not be shown again.');
+ } else {
+ lines.push('Public client (PKCE-only) — no secret needed.');
+ }
+ lines.push(`Revoke with: gbrain auth revoke-client "${r.clientId}"`);
+ return lines;
+}
+
+async function registerClient(name: string, args: string[]) {
+ if (!name) {
+ console.error('Usage: auth register-client <name> [--grant-types G] [--scopes S] [--source SOURCE] [--federated-read SRC1,SRC2,...] [--redirect-uri URI ...] [--token-endpoint-auth-method client_secret_post|client_secret_basic|none] [--bound-tools T1,T2] [--bound-source SOURCE] [--bound-brain BRAIN] [--bound-slug-prefixes P1,P2] [--bound-max-concurrent N] [--budget-usd-per-day USD] [--token-ttl SECONDS]');
+ process.exit(1);
+ }
+ let parsed: RegisterClientArgs;
+ try {
+ parsed = parseRegisterClientArgs(args);
+ } catch (e: any) {
+ console.error(`Error: ${e.message}`);
+ console.error('Usage: auth register-client <name> [--grant-types G] [--scopes S] [--source SOURCE] [--federated-read SRC1,SRC2,...] [--redirect-uri URI ...] [--token-endpoint-auth-method client_secret_post|client_secret_basic|none] [--bound-tools T1,T2] [--bound-source SOURCE] [--bound-brain BRAIN] [--bound-slug-prefixes P1,P2] [--bound-max-concurrent N] [--budget-usd-per-day USD] [--token-ttl SECONDS]');
+ process.exit(1);
+ }
try {
await withConfiguredSql(async (sql) => {
- const { GBrainOAuthProvider } = await import('../core/oauth-provider.ts');
- const provider = new GBrainOAuthProvider({ sql });
- const { clientId, clientSecret } = await provider.registerClientManual(
- name, grantTypes, scopes, redirectUris, sourceId, federatedRead, tokenEndpointAuthMethod, agentBindings,
- );
- const effectiveFederated = federatedRead && federatedRead.length > 0 ? federatedRead : [sourceId];
- const effectiveAuthMethod = tokenEndpointAuthMethod || 'client_secret_post';
- console.log(`OAuth client registered: "${name}"\n`);
- console.log(` Client ID: ${clientId}`);
- if (clientSecret) {
- console.log(` Client Secret: ${clientSecret}\n`);
- } else {
- console.log(` Client Secret: <public client — none issued>\n`);
+ const columns = parsed.tokenTtlSeconds !== undefined
+ ? await preflightOauthClientColumns(sql)
+ : undefined;
+ const registered = await registerScopedClient(sql, name, parsed, { columns });
+ if (registered.skipped?.tokenTtl) {
+ console.error('Note: this brain predates the token_ttl column; run `gbrain apply-migrations --yes`, then rescope. The server default TTL applies.');
}
- console.log(` Grant types: ${grantTypes.join(', ')}`);
- console.log(` Scopes: ${scopes}`);
- console.log(` Token auth method: ${effectiveAuthMethod}`);
- if (redirectUris.length > 0) {
- console.log(` Redirect URIs: ${redirectUris.join(', ')}`);
+ for (const line of formatRegisterClientOutput(name, registered, parsed)) {
+ console.log(line);
}
- console.log(` Write source: ${sourceId}`);
- console.log(` Federated reads: ${effectiveFederated.join(', ')}`);
- if (agentBindings) {
- console.log(` Bound tools: ${(parsed.boundTools ?? []).join(', ') || '<none>'}`);
- console.log(` Bound source: ${parsed.boundSourceId ?? '<none>'}`);
- console.log(` Bound brain: ${parsed.boundBrainId ?? '<none>'}`);
- console.log(` Bound slug prefixes:${parsed.boundSlugPrefixes ? ' ' + parsed.boundSlugPrefixes.join(', ') : ' <none>'}`);
- console.log(` Max concurrency: ${parsed.boundMaxConcurrent ?? 1}`);
- console.log(` Daily budget USD: ${parsed.budgetUsdPerDay ?? '<none>'}`);
- }
- console.log('');
- if (clientSecret) {
- console.log('Save the client secret — it will not be shown again.');
- } else {
- console.log('Public client (PKCE-only) — no secret needed.');
- }
- console.log(`Revoke with: gbrain auth revoke-client "${clientId}"`);
});
} catch (e: any) {
console.error('Error:', e.message);
@@ -757,12 +931,56 @@ export function parseAuthClientsArgs(args: string[]): { usage: boolean; days: nu
return out;
}
-interface ClientRow {
+export interface ClientRow {
client_id: string;
client_name: string | null;
scope: string | null;
surface: string | null;
surface_set_by: string | null;
+ source_id: string | null;
+ federated_read: string[] | null;
+}
+
+/**
+ * Projection-widened client listing with a degrade ladder for pre-migration
+ * brains: full shape (scope + surface + source-scoping columns) → source
+ * columns without surface → the bare original triple. Drops the NEWEST
+ * columns first; missing columns render as null. Only schema-shape errors
+ * (undefined column/table) degrade — anything else (dropped connection,
+ * permission) rethrows instead of silently narrowing the listing. One round
+ * trip on a current brain (the widen adds columns, not queries). Exported
+ * for the unit suite.
+ */
+export async function listClientRows(engine: BrainEngine): Promise<ClientRow[]> {
+ // The columns each degrade tier drops. isUndefinedColumnError matches any
+ // 42703 by code; the column list covers message-only (code-less) variants.
+ const isSchemaShapeError = (e: unknown): boolean =>
+ isUndefinedTableError(e) ||
+ ['surface', 'surface_set_by', 'source_id', 'federated_read']
+ .some(col => isUndefinedColumnError(e, col));
+ try {
+ return await engine.executeRaw<ClientRow>(
+ `SELECT client_id, client_name, scope, surface, surface_set_by, source_id, federated_read
+ FROM oauth_clients ORDER BY client_name, client_id`,
+ );
+ } catch (e) {
+ // Brain predates the surface columns — fall through. Rethrow non-shape errors.
+ if (!isSchemaShapeError(e)) throw e;
+ }
+ try {
+ const mid = await engine.executeRaw<Omit<ClientRow, 'surface' | 'surface_set_by'>>(
+ `SELECT client_id, client_name, scope, source_id, federated_read
+ FROM oauth_clients ORDER BY client_name, client_id`,
+ );
+ return mid.map(r => ({ ...r, surface: null, surface_set_by: null }));
+ } catch (e) {
+ // Brain predates the source-scoping columns — fall through likewise.
+ if (!isSchemaShapeError(e)) throw e;
+ }
+ const bare = await engine.executeRaw<Pick<ClientRow, 'client_id' | 'client_name' | 'scope'>>(
+ `SELECT client_id, client_name, scope FROM oauth_clients ORDER BY client_name, client_id`,
+ );
+ return bare.map(r => ({ ...r, surface: null, surface_set_by: null, source_id: null, federated_read: null }));
}
async function clientsCmd(args: string[]) {
@@ -777,20 +995,9 @@ async function clientsCmd(args: string[]) {
}
try {
await withConfiguredSql(async (_sql, engine) => {
- // Surface columns land in migration v127; a pre-migration brain still
- // gets the listing (surface renders as unknown) instead of an error.
- let clients: ClientRow[];
- try {
- clients = await engine.executeRaw<ClientRow>(
- `SELECT client_id, client_name, scope, surface, surface_set_by
- FROM oauth_clients ORDER BY client_name, client_id`,
- );
- } catch {
- const bare = await engine.executeRaw<Omit<ClientRow, 'surface' | 'surface_set_by'>>(
- `SELECT client_id, client_name, scope FROM oauth_clients ORDER BY client_name, client_id`,
- );
- clients = bare.map(r => ({ ...r, surface: null, surface_set_by: null }));
- }
+ // Degrade ladder lives in listClientRows: a pre-migration brain still
+ // gets the listing (missing columns render as null) instead of an error.
+ const clients = await listClientRows(engine);
const { readClientOpUsage } = await import('../core/mcp-usage.ts');
const usage = parsed.usage ? await readClientOpUsage(engine, { days: parsed.days }) : [];
@@ -808,6 +1015,8 @@ async function clientsCmd(args: string[]) {
scopes: c.scope,
surface: c.surface,
surface_set_by: c.surface_set_by,
+ source_id: c.source_id,
+ federated_read: c.federated_read,
usage: usageByToken.get(c.client_id) ?? null,
})),
// Legacy bearer tokens seen in the window (no oauth_clients row).
@@ -829,6 +1038,7 @@ async function clientsCmd(args: string[]) {
? `${c.surface}${c.surface_set_by ? ` (set by ${c.surface_set_by})` : ''}`
: '<server/config resolution>';
console.log(` scopes: ${c.scope ?? '<none>'} surface: ${surfaceStr}`);
+ console.log(` write source: ${c.source_id ?? '<none>'} federated reads: ${(c.federated_read ?? []).join(', ') || '<none>'}`);
if (parsed.usage) {
if (u) {
const auto = u.likely_automation ? ' [automation-shaped: >90% context_pack/delta]' : '';
@@ -983,7 +1193,8 @@ Usage:
request_tools cannot override; 'clear' removes the pin
so server/config resolution applies again). Always
bounded by the server's --surface ceiling.
- gbrain auth clients [--usage] [--days N] [--json] List OAuth clients with scopes + tool surface. --usage
+ gbrain auth clients [--usage] [--days N] [--json] List OAuth clients with scopes, write source, federated
+ reads + tool surface. --usage
joins per-client op-call counts, top ops, and last-seen
from mcp_request_log (default 30d window; HTTP clients
only — stdio use is not logged). Automation-shaped
diff --git a/src/commands/connect.ts b/src/commands/connect.ts
index 762001c7ab..67fcc82459 100644
--- a/src/commands/connect.ts
+++ b/src/commands/connect.ts
@@ -51,6 +51,7 @@ import {
import { promptLine } from '../core/cli-util.ts';
import {
NAME_RE,
+ OAUTH_SECRET_NOTE,
REDACTED,
buildClaudeMcpAddArgv,
buildCodexMcpAddArgv,
@@ -69,6 +70,7 @@ import {
// commands). Re-exported so this module's public surface — and every test
// that imports from it — is unchanged.
export {
+ OAUTH_SECRET_NOTE,
REDACTED,
buildClaudeMcpAddArgv,
buildCodexMcpAddArgv,
@@ -133,9 +135,8 @@ const SECRET_NOTE =
'Note: that bearer token is a long-lived, full-access secret — keep it private and ' +
'prefer a scoped/short-lived token if your host supports one.';
-const OAUTH_SECRET_NOTE =
- 'Note: the client secret is sensitive — store it like a password. It mints ' +
- 'short-lived, scoped access tokens; revoke with `gbrain auth revoke-client`.';
+// OAUTH_SECRET_NOTE moved to src/core/mcp-registration.ts (imported +
+// re-exported above; text unchanged).
const PERPLEXITY_REMOTE_NOTE = [
'Perplexity connects remotely, so the brain must be reachable over HTTPS. On the',
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 7c6f894599..2221f0a18a 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -89,6 +89,7 @@ export {
checkSourceRoutingHealth,
checkFederationHealth,
checkOauthConfidentialHealth,
+ checkOauthClientScopeHealth,
checkAutopilotLockScope,
checkStaleLocks,
checkCyclePhaseScope,
@@ -166,6 +167,7 @@ import {
import {
checkSourceRoutingHealth,
checkOauthConfidentialHealth,
+ checkOauthClientScopeHealth,
checkAutopilotLockScope,
checkStaleLocks,
checkCyclePhaseScope,
@@ -3730,6 +3732,9 @@ export async function buildChecks(
// 5L — oauth_confidential_client_health (success-path probe per codex CF8)
progress.heartbeat('oauth_confidential_client_health');
checks.push(await checkOauthConfidentialHealth(engine));
+ // oauth_client_scope_health — dangling federated grants + orphaned empty workspace sources
+ progress.heartbeat('oauth_client_scope_health');
+ checks.push(await checkOauthClientScopeHealth(engine));
// 5M — autopilot_lock_scope (PID-safe hint per codex CF11)
progress.heartbeat('autopilot_lock_scope');
checks.push(checkAutopilotLockScope());
diff --git a/src/commands/doctor/checks/routing-federation.ts b/src/commands/doctor/checks/routing-federation.ts
index 61afeda43d..91bbc3bf84 100644
--- a/src/commands/doctor/checks/routing-federation.ts
+++ b/src/commands/doctor/checks/routing-federation.ts
@@ -7,6 +7,7 @@
import { existsSync, readFileSync } from 'fs';
import type { BrainEngine } from '../../../core/engine.ts';
import { gbrainPath } from '../../../core/config.ts';
+import { isUndefinedTableError, isUndefinedColumnError } from '../../../core/utils.ts';
import type { Check } from '../../doctor.ts';
/**
@@ -192,6 +193,127 @@ export async function checkOauthConfidentialHealth(engine: BrainEngine): Promise
}
}
+/**
+ * oauth_client_scope_health — scoped-client grant hygiene (cathedral-6).
+ *
+ * Two warn conditions, each a single query (no per-client N+1):
+ *
+ * (a) DANGLING FEDERATED GRANTS — a federated read grant id with no
+ * sources row. oauth_clients.federated_read is a TEXT[] with no FK
+ * (only source_id carries ON DELETE RESTRICT), so removing a source
+ * leaves grants pointing at nothing and the client's reads silently
+ * return less than the operator believes was granted.
+ *
+ * (b) ORPHANED EMPTY WORKSPACE SOURCES — an auto-created
+ * '<name>-workspace' source (DB-only: no local_path, zero pages, ZERO
+ * FACTS, not archived) that no live client references by write source
+ * or read grant. This is the post-failure / post-revoke residue
+ * heuristic for `gbrain agent register` derived workspaces. A
+ * non-default source WITH pages is normal on every local brain and is
+ * never flagged; a zero-page source WITH facts is a revoked agent's
+ * memory (the primary agent write lane) and is never flagged either —
+ * the `sources remove` hint would cascade the facts away.
+ *
+ * Pre-OAuth / pre-migration schemas (missing table or missing column)
+ * short-circuit to ok — same posture as oauth_confidential_client_health.
+ */
+export async function checkOauthClientScopeHealth(engine: BrainEngine): Promise<Check> {
+ try {
+ // Single source of truth for the derived-workspace suffix — lazy import
+ // (same pattern as the other checks) so agent-register.ts stays out of
+ // doctor's static import graph.
+ const { WORKSPACE_SUFFIX } = await import('../../agent-register.ts');
+ const dangling = await engine.executeRaw<{ client_id: string; client_name: string | null; grant_id: string }>(
+ `SELECT c.client_id, c.client_name, g.grant_id
+ FROM oauth_clients c
+ CROSS JOIN LATERAL unnest(c.federated_read) AS g(grant_id)
+ LEFT JOIN sources s ON s.id = g.grant_id
+ WHERE s.id IS NULL AND c.deleted_at IS NULL
+ ORDER BY c.client_id, g.grant_id`,
+ );
+ // A revoked agent's workspace can hold FACTS with zero pages (facts are
+ // the primary agent write lane) — such a source is NOT empty and the
+ // `gbrain sources remove` recommendation would cascade the facts away.
+ const orphanSql = (withFactsExclusion: boolean) =>
+ `SELECT s.id
+ FROM sources s
+ WHERE s.id LIKE '%' || $1
+ AND s.local_path IS NULL
+ AND COALESCE(s.archived, false) = false
+ AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id = s.id)
+ ${withFactsExclusion ? `AND NOT EXISTS (SELECT 1 FROM facts f WHERE f.source_id = s.id)` : ''}
+ AND NOT EXISTS (
+ SELECT 1 FROM oauth_clients c
+ WHERE c.deleted_at IS NULL
+ AND (c.source_id = s.id OR s.id = ANY(c.federated_read))
+ )
+ ORDER BY s.id`;
+ let orphaned: Array<{ id: string }>;
+ try {
+ orphaned = await engine.executeRaw<{ id: string }>(orphanSql(true), [WORKSPACE_SUFFIX]);
+ } catch (e) {
+ // Pre-v0.31 brain without the facts table: a source can't hold facts it
+ // has no table for — retry without the exclusion. Scoped here (code-first
+ // classification + the message must name `facts`) so the dangling-grant
+ // arm's findings above aren't lost to the outer catch's schema-degrade.
+ const msg = e instanceof Error ? e.message : String(e);
+ if (!(isUndefinedTableError(e) && /facts/i.test(msg))) throw e;
+ orphaned = await engine.executeRaw<{ id: string }>(orphanSql(false), [WORKSPACE_SUFFIX]);
+ }
+ const problems: string[] = [];
+ if (dangling.length > 0) {
+ const byClient = new Map<string, { name: string | null; grants: string[] }>();
+ for (const d of dangling) {
+ const entry = byClient.get(d.client_id) ?? { name: d.client_name, grants: [] };
+ entry.grants.push(d.grant_id);
+ byClient.set(d.client_id, entry);
+ }
+ const shown = [...byClient.entries()].slice(0, 5)
+ .map(([id, e]) => `"${e.name ?? id}" (${id}) → ${e.grants.join(', ')}`);
+ problems.push(
+ `${dangling.length} federated read grant(s) point at missing sources: ${shown.join('; ')}` +
+ (byClient.size > 5 ? ` (+${byClient.size - 5} more clients)` : '') +
+ `. Fix each with \`gbrain auth rescope-client <client_id>\` (set a federated read list naming only existing sources), or recreate the source.`,
+ );
+ }
+ if (orphaned.length > 0) {
+ const shown = orphaned.slice(0, 5).map(o => o.id);
+ problems.push(
+ `${orphaned.length} empty auto-created workspace source(s) with no live client: ${shown.join(', ')}` +
+ (orphaned.length > 5 ? ` (+${orphaned.length - 5} more)` : '') +
+ `. May be residue from a revoked or failed \`gbrain agent register\`; verify before removing with \`gbrain sources remove <id>\`.`,
+ );
+ }
+ if (problems.length > 0) {
+ return {
+ name: 'oauth_client_scope_health',
+ status: 'warn',
+ message: problems.join('\n'),
+ };
+ }
+ return {
+ name: 'oauth_client_scope_health',
+ status: 'ok',
+ message: 'Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources)',
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ // Pre-OAuth schema (table missing) or pre-migration schema (column
+ // missing) → ok, matching the confidential-client check's posture.
+ // CODE-FIRST classification (42P01/42703 via core/utils): a bare message
+ // regex would classify e.g. `function unnest(jsonb) does not exist` — a
+ // type-drift failure this check exists to catch — as "schema not present"
+ // and lie green. Column candidates are the optional oauth-scoping columns
+ // this check's queries touch.
+ const missingColumn = ['federated_read', 'source_id', 'deleted_at', 'archived', 'local_path']
+ .some((c) => isUndefinedColumnError(e, c));
+ if (isUndefinedTableError(e) || missingColumn) {
+ return { name: 'oauth_client_scope_health', status: 'ok', message: 'OAuth scoping schema not present (skipping)' };
+ }
+ return { name: 'oauth_client_scope_health', status: 'warn', message: `Check failed: ${msg}` };
+ }
+}
+
/**
* v0.37.7.0 — Tier 5M autopilot_lock_scope (PID-safe hint per codex CF11).
*
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index a43cfdd85a..11273cee5b 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -57,6 +57,15 @@ import { VERSION } from '../version.ts';
import * as db from '../core/db.ts';
import { sqlQueryForEngine, executeRawJsonb } from '../core/sql-query.ts';
import { MinionQueue } from '../core/minions/queue.ts';
+import {
+ registerScopedClient,
+ preflightOauthClientColumns,
+ TOKEN_TTL_MIN_SECONDS,
+ TOKEN_TTL_MAX_SECONDS,
+ type RegisteredClient,
+} from './auth.ts';
+import { registerClientNameLockKey } from './agent-register.ts';
+import { isUndefinedColumnError } from '../core/utils.ts';
import { isRetryableError } from '../core/retry-matcher.ts';
import {
computeContentHash,
@@ -1733,6 +1742,10 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
// Register client from admin dashboard
app.post('/admin/api/register-client', requireAdmin, express.json(), async (req: Request, res: Response) => {
+ // Set only once the client row has COMMITTED — the catch below folds it
+ // into the 500 payload so a post-commit failure never reads as
+ // "nothing was created".
+ let createdClientId: string | undefined;
try {
// v0.39.3.0 WARN-9 + CV12: accept BOTH `scopes` (admin SPA convention)
// AND `scope` (OAuth wire-format convention, singular). The pre-fix
@@ -1795,16 +1808,129 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
});
return;
}
- const result = await oauthProvider.registerClientManual(
- name, grants, scopeString, uris, sourceId, federatedReadIds, validatedAuthMethod,
- );
- // Set per-client TTL if specified
- if (tokenTtl && Number(tokenTtl) > 0) {
- await sql`UPDATE oauth_clients SET token_ttl = ${Number(tokenTtl)} WHERE client_id = ${result.clientId}`;
+ // cathedral-6: a WELL-FORMED but nonexistent source used to surface as
+ // a 500 (the source_id FK fires inside the INSERT). Check existence +
+ // archived up front for a structured 400 — same contract as the
+ // malformed case, mirroring the CLI lane. ONE batched query on the
+ // engine lane (SqlQuery forbids arrays; engine is in scope).
+ {
+ const idsToCheck = [...new Set([sourceId, ...(federatedReadIds ?? [])])];
+ const found = await engine.executeRaw<{ id: string; archived: boolean | null }>(
+ `SELECT id, archived FROM sources WHERE id = ANY($1::text[])`,
+ [idsToCheck],
+ );
+ const byId = new Map(found.map(r => [r.id, r]));
+ for (const id of idsToCheck) {
+ const row = byId.get(id);
+ if (!row) {
+ res.status(400).json({
+ error: 'unknown_source',
+ message: `source "${id}" does not exist — create it first (gbrain sources add ${id})`,
+ });
+ return;
+ }
+ if (row.archived) {
+ res.status(400).json({
+ error: 'archived_source',
+ message: `source "${id}" is archived — unarchive it or drop it from the grant`,
+ });
+ return;
+ }
+ }
}
- res.json({ ...result, tokenTtl: tokenTtl ? Number(tokenTtl) : null });
+ // cathedral-6: validate tokenTtl BEFORE the transaction. The old
+ // `Number(tokenTtl) > 0` passed Infinity/floats through to fail the
+ // integer UPDATE inside the tx (rollback → opaque 500). Falsy values
+ // (omitted / null / 0 / '') keep the historical "no TTL requested"
+ // meaning; anything else must be an integer inside the shared bounds.
+ let ttlNum: number | undefined;
+ if (tokenTtl) {
+ const v = Number(tokenTtl);
+ if (!Number.isInteger(v) || v < TOKEN_TTL_MIN_SECONDS || v > TOKEN_TTL_MAX_SECONDS) {
+ res.status(400).json({
+ error: 'invalid_token_ttl',
+ message: `tokenTtl must be an integer number of seconds between ${TOKEN_TTL_MIN_SECONDS} and ${TOKEN_TTL_MAX_SECONDS} (90 days); got ${JSON.stringify(tokenTtl)}. Omit the field (or pass 0/null) to keep the server default.`,
+ });
+ return;
+ }
+ ttlNum = v;
+ }
+ // Column pre-flight OUTSIDE the tx (25P02 — nothing inside may degrade):
+ // pre-v61 brains lack the scoped-client columns and registerClientManual's
+ // internal 42703 retry ladder would abort the transaction, so refuse up
+ // front with the CLI lane's brain_too_old contract. Passing {columns}
+ // through also makes the ttl write SKIP (rather than throw) on brains
+ // without token_ttl.
+ const columns = await preflightOauthClientColumns(sql);
+ if (!columns.has('source_id') || !columns.has('federated_read')) {
+ res.status(400).json({
+ error: 'brain_too_old',
+ message: 'this brain predates scoped OAuth clients (source_id/federated_read columns) — run `gbrain apply-migrations --yes` first.',
+ });
+ return;
+ }
+ // Duplicate-name parity with the CLI lane: a second client under the
+ // same name is a 409, never a silent second row. The dup-check and the
+ // INSERT run in ONE transaction under the SAME name-scoped advisory
+ // lock the CLI takes — two concurrent same-name requests serialize, and
+ // the loser sees the winner's committed row (as two separate autocommit
+ // statements, both used to pass the pre-check). deleted_at tolerance is
+ // preflight-decided (no in-tx 42703 retry).
+ let dupClientId: string | null = null;
+ let registered: RegisteredClient | undefined;
+ await engine.transaction(async (tx) => {
+ await tx.executeRaw(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [registerClientNameLockKey(name)]);
+ const txSql = sqlQueryForEngine(tx);
+ const dupRows = columns.has('deleted_at')
+ ? await txSql`SELECT client_id FROM oauth_clients WHERE client_name = ${name} AND deleted_at IS NULL`
+ : await txSql`SELECT client_id FROM oauth_clients WHERE client_name = ${name}`;
+ if (dupRows.length > 0) {
+ dupClientId = String(dupRows[0].client_id);
+ return;
+ }
+ // Compose the SAME core the CLI uses (registerScopedClient) instead of
+ // open-coding registerClientManual + a raw TTL UPDATE — the two paths
+ // had already drifted once (this route hardcoded 'default' pre-v0.41).
+ registered = await registerScopedClient(txSql, name, {
+ grantTypes: grants,
+ scopes: scopeString,
+ sourceId,
+ federatedRead: federatedReadIds,
+ redirectUris: uris,
+ tokenEndpointAuthMethod: validatedAuthMethod,
+ boundTools: undefined,
+ boundSourceId: undefined,
+ boundBrainId: undefined,
+ boundSlugPrefixes: undefined,
+ boundMaxConcurrent: undefined,
+ budgetUsdPerDay: undefined,
+ tokenTtlSeconds: undefined,
+ }, { tokenTtlSeconds: ttlNum, columns });
+ });
+ if (dupClientId !== null) {
+ res.status(409).json({
+ error: 'duplicate_name',
+ client_id: dupClientId,
+ });
+ return;
+ }
+ // Post-commit: the row exists from here on — any later failure must
+ // name the created client (no false "nothing was created").
+ const reg = registered!;
+ createdClientId = reg.clientId;
+ res.json({
+ clientId: reg.clientId,
+ ...(reg.clientSecret !== undefined ? { clientSecret: reg.clientSecret } : {}),
+ tokenTtl: reg.tokenTtl ?? null,
+ });
} catch (e) {
- res.status(500).json({ error: e instanceof Error ? e.message : 'Registration failed' });
+ // A throw INSIDE the tx rolls the row back (no client persists); the
+ // only window where a client exists at failure time is post-commit,
+ // marked by createdClientId — include it so the operator can revoke.
+ res.status(500).json({
+ error: e instanceof Error ? e.message : 'Registration failed',
+ ...(createdClientId !== undefined ? { client_id: createdClientId } : {}),
+ });
}
});
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 98185acaf0..959da41f71 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -40,6 +40,8 @@ import {
purgeExpiredSources,
formatImpact,
formatSoftDelete,
+ clientsReferencingSource,
+ formatClientReferentsBlock,
SOFT_DELETE_TTL_HOURS,
} from '../core/destructive-guard.ts';
import {
@@ -60,6 +62,8 @@ import {
sourceFederationState,
type SourceRow as LoadedSourceRow,
} from '../core/sources-load.ts';
+import { sqlQueryForEngine } from '../core/sql-query.ts';
+import { preflightOauthClientColumns } from './auth.ts';
// ── Validation ──────────────────────────────────────────────
@@ -535,19 +539,63 @@ async function runRemove(engine: BrainEngine, args: string[]): Promise<void> {
}
}
- // v0.42.44 — tear down durability scaffolding BEFORE the row is deleted (we
- // need the path/label while it still exists). Best-effort; tolerates missing
- // repo/cron/credential independently.
+ // PR6 D5b: FK-RESTRICT pre-check — a referenced source refuses with revoke
+ // guidance, never a raw FK violation.
+ const referents = await clientsReferencingSource(engine, id);
+ if (referents.length > 0) {
+ console.error(formatClientReferentsBlock(id, referents));
+ process.exit(5);
+ }
+
+ // cathedral-6 (F1): the row DELETE commits FIRST — atomically with an in-tx
+ // referents re-check — and external teardown (unharden: git scaffolding /
+ // cron / credential) runs only AFTER the commit. Pre-fix the teardown ran
+ // before the DELETE, so a registration racing between the pre-check and the
+ // DELETE failed the FK AFTER scaffolding was already destroyed. The in-tx
+ // re-check uses a column-preflighted statement shape (25P02: no
+ // catch-and-retry degrade inside a tx; missing table ⇒ empty column set ⇒
+ // no FK ⇒ skip); the FK constraint itself is the backstop for a
+ // registration committing between the re-check and the DELETE.
+ class SourceReferencedError extends Error {}
try {
- const { unhardenBrainRepo } = await import('../core/brain-repo-durability.ts');
- await unhardenBrainRepo({ repoPath: src.local_path ?? '', sourceId: id, logger: (l) => console.error(l) });
+ await engine.transaction(async (tx) => {
+ const cols = await preflightOauthClientColumns(sqlQueryForEngine(tx));
+ if (cols.has('source_id')) {
+ // PHYSICAL count (no deleted_at filter): the FK ignores soft-deletion.
+ const rows = await tx.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM oauth_clients WHERE source_id = $1`,
+ [id],
+ );
+ if (Number(rows[0]?.n ?? 0) > 0) throw new SourceReferencedError();
+ }
+ await tx.executeRaw(`DELETE FROM sources WHERE id = $1`, [id]);
+ });
} catch (e) {
- console.error(`[gbrain] durability teardown skipped (non-fatal): ${(e as Error).message}`);
+ const code = typeof e === 'object' && e !== null && 'code' in e ? String((e as { code?: unknown }).code) : '';
+ if (e instanceof SourceReferencedError || code === '23503') {
+ const raced = await clientsReferencingSource(engine, id);
+ console.error(formatClientReferentsBlock(id, raced.length > 0 ? raced : referents));
+ process.exit(5);
+ }
+ throw e;
}
- await engine.executeRaw(`DELETE FROM sources WHERE id = $1`, [id]);
const pageCount = impact?.pageCount ?? 0;
console.log(`Removed source "${id}" (${pageCount} pages + dependent rows cascaded).`);
+
+ // v0.42.44 — durability-scaffolding teardown, POST-COMMIT as of cathedral-6
+ // (the path/label were captured from `src` before the delete). Best-effort;
+ // on failure the DB row is already gone — print exactly what remains so the
+ // operator can sweep the residue (doctor also surfaces it).
+ try {
+ const { unhardenBrainRepo } = await import('../core/brain-repo-durability.ts');
+ await unhardenBrainRepo({ repoPath: src.local_path ?? '', sourceId: id, logger: (l) => console.error(l) });
+ } catch (e) {
+ console.error(
+ `[gbrain] source row "${id}" is deleted, but durability teardown failed (non-fatal): ${(e as Error).message}. ` +
+ `Residue may remain${src.local_path ? ` at ${src.local_path}` : ''} (git hardening / cron entry / stored credential) — \`gbrain doctor\` surfaces it.`,
+ );
+ }
}
// ── Subcommand: archive (soft-delete) ───────────────────────
@@ -724,6 +772,14 @@ async function runPurge(engine: BrainEngine, args: string[]): Promise<void> {
process.exit(5);
}
+ // PR6 D5b: FK-RESTRICT pre-check — refuse with revoke guidance instead of
+ // letting the raw FK violation surface from the DELETE.
+ const referents = await clientsReferencingSource(engine, id);
+ if (referents.length > 0) {
+ console.error(formatClientReferentsBlock(id, referents));
+ process.exit(5);
+ }
+
await engine.executeRaw(`DELETE FROM sources WHERE id = $1`, [id]);
console.log(`Permanently deleted source "${id}" (${impact.pageCount} pages cascaded).`);
return;
diff --git a/src/core/bootstrap/codex-toml.ts b/src/core/bootstrap/codex-toml.ts
index 8739f3f178..157889cc14 100644
--- a/src/core/bootstrap/codex-toml.ts
+++ b/src/core/bootstrap/codex-toml.ts
@@ -147,6 +147,40 @@ function renderBlock(block: CodexHttpServerBlock): string[] {
];
}
+/**
+ * Render the `[mcp_servers.<name>]` table as a paste-ready snippet WITHOUT
+ * the CODEX_TOML_BLOCK_BEGIN/END lines. The managed markers are SINGLETON —
+ * findBlock refuses duplicate marker pairs and writeCodexHttpServerBlock
+ * strips any prior managed block on rewrite — so a printed snippet carrying
+ * markers would later be stripped or rejected by the writer. A marker-free
+ * snippet stays ordinary user content: a later managed write sees it as a
+ * FOREIGN table and refuses to double-define rather than silently absorbing
+ * it.
+ *
+ * Validation mirrors the writer: the bare-key name assertion up front, then
+ * the rendered text is parsed back and our table's keys are asserted to be
+ * exactly [bearer_token, url] (the same key-set check the writer's
+ * post-render validation performs).
+ */
+export function renderCodexHttpServerBlock(block: CodexHttpServerBlock): string {
+ assertBareKeyName(block.name);
+ const lines = renderBlock(block).filter(
+ (line) => line !== CODEX_TOML_BLOCK_BEGIN && line !== CODEX_TOML_BLOCK_END,
+ );
+ const text = lines.join('\n');
+ const parsed = parseToml(text);
+ const servers = parsed.mcp_servers as Record<string, unknown> | undefined;
+ const ours = servers?.[block.name];
+ const ourKeys = typeof ours === 'object' && ours !== null ? Object.keys(ours as object).sort() : [];
+ if (ourKeys.join(',') !== 'bearer_token,url') {
+ throw new Error(
+ `render validation failed: [mcp_servers.${block.name}] keys are [${ourKeys.join(', ')}], ` +
+ `expected exactly [bearer_token, url].`,
+ );
+ }
+ return text;
+}
+
/** Atomic 0600 write preserving symlinks and the file's dominant EOL
* (forceMode: the file carries a bearer token regardless of prior mode). */
function atomicWriteToml(configPath: string, unixText: string, crlf: boolean): void {
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index 0b706eb061..f1bba6b726 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -104,6 +104,17 @@ import {
removeOpencodeMcpEntry,
writeOpencodeMcpEntry,
} from './opencode-json.ts';
+import { isServeOlderThanScopes, probeServeHealth } from './serve-health.ts';
+
+// Peeled façade seam (cathedral-6): the serve probe + scopes version floor
+// moved to serve-health.ts; re-exported so this module's public surface — and
+// every import site — is unchanged.
+export {
+ SCOPES_MIN_SERVE_VERSION,
+ isServeOlderThanScopes,
+ probeServeHealth,
+ type ServeHealth,
+} from './serve-health.ts';
// ── Flags ───────────────────────────────────────────────────────────────────
@@ -227,13 +238,6 @@ export function parseHarnessArgs(rest: string[]): HarnessFlags {
// ── Deps (injectable for the serial suite) ──────────────────────────────────
-export interface ServeHealth {
- ok: boolean;
- engine?: string;
- version?: string;
- detail?: string;
-}
-
export interface HarnessDeps {
runner: ExecRunner;
gbrainHome: string;
@@ -351,25 +355,6 @@ function defaultPgliteLiveServe(): boolean {
return probeLivePgliteHolder(cfg.database_path) !== null;
}
-// ── Serve probe ─────────────────────────────────────────────────────────────
-
-export async function probeServeHealth(
- mcpUrl: string,
- fetchFn: typeof fetch,
- timeoutMs = 3000,
-): Promise<ServeHealth> {
- const base = mcpUrl.replace(/\/mcp$/, '');
- try {
- const res = await fetchFn(`${base}/health`, { signal: AbortSignal.timeout(timeoutMs) });
- if (!res.ok) return { ok: false, detail: `GET ${base}/health → ${res.status}` };
- const body = (await res.json()) as { status?: string; version?: string; engine?: string };
- if (body.status !== 'ok') return { ok: false, detail: `health status: ${body.status ?? 'unknown'}` };
- return { ok: true, version: body.version, engine: body.engine };
- } catch (e) {
- return { ok: false, detail: (e as Error).message };
- }
-}
-
// ── Consent copy [C5 / #4029 register] ──────────────────────────────────────
export function buildConsentBlock(p: {
@@ -1381,24 +1366,6 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
return allConfirmed && smokeOk ? 0 : 1;
}
-/** The scopes-honoring release: any serve older verifies scoped tokens as full access. */
-/** The first release whose verify path honors the scopes column. PINNED — a
- * comparison against the moving CLI VERSION would false-flag every scope-aware
- * serve as soon as the next release ships (ship-review P3). */
-export const SCOPES_MIN_SERVE_VERSION = '0.45.14.0';
-
-export function isServeOlderThanScopes(serveVersion: string): boolean {
- const parse = (v: string): number[] => v.split('.').map((n) => Number.parseInt(n, 10) || 0);
- const a = parse(serveVersion);
- const b = parse(SCOPES_MIN_SERVE_VERSION);
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
- const x = a[i] ?? 0;
- const y = b[i] ?? 0;
- if (x !== y) return x < y;
- }
- return false;
-}
-
// ── Remove [C9/F2/C8] ───────────────────────────────────────────────────────
export async function removeHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Promise<number> {
diff --git a/src/core/bootstrap/serve-health.ts b/src/core/bootstrap/serve-health.ts
new file mode 100644
index 0000000000..6d66580b49
--- /dev/null
+++ b/src/core/bootstrap/serve-health.ts
@@ -0,0 +1,49 @@
+/**
+ * serve-health.ts — serve /health probe + scopes version-skew floor, peeled
+ * from harness.ts (cathedral-6: the agent-register lane needs these without
+ * dragging the whole harness in). harness.ts re-exports this entire surface
+ * (peeled-façade rule: import sites never chase the peel). fetchFn stays an
+ * explicit argument — no ambient fetch, no engine, no config.
+ */
+
+export interface ServeHealth {
+ ok: boolean;
+ engine?: string;
+ version?: string;
+ detail?: string;
+}
+
+export async function probeServeHealth(
+ mcpUrl: string,
+ fetchFn: typeof fetch,
+ timeoutMs = 3000,
+): Promise<ServeHealth> {
+ const base = mcpUrl.replace(/\/mcp$/, '');
+ try {
+ const res = await fetchFn(`${base}/health`, { signal: AbortSignal.timeout(timeoutMs) });
+ if (!res.ok) return { ok: false, detail: `GET ${base}/health → ${res.status}` };
+ const body = (await res.json()) as { status?: string; version?: string; engine?: string };
+ if (body.status !== 'ok') return { ok: false, detail: `health status: ${body.status ?? 'unknown'}` };
+ return { ok: true, version: body.version, engine: body.engine };
+ } catch (e) {
+ return { ok: false, detail: (e as Error).message };
+ }
+}
+
+/** The scopes-honoring release: any serve older verifies scoped tokens as full access. */
+/** The first release whose verify path honors the scopes column. PINNED — a
+ * comparison against the moving CLI VERSION would false-flag every scope-aware
+ * serve as soon as the next release ships (ship-review P3). */
+export const SCOPES_MIN_SERVE_VERSION = '0.45.14.0';
+
+export function isServeOlderThanScopes(serveVersion: string): boolean {
+ const parse = (v: string): number[] => v.split('.').map((n) => Number.parseInt(n, 10) || 0);
+ const a = parse(serveVersion);
+ const b = parse(SCOPES_MIN_SERVE_VERSION);
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
+ const x = a[i] ?? 0;
+ const y = b[i] ?? 0;
+ if (x !== y) return x < y;
+ }
+ return false;
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 92f5af9e6b..73ff779a0a 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -15,7 +15,7 @@
// status quo; missing a real one breaks working invocations.
export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'advisor': ['--aliases', '--all', '--apply', '--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--skills-dir', '--source', '--stale', '--supersessions', '--surface', '--thin', '--token-ttl', '--verbose', '--workspace', '--yes'],
- 'agent': ['--aliases', '--all', '--brain', '--detach', '--fanout-manifest', '--federated', '--flag', '--flags', '--follow', '--help', '--include-null-signature', '--json', '--max-turns', '--model', '--no-extract', '--no-federated', '--no-follow', '--note', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--since', '--source', '--source-guard', '--stale', '--subagent-def', '--supersessions', '--thin', '--timeout-ms', '--tools', '--word'],
+ 'agent': ['--aliases', '--all', '--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated', '--federated-read', '--flag', '--flags', '--follow', '--harness', '--help', '--http', '--include-null-signature', '--json', '--max-turns', '--mcp-only', '--model', '--no-extract', '--no-federated', '--no-follow', '--note', '--path', '--pattern', '--pending', '--port', '--preset', '--reissue', '--repo', '--reset', '--resolve', '--restore-only', '--scopes', '--show-token', '--since', '--source', '--source-guard', '--stale', '--subagent-def', '--supersessions', '--surface', '--thin', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],
'anomalies': ['--aliases', '--all', '--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lookback-days', '--mcp-only', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--sigma', '--since', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl'],
'apply-migrations': ['--ab', '--all', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dry-run', '--exclusive', '--fast', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--from-meetings', '--from-pages', '--help', '--history', '--host-dir', '--http', '--json', '--lang', '--list', '--locks', '--markdown', '--max-age', '--migrate-only', '--migration', '--mode', '--multimodal', '--no-autopilot-install', '--no-embedding', '--no-extract', '--non-interactive', '--phase', '--priority', '--refresh-unqualified', '--remediate', '--rollback', '--skip-verify', '--source', '--stale', '--surface', '--token-ttl', '--undo-wave', '--use-captured-snapshot', '--with-calibration', '--yes'],
'auth': ['--aliases', '--all', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--days', '--enable-dcr', '--enable-dcr-insecure', '--fast', '--federated-read', '--force', '--from-pages', '--grant-types', '--help', '--http', '--id', '--include-null-signature', '--json', '--no-embedding', '--no-extract', '--pattern', '--pending', '--redirect-uri', '--reset', '--resolve', '--scopes', '--source', '--stale', '--supersessions', '--surface', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
@@ -38,9 +38,9 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'code-def': ['--aliases', '--all', '--brain', '--chunker-debug', '--help', '--include-null-signature', '--json', '--lang', '--limit', '--no-extract', '--no-json', '--pattern', '--pending', '--pretty', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin', '--yes'],
'code-refs': ['--aliases', '--all', '--brain', '--chunker-debug', '--help', '--include-null-signature', '--json', '--lang', '--limit', '--no-extract', '--no-json', '--pattern', '--pending', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin', '--yes'],
'config': ['--aliases', '--all', '--brain', '--column', '--coverage-override', '--detail', '--embedding-dimensions', '--embedding-model', '--fast', '--federated-read', '--follow', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--markdown', '--model', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--pattern', '--pending', '--pglite', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--surface', '--thin', '--token-ttl', '--yes'],
- 'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--delete-brain', '--env', '--force', '--grant-types', '--header', '--help', '--http', '--install', '--json', '--name', '--oauth', '--public-url', '--pure', '--register', '--remove', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
+ 'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--delete-brain', '--env', '--force', '--grant-types', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
'conversation-parser': ['--aliases', '--all', '--brain', '--help', '--include-null-signature', '--json', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin'],
- 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--aliases', '--all', '--allow-shell-jobs', '--allow-unverified-remote', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-null-signature', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pattern', '--pending', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--refresh-unqualified', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--set', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'],
+ 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--aliases', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-null-signature', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pattern', '--pending', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--refresh-unqualified', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--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', '--stats', '--status', '--strategy', '--strict', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'],
'dream': ['--against', '--aliases', '--all', '--allow-regression', '--anchor', '--asof', '--audit-rejects', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--cancel-unmatched', '--code', '--committed-baseline', '--compare', '--compile', '--concurrent', '--ctx-size', '--cycles', '--date', '--detail', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--expansion', '--explain', '--fast', '--federated', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--format', '--from', '--from-db', '--from-pages', '--gold', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--install', '--json', '--judge-model', '--justification', '--keyword-only', '--lang', '--limit', '--llm', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-tokens', '--max-usd', '--mcp-only', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--name-only', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-llm', '--no-mutate', '--no-trajectory', '--once', '--out', '--output', '--output-dir', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--phase', '--priority', '--progress-interval', '--progress-json', '--pull', '--quiet', '--receipt-dir', '--reconcile-queue', '--remediate', '--repo', '--reranking', '--reset', '--resolve', '--restore-only', '--resume-from', '--retrieval-only', '--rounds', '--rubric-version', '--save', '--seed', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--suite', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--take', '--task', '--thin', '--threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--unsafe-bypass-dream-guard', '--update-baseline', '--verify', '--version', '--window', '--yes'],
'edges-backfill': ['--aliases', '--all', '--all-sources', '--brain', '--concurrency', '--federated', '--help', '--include-null-signature', '--json', '--max-age', '--max-chunks', '--max-cost-usd', '--no-extract', '--no-federated', '--older-than', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--source-guard', '--stale', '--supersessions', '--thin', '--timeout', '--workers'],
'embed': ['--aliases', '--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--serial', '--slugs', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--to', '--token-ttl', '--version'],
@@ -88,7 +88,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'remote': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-pages', '--full', '--help', '--http', '--include-flagged', '--index-audit', '--json', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--multimodal', '--nice', '--no-embedding', '--older-than', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--progress-json', '--query', '--queue', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resume', '--scope', '--scopes', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--target', '--target-score', '--timeout', '--to', '--token-ttl', '--top-k', '--url', '--window', '--workers', '--yes'],
'repair-jsonb': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--lang', '--markdown', '--multimodal', '--near-symbol', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restore-only', '--source', '--stale', '--supabase', '--surface', '--symbol-kind', '--thin', '--timeout', '--token-ttl', '--url'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abbrev-ref', '--abort', '--aliases', '--all', '--all-sources', '--allow-unverified-remote', '--brain', '--branch', '--break-lock', '--cached', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--detect', '--diff-filter', '--dry-run', '--exclude-standard', '--explain', '--fast', '--federated', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--help', '--http', '--include-null-signature', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--lang', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--pattern', '--pending', '--porcelain', '--push-only', '--quiet', '--rebase', '--repo', '--reset', '--resolve', '--restore-only', '--secret', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supersessions', '--surface', '--symbol-kind', '--thin', '--token-ttl', '--unset-all', '--url', '--url-managed', '--yes'],
+ 'repos': ['--abbrev-ref', '--abort', '--aliases', '--all', '--all-sources', '--allow-unverified-remote', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--detect', '--diff-filter', '--dry-run', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--http', '--id', '--include-null-signature', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--lang', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--pattern', '--pending', '--porcelain', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repo', '--reset', '--resolve', '--restore-only', '--scopes', '--secret', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supersessions', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unset-all', '--url', '--url-managed', '--usage', '--yes'],
'resolvers': ['--auto', '--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--aliases', '--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-sunset-target', '--from-pages', '--help', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--max-age', '--model', '--multimodal', '--name', '--nice', '--no', '--no-embed', '--no-embedding', '--no-extract', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--pattern', '--pending', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reranking', '--reset', '--resolve', '--resume', '--retarget', '--slugs', '--source', '--stale', '--status', '--supersessions', '--surface', '--thin', '--timeout', '--to', '--token-ttl', '--version', '--yes'],
'routing-eval': ['--brain', '--fix', '--help', '--json', '--llm', '--skills-dir', '--source', '--strict', '--verbose'],
@@ -101,7 +101,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--brain', '--dry-run', '--exit-code', '--fast', '--fix', '--force', '--force-unlock', '--format', '--from', '--from-pages', '--frontmatter', '--full', '--help', '--homepage', '--http', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-embedding', '--no-lint', '--note', '--out', '--overwrite-local', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--short', '--since', '--skills-dir', '--skip-doctor', '--source', '--strict', '--surface', '--target', '--tier', '--token-ttl', '--trust', '--url', '--verbose', '--verify', '--workspace', '--yes'],
'skillpack-check': ['--background', '--brain', '--brain-wide-max-cost-usd', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strict', '--timeout', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abbrev-ref', '--abort', '--aliases', '--all', '--all-sources', '--allow-unverified-remote', '--brain', '--branch', '--break-lock', '--cached', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--detect', '--diff-filter', '--dry-run', '--exclude-standard', '--explain', '--fast', '--federated', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--help', '--http', '--include-null-signature', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--lang', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--pattern', '--pending', '--porcelain', '--push-only', '--quiet', '--rebase', '--repo', '--reset', '--resolve', '--restore-only', '--secret', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supersessions', '--surface', '--symbol-kind', '--thin', '--token-ttl', '--unset-all', '--url', '--url-managed', '--yes'],
+ 'sources': ['--abbrev-ref', '--abort', '--aliases', '--all', '--all-sources', '--allow-unverified-remote', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--detect', '--diff-filter', '--dry-run', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--file', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--http', '--id', '--include-null-signature', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--lang', '--local', '--markdown', '--max-age', '--max-cost-usd', '--message', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--no-cron', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-verify', '--others', '--params', '--pat-file', '--path', '--pattern', '--pending', '--porcelain', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repo', '--reset', '--resolve', '--restore-only', '--scopes', '--secret', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supersessions', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unset-all', '--url', '--url-managed', '--usage', '--yes'],
'status': ['--abbrev-ref', '--abi', '--abort', '--aliases', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--budget-usd-per-day', '--by-mention', '--cached', '--catch-up', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content', '--content-audit', '--count', '--date', '--days', '--deadline-ms', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--git-path', '--hard-deadline', '--help', '--http', '--image', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--json', '--judge-model', '--kind', '--lang', '--limit', '--lock', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-sources', '--max-usd', '--mcp-only', '--migrate-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--offset', '--older-than', '--order', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pattern', '--pending', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--reenrich-after', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--scopes', '--section', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--thin-threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--trusted-extraction', '--type', '--types', '--url', '--url-managed', '--verbose', '--verify', '--version', '--watch', '--what', '--where', '--who', '--window', '--with-db', '--workers', '--yes'],
'storage': ['--aliases', '--all', '--brain', '--federated', '--fix', '--help', '--include-null-signature', '--json', '--no-extract', '--no-federated', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--source-guard', '--stale', '--supersessions', '--thin', '--to'],
'sweep': ['--aliases', '--all', '--batch-limit', '--brain', '--budget-ms', '--help', '--include-null-signature', '--json', '--no-extract', '--once', '--pattern', '--pending', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin', '--timeout'],
diff --git a/src/core/db.ts b/src/core/db.ts
index 290ad721d0..7d89413dfa 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -357,6 +357,7 @@ export async function disconnect(): Promise<void> {
export async function initSchema(): Promise<void> {
const conn = getConnection();
// Advisory lock prevents concurrent initSchema() calls from deadlocking
+ // Lock-census (PR6 D5): INTENTIONALLY brain-global (session lock, fixed key 42) — schema replay mutates the whole database, not one source.
await conn`SELECT pg_advisory_lock(42)`;
try {
await conn.unsafe(SCHEMA_SQL);
diff --git a/src/core/destructive-guard.ts b/src/core/destructive-guard.ts
index c35d55b4bd..b52f08ecb4 100644
--- a/src/core/destructive-guard.ts
+++ b/src/core/destructive-guard.ts
@@ -15,6 +15,7 @@
import type { BrainEngine } from './engine.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from './source-config-sql.ts';
+import { isUndefinedColumnError, isUndefinedTableError } from './utils.ts';
// ── Types ───────────────────────────────────────────────────
@@ -25,10 +26,36 @@ export interface DestructiveImpact {
chunkCount: number;
embeddingCount: number;
fileCount: number;
+ /**
+ * PR6 D5b: count of ALL OAuth clients (live AND soft-deleted — the FK is
+ * physical, ON DELETE RESTRICT ignores deleted_at) whose source_id
+ * references this source. A hard delete with referents raises a raw FK
+ * violation — the preview surfaces the block before the trigger is pulled.
+ * Optional so hand-built impact literals (tests, older callers) stay valid.
+ */
+ oauthClientCount?: number;
+ /**
+ * cathedral-6: count of hot-memory facts in the source. Facts are the
+ * primary agent write lane — a revoked agent's workspace can hold facts
+ * with ZERO pages, so a pages-only preview would say "safe to remove"
+ * while the delete cascades the agent's memory away. Optional so
+ * hand-built impact literals (tests, older callers) stay valid; consumers
+ * read it as `?? 0`.
+ */
+ factCount?: number;
/** Human-readable summary line */
summary: string;
}
+/** An OAuth client row that references a source via oauth_clients.source_id.
+ * `deleted` marks soft-deleted (revoked-but-retained) rows — the FK is
+ * PHYSICAL (ON DELETE RESTRICT ignores deleted_at), so they block too. */
+export interface SourceClientReferent {
+ clientId: string;
+ clientName: string;
+ deleted: boolean;
+}
+
export interface SoftDeletedSource {
id: string;
name: string;
@@ -45,6 +72,95 @@ export const SOFT_DELETE_TTL_HOURS = 72;
/** Threshold: operations affecting this many pages or more require confirmation. */
export const CONFIRM_THRESHOLD_PAGES = 1;
+// ── FK-RESTRICT lifecycle (PR6 D5b) ─────────────────────────
+
+/**
+ * ALL OAuth clients referencing a source via oauth_clients.source_id
+ * (ON DELETE RESTRICT — these rows BLOCK a hard delete of the source).
+ * PHYSICAL semantics: soft-deleted rows (admin revoke does UPDATE SET
+ * deleted_at) still hold the FK, so they are returned too, tagged
+ * `deleted: true`, and the guidance splits per row. Pre-migration brains
+ * without the deleted_at column fall back to all referents (same
+ * 42703-retry idiom as oauth-provider.ts) tagged live; brains without
+ * the oauth_clients table — or without the source_id column (no column
+ * ⇒ no FK ⇒ no referents) — have no referents by construction.
+ */
+export async function clientsReferencingSource(
+ engine: BrainEngine,
+ sourceId: string,
+): Promise<SourceClientReferent[]> {
+ try {
+ const rows = await engine.executeRaw<{ client_id: string; client_name: string; deleted: boolean }>(
+ `SELECT client_id, client_name, (deleted_at IS NOT NULL) AS deleted
+ FROM oauth_clients
+ WHERE source_id = $1
+ ORDER BY client_id`,
+ [sourceId],
+ );
+ return rows.map((r) => ({ clientId: r.client_id, clientName: r.client_name, deleted: r.deleted === true }));
+ } catch (e) {
+ if (isUndefinedTableError(e)) return [];
+ // isUndefinedColumnError is code-first (any 42703 matches), and the
+ // primary query references BOTH optional columns — disambiguate on the
+ // message, which names the missing column.
+ const msg = e instanceof Error ? e.message : String(e);
+ if (isUndefinedColumnError(e, 'source_id') && msg.includes('source_id')) return [];
+ if (!(isUndefinedColumnError(e, 'deleted_at') && msg.includes('deleted_at'))) throw e;
+ try {
+ const rows = await engine.executeRaw<{ client_id: string; client_name: string }>(
+ `SELECT client_id, client_name FROM oauth_clients
+ WHERE source_id = $1
+ ORDER BY client_id`,
+ [sourceId],
+ );
+ return rows.map((r) => ({ clientId: r.client_id, clientName: r.client_name, deleted: false }));
+ } catch (e2) {
+ // The fallback's only optional column is source_id — no column ⇒ no FK.
+ if (isUndefinedColumnError(e2, 'source_id')) return [];
+ throw e2;
+ }
+ }
+}
+
+/**
+ * Refusal message for `sources remove` / `sources purge <id>` when live OAuth
+ * clients still reference the source. Built here (not in sources.ts — that
+ * file is module-size-ratcheted) so both arms print identical guidance
+ * instead of letting the raw FK violation surface.
+ */
+export function formatClientReferentsBlock(
+ sourceId: string,
+ referents: SourceClientReferent[],
+): string {
+ const live = referents.filter((r) => !r.deleted);
+ const dead = referents.filter((r) => r.deleted);
+ const lines: string[] = [
+ ``,
+ `Cannot delete source "${sourceId}": ${referents.length} OAuth client(s) reference this source`,
+ `(oauth_clients.source_id is ON DELETE RESTRICT — the delete would fail at the database).`,
+ ``,
+ ];
+ for (const r of referents) {
+ lines.push(` - ${r.clientName} (${r.clientId})${r.deleted ? ' [revoked, retained]' : ''}`);
+ }
+ if (live.length > 0) {
+ lines.push(``);
+ lines.push(`Revoke each live client first (hard delete), then retry:`);
+ for (const r of live) {
+ lines.push(` gbrain auth revoke-client "${r.clientId}"`);
+ }
+ }
+ if (dead.length > 0) {
+ lines.push(``);
+ lines.push(`Revoked-but-retained rows still block the FK — \`gbrain auth revoke-client "<id>"\` hard-deletes them:`);
+ for (const r of dead) {
+ lines.push(` gbrain auth revoke-client "${r.clientId}"`);
+ }
+ }
+ lines.push(``);
+ return lines.join('\n');
+}
+
// ── Impact Assessment ───────────────────────────────────────
/**
@@ -106,11 +222,31 @@ export async function assessDestructiveImpact(
fileCount = fileRows[0]?.n ?? 0;
}
+ // cathedral-6: count hot-memory facts. A revoked agent's workspace can
+ // hold facts with zero pages — those are data at risk, not "no data".
+ // Tolerant of a pre-v0.31 brain without the facts table (same degrade
+ // posture as clientsReferencingSource).
+ let factCount = 0;
+ try {
+ const factRows = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM facts WHERE source_id = $1`,
+ [sourceId],
+ );
+ factCount = factRows[0]?.n ?? 0;
+ } catch (e) {
+ if (!isUndefinedTableError(e)) throw e;
+ }
+
+ // PR6 D5b: fold the FK-RESTRICT referent count into the preview so the
+ // operator sees the block BEFORE pulling the trigger.
+ const oauthClientCount = (await clientsReferencingSource(engine, sourceId)).length;
+
const parts: string[] = [];
if (pageCount > 0) parts.push(`${pageCount.toLocaleString()} pages`);
if (chunkCount > 0) parts.push(`${chunkCount.toLocaleString()} chunks`);
if (embeddingCount > 0) parts.push(`${embeddingCount.toLocaleString()} embeddings`);
if (fileCount > 0) parts.push(`${fileCount.toLocaleString()} files`);
+ if (factCount > 0) parts.push(`${factCount.toLocaleString()} facts`);
const summary = parts.length > 0
? `⚠️ This will permanently delete: ${parts.join(', ')}`
@@ -123,6 +259,8 @@ export async function assessDestructiveImpact(
chunkCount,
embeddingCount,
fileCount,
+ factCount,
+ oauthClientCount,
summary,
};
}
@@ -144,8 +282,10 @@ export function checkDestructiveConfirmation(
// Dry run always passes (no side effects)
if (opts.dryRun) return null;
- // No data = no risk
- if (impact.pageCount === 0 && impact.chunkCount === 0 && impact.fileCount === 0) {
+ // No data = no risk. Facts gate exactly like pages (cathedral-6): a
+ // fact-only source (revoked agent workspace) is data at stake, not empty.
+ if (impact.pageCount === 0 && impact.chunkCount === 0 && impact.fileCount === 0
+ && (impact.factCount ?? 0) === 0) {
return null;
}
@@ -154,8 +294,9 @@ export function checkDestructiveConfirmation(
// --yes alone is NOT sufficient for destructive operations with data.
// This is the key behavior change: --yes used to be enough, now you
- // need --confirm-destructive when there's actual data at stake.
- if (opts.yes && impact.pageCount === 0) return null;
+ // need --confirm-destructive when there's actual data at stake. Facts
+ // mirror pages here too — --yes never bypasses a fact-holding source.
+ if (opts.yes && impact.pageCount === 0 && (impact.factCount ?? 0) === 0) return null;
return (
`\n${impact.summary}\n\n` +
@@ -282,17 +423,52 @@ export async function listArchivedSources(
* v0.26.5: moved from JSONB-driven iteration to a single set-based DELETE
* with `archived = true AND archive_expires_at <= now()`. Server-side
* filter; one round-trip; cascade-friendly.
+ *
+ * PR6 D5b: sources still referenced by ANY oauth_clients row (including
+ * soft-deleted ones — the FK is physical, ON DELETE RESTRICT ignores
+ * deleted_at) are SKIPPED via NOT EXISTS instead of aborting the whole
+ * set-based DELETE with an FK violation. Skips surface as ONE stderr warn
+ * naming the skipped ids; the return contract stays string[] (purged ids
+ * only) for the cycle.ts + jobs.ts callers.
*/
export async function purgeExpiredSources(
engine: BrainEngine,
): Promise<string[]> {
- const rows = await engine.executeRaw<{ id: string }>(
- `DELETE FROM sources
- WHERE archived = true
+ const expiredCond = `archived = true
AND archive_expires_at IS NOT NULL
- AND archive_expires_at <= now()
- RETURNING id`,
+ AND archive_expires_at <= now()`;
+ const referencedCond = `EXISTS (SELECT 1 FROM oauth_clients c WHERE c.source_id = sources.id)`;
+
+ // Query the skip set FIRST so the warn can name ids even though the DELETE
+ // never touches them. Pre-oauth brains (no oauth_clients table) — and
+ // pre-migration brains without the source_id column (no column ⇒ no FK) —
+ // purge unconditionally. The EXISTS is deliberately PHYSICAL (no deleted_at
+ // filter): the FK ignores soft-deletion.
+ let skipped: Array<{ id: string }> = [];
+ let hasOauthTable = true;
+ try {
+ skipped = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources WHERE ${expiredCond} AND ${referencedCond} ORDER BY id`,
+ );
+ } catch (e) {
+ if (!isUndefinedTableError(e) && !isUndefinedColumnError(e, 'source_id')) throw e;
+ hasOauthTable = false;
+ }
+
+ const rows = await engine.executeRaw<{ id: string }>(
+ hasOauthTable
+ ? `DELETE FROM sources WHERE ${expiredCond} AND NOT ${referencedCond} RETURNING id`
+ : `DELETE FROM sources WHERE ${expiredCond} RETURNING id`,
);
+
+ if (skipped.length > 0) {
+ const ids = skipped.map((s) => s.id).join(', ');
+ console.error(
+ `[gbrain] purge skipped ${skipped.length} expired source(s) still referenced by OAuth clients: ${ids}. ` +
+ `Revoke the referencing client(s) (gbrain auth revoke-client "<client-id>") and re-run the purge.`,
+ );
+ }
+
return rows.map((r) => r.id);
}
@@ -314,11 +490,19 @@ export function formatImpact(impact: DestructiveImpact): string {
`║ Chunks: ${String(impact.chunkCount.toLocaleString()).padEnd(42)}║`,
`║ Embeddings: ${String(impact.embeddingCount.toLocaleString()).padEnd(42)}║`,
`║ Files: ${String(impact.fileCount.toLocaleString()).padEnd(42)}║`,
+ `║ Facts: ${String((impact.factCount ?? 0).toLocaleString()).padEnd(42)}║`,
`╠══════════════════════════════════════════════════════════╣`,
`║ ${impact.summary.padEnd(56)}║`,
`╚══════════════════════════════════════════════════════════╝`,
``,
];
+ // PR6 D5b: surface the FK-RESTRICT block in the preview. Rendered outside
+ // the box (variable-width padding inside would misalign the frame).
+ if ((impact.oauthClientCount ?? 0) > 0) {
+ lines.push(`⚠️ ${impact.oauthClientCount} OAuth client(s) reference this source — a hard delete is`);
+ lines.push(` blocked (FK RESTRICT) until they are revoked: gbrain auth revoke-client "<client-id>"`);
+ lines.push(``);
+ }
return lines.join('\n');
}
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index d0ffcc4129..789e9d0fef 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -167,6 +167,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'home_dir_in_worktree',
'index_audit',
'npm_squat',
+ 'oauth_client_scope_health',
'oauth_confidential_client_health',
'orphan_clones',
'pgbouncer_prepare',
diff --git a/src/core/engine.ts b/src/core/engine.ts
index f705b2f296..b612497ec5 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1917,11 +1917,13 @@ export interface BrainEngine {
/**
* Audit log: facts that were superseded (expired_at + superseded_by both set),
- * newest first. Drives `gbrain recall --supersessions`.
+ * newest first. Drives `gbrain recall --supersessions`. `visibility` filters
+ * BEFORE the LIMIT (same contract as FactListOpts.visibility) so a remote
+ * world-only caller can't have a private row consume a limit slot.
*/
listSupersessions(
source_id: string,
- opts?: { since?: Date; limit?: number },
+ opts?: { since?: Date; limit?: number; visibility?: FactVisibility[] },
): Promise<FactRow[]>;
/**
diff --git a/src/core/mcp-registration.ts b/src/core/mcp-registration.ts
index 5f77bb2e87..c95267d6ec 100644
--- a/src/core/mcp-registration.ts
+++ b/src/core/mcp-registration.ts
@@ -166,6 +166,48 @@ export function cmdString(binary: string, argv: string[]): string {
return `${binary} ${argv.map(shellQuote).join(' ')}`;
}
+/**
+ * OAuth client-secret hygiene note. Moved here from src/commands/connect.ts
+ * (cathedral-6: the agent-register lane extends it with scoped-to/expiry/
+ * revoke lines and core must not import from commands); connect.ts re-exports
+ * it, so its surface — and this text — is unchanged.
+ */
+export const OAUTH_SECRET_NOTE =
+ 'Note: the client secret is sensitive — store it like a password. It mints ' +
+ 'short-lived, scoped access tokens; revoke with `gbrain auth revoke-client`.';
+
+/**
+ * Paste-ready OpenClaw wiring block — HONEST v1. OpenClaw has no native
+ * remote-MCP client yet, so the scoped path is a thin gbrain install on the
+ * OpenClaw machine (`gbrain init` in mcp-only mode), which routes brain access
+ * through the OAuth client minted for it. Deliberately NOT an mcpServers/
+ * stdio JSON config: the stdio config in docs/mcp/OPENCLAW.md grants FULL
+ * local DB access and does not use this client.
+ */
+export function openclawThinClientBlock(opts: {
+ issuerUrl: string;
+ mcpUrl: string;
+ clientId: string;
+ clientSecret: string;
+}): string {
+ const init = cmdString('gbrain', [
+ 'init',
+ '--mcp-only',
+ '--issuer-url', opts.issuerUrl,
+ '--mcp-url', opts.mcpUrl,
+ '--oauth-client-id', opts.clientId,
+ '--oauth-client-secret', opts.clientSecret,
+ ]);
+ return [
+ '# On the OpenClaw machine, install the gbrain CLI, then wire this scoped thin client:',
+ init,
+ '',
+ 'Your OpenClaw reaches the brain through the scoped gbrain CLI (search/query/recall/put);',
+ "native remote MCP isn't supported yet — the stdio config in docs/mcp/OPENCLAW.md grants",
+ 'FULL local DB access and does not use this client.',
+ ].join('\n');
+}
+
export function redactToken(s: string, token: string | null): string {
// Exact-substring scrub of the known token, plus a defense-in-depth pass over
// any `Bearer <value>` shape the SDK/CLI might echo in a transformed form the
diff --git a/src/core/minions/budget-meter.ts b/src/core/minions/budget-meter.ts
index cf0117ab6d..67b4a96dd6 100644
--- a/src/core/minions/budget-meter.ts
+++ b/src/core/minions/budget-meter.ts
@@ -92,6 +92,7 @@ export async function reserve(
// callers cannot both observe the same headroom. PGLite serializes its
// single connection and does not implement advisory locks.
if (tx.kind === 'postgres') {
+ // Lock-census (PR6 D5): INTENTIONALLY per-client, not per-source — the budget cap is an oauth_clients.budget_usd_per_day property; one client's concurrent requests must serialize regardless of which source each targets.
await sql`SELECT pg_advisory_xact_lock(${BigInt(lockKey)})`;
}
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 97fba3080c..02ed523ea8 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -320,6 +320,7 @@ export class MinionQueue {
// silently kill the fresh intent an hour later (round-2 V7).
if (coalesceActive && paramHash) {
const admissionQueue = opts?.queue ?? 'default';
+ // Lock-census (PR6 D5): INTENTIONALLY not source-keyed — admission identity is (name, queue, param-hash); any source in the payload is already folded into paramHash.
await tx.executeRaw(
`SELECT pg_advisory_xact_lock(hashtext('minion_admission:' || $1 || ':' || $2 || ':' || $3))`,
[jobName, admissionQueue, paramHash]
@@ -363,6 +364,7 @@ export class MinionQueue {
// concurrency — defeating the DoS backstop). Serialization cost only
// applies to names with a quota configured, i.e. the runaway ones.
if (policy.quotaMaxWaiting != null) {
+ // Lock-census (PR6 D5): INTENTIONALLY cross-source AND cross-queue — the quota is a name-global DoS backstop; scoping the key would let per-source submitters overshoot it in parallel.
await tx.executeRaw(
`SELECT pg_advisory_xact_lock(hashtext('minion_quota:' || $1))`,
[jobName]
@@ -419,6 +421,7 @@ export class MinionQueue {
const bpSourceId = typeof d?.sourceId === 'string' ? d.sourceId as string
: typeof d?.source_id === 'string' ? d.source_id as string
: null;
+ // Lock-census (PR6 D5): COMPLIANT — key already folds the payload source (coalesce($3,'')); the NULL-source wildcard arm is the documented maxWaiting contract above.
await tx.executeRaw(
`SELECT pg_advisory_xact_lock(hashtext('minion_maxwaiting:' || $1 || ':' || $2 || ':' || coalesce($3, '')))`,
[jobName, backpressureQueue, bpSourceId]
diff --git a/src/core/minions/rate-leases.ts b/src/core/minions/rate-leases.ts
index 7f4697d571..12628201a0 100644
--- a/src/core/minions/rate-leases.ts
+++ b/src/core/minions/rate-leases.ts
@@ -77,6 +77,7 @@ export async function acquireLease(
return engine.transaction(async (tx) => {
// txn-scoped advisory lock keyed on the rate-lease key name. Released
// automatically when the txn commits/rolls back.
+ // Lock-census (PR6 D5): INTENTIONALLY not source-keyed — a rate lease meters a shared external resource (per lease key, e.g. provider concurrency) brain-wide, not per source.
await tx.executeRaw(`SELECT pg_advisory_xact_lock($1::bigint)`, [lockKey.toString()]);
// Pre-prune stale leases for this key.
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 09b07b97a0..c1dab84bba 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -108,10 +108,26 @@ const recall: Operation = {
annotations: { title: 'recall (memory read)', readOnlyHint: true },
handler: async (ctx, p) => {
const sourceId = ctx.sourceId ?? 'default';
- const limit = typeof p.limit === 'number' ? p.limit : 50;
+ const limit = clampRecallLimit(p.limit);
const includeExpired = p.include_expired === true;
const grep = typeof p.grep === 'string' ? p.grep.toLowerCase() : null;
+ // Federated grants (cathedral-6): the fact arms honor the SAME scope
+ // ladder as every other read-side op — federated array > scalar >
+ // default — via sourceScopeOpts, never a hand-rolled filter. The engine
+ // fact APIs are scalar-source, so a federated grant fans out per granted
+ // source and merges newest-first; a single-source caller takes exactly
+ // the pre-v1 single-query path. A trusted-local `__all__` ({}) has no
+ // enumerable grant and keeps the resolved-scalar behavior.
+ const scope = sourceScopeOpts(ctx);
+ // Set-dedupe: a grant carrying a repeated id (or the scalar source again)
+ // must not fan out the same source twice into the merge.
+ const factSources: string[] = [...new Set(
+ scope.sourceIds && scope.sourceIds.length > 0 ? scope.sourceIds
+ : scope.sourceId ? [scope.sourceId]
+ : [sourceId],
+ )];
+
// Visibility filter: remote callers see world-only unless their token
// grants elevated visibility (future-proofing; v0.31 ships world-only
// for remote, all for local CLI).
@@ -120,52 +136,107 @@ const recall: Operation = {
? undefined
: ['world'] as ('private' | 'world')[];
- let rows: Awaited<ReturnType<typeof ctx.engine.listFactsByEntity>> = [];
+ type FactRows = Awaited<ReturnType<typeof ctx.engine.listFactsByEntity>>;
+ type FactRowItem = FactRows[number];
+ // Per-arm merge key: each arm's engine query ORDERs by a different column
+ // (supersessions by expired_at, entity by valid_from, the rest by
+ // created_at) — the cross-source merge must sort by the SAME key or the
+ // truncation at `limit` silently drops the wrong rows. Decorate-sort-
+ // undecorate: the key is computed once per row.
+ const mergeNewest = (lists: FactRows[], keyOf: (rec: Record<string, unknown>) => unknown): FactRows => {
+ if (lists.length === 1) return lists[0];
+ const toTime = (v: unknown): number => {
+ const t = v instanceof Date ? v.getTime() : v ? new Date(String(v)).getTime() : 0;
+ return Number.isFinite(t) ? t : 0;
+ };
+ const decorated = lists.flat().map((r: FactRowItem) => ({
+ r,
+ k: toTime(keyOf(r as unknown as Record<string, unknown>)),
+ }));
+ decorated.sort((a, b) => b.k - a.k);
+ return decorated.slice(0, limit).map(d => d.r);
+ };
+ const byCreated = (rec: Record<string, unknown>) => rec.created_at ?? rec.since_date;
+
+ let rows: FactRows = [];
if (p.supersessions === true) {
const since = parseSinceParam(p.since);
- rows = await ctx.engine.listSupersessions(sourceId, { since: since ?? undefined, limit });
+ // Visibility filters at the ENGINE level (before each source's LIMIT),
+ // same as the sibling fact-list arms — a post-merge filter would let a
+ // private newest row consume a limit slot and hide an older world row.
+ rows = mergeNewest(
+ await Promise.all(factSources.map(src =>
+ ctx.engine.listSupersessions(src, { since: since ?? undefined, limit, visibility }),
+ )),
+ (rec) => rec.expired_at ?? rec.created_at,
+ );
} else if (typeof p.entity === 'string' && p.entity.length > 0) {
const { resolveEntitySlug } = await import('../entities/resolve.ts');
- const slug = (await resolveEntitySlug(ctx.engine, sourceId, p.entity)) ?? p.entity;
- rows = await ctx.engine.listFactsByEntity(sourceId, slug, {
- activeOnly: !includeExpired,
- limit,
- visibility,
- });
+ rows = mergeNewest(
+ await Promise.all(factSources.map(async (src) => {
+ const slug = (await resolveEntitySlug(ctx.engine, src, p.entity as string)) ?? (p.entity as string);
+ return ctx.engine.listFactsByEntity(src, slug, {
+ activeOnly: !includeExpired,
+ limit,
+ visibility,
+ });
+ })),
+ (rec) => rec.valid_from ?? rec.created_at,
+ );
} else if (typeof p.session_id === 'string' && p.session_id.length > 0) {
- rows = await ctx.engine.listFactsBySession(sourceId, p.session_id, {
- activeOnly: !includeExpired,
- limit,
- visibility,
- });
+ rows = mergeNewest(
+ await Promise.all(factSources.map(src =>
+ ctx.engine.listFactsBySession(src, p.session_id as string, {
+ activeOnly: !includeExpired,
+ limit,
+ visibility,
+ }),
+ )),
+ byCreated,
+ );
} else if (p.since !== undefined) {
const since = parseSinceParam(p.since);
if (since) {
- rows = await ctx.engine.listFactsSince(sourceId, since, {
- activeOnly: !includeExpired,
- limit,
- visibility,
- });
+ rows = mergeNewest(
+ await Promise.all(factSources.map(src =>
+ ctx.engine.listFactsSince(src, since, {
+ activeOnly: !includeExpired,
+ limit,
+ visibility,
+ }),
+ )),
+ byCreated,
+ );
}
} else {
- // No filter: return recent across the source.
- rows = await ctx.engine.listFactsSince(sourceId, new Date(0), {
- activeOnly: !includeExpired,
- limit,
- visibility,
- });
+ // No filter: return recent across the granted source(s).
+ rows = mergeNewest(
+ await Promise.all(factSources.map(src =>
+ ctx.engine.listFactsSince(src, new Date(0), {
+ activeOnly: !includeExpired,
+ limit,
+ visibility,
+ }),
+ )),
+ byCreated,
+ );
}
if (grep) rows = rows.filter(r => r.fact.toLowerCase().includes(grep));
// v0.32: optional pending-consolidation count piggy-backed on the recall
// response. Single round trip on thin-client; omitted when not requested
- // so existing callers see no shape change.
+ // so existing callers see no shape change. Sums over the SAME factSources
+ // set the fact arms fan out across — a federated caller's pending count
+ // must cover every granted source, not just the scalar sourceId.
let pending_consolidation_count: number | undefined;
if (p.include_pending === true) {
try {
- pending_consolidation_count = await ctx.engine.countUnconsolidatedFacts(sourceId);
+ const counts = await Promise.all(
+ factSources.map(src => ctx.engine.countUnconsolidatedFacts(src)),
+ );
+ pending_consolidation_count = counts.reduce((a, b) => a + b, 0);
} catch (e) {
// Best-effort: if the count query fails we still return facts. Field
// stays undefined so callers can tell the difference between "0
@@ -604,6 +675,19 @@ const forget_fact: Operation = {
},
};
+/**
+ * recall's per-arm limit clamp — applied ONCE, before the per-source fan-out.
+ * The doc contract is "Default 50, cap 100": each engine clamps its own query,
+ * but the cross-source merge slices with THIS value, so an unclamped limit
+ * (e.g. 150 across two granted sources) would return up to 200 rows.
+ * Invalid input (undefined / NaN / non-positive / non-integer) → default 50;
+ * valid positive integers clamp to [1, 100]. Exported for the unit suite.
+ */
+export function clampRecallLimit(raw: unknown): number {
+ if (typeof raw !== 'number' || !Number.isInteger(raw) || raw <= 0) return 50;
+ return Math.min(raw, 100);
+}
+
/**
* Parse a `since` parameter into a Date. Accepts ISO 8601, plain duration
* shorthand ("8 hours ago", "3 days ago", "30m", "1h", "2d", "7d"), or
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 65c0e25245..a3b8b7765b 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -392,7 +392,10 @@ const put_page: Operation = {
try {
const enabled = await isAutoLinkEnabled(ctx.engine);
if (enabled) {
- autoLinks = await runAutoLink(ctx.engine, slug, result.parsedPage, ctx.sourceId ? { sourceId: ctx.sourceId } : undefined);
+ // ctx.sourceId is REQUIRED on OperationContext (v0.34 D4) — always
+ // pass it so the reconciliation reads/writes AND the advisory lock
+ // key stay scoped to the source this put_page targets.
+ autoLinks = await runAutoLink(ctx.engine, slug, result.parsedPage, { sourceId: ctx.sourceId });
}
} catch (e) {
autoLinks = { error: e instanceof Error ? e.message : String(e) };
@@ -556,6 +559,20 @@ const put_page: Operation = {
// so sync.ts, file_upload, code_import, and runFactsBackstop all share one
// predicate. Imported above.
+/**
+ * Advisory-lock key for the auto-link reconciliation critical section.
+ * Source-scoped (PR6 D5): two concurrent put_page calls on the SAME slug in
+ * DIFFERENT sources reconcile disjoint link rows — a shared `auto_link:${slug}`
+ * key serialized them for no correctness benefit (cross-source contention),
+ * while same-(source, slug) writers still serialize. runAutoLink has exactly
+ * ONE caller (the put_page handler above) and OperationContext.sourceId is a
+ * REQUIRED string, so sourceId is always present here; the `?? ''` fallback is
+ * belt-and-braces only, never a real key shape.
+ */
+export function autoLinkLockKey(sourceId: string | undefined, slug: string): string {
+ return `auto_link:${sourceId ?? ''}:${slug}`;
+}
+
/**
* Extract entity refs from a freshly-written page, sync the links table to match.
* Creates new links via addLink, removes stale ones (links present in DB but no
@@ -576,9 +593,10 @@ async function runAutoLink(
// v0.31.8 (codex OV-2): thread sourceId through every read + write inside
// reconcileLinks. Without this the FS walker reads cross-source links/slugs
// but writes scoped to one source — phantom stale-deletions and duplicate
- // inserts. opts.sourceId is set when caller knows the source (put_page from
- // a multi-source-aware handler); when omitted, every read returns the
- // pre-v0.31.8 cross-source view (back-compat for any existing caller).
+ // inserts. runAutoLink has exactly ONE caller (the put_page handler) and
+ // ctx.sourceId is a REQUIRED string there, so opts.sourceId is always set in
+ // practice; the omitted-opts branches below (and the `?? ''` in
+ // autoLinkLockKey) are belt-and-braces only, not a live back-compat path.
const sourceOpts = opts?.sourceId ? { sourceId: opts.sourceId } : {};
const linkSourceOpts = opts?.sourceId
? { fromSourceId: opts.sourceId, toSourceId: opts.sourceId, originSourceId: opts.sourceId }
@@ -634,7 +652,12 @@ async function runAutoLink(
// single-process so there's no cross-process concern there anyway).
const result = await engine.transaction(async (tx) => {
try {
- await tx.executeRaw(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [`auto_link:${slug}`]);
+ // hashtext (not hashtextextended): this call must behave identically on
+ // BOTH engines and any failure here is SILENTLY swallowed by the catch
+ // below — a primitive that errored on either engine would quietly drop
+ // the lock entirely. hashtext is the primitive every advisory-lock site
+ // in this repo already proves on both engines; keep the family uniform.
+ await tx.executeRaw(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [autoLinkLockKey(opts?.sourceId, slug)]);
} catch {
// engine doesn't support advisory locks — fall through
}
diff --git a/src/core/output/writer.ts b/src/core/output/writer.ts
index d96ed8ab7a..f3db30d93d 100644
--- a/src/core/output/writer.ts
+++ b/src/core/output/writer.ts
@@ -130,6 +130,19 @@ export interface WriteTx {
readonly context: ResolverContext;
}
+/**
+ * Advisory-lock key for the createEntity slug-claim critical section.
+ * Source-scoped (PR6 D5): slug uniqueness is (source_id, slug), so two
+ * writers claiming the same desiredSlug in DIFFERENT sources are not in
+ * conflict — a shared per-slug key serialized them for nothing, while
+ * same-(source, slug) claimants still serialize. `?? 'default'` mirrors
+ * engine.putPage's implicit default source (WriteTxImpl.scope()), so the
+ * lock key names the exact source the paired putPage will land in.
+ */
+export function slugRegistryLockKey(sourceId: string | undefined, slug: string): string {
+ return `slug_registry:${sourceId ?? 'default'}:${slug}`;
+}
+
class WriteTxImpl implements WriteTx {
readonly touchedSlugs = new Set<string>();
private slugRegistry: SlugRegistry;
@@ -152,14 +165,32 @@ class WriteTxImpl implements WriteTx {
throw new WriteError('invalid_input', 'createEntity requires desiredSlug, displayName, and type');
}
// Cross-process TOCTOU guard: take a transaction-scoped advisory lock
- // keyed on the desired slug prefix so two putPage('people/alice') calls
+ // keyed on (source, desired slug) so two putPage('people/alice') calls
// from separate processes serialize at the DB level. The second caller's
// slugRegistry.create() then observes the first's write and disambiguates.
// PGLite is single-process so this is a harmless no-op there.
+ //
+ // TX SCOPE (PR6 D5 — why there is no `engine.transaction` wrap here):
+ // WriteTxImpl is constructed in exactly one place — inside
+ // BrainWriter.transaction's `engine.transaction(async (txEngine) => ...)`
+ // — and `this.engine` IS that txEngine (its `sql`/`db` route to the tx
+ // connection on both engines). So this xact lock is ALREADY taken inside
+ // the one wrapping transaction and is held across slugRegistry.create's
+ // existence probes AND the putPage below, until the outer commit — the
+ // full TOCTOU window. Adding another engine.transaction here would NEST,
+ // which throws on both engines (postgres tx clones have no `.begin`;
+ // PGLite tx proxies have no `.transaction`). Pinned by
+ // test/lock-keys.test.ts (single-transaction routing proof).
+ //
+ // hashtext (not hashtextextended): must behave identically on BOTH
+ // engines and any failure is SILENTLY swallowed by the catch below — an
+ // erroring primitive would quietly drop the lock. hashtext is the
+ // primitive every advisory-lock site in this repo already proves on both
+ // engines; keep the family uniform.
try {
await this.engine.executeRaw(
`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`,
- [input.desiredSlug],
+ [slugRegistryLockKey(this.sourceId, input.desiredSlug)],
);
} catch {
// Some engines/test doubles may not support advisory locks. Fall
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index d2f00587c8..d38e158e7c 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -4808,7 +4808,7 @@ export class PGLiteEngine implements BrainEngine {
async listSupersessions(
source_id: string,
- opts?: { since?: Date; limit?: number },
+ opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[] },
): Promise<FactRow[]> {
return factsImpl.listSupersessions(this.factsDeps, source_id, opts);
}
diff --git a/src/core/pglite-engine/facts.ts b/src/core/pglite-engine/facts.ts
index ffa9f2f72f..bb8bae19ff 100644
--- a/src/core/pglite-engine/facts.ts
+++ b/src/core/pglite-engine/facts.ts
@@ -292,7 +292,7 @@ export async function listFactsBySession(
export async function listSupersessions(
deps: PgliteFactsDeps,
source_id: string,
- opts?: { since?: Date; limit?: number },
+ opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[] },
): Promise<FactRow[]> {
const where: string[] = [`expired_at IS NOT NULL`, `superseded_by IS NOT NULL`];
const params: Record<string, unknown> = {};
@@ -303,6 +303,7 @@ export async function listSupersessions(
return _listFacts(deps, source_id, {
activeOnly: false,
limit: opts?.limit,
+ visibility: opts?.visibility,
whereClauses: where,
whereParams: params,
order: 'expired_at DESC, id DESC',
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 5a9d84a289..db9039aed6 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -440,6 +440,7 @@ export class PostgresEngine implements BrainEngine {
op: 'acquire',
caller: 'PostgresEngine.initSchema',
});
+ // Lock-census (PR6 D5): INTENTIONALLY brain-global (session lock, fixed key 42) — initSchema DDL mutates the whole database; a per-source key would let two initSchema calls deadlock on shared DDL.
await conn`SELECT pg_advisory_lock(42)`;
try {
// Pre-schema bootstrap: add forward-referenced state the embedded schema
@@ -4717,7 +4718,7 @@ export class PostgresEngine implements BrainEngine {
async listSupersessions(
source_id: string,
- opts?: { since?: Date; limit?: number },
+ opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[] },
): Promise<FactRow[]> {
return factsImpl.listSupersessions(this.factsDeps, source_id, opts);
}
diff --git a/src/core/postgres-engine/facts.ts b/src/core/postgres-engine/facts.ts
index 70c63cf377..24016bfc62 100644
--- a/src/core/postgres-engine/facts.ts
+++ b/src/core/postgres-engine/facts.ts
@@ -57,6 +57,7 @@ export async function insertFact(
const supersedeId = ctx.supersedeId;
const newId = await sql.begin(async (tx) => {
if (entitySlug) {
+ // Lock-census (PR6 D5): COMPLIANT — key is already source-scoped (source_id || ':' || entity_slug).
await tx`SELECT pg_advisory_xact_lock(hashtextextended(${ctx.source_id} || ':' || ${entitySlug}, 0))`;
}
const ins = await tx<Array<{ id: number }>>`
@@ -83,6 +84,7 @@ export async function insertFact(
// Plain insert path with optional advisory lock for the dedup window.
const id = await sql.begin(async (tx) => {
if (entitySlug) {
+ // Lock-census (PR6 D5): COMPLIANT — key is already source-scoped (source_id || ':' || entity_slug).
await tx`SELECT pg_advisory_xact_lock(hashtextextended(${ctx.source_id} || ':' || ${entitySlug}, 0))`;
}
const ins = await tx<Array<{ id: number }>>`
@@ -297,17 +299,19 @@ export async function listFactsBySession(
export async function listSupersessions(
deps: PgFactsDeps,
source_id: string,
- opts?: { since?: Date; limit?: number },
+ opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[] },
): Promise<FactRow[]> {
const sql = deps.sql;
const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
const since = opts?.since ?? null;
+ const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;
const rows = await sql<FactRowSqlShape[]>`
SELECT * FROM facts
WHERE source_id = ${source_id}
AND expired_at IS NOT NULL
AND superseded_by IS NOT NULL
${since ? sql`AND expired_at >= ${since}` : sql``}
+ ${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}
ORDER BY expired_at DESC, id DESC
LIMIT ${limit}
`;
diff --git a/src/core/surface-audit.ts b/src/core/surface-audit.ts
index 7c7f14f311..831f9ec5a6 100644
--- a/src/core/surface-audit.ts
+++ b/src/core/surface-audit.ts
@@ -33,7 +33,7 @@ export interface SurfaceChangeAudit {
old: string | null;
/** New row value (null = cleared). */
new: string | null;
- via: 'rescope_cli' | 'admin_api' | 'request_tools';
+ via: 'rescope_cli' | 'admin_api' | 'request_tools' | 'register_cli';
}
/** Returns true when the audit row landed; false (after a stderr warn) otherwise. */
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index adaeca4c2c..87df993fa4 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.46.12.3 -->
+<!-- gbrain-template-stamp: 0.46.13.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/agent-cli.test.ts b/test/agent-cli.test.ts
index fdb71922e8..aeb0238b60 100644
--- a/test/agent-cli.test.ts
+++ b/test/agent-cli.test.ts
@@ -520,3 +520,56 @@ describe('fan-out manifest shape (integration)', () => {
}
});
});
+
+describe('dispatcher routes register (cathedral-6)', () => {
+ test('runAgent dispatches register and its --help never touches the engine', async () => {
+ const { runAgent } = await import('../src/commands/agent.ts');
+ // engine=null: the SELF_HELP_WITHOUT_ENGINE lane. Help must print and return.
+ const logs: string[] = [];
+ const orig = console.log;
+ console.log = (...a: unknown[]) => { logs.push(a.join(' ')); };
+ try {
+ await runAgent(null, ['register', '--help']);
+ } finally {
+ console.log = orig;
+ }
+ const out = logs.join('\n');
+ expect(out).toContain('gbrain agent register');
+ expect(out).toContain('--preset daily-driver|coding-agent');
+ });
+
+ test('top-level help mentions register', async () => {
+ const { runAgent } = await import('../src/commands/agent.ts');
+ const logs: string[] = [];
+ const orig = console.log;
+ console.log = (...a: unknown[]) => { logs.push(a.join(' ')); };
+ try {
+ await runAgent(null, ['--help']);
+ } finally {
+ console.log = orig;
+ }
+ expect(logs.join('\n')).toContain('agent register');
+ });
+
+ test('`agent run -- --help` is NOT a help request (-- terminator honored)', async () => {
+ const { runAgent } = await import('../src/commands/agent.ts');
+ // With a null engine and a post-`--` --help, the dispatcher must treat it
+ // as a REAL run (and refuse on the missing engine) — never print help.
+ const errs: string[] = [];
+ const origErr = console.error;
+ const origExit = process.exit;
+ let exitCode: number | undefined;
+ console.error = (...a: unknown[]) => { errs.push(a.join(' ')); };
+ (process as any).exit = (code?: number) => { exitCode = code; throw new Error('__exit__'); };
+ try {
+ await runAgent(null, ['run', '--', '--help']).catch((e) => {
+ if (!/__exit__/.test(String(e?.message))) throw e;
+ });
+ } finally {
+ console.error = origErr;
+ (process as any).exit = origExit;
+ }
+ expect(exitCode).toBe(1);
+ expect(errs.join('\n')).toContain('needs a configured brain');
+ });
+});
diff --git a/test/agent-register-guards.serial.test.ts b/test/agent-register-guards.serial.test.ts
new file mode 100644
index 0000000000..13278cfcc2
--- /dev/null
+++ b/test/agent-register-guards.serial.test.ts
@@ -0,0 +1,151 @@
+/**
+ * cathedral-6: the cli.ts PRE-CONNECT guard for `agent register` — a thin
+ * client must be refused BEFORE connectEngine (which would otherwise build a
+ * scratch PGLite and mint dead credentials into it). Subprocess-level so the
+ * guard is exercised where it lives (handleCliOnly, before any engine work):
+ * no database exists in the spawned HOME, so reaching the refusal at all
+ * proves the guard fires pre-connect.
+ */
+import { describe, test, expect } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const REPO = join(import.meta.dir, '..');
+
+describe('agent register pre-connect guards (cli.ts)', () => {
+ test('thin client is refused with a structured JSON failure before any engine work', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-thin-'));
+ const dir = join(home, '.gbrain');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'config.json'), JSON.stringify({
+ remote_mcp: {
+ issuer_url: 'https://brain.example.com',
+ mcp_url: 'https://brain.example.com/mcp',
+ oauth_client_id: 'gbrain_cl_thin',
+ },
+ }));
+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home };
+ delete env.GBRAIN_DATABASE_URL;
+ delete env.DATABASE_URL;
+ const proc = Bun.spawn([
+ 'bun', '--no-env-file', 'run', 'src/cli.ts',
+ 'agent', 'register', 'aurora',
+ '--harness', 'codex',
+ '--url', 'https://brain.example.com/mcp',
+ '--json',
+ ], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ ]);
+ const code = await proc.exited;
+ expect(code).toBe(1);
+ // Structured single-document JSON failure on stdout (notes go to stderr).
+ let doc: any;
+ try {
+ doc = JSON.parse(stdout.trim());
+ } catch {
+ throw new Error(`expected a single JSON doc on stdout, got:\n${stdout}\nstderr: ${stderr}`);
+ }
+ expect(doc.ok).toBe(false);
+ expect(doc.reason).toBe('thin_client');
+ expect(doc.message).toContain('HOST brain');
+ }, 30_000);
+});
+
+describe('agent register live-serve + duplicate-name refusals (real PGLite brain)', () => {
+ /** Shared PGLite brain home for both cases: init once, ~seconds. */
+ async function initBrain(): Promise<{ home: string; env: Record<string, string | undefined> }> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-guards-'));
+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home };
+ delete env.GBRAIN_DATABASE_URL;
+ delete env.DATABASE_URL;
+ const init = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', 'init', '--pglite'], {
+ cwd: REPO, env, stdout: 'pipe', stderr: 'pipe', stdin: 'ignore',
+ });
+ const initOut = await new Response(init.stdout).text();
+ const initErr = await new Response(init.stderr).text();
+ const code = await init.exited;
+ if (code !== 0) throw new Error(`init --pglite failed (${code}):\n${initOut}\n${initErr}`);
+ return { home, env };
+ }
+
+ // No explicit return annotation: `ReturnType<typeof Bun.spawn>` resolves the
+ // generic's DEFAULT io types (stdout: number | ReadableStream | undefined);
+ // inference from the literal options gives the precise piped Subprocess.
+ function register(env: Record<string, string | undefined>, extra: string[] = []) {
+ return Bun.spawn([
+ 'bun', '--no-env-file', 'run', 'src/cli.ts',
+ 'agent', 'register', 'aurora-guard',
+ '--harness', 'codex', '--url', 'http://localhost:19139/mcp', '--json',
+ ...extra,
+ ], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });
+ }
+
+ test('duplicate name is refused with the existing client id + reissue hint; pglite live serve is refused pre-connect', async () => {
+ const { home, env } = await initBrain();
+
+ // First register succeeds (probe against the dead 19139 port is a note, not a failure).
+ const first = register(env);
+ const firstOut = await new Response(first.stdout).text();
+ const firstErr = await new Response(first.stderr).text();
+ expect(await first.exited).toBe(0);
+ let firstDoc: any;
+ try { firstDoc = JSON.parse(firstOut.trim()); } catch {
+ throw new Error(`first register: expected JSON stdout, got:\n${firstOut}\nstderr: ${firstErr}`);
+ }
+ expect(firstDoc.ok).toBe(true);
+ expect(firstDoc.client_id).toMatch(/^gbrain_cl_/);
+
+ // Second register with the SAME name → duplicate_name envelope, exit 1,
+ // message carries the existing client id + the --reissue hint.
+ const dup = register(env);
+ const dupOut = await new Response(dup.stdout).text();
+ expect(await dup.exited).toBe(1);
+ const dupDoc = JSON.parse(dupOut.trim());
+ expect(dupDoc.ok).toBe(false);
+ expect(dupDoc.reason).toBe('duplicate_name');
+ expect(dupDoc.message).toContain(firstDoc.client_id);
+ expect(dupDoc.message).toContain('--reissue');
+
+ // Live PGLite serve: spawn `gbrain serve` (stdio) so it takes the
+ // single-writer lock, then register must refuse PRE-connect with the
+ // typed pglite_live_serve reason (never a 30s lock hang — enforce with
+ // a wall-clock ceiling well under the lock timeout).
+ const serve = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', 'serve'], {
+ cwd: REPO, env, stdout: 'pipe', stderr: 'pipe', stdin: 'pipe',
+ });
+ try {
+ // Wait for the serve to hold the lock (lock file appears).
+ const lockPath = join(home, '.gbrain', 'brain.pglite', '.gbrain-lock', 'lock');
+ const { existsSync, readFileSync } = await import('node:fs');
+ const deadline = Date.now() + 20_000;
+ let holds = false;
+ while (Date.now() < deadline) {
+ try {
+ const raw = JSON.parse(readFileSync(lockPath, 'utf8'));
+ if (raw?.pid && (raw.subcommand === 'serve' || String(raw.command ?? '').includes('serve'))) { holds = true; break; }
+ } catch { /* not yet */ }
+ await new Promise(r => setTimeout(r, 250));
+ if (!existsSync(lockPath)) continue;
+ }
+ expect(holds).toBe(true);
+
+ const started = Date.now();
+ const blocked = register(env, []);
+ const blockedOut = await new Response(blocked.stdout).text();
+ expect(await blocked.exited).toBe(1);
+ const elapsed = Date.now() - started;
+ const blockedDoc = JSON.parse(blockedOut.trim());
+ expect(blockedDoc.ok).toBe(false);
+ expect(blockedDoc.reason).toBe('pglite_live_serve');
+ expect(blockedDoc.message).toContain('stop the serve');
+ // Pre-connect means no single-writer 30s spin: generous CI ceiling.
+ expect(elapsed).toBeLessThan(15_000);
+ } finally {
+ serve.kill('SIGTERM');
+ await serve.exited;
+ }
+ }, 120_000);
+});
diff --git a/test/agent-register.test.ts b/test/agent-register.test.ts
new file mode 100644
index 0000000000..88ac4a6c01
--- /dev/null
+++ b/test/agent-register.test.ts
@@ -0,0 +1,464 @@
+/**
+ * gbrain agent register (cathedral-6) — parser, presets, guards, and the
+ * PGLite end-to-end integration (pre-flight → one tx → post-commit audit →
+ * exchange → verify round-trip).
+ *
+ * The 3600s-default regression pin lives here: register ALWAYS writes
+ * oauth_clients.token_ttl (default 30d) because the server default for
+ * CLI-minted access tokens is one hour.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { writeSurfaceChangeAudit } from '../src/core/surface-audit.ts';
+import {
+ parseAgentRegisterArgs,
+ resolvePreset,
+ rotateClientSecret,
+ ensureWorkspaceSource,
+ snapshotGrantSources,
+ RegisterError,
+ REGISTER_DEFAULT_TOKEN_TTL_SECONDS,
+ WORKSPACE_NAME_MAX,
+} from '../src/commands/agent-register.ts';
+import {
+ registerScopedClient,
+ preflightOauthClientColumns,
+ type RegisterClientArgs,
+} from '../src/commands/auth.ts';
+
+function baseRegisterArgs(over: Partial<RegisterClientArgs> = {}): RegisterClientArgs {
+ return {
+ grantTypes: ['client_credentials'],
+ scopes: 'read write',
+ sourceId: 'default',
+ federatedRead: undefined,
+ redirectUris: [],
+ tokenEndpointAuthMethod: undefined,
+ boundTools: undefined,
+ boundSourceId: undefined,
+ boundBrainId: undefined,
+ boundSlugPrefixes: undefined,
+ boundMaxConcurrent: undefined,
+ budgetUsdPerDay: undefined,
+ tokenTtlSeconds: undefined,
+ ...over,
+ };
+}
+
+// ── parser (pure) ─────────────────────────────────────────────────────────
+
+describe('parseAgentRegisterArgs', () => {
+ test('happy path parses all flags', () => {
+ const p = parseAgentRegisterArgs([
+ 'aurora-coder', '--harness', 'claude-code', '--preset', 'coding-agent',
+ '--federated-read', 'proj-widget,shared', '--url', 'https://brain.example.com/mcp',
+ '--token-ttl', '86400', '--show-token', '--json',
+ ]);
+ expect(p.name).toBe('aurora-coder');
+ expect(p.harness).toBe('claude-code');
+ expect(p.preset).toBe('coding-agent');
+ expect(p.federatedRead).toEqual(['proj-widget', 'shared']);
+ expect(p.tokenTtlSeconds).toBe(86400);
+ expect(p.showToken).toBe(true);
+ expect(p.json).toBe(true);
+ });
+
+ test('requires --harness and validates its values', () => {
+ expect(() => parseAgentRegisterArgs(['a'])).toThrow(/--harness is required/);
+ expect(() => parseAgentRegisterArgs(['a', '--harness', 'cursor'])).toThrow(/--harness must be one of/);
+ });
+
+ test('requires a name (outside --reissue)', () => {
+ expect(() => parseAgentRegisterArgs(['--harness', 'codex'])).toThrow(/requires a <name>/);
+ });
+
+ test('scope blocklist rejects operator scopes per token', () => {
+ for (const bad of ['admin', 'sources_admin', 'users_admin', 'agent']) {
+ expect(() => parseAgentRegisterArgs(['a', '--harness', 'codex', '--scopes', `read ${bad}`]))
+ .toThrow(/not grantable to an agent client/);
+ }
+ });
+
+ test('unknown scopes still rejected by the shared allowlist', () => {
+ expect(() => parseAgentRegisterArgs(['a', '--harness', 'codex', '--scopes', 'read wrote']))
+ .toThrow();
+ });
+
+ test('rejects the __all__ literal in --federated-read', () => {
+ expect(() => parseAgentRegisterArgs(['a', '--harness', 'codex', '--federated-read', 'default,__all__']))
+ .toThrow(/no wildcard read grant exists/);
+ });
+
+ test('--federated-read dedupes repeated ids, preserving first-seen order', () => {
+ const p = parseAgentRegisterArgs([
+ 'a', '--harness', 'codex', '--federated-read', 'proj-widget,shared,proj-widget,shared',
+ ]);
+ expect(p.federatedRead).toEqual(['proj-widget', 'shared']);
+ });
+
+ test('url|port mutual exclusion; port bounds', () => {
+ expect(() => parseAgentRegisterArgs(['a', '--harness', 'codex', '--url', 'https://x/mcp', '--port', '3131']))
+ .toThrow(/--url OR --port/);
+ expect(() => parseAgentRegisterArgs(['a', '--harness', 'codex', '--port', '0'])).toThrow(/--port/);
+ expect(() => parseAgentRegisterArgs(['a', '--harness', 'codex', '--port', '70000'])).toThrow(/--port/);
+ });
+
+ test.each([['0'], ['-1'], ['abc'], ['10000000']])('rejects --token-ttl %s', (raw) => {
+ expect(() => parseAgentRegisterArgs(['a', '--harness', 'codex', '--token-ttl', raw]))
+ .toThrow(/between 60 and 7776000/);
+ });
+
+ test('name validation: shell-unsafe or uppercase names refused', () => {
+ expect(() => parseAgentRegisterArgs(['Bad Name', '--harness', 'codex'])).toThrow(/invalid name/);
+ expect(() => parseAgentRegisterArgs(['UPPER', '--harness', 'codex'])).toThrow(/invalid name/);
+ });
+
+ test('--reissue grammar: no name, no scope flags', () => {
+ const p = parseAgentRegisterArgs(['--reissue', 'gbrain_cl_x', '--harness', 'codex']);
+ expect(p.reissueClientId).toBe('gbrain_cl_x');
+ expect(() => parseAgentRegisterArgs(['name', '--reissue', 'gbrain_cl_x', '--harness', 'codex']))
+ .toThrow(/client-id, not a name/);
+ expect(() => parseAgentRegisterArgs(['--reissue', 'gbrain_cl_x', '--harness', 'codex', '--scopes', 'read']))
+ .toThrow(/scope flags are not allowed/);
+ });
+
+ test('unknown flag throws', () => {
+ expect(() => parseAgentRegisterArgs(['a', '--harness', 'codex', '--frobnicate'])).toThrow(/Unknown flag/);
+ });
+
+ test('--allow-old-serve parses (default false)', () => {
+ expect(parseAgentRegisterArgs(['a', '--harness', 'codex']).allowOldServe).toBe(false);
+ expect(parseAgentRegisterArgs(['a', '--harness', 'codex', '--allow-old-serve']).allowOldServe).toBe(true);
+ // Boolean flag: it must not eat a following positional.
+ const p = parseAgentRegisterArgs(['a', '--allow-old-serve', '--harness', 'codex']);
+ expect(p.allowOldServe).toBe(true);
+ expect(p.name).toBe('a');
+ expect(p.harness).toBe('codex');
+ });
+});
+
+// ── snapshot grant (daily-driver) — workspace exclusion ───────────────────
+
+describe('snapshotGrantSources', () => {
+ test('excludes *-workspace sources from the snapshot grant, keeps the rest', () => {
+ const r = snapshotGrantSources(['default', 'proj-widget', 'x-workspace', 'nova-notes', 'aurora-coder-workspace']);
+ expect(r.granted).toEqual(['default', 'proj-widget', 'nova-notes']);
+ expect(r.excludedWorkspaces).toEqual(['x-workspace', 'aurora-coder-workspace']);
+ });
+
+ test('no workspaces → nothing excluded', () => {
+ const r = snapshotGrantSources(['default', 'proj-widget']);
+ expect(r.granted).toEqual(['default', 'proj-widget']);
+ expect(r.excludedWorkspaces).toEqual([]);
+ });
+
+ test('an EXPLICIT --federated-read grant of a workspace bypasses the snapshot (no filtering)', () => {
+ // The exclusion lives in the snapshot branch only: an explicit grant
+ // resolves through preset.federatedRead = flags.federatedRead verbatim.
+ const flags = { showToken: false, json: false, allowOldServe: false, name: 'aurora', harness: 'claude-code' } as any;
+ const r = resolvePreset({ ...flags, preset: 'daily-driver', federatedRead: ['x-workspace', 'proj-widget'] });
+ expect(r.federatedRead).toEqual(['x-workspace', 'proj-widget']);
+ });
+});
+
+// ── presets (pure) ────────────────────────────────────────────────────────
+
+describe('resolvePreset', () => {
+ const flags = (over: Record<string, unknown>) =>
+ ({ showToken: false, json: false, name: 'aurora', harness: 'claude-code', ...over }) as any;
+
+ test('daily-driver: snapshot grant, default write source, starter surface', () => {
+ const r = resolvePreset(flags({ preset: 'daily-driver' }));
+ expect(r).toEqual({
+ scopes: 'read write',
+ writeSource: 'default',
+ federatedRead: 'snapshot',
+ surface: 'starter',
+ workspaceDerived: false,
+ });
+ });
+
+ test('coding-agent: derived workspace first in the read list, starter surface', () => {
+ const r = resolvePreset(flags({ preset: 'coding-agent', federatedRead: ['proj-widget'] }));
+ expect(r.writeSource).toBe('aurora-workspace');
+ expect(r.workspaceDerived).toBe(true);
+ expect(r.federatedRead).toEqual(['aurora-workspace', 'proj-widget']);
+ expect(r.surface).toBe('starter');
+ });
+
+ test('coding-agent without --federated-read fails loud', () => {
+ expect(() => resolvePreset(flags({ preset: 'coding-agent' }))).toThrow(/requires --federated-read/);
+ });
+
+ test('explicit flags beat preset', () => {
+ const r = resolvePreset(flags({
+ preset: 'coding-agent', federatedRead: ['proj-widget'],
+ source: 'shared', scopes: 'read', surface: 'full',
+ }));
+ expect(r.writeSource).toBe('shared');
+ expect(r.workspaceDerived).toBe(false);
+ expect(r.scopes).toBe('read');
+ expect(r.surface).toBe('full');
+ });
+
+ test(`workspace derivation: ${WORKSPACE_NAME_MAX}-char name ok, ${WORKSPACE_NAME_MAX + 1} refused with guidance`, () => {
+ const ok = 'a'.repeat(WORKSPACE_NAME_MAX);
+ const long = 'a'.repeat(WORKSPACE_NAME_MAX + 1);
+ expect(resolvePreset(flags({ name: ok, preset: 'coding-agent', federatedRead: ['x'] })).writeSource)
+ .toBe(`${ok}-workspace`);
+ expect(() => resolvePreset(flags({ name: long, preset: 'coding-agent', federatedRead: ['x'] })))
+ .toThrow(/Pass --source <id> or shorten the name/);
+ expect(() => resolvePreset(flags({ name: 'a'.repeat(33), preset: 'coding-agent', federatedRead: ['x'] })))
+ .toThrow(/shorten the name/);
+ });
+
+ test('underscore names cannot derive a workspace (SOURCE_ID_RE)', () => {
+ expect(() => resolvePreset(flags({ name: 'my_agent', preset: 'coding-agent', federatedRead: ['x'] })))
+ .toThrow(/Pass --source/);
+ });
+
+ test('no preset: passthrough defaults matching auth register-client, no surface', () => {
+ const r = resolvePreset(flags({}));
+ expect(r).toEqual({
+ scopes: 'read write',
+ writeSource: 'default',
+ federatedRead: ['default'],
+ surface: undefined,
+ workspaceDerived: false,
+ });
+ });
+});
+
+// ── structural guards (the PGLite self-deadlock class) ───────────────────
+
+describe('structural guards', () => {
+ const src = fs.readFileSync(path.join(import.meta.dir, '../src/commands/agent-register.ts'), 'utf8');
+
+ test('agent-register never acquires its own engine (withConfiguredSql / .connect are banned)', () => {
+ expect(src).not.toMatch(/withConfiguredSql/);
+ expect(src).not.toMatch(/\.connect\(/);
+ expect(src).not.toMatch(/createEngine\(/);
+ });
+
+ test('registerScopedClient core is print-free and exit-free', () => {
+ const auth = fs.readFileSync(path.join(import.meta.dir, '../src/commands/auth.ts'), 'utf8');
+ const coreStart = auth.indexOf('export async function registerScopedClient');
+ const coreEnd = auth.indexOf('export function formatRegisterClientOutput');
+ const core = auth.slice(coreStart, coreEnd);
+ expect(coreStart).toBeGreaterThan(0);
+ // Call sites only — prose in neighboring docblocks may NAME console.log.
+ expect(core).not.toMatch(/console\.\w+\s*\(/);
+ expect(core).not.toMatch(/process\.exit\s*\(/);
+ });
+});
+
+// ── PGLite integration ────────────────────────────────────────────────────
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM oauth_tokens');
+ await engine.executeRaw('DELETE FROM oauth_clients');
+});
+
+describe('PGLite integration (pre-flight → tx → audit → exchange)', () => {
+ test('end-to-end: row, ttl, surface via rescope, audit row, verify round-trip', async () => {
+ const sql = sqlQueryForEngine(engine);
+ const columns = await preflightOauthClientColumns(sql);
+ expect(columns.has('token_ttl')).toBe(true);
+ expect(columns.has('surface')).toBe(true);
+ expect(columns.has('deleted_at')).toBe(true);
+
+ let registered!: Awaited<ReturnType<typeof registerScopedClient>>;
+ await engine.transaction(async (tx) => {
+ const txSql = sqlQueryForEngine(tx);
+ registered = await registerScopedClient(txSql, 'itest-agent', baseRegisterArgs({
+ sourceId: 'default',
+ federatedRead: ['default'],
+ }), {
+ tokenTtlSeconds: REGISTER_DEFAULT_TOKEN_TTL_SECONDS,
+ surface: 'starter',
+ columns,
+ });
+ });
+
+ expect(registered.tokenTtl).toBe(REGISTER_DEFAULT_TOKEN_TTL_SECONDS);
+ expect(registered.surface).toBe('starter');
+ expect(registered.clientSecret).toMatch(/^gbrain_cs_/);
+
+ // Row state: ttl written, surface set through the audited writer path
+ // (surface_set_by='operator' — the request_tools lock).
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT token_ttl, surface, surface_set_by FROM oauth_clients WHERE client_id = $1`,
+ [registered.clientId],
+ );
+ expect(rows[0].token_ttl).toBe(REGISTER_DEFAULT_TOKEN_TTL_SECONDS);
+ expect(rows[0].surface).toBe('starter');
+ expect(rows[0].surface_set_by).toBe('operator');
+
+ // Post-commit fail-open audit (designed position — never inside the tx).
+ const audited = await writeSurfaceChangeAudit(engine, {
+ actor: 'operator',
+ client_id: registered.clientId,
+ old: registered.surfaceOld ?? null,
+ new: 'starter',
+ via: 'register_cli',
+ });
+ expect(audited).toBe(true);
+ const auditRows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT operation FROM mcp_request_log WHERE operation = 'surface_change'`,
+ );
+ expect(auditRows.length).toBe(1);
+
+ // Exchange on the OUTER engine (tx sql is dead after commit) — the
+ // 3600s-default regression pin: expires_in must reflect the 30d column.
+ const provider = new GBrainOAuthProvider({ sql });
+ const tokens = await provider.exchangeClientCredentials(registered.clientId, registered.clientSecret!);
+ expect(tokens.expires_in).toBe(REGISTER_DEFAULT_TOKEN_TTL_SECONDS);
+
+ const auth = await provider.verifyAccessToken(tokens.access_token);
+ expect((auth as any).sourceId).toBe('default');
+ expect((auth as any).allowedSources).toEqual(['default']);
+ });
+
+ test('42703 degrade path: missing columns are skipped OUTSIDE the tx, register still lands', async () => {
+ const sql = sqlQueryForEngine(engine);
+ // Simulate a pre-migration brain: a column set that lacks token_ttl+surface.
+ const columns = new Set(['source_id', 'federated_read', 'deleted_at']);
+ let registered!: Awaited<ReturnType<typeof registerScopedClient>>;
+ await engine.transaction(async (tx) => {
+ const txSql = sqlQueryForEngine(tx);
+ registered = await registerScopedClient(txSql, 'itest-degrade', baseRegisterArgs(), {
+ tokenTtlSeconds: REGISTER_DEFAULT_TOKEN_TTL_SECONDS,
+ surface: 'starter',
+ columns,
+ });
+ });
+ expect(registered.skipped).toEqual({ tokenTtl: true, surface: true });
+ expect(registered.tokenTtl).toBeUndefined();
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT client_id, token_ttl FROM oauth_clients WHERE client_id = $1`,
+ [registered.clientId],
+ );
+ expect(rows.length).toBe(1);
+ expect(rows[0].token_ttl).toBeNull();
+ });
+
+ test('reissue: rotation invalidates the old secret, keeps one row, new secret works', async () => {
+ const sql = sqlQueryForEngine(engine);
+ let registered!: Awaited<ReturnType<typeof registerScopedClient>>;
+ await engine.transaction(async (tx) => {
+ registered = await registerScopedClient(sqlQueryForEngine(tx), 'itest-rotate', baseRegisterArgs(), {});
+ });
+ const oldSecret = registered.clientSecret!;
+ const provider = new GBrainOAuthProvider({ sql });
+ await provider.exchangeClientCredentials(registered.clientId, oldSecret); // sanity: works pre-rotation
+
+ const newSecret = await rotateClientSecret(engine, registered.clientId, 'itest-rotate');
+ expect(newSecret).toMatch(/^gbrain_cs_/);
+ expect(newSecret).not.toBe(oldSecret);
+
+ await expect(provider.exchangeClientCredentials(registered.clientId, oldSecret)).rejects.toThrow();
+ const tokens = await provider.exchangeClientCredentials(registered.clientId, newSecret);
+ expect(tokens.access_token).toBeTruthy();
+
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT count(*) AS n FROM oauth_clients WHERE client_name = $1`, ['itest-rotate'],
+ );
+ expect(Number(rows[0].n)).toBe(1);
+ });
+});
+
+// ── ensureWorkspaceSource (create-or-clean-reuse, refuse dirty/archived) ──
+
+describe('ensureWorkspaceSource', () => {
+ const sql = () => sqlQueryForEngine(engine);
+
+ test('creates the source when missing (returns true)', async () => {
+ const created = await ensureWorkspaceSource(engine, sql(), 'ews-new-workspace');
+ expect(created).toBe(true);
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources WHERE id = $1`, ['ews-new-workspace'],
+ );
+ expect(rows.length).toBe(1);
+ });
+
+ test('reuses an existing CLEAN source (returns false)', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('ews-clean-workspace', 'ews-clean-workspace')`,
+ );
+ const created = await ensureWorkspaceSource(engine, sql(), 'ews-clean-workspace');
+ expect(created).toBe(false);
+ });
+
+ test('archived-but-empty workspace is refused with an unarchive hint (never silently reused)', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, archived) VALUES ('ews-archived-workspace', 'ews-archived-workspace', true)`,
+ );
+ const caught = await ensureWorkspaceSource(engine, sql(), 'ews-archived-workspace')
+ .then(() => null, (e: unknown) => e);
+ expect(caught).toBeInstanceOf(RegisterError);
+ expect((caught as RegisterError).reason).toBe('archived_source');
+ expect((caught as Error).message).toMatch(/exists but is archived — unarchive it/);
+ });
+
+ test('source holding pages is dirty', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('ews-pages-workspace', 'ews-pages-workspace')`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO pages (source_id, slug, type, title) VALUES ('ews-pages-workspace', 'ews/p1', 'note', 'p1')`,
+ );
+ await expect(ensureWorkspaceSource(engine, sql(), 'ews-pages-workspace'))
+ .rejects.toThrow(/holds 1 pages/);
+ });
+
+ test('source holding FACTS (zero pages) is dirty too — the primary agent write lane', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('ews-facts-workspace', 'ews-facts-workspace')`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, fact, source) VALUES ('ews-facts-workspace', 'agent memory row', 'test')`,
+ );
+ const caught = await ensureWorkspaceSource(engine, sql(), 'ews-facts-workspace')
+ .then(() => null, (e: unknown) => e);
+ expect((caught as RegisterError).reason).toBe('dirty_source');
+ expect((caught as Error).message).toMatch(/holds 1 facts/);
+ });
+
+ test('source backed by a local path is dirty', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path) VALUES ('ews-path-workspace', 'ews-path-workspace', '/tmp/x')`,
+ );
+ await expect(ensureWorkspaceSource(engine, sql(), 'ews-path-workspace'))
+ .rejects.toThrow(/backed by a local path/);
+ });
+
+ test('source holding FILES (zero pages, zero facts) is dirty too — files can exist page-less', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('ews-files-workspace', 'ews-files-workspace')`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO files (source_id, filename, storage_path, content_hash)
+ VALUES ('ews-files-workspace', 'notes.pdf', 'files/notes.pdf', 'deadbeef')`,
+ );
+ const caught = await ensureWorkspaceSource(engine, sql(), 'ews-files-workspace')
+ .then(() => null, (e: unknown) => e);
+ expect((caught as RegisterError).reason).toBe('dirty_source');
+ expect((caught as Error).message).toMatch(/holds 1 files/);
+ });
+});
diff --git a/test/auth-create-args.test.ts b/test/auth-create-args.test.ts
index baa27af196..3210a22c15 100644
--- a/test/auth-create-args.test.ts
+++ b/test/auth-create-args.test.ts
@@ -1,5 +1,6 @@
-import { test, expect, describe } from 'bun:test';
-import { parseAuthCreateArgs, parseAuthClientsArgs, parseRescopeSurfaceValue, renderTokenScopes } from '../src/commands/auth.ts';
+import { test, expect, describe, beforeAll, afterAll } from 'bun:test';
+import { parseAuthCreateArgs, parseAuthClientsArgs, parseRescopeSurfaceValue, renderTokenScopes, listClientRows } from '../src/commands/auth.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
describe('parseAuthCreateArgs', () => {
test('bare name (no flag) resolves the name — regression for the dropped-name bug', () => {
@@ -132,3 +133,41 @@ describe('parseAuthClientsArgs (E4)', () => {
expect(() => parseAuthClientsArgs(['--nope'])).toThrow(/Unknown flag/);
});
});
+
+// cathedral-6: `auth clients` projection widen — source_id + federated_read
+// ride the same SELECT (zero extra round trips) with a degrade ladder for
+// pre-migration brains. PGLite-backed: proves the full-shape query is valid
+// SQL on a current schema and the row shape carries the new columns.
+describe('listClientRows (projection widen)', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ test('full-shape rows carry scope, surface, source_id and federated_read', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('proj-widget', 'proj-widget')`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO oauth_clients (client_id, client_name, scope, surface, surface_set_by, source_id, federated_read)
+ VALUES ('c-aurora', 'aurora-coder', 'read write', 'starter', 'operator', 'proj-widget', $1)`,
+ [['proj-widget', 'default']],
+ );
+ const rows = await listClientRows(engine);
+ const aurora = rows.find(r => r.client_id === 'c-aurora');
+ expect(aurora).toBeDefined();
+ expect(aurora!.client_name).toBe('aurora-coder');
+ expect(aurora!.scope).toBe('read write');
+ expect(aurora!.surface).toBe('starter');
+ expect(aurora!.surface_set_by).toBe('operator');
+ expect(aurora!.source_id).toBe('proj-widget');
+ expect(aurora!.federated_read).toEqual(['proj-widget', 'default']);
+ });
+});
diff --git a/test/auth-register-client-args.test.ts b/test/auth-register-client-args.test.ts
index b206fc6d43..1ed95ac19e 100644
--- a/test/auth-register-client-args.test.ts
+++ b/test/auth-register-client-args.test.ts
@@ -267,3 +267,28 @@ describe('parseRegisterClientArgs', () => {
});
});
});
+
+describe('--token-ttl (cathedral-6 T2)', () => {
+ const { TOKEN_TTL_MIN_SECONDS, TOKEN_TTL_MAX_SECONDS } = require('../src/commands/auth.ts');
+
+ test('accepts the bounds and passes the value through', () => {
+ expect(parseRegisterClientArgs(['--token-ttl', String(TOKEN_TTL_MIN_SECONDS)]).tokenTtlSeconds).toBe(60);
+ expect(parseRegisterClientArgs(['--token-ttl', String(TOKEN_TTL_MAX_SECONDS)]).tokenTtlSeconds).toBe(7_776_000);
+ expect(parseRegisterClientArgs(['--token-ttl', '2592000']).tokenTtlSeconds).toBe(2_592_000);
+ });
+
+ test('omitted flag leaves tokenTtlSeconds undefined (server default applies)', () => {
+ expect(parseRegisterClientArgs([]).tokenTtlSeconds).toBeUndefined();
+ });
+
+ test.each([['0'], ['-1'], ['abc'], ['10000000'], ['59'], ['3600.5']])(
+ 'rejects %s with the range in the message',
+ (raw) => {
+ expect(() => parseRegisterClientArgs(['--token-ttl', raw])).toThrow(/between 60 and 7776000/);
+ },
+ );
+
+ test('requires a value', () => {
+ expect(() => parseRegisterClientArgs(['--token-ttl'])).toThrow(/requires a value/);
+ });
+});
diff --git a/test/auth-register-client-output-pin.test.ts b/test/auth-register-client-output-pin.test.ts
new file mode 100644
index 0000000000..615e94c472
--- /dev/null
+++ b/test/auth-register-client-output-pin.test.ts
@@ -0,0 +1,106 @@
+/**
+ * Output-format pin for `gbrain auth register-client` (cathedral-6 commit 1).
+ *
+ * The printed block is a PRODUCT contract, not just a test convenience:
+ * - src/commands/connect.ts defaultRegisterOAuthClient scrapes
+ * `/Client ID:\s+(\S+)/` and `/Client Secret:\s+(\S+)/` in production.
+ * - test/e2e/serve-http-oauth.test.ts (6 sites) + connect-bearer.test.ts
+ * scrape the same two lines with the gbrain_cl_/gbrain_cs_ prefixes.
+ *
+ * formatRegisterClientOutput is the single producer; this suite pins the
+ * exact bytes so the registerScopedClient peel (and any future refactor)
+ * cannot drift them.
+ */
+import { describe, test, expect } from 'bun:test';
+import {
+ formatRegisterClientOutput,
+ parseRegisterClientArgs,
+ type RegisteredClient,
+} from '../src/commands/auth.ts';
+
+const CONNECT_ID_RE = /Client ID:\s+(\S+)/;
+const CONNECT_SECRET_RE = /Client Secret:\s+(\S+)/;
+const E2E_ID_RE = /Client ID:\s+(gbrain_cl_\S+)/;
+const E2E_SECRET_RE = /Client Secret:\s+(gbrain_cs_\S+)/;
+
+function confidential(): RegisteredClient {
+ return {
+ clientId: 'gbrain_cl_abc123',
+ clientSecret: 'gbrain_cs_secret456',
+ grantTypes: ['client_credentials'],
+ scopes: 'read write',
+ authMethod: 'client_secret_post',
+ redirectUris: [],
+ sourceId: 'default',
+ federatedRead: ['default'],
+ created: { source: false },
+ };
+}
+
+describe('auth register-client output pin (byte-identical product contract)', () => {
+ test('confidential client: exact lines, in order', () => {
+ const parsed = parseRegisterClientArgs(['--scopes', 'read write']);
+ const lines = formatRegisterClientOutput('demo', confidential(), parsed);
+ expect(lines).toEqual([
+ 'OAuth client registered: "demo"\n',
+ ' Client ID: gbrain_cl_abc123',
+ ' Client Secret: gbrain_cs_secret456\n',
+ ' Grant types: client_credentials',
+ ' Scopes: read write',
+ ' Token auth method: client_secret_post',
+ ' Write source: default',
+ ' Federated reads: default',
+ '',
+ 'Save the client secret — it will not be shown again.',
+ 'Revoke with: gbrain auth revoke-client "gbrain_cl_abc123"',
+ ]);
+ });
+
+ test('connect.ts production scraping regexes match the joined output', () => {
+ const parsed = parseRegisterClientArgs([]);
+ const stdout = formatRegisterClientOutput('demo', confidential(), parsed).join('\n');
+ expect(stdout.match(CONNECT_ID_RE)?.[1]).toBe('gbrain_cl_abc123');
+ expect(stdout.match(CONNECT_SECRET_RE)?.[1]).toBe('gbrain_cs_secret456');
+ });
+
+ test('serve-http-oauth e2e prefixed regexes match the joined output', () => {
+ const parsed = parseRegisterClientArgs([]);
+ const stdout = formatRegisterClientOutput('demo', confidential(), parsed).join('\n');
+ expect(stdout.match(E2E_ID_RE)?.[1]).toBe('gbrain_cl_abc123');
+ expect(stdout.match(E2E_SECRET_RE)?.[1]).toBe('gbrain_cs_secret456');
+ });
+
+ test('public client: placeholder secret line keeps the label prefix scrapeable shape', () => {
+ const parsed = parseRegisterClientArgs(['--redirect-uri', 'https://a.example/cb']);
+ const r: RegisteredClient = {
+ ...confidential(),
+ clientSecret: undefined,
+ grantTypes: ['authorization_code', 'refresh_token'],
+ authMethod: 'none',
+ redirectUris: ['https://a.example/cb'],
+ };
+ const lines = formatRegisterClientOutput('pub', r, parsed);
+ expect(lines).toContain(' Client Secret: <public client — none issued>\n');
+ expect(lines).toContain(' Redirect URIs: https://a.example/cb');
+ expect(lines).toContain('Public client (PKCE-only) — no secret needed.');
+ // The e2e "public client" site scrapes ID only — must still match.
+ expect(lines.join('\n').match(E2E_ID_RE)?.[1]).toBe('gbrain_cl_abc123');
+ });
+
+ test('agent-bindings block: all six lines, exact alignment', () => {
+ const parsed = parseRegisterClientArgs([
+ '--bound-tools', 'search,recall',
+ '--bound-source', 'ws',
+ '--bound-slug-prefixes', 'agents/',
+ '--bound-max-concurrent', '2',
+ '--budget-usd-per-day', '1.50',
+ ]);
+ const lines = formatRegisterClientOutput('bound', confidential(), parsed);
+ expect(lines).toContain(' Bound tools: search, recall');
+ expect(lines).toContain(' Bound source: ws');
+ expect(lines).toContain(' Bound brain: <none>');
+ expect(lines).toContain(' Bound slug prefixes: agents/');
+ expect(lines).toContain(' Max concurrency: 2');
+ expect(lines).toContain(' Daily budget USD: 1.50');
+ });
+});
diff --git a/test/cli-help-without-brain.serial.test.ts b/test/cli-help-without-brain.serial.test.ts
index d63c66c30a..010e530247 100644
--- a/test/cli-help-without-brain.serial.test.ts
+++ b/test/cli-help-without-brain.serial.test.ts
@@ -29,6 +29,8 @@ const HELP_WITHOUT_BRAIN = [
'jobs',
// #4152: dream answers --help (and the retriage subverb help) engine-free.
'dream',
+ // cathedral-6: agent answers --help (incl. `register --help`) engine-free.
+ 'agent',
// ZE interim cleanup: the retired ze-switch shim answers --help engine-free
// (truthful sunset copy + the canonical migration command).
'ze-switch',
@@ -78,6 +80,26 @@ async function runHelp(command: string): Promise<{ code: number; out: string }>
}
describe('--help without a configured brain', () => {
+ // cathedral-6: the register SUBCOMMAND help must also answer brainless —
+ // the whole point of the SELF_HELP_WITHOUT_ENGINE entry is that a reader on
+ // a fresh machine can discover the mint flow before they have a brain.
+ test('agent register --help answers with real help', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-nobrain-'));
+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home };
+ delete env.GBRAIN_DATABASE_URL;
+ delete env.DATABASE_URL;
+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', 'agent', 'register', '--help'], {
+ cwd: REPO, env, stdout: 'pipe', stderr: 'pipe',
+ });
+ const [stdout, stderr] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ ]);
+ const code = await proc.exited;
+ expect(code).toBe(0);
+ expect(stdout + stderr).toContain('--preset daily-driver|coding-agent');
+ }, 30_000);
+
for (const command of HELP_WITHOUT_BRAIN) {
test(`${command} --help answers`, async () => {
const { code, out } = await runHelp(command);
diff --git a/test/codex-toml.test.ts b/test/codex-toml.test.ts
index 821a3e37cc..d63933adfa 100644
--- a/test/codex-toml.test.ts
+++ b/test/codex-toml.test.ts
@@ -13,6 +13,7 @@ import { join } from 'node:path';
import {
detectForeignCodexServer,
removeCodexHttpServerBlock,
+ renderCodexHttpServerBlock,
tomlString,
writeCodexHttpServerBlock,
} from '../src/core/bootstrap/codex-toml.ts';
@@ -204,3 +205,41 @@ describe('tomlString', () => {
expect(() => tomlString('a\nb')).toThrow(/control characters/);
});
});
+
+describe('renderCodexHttpServerBlock', () => {
+ const parseToml = (t: string): Record<string, any> =>
+ (Bun as unknown as { TOML: { parse(x: string): unknown } }).TOML.parse(t) as Record<string, any>;
+
+ test('parses back to exactly {bearer_token, url}; contains NO marker lines', () => {
+ const text = renderCodexHttpServerBlock(BLOCK);
+ expect(text).not.toContain(CODEX_TOML_BLOCK_BEGIN);
+ expect(text).not.toContain(CODEX_TOML_BLOCK_END);
+ // markers are full-line comments — a marker-free snippet has no comment lines at all
+ for (const line of text.split('\n')) expect(line.trimStart().startsWith('#')).toBe(false);
+ const ours = parseToml(text).mcp_servers?.[BLOCK.name];
+ expect(Object.keys(ours as object).sort()).toEqual(['bearer_token', 'url']);
+ expect(ours.url).toBe(BLOCK.url);
+ expect(ours.bearer_token).toBe(BLOCK.bearerToken);
+ });
+
+ test('escaped values round-trip through the TOML parser', () => {
+ const gnarly = { name: 'gbrain', url: 'http://127.0.0.1:3131/mcp', bearerToken: 'to"ken\\v2' };
+ const ours = parseToml(renderCodexHttpServerBlock(gnarly)).mcp_servers?.gbrain;
+ expect(ours.bearer_token).toBe('to"ken\\v2');
+ expect(Object.keys(ours as object).sort()).toEqual(['bearer_token', 'url']);
+ });
+
+ test('refuses a non-bare-key name (same assertion as the writer)', () => {
+ expect(() => renderCodexHttpServerBlock({ ...BLOCK, name: 'bad name' })).toThrow(/bare TOML key/);
+ });
+
+ test('refuses control characters in values (writer parity)', () => {
+ expect(() => renderCodexHttpServerBlock({ ...BLOCK, bearerToken: 'a\nb' })).toThrow(/control characters/);
+ });
+
+ test('pasted snippet reads as a FOREIGN table — the managed writer refuses to double-define, never strips it', () => {
+ const path = tmpConfig();
+ writeFileSync(path, `${renderCodexHttpServerBlock(BLOCK)}\n`);
+ expect(() => writeCodexHttpServerBlock(path, BLOCK)).toThrow(/already defined/);
+ });
+});
diff --git a/test/destructive-guard.test.ts b/test/destructive-guard.test.ts
index 76d612cd26..ddf2f28bc7 100644
--- a/test/destructive-guard.test.ts
+++ b/test/destructive-guard.test.ts
@@ -13,7 +13,7 @@
* RLS) are covered separately by E2E tests.
*/
-import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { describe, test, expect, beforeAll, afterAll, spyOn } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import {
assessDestructiveImpact,
@@ -24,6 +24,8 @@ import {
purgeExpiredSources,
formatImpact,
formatSoftDelete,
+ clientsReferencingSource,
+ formatClientReferentsBlock,
SOFT_DELETE_TTL_HOURS,
type DestructiveImpact,
} from '../src/core/destructive-guard.ts';
@@ -113,6 +115,23 @@ describe('assessDestructiveImpact', () => {
expect(a!.pageCount).toBe(2);
expect(b!.pageCount).toBe(5);
});
+
+ test('counts facts — a zero-page fact-holding source is data at risk, not "safe to remove"', async () => {
+ // Revoked-agent-workspace shape: zero pages, facts present (the primary
+ // agent write lane). Pre-fix the preview said "safe to remove" while the
+ // delete would cascade the facts away.
+ await seedSource(engine, 'aim-facts-only', { withPages: 0 });
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, fact, source) VALUES ($1, 'agent memory row', 'test'), ($1, 'second memory row', 'test')`,
+ ['aim-facts-only'],
+ );
+ const impact = await assessDestructiveImpact(engine, 'aim-facts-only');
+ expect(impact!.pageCount).toBe(0);
+ expect(impact!.factCount).toBe(2);
+ expect(impact!.summary).toContain('2 facts');
+ expect(impact!.summary).toContain('permanently delete');
+ expect(impact!.summary).not.toContain('safe to remove');
+ });
});
describe('checkDestructiveConfirmation (gate truth table)', () => {
@@ -163,6 +182,27 @@ describe('checkDestructiveConfirmation (gate truth table)', () => {
expect(msg).not.toBeNull();
expect(msg).toContain('--confirm-destructive');
});
+
+ test('a fact-only source requires --confirm-destructive (facts gate exactly like pages)', () => {
+ const factOnly: DestructiveImpact = {
+ sourceId: 'revoked-agent-workspace',
+ sourceName: 'revoked-agent-workspace',
+ pageCount: 0,
+ chunkCount: 0,
+ embeddingCount: 0,
+ fileCount: 0,
+ factCount: 7,
+ summary: '⚠️ This will permanently delete: 7 facts',
+ };
+ // No flags → blocked; --yes alone → still blocked (mirrors pages).
+ expect(checkDestructiveConfirmation(factOnly, {})).toContain('--confirm-destructive');
+ expect(checkDestructiveConfirmation(factOnly, { yes: true })).toContain('--confirm-destructive');
+ // --confirm-destructive and --dry-run pass.
+ expect(checkDestructiveConfirmation(factOnly, { confirmDestructive: true })).toBeNull();
+ expect(checkDestructiveConfirmation(factOnly, { dryRun: true })).toBeNull();
+ // Hand-built literal WITHOUT factCount stays valid (optional field, ?? 0).
+ expect(checkDestructiveConfirmation({ ...factOnly, factCount: undefined }, { yes: true })).toBeNull();
+ });
});
describe('soft-delete + restore lifecycle (column-based v0.26.5)', () => {
@@ -362,6 +402,238 @@ describe('soft-delete + restore lifecycle (column-based v0.26.5)', () => {
});
});
+// ── PR6 D5b: FK-RESTRICT lifecycle ──────────────────────────
+// oauth_clients.source_id is ON DELETE RESTRICT; the guard must surface the
+// block BEFORE a hard delete instead of letting the raw FK violation escape.
+
+describe('FK-RESTRICT lifecycle (clientsReferencingSource + purge skip)', () => {
+ // Own engine — the soft-delete describe's purge tests mutate every
+ // archived row's expiry; don't cross-pollute.
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = await setupBrain();
+ }, 30000);
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ async function seedClient(
+ clientId: string,
+ sourceId: string | null,
+ opts?: { deleted?: boolean },
+ ): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO oauth_clients (client_id, client_name, source_id, deleted_at)
+ VALUES ($1, $2, $3, ${opts?.deleted ? 'now()' : 'NULL'})
+ ON CONFLICT (client_id) DO NOTHING`,
+ [clientId, `${clientId}-name`, sourceId],
+ );
+ }
+
+ test('clientsReferencingSource returns ALL physical referents (soft-deleted tagged), scoped to the source', async () => {
+ await seedSource(engine, 'fk-ref-a');
+ await seedSource(engine, 'fk-ref-b');
+ await seedClient('cl-live-1', 'fk-ref-a');
+ await seedClient('cl-live-2', 'fk-ref-a');
+ await seedClient('cl-dead', 'fk-ref-a', { deleted: true });
+ await seedClient('cl-other-src', 'fk-ref-b');
+ await seedClient('cl-no-src', null);
+
+ // PHYSICAL semantics: the soft-deleted row still holds the FK, so it is
+ // returned too — tagged deleted:true, never silently dropped.
+ const refs = await clientsReferencingSource(engine, 'fk-ref-a');
+ expect(refs).toEqual([
+ { clientId: 'cl-dead', clientName: 'cl-dead-name', deleted: true },
+ { clientId: 'cl-live-1', clientName: 'cl-live-1-name', deleted: false },
+ { clientId: 'cl-live-2', clientName: 'cl-live-2-name', deleted: false },
+ ]);
+ expect(await clientsReferencingSource(engine, 'fk-ref-none')).toEqual([]);
+ });
+
+ test('a soft-deleted referent alone BLOCKS the remove/purge pre-check with the retained-row guidance', async () => {
+ await seedSource(engine, 'fk-soft-only', { withPages: 1 });
+ await seedClient('cl-soft-only', 'fk-soft-only', { deleted: true });
+
+ // The pre-check truth (sources.ts blocks on referents.length > 0): the
+ // helper must return the soft-deleted row, because the FK ignores
+ // deleted_at and the hard delete WOULD fail at the database.
+ const refs = await clientsReferencingSource(engine, 'fk-soft-only');
+ expect(refs).toEqual([
+ { clientId: 'cl-soft-only', clientName: 'cl-soft-only-name', deleted: true },
+ ]);
+
+ const block = formatClientReferentsBlock('fk-soft-only', refs);
+ expect(block).toContain('Cannot delete source "fk-soft-only"');
+ expect(block).toContain('Revoked-but-retained rows still block the FK');
+ expect(block).toContain('hard-deletes them');
+ expect(block).toContain('gbrain auth revoke-client "cl-soft-only"');
+ // No live rows → no live-revoke section.
+ expect(block).not.toContain('Revoke each live client first');
+ });
+
+ test('assessDestructiveImpact folds the referent count; formatImpact shows it', async () => {
+ await seedSource(engine, 'fk-impact', { withPages: 1 });
+ await seedClient('cl-impact', 'fk-impact');
+
+ const impact = await assessDestructiveImpact(engine, 'fk-impact');
+ expect(impact).not.toBeNull();
+ expect(impact!.oauthClientCount).toBe(1);
+
+ const out = formatImpact(impact!);
+ expect(out).toContain('1 OAuth client(s) reference this source');
+ expect(out).toContain('revoke-client');
+ });
+
+ test('assessDestructiveImpact reports zero referents for an unreferenced source', async () => {
+ await seedSource(engine, 'fk-unref', { withPages: 1 });
+ const impact = await assessDestructiveImpact(engine, 'fk-unref');
+ expect(impact!.oauthClientCount).toBe(0);
+ expect(formatImpact(impact!)).not.toContain('OAuth client');
+ });
+
+ test('purgeExpiredSources purges only the unreferenced expired source and warns naming the skipped id', async () => {
+ await seedSource(engine, 'fk-purge-ref', { withPages: 1 });
+ await seedSource(engine, 'fk-purge-free', { withPages: 1 });
+ await seedClient('cl-purge-ref', 'fk-purge-ref');
+ await softDeleteSource(engine, 'fk-purge-ref');
+ await softDeleteSource(engine, 'fk-purge-free');
+ await engine.executeRaw(
+ `UPDATE sources SET archive_expires_at = now() - INTERVAL '1 hour' WHERE id = ANY($1::text[])`,
+ [['fk-purge-ref', 'fk-purge-free']],
+ );
+
+ const errSpy = spyOn(console, 'error').mockImplementation(() => {});
+ let purged: string[];
+ let errCalls: string[];
+ try {
+ purged = await purgeExpiredSources(engine);
+ } finally {
+ // Snapshot BEFORE restore — mockRestore() clears mock.calls.
+ errCalls = errSpy.mock.calls.map((c) => String(c[0]));
+ errSpy.mockRestore();
+ }
+
+ // Return contract preserved: string[] of purged ids ONLY — exactly the
+ // unreferenced one.
+ expect(purged).toEqual(['fk-purge-free']);
+
+ // Referenced source survives (skipped, not FK-crashed).
+ const remaining = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources WHERE id = ANY($1::text[])`,
+ [['fk-purge-ref', 'fk-purge-free']],
+ );
+ expect(remaining.map((r) => r.id)).toEqual(['fk-purge-ref']);
+
+ // ONE stderr warn naming the skipped id + revoke guidance.
+ const warns = errCalls.filter((m) => m.includes('purge skipped'));
+ expect(warns.length).toBe(1);
+ expect(warns[0]).toContain('fk-purge-ref');
+ expect(warns[0]).toContain('revoke-client');
+ expect(warns[0]).not.toContain('fk-purge-free');
+ });
+
+ test('purge skip is PHYSICAL: a soft-deleted client row still blocks (FK ignores deleted_at)', async () => {
+ await seedSource(engine, 'fk-purge-dead', { withPages: 1 });
+ await seedClient('cl-purge-dead', 'fk-purge-dead', { deleted: true });
+ await softDeleteSource(engine, 'fk-purge-dead');
+ await engine.executeRaw(
+ `UPDATE sources SET archive_expires_at = now() - INTERVAL '1 hour' WHERE id = $1`,
+ ['fk-purge-dead'],
+ );
+
+ const errSpy = spyOn(console, 'error').mockImplementation(() => {});
+ let purged: string[];
+ try {
+ purged = await purgeExpiredSources(engine);
+ } finally {
+ errSpy.mockRestore();
+ }
+
+ expect(purged).not.toContain('fk-purge-dead');
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources WHERE id = $1`, ['fk-purge-dead'],
+ );
+ expect(rows.length).toBe(1);
+ });
+
+ test('formatClientReferentsBlock lists clients + per-client revoke commands, split by liveness', () => {
+ const block = formatClientReferentsBlock('acme-example', [
+ { clientId: 'client-1', clientName: 'Agent One', deleted: false },
+ { clientId: 'client-2', clientName: 'Agent Two', deleted: true },
+ ]);
+ expect(block).toContain('Cannot delete source "acme-example"');
+ expect(block).toContain('2 OAuth client(s) reference this source');
+ expect(block).toContain('Agent One (client-1)');
+ expect(block).toContain('Agent Two (client-2) [revoked, retained]');
+ // Live rows get the hard-delete revoke guidance...
+ expect(block).toContain('Revoke each live client first');
+ expect(block).toContain('gbrain auth revoke-client "client-1"');
+ // ...soft-deleted rows get the retained-rows-still-block guidance.
+ expect(block).toContain('Revoked-but-retained rows still block the FK');
+ expect(block).toContain('gbrain auth revoke-client "client-2"');
+ });
+
+ test('degrade ladder: missing oauth_clients table → [], missing deleted_at → all referents, other errors propagate', async () => {
+ // Pre-oauth brain: no oauth_clients table at all → no referents by
+ // construction (isUndefinedTableError arm).
+ const noTable = {
+ executeRaw: async () => {
+ throw Object.assign(new Error('relation "oauth_clients" does not exist'), { code: '42P01' });
+ },
+ } as any;
+ expect(await clientsReferencingSource(noTable, 'x')).toEqual([]);
+
+ // Pre-migration brain: deleted_at column missing → falls back to ALL
+ // referents (the 42703-retry idiom), tagged live (deleted:false — the
+ // column that would say otherwise doesn't exist).
+ const noColumn = {
+ executeRaw: async (sql: string) => {
+ if (sql.includes('deleted_at')) {
+ throw Object.assign(new Error('column "deleted_at" does not exist'), { code: '42703' });
+ }
+ return [{ client_id: 'c1', client_name: 'n1' }];
+ },
+ } as any;
+ expect(await clientsReferencingSource(noColumn, 'x')).toEqual([
+ { clientId: 'c1', clientName: 'n1', deleted: false },
+ ]);
+
+ // Anything else (e.g. a dropped connection) must PROPAGATE — a swallowed
+ // error here would let a hard delete proceed past live referents.
+ const broken = {
+ executeRaw: async () => { throw new Error('connection reset'); },
+ } as any;
+ await expect(clientsReferencingSource(broken, 'x')).rejects.toThrow('connection reset');
+ });
+
+ test('missing source_id column → [] (no column ⇒ no FK ⇒ no referents)', async () => {
+ // Pre-v61 brain: oauth_clients exists but has no source_id column at all.
+ const noSourceId = {
+ executeRaw: async () => {
+ throw Object.assign(new Error('column "source_id" does not exist'), { code: '42703' });
+ },
+ } as any;
+ expect(await clientsReferencingSource(noSourceId, 'x')).toEqual([]);
+
+ // Same brain shape must not break the purge path either: the skip-set
+ // query 42703s, and the purge falls back to the unconditional DELETE.
+ let sawUnconditionalDelete = false;
+ const purgeStub = {
+ executeRaw: async (sql: string) => {
+ if (sql.includes('oauth_clients')) {
+ throw Object.assign(new Error('column "source_id" does not exist'), { code: '42703' });
+ }
+ if (sql.startsWith('DELETE FROM sources')) sawUnconditionalDelete = true;
+ return [];
+ },
+ } as any;
+ expect(await purgeExpiredSources(purgeStub)).toEqual([]);
+ expect(sawUnconditionalDelete).toBe(true);
+ });
+});
+
describe('formatters (display helpers)', () => {
test('formatImpact renders the boxed preview with the source id and counts', () => {
const impact: DestructiveImpact = {
@@ -379,6 +651,43 @@ describe('formatters (display helpers)', () => {
expect(out).toContain('5,033');
expect(out).toContain('22,000');
expect(out).toContain('DESTRUCTIVE OPERATION');
+ // cathedral-6: the box renders a Facts row (0 for a literal without it).
+ expect(out).toMatch(/Facts:\s+0/);
+ });
+
+ test('formatImpact renders the facts count (mirrors the page-count line)', () => {
+ const impact: DestructiveImpact = {
+ sourceId: 'revoked-agent-workspace',
+ sourceName: 'revoked-agent-workspace',
+ pageCount: 0,
+ chunkCount: 0,
+ embeddingCount: 0,
+ fileCount: 0,
+ factCount: 1234,
+ summary: '⚠️ This will permanently delete: 1,234 facts',
+ };
+ const out = formatImpact(impact);
+ expect(out).toMatch(/Facts:\s+1,234/);
+ });
+
+ test('sources remove orders the row DELETE (in-tx) BEFORE external teardown (F1 structural pin)', () => {
+ // A concurrent registration between the referents pre-check and the
+ // DELETE must surface as the refusal, never as destroyed scaffolding
+ // with the row still present — so the tx'd DELETE precedes unharden.
+ const { readFileSync } = require('fs');
+ const src = readFileSync(new URL('../src/commands/sources.ts', import.meta.url), 'utf-8');
+ const removeStart = src.indexOf('async function runRemove');
+ const removeEnd = src.indexOf('async function', removeStart + 1);
+ const body = src.slice(removeStart, removeEnd);
+ const deleteIdx = body.indexOf(`DELETE FROM sources WHERE id = $1`);
+ const teardownIdx = body.indexOf('unhardenBrainRepo');
+ expect(deleteIdx).toBeGreaterThan(0);
+ expect(teardownIdx).toBeGreaterThan(0);
+ expect(deleteIdx).toBeLessThan(teardownIdx);
+ // And the DELETE runs inside engine.transaction (atomic with the re-check).
+ const txIdx = body.indexOf('engine.transaction');
+ expect(txIdx).toBeGreaterThan(0);
+ expect(txIdx).toBeLessThan(deleteIdx);
});
test('formatSoftDelete renders the post-archive guidance with restore command', () => {
diff --git a/test/doctor-oauth-client-scope-health.test.ts b/test/doctor-oauth-client-scope-health.test.ts
new file mode 100644
index 0000000000..4e12e549fb
--- /dev/null
+++ b/test/doctor-oauth-client-scope-health.test.ts
@@ -0,0 +1,122 @@
+/**
+ * oauth_client_scope_health (cathedral-6) — scoped-client grant hygiene.
+ *
+ * - (a) a federated read grant naming a nonexistent source (federated_read
+ * is a TEXT[] with no FK) → warn naming the client + the missing id.
+ * - (b) an empty auto-created '<name>-workspace' source with no live client
+ * referencing it (the post-failure / post-revoke residue from
+ * `gbrain agent register`) → warn naming the source.
+ * - A pages-bearing non-default source is NEVER flagged (that shape is
+ * every ordinary local brain, not residue).
+ * - An empty workspace still referenced by a live client is NOT residue.
+ * - Deleted clients (deleted_at set) don't produce dangling-grant warns.
+ *
+ * Hermetic via PGLite. Imports from doctor.ts (the façade re-export), same
+ * as the sibling routing-federation check tests.
+ */
+
+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';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+async function truncate(): Promise<void> {
+ for (const t of ['pages', 'facts', 'oauth_tokens', 'oauth_codes', 'oauth_clients']) {
+ await (engine as any).db.exec(`DELETE FROM ${t}`);
+ }
+ await (engine as any).db.exec(`DELETE FROM sources WHERE id <> 'default'`);
+}
+
+describe('checkOauthClientScopeHealth', () => {
+ beforeEach(truncate);
+
+ test('clean brain → ok', async () => {
+ const r = await checkOauthClientScopeHealth(engine);
+ expect(r.status).toBe('ok');
+ expect(r.message).toMatch(/consistent/i);
+ });
+
+ test('dangling federated grant + orphaned empty workspace → both warn', async () => {
+ // (a) live client granted a read on a source that no longer exists.
+ await engine.executeRaw(
+ `INSERT INTO oauth_clients (client_id, client_name, scope, federated_read)
+ VALUES ('c-dangler', 'nova-daily', 'read write', $1)`,
+ [['default', 'ghost-source']],
+ );
+ // (b) empty derived workspace, DB-only, referenced by no live client.
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('aurora-coder-workspace', 'aurora-coder-workspace')`,
+ );
+ const r = await checkOauthClientScopeHealth(engine);
+ expect(r.status).toBe('warn');
+ // Arm (a): names the client and the missing grant id, with the rescope hint.
+ expect(r.message).toMatch(/nova-daily/);
+ expect(r.message).toMatch(/ghost-source/);
+ expect(r.message).toMatch(/rescope-client/);
+ // Arm (b): names the orphaned workspace, with the removal hint.
+ expect(r.message).toMatch(/aurora-coder-workspace/);
+ expect(r.message).toMatch(/gbrain sources remove/);
+ });
+
+ test('zero-page workspace WITH facts → NOT flagged (revoked agent memory, not residue)', async () => {
+ // A revoked agent's workspace: the client row is gone, no pages were ever
+ // written, but FACTS exist (the primary agent write lane). Recommending
+ // `gbrain sources remove` here would cascade the facts away.
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('revoked-agent-workspace', 'revoked-agent-workspace')`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, fact, source)
+ VALUES ('revoked-agent-workspace', 'agent memory row', 'test')`,
+ );
+ const r = await checkOauthClientScopeHealth(engine);
+ expect(r.status).toBe('ok');
+ expect(r.message).not.toMatch(/revoked-agent-workspace/);
+ });
+
+ test('pages-bearing non-default source → NOT flagged', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('proj-widget-workspace', 'proj-widget-workspace')`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('p1', 'proj-widget-workspace', 'note', 'p1', '', '')`,
+ );
+ const r = await checkOauthClientScopeHealth(engine);
+ expect(r.status).toBe('ok');
+ });
+
+ test('empty workspace referenced by a live client → NOT flagged', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('aurora-coder-workspace', 'aurora-coder-workspace')`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read)
+ VALUES ('c-live', 'aurora-coder', 'read write', 'aurora-coder-workspace', $1)`,
+ [['aurora-coder-workspace', 'default']],
+ );
+ const r = await checkOauthClientScopeHealth(engine);
+ expect(r.status).toBe('ok');
+ });
+
+ test('deleted client with a dangling grant → NOT flagged', async () => {
+ await engine.executeRaw(
+ `INSERT INTO oauth_clients (client_id, client_name, scope, federated_read, deleted_at)
+ VALUES ('c-deleted', 'retired-agent', 'read', $1, now())`,
+ [['ghost-source']],
+ );
+ const r = await checkOauthClientScopeHealth(engine);
+ expect(r.status).toBe('ok');
+ });
+});
diff --git a/test/e2e/serve-http-multi-agent.test.ts b/test/e2e/serve-http-multi-agent.test.ts
new file mode 100644
index 0000000000..f88ec512f8
--- /dev/null
+++ b/test/e2e/serve-http-multi-agent.test.ts
@@ -0,0 +1,823 @@
+/**
+ * E2E: multi-agent shared brain — continuity + isolation (cathedral-6, T7).
+ *
+ * Spins up a real `gbrain serve --http` against real Postgres, mints scoped
+ * agent clients through the NEW `gbrain agent register` CLI (presets,
+ * --json --show-token, --url probe, --reissue), and exercises the full
+ * cross-agent story end-to-end:
+ *
+ * 1. CLI register IS the canonical creation of client A (coding-agent).
+ * 2. Continuity: B writes → A reads (search + get_page); A's workspace
+ * stays invisible to B.
+ * 3. Isolation: an out-of-grant per-call source_id → permission_denied.
+ * 4. put_page with a foreign `source_id` param: warn-ignored (put_page
+ * declares no such param), row lands in the token's write source.
+ * 5. Facts: B `remember`s a world fact → B and A (federated grant) recall
+ * it; a nova-scoped C does not — the cross-agent recall continuity pin.
+ * 6. Concurrency hammer: ~24 parallel put_page across A+B tokens.
+ * 7. takes_* regression pin (source-scoped via the take's page source).
+ * 8. Serve-version probe notes (live OK line; dead port → note, exit 0).
+ * 9. Admin register-client route: source binding + invalid_source +
+ * unknown_source structured 400s (absorbs TODOS:894).
+ * 10. --reissue rotates the secret; OUTSTANDING tokens stay valid.
+ * 11. CHAOS (last, own serve on 19134): SIGKILL mid-hammer, then direct SQL
+ * proves every landed row kept its writer's source and zero
+ * cross-source links exist.
+ *
+ * Run: DATABASE_URL=... bun test test/e2e/serve-http-multi-agent.test.ts
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { spawnSync } from 'child_process';
+import { hasDatabase, setupDB, teardownDB, getConn } from './helpers.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const skip = !hasDatabase();
+// #3485 name floor: this suite opens direct SQL on the ambient URL and runs
+// DELETE cleanups — refuse non-test-shaped database names before any
+// connection is made.
+if (!skip) {
+ assertSafeE2eDatabaseUrl(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL || '');
+}
+const describeE2E = skip ? describe.skip : describe;
+
+if (skip) {
+ console.log('Skipping E2E serve-http-multi-agent tests (DATABASE_URL not set)');
+}
+
+// Non-vacuity guard: this file must never be a green skip in CI. It lives
+// OUTSIDE describeE2E so it runs even when the gated suite is skipped.
+test('not vacuously skipped in CI', () => {
+ if (process.env.CI) expect(skip).toBe(false);
+});
+
+const PORT = 19133; // unique per e2e file (serve-http-oauth uses 19131)
+const CHAOS_PORT = 19134; // chaos serve — fully isolated spawn + cleanup
+const DEAD_PORT = 19140; // free per port census — nothing ever listens here
+const BASE = `http://localhost:${PORT}`;
+const ADMIN_BOOTSTRAP_TOKEN = 'e2e-admin-bootstrap-token-000000000000';
+
+// Every client_name this file may mint. Pre-cleaned in beforeAll so a crashed
+// prior run can't trip the duplicate_name guard (oauth_clients is NOT in
+// helpers.ALL_TABLES, so rows survive setupDB's truncation).
+const CLIENT_NAMES = [
+ 'aurora-coder',
+ 'nova-daily',
+ 'nova-reader',
+ 'probe-live-agent',
+ 'probe-dead-agent',
+ 'reissue-target',
+ 'admin-bound-agent',
+] as const;
+
+// Write sources by client (A's workspace derives from its name).
+const A_SOURCE = 'aurora-coder-workspace';
+const B_SOURCE = 'proj-widget';
+const C_SOURCE = 'nova-notes';
+
+// Embedding is FORCED UNAVAILABLE in every serve this file spawns: the
+// nightly coverage lane (and dev shells) inject real provider keys, and the
+// hammer must not spend. Blanking OPENAI alone is not enough — the gateway's
+// config-less default embedding model is zeroentropyai:zembed-1 (1280-dim,
+// keyed by ZEROENTROPY_API_KEY), and a lane-injected ZE/Voyage/Gemini key
+// would make the serve embed for real: 1280-dim vectors into the 1536-dim
+// column kill every write with a pgvector dimension error (observed), and
+// each one costs money. Blank every embedding-capable provider key.
+const NO_EMBED_ENV = {
+ OPENAI_API_KEY: '',
+ ZEROENTROPY_API_KEY: '',
+ VOYAGE_API_KEY: '',
+ GEMINI_API_KEY: '',
+ GOOGLE_API_KEY: '',
+} as const;
+
+describeE2E('serve-http multi-agent E2E (cathedral-6)', () => {
+ let serverProcess: ReturnType<typeof import('child_process').spawn> | null = null;
+ let serveStderr = '';
+ // Client ids accumulate here THE MOMENT they are parsed so afterAll can
+ // revoke every one of them even if a later assertion throws.
+ const registeredClientIds: string[] = [];
+
+ let clientIdA: string | undefined;
+ let tokenA: string | undefined;
+ let tokenB: string | undefined;
+ let tokenC: string | undefined;
+
+ beforeAll(async () => {
+ // Schema init + table truncation via the standard helper (also connects
+ // the direct SQL pool used by the seed + assert queries below).
+ const engine = await setupDB();
+ const conn = getConn();
+
+ // Pre-clean any clients a crashed prior run left behind (static name
+ // list — no interpolation of runtime values).
+ const nameList = CLIENT_NAMES.map(n => `'${n}'`).join(', ');
+ await conn.unsafe(
+ `DELETE FROM oauth_tokens WHERE client_id IN (SELECT client_id FROM oauth_clients WHERE client_name IN (${nameList}))`,
+ );
+ await conn.unsafe(`DELETE FROM oauth_clients WHERE client_name IN (${nameList})`);
+
+ // Seed the two shared sources. setupDB deleted every non-default source,
+ // so this is a fresh create; ON CONFLICT keeps it re-runnable.
+ await conn.unsafe(`
+ INSERT INTO sources (id, name) VALUES
+ ('proj-widget', 'proj-widget'),
+ ('nova-notes', 'nova-notes')
+ ON CONFLICT (id) DO NOTHING
+ `);
+
+ // Seed a nova-notes page so grant-exclusion assertions are non-vacuous:
+ // it deliberately shares the 'handoff' keyword with B's proj-widget page.
+ const { importFromContent } = await import('../../src/core/import-file.ts');
+ await importFromContent(
+ engine,
+ 'notes/nova-secret',
+ '---\ntitle: Nova secret handoff\n---\nThe nova-only handoff decision that agent A must never see.',
+ { noEmbed: true, sourceId: C_SOURCE },
+ );
+
+ // Start the HTTP server. env spread is required: bun's spawn/execSync do
+ // NOT inherit process.env mutations (helpers.ts loads .env.testing via
+ // mutation) unless we re-pass { ...process.env }. NO_EMBED_ENV forces
+ // embedding unavailable (see its comment).
+ const { spawn } = await import('child_process');
+ serverProcess = spawn('bun', [
+ 'run', 'src/cli.ts', 'serve', '--http',
+ '--port', String(PORT),
+ '--public-url', `http://localhost:${PORT}`,
+ '--enable-dcr',
+ ], {
+ cwd: process.cwd(),
+ env: {
+ ...process.env,
+ GBRAIN_POOL_SIZE: '16',
+ GBRAIN_ADMIN_BOOTSTRAP_TOKEN: ADMIN_BOOTSTRAP_TOKEN,
+ ...NO_EMBED_ENV,
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ serverProcess.stderr?.on('data', (d: Buffer) => { serveStderr += d.toString(); });
+
+ // Wait for the server to be ready (up to 15s).
+ let ready = false;
+ for (let i = 0; i < 30; i++) {
+ try {
+ const res = await fetch(`${BASE}/health`);
+ if (res.ok) { ready = true; break; }
+ } catch {}
+ await new Promise(r => setTimeout(r, 500));
+ }
+ if (!ready) throw new Error('Server failed to start within 15s.\nstderr: ' + serveStderr.slice(-800));
+ }, 90_000);
+
+ afterAll(async () => {
+ // Kill server first so it can't issue more tokens during cleanup.
+ if (serverProcess) {
+ serverProcess.kill('SIGTERM');
+ await new Promise(r => setTimeout(r, 1000));
+ if (!serverProcess.killed) serverProcess.kill('SIGKILL');
+ }
+ // Revoke every client this file registered; surface cleanup failures to
+ // stderr without throwing — a real test failure is more interesting than
+ // the cleanup error that follows it.
+ const { execSync } = await import('child_process');
+ for (const id of registeredClientIds) {
+ try {
+ execSync(`bun run src/cli.ts auth revoke-client "${id}"`,
+ { cwd: process.cwd(), encoding: 'utf8', env: { ...process.env } });
+ } catch (e: any) {
+ // eslint-disable-next-line no-console
+ console.error(`[afterAll] revoke-client cleanup failed for ${id}: ${e.message}`);
+ }
+ }
+ await teardownDB();
+ }, 30_000);
+
+ // ── helpers ──────────────────────────────────────────────────────────────
+
+ /** Call MCP JSON-RPC with a bearer token (model-file idiom). */
+ async function mcpCall(token: string, method: string, params?: any, base = BASE): Promise<Response> {
+ return fetch(`${base}/mcp`, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json, text/event-stream',
+ },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, ...(params ? { params } : {}) }),
+ });
+ }
+
+ /** Parse an /mcp response body — plain JSON or SSE-framed (`data:` lines). */
+ function parseRpcText(raw: string): any {
+ const trimmed = raw.trim();
+ try { return JSON.parse(trimmed); } catch { /* fall through to SSE */ }
+ const dataLines = trimmed.split('\n').filter(l => l.startsWith('data:'));
+ if (dataLines.length > 0) {
+ return JSON.parse(dataLines[dataLines.length - 1].slice(5).trim());
+ }
+ throw new Error(`unparseable /mcp response: ${trimmed.slice(0, 400)}`);
+ }
+
+ interface ToolCallResult {
+ status: number;
+ isError: boolean;
+ /** JSON.parse of content[0].text when parseable, else null. */
+ payload: any;
+ /** All content-block texts joined (op result + warn blocks). */
+ text: string;
+ raw: string;
+ }
+
+ /** tools/call helper: unwraps the dispatch ToolResult envelope. */
+ async function callTool(token: string, name: string, args: Record<string, unknown>, base = BASE): Promise<ToolCallResult> {
+ const res = await mcpCall(token, 'tools/call', { name, arguments: args }, base);
+ const raw = await res.text();
+ let isError = false;
+ let payload: any = null;
+ let text = '';
+ try {
+ const rpc = parseRpcText(raw);
+ if (rpc.error) {
+ isError = true;
+ text = JSON.stringify(rpc.error);
+ } else {
+ const result = rpc.result ?? {};
+ isError = result.isError === true;
+ const blocks: Array<{ text?: string }> = Array.isArray(result.content) ? result.content : [];
+ text = blocks.map(b => b?.text ?? '').join('\n');
+ if (typeof blocks[0]?.text === 'string') {
+ try { payload = JSON.parse(blocks[0].text); } catch { /* non-JSON content */ }
+ }
+ }
+ } catch {
+ isError = true;
+ text = raw;
+ }
+ return { status: res.status, isError, payload, text, raw };
+ }
+
+ /** Run `gbrain agent register <args>` as a subprocess. spawnSync (not
+ * execSync) so stdout and stderr assert separately — same ambient-env
+ * passthrough idiom as the model file's execSync calls (the CLI reaches
+ * the serve's brain via the ambient DATABASE_URL). */
+ function runRegister(args: string[]): { status: number | null; stdout: string; stderr: string } {
+ const res = spawnSync('bun', ['run', 'src/cli.ts', 'agent', 'register', ...args],
+ { cwd: process.cwd(), encoding: 'utf8', env: { ...process.env } });
+ return { status: res.status, stdout: res.stdout ?? '', stderr: res.stderr ?? '' };
+ }
+
+ /** Parse the --json register output. JSON.parse of the ENTIRE stdout is
+ * itself the stdout-purity assertion (all notes must go to stderr). */
+ function parseRegisterJson(r: { status: number | null; stdout: string; stderr: string }): any {
+ if (r.status !== 0) {
+ throw new Error(`agent register exited ${r.status}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`);
+ }
+ let doc: any;
+ try {
+ doc = JSON.parse(r.stdout);
+ } catch {
+ throw new Error(`register stdout is not a single JSON document (stdout-purity violation):\n${r.stdout}\nstderr: ${r.stderr}`);
+ }
+ // Dedupe: a --reissue doc carries the SAME client_id as its original
+ // registration; revoking twice would log a spurious cleanup failure.
+ if (typeof doc.client_id === 'string' && !registeredClientIds.includes(doc.client_id)) {
+ registeredClientIds.push(doc.client_id);
+ }
+ return doc;
+ }
+
+ async function adminCookie(): Promise<string> {
+ const login = await fetch(`${BASE}/admin/login`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ token: ADMIN_BOOTSTRAP_TOKEN }),
+ });
+ expect(login.ok).toBe(true);
+ const match = (login.headers.get('set-cookie') || '').match(/gbrain_admin=([^;]+)/);
+ expect(match).toBeTruthy();
+ return `gbrain_admin=${match![1]}`;
+ }
+
+ const pageBody = (title: string, body: string) => `---\ntitle: ${title}\n---\n${body}`;
+
+ // =========================================================================
+ // Case 1 — CLI register end-to-end IS client A's canonical creation
+ // =========================================================================
+
+ test('case 1: agent register mints client A (coding-agent) and the token works at /mcp', async () => {
+ const r = runRegister([
+ 'aurora-coder',
+ '--harness', 'claude-code',
+ '--preset', 'coding-agent',
+ '--federated-read', 'proj-widget',
+ '--url', `http://localhost:${PORT}`,
+ '--json', '--show-token',
+ ]);
+ const doc = parseRegisterJson(r);
+
+ expect(doc.ok).toBe(true);
+ expect(doc.schema_version).toBe(1);
+ // coding-agent derives the write source from the client name.
+ expect(doc.preset_resolved.write_source).toBe(A_SOURCE);
+ expect(doc.created_workspace_source).toBe(true);
+ expect(doc.preset_resolved.federated_read).toEqual([A_SOURCE, 'proj-widget']);
+ expect(doc.client_id).toMatch(/^gbrain_cl_/);
+ expect(doc.access_token).toMatch(/^gbrain_at_/);
+ expect(doc.token_redacted).toBe(false);
+ expect(doc.mcp_url).toBe(`http://localhost:${PORT}/mcp`);
+
+ clientIdA = doc.client_id;
+ tokenA = doc.access_token;
+
+ // USE the minted token against the live serve.
+ const list = await mcpCall(tokenA!, 'tools/list');
+ expect(list.status).toBe(200);
+ const body = await list.text();
+ expect(body).toContain('tools');
+ expect(body).toContain('search');
+ }, 45_000);
+
+ // =========================================================================
+ // Case 2 — continuity: B writes, A reads; A's workspace invisible to B
+ // =========================================================================
+
+ test('case 2: B (daily-driver) writes notes/handoff → A reads it; A workspace page denied to B', async () => {
+ const r = runRegister([
+ 'nova-daily',
+ '--harness', 'claude-code',
+ '--preset', 'daily-driver',
+ '--source', 'proj-widget',
+ '--federated-read', 'proj-widget,nova-notes',
+ '--url', `http://localhost:${PORT}`,
+ '--json', '--show-token',
+ ]);
+ const doc = parseRegisterJson(r);
+ expect(doc.ok).toBe(true);
+ expect(doc.preset_resolved.write_source).toBe(B_SOURCE);
+ tokenB = doc.access_token;
+ expect(tokenB).toMatch(/^gbrain_at_/);
+
+ // B writes the handoff page (lands in proj-widget, B's write source).
+ const put = await callTool(tokenB!, 'put_page', {
+ slug: 'notes/handoff',
+ content: pageBody('Widget handoff', 'Handoff decision: ship the widget importer next sprint.'),
+ });
+ expect(put.isError).toBe(false);
+ expect(put.payload?.slug).toBe('notes/handoff');
+
+ // A reads it via search (keyword arm — embedding is forced unavailable)…
+ const search = await callTool(tokenA!, 'search', { query: 'handoff', limit: 10 });
+ expect(search.isError).toBe(false);
+ const slugs = (Array.isArray(search.payload) ? search.payload : []).map((x: any) => x.slug);
+ expect(slugs).toContain('notes/handoff');
+ // …and the nova-notes page sharing the keyword stays OUT of A's grant.
+ expect(slugs).not.toContain('notes/nova-secret');
+
+ // …AND via get_page (federated grant includes proj-widget).
+ const get = await callTool(tokenA!, 'get_page', { slug: 'notes/handoff' });
+ expect(get.isError).toBe(false);
+ expect(get.payload?.slug).toBe('notes/handoff');
+ expect(get.payload?.source_id).toBe(B_SOURCE);
+
+ // A writes into its own workspace…
+ const scratch = await callTool(tokenA!, 'put_page', {
+ slug: 'agents/scratch',
+ content: pageBody('Aurora scratch', 'Private workspace scratchpad for aurora-coder.'),
+ });
+ expect(scratch.isError).toBe(false);
+
+ // …and B (grant: proj-widget + nova-notes) cannot read it.
+ const denied = await callTool(tokenB!, 'get_page', { slug: 'agents/scratch' });
+ expect(denied.isError).toBe(true);
+ expect(denied.text).toContain('page_not_found');
+ }, 45_000);
+
+ // =========================================================================
+ // Case 3 — isolation: per-call source_id outside the grant
+ // =========================================================================
+
+ test('case 3: A query with source_id nova-notes → permission_denied; unqualified query stays in grant', async () => {
+ const denied = await callTool(tokenA!, 'query', {
+ query: 'handoff', source_id: 'nova-notes', expand: false,
+ });
+ expect(denied.isError).toBe(true);
+ expect(denied.text).toContain('permission_denied');
+
+ const ok = await callTool(tokenA!, 'query', { query: 'handoff', expand: false });
+ expect(ok.isError).toBe(false);
+ expect(ok.text).toContain('notes/handoff');
+ // The nova-notes page matching the same keyword must never leak.
+ expect(ok.text).not.toContain('nova-secret');
+ }, 30_000);
+
+ // =========================================================================
+ // Case 4 — put_page with a foreign source_id param (undeclared → warn-ignore)
+ // =========================================================================
+
+ test('case 4: put_page foreign source_id param is warn-ignored; row lands in the token write source', async () => {
+ // put_page declares NO source_id param; in the default strict_params=warn
+ // mode the dispatcher accepts the call, appends a warning content block,
+ // and the write routes by the TOKEN's source — never the param.
+ const put = await callTool(tokenA!, 'put_page', {
+ slug: 'agents/foreign-param',
+ content: pageBody('Foreign param probe', 'Body written with a foreign source_id param.'),
+ source_id: 'proj-widget',
+ });
+ expect(put.isError).toBe(false);
+ expect(put.payload?.slug).toBe('agents/foreign-param');
+ // The warn-ignore block is model-visible (content[1]).
+ expect(put.text).toContain('unknown parameter "source_id" ignored');
+
+ const conn = getConn();
+ const rows = await conn.unsafe(
+ `SELECT source_id FROM pages WHERE slug = 'agents/foreign-param'`,
+ ) as unknown as Array<{ source_id: string }>;
+ expect(rows.length).toBe(1);
+ expect(rows[0].source_id).toBe(A_SOURCE);
+ }, 30_000);
+
+ // =========================================================================
+ // Case 5 — facts continuity across agents (the cathedral-6 pin)
+ // =========================================================================
+
+ test('case 5: B remembers a world fact → B and A recall it; nova-scoped C does not', async () => {
+ // Register client C first: read lane scoped ONLY to nova-notes (no preset
+ // → passthrough grants federated_read=[nova-notes]).
+ const r = runRegister([
+ 'nova-reader',
+ '--harness', 'claude-code',
+ '--source', 'nova-notes',
+ '--url', `http://localhost:${PORT}`,
+ '--json', '--show-token',
+ ]);
+ const doc = parseRegisterJson(r);
+ expect(doc.ok).toBe(true);
+ expect(doc.preset_resolved.federated_read).toEqual([C_SOURCE]);
+ tokenC = doc.access_token;
+
+ // B writes the fact into its write source (proj-widget), world-visible.
+ const remembered = await callTool(tokenB!, 'remember', {
+ fact: 'The Q3 launch decision is frozen (e2e-ma-fact).',
+ provenance: 'e2e multi-agent case 5',
+ visibility: 'world',
+ });
+ expect(remembered.isError).toBe(false);
+ expect(['inserted', 'duplicate', 'superseded']).toContain(remembered.payload?.status);
+
+ // B recalls its own fact.
+ const recallB = await callTool(tokenB!, 'recall', { grep: 'e2e-ma-fact' });
+ expect(recallB.isError).toBe(false);
+ expect((recallB.payload?.facts ?? []).some((f: any) => f.fact.includes('e2e-ma-fact'))).toBe(true);
+
+ // A recalls it too — federated grant includes proj-widget (cross-agent
+ // recall continuity, Deliverable 1b).
+ const recallA = await callTool(tokenA!, 'recall', { grep: 'e2e-ma-fact' });
+ expect(recallA.isError).toBe(false);
+ expect((recallA.payload?.facts ?? []).some((f: any) => f.fact.includes('e2e-ma-fact'))).toBe(true);
+
+ // C is scoped to nova-notes only: the fact must NOT surface.
+ const recallC = await callTool(tokenC!, 'recall', { grep: 'e2e-ma-fact' });
+ expect(recallC.isError).toBe(false);
+ expect((recallC.payload?.facts ?? []).some((f: any) => f.fact.includes('e2e-ma-fact'))).toBe(false);
+ }, 45_000);
+
+ // =========================================================================
+ // Case 6 — concurrency hammer (write integrity under parallel load)
+ // =========================================================================
+
+ test('case 6: 24 parallel put_page across A+B — zero 5xx, exact per-source counts, no cross-source links', async () => {
+ // Bodies carry [[wikilinks]] deliberately: auto-link does NOT run for
+ // remote (MCP) callers (ops/pages.ts skips runAutoLink when
+ // ctx.remote !== false), so ZERO link rows may appear from these writes.
+ const body = (slug: string) =>
+ pageBody(`Hammer ${slug}`, `Hammer body for ${slug} referencing [[notes/handoff]] and [[hammer/a-0]].`);
+
+ interface Put { token: string; slug: string }
+ const puts: Put[] = [];
+ for (let i = 0; i < 10; i++) puts.push({ token: tokenA!, slug: `hammer/a-${i}` });
+ // shared-a: same slug, same source, written twice by A. The two writes
+ // sit in DIFFERENT chunks (sequential) so the case pins last-write-wins
+ // row semantics rather than manufacturing an insert race.
+ puts.push({ token: tokenA!, slug: 'hammer/shared-a' });
+ for (let i = 0; i < 5; i++) puts.push({ token: tokenB!, slug: `hammer/b-${i}` });
+ for (let i = 5; i < 10; i++) puts.push({ token: tokenB!, slug: `hammer/b-${i}` });
+ puts.push({ token: tokenA!, slug: 'hammer/shared-a' });
+ // shared-x: same slug, CROSS source, concurrently in the same chunk —
+ // distinct (source_id, slug) rows must both land.
+ puts.push({ token: tokenA!, slug: 'hammer/shared-x' });
+ puts.push({ token: tokenB!, slug: 'hammer/shared-x' });
+ expect(puts.length).toBe(24);
+
+ const failures: string[] = [];
+ for (let i = 0; i < puts.length; i += 8) {
+ const chunk = puts.slice(i, i + 8);
+ await Promise.all(chunk.map(async p => {
+ const res = await callTool(p.token, 'put_page', { slug: p.slug, content: body(p.slug) });
+ if (res.status >= 500) failures.push(`${p.slug}: HTTP ${res.status}`);
+ else if (res.isError) failures.push(`${p.slug}: isError ${res.text.slice(0, 200)}`);
+ }));
+ }
+ expect(
+ failures.length,
+ `hammer failures: ${failures.join(' | ')}\nserve stderr tail: ${serveStderr.slice(-800)}`,
+ ).toBe(0);
+ expect(
+ serveStderr.includes('connect_timeout'),
+ `serve stderr carries connect_timeout — pool starvation under the hammer.\nstderr tail: ${serveStderr.slice(-800)}`,
+ ).toBe(false);
+
+ const conn = getConn();
+ // Per-source row counts, exact: A wrote a-0..a-9 + shared-a + shared-x =
+ // 12 rows in its workspace; B wrote b-0..b-9 + shared-x = 11 rows.
+ const aCount = await conn.unsafe(
+ `SELECT count(*)::int AS n FROM pages WHERE source_id = '${A_SOURCE}' AND slug LIKE 'hammer/%'`,
+ ) as unknown as Array<{ n: number }>;
+ expect(aCount[0].n).toBe(12);
+ const bCount = await conn.unsafe(
+ `SELECT count(*)::int AS n FROM pages WHERE source_id = '${B_SOURCE}' AND slug LIKE 'hammer/%'`,
+ ) as unknown as Array<{ n: number }>;
+ expect(bCount[0].n).toBe(11);
+
+ // Both same-slug-cross-source rows exist.
+ const sharedX = await conn.unsafe(
+ `SELECT source_id FROM pages WHERE slug = 'hammer/shared-x' ORDER BY source_id`,
+ ) as unknown as Array<{ source_id: string }>;
+ expect(sharedX.map(r => r.source_id)).toEqual([A_SOURCE, B_SOURCE]);
+
+ // Zero cross-source links, brain-wide (remote put_page skips auto-link).
+ const crossLinks = await conn.unsafe(`
+ SELECT count(*)::int AS n
+ FROM links l
+ JOIN pages pf ON l.from_page_id = pf.id
+ JOIN pages pt ON l.to_page_id = pt.id
+ WHERE pf.source_id <> pt.source_id
+ `) as unknown as Array<{ n: number }>;
+ expect(crossLinks[0].n).toBe(0);
+ }, 45_000);
+
+ // =========================================================================
+ // Case 7 — takes_* regression pin (source-scoped via the take's page)
+ // =========================================================================
+
+ test('case 7: takes_list never returns foreign rows — starter surface denies A; scoped C sees only its source', async () => {
+ const conn = getConn();
+ // Seed one world-holder take per source (world passes the fail-closed
+ // per-token holder allow-list, so the only filter under test is SOURCE).
+ await conn.unsafe(`
+ INSERT INTO takes (page_id, row_num, claim, kind, holder)
+ SELECT id, 9001, 'nova secret take e2e-ma', 'take', 'world'
+ FROM pages WHERE slug = 'notes/nova-secret' AND source_id = '${C_SOURCE}'
+ ON CONFLICT (page_id, row_num) DO NOTHING
+ `);
+ await conn.unsafe(`
+ INSERT INTO takes (page_id, row_num, claim, kind, holder)
+ SELECT id, 9001, 'proj widget take e2e-ma', 'take', 'world'
+ FROM pages WHERE slug = 'notes/handoff' AND source_id = '${B_SOURCE}'
+ ON CONFLICT (page_id, row_num) DO NOTHING
+ `);
+
+ // A runs on the 'starter' surface (coding-agent preset): takes_list is
+ // hidden there, and a hidden op is indistinguishable from a nonexistent
+ // one — denied. Either way, the foreign claim must never appear.
+ const deniedA = await callTool(tokenA!, 'takes_list', { page_slug: 'notes/nova-secret' });
+ expect(deniedA.isError).toBe(true);
+ expect(deniedA.text).not.toContain('nova secret take e2e-ma');
+
+ // C has no per-client surface row (no preset) → effective surface 'full',
+ // so takes_list dispatches and the SOURCE scope does the work: a
+ // proj-widget page's takes are foreign to nova-scoped C → empty.
+ const foreignC = await callTool(tokenC!, 'takes_list', { page_slug: 'notes/handoff' });
+ expect(foreignC.isError).toBe(false);
+ expect(Array.isArray(foreignC.payload)).toBe(true);
+ expect(foreignC.payload.length).toBe(0);
+ expect(foreignC.text).not.toContain('proj widget take e2e-ma');
+
+ // Positive control: C DOES see the take inside its own granted source —
+ // the empty result above is scoping, not a broken op.
+ const ownC = await callTool(tokenC!, 'takes_list', { page_slug: 'notes/nova-secret' });
+ expect(ownC.isError).toBe(false);
+ expect((ownC.payload ?? []).some((t: any) => t.claim === 'nova secret take e2e-ma')).toBe(true);
+ }, 30_000);
+
+ // =========================================================================
+ // Case 8 — serve probe notes (live OK; dead port → note, still exit 0)
+ // =========================================================================
+
+ test('case 8: register --url probes the serve — live OK note; dead port note with exit 0', async () => {
+ // Live serve: the probe note prints to stderr in --json mode.
+ const live = runRegister([
+ 'probe-live-agent',
+ '--harness', 'claude-code',
+ '--source', 'proj-widget',
+ '--url', `http://localhost:${PORT}`,
+ '--json',
+ ]);
+ const liveDoc = parseRegisterJson(live);
+ expect(liveDoc.ok).toBe(true);
+ expect(live.stderr).toContain('serve health: OK');
+
+ // Dead port: the probe is informational, NEVER a failure — exit stays 0
+ // and the JSON document still lands on stdout.
+ const dead = runRegister([
+ 'probe-dead-agent',
+ '--harness', 'claude-code',
+ '--source', 'proj-widget',
+ '--url', `http://localhost:${DEAD_PORT}/mcp`,
+ '--json',
+ ]);
+ expect(dead.status).toBe(0);
+ const deadDoc = parseRegisterJson(dead);
+ expect(deadDoc.ok).toBe(true);
+ expect(dead.stderr).toContain('could not reach');
+ }, 45_000);
+
+ // =========================================================================
+ // Case 9 (task item 9) — admin register-client route (absorbs TODOS:894)
+ // =========================================================================
+
+ test('case 9: admin register-client — source binding stored; invalid_source and unknown_source are structured 400s', async () => {
+ const cookie = await adminCookie();
+
+ // Happy path with source binding.
+ const res = await fetch(`${BASE}/admin/api/register-client`, {
+ method: 'POST',
+ headers: { Cookie: cookie, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'admin-bound-agent',
+ source: 'proj-widget',
+ federatedRead: ['proj-widget', 'nova-notes'],
+ }),
+ });
+ expect(res.ok).toBe(true);
+ const created = await res.json() as { clientId: string };
+ expect(created.clientId).toMatch(/^gbrain_cl_/);
+ registeredClientIds.push(created.clientId);
+
+ // The stored binding is visible through the admin listing route.
+ const agentsRes = await fetch(`${BASE}/admin/api/agents`, { headers: { Cookie: cookie } });
+ expect(agentsRes.ok).toBe(true);
+ const agents = await agentsRes.json() as Array<{ id: string; source_id: string | null; federated_read: string[] }>;
+ const row = agents.find(a => a.id === created.clientId);
+ expect(row).toBeDefined();
+ expect(row!.source_id).toBe('proj-widget');
+ expect(row!.federated_read).toContain('proj-widget');
+ expect(row!.federated_read).toContain('nova-notes');
+
+ // Malformed source id → structured 400 invalid_source.
+ const malformed = await fetch(`${BASE}/admin/api/register-client`, {
+ method: 'POST',
+ headers: { Cookie: cookie, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'admin-bad-agent', source: 'Bad/Source' }),
+ });
+ expect(malformed.status).toBe(400);
+ expect(((await malformed.json()) as any).error).toBe('invalid_source');
+
+ // Well-formed but nonexistent source → structured 400 unknown_source
+ // (pre-fix this surfaced as a 500 when the FK fired inside the INSERT).
+ const ghost = await fetch(`${BASE}/admin/api/register-client`, {
+ method: 'POST',
+ headers: { Cookie: cookie, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'admin-ghost-agent', source: 'ghost-source' }),
+ });
+ expect(ghost.status).toBe(400);
+ expect(((await ghost.json()) as any).error).toBe('unknown_source');
+ }, 30_000);
+
+ // =========================================================================
+ // --reissue lifecycle — rotation is NOT revocation
+ // =========================================================================
+
+ test('reissue: secret rotates, OLD access token still works until expiry, new secret mints', async () => {
+ const reg = runRegister([
+ 'reissue-target',
+ '--harness', 'claude-code',
+ '--source', 'proj-widget',
+ '--url', `http://localhost:${PORT}`,
+ '--json', '--show-token',
+ ]);
+ const doc = parseRegisterJson(reg);
+ expect(doc.ok).toBe(true);
+ const clientId = doc.client_id as string;
+ const oldSecret = doc.client_secret as string;
+ const oldToken = doc.access_token as string;
+ expect((await mcpCall(oldToken, 'tools/list')).status).toBe(200);
+
+ const reissue = runRegister([
+ '--reissue', clientId,
+ '--harness', 'claude-code',
+ '--url', `http://localhost:${PORT}`,
+ '--json', '--show-token',
+ ]);
+ const doc2 = parseRegisterJson(reissue);
+ expect(doc2.ok).toBe(true);
+ expect(doc2.client_id).toBe(clientId);
+ const newSecret = doc2.client_secret as string;
+ const newToken = doc2.access_token as string;
+ expect(newSecret).not.toBe(oldSecret);
+
+ // Rotation is not revocation: the OLD access token STILL WORKS until it
+ // expires — assert that explicitly.
+ expect((await mcpCall(oldToken, 'tools/list')).status).toBe(200);
+ // The token minted by the reissue works too.
+ expect((await mcpCall(newToken, 'tools/list')).status).toBe(200);
+
+ // The old secret no longer mints…
+ const oldMint = await fetch(`${BASE}/token`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: `grant_type=client_credentials&client_id=${clientId}&client_secret=${encodeURIComponent(oldSecret)}&scope=read`,
+ });
+ expect(oldMint.ok).toBe(false);
+ // …and the new secret exchanges OK.
+ const newMint = await fetch(`${BASE}/token`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: `grant_type=client_credentials&client_id=${clientId}&client_secret=${encodeURIComponent(newSecret)}&scope=read`,
+ });
+ expect(newMint.ok).toBe(true);
+ expect(((await newMint.json()) as any).access_token).toMatch(/^gbrain_at_/);
+ }, 45_000);
+
+ // =========================================================================
+ // Case 10 — CHAOS (LAST): SIGKILL the serve mid-hammer; integrity holds
+ // =========================================================================
+
+ test('case 10 CHAOS: SIGKILL mid-hammer on own serve — landed rows keep writer source, zero cross-source links', async () => {
+ const { spawn } = await import('child_process');
+ let chaosProcess: ReturnType<typeof spawn> | null = null;
+ let chaosStderr = '';
+ try {
+ // Own serve, fully isolated from 19133 (own spawn + own cleanup).
+ chaosProcess = spawn('bun', [
+ 'run', 'src/cli.ts', 'serve', '--http',
+ '--port', String(CHAOS_PORT),
+ '--public-url', `http://localhost:${CHAOS_PORT}`,
+ '--enable-dcr',
+ ], {
+ cwd: process.cwd(),
+ env: {
+ ...process.env,
+ GBRAIN_POOL_SIZE: '16',
+ GBRAIN_ADMIN_BOOTSTRAP_TOKEN: ADMIN_BOOTSTRAP_TOKEN,
+ ...NO_EMBED_ENV,
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ chaosProcess.stderr?.on('data', (d: Buffer) => { chaosStderr += d.toString(); });
+
+ let ready = false;
+ for (let i = 0; i < 30; i++) {
+ try {
+ const res = await fetch(`http://localhost:${CHAOS_PORT}/health`);
+ if (res.ok) { ready = true; break; }
+ } catch {}
+ await new Promise(r => setTimeout(r, 500));
+ }
+ if (!ready) throw new Error('Chaos server failed to start within 15s.\nstderr: ' + chaosStderr.slice(-800));
+
+ // Fire 16 writes WITHOUT awaiting, then SIGKILL mid-flight. Tokens are
+ // DB-backed, so A/B tokens verify against 19134 too.
+ const chaosBase = `http://localhost:${CHAOS_PORT}`;
+ const body = (slug: string) =>
+ pageBody(`Chaos ${slug}`, `Chaos body for ${slug} referencing [[notes/handoff]].`);
+ const inflight: Promise<unknown>[] = [];
+ for (let i = 0; i < 8; i++) {
+ inflight.push(callTool(tokenA!, 'put_page', { slug: `chaos/a-${i}`, content: body(`chaos/a-${i}`) }, chaosBase).catch(() => null));
+ inflight.push(callTool(tokenB!, 'put_page', { slug: `chaos/b-${i}`, content: body(`chaos/b-${i}`) }, chaosBase).catch(() => null));
+ }
+ await new Promise(r => setTimeout(r, 200));
+ chaosProcess.kill('SIGKILL');
+ await Promise.allSettled(inflight);
+ } finally {
+ if (chaosProcess && !chaosProcess.killed) chaosProcess.kill('SIGKILL');
+ }
+
+ // Integrity via direct SQL: every landed chaos row carries its WRITER's
+ // source (partial landings are fine — the invariant is per-row, and a
+ // kill before any landing still satisfies it).
+ const conn = getConn();
+ const rows = await conn.unsafe(
+ `SELECT slug, source_id FROM pages WHERE slug LIKE 'chaos/%'`,
+ ) as unknown as Array<{ slug: string; source_id: string }>;
+ expect(rows.length).toBeLessThanOrEqual(16);
+ for (const row of rows) {
+ const expected = row.slug.startsWith('chaos/a-') ? A_SOURCE : B_SOURCE;
+ expect(`${row.slug}=${row.source_id}`).toBe(`${row.slug}=${expected}`);
+ }
+
+ // Zero cross-source links survive the chaos too.
+ const crossLinks = await conn.unsafe(`
+ SELECT count(*)::int AS n
+ FROM links l
+ JOIN pages pf ON l.from_page_id = pf.id
+ JOIN pages pt ON l.to_page_id = pt.id
+ WHERE pf.source_id <> pt.source_id
+ `) as unknown as Array<{ n: number }>;
+ expect(crossLinks[0].n).toBe(0);
+
+ // The 19133 serve was never touched: still healthy.
+ const health = await fetch(`${BASE}/health`);
+ expect(health.ok).toBe(true);
+ }, 45_000);
+});
diff --git a/test/fix-wave-structural.test.ts b/test/fix-wave-structural.test.ts
index 9e71a094b7..3d46faf103 100644
--- a/test/fix-wave-structural.test.ts
+++ b/test/fix-wave-structural.test.ts
@@ -87,7 +87,22 @@ describe('v0.36.1.x #1077 — admin register-client supports PKCE public clients
// UPDATE block (the regex deliberately asserts the post-insert UPDATE
// is GONE).
expect(src).toMatch(/validateTokenEndpointAuthMethod\(tokenEndpointAuthMethod\)/);
- expect(src).toMatch(/registerClientManual\([^)]*validatedAuthMethod[^)]*\)/);
+ // cathedral-6: the route now composes registerScopedClient (the same core
+ // the CLI uses) instead of open-coding registerClientManual + a raw TTL
+ // UPDATE. The atomicity contract is unchanged — the validated method is
+ // threaded through the parsed args into registerClientManual's single
+ // INSERT inside the core; the no-post-insert-UPDATE guard below still
+ // pins the F4 regression. The call now runs on the tx-scoped sql handle
+ // (dup-check + INSERT are one transaction under the shared name lock).
+ expect(src).toMatch(/registerScopedClient\(txSql,\s*name,\s*\{[\s\S]*?tokenEndpointAuthMethod:\s*validatedAuthMethod[\s\S]*?\}/);
+ // cathedral-6: the dup-check + INSERT run in ONE engine.transaction under
+ // the SAME name-scoped advisory lock the CLI lane takes — two concurrent
+ // same-name requests can no longer both pass the autocommit pre-check.
+ expect(src).toMatch(/pg_advisory_xact_lock\(hashtext\(\$1\)::bigint\)`,\s*\[registerClientNameLockKey\(name\)\]/);
+ // cathedral-6 (C1): tokenTtl validates BEFORE the tx (integer within the
+ // shared bounds → structured 400, never an in-tx integer-cast 500).
+ expect(src).toMatch(/invalid_token_ttl/);
+ expect(src).toMatch(/Number\.isInteger\(v\) \|\| v < TOKEN_TTL_MIN_SECONDS \|\| v > TOKEN_TTL_MAX_SECONDS/);
// Regression guard: post-insert UPDATE flipping client_secret_hash to
// NULL based on a runtime check is exactly the non-atomic pattern T4
// killed. Re-introducing it brings back codex F4.
diff --git a/test/lock-keys.test.ts b/test/lock-keys.test.ts
new file mode 100644
index 0000000000..9a2379b0ea
--- /dev/null
+++ b/test/lock-keys.test.ts
@@ -0,0 +1,155 @@
+/**
+ * PR6 D5 — source-scoped advisory-lock key helpers.
+ *
+ * Pins the EXACT key strings (they are cross-process wire contracts: every
+ * writer hashing a different string holds a different lock) plus the
+ * writer-side transaction routing: WriteTxImpl runs inside exactly ONE
+ * engine.transaction (BrainWriter.transaction's), and the advisory lock,
+ * the slug-registry existence probes, and the paired putPage all flow
+ * through the tx engine — so the pg_advisory_xact_lock genuinely spans the
+ * TOCTOU window until the outer commit. A nested engine.transaction inside
+ * createEntity would throw on both engines (postgres tx clones have no
+ * `.begin`; PGLite tx proxies have no `.transaction`); the txCount === 1
+ * assertion pins that no such wrap exists.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { autoLinkLockKey } from '../src/core/ops/pages.ts';
+import { registerClientNameLockKey } from '../src/commands/agent-register.ts';
+import { slugRegistryLockKey, BrainWriter } from '../src/core/output/writer.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { ResolverContext } from '../src/core/resolvers/index.ts';
+
+describe('autoLinkLockKey (ops/pages.ts)', () => {
+ test('exact string with a sourceId', () => {
+ expect(autoLinkLockKey('src-a', 'people/alice-example')).toBe('auto_link:src-a:people/alice-example');
+ });
+
+ test('exact string with undefined sourceId (belt-and-braces empty segment)', () => {
+ expect(autoLinkLockKey(undefined, 'people/alice-example')).toBe('auto_link::people/alice-example');
+ });
+
+ test('different sources produce different keys (no cross-source contention)', () => {
+ expect(autoLinkLockKey('src-a', 'notes/x')).not.toBe(autoLinkLockKey('src-b', 'notes/x'));
+ });
+
+ test('same (source, slug) produces the same key (same-scope writers still serialize)', () => {
+ expect(autoLinkLockKey('src-a', 'notes/x')).toBe(autoLinkLockKey('src-a', 'notes/x'));
+ });
+});
+
+describe('registerClientNameLockKey (commands/agent-register.ts)', () => {
+ test('exact string (cross-process wire contract shared by register + reissue rotation)', () => {
+ expect(registerClientNameLockKey('aurora-coder')).toBe('register_client_name:aurora-coder');
+ });
+
+ test('different names produce different keys; same name serializes', () => {
+ expect(registerClientNameLockKey('a')).not.toBe(registerClientNameLockKey('b'));
+ expect(registerClientNameLockKey('a')).toBe(registerClientNameLockKey('a'));
+ });
+});
+
+describe('slugRegistryLockKey (output/writer.ts)', () => {
+ test('exact string with a sourceId', () => {
+ expect(slugRegistryLockKey('src-a', 'people/alice-example')).toBe('slug_registry:src-a:people/alice-example');
+ });
+
+ test("exact string with undefined sourceId falls back to 'default' (mirrors putPage's implicit source)", () => {
+ expect(slugRegistryLockKey(undefined, 'people/alice-example')).toBe('slug_registry:default:people/alice-example');
+ });
+
+ test('different sources produce different keys (no cross-source contention)', () => {
+ expect(slugRegistryLockKey('src-a', 'people/x')).not.toBe(slugRegistryLockKey('src-b', 'people/x'));
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Writer transaction routing proof (stub engine)
+// ---------------------------------------------------------------------------
+
+type RecordedCall = { method: string; onTx: boolean; sql?: string; params?: unknown[] };
+
+function makeStubEngine(): { engine: BrainEngine; calls: RecordedCall[]; getTxCount: () => number } {
+ const calls: RecordedCall[] = [];
+ let txCount = 0;
+ const base = {
+ isTx: false,
+ async transaction(fn: (e: unknown) => Promise<unknown>) {
+ txCount++;
+ // Mirrors both real engines: the tx engine is a prototype clone whose
+ // connection routes to the transaction. A SECOND transaction() call on
+ // the clone would throw on both real engines — txCount pins there is
+ // exactly one.
+ const clone = Object.create(this) as typeof base;
+ clone.isTx = true;
+ return fn(clone);
+ },
+ async executeRaw(sql: string, params?: unknown[]) {
+ calls.push({ method: 'executeRaw', onTx: this.isTx, sql, params });
+ return [];
+ },
+ async getPage(_slug: string, _opts?: unknown) {
+ calls.push({ method: 'getPage', onTx: this.isTx });
+ return null; // desired slug is free — fast path, no disambiguation
+ },
+ async putPage(slug: string, _page: unknown, _opts?: unknown) {
+ calls.push({ method: 'putPage', onTx: this.isTx });
+ return { slug };
+ },
+ };
+ return { engine: base as unknown as BrainEngine, calls, getTxCount: () => txCount };
+}
+
+function makeCtx(): ResolverContext {
+ return {
+ config: {},
+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
+ requestId: 'lock-keys-test',
+ remote: false,
+ };
+}
+
+describe('createEntity advisory lock — transaction scope + key routing', () => {
+ test('lock + slug probes + putPage all run inside the ONE wrapping transaction, keyed per source', async () => {
+ const { engine, calls, getTxCount } = makeStubEngine();
+ const writer = new BrainWriter(engine, { strictMode: 'off', sourceId: 'src-a' });
+
+ const { result } = await writer.transaction(async (tx) => tx.createEntity({
+ desiredSlug: 'people/alice-example',
+ displayName: 'Alice Example',
+ type: 'person',
+ compiledTruth: 'Alice is a person.',
+ }), makeCtx());
+
+ expect(result).toBe('people/alice-example');
+ // Exactly ONE transaction — createEntity must NOT nest engine.transaction
+ // (nesting throws on both real engines).
+ expect(getTxCount()).toBe(1);
+
+ const lock = calls.find((c) => c.sql?.includes('pg_advisory_xact_lock'));
+ expect(lock).toBeDefined();
+ expect(lock!.params).toEqual([slugRegistryLockKey('src-a', 'people/alice-example')]);
+ expect(lock!.params).toEqual(['slug_registry:src-a:people/alice-example']);
+
+ // Every statement in the TOCTOU window (lock, registry getPage probe,
+ // putPage) flowed through the tx engine — the xact lock spans them all.
+ expect(calls.length).toBeGreaterThanOrEqual(3);
+ for (const c of calls) expect(c.onTx).toBe(true);
+ expect(calls.map((c) => c.method)).toContain('putPage');
+ });
+
+ test("writer without an explicit source locks the 'default' key (matches putPage's implicit source)", async () => {
+ const { engine, calls } = makeStubEngine();
+ const writer = new BrainWriter(engine, { strictMode: 'off' });
+
+ await writer.transaction(async (tx) => tx.createEntity({
+ desiredSlug: 'people/bob-example',
+ displayName: 'Bob Example',
+ type: 'person',
+ compiledTruth: 'Bob is a person.',
+ }), makeCtx());
+
+ const lock = calls.find((c) => c.sql?.includes('pg_advisory_xact_lock'));
+ expect(lock!.params).toEqual(['slug_registry:default:people/bob-example']);
+ });
+});
diff --git a/test/mcp-registration-blocks.test.ts b/test/mcp-registration-blocks.test.ts
new file mode 100644
index 0000000000..0b9b243483
--- /dev/null
+++ b/test/mcp-registration-blocks.test.ts
@@ -0,0 +1,65 @@
+/**
+ * mcp-registration-blocks.test.ts — cathedral-6 lane B pins:
+ * - openclawThinClientBlock is the HONEST v1 OpenClaw path: the scoped
+ * `gbrain init` thin-client command with all four connection args, plus the
+ * FULL-local-DB-access honesty sentence — and NOT an mcpServers/stdio JSON
+ * config.
+ * - OAUTH_SECRET_NOTE moved to core with its text unchanged; connect.ts
+ * re-exports the identical value (surface unchanged).
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { OAUTH_SECRET_NOTE, openclawThinClientBlock } from '../src/core/mcp-registration.ts';
+import { OAUTH_SECRET_NOTE as CONNECT_REEXPORTED_NOTE } from '../src/commands/connect.ts';
+
+const OPTS = {
+ issuerUrl: 'https://brain.example.com',
+ mcpUrl: 'https://brain.example.com/mcp',
+ clientId: 'client_abc123',
+ clientSecret: 'sekret_xyz789',
+};
+
+describe('openclawThinClientBlock', () => {
+ test('carries the gbrain init thin-client command with all four connection args', () => {
+ const block = openclawThinClientBlock(OPTS);
+ expect(block).toContain('gbrain init --mcp-only');
+ expect(block).toContain('--issuer-url https://brain.example.com');
+ expect(block).toContain('--mcp-url https://brain.example.com/mcp');
+ expect(block).toContain('--oauth-client-id client_abc123');
+ expect(block).toContain('--oauth-client-secret sekret_xyz789');
+ });
+
+ test('states the honesty note: scoped-CLI path, no native remote MCP, stdio grants FULL local DB access', () => {
+ const block = openclawThinClientBlock(OPTS);
+ expect(block).toContain(
+ 'Your OpenClaw reaches the brain through the scoped gbrain CLI (search/query/recall/put);',
+ );
+ expect(block).toContain("native remote MCP isn't supported yet");
+ expect(block).toContain('the stdio config in docs/mcp/OPENCLAW.md grants');
+ expect(block).toContain('FULL local DB access and does not use this client.');
+ });
+
+ test('is NOT an mcpServers/stdio JSON config', () => {
+ const block = openclawThinClientBlock(OPTS);
+ expect(block).not.toMatch(/mcpServers|"command"\s*:/);
+ });
+
+ test('shell-quotes unsafe values so a pasted block cannot command-substitute', () => {
+ const block = openclawThinClientBlock({ ...OPTS, clientSecret: 'se$(boom)cret' });
+ expect(block).toContain("--oauth-client-secret 'se$(boom)cret'");
+ expect(block).not.toContain('--oauth-client-secret se$(boom)cret');
+ });
+});
+
+describe('OAUTH_SECRET_NOTE (moved to core)', () => {
+ test('text is unchanged by the move', () => {
+ expect(OAUTH_SECRET_NOTE).toBe(
+ 'Note: the client secret is sensitive — store it like a password. It mints ' +
+ 'short-lived, scoped access tokens; revoke with `gbrain auth revoke-client`.',
+ );
+ });
+
+ test('connect.ts re-exports the identical value (surface unchanged)', () => {
+ expect(CONNECT_REEXPORTED_NOTE).toBe(OAUTH_SECRET_NOTE);
+ });
+});
diff --git a/test/recall-federated.test.ts b/test/recall-federated.test.ts
new file mode 100644
index 0000000000..a299ca6b8e
--- /dev/null
+++ b/test/recall-federated.test.ts
@@ -0,0 +1,237 @@
+/**
+ * cathedral-6 D1b: `recall` honors federated grants. The fact arms route
+ * through sourceScopeOpts — a remote caller whose token carries
+ * allowedSources sees world facts across every granted source (the spec's
+ * cross-agent continuity), while an ungranted source stays invisible and
+ * private facts stay local-only. Single-source callers keep the exact
+ * pre-v1 single-query path.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { clampRecallLimit } from '../src/core/ops/facts.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+
+function ctx(over: Record<string, unknown>): OperationContext {
+ return {
+ engine,
+ config: {},
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
+ dryRun: false,
+ ...over,
+ } as unknown as OperationContext;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ for (const id of ['aurora-workspace', 'proj-widget', 'nova-notes']) {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING`, [id],
+ );
+ }
+ const remember = operationsByName['remember'];
+ // B (writes proj-widget): a world fact — the cross-agent continuity payload.
+ await remember.handler(
+ ctx({ remote: true, sourceId: 'proj-widget' }),
+ { fact: 'The payments provider decision is Stripe-shaped (test marker QQF1)', provenance: 'recall-federated test', visibility: 'world' },
+ );
+ // A private fact in proj-widget: must never cross to remote readers.
+ await remember.handler(
+ ctx({ remote: false, sourceId: 'proj-widget' }),
+ { fact: 'Private hunch marker QQF2', provenance: 'recall-federated test', visibility: 'private' },
+ );
+ // A fact in an UNGRANTED source: must not leak through the federated arm.
+ await remember.handler(
+ ctx({ remote: true, sourceId: 'nova-notes' }),
+ { fact: 'Ungranted-source marker QQF3', provenance: 'recall-federated test', visibility: 'world' },
+ );
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('recall federated grants (D1b)', () => {
+ const recall = () => operationsByName['recall'];
+
+ it('a federated remote caller recalls world facts from a GRANTED foreign source', async () => {
+ const res: any = await recall().handler(
+ ctx({
+ remote: true,
+ sourceId: 'aurora-workspace',
+ auth: { allowedSources: ['aurora-workspace', 'proj-widget'] },
+ }),
+ {},
+ );
+ const facts = (res.facts ?? []).map((f: any) => String(f.fact));
+ expect(facts.some((f: string) => f.includes('QQF1'))).toBe(true);
+ expect(facts.some((f: string) => f.includes('QQF3'))).toBe(false); // ungranted source
+ expect(facts.some((f: string) => f.includes('QQF2'))).toBe(false); // private stays hidden
+ });
+
+ it('without the federated grant the foreign source stays invisible (scalar path)', async () => {
+ const res: any = await recall().handler(
+ ctx({ remote: true, sourceId: 'aurora-workspace' }),
+ {},
+ );
+ const facts = (res.facts ?? []).map((f: any) => String(f.fact));
+ expect(facts.some((f: string) => f.includes('QQF1'))).toBe(false);
+ });
+
+ it('an empty allowedSources array is a deny-not-widen: scalar source only', async () => {
+ const res: any = await recall().handler(
+ ctx({ remote: true, sourceId: 'proj-widget', auth: { allowedSources: [] } }),
+ {},
+ );
+ const facts = (res.facts ?? []).map((f: any) => String(f.fact));
+ expect(facts.some((f: string) => f.includes('QQF1'))).toBe(true); // own scalar source
+ expect(facts.some((f: string) => f.includes('QQF3'))).toBe(false); // never widened
+ });
+
+ it('the since arm fans out across the federated grant too (not just the no-filter arm)', async () => {
+ const res: any = await recall().handler(
+ ctx({
+ remote: true,
+ sourceId: 'aurora-workspace',
+ auth: { allowedSources: ['aurora-workspace', 'proj-widget'] },
+ }),
+ { since: '2000-01-01' },
+ );
+ const facts = (res.facts ?? []).map((f: any) => String(f.fact));
+ expect(facts.some((f: string) => f.includes('QQF1'))).toBe(true); // granted foreign source
+ expect(facts.some((f: string) => f.includes('QQF3'))).toBe(false); // ungranted source
+ expect(facts.some((f: string) => f.includes('QQF2'))).toBe(false); // private stays hidden
+ });
+
+ it('local trusted caller still reads private facts (visibility unchanged)', async () => {
+ const res: any = await recall().handler(
+ ctx({ remote: false, sourceId: 'proj-widget' }),
+ {},
+ );
+ const facts = (res.facts ?? []).map((f: any) => String(f.fact));
+ expect(facts.some((f: string) => f.includes('QQF2'))).toBe(true);
+ });
+
+ it('a private superseded fact is invisible to a remote supersessions=true call', async () => {
+ const remember = operationsByName['remember'];
+ await remember.handler(
+ ctx({ remote: false, sourceId: 'proj-widget' }),
+ { fact: 'Private superseded marker QQF4', provenance: 'recall-federated test', visibility: 'private' },
+ );
+ await remember.handler(
+ ctx({ remote: true, sourceId: 'proj-widget' }),
+ { fact: 'World superseded marker QQF5', provenance: 'recall-federated test', visibility: 'world' },
+ );
+ // Put both into the supersession audit-log shape (expired_at +
+ // superseded_by both set). Self-reference keeps the FK satisfied.
+ await engine.executeRaw(
+ `UPDATE facts SET expired_at = now(), superseded_by = id
+ WHERE fact LIKE '%QQF4%' OR fact LIKE '%QQF5%'`,
+ );
+
+ // Remote federated caller: the audit arm filters visibility at the
+ // ENGINE level (before each source's LIMIT) — the private row must
+ // never surface.
+ const remoteRes: any = await recall().handler(
+ ctx({
+ remote: true,
+ sourceId: 'aurora-workspace',
+ auth: { allowedSources: ['aurora-workspace', 'proj-widget'] },
+ }),
+ { supersessions: true },
+ );
+ const remoteFacts = (remoteRes.facts ?? []).map((f: any) => String(f.fact));
+ expect(remoteFacts.some((f: string) => f.includes('QQF5'))).toBe(true); // world audit row visible
+ expect(remoteFacts.some((f: string) => f.includes('QQF4'))).toBe(false); // private stays hidden
+
+ // Local trusted caller still sees the private audit row.
+ const localRes: any = await recall().handler(
+ ctx({ remote: false, sourceId: 'proj-widget' }),
+ { supersessions: true },
+ );
+ const localFacts = (localRes.facts ?? []).map((f: any) => String(f.fact));
+ expect(localFacts.some((f: string) => f.includes('QQF4'))).toBe(true);
+ });
+
+ it('with limit=1 and the newest supersession private, a remote call still returns the older world row', async () => {
+ // Pre-fix ordering bug: the post-merge visibility filter let the private
+ // newest row consume the single limit slot at the engine, then filtered
+ // it away → empty response instead of the older world-visible row.
+ // Own source so the earlier supersession test's rows can't take the slot.
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('sup-limit', 'sup-limit') ON CONFLICT (id) DO NOTHING`,
+ );
+ const remember = operationsByName['remember'];
+ await remember.handler(
+ ctx({ remote: false, sourceId: 'sup-limit' }),
+ { fact: 'Private newest superseded marker QQF6', provenance: 'recall-federated test', visibility: 'private' },
+ );
+ await remember.handler(
+ ctx({ remote: true, sourceId: 'sup-limit' }),
+ { fact: 'World older superseded marker QQF7', provenance: 'recall-federated test', visibility: 'world' },
+ );
+ // Audit-log shape with DISTINCT expired_at: the private row is NEWEST.
+ await engine.executeRaw(
+ `UPDATE facts SET expired_at = now(), superseded_by = id WHERE fact LIKE '%QQF6%'`,
+ );
+ await engine.executeRaw(
+ `UPDATE facts SET expired_at = now() - interval '1 hour', superseded_by = id WHERE fact LIKE '%QQF7%'`,
+ );
+
+ const res: any = await recall().handler(
+ ctx({ remote: true, sourceId: 'sup-limit' }),
+ { supersessions: true, limit: 1 },
+ );
+ const facts = (res.facts ?? []).map((f: any) => String(f.fact));
+ expect(facts.length).toBe(1);
+ expect(facts[0]).toContain('QQF7');
+ expect(facts.some((f: string) => f.includes('QQF6'))).toBe(false);
+ });
+
+ it('include_pending sums pending-consolidation counts across the federated grant', async () => {
+ const remember = operationsByName['remember'];
+ await remember.handler(
+ ctx({ remote: true, sourceId: 'aurora-workspace' }),
+ { fact: 'Pending marker QQF8', provenance: 'recall-federated test', visibility: 'world' },
+ );
+ const a = await engine.countUnconsolidatedFacts('aurora-workspace');
+ const b = await engine.countUnconsolidatedFacts('proj-widget');
+ expect(a).toBeGreaterThan(0);
+ expect(b).toBeGreaterThan(0);
+
+ const res: any = await recall().handler(
+ ctx({
+ remote: true,
+ sourceId: 'aurora-workspace',
+ auth: { allowedSources: ['aurora-workspace', 'proj-widget'] },
+ }),
+ { include_pending: true },
+ );
+ // Sum over the SAME factSources set the fact arms fan out across — not
+ // just the scalar sourceId (which would report `a` alone).
+ expect(res.pending_consolidation_count).toBe(a + b);
+ });
+});
+
+describe('clampRecallLimit (per-arm cap, applied once before the fan-out)', () => {
+ it('caps valid integers at 100 and passes small ones through', () => {
+ expect(clampRecallLimit(150)).toBe(100);
+ expect(clampRecallLimit(100)).toBe(100);
+ expect(clampRecallLimit(7)).toBe(7);
+ expect(clampRecallLimit(1)).toBe(1);
+ });
+
+ it('invalid input (undefined / NaN / non-positive / non-integer) → default 50', () => {
+ expect(clampRecallLimit(undefined)).toBe(50);
+ expect(clampRecallLimit(NaN)).toBe(50);
+ expect(clampRecallLimit(-1)).toBe(50);
+ expect(clampRecallLimit(0)).toBe(50);
+ expect(clampRecallLimit(3.7)).toBe(50);
+ expect(clampRecallLimit('25' as unknown)).toBe(50);
+ expect(clampRecallLimit(Infinity)).toBe(50);
+ });
+});
diff --git a/test/register-client-source-normalize.test.ts b/test/register-client-source-normalize.test.ts
index efc3b73118..1115704756 100644
--- a/test/register-client-source-normalize.test.ts
+++ b/test/register-client-source-normalize.test.ts
@@ -58,7 +58,13 @@ describe('register-client route wiring (structural)', () => {
const src = readFileSync(new URL('../src/commands/serve-http.ts', import.meta.url), 'utf-8');
expect(src).toContain('sourceId = normalizeSourceInput(source)');
expect(src).toContain('federatedReadIds = normalizeFederatedReadInput(federatedRead)');
- expect(src).toMatch(/registerClientManual\(\s*name,\s*grants,\s*scopeString,\s*uris,\s*sourceId,\s*federatedReadIds,\s*validatedAuthMethod/);
+ // cathedral-6: the route composes registerScopedClient (the CLI's core)
+ // instead of calling registerClientManual directly — now on the
+ // tx-scoped sql handle (dup-check + INSERT are one transaction). The
+ // transposition hazard this pin exists for is now a NAMED-FIELD hazard —
+ // pin that the normalized values land on the right keys of the
+ // parsed-args object.
+ expect(src).toMatch(/registerScopedClient\(txSql,\s*name,\s*\{[\s\S]*?scopes:\s*scopeString,[\s\S]*?sourceId,[\s\S]*?federatedRead:\s*federatedReadIds,[\s\S]*?tokenEndpointAuthMethod:\s*validatedAuthMethod[\s\S]*?\}/);
});
});